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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5cfec2570c01bb590da565e198861d9ffa4a34e4 | 6,013 | h | C | cpp/src/rule.h | tompee26/libaddressinput | 0b423a4c0290815decd11f73fb8dbe009e80a576 | [
"Apache-2.0"
] | 136 | 2019-05-29T08:25:19.000Z | 2022-03-08T13:28:29.000Z | cpp/src/rule.h | tompee26/libaddressinput | 0b423a4c0290815decd11f73fb8dbe009e80a576 | [
"Apache-2.0"
] | 47 | 2019-05-31T10:36:15.000Z | 2022-01-12T08:12:43.000Z | cpp/src/rule.h | tompee26/libaddressinput | 0b423a4c0290815decd11f73fb8dbe009e80a576 | [
"Apache-2.0"
] | 34 | 2019-07-09T13:28:13.000Z | 2022-03-21T02:07:58.000Z | // Copyright (C) 2013 Google 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.
//
// An object to store address metadata, describing the addressing rules for
// regions and sub-regions. The address metadata format is documented here:
//
// https://github.com/google/libaddressinput/wiki/AddressValidationMetadata
#ifndef I18N_ADDRESSINPUT_RULE_H_
#define I18N_ADDRESSINPUT_RULE_H_
#include <libaddressinput/address_field.h>
#include <memory>
#include <string>
#include <vector>
namespace i18n {
namespace addressinput {
class FormatElement;
class Json;
struct RE2ptr;
// Stores address metadata addressing rules, to be used for determining the
// layout of an address input widget or for address validation. Sample usage:
// Rule rule;
// if (rule.ParseSerializedRule("{\"fmt\": \"%A%n%C%S %Z\"}")) {
// Process(rule.GetFormat());
// }
class Rule {
public:
Rule(const Rule&) = delete;
Rule& operator=(const Rule&) = delete;
Rule();
~Rule();
// Returns the default rule at a country level. If a country does not specify
// address format, for example, then the format from this rule should be used
// instead.
static const Rule& GetDefault();
// Copies all data from |rule|.
void CopyFrom(const Rule& rule);
// Parses |serialized_rule|. Returns |true| if the |serialized_rule| has valid
// format (JSON dictionary).
bool ParseSerializedRule(const std::string& serialized_rule);
// Reads data from |json|, which must already have parsed a serialized rule.
void ParseJsonRule(const Json& json);
// Returns the ID string for this rule.
const std::string& GetId() const { return id_; }
// Returns the format elements for this rule. The format can include the
// relevant address fields, but also strings used for formatting, or newline
// information.
const std::vector<FormatElement>& GetFormat() const { return format_; }
// Returns the approximate address format with the Latin order of fields. The
// format can include the relevant address fields, but also strings used for
// formatting, or newline information.
const std::vector<FormatElement>& GetLatinFormat() const {
return latin_format_;
}
// Returns the required fields for this rule.
const std::vector<AddressField>& GetRequired() const { return required_; }
// Returns the sub-keys for this rule, which are the administrative areas of a
// country, the localities of an administrative area, or the dependent
// localities of a locality. For example, the rules for "US" have sub-keys of
// "CA", "NY", "TX", etc.
const std::vector<std::string>& GetSubKeys() const { return sub_keys_; }
// Returns all of the language tags supported by this rule, for example ["de",
// "fr", "it"].
const std::vector<std::string>& GetLanguages() const { return languages_; }
// Returns a pointer to a RE2 regular expression object created from the
// postal code format string, if specified, or nullptr otherwise. The regular
// expression is anchored to the beginning of the string so that it can be
// used either with RE2::PartialMatch() to perform prefix matching or else
// with RE2::FullMatch() to perform matching against the entire string.
const RE2ptr* GetPostalCodeMatcher() const {
return postal_code_matcher_.get();
}
// Returns the sole postal code for this rule, if there is one.
const std::string& GetSolePostalCode() const { return sole_postal_code_; }
// The message string identifier for admin area name. If not set, then
// INVALID_MESSAGE_ID.
int GetAdminAreaNameMessageId() const { return admin_area_name_message_id_; }
// The message string identifier for postal code name. If not set, then
// INVALID_MESSAGE_ID.
int GetPostalCodeNameMessageId() const {
return postal_code_name_message_id_;
}
// The message string identifier for locality name. If not set, then
// INVALID_MESSAGE_ID.
int GetLocalityNameMessageId() const {
return locality_name_message_id_;
}
// The message string identifier for sublocality name. If not set, then
// INVALID_MESSAGE_ID.
int GetSublocalityNameMessageId() const {
return sublocality_name_message_id_;
}
// Returns the name for the most specific place described by this rule, if
// there is one. This is typically set when it differs from the key.
const std::string& GetName() const { return name_; }
// Returns the Latin-script name for the most specific place described by this
// rule, if there is one.
const std::string& GetLatinName() const { return latin_name_; }
// Returns the postal code example string for this rule.
const std::string& GetPostalCodeExample() const {
return postal_code_example_;
}
// Returns the post service URL string for this rule.
const std::string& GetPostServiceUrl() const { return post_service_url_; }
private:
std::string id_;
std::vector<FormatElement> format_;
std::vector<FormatElement> latin_format_;
std::vector<AddressField> required_;
std::vector<std::string> sub_keys_;
std::vector<std::string> languages_;
std::unique_ptr<const RE2ptr> postal_code_matcher_;
std::string sole_postal_code_;
int admin_area_name_message_id_;
int postal_code_name_message_id_;
int locality_name_message_id_;
int sublocality_name_message_id_;
std::string name_;
std::string latin_name_;
std::string postal_code_example_;
std::string post_service_url_;
};
} // namespace addressinput
} // namespace i18n
#endif // I18N_ADDRESSINPUT_RULE_H_
| 36.222892 | 80 | 0.735573 | [
"object",
"vector"
] |
cf0bd2316bd1ceaf491c47d51438609c1e2bcc9d | 749 | h | C | HTTestTools/HTTestTools/EditMyTools/EditMyToolsCollectionViewCell.h | longfeiwang91/HTTestTools | 8a603a150a567198c19888b9bef6a1558f1167ad | [
"MIT"
] | null | null | null | HTTestTools/HTTestTools/EditMyTools/EditMyToolsCollectionViewCell.h | longfeiwang91/HTTestTools | 8a603a150a567198c19888b9bef6a1558f1167ad | [
"MIT"
] | null | null | null | HTTestTools/HTTestTools/EditMyTools/EditMyToolsCollectionViewCell.h | longfeiwang91/HTTestTools | 8a603a150a567198c19888b9bef6a1558f1167ad | [
"MIT"
] | null | null | null | //
// EditMyToolsCollectionViewCell.h
// HTTestTools
//
// Created by longfei on 2019/8/1.
// Copyright © 2019 LongfeiWang. All rights reserved.
//
#import <UIKit/UIKit.h>
@class EditMyToolsModel;
typedef void(^EditMyToolsCollectionViewCellBlock)(EditMyToolsModel *model);
typedef NS_ENUM(NSInteger, EditMyToolsCollectionViewCellEditState) {
EditMyToolsCollectionViewCellEditStateEdit,
EditMyToolsCollectionViewCellEditStateDetail,
};
@interface EditMyToolsCollectionViewCell : UICollectionViewCell
@property(nonatomic, assign) EditMyToolsCollectionViewCellEditState editState;
@property(nonatomic, copy) EditMyToolsCollectionViewCellBlock buttonClickBlock;
@property(nonatomic, strong) EditMyToolsModel *model;
@end
| 23.40625 | 79 | 0.805073 | [
"model"
] |
cf0ca8d8c0d35df983d2cb87a3ddbe581488ccaa | 4,610 | h | C | SRC/material/nD/cyclicSoil/MultiaxialCyclicPlasticityPlaneStrain.h | steva44/OpenSees | 417c3be117992a108c6bbbcf5c9b63806b9362ab | [
"TCL"
] | 8 | 2019-03-05T16:25:10.000Z | 2020-04-17T14:12:03.000Z | SRC/material/nD/cyclicSoil/MultiaxialCyclicPlasticityPlaneStrain.h | steva44/OpenSees | 417c3be117992a108c6bbbcf5c9b63806b9362ab | [
"TCL"
] | null | null | null | SRC/material/nD/cyclicSoil/MultiaxialCyclicPlasticityPlaneStrain.h | steva44/OpenSees | 417c3be117992a108c6bbbcf5c9b63806b9362ab | [
"TCL"
] | 3 | 2019-09-21T03:11:11.000Z | 2020-01-19T07:29:37.000Z | /* ****************************************************************** **
** OpenSees - Open System for Earthquake Engineering Simulation **
** Pacific Earthquake Engineering Research Center **
** **
** **
** (C) Copyright 1999, The Regents of the University of California **
** All Rights Reserved. **
** **
** Commercial use of this program without express permission of the **
** University of California, Berkeley, is strictly prohibited. See **
** file 'COPYRIGHT' in main directory for information on usage and **
** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. **
** **
** ****************************************************************** */
/*----+----+----+----+----+----+----+----+----+----+----+----+----+----+----*
| |
| MultiaxialCyclicPlasticity NDMaterial |
+ +
|--------------------------------------------------------------------------|
| |
+ Authors: Gang Wang AND Professor Nicholas Sitar +
| |
| Department of Civil and Environmental Engineering |
+ University of California, Berkeley, CA 94720, USA +
| |
| Email: wang@ce.berkeley.edu (G.W.) |
| |
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----*/
#ifndef MultiaxialCyclicPlasticityPlaneStrain_h
#define MultiaxialCyclicPlasticityPlaneStrain_h
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <Vector.h>
#include <Matrix.h>
#include <MultiaxialCyclicPlasticity.h>
class MultiaxialCyclicPlasticityPlaneStrain : public MultiaxialCyclicPlasticity {
//-------------------Declarations-------------------------------
public :
//null constructor
MultiaxialCyclicPlasticityPlaneStrain( ) ;
//full constructor
MultiaxialCyclicPlasticityPlaneStrain( int tag,
double rho,
double K,
double G,
double Su,
double Ho_kin,
double Parameter_h,
double Parameter_m,
double Parameter_beta,
double Kcoeff,
double viscosity=0 ) ;
//elastic constructor // add density by Gang Wang
MultiaxialCyclicPlasticityPlaneStrain( int tag, double rho, double K, double G ) ;
//destructor
~MultiaxialCyclicPlasticityPlaneStrain( ) ;
const char *getClassType(void) const {return "MultiaxialCyclicPlasticityPlaneStrain";};
//make a clone of this material
NDMaterial* getCopy( ) ;
//send back type of material
const char* getType( ) const ;
//send back order of strain in vector form
int getOrder( ) const ;
//get the strain and integrate plasticity equations
int setTrialStrain( const Vector &strain_from_element) ;
//unused trial strain functions
int setTrialStrain( const Vector &v, const Vector &r ) ;
int setTrialStrainIncr( const Vector &v ) ;
int setTrialStrainIncr( const Vector &v, const Vector &r ) ;
//send back the strain
const Vector& getStrain( ) ;
//send back the stress
const Vector& getStress( ) ;
//send back the tangent
const Matrix& getTangent( ) ;
const Matrix& getInitialTangent( ) ;
//swap history variables
//int commitState( ) ;
//int revertToLastCommit( ) ;
//int revertToStart( ) ;
//sending and receiving
//int sendSelf(int commitTag, Channel &theChannel) ;
//int recvSelf(int commitTag, Channel &theChannel,
// FEM_ObjectBroker &theBroker ) ;
private :
//static vectors and matrices
static Vector strain_vec ; //strain in vector notation
static Vector stress_vec ; //stress in vector notation
static Matrix tangent_matrix ; //material tangent in matrix notation
} ;
//end of MultiaxialCyclicPlasticityPlaneStrain declarations
#endif
| 36.88 | 89 | 0.484382 | [
"vector"
] |
cf0d6610c256afefce893ec7971e6bb325f12e3b | 15,168 | h | C | Base/PLMesh/include/PLMesh/Loader/MeshFile.h | ktotheoz/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 83 | 2015-01-08T15:06:14.000Z | 2021-07-20T17:07:00.000Z | Base/PLMesh/include/PLMesh/Loader/MeshFile.h | PixelLightFoundation/pixellight | 43a661e762034054b47766d7e38d94baf22d2038 | [
"MIT"
] | 27 | 2019-06-18T06:46:07.000Z | 2020-02-02T11:11:28.000Z | Base/PLMesh/include/PLMesh/Loader/MeshFile.h | naetherm/PixelLight | d7666f5b49020334cbb5debbee11030f34cced56 | [
"MIT"
] | 40 | 2015-02-25T18:24:34.000Z | 2021-03-06T09:01:48.000Z | /*********************************************************\
* File: MeshFile.h *
*
* Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/)
*
* This file is part of PixelLight.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\*********************************************************/
#ifndef __PLMESH_MESHFILE_H__
#define __PLMESH_MESHFILE_H__
#pragma once
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include <PLCore/PLCore.h>
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace PLMesh {
//[-------------------------------------------------------]
//[ Classes ]
//[-------------------------------------------------------]
/**
* @brief
* PL mesh file format (binary, Little-Endian)
*
* @verbatim
PixelLight mesh format description:
MESHFILE
|
+--PLCore::uint32 nMagic
|
+--PLCore::uint32 nVersion
|
+--MATERIALS
| |
| +--PLCore::uint32 nMaterials
| |
| +--char szName[256][nMaterials]
|
+--MESH
| |
| +--PLCore::uint32 nLODLevels
| |
| +--PLCore::uint32 nMorphTargets
| |
| +--PLCore::uint32 nWeights
| |
| +--PLCore::uint32 nVertexWeights
| |
| +--LODLEVEL (*)
| | |
| | +--float fDistance
| | |
| | +--PLCore::uint32 nGeometries
| | |
| | +--PLCore::uint32 nOctreeSubdivide
| | |
| | +--PLCore::uint32 nOctreeMinGeometries
| | |
| | +--INDEXBUFFER
| | | |
| | | +--PLCore::uint32 nElementType
| | | |
| | | +--PLCore::uint32 nElements
| | | |
| | | +--PLCore::uint32 nSize;
| | | |
| | | +--... 'nElements' indices of type 'nElementType'
| | |
| | +--GEOMETRY (*)
| | | |
| | | +--char szName[64]
| | | |
| | | +--PLCore::uint32 nFlags
| | | |
| | | +--bool bActive
| | | |
| | | +--int nPrimitiveType
| | | |
| | | +--int nMaterial
| | | |
| | | +--int nStartIndex
| | | |
| | | +--int nIndexSize
| | |
| | +--... 'nGeometries' geometries
| |
| +--... 'nLODLevels' LOD levels
| |
| +--MORPHTARGET (*)
| | |
| | +--char szName
| | |
| | +--bool bRelative
| | |
| | +--PLCore::uint32 nVertexIDs
| | |
| | +--PLCore::uint32 nVertexBuffers
| | |
| | +--'nVertexIDs' vertex ID's
| | |
| | +--VERTEXBUFFER (*)
| | | |
| | | +--PLCore::uint32 nVertexAttributes
| | | |
| | | +--PLCore::uint32 nVertices
| | | |
| | | +--PLCore::uint32 nSize;
| | | |
| | | +--VERTEXATTRIBUTE (*)
| | | | |
| | | | +--int nSemantic;
| | | | |
| | | | +--int nChannel;
| | | | |
| | | | +--int nType;
| | | |
| | | +--... 'nVertexAttributes' vertex attributes
| | | |
| | | +--... 'nVertices' vertices, a vertex consists of 'nVertexAttributes' attributes
| | |
| | +--... 'nVertexBuffers' vertex buffers
| |
| +--... 'nMorphTargets' morph targets
| |
| +--WEIGHT (*)
| | |
| | +--int nJoint
| | |
| | +--float fBias
| |
| +--... 'nWeights' weights
| |
| +--VERTEXWEIGHTS (*)
| | |
| | +--PLCore::uint32 nWeights
| | |
| | +-- 'nWeights' weight indices for the vertex
| |
| +--... one vertex weight for each LOD level vertex
|
+--MORPHTARGETANIMATION (*)
| |
| +--char szName
| |
| +--PLCore::uint32 nMorphTargets
| |
| +--PLCore::uint32 nFrames
| |
| +--MORPHTARGETANIMATIONTARGET (*)
| | |
| | +-- char szName[64]
| |
| +--... 'nMorphTargets' animation morph targets
| |
| +--FRAMEKEYS (*)
| | |
| | +-- FRAMEKEY (*)
| | | |
| | | +-- float fKey
| | |
| | +--... for each animation morph target
| |
| +-... 'nFrames' frame keys
|
+--SKELETON
| |
| +--char szName
| |
| +--PLCore::uint32 nJoints
| |
| +--PLCore::uint32 nFrames
| |
| +--JOINT (*)
| | |
| | +-- char szName[64]
| | |
| | +-- int nParent
| | |
| | +-- PLCore::uint8 nAnimatedComponents
| |
| +--... 'nJoints' joints
| |
| +--BASEFRAME
| | |
| | +--JOINTSTATE (*)
| | | |
| | | +-- float fTranslation[3]
| | | |
| | | +-- float fRotation[4]
| | | |
| | | +-- float fTranslationJointSpace[3]
| | | |
| | | +-- float fRotationJointSpace[4]
| | |
| | +--... 'nJoints' joint states
| |
| +--FRAMEKEYS (*)
| | |
| | +-- FRAMEKEY (*)
| | | |
| | | +-- float fKey
| | |
| | +--... for each animated component
| |
| +-... 'nFrames' frame keys
|
+--ANCHORPOINTS
| |
| +--PLCore::uint32 nAnchorPoints
| |
| +--ANCHORPOINT (*)
| | |
| | +-- char szName[64]
| | |
| | +-- bool bType
| | |
| | +-- int nID
| |
| +--... 'nAnchorPoints' anchor points
|
+--ANIMATIONS
| |
| +--PLCore::uint32 nAnimations
| |
| +--ANIMATION (*)
| | |
| | +--char szName[64]
| | |
| | +--int nType
| | |
| | +--int nStart
| | |
| | +--int nEnd
| | |
| | +--float fSpeed
| | |
| | +--PLCore::uint32 nFlags
| | |
| | +--int nEvents
| | |
| | +--ANIMATION_FRAMES
| | | |
| | | +--ANIMATION_FRAME (*)
| | | | |
| | | | +--float fSpeed
| | | |
| | | +--... |nEnd-nStart| animation frames
| | |
| | +--ANIMATION_EVENTS
| | |
| | +--ANIMATION_EVENT (*)
| | | |
| | | +--int nID
| | | |
| | | +--int nFrame
| | |
| | +--... 'nEvents' animation events
| |
| +--MESHBOUNDINGBOX (*)
| | |
| | +--float fMin[3]
| | |
| | +--float fMax[3]
| |
| +--...
|
@endverbatim
*/
class MeshFile {
//[-------------------------------------------------------]
//[ Constants ]
//[-------------------------------------------------------]
public:
// Format definition
static const PLCore::uint32 MAGIC = 0x57754631;
static const PLCore::uint32 VERSION = 2;
// Chunk types (0x0-------)
static const PLCore::uint32 CHUNK_MESHFILE = 0x00000001;
static const PLCore::uint32 CHUNK_MATERIALS = 0x00000010;
static const PLCore::uint32 CHUNK_MESH = 0x00000011;
static const PLCore::uint32 CHUNK_LODLEVEL = 0x00000012;
static const PLCore::uint32 CHUNK_INDEXBUFFER = 0x00000013;
static const PLCore::uint32 CHUNK_GEOMETRY = 0x00000014;
static const PLCore::uint32 CHUNK_MORPHTARGET = 0x00000015;
static const PLCore::uint32 CHUNK_VERTEXBUFFER = 0x00000016;
static const PLCore::uint32 CHUNK_VERTEXATTRIBUTE = 0x00000017;
static const PLCore::uint32 CHUNK_WEIGHT = 0x00000018;
static const PLCore::uint32 CHUNK_VERTEXWEIGHTS = 0x00000019;
static const PLCore::uint32 CHUNK_SKELETON = 0x00000020;
static const PLCore::uint32 CHUNK_SKELETONANIMATION = 0x00000021;
static const PLCore::uint32 CHUNK_ANCHORPOINTS = 0x00000022;
static const PLCore::uint32 CHUNK_ANIMATIONS = 0x00000023;
static const PLCore::uint32 CHUNK_MORPHTARGETANIMATION = 0x00000024;
static const PLCore::uint32 CHUNK_MESHBOUNDINGBOX = 0x00000025;
// Experimental chunks (0xA-------)
// Unimplemented chunks (0xE-------)
// Obsolete chunks (0xF-------)
//[-------------------------------------------------------]
//[ File format structures ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Chunk header
*/
struct Chunk {
PLCore::uint32 nType; /**< Chunk type (e.g. CHUNK_MESHFILE) */
PLCore::uint32 nSize; /**< Chunk size in bytes (including the 8 bytes for the chunk header) */
};
/**
* @brief
* Main file header
*/
struct MeshFileHeader {
PLCore::uint32 nMagic; /**< MeshFile ID "" (see MAGIC above) */
PLCore::uint32 nVersion; /**< MeshFile Version (see VERSION above) */
};
/**
* @brief
* Material list
*/
struct Materials {
PLCore::uint32 nMaterials; /**< Number of materials */
};
/**
* @brief
* Mesh
*/
struct Mesh {
PLCore::uint32 nLODLevels; /**< Number of LOD levels */
PLCore::uint32 nMorphTargets; /**< Number of morph targets */
PLCore::uint32 nWeights; /**< Total number of weights */
PLCore::uint32 nVertexWeights; /**< Number of vertices with weights */
};
/**
* @brief
* Bounding box
*/
struct BoundingBox {
float fMin[3]; /**< Minimum bounding box position */
float fMax[3]; /**< Maximum bounding box position */
};
/**
* @brief
* Weight
*/
struct Weight {
int nJoint; /**< Joint this weight is for */
float fBias; /**< Bias factor */
};
/**
* @brief
* Vertex weights
*/
struct VertexWeights {
PLCore::uint32 nWeights; /**< Number of weights for the vertex */
};
/**
* @brief
* LOD level
*/
struct LODLevel {
float fDistance; /**< Distance this LOD level is used */
PLCore::uint32 nGeometries; /**< Number of geometries */
PLCore::uint32 nOctreeSubdivide; /**< Octree subdivide */
PLCore::uint32 nOctreeMinGeometries; /**< Minimum number of geometries per octree */
};
/**
* @brief
* Index buffer
*/
struct IndexBuffer {
PLCore::uint32 nElementType; /**< Index element type (see IndexBuffer::EType) */
PLCore::uint32 nElements; /**< Number of indices */
PLCore::uint32 nSize; /**< Total index buffer size in bytes */
};
/**
* @brief
* Geometry object
*/
struct Geometry {
char szName[64]; /**< Optional geometry name */
PLCore::uint32 nFlags; /**< Optional geometry flags */
bool bActive; /**< Is the geometry active/inactive? */
int nPrimitiveType; /**< Geometry primitive type (see PLRenderer::Primitive) */
int nMaterial; /**< ID of the material the geometry is using */
int nStartIndex; /**< First geometry index within the index buffer */
int nIndexSize; /**< Number of indices */
};
/**
* @brief
* Morph target
*/
struct MorphTarget {
char szName[64]; /**< Name of the morph target */
bool bRelative; /**< Is this morph target relative to the basis morph target? */
PLCore::uint32 nVertexIDs; /**< Number of vertex ID's, if 0 ALL vertices are influenced */
PLCore::uint32 nVertexBuffers; /**< Number of vertex buffers (one VB per LOD level) */
};
/**
* @brief
* Vertex buffer
*/
struct VertexBuffer {
PLCore::uint32 nVertexAttributes; /**< Number of vertex attributes */
PLCore::uint32 nVertices; /**< Number of vertices */
PLCore::uint32 nSize; /**< Total vertex buffer size in bytes */
};
/**
* @brief
* Vertex attribute of a vertex buffer
*/
struct VertexAttribute {
int nSemantic; /**< Semantic of the vertex attribute (see VertexBuffer::ESemantic) */
int nChannel; /**< Vertex attribute pipeline channel (primary color, secondary color,
first texture unit, second texture unit etc.) */
int nType; /**< Vertex attribute type (see VertexBuffer::EType) */
};
/**
* @brief
* Morph target animation
*/
struct MorphTargetAnimation {
char szName[64]; /**< Name of the morph target animation */
PLCore::uint32 nMorphTargets; /**< Number of morph targets */
PLCore::uint32 nFrames; /**< Number of morph target animation frames */
};
/**
* @brief
* Skeleton
*/
struct Skeleton {
char szName[64]; /**< Name of the skeleton (animation) */
PLCore::uint32 nJoints; /**< Number of joints the skeleton consists of */
PLCore::uint32 nFrames; /**< Number of skeleton animation frames */
};
/**
* @brief
* Joint
*/
struct Joint {
char szName[64]; /**< Unique joint name */
int nParent; /**< Number of the parent joint, < 0 if no parent */
PLCore::uint8 nAnimatedComponents; /**< X, Y, Z, Yaw, Pitch, Roll, W */
};
/**
* @brief
* Joint state
*/
struct JointState {
float fTranslation[3]; /**< Joint x/y/z translation, relative if the joint has a parent */
float fRotation[4]; /**< Joint w/x/y/z rotation quaternion, relative if the joint has a parent */
float fTranslationJointSpace[3]; /**< Joint x/y/z translation in joint space */
float fRotationJointSpace[4]; /**< Joint w/x/y/z rotation quaternion in joint space */
};
/**
* @brief
* Anchor points list
*/
struct AnchorPoints {
PLCore::uint32 nAnchorPoints; /**< Number of anchor points */
};
/**
* @brief
* Anchor point
*/
struct AnchorPoint {
char szName[64]; /**< Unique anchor point name */
bool bType; /**< Anchor point type (0=vertex 1=joint) */
int nID; /**< Vertex/bone ID the anchor is attached to */
};
/**
* @brief
* Animations list
*/
struct Animations {
PLCore::uint32 nAnimations; /**< Number of animations */
};
/**
* @brief
* Animation
*/
struct Animation {
char szName[64]; /**< Unique animation name */
int nType; /**< Animation type (0=vertex 1=skeleton) */
int nStart; /**< Start frame of the animation (inclusive) */
int nEnd; /**< End frame of the animation (inclusive) */
float fSpeed; /**< Playback speed (1.0 = normal) */
PLCore::uint32 nFlags; /**< Animation information flags */
int nEvents; /**< Number of animation events */
};
/**
* @brief
* Animation frame
*/
struct AnimationFrame {
float m_fSpeed; /**< Frame speed (1.0 = normal) */
};
/**
* @brief
* Animation event
*/
struct AnimationEvent {
int m_nID; /**< Event ID */
int m_nFrame; /**< Frame causing this event */
};
};
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // PLMesh
#endif // __PLMESH_MESHFILE_H__
| 26.425087 | 104 | 0.524262 | [
"mesh",
"geometry",
"object"
] |
cf0e0d871874ef7e9df50e7172b6697438a454a3 | 56,745 | h | C | src/third_party/mozjs-45/extract/js/src/vm/NativeObject.h | EdwardPrentice/wrongo | 1e7c9136f5fab7040b5bd5df51b4946876625c88 | [
"Apache-2.0"
] | 72 | 2020-06-12T06:33:41.000Z | 2021-03-22T03:15:56.000Z | src/third_party/mozjs-45/extract/js/src/vm/NativeObject.h | EdwardPrentice/wrongo | 1e7c9136f5fab7040b5bd5df51b4946876625c88 | [
"Apache-2.0"
] | 9 | 2020-07-02T09:36:49.000Z | 2021-03-25T23:54:00.000Z | src/third_party/mozjs-45/extract/js/src/vm/NativeObject.h | EdwardPrentice/wrongo | 1e7c9136f5fab7040b5bd5df51b4946876625c88 | [
"Apache-2.0"
] | 14 | 2020-06-12T03:08:03.000Z | 2021-02-03T11:43:09.000Z | /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sts=4 et sw=4 tw=99:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef vm_NativeObject_h
#define vm_NativeObject_h
#include "mozilla/Assertions.h"
#include "mozilla/Attributes.h"
#include <stdint.h>
#include "jsfriendapi.h"
#include "jsobj.h"
#include "NamespaceImports.h"
#include "gc/Barrier.h"
#include "gc/Heap.h"
#include "gc/Marking.h"
#include "js/Value.h"
#include "vm/Shape.h"
#include "vm/String.h"
#include "vm/TypeInference.h"
namespace js {
class Shape;
class TenuringTracer;
/*
* To really poison a set of values, using 'magic' or 'undefined' isn't good
* enough since often these will just be ignored by buggy code (see bug 629974)
* in debug builds and crash in release builds. Instead, we use a safe-for-crash
* pointer.
*/
static MOZ_ALWAYS_INLINE void
Debug_SetValueRangeToCrashOnTouch(Value* beg, Value* end)
{
#ifdef DEBUG
for (Value* v = beg; v != end; ++v)
v->setObject(*reinterpret_cast<JSObject*>(0x42));
#endif
}
static MOZ_ALWAYS_INLINE void
Debug_SetValueRangeToCrashOnTouch(Value* vec, size_t len)
{
#ifdef DEBUG
Debug_SetValueRangeToCrashOnTouch(vec, vec + len);
#endif
}
static MOZ_ALWAYS_INLINE void
Debug_SetValueRangeToCrashOnTouch(HeapValue* vec, size_t len)
{
#ifdef DEBUG
Debug_SetValueRangeToCrashOnTouch((Value*) vec, len);
#endif
}
static MOZ_ALWAYS_INLINE void
Debug_SetSlotRangeToCrashOnTouch(HeapSlot* vec, uint32_t len)
{
#ifdef DEBUG
Debug_SetValueRangeToCrashOnTouch((Value*) vec, len);
#endif
}
static MOZ_ALWAYS_INLINE void
Debug_SetSlotRangeToCrashOnTouch(HeapSlot* begin, HeapSlot* end)
{
#ifdef DEBUG
Debug_SetValueRangeToCrashOnTouch((Value*) begin, end - begin);
#endif
}
class ArrayObject;
/*
* ES6 20130308 draft 8.4.2.4 ArraySetLength.
*
* |id| must be "length", |attrs| are the attributes to be used for the newly-
* changed length property, |value| is the value for the new length, and
* |result| receives an error code if the change is invalid.
*/
extern bool
ArraySetLength(JSContext* cx, Handle<ArrayObject*> obj, HandleId id,
unsigned attrs, HandleValue value, ObjectOpResult& result);
/*
* Elements header used for native objects. The elements component of such objects
* offers an efficient representation for all or some of the indexed properties
* of the object, using a flat array of Values rather than a shape hierarchy
* stored in the object's slots. This structure is immediately followed by an
* array of elements, with the elements member in an object pointing to the
* beginning of that array (the end of this structure).
* See below for usage of this structure.
*
* The sets of properties represented by an object's elements and slots
* are disjoint. The elements contain only indexed properties, while the slots
* can contain both named and indexed properties; any indexes in the slots are
* distinct from those in the elements. If isIndexed() is false for an object,
* all indexed properties (if any) are stored in the dense elements.
*
* Indexes will be stored in the object's slots instead of its elements in
* the following case:
* - there are more than MIN_SPARSE_INDEX slots total and the load factor
* (COUNT / capacity) is less than 0.25
* - a property is defined that has non-default property attributes.
*
* We track these pieces of metadata for dense elements:
* - The length property as a uint32_t, accessible for array objects with
* ArrayObject::{length,setLength}(). This is unused for non-arrays.
* - The number of element slots (capacity), gettable with
* getDenseCapacity().
* - The array's initialized length, accessible with
* getDenseInitializedLength().
*
* Holes in the array are represented by MagicValue(JS_ELEMENTS_HOLE) values.
* These indicate indexes which are not dense properties of the array. The
* property may, however, be held by the object's properties.
*
* The capacity and length of an object's elements are almost entirely
* unrelated! In general the length may be greater than, less than, or equal
* to the capacity. The first case occurs with |new Array(100)|. The length
* is 100, but the capacity remains 0 (indices below length and above capacity
* must be treated as holes) until elements between capacity and length are
* set. The other two cases are common, depending upon the number of elements
* in an array and the underlying allocator used for element storage.
*
* The only case in which the capacity and length of an object's elements are
* related is when the object is an array with non-writable length. In this
* case the capacity is always less than or equal to the length. This permits
* JIT code to optimize away the check for non-writable length when assigning
* to possibly out-of-range elements: such code already has to check for
* |index < capacity|, and fallback code checks for non-writable length.
*
* The initialized length of an object specifies the number of elements that
* have been initialized. All elements above the initialized length are
* holes in the object, and the memory for all elements between the initialized
* length and capacity is left uninitialized. The initialized length is some
* value less than or equal to both the object's length and the object's
* capacity.
*
* There is flexibility in exactly the value the initialized length must hold,
* e.g. if an array has length 5, capacity 10, completely empty, it is valid
* for the initialized length to be any value between zero and 5, as long as
* the in memory values below the initialized length have been initialized with
* a hole value. However, in such cases we want to keep the initialized length
* as small as possible: if the object is known to have no hole values below
* its initialized length, then it is "packed" and can be accessed much faster
* by JIT code.
*
* Elements do not track property creation order, so enumerating the elements
* of an object does not necessarily visit indexes in the order they were
* created.
*/
class ObjectElements
{
public:
enum Flags {
// Integers written to these elements must be converted to doubles.
CONVERT_DOUBLE_ELEMENTS = 0x1,
// Present only if these elements correspond to an array with
// non-writable length; never present for non-arrays.
NONWRITABLE_ARRAY_LENGTH = 0x2,
// These elements are shared with another object and must be copied
// before they can be changed. A pointer to the original owner of the
// elements, which is immutable, is stored immediately after the
// elements data. There is one case where elements can be written to
// before being copied: when setting the CONVERT_DOUBLE_ELEMENTS flag
// the shared elements may change (from ints to doubles) without
// making a copy first.
COPY_ON_WRITE = 0x4,
// For TypedArrays only: this TypedArray's storage is mapping shared
// memory. This is a static property of the TypedArray, set when it
// is created and never changed.
SHARED_MEMORY = 0x8
};
private:
friend class ::JSObject;
friend class ArrayObject;
friend class NativeObject;
friend class TenuringTracer;
friend bool js::SetIntegrityLevel(JSContext* cx, HandleObject obj, IntegrityLevel level);
friend bool
ArraySetLength(JSContext* cx, Handle<ArrayObject*> obj, HandleId id,
unsigned attrs, HandleValue value, ObjectOpResult& result);
/* See Flags enum above. */
uint32_t flags;
/*
* Number of initialized elements. This is <= the capacity, and for arrays
* is <= the length. Memory for elements above the initialized length is
* uninitialized, but values between the initialized length and the proper
* length are conceptually holes.
*/
uint32_t initializedLength;
/* Number of allocated slots. */
uint32_t capacity;
/* 'length' property of array objects, unused for other objects. */
uint32_t length;
bool shouldConvertDoubleElements() const {
return flags & CONVERT_DOUBLE_ELEMENTS;
}
void setShouldConvertDoubleElements() {
// Note: allow isCopyOnWrite() here, see comment above.
flags |= CONVERT_DOUBLE_ELEMENTS;
}
void clearShouldConvertDoubleElements() {
MOZ_ASSERT(!isCopyOnWrite());
flags &= ~CONVERT_DOUBLE_ELEMENTS;
}
bool hasNonwritableArrayLength() const {
return flags & NONWRITABLE_ARRAY_LENGTH;
}
void setNonwritableArrayLength() {
MOZ_ASSERT(!isCopyOnWrite());
flags |= NONWRITABLE_ARRAY_LENGTH;
}
bool isCopyOnWrite() const {
return flags & COPY_ON_WRITE;
}
void clearCopyOnWrite() {
MOZ_ASSERT(isCopyOnWrite());
flags &= ~COPY_ON_WRITE;
}
public:
MOZ_CONSTEXPR ObjectElements(uint32_t capacity, uint32_t length)
: flags(0), initializedLength(0), capacity(capacity), length(length)
{}
enum class SharedMemory {
IsShared
};
MOZ_CONSTEXPR ObjectElements(uint32_t capacity, uint32_t length, SharedMemory shmem)
: flags(SHARED_MEMORY), initializedLength(0), capacity(capacity), length(length)
{}
HeapSlot* elements() {
return reinterpret_cast<HeapSlot*>(uintptr_t(this) + sizeof(ObjectElements));
}
const HeapSlot* elements() const {
return reinterpret_cast<const HeapSlot*>(uintptr_t(this) + sizeof(ObjectElements));
}
static ObjectElements * fromElements(HeapSlot* elems) {
return reinterpret_cast<ObjectElements*>(uintptr_t(elems) - sizeof(ObjectElements));
}
bool isSharedMemory() const {
return flags & SHARED_MEMORY;
}
HeapPtrNativeObject& ownerObject() const {
MOZ_ASSERT(isCopyOnWrite());
return *(HeapPtrNativeObject*)(&elements()[initializedLength]);
}
static int offsetOfFlags() {
return int(offsetof(ObjectElements, flags)) - int(sizeof(ObjectElements));
}
static int offsetOfInitializedLength() {
return int(offsetof(ObjectElements, initializedLength)) - int(sizeof(ObjectElements));
}
static int offsetOfCapacity() {
return int(offsetof(ObjectElements, capacity)) - int(sizeof(ObjectElements));
}
static int offsetOfLength() {
return int(offsetof(ObjectElements, length)) - int(sizeof(ObjectElements));
}
static bool ConvertElementsToDoubles(JSContext* cx, uintptr_t elements);
static bool MakeElementsCopyOnWrite(ExclusiveContext* cx, NativeObject* obj);
// This is enough slots to store an object of this class. See the static
// assertion below.
static const size_t VALUES_PER_HEADER = 2;
};
static_assert(ObjectElements::VALUES_PER_HEADER * sizeof(HeapSlot) == sizeof(ObjectElements),
"ObjectElements doesn't fit in the given number of slots");
/*
* Shared singletons for objects with no elements.
* emptyObjectElementsShared is used only for TypedArrays, when the TA
* maps shared memory.
*/
extern HeapSlot* const emptyObjectElements;
extern HeapSlot* const emptyObjectElementsShared;
struct Class;
class GCMarker;
class Shape;
class NewObjectCache;
#ifdef DEBUG
static inline bool
IsObjectValueInCompartment(Value v, JSCompartment* comp);
#endif
// Operations which change an object's dense elements can either succeed, fail,
// or be unable to complete. For native objects, the latter is used when the
// object's elements must become sparse instead. The enum below is used for
// such operations, and for similar operations on unboxed arrays and methods
// that work on both kinds of objects.
enum class DenseElementResult {
Failure,
Success,
Incomplete
};
/*
* NativeObject specifies the internal implementation of a native object.
*
* Native objects extend the base implementation of an object with storage
* for the object's named properties and indexed elements.
*
* These are stored separately from one another. Objects are followed by a
* variable-sized array of values for inline storage, which may be used by
* either properties of native objects (fixed slots), by elements (fixed
* elements), or by other data for certain kinds of objects, such as
* ArrayBufferObjects and TypedArrayObjects.
*
* Two native objects with the same shape are guaranteed to have the same
* number of fixed slots.
*
* Named property storage can be split between fixed slots and a dynamically
* allocated array (the slots member). For an object with N fixed slots, shapes
* with slots [0..N-1] are stored in the fixed slots, and the remainder are
* stored in the dynamic array. If all properties fit in the fixed slots, the
* 'slots_' member is nullptr.
*
* Elements are indexed via the 'elements_' member. This member can point to
* either the shared emptyObjectElements and emptyObjectElementsShared singletons,
* into the inline value array (the address of the third value, to leave room
* for a ObjectElements header;in this case numFixedSlots() is zero) or to
* a dynamically allocated array.
*
* Slots and elements may both be non-empty. The slots may be either names or
* indexes; no indexed property will be in both the slots and elements.
*/
class NativeObject : public JSObject
{
protected:
// Property layout description and other state.
HeapPtrShape shape_;
/* Slots for object properties. */
js::HeapSlot* slots_;
/* Slots for object dense elements. */
js::HeapSlot* elements_;
friend class ::JSObject;
private:
static void staticAsserts() {
static_assert(sizeof(NativeObject) == sizeof(JSObject_Slots0),
"native object size must match GC thing size");
static_assert(sizeof(NativeObject) == sizeof(shadow::Object),
"shadow interface must match actual implementation");
static_assert(sizeof(NativeObject) % sizeof(Value) == 0,
"fixed slots after an object must be aligned");
static_assert(offsetof(NativeObject, shape_) == offsetof(shadow::Object, shape),
"shadow shape must match actual shape");
static_assert(offsetof(NativeObject, group_) == offsetof(shadow::Object, group),
"shadow type must match actual type");
static_assert(offsetof(NativeObject, slots_) == offsetof(shadow::Object, slots),
"shadow slots must match actual slots");
static_assert(offsetof(NativeObject, elements_) == offsetof(shadow::Object, _1),
"shadow placeholder must match actual elements");
static_assert(MAX_FIXED_SLOTS <= Shape::FIXED_SLOTS_MAX,
"verify numFixedSlots() bitfield is big enough");
static_assert(sizeof(NativeObject) + MAX_FIXED_SLOTS * sizeof(Value) == JSObject::MAX_BYTE_SIZE,
"inconsistent maximum object size");
}
public:
Shape* lastProperty() const {
MOZ_ASSERT(shape_);
return shape_;
}
uint32_t propertyCount() const {
return lastProperty()->entryCount();
}
bool hasShapeTable() const {
return lastProperty()->hasTable();
}
HeapSlotArray getDenseElements() {
return HeapSlotArray(elements_, !getElementsHeader()->isCopyOnWrite());
}
HeapSlotArray getDenseElementsAllowCopyOnWrite() {
// Backdoor allowing direct access to copy on write elements.
return HeapSlotArray(elements_, true);
}
const Value& getDenseElement(uint32_t idx) {
MOZ_ASSERT(idx < getDenseInitializedLength());
return elements_[idx];
}
bool containsDenseElement(uint32_t idx) {
return idx < getDenseInitializedLength() && !elements_[idx].isMagic(JS_ELEMENTS_HOLE);
}
uint32_t getDenseInitializedLength() {
return getElementsHeader()->initializedLength;
}
uint32_t getDenseCapacity() const {
return getElementsHeader()->capacity;
}
bool isSharedMemory() const {
return getElementsHeader()->isSharedMemory();
}
// Update the last property, keeping the number of allocated slots in sync
// with the object's new slot span.
bool setLastProperty(ExclusiveContext* cx, Shape* shape);
// As for setLastProperty(), but allows the number of fixed slots to
// change. This can only be used when fixed slots are being erased from the
// object, and only when the object will not require dynamic slots to cover
// the new properties.
void setLastPropertyShrinkFixedSlots(Shape* shape);
// As for setLastProperty(), but changes the class associated with the
// object to a non-native one. This leaves the object with a type and shape
// that are (temporarily) inconsistent.
void setLastPropertyMakeNonNative(Shape* shape);
// As for setLastProperty(), but changes the class associated with the
// object to a native one. The object's type has already been changed, and
// this brings the shape into sync with it.
void setLastPropertyMakeNative(ExclusiveContext* cx, Shape* shape);
// Newly-created TypedArrays that map a SharedArrayBuffer are
// marked as shared by giving them an ObjectElements that has the
// ObjectElements::SHARED_MEMORY flag set.
void setIsSharedMemory() {
MOZ_ASSERT(elements_ == emptyObjectElements);
elements_ = emptyObjectElementsShared;
}
protected:
#ifdef DEBUG
void checkShapeConsistency();
#else
void checkShapeConsistency() { }
#endif
Shape*
replaceWithNewEquivalentShape(ExclusiveContext* cx,
Shape* existingShape, Shape* newShape = nullptr,
bool accessorShape = false);
/*
* Remove the last property of an object, provided that it is safe to do so
* (the shape and previous shape do not carry conflicting information about
* the object itself).
*/
inline void removeLastProperty(ExclusiveContext* cx);
inline bool canRemoveLastProperty();
/*
* Update the slot span directly for a dictionary object, and allocate
* slots to cover the new span if necessary.
*/
bool setSlotSpan(ExclusiveContext* cx, uint32_t span);
bool toDictionaryMode(ExclusiveContext* cx);
private:
friend class TenuringTracer;
/*
* Get internal pointers to the range of values starting at start and
* running for length.
*/
void getSlotRangeUnchecked(uint32_t start, uint32_t length,
HeapSlot** fixedStart, HeapSlot** fixedEnd,
HeapSlot** slotsStart, HeapSlot** slotsEnd)
{
MOZ_ASSERT(start + length >= start);
uint32_t fixed = numFixedSlots();
if (start < fixed) {
if (start + length < fixed) {
*fixedStart = &fixedSlots()[start];
*fixedEnd = &fixedSlots()[start + length];
*slotsStart = *slotsEnd = nullptr;
} else {
uint32_t localCopy = fixed - start;
*fixedStart = &fixedSlots()[start];
*fixedEnd = &fixedSlots()[start + localCopy];
*slotsStart = &slots_[0];
*slotsEnd = &slots_[length - localCopy];
}
} else {
*fixedStart = *fixedEnd = nullptr;
*slotsStart = &slots_[start - fixed];
*slotsEnd = &slots_[start - fixed + length];
}
}
void getSlotRange(uint32_t start, uint32_t length,
HeapSlot** fixedStart, HeapSlot** fixedEnd,
HeapSlot** slotsStart, HeapSlot** slotsEnd)
{
MOZ_ASSERT(slotInRange(start + length, SENTINEL_ALLOWED));
getSlotRangeUnchecked(start, length, fixedStart, fixedEnd, slotsStart, slotsEnd);
}
protected:
friend class GCMarker;
friend class Shape;
friend class NewObjectCache;
void invalidateSlotRange(uint32_t start, uint32_t length) {
#ifdef DEBUG
HeapSlot* fixedStart;
HeapSlot* fixedEnd;
HeapSlot* slotsStart;
HeapSlot* slotsEnd;
getSlotRange(start, length, &fixedStart, &fixedEnd, &slotsStart, &slotsEnd);
Debug_SetSlotRangeToCrashOnTouch(fixedStart, fixedEnd);
Debug_SetSlotRangeToCrashOnTouch(slotsStart, slotsEnd);
#endif /* DEBUG */
}
void initializeSlotRange(uint32_t start, uint32_t count);
/*
* Initialize a flat array of slots to this object at a start slot. The
* caller must ensure that are enough slots.
*/
void initSlotRange(uint32_t start, const Value* vector, uint32_t length);
/*
* Copy a flat array of slots to this object at a start slot. Caller must
* ensure there are enough slots in this object.
*/
void copySlotRange(uint32_t start, const Value* vector, uint32_t length);
#ifdef DEBUG
enum SentinelAllowed {
SENTINEL_NOT_ALLOWED,
SENTINEL_ALLOWED
};
/*
* Check that slot is in range for the object's allocated slots.
* If sentinelAllowed then slot may equal the slot capacity.
*/
bool slotInRange(uint32_t slot, SentinelAllowed sentinel = SENTINEL_NOT_ALLOWED) const;
#endif
/*
* Minimum size for dynamically allocated slots in normal Objects.
* ArrayObjects don't use this limit and can have a lower slot capacity,
* since they normally don't have a lot of slots.
*/
static const uint32_t SLOT_CAPACITY_MIN = 8;
HeapSlot* fixedSlots() const {
return reinterpret_cast<HeapSlot*>(uintptr_t(this) + sizeof(NativeObject));
}
public:
bool generateOwnShape(ExclusiveContext* cx, Shape* newShape = nullptr) {
return replaceWithNewEquivalentShape(cx, lastProperty(), newShape);
}
bool shadowingShapeChange(ExclusiveContext* cx, const Shape& shape);
bool clearFlag(ExclusiveContext* cx, BaseShape::Flag flag);
// The maximum number of slots in an object.
// |MAX_SLOTS_COUNT * sizeof(JS::Value)| shouldn't overflow
// int32_t (see slotsSizeMustNotOverflow).
static const uint32_t MAX_SLOTS_COUNT = (1 << 28) - 1;
static void slotsSizeMustNotOverflow() {
static_assert(NativeObject::MAX_SLOTS_COUNT <= INT32_MAX / sizeof(JS::Value),
"every caller of this method requires that a slot "
"number (or slot count) count multiplied by "
"sizeof(Value) can't overflow uint32_t (and sometimes "
"int32_t, too)");
}
uint32_t numFixedSlots() const {
return reinterpret_cast<const shadow::Object*>(this)->numFixedSlots();
}
uint32_t numUsedFixedSlots() const {
uint32_t nslots = lastProperty()->slotSpan(getClass());
return Min(nslots, numFixedSlots());
}
uint32_t slotSpan() const {
if (inDictionaryMode())
return lastProperty()->base()->slotSpan();
return lastProperty()->slotSpan();
}
/* Whether a slot is at a fixed offset from this object. */
bool isFixedSlot(size_t slot) {
return slot < numFixedSlots();
}
/* Index into the dynamic slots array to use for a dynamic slot. */
size_t dynamicSlotIndex(size_t slot) {
MOZ_ASSERT(slot >= numFixedSlots());
return slot - numFixedSlots();
}
/*
* Grow or shrink slots immediately before changing the slot span.
* The number of allocated slots is not stored explicitly, and changes to
* the slots must track changes in the slot span.
*/
bool growSlots(ExclusiveContext* cx, uint32_t oldCount, uint32_t newCount);
void shrinkSlots(ExclusiveContext* cx, uint32_t oldCount, uint32_t newCount);
/*
* This method is static because it's called from JIT code. On OOM, returns
* false without leaving a pending exception on the context.
*/
static bool growSlotsDontReportOOM(ExclusiveContext* cx, NativeObject* obj, uint32_t newCount);
bool hasDynamicSlots() const { return !!slots_; }
/* Compute dynamicSlotsCount() for this object. */
uint32_t numDynamicSlots() const {
return dynamicSlotsCount(numFixedSlots(), slotSpan(), getClass());
}
bool empty() const {
return lastProperty()->isEmptyShape();
}
Shape* lookup(ExclusiveContext* cx, jsid id);
Shape* lookup(ExclusiveContext* cx, PropertyName* name) {
return lookup(cx, NameToId(name));
}
bool contains(ExclusiveContext* cx, jsid id) {
return lookup(cx, id) != nullptr;
}
bool contains(ExclusiveContext* cx, PropertyName* name) {
return lookup(cx, name) != nullptr;
}
bool contains(ExclusiveContext* cx, Shape* shape) {
return lookup(cx, shape->propid()) == shape;
}
bool containsShapeOrElement(ExclusiveContext* cx, jsid id) {
if (JSID_IS_INT(id) && containsDenseElement(JSID_TO_INT(id)))
return true;
return contains(cx, id);
}
/* Contextless; can be called from other pure code. */
Shape* lookupPure(jsid id);
Shape* lookupPure(PropertyName* name) {
return lookupPure(NameToId(name));
}
bool containsPure(jsid id) {
return lookupPure(id) != nullptr;
}
bool containsPure(PropertyName* name) {
return containsPure(NameToId(name));
}
bool containsPure(Shape* shape) {
return lookupPure(shape->propid()) == shape;
}
/*
* Allocate and free an object slot.
*
* FIXME: bug 593129 -- slot allocation should be done by object methods
* after calling object-parameter-free shape methods, avoiding coupling
* logic across the object vs. shape module wall.
*/
static bool allocSlot(ExclusiveContext* cx, HandleNativeObject obj, uint32_t* slotp);
void freeSlot(uint32_t slot);
private:
static Shape* getChildPropertyOnDictionary(ExclusiveContext* cx, HandleNativeObject obj,
HandleShape parent, MutableHandle<StackShape> child);
static Shape* getChildProperty(ExclusiveContext* cx, HandleNativeObject obj,
HandleShape parent, MutableHandle<StackShape> child);
public:
/* Add a property whose id is not yet in this scope. */
static Shape* addProperty(ExclusiveContext* cx, HandleNativeObject obj, HandleId id,
JSGetterOp getter, JSSetterOp setter,
uint32_t slot, unsigned attrs, unsigned flags,
bool allowDictionary = true);
/* Add a data property whose id is not yet in this scope. */
Shape* addDataProperty(ExclusiveContext* cx,
jsid id_, uint32_t slot, unsigned attrs);
Shape* addDataProperty(ExclusiveContext* cx, HandlePropertyName name,
uint32_t slot, unsigned attrs);
/* Add or overwrite a property for id in this scope. */
static Shape*
putProperty(ExclusiveContext* cx, HandleNativeObject obj, HandleId id,
JSGetterOp getter, JSSetterOp setter,
uint32_t slot, unsigned attrs,
unsigned flags);
static inline Shape*
putProperty(ExclusiveContext* cx, HandleObject obj, PropertyName* name,
JSGetterOp getter, JSSetterOp setter,
uint32_t slot, unsigned attrs,
unsigned flags);
/* Change the given property into a sibling with the same id in this scope. */
static Shape*
changeProperty(ExclusiveContext* cx, HandleNativeObject obj, HandleShape shape,
unsigned attrs, JSGetterOp getter, JSSetterOp setter);
/* Remove the property named by id from this object. */
bool removeProperty(ExclusiveContext* cx, jsid id);
/* Clear the scope, making it empty. */
static void clear(ExclusiveContext* cx, HandleNativeObject obj);
protected:
/*
* Internal helper that adds a shape not yet mapped by this object.
*
* Notes:
* 1. getter and setter must be normalized based on flags (see jsscope.cpp).
* 2. Checks for non-extensibility must be done by callers.
*/
static Shape*
addPropertyInternal(ExclusiveContext* cx, HandleNativeObject obj, HandleId id,
JSGetterOp getter, JSSetterOp setter, uint32_t slot, unsigned attrs,
unsigned flags, ShapeTable::Entry* entry, bool allowDictionary);
bool fillInAfterSwap(JSContext* cx, const Vector<Value>& values, void* priv);
public:
// Return true if this object has been converted from shared-immutable
// prototype-rooted shape storage to dictionary-shapes in a doubly-linked
// list.
bool inDictionaryMode() const {
return lastProperty()->inDictionary();
}
const Value& getSlot(uint32_t slot) const {
MOZ_ASSERT(slotInRange(slot));
uint32_t fixed = numFixedSlots();
if (slot < fixed)
return fixedSlots()[slot];
return slots_[slot - fixed];
}
const HeapSlot* getSlotAddressUnchecked(uint32_t slot) const {
uint32_t fixed = numFixedSlots();
if (slot < fixed)
return fixedSlots() + slot;
return slots_ + (slot - fixed);
}
HeapSlot* getSlotAddressUnchecked(uint32_t slot) {
uint32_t fixed = numFixedSlots();
if (slot < fixed)
return fixedSlots() + slot;
return slots_ + (slot - fixed);
}
HeapSlot* getSlotAddress(uint32_t slot) {
/*
* This can be used to get the address of the end of the slots for the
* object, which may be necessary when fetching zero-length arrays of
* slots (e.g. for callObjVarArray).
*/
MOZ_ASSERT(slotInRange(slot, SENTINEL_ALLOWED));
return getSlotAddressUnchecked(slot);
}
const HeapSlot* getSlotAddress(uint32_t slot) const {
/*
* This can be used to get the address of the end of the slots for the
* object, which may be necessary when fetching zero-length arrays of
* slots (e.g. for callObjVarArray).
*/
MOZ_ASSERT(slotInRange(slot, SENTINEL_ALLOWED));
return getSlotAddressUnchecked(slot);
}
HeapSlot& getSlotRef(uint32_t slot) {
MOZ_ASSERT(slotInRange(slot));
return *getSlotAddress(slot);
}
const HeapSlot& getSlotRef(uint32_t slot) const {
MOZ_ASSERT(slotInRange(slot));
return *getSlotAddress(slot);
}
void setSlot(uint32_t slot, const Value& value) {
MOZ_ASSERT(slotInRange(slot));
MOZ_ASSERT(IsObjectValueInCompartment(value, compartment()));
getSlotRef(slot).set(this, HeapSlot::Slot, slot, value);
}
void initSlot(uint32_t slot, const Value& value) {
MOZ_ASSERT(getSlot(slot).isUndefined());
MOZ_ASSERT(slotInRange(slot));
MOZ_ASSERT(IsObjectValueInCompartment(value, compartment()));
initSlotUnchecked(slot, value);
}
void initSlotUnchecked(uint32_t slot, const Value& value) {
getSlotAddressUnchecked(slot)->init(this, HeapSlot::Slot, slot, value);
}
// MAX_FIXED_SLOTS is the biggest number of fixed slots our GC
// size classes will give an object.
static const uint32_t MAX_FIXED_SLOTS = 16;
protected:
inline bool updateSlotsForSpan(ExclusiveContext* cx, size_t oldSpan, size_t newSpan);
public:
/*
* Trigger the write barrier on a range of slots that will no longer be
* reachable.
*/
void prepareSlotRangeForOverwrite(size_t start, size_t end) {
for (size_t i = start; i < end; i++)
getSlotAddressUnchecked(i)->HeapSlot::~HeapSlot();
}
void prepareElementRangeForOverwrite(size_t start, size_t end) {
MOZ_ASSERT(end <= getDenseInitializedLength());
MOZ_ASSERT(!denseElementsAreCopyOnWrite());
for (size_t i = start; i < end; i++)
elements_[i].HeapSlot::~HeapSlot();
}
static bool rollbackProperties(ExclusiveContext* cx, HandleNativeObject obj,
uint32_t slotSpan);
inline void setSlotWithType(ExclusiveContext* cx, Shape* shape,
const Value& value, bool overwriting = true);
inline const Value& getReservedSlot(uint32_t index) const {
MOZ_ASSERT(index < JSSLOT_FREE(getClass()));
return getSlot(index);
}
const HeapSlot& getReservedSlotRef(uint32_t index) const {
MOZ_ASSERT(index < JSSLOT_FREE(getClass()));
return getSlotRef(index);
}
HeapSlot& getReservedSlotRef(uint32_t index) {
MOZ_ASSERT(index < JSSLOT_FREE(getClass()));
return getSlotRef(index);
}
void initReservedSlot(uint32_t index, const Value& v) {
MOZ_ASSERT(index < JSSLOT_FREE(getClass()));
initSlot(index, v);
}
void setReservedSlot(uint32_t index, const Value& v) {
MOZ_ASSERT(index < JSSLOT_FREE(getClass()));
setSlot(index, v);
}
/* For slots which are known to always be fixed, due to the way they are allocated. */
HeapSlot& getFixedSlotRef(uint32_t slot) {
MOZ_ASSERT(slot < numFixedSlots());
return fixedSlots()[slot];
}
const Value& getFixedSlot(uint32_t slot) const {
MOZ_ASSERT(slot < numFixedSlots());
return fixedSlots()[slot];
}
void setFixedSlot(uint32_t slot, const Value& value) {
MOZ_ASSERT(slot < numFixedSlots());
fixedSlots()[slot].set(this, HeapSlot::Slot, slot, value);
}
void initFixedSlot(uint32_t slot, const Value& value) {
MOZ_ASSERT(slot < numFixedSlots());
fixedSlots()[slot].init(this, HeapSlot::Slot, slot, value);
}
/*
* Get the number of dynamic slots to allocate to cover the properties in
* an object with the given number of fixed slots and slot span. The slot
* capacity is not stored explicitly, and the allocated size of the slot
* array is kept in sync with this count.
*/
static uint32_t dynamicSlotsCount(uint32_t nfixed, uint32_t span, const Class* clasp);
static uint32_t dynamicSlotsCount(Shape* shape) {
return dynamicSlotsCount(shape->numFixedSlots(), shape->slotSpan(), shape->getObjectClass());
}
/* Elements accessors. */
// The maximum size, in sizeof(Value), of the allocation used for an
// object's dense elements. (This includes space used to store an
// ObjectElements instance.)
// |MAX_DENSE_ELEMENTS_ALLOCATION * sizeof(JS::Value)| shouldn't overflow
// int32_t (see elementsSizeMustNotOverflow).
static const uint32_t MAX_DENSE_ELEMENTS_ALLOCATION = (1 << 28) - 1;
// The maximum number of usable dense elements in an object.
static const uint32_t MAX_DENSE_ELEMENTS_COUNT =
MAX_DENSE_ELEMENTS_ALLOCATION - ObjectElements::VALUES_PER_HEADER;
static void elementsSizeMustNotOverflow() {
static_assert(NativeObject::MAX_DENSE_ELEMENTS_COUNT <= INT32_MAX / sizeof(JS::Value),
"every caller of this method require that an element "
"count multiplied by sizeof(Value) can't overflow "
"uint32_t (and sometimes int32_t ,too)");
}
ObjectElements * getElementsHeader() const {
return ObjectElements::fromElements(elements_);
}
/* Accessors for elements. */
bool ensureElements(ExclusiveContext* cx, uint32_t capacity) {
MOZ_ASSERT(!denseElementsAreCopyOnWrite());
if (capacity > getDenseCapacity())
return growElements(cx, capacity);
return true;
}
static bool goodElementsAllocationAmount(ExclusiveContext* cx, uint32_t reqAllocated,
uint32_t length, uint32_t* goodAmount);
bool growElements(ExclusiveContext* cx, uint32_t newcap);
void shrinkElements(ExclusiveContext* cx, uint32_t cap);
void setDynamicElements(ObjectElements* header) {
MOZ_ASSERT(!hasDynamicElements());
elements_ = header->elements();
MOZ_ASSERT(hasDynamicElements());
}
static bool CopyElementsForWrite(ExclusiveContext* cx, NativeObject* obj);
bool maybeCopyElementsForWrite(ExclusiveContext* cx) {
if (denseElementsAreCopyOnWrite())
return CopyElementsForWrite(cx, this);
return true;
}
private:
inline void ensureDenseInitializedLengthNoPackedCheck(ExclusiveContext* cx,
uint32_t index, uint32_t extra);
// Run a post write barrier that encompasses multiple contiguous elements in a
// single step.
inline void elementsRangeWriteBarrierPost(uint32_t start, uint32_t count) {
for (size_t i = 0; i < count; i++) {
const Value& v = elements_[start + i];
if (v.isObject() && IsInsideNursery(&v.toObject())) {
JS::shadow::Runtime* shadowRuntime = shadowRuntimeFromMainThread();
shadowRuntime->gcStoreBufferPtr()->putSlot(this, HeapSlot::Element,
start + i, count - i);
return;
}
}
}
public:
void setDenseInitializedLength(uint32_t length) {
MOZ_ASSERT(length <= getDenseCapacity());
MOZ_ASSERT(!denseElementsAreCopyOnWrite());
prepareElementRangeForOverwrite(length, getElementsHeader()->initializedLength);
getElementsHeader()->initializedLength = length;
}
inline void ensureDenseInitializedLength(ExclusiveContext* cx,
uint32_t index, uint32_t extra);
void setDenseElement(uint32_t index, const Value& val) {
MOZ_ASSERT(index < getDenseInitializedLength());
MOZ_ASSERT(!denseElementsAreCopyOnWrite());
elements_[index].set(this, HeapSlot::Element, index, val);
}
void initDenseElement(uint32_t index, const Value& val) {
MOZ_ASSERT(index < getDenseInitializedLength());
MOZ_ASSERT(!denseElementsAreCopyOnWrite());
elements_[index].init(this, HeapSlot::Element, index, val);
}
void setDenseElementMaybeConvertDouble(uint32_t index, const Value& val) {
if (val.isInt32() && shouldConvertDoubleElements())
setDenseElement(index, DoubleValue(val.toInt32()));
else
setDenseElement(index, val);
}
inline void setDenseElementWithType(ExclusiveContext* cx, uint32_t index,
const Value& val);
inline void initDenseElementWithType(ExclusiveContext* cx, uint32_t index,
const Value& val);
inline void setDenseElementHole(ExclusiveContext* cx, uint32_t index);
static inline void removeDenseElementForSparseIndex(ExclusiveContext* cx,
HandleNativeObject obj, uint32_t index);
inline Value getDenseOrTypedArrayElement(uint32_t idx);
void copyDenseElements(uint32_t dstStart, const Value* src, uint32_t count) {
MOZ_ASSERT(dstStart + count <= getDenseCapacity());
MOZ_ASSERT(!denseElementsAreCopyOnWrite());
if (JS::shadow::Zone::asShadowZone(zone())->needsIncrementalBarrier()) {
for (uint32_t i = 0; i < count; ++i)
elements_[dstStart + i].set(this, HeapSlot::Element, dstStart + i, src[i]);
} else {
memcpy(&elements_[dstStart], src, count * sizeof(HeapSlot));
elementsRangeWriteBarrierPost(dstStart, count);
}
}
void initDenseElements(uint32_t dstStart, const Value* src, uint32_t count) {
MOZ_ASSERT(dstStart + count <= getDenseCapacity());
MOZ_ASSERT(!denseElementsAreCopyOnWrite());
memcpy(&elements_[dstStart], src, count * sizeof(HeapSlot));
elementsRangeWriteBarrierPost(dstStart, count);
}
void moveDenseElements(uint32_t dstStart, uint32_t srcStart, uint32_t count) {
MOZ_ASSERT(dstStart + count <= getDenseCapacity());
MOZ_ASSERT(srcStart + count <= getDenseInitializedLength());
MOZ_ASSERT(!denseElementsAreCopyOnWrite());
/*
* Using memmove here would skip write barriers. Also, we need to consider
* an array containing [A, B, C], in the following situation:
*
* 1. Incremental GC marks slot 0 of array (i.e., A), then returns to JS code.
* 2. JS code moves slots 1..2 into slots 0..1, so it contains [B, C, C].
* 3. Incremental GC finishes by marking slots 1 and 2 (i.e., C).
*
* Since normal marking never happens on B, it is very important that the
* write barrier is invoked here on B, despite the fact that it exists in
* the array before and after the move.
*/
if (JS::shadow::Zone::asShadowZone(zone())->needsIncrementalBarrier()) {
if (dstStart < srcStart) {
HeapSlot* dst = elements_ + dstStart;
HeapSlot* src = elements_ + srcStart;
for (uint32_t i = 0; i < count; i++, dst++, src++)
dst->set(this, HeapSlot::Element, dst - elements_, *src);
} else {
HeapSlot* dst = elements_ + dstStart + count - 1;
HeapSlot* src = elements_ + srcStart + count - 1;
for (uint32_t i = 0; i < count; i++, dst--, src--)
dst->set(this, HeapSlot::Element, dst - elements_, *src);
}
} else {
memmove(elements_ + dstStart, elements_ + srcStart, count * sizeof(HeapSlot));
elementsRangeWriteBarrierPost(dstStart, count);
}
}
void moveDenseElementsNoPreBarrier(uint32_t dstStart, uint32_t srcStart, uint32_t count) {
MOZ_ASSERT(!shadowZone()->needsIncrementalBarrier());
MOZ_ASSERT(dstStart + count <= getDenseCapacity());
MOZ_ASSERT(srcStart + count <= getDenseCapacity());
MOZ_ASSERT(!denseElementsAreCopyOnWrite());
memmove(elements_ + dstStart, elements_ + srcStart, count * sizeof(Value));
elementsRangeWriteBarrierPost(dstStart, count);
}
bool shouldConvertDoubleElements() {
return getElementsHeader()->shouldConvertDoubleElements();
}
inline void setShouldConvertDoubleElements();
inline void clearShouldConvertDoubleElements();
bool denseElementsAreCopyOnWrite() {
return getElementsHeader()->isCopyOnWrite();
}
/* Packed information for this object's elements. */
inline bool writeToIndexWouldMarkNotPacked(uint32_t index);
inline void markDenseElementsNotPacked(ExclusiveContext* cx);
// Ensures that the object can hold at least index + extra elements. This
// returns DenseElement_Success on success, DenseElement_Failed on failure
// to grow the array, or DenseElement_Incomplete when the object is too
// sparse to grow (this includes the case of index + extra overflow). In
// the last two cases the object is kept intact.
inline DenseElementResult ensureDenseElements(ExclusiveContext* cx,
uint32_t index, uint32_t extra);
inline DenseElementResult extendDenseElements(ExclusiveContext* cx,
uint32_t requiredCapacity, uint32_t extra);
/* Convert a single dense element to a sparse property. */
static bool sparsifyDenseElement(ExclusiveContext* cx,
HandleNativeObject obj, uint32_t index);
/* Convert all dense elements to sparse properties. */
static bool sparsifyDenseElements(ExclusiveContext* cx, HandleNativeObject obj);
/* Small objects are dense, no matter what. */
static const uint32_t MIN_SPARSE_INDEX = 1000;
/*
* Element storage for an object will be sparse if fewer than 1/8 indexes
* are filled in.
*/
static const unsigned SPARSE_DENSITY_RATIO = 8;
/*
* Check if after growing the object's elements will be too sparse.
* newElementsHint is an estimated number of elements to be added.
*/
bool willBeSparseElements(uint32_t requiredCapacity, uint32_t newElementsHint);
/*
* After adding a sparse index to obj, see if it should be converted to use
* dense elements.
*/
static DenseElementResult maybeDensifySparseElements(ExclusiveContext* cx,
HandleNativeObject obj);
inline HeapSlot* fixedElements() const {
static_assert(2 * sizeof(Value) == sizeof(ObjectElements),
"when elements are stored inline, the first two "
"slots will hold the ObjectElements header");
return &fixedSlots()[2];
}
#ifdef DEBUG
bool canHaveNonEmptyElements();
#endif
void setFixedElements() {
MOZ_ASSERT(canHaveNonEmptyElements());
elements_ = fixedElements();
}
inline bool hasDynamicElements() const {
/*
* Note: for objects with zero fixed slots this could potentially give
* a spurious 'true' result, if the end of this object is exactly
* aligned with the end of its arena and dynamic slots are allocated
* immediately afterwards. Such cases cannot occur for dense arrays
* (which have at least two fixed slots) and can only result in a leak.
*/
return !hasEmptyElements() && elements_ != fixedElements();
}
inline bool hasFixedElements() const {
return elements_ == fixedElements();
}
inline bool hasEmptyElements() const {
return elements_ == emptyObjectElements || elements_ == emptyObjectElementsShared;
}
/*
* Get a pointer to the unused data in the object's allocation immediately
* following this object, for use with objects which allocate a larger size
* class than they need and store non-elements data inline.
*/
inline uint8_t* fixedData(size_t nslots) const;
inline void privateWriteBarrierPre(void** oldval);
void privateWriteBarrierPost(void** pprivate) {
gc::Cell** cellp = reinterpret_cast<gc::Cell**>(pprivate);
MOZ_ASSERT(cellp);
MOZ_ASSERT(*cellp);
gc::StoreBuffer* storeBuffer = (*cellp)->storeBuffer();
if (storeBuffer)
storeBuffer->putCell(cellp);
}
/* Private data accessors. */
inline void*& privateRef(uint32_t nfixed) const { /* XXX should be private, not protected! */
/*
* The private pointer of an object can hold any word sized value.
* Private pointers are stored immediately after the last fixed slot of
* the object.
*/
MOZ_ASSERT(nfixed == numFixedSlots());
MOZ_ASSERT(hasPrivate());
HeapSlot* end = &fixedSlots()[nfixed];
return *reinterpret_cast<void**>(end);
}
bool hasPrivate() const {
return getClass()->hasPrivate();
}
void* getPrivate() const {
return privateRef(numFixedSlots());
}
void setPrivate(void* data) {
void** pprivate = &privateRef(numFixedSlots());
privateWriteBarrierPre(pprivate);
*pprivate = data;
}
void setPrivateGCThing(gc::Cell* cell) {
void** pprivate = &privateRef(numFixedSlots());
privateWriteBarrierPre(pprivate);
*pprivate = reinterpret_cast<void*>(cell);
privateWriteBarrierPost(pprivate);
}
void setPrivateUnbarriered(void* data) {
void** pprivate = &privateRef(numFixedSlots());
*pprivate = data;
}
void initPrivate(void* data) {
privateRef(numFixedSlots()) = data;
}
/* Access private data for an object with a known number of fixed slots. */
inline void* getPrivate(uint32_t nfixed) const {
return privateRef(nfixed);
}
static inline NativeObject*
copy(ExclusiveContext* cx, gc::AllocKind kind, gc::InitialHeap heap,
HandleNativeObject templateObject);
/* JIT Accessors */
static size_t offsetOfElements() { return offsetof(NativeObject, elements_); }
static size_t offsetOfFixedElements() {
return sizeof(NativeObject) + sizeof(ObjectElements);
}
static size_t getFixedSlotOffset(size_t slot) {
return sizeof(NativeObject) + slot * sizeof(Value);
}
static size_t getPrivateDataOffset(size_t nfixed) { return getFixedSlotOffset(nfixed); }
static size_t offsetOfSlots() { return offsetof(NativeObject, slots_); }
};
// Object class for plain native objects created using '{}' object literals,
// 'new Object()', 'Object.create', etc.
class PlainObject : public NativeObject
{
public:
static const js::Class class_;
};
inline void
NativeObject::privateWriteBarrierPre(void** oldval)
{
JS::shadow::Zone* shadowZone = this->shadowZoneFromAnyThread();
if (shadowZone->needsIncrementalBarrier()) {
if (*oldval && getClass()->trace)
getClass()->trace(shadowZone->barrierTracer(), this);
}
}
#ifdef DEBUG
static inline bool
IsObjectValueInCompartment(Value v, JSCompartment* comp)
{
if (!v.isObject())
return true;
return v.toObject().compartment() == comp;
}
#endif
/*** Standard internal methods *******************************************************************/
/*
* These functions should follow the algorithms in ES6 draft rev 29 section 9.1
* ("Ordinary Object Internal Methods"). It's an ongoing project.
*
* Many native objects are not "ordinary" in ES6, so these functions also have
* to serve some of the special needs of Functions (9.2, 9.3, 9.4.1), Arrays
* (9.4.2), Strings (9.4.3), and so on.
*/
extern bool
NativeDefineProperty(ExclusiveContext* cx, HandleNativeObject obj, HandleId id,
Handle<PropertyDescriptor> desc,
ObjectOpResult& result);
extern bool
NativeDefineProperty(ExclusiveContext* cx, HandleNativeObject obj, HandleId id, HandleValue value,
JSGetterOp getter, JSSetterOp setter, unsigned attrs,
ObjectOpResult& result);
extern bool
NativeDefineProperty(ExclusiveContext* cx, HandleNativeObject obj, PropertyName* name,
HandleValue value, GetterOp getter, SetterOp setter,
unsigned attrs, ObjectOpResult& result);
extern bool
NativeDefineElement(ExclusiveContext* cx, HandleNativeObject obj, uint32_t index, HandleValue value,
JSGetterOp getter, JSSetterOp setter, unsigned attrs,
ObjectOpResult& result);
/* If the result out-param is omitted, throw on failure. */
extern bool
NativeDefineProperty(ExclusiveContext* cx, HandleNativeObject obj, HandleId id, HandleValue value,
JSGetterOp getter, JSSetterOp setter, unsigned attrs);
extern bool
NativeDefineProperty(ExclusiveContext* cx, HandleNativeObject obj, PropertyName* name,
HandleValue value, JSGetterOp getter, JSSetterOp setter,
unsigned attrs);
extern bool
NativeHasProperty(JSContext* cx, HandleNativeObject obj, HandleId id, bool* foundp);
extern bool
NativeGetProperty(JSContext* cx, HandleNativeObject obj, HandleValue receiver, HandleId id,
MutableHandleValue vp);
extern bool
NativeGetPropertyNoGC(JSContext* cx, NativeObject* obj, const Value& receiver, jsid id, Value* vp);
extern bool
NativeGetElement(JSContext* cx, HandleNativeObject obj, HandleValue receiver, uint32_t index,
MutableHandleValue vp);
inline bool
NativeGetProperty(JSContext* cx, HandleNativeObject obj, HandleId id, MutableHandleValue vp)
{
RootedValue receiver(cx, ObjectValue(*obj));
return NativeGetProperty(cx, obj, receiver, id, vp);
}
inline bool
NativeGetElement(JSContext* cx, HandleNativeObject obj, uint32_t index, MutableHandleValue vp)
{
RootedValue receiver(cx, ObjectValue(*obj));
return NativeGetElement(cx, obj, receiver, index, vp);
}
bool
SetPropertyByDefining(JSContext* cx, HandleId id, HandleValue v, HandleValue receiver,
ObjectOpResult& result);
bool
SetPropertyOnProto(JSContext* cx, HandleObject obj, HandleId id, HandleValue v,
HandleValue receiver, ObjectOpResult& result);
/*
* Indicates whether an assignment operation is qualified (`x.y = 0`) or
* unqualified (`y = 0`). In strict mode, the latter is an error if no such
* variable already exists.
*
* Used as an argument to NativeSetProperty.
*/
enum QualifiedBool {
Unqualified = 0,
Qualified = 1
};
extern bool
NativeSetProperty(JSContext* cx, HandleNativeObject obj, HandleId id, HandleValue v,
HandleValue receiver, QualifiedBool qualified, ObjectOpResult& result);
extern bool
NativeSetElement(JSContext* cx, HandleNativeObject obj, uint32_t index, HandleValue v,
HandleValue receiver, ObjectOpResult& result);
extern bool
NativeDeleteProperty(JSContext* cx, HandleNativeObject obj, HandleId id, ObjectOpResult& result);
/*** SpiderMonkey nonstandard internal methods ***************************************************/
template <AllowGC allowGC>
extern bool
NativeLookupOwnProperty(ExclusiveContext* cx,
typename MaybeRooted<NativeObject*, allowGC>::HandleType obj,
typename MaybeRooted<jsid, allowGC>::HandleType id,
typename MaybeRooted<Shape*, allowGC>::MutableHandleType propp);
/*
* Get a property from `receiver`, after having already done a lookup and found
* the property on a native object `obj`.
*
* `shape` must not be null and must not be an implicit dense property. It must
* be present in obj's shape chain.
*/
extern bool
NativeGetExistingProperty(JSContext* cx, HandleObject receiver, HandleNativeObject obj,
HandleShape shape, MutableHandleValue vp);
/* * */
/*
* If obj has an already-resolved data property for id, return true and
* store the property value in *vp.
*/
extern bool
HasDataProperty(JSContext* cx, NativeObject* obj, jsid id, Value* vp);
inline bool
HasDataProperty(JSContext* cx, NativeObject* obj, PropertyName* name, Value* vp)
{
return HasDataProperty(cx, obj, NameToId(name), vp);
}
extern bool
GetPropertyForNameLookup(JSContext* cx, HandleObject obj, HandleId id, MutableHandleValue vp);
} /* namespace js */
template <>
inline bool
JSObject::is<js::NativeObject>() const { return isNative(); }
namespace js {
// Alternate to JSObject::as<NativeObject>() that tolerates null pointers.
inline NativeObject*
MaybeNativeObject(JSObject* obj)
{
return obj ? &obj->as<NativeObject>() : nullptr;
}
} // namespace js
/*** Inline functions declared in jsobj.h that use the native declarations above *****************/
inline bool
js::HasProperty(JSContext* cx, HandleObject obj, HandleId id, bool* foundp)
{
if (HasPropertyOp op = obj->getOps()->hasProperty)
return op(cx, obj, id, foundp);
return NativeHasProperty(cx, obj.as<NativeObject>(), id, foundp);
}
inline bool
js::GetProperty(JSContext* cx, HandleObject obj, HandleValue receiver, HandleId id,
MutableHandleValue vp)
{
if (GetPropertyOp op = obj->getOps()->getProperty)
return op(cx, obj, receiver, id, vp);
return NativeGetProperty(cx, obj.as<NativeObject>(), receiver, id, vp);
}
inline bool
js::GetPropertyNoGC(JSContext* cx, JSObject* obj, const Value& receiver, jsid id, Value* vp)
{
if (obj->getOps()->getProperty)
return false;
return NativeGetPropertyNoGC(cx, &obj->as<NativeObject>(), receiver, id, vp);
}
inline bool
js::SetProperty(JSContext* cx, HandleObject obj, HandleId id, HandleValue v,
HandleValue receiver, ObjectOpResult& result)
{
if (obj->getOps()->setProperty)
return JSObject::nonNativeSetProperty(cx, obj, id, v, receiver, result);
return NativeSetProperty(cx, obj.as<NativeObject>(), id, v, receiver, Qualified, result);
}
inline bool
js::SetElement(JSContext* cx, HandleObject obj, uint32_t index, HandleValue v,
HandleValue receiver, ObjectOpResult& result)
{
if (obj->getOps()->setProperty)
return JSObject::nonNativeSetElement(cx, obj, index, v, receiver, result);
return NativeSetElement(cx, obj.as<NativeObject>(), index, v, receiver, result);
}
#endif /* vm_NativeObject_h */
| 37.804797 | 104 | 0.670138 | [
"object",
"shape",
"vector"
] |
cf0fc3e885abb080b0f24a1736e69548818d964a | 2,004 | c | C | lib_poise/intens_pixel_diff_mex.c | jbellis/superpixel-benchmark | 81a45649d426751d1ae450ef8ea0d2d9c7b3545f | [
"Unlicense"
] | 344 | 2016-12-16T10:11:05.000Z | 2022-03-29T06:08:14.000Z | lib_poise/intens_pixel_diff_mex.c | jbellis/superpixel-benchmark | 81a45649d426751d1ae450ef8ea0d2d9c7b3545f | [
"Unlicense"
] | 12 | 2018-02-15T19:34:19.000Z | 2021-07-31T17:04:48.000Z | lib_poise/intens_pixel_diff_mex.c | jbellis/superpixel-benchmark | 81a45649d426751d1ae450ef8ea0d2d9c7b3545f | [
"Unlicense"
] | 111 | 2016-12-08T07:19:21.000Z | 2022-03-29T06:08:16.000Z | /* Copyright (C) 2010 Joao Carreira
This code is part of the extended implementation of the paper:
J. Carreira, C. Sminchisescu, Constrained Parametric Min-Cuts for Automatic Object Segmentation, IEEE CVPR 2010
*/
/*---
function [w] = intens_pixel_diff_mex(I, i, j)
Input:
I - gray level image, must be double
[i,j] = indices of pixels
Output:
cw = real vector of the same size as ci,
absolute difference between pixel values at positions i and j
--*/
# include "mex.h"
# include "math.h"
void mexFunction(
int nargout,
mxArray *out[],
int nargin,
const mxArray *in[]) {
/* declare variables */
int nr, nc, np, a, total;
unsigned int *i, *j;
double *I;
double *w;
/* check argument */
if (nargin<3) {
mexErrMsgTxt("Three input arguments required");
}
if (nargout>1) {
mexErrMsgTxt("Too many output arguments");
}
int diff_type = 0;
if (nargin == 4) {
double* diff_opt = mxGetData(in[3]);
if (diff_opt[0] == 0) {
/* L1 difference */
diff_type = 0;
} else {
/* max (L-inf) */
diff_type = 1;
}
}
nr = mxGetM(in[0]);
nc = mxGetN(in[0]);
I = mxGetData(in[0]);
/* get the ij-index pair */
if (!mxIsUint32(in[1]) || !mxIsUint32(in[2])) {
mexErrMsgTxt("Index pair shall be of type UINT32");
}
i = mxGetData(in[2]);
j = mxGetData(in[1]);
np = mxGetM(in[2]) * mxGetN(in[2]);
/* create output */
total = mxGetM(in[1]) * mxGetN(in[1]);
out[0] = mxCreateDoubleMatrix(total,1,mxREAL);
if (out[0]==NULL) {
mexErrMsgTxt("Not enough memory for the output vector");
}
w = mxGetPr(out[0]);
/* computation, indexing is zero-based, in contrast to matlab */
if (diff_type == 0) {
for (a=0; a<np; a++) {
w[a] = fabs(I[i[a]-1] - I[j[a]-1]);
}
} else {
for (a=0; a<np; a++) {
w[a] = I[i[a]-1] > I[j[a]-1] ? I[i[a]-1] : I[j[a]-1];
}
}
}
| 23.034483 | 113 | 0.550399 | [
"object",
"vector"
] |
cf128e5b134433a20d85d069b2f01a0a47af82c8 | 8,835 | c | C | src/emu/cpu/vtlb.c | seleuco/MAME4droid_Native | b6adcf8ba8ac602d93d28ec4e6f7346f92c84363 | [
"Unlicense"
] | 5 | 2020-09-09T09:24:59.000Z | 2022-03-22T04:44:14.000Z | src/emu/cpu/vtlb.c | seleuco/MAME4droid_Native | b6adcf8ba8ac602d93d28ec4e6f7346f92c84363 | [
"Unlicense"
] | null | null | null | src/emu/cpu/vtlb.c | seleuco/MAME4droid_Native | b6adcf8ba8ac602d93d28ec4e6f7346f92c84363 | [
"Unlicense"
] | 4 | 2021-02-04T13:26:39.000Z | 2022-03-07T08:51:45.000Z | /***************************************************************************
vtlb.c
Generic virtual TLB implementation.
Copyright Aaron Giles
Released for general non-commercial use under the MAME license
Visit http://mamedev.org for licensing and usage restrictions.
***************************************************************************/
#include "emu.h"
#include "vtlb.h"
/***************************************************************************
DEBUGGING
***************************************************************************/
#define PRINTF_TLB (0)
/***************************************************************************
TYPE DEFINITIONS
***************************************************************************/
/* VTLB state */
struct _vtlb_state
{
cpu_device * cpudevice; /* CPU device */
int space; /* address space */
int dynamic; /* number of dynamic entries */
int fixed; /* number of fixed entries */
int dynindex; /* index of next dynamic entry */
int pageshift; /* bits to shift to get page index */
int addrwidth; /* logical address bus width */
offs_t * live; /* array of live entries by table index */
int * fixedpages; /* number of pages each fixed entry covers */
vtlb_entry * table; /* table of entries by address */
vtlb_entry * save; /* cache of live table entries for saving */
};
/***************************************************************************
INITIALIZATION/TEARDOWN
***************************************************************************/
/*-------------------------------------------------
vtlb_alloc - allocate a new VTLB for the
given CPU
-------------------------------------------------*/
vtlb_state *vtlb_alloc(running_device *cpu, int space, int fixed_entries, int dynamic_entries)
{
vtlb_state *vtlb;
/* allocate memory for the core structure */
vtlb = auto_alloc_clear(cpu->machine, vtlb_state);
/* fill in CPU information */
vtlb->cpudevice = downcast<cpu_device *>(cpu);
vtlb->space = space;
vtlb->dynamic = dynamic_entries;
vtlb->fixed = fixed_entries;
const address_space_config *spaceconfig = devconfig_get_space_config(cpu->baseconfig(), space);
assert(spaceconfig != NULL);
vtlb->pageshift = spaceconfig->m_page_shift;
vtlb->addrwidth = spaceconfig->m_logaddr_width;
/* validate CPU information */
assert((1 << vtlb->pageshift) > VTLB_FLAGS_MASK);
assert(vtlb->addrwidth > vtlb->pageshift);
/* allocate the entry array */
vtlb->live = auto_alloc_array_clear(cpu->machine, offs_t, fixed_entries + dynamic_entries);
state_save_register_device_item_pointer(cpu, space, vtlb->live, fixed_entries + dynamic_entries);
/* allocate the lookup table */
vtlb->table = auto_alloc_array_clear(cpu->machine, vtlb_entry, (size_t) 1 << (vtlb->addrwidth - vtlb->pageshift));
state_save_register_device_item_pointer(cpu, space, vtlb->table, 1 << (vtlb->addrwidth - vtlb->pageshift));
/* allocate the fixed page count array */
if (fixed_entries > 0)
{
vtlb->fixedpages = auto_alloc_array_clear(cpu->machine, int, fixed_entries);
state_save_register_device_item_pointer(cpu, space, vtlb->fixedpages, fixed_entries);
}
return vtlb;
}
/*-------------------------------------------------
vtlb_free - free an allocated VTLB
-------------------------------------------------*/
void vtlb_free(vtlb_state *vtlb)
{
/* free the fixed pages if allocated */
if (vtlb->fixedpages != NULL)
auto_free(vtlb->cpudevice->machine, vtlb->fixedpages);
/* free the table and array if they exist */
if (vtlb->live != NULL)
auto_free(vtlb->cpudevice->machine, vtlb->live);
if (vtlb->table != NULL)
auto_free(vtlb->cpudevice->machine, vtlb->table);
/* and then the VTLB object itself */
auto_free(vtlb->cpudevice->machine, vtlb);
}
/***************************************************************************
FILLING
***************************************************************************/
/*-------------------------------------------------
vtlb_fill - rcalled by the CPU core in
response to an unmapped access
-------------------------------------------------*/
int vtlb_fill(vtlb_state *vtlb, offs_t address, int intention)
{
offs_t tableindex = address >> vtlb->pageshift;
vtlb_entry entry = vtlb->table[tableindex];
offs_t taddress;
if (PRINTF_TLB)
printf("vtlb_fill: %08X(%X) ... ", address, intention);
/* should not be called here if the entry is in the table already */
// assert((entry & (1 << intention)) == 0);
/* if we have no dynamic entries, we always fail */
if (vtlb->dynamic == 0)
{
if (PRINTF_TLB)
printf("failed: no dynamic entries\n");
return FALSE;
}
/* ask the CPU core to translate for us */
taddress = address;
if (!vtlb->cpudevice->translate(vtlb->space, intention, taddress))
{
if (PRINTF_TLB)
printf("failed: no translation\n");
return FALSE;
}
/* if this is the first successful translation for this address, allocate a new entry */
if ((entry & VTLB_FLAGS_MASK) == 0)
{
int liveindex = vtlb->dynindex++ % vtlb->dynamic;
/* if an entry already exists at this index, free it */
if (vtlb->live[liveindex] != 0)
vtlb->table[vtlb->live[liveindex] - 1] = 0;
/* claim this new entry */
vtlb->live[liveindex] = tableindex + 1;
/* form a new blank entry */
entry = (taddress >> vtlb->pageshift) << vtlb->pageshift;
entry |= VTLB_FLAG_VALID;
if (PRINTF_TLB)
printf("success (%08X), new entry\n", taddress);
}
/* otherwise, ensure that different intentions do not produce different addresses */
else
{
assert((entry >> vtlb->pageshift) == (taddress >> vtlb->pageshift));
assert(entry & VTLB_FLAG_VALID);
if (PRINTF_TLB)
printf("success (%08X), existing entry\n", taddress);
}
/* add the intention to the list of valid intentions and store */
entry |= 1 << (intention & (TRANSLATE_TYPE_MASK | TRANSLATE_USER_MASK));
vtlb->table[tableindex] = entry;
return TRUE;
}
/*-------------------------------------------------
vtlb_load - load a fixed VTLB entry
-------------------------------------------------*/
void vtlb_load(vtlb_state *vtlb, int entrynum, int numpages, offs_t address, vtlb_entry value)
{
offs_t tableindex = address >> vtlb->pageshift;
int liveindex = vtlb->dynamic + entrynum;
int pagenum;
/* must be in range */
assert(entrynum >= 0 && entrynum < vtlb->fixed);
if (PRINTF_TLB)
printf("vtlb_load %d for %d pages at %08X == %08X\n", entrynum, numpages, address, value);
/* if an entry already exists at this index, free it */
if (vtlb->live[liveindex] != 0)
{
int pagecount = vtlb->fixedpages[entrynum];
int oldtableindex = vtlb->live[liveindex] - 1;
for (pagenum = 0; pagenum < pagecount; pagenum++)
vtlb->table[oldtableindex + pagenum] = 0;
}
/* claim this new entry */
vtlb->live[liveindex] = tableindex + 1;
/* store the raw value, making sure the "fixed" flag is set */
value |= VTLB_FLAG_FIXED;
vtlb->fixedpages[entrynum] = numpages;
for (pagenum = 0; pagenum < numpages; pagenum++)
vtlb->table[tableindex + pagenum] = value + (pagenum << vtlb->pageshift);
}
/***************************************************************************
FLUSHING
***************************************************************************/
/*-------------------------------------------------
vtlb_flush_dynamic - flush all knowledge
from the dynamic part of the VTLB
-------------------------------------------------*/
void vtlb_flush_dynamic(vtlb_state *vtlb)
{
int liveindex;
if (PRINTF_TLB)
printf("vtlb_flush_dynamic\n");
/* loop over live entries and release them from the table */
for (liveindex = 0; liveindex < vtlb->dynamic; liveindex++)
if (vtlb->live[liveindex] != 0)
{
offs_t tableindex = vtlb->live[liveindex] - 1;
vtlb->table[tableindex] = 0;
vtlb->live[liveindex] = 0;
}
}
/*-------------------------------------------------
vtlb_flush_address - flush knowledge of a
particular address from the VTLB
-------------------------------------------------*/
void vtlb_flush_address(vtlb_state *vtlb, offs_t address)
{
offs_t tableindex = address >> vtlb->pageshift;
if (PRINTF_TLB)
printf("vtlb_flush_address %08X\n", address);
/* free the entry in the table; for speed, we leave the entry in the live array */
vtlb->table[tableindex] = 0;
}
/***************************************************************************
ACCESSORS
***************************************************************************/
/*-------------------------------------------------
vtlb_table - return a pointer to the base of
the linear VTLB lookup table
-------------------------------------------------*/
const vtlb_entry *vtlb_table(vtlb_state *vtlb)
{
return vtlb->table;
}
| 30.677083 | 115 | 0.549519 | [
"object"
] |
cf163379093db7f947e0c0e52829148ca5caabda | 3,026 | h | C | third_party/WebKit/Source/core/paint/BoxBorderPainter.h | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-28T08:09:58.000Z | 2021-11-15T15:32:10.000Z | third_party/WebKit/Source/core/paint/BoxBorderPainter.h | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/core/paint/BoxBorderPainter.h | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.000Z | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BoxBorderPainter_h
#define BoxBorderPainter_h
#include "core/layout/BackgroundBleedAvoidance.h"
#include "core/style/BorderEdge.h"
#include "platform/geometry/FloatRoundedRect.h"
namespace blink {
class ComputedStyle;
class GraphicsContext;
class IntRect;
class LayoutBox;
class LayoutRect;
struct PaintInfo;
class Path;
typedef unsigned BorderEdgeFlags;
class BoxBorderPainter {
STACK_ALLOCATED();
public:
BoxBorderPainter(const LayoutRect& borderRect, const ComputedStyle&,
BackgroundBleedAvoidance, bool includeLogicalLeftEdge, bool includeLogicalRightEdge);
BoxBorderPainter(const ComputedStyle&, const LayoutRect& outer, const LayoutRect& inner,
const BorderEdge& uniformEdgeInfo);
void paintBorder(const PaintInfo&, const LayoutRect& borderRect) const;
private:
struct ComplexBorderInfo;
enum MiterType {
NoMiter,
SoftMiter, // Anti-aliased
HardMiter, // Not anti-aliased
};
void computeBorderProperties();
BorderEdgeFlags paintOpacityGroup(GraphicsContext&, const ComplexBorderInfo&, unsigned index,
float accumulatedOpacity) const;
void paintSide(GraphicsContext&, const ComplexBorderInfo&, BoxSide, unsigned alpha, BorderEdgeFlags) const;
void paintOneBorderSide(GraphicsContext&, const FloatRect& sideRect, BoxSide, BoxSide adjacentSide1,
BoxSide adjacentSide2, const Path*, bool antialias, Color, BorderEdgeFlags) const;
bool paintBorderFastPath(GraphicsContext&, const LayoutRect& borderRect) const;
void drawDoubleBorder(GraphicsContext&, const LayoutRect& borderRect) const;
void drawBoxSideFromPath(GraphicsContext&, const LayoutRect&, const Path&, float thickness,
float drawThickness, BoxSide, Color, EBorderStyle) const;
void clipBorderSidePolygon(GraphicsContext&, BoxSide, MiterType miter1, MiterType miter2) const;
void clipBorderSideForComplexInnerPath(GraphicsContext&, BoxSide) const;
MiterType computeMiter(BoxSide, BoxSide adjacentSide, BorderEdgeFlags, bool antialias) const;
static bool mitersRequireClipping(MiterType miter1, MiterType miter2, EBorderStyle, bool antialias);
const BorderEdge& firstEdge() const
{
ASSERT(m_visibleEdgeSet);
return m_edges[m_firstVisibleEdge];
}
// const inputs
const ComputedStyle& m_style;
const BackgroundBleedAvoidance m_bleedAvoidance;
const bool m_includeLogicalLeftEdge;
const bool m_includeLogicalRightEdge;
// computed attributes
FloatRoundedRect m_outer;
FloatRoundedRect m_inner;
BorderEdge m_edges[4];
unsigned m_visibleEdgeCount;
unsigned m_firstVisibleEdge;
BorderEdgeFlags m_visibleEdgeSet;
bool m_isUniformStyle;
bool m_isUniformWidth;
bool m_isUniformColor;
bool m_isRounded;
bool m_hasAlpha;
};
} // namespace blink
#endif
| 32.891304 | 111 | 0.764706 | [
"geometry"
] |
cf1d4f3462fe618656e6752aaaafaba8aa9c004f | 73,523 | c | C | src/cave.c | zaimoni/zaiband | 5a24bfe51695241fe15697150e35a58c44aa5d8f | [
"BSL-1.0",
"CC-BY-3.0"
] | null | null | null | src/cave.c | zaimoni/zaiband | 5a24bfe51695241fe15697150e35a58c44aa5d8f | [
"BSL-1.0",
"CC-BY-3.0"
] | null | null | null | src/cave.c | zaimoni/zaiband | 5a24bfe51695241fe15697150e35a58c44aa5d8f | [
"BSL-1.0",
"CC-BY-3.0"
] | null | null | null | /* File: cave.c */
/*
* Copyright (c) 1997 Ben Harrison, James E. Wilson, Robert A. Koeneke
* Copyright (c) 2007 Kenneth 'Bessarion' Boyd
*
* This work is free software; you can redistribute it and/or modify it
* under the terms of either:
*
* a) the GNU General Public License as published by the Free Software
* Foundation, version 2, or
*
* b) the "Angband licence":
* This software may be copied and distributed for educational, research,
* and not for profit purposes provided that this copyright and statement
* are included in all such copies. Other copyrights may also apply.
*/
#include "angband.h"
#include "game-event.h"
#include "option.h"
#include "raceflag.h"
#include "wind_flg.h"
#include "flow.h"
#include "keypad.h"
/*
* Support for Adam Bolt's tileset, lighting and transparency effects
* by Robert Ruehlmann (rr9@thangorodrim.net)
*/
/**
* Angband has three different "line of sight" type concepts, including this
* function (which is used almost nowhere), the "project()" method (which
* is used for determining the paths of projectables and spells and such),
* and the "update_view()" concept (which is used to determine which grids
* are "viewable" by the player, which is used for many things, such as
* determining which grids are illuminated by the player's torch, and which
* grids and monsters can be "seen" by the player, etc).
*
* Zaiband defines all of these in terms of project.
*/
bool los(coord g1, coord g2)
{
coord grid_g[MAX(DUNGEON_HGT,DUNGEON_WID)];
int grid_n = project_path(grid_g, MAX(DUNGEON_HGT,DUNGEON_WID), g1, g2, true, &wall_stop); /* Check the projection path */
if (0==grid_n) return TRUE;
if (grid_g[grid_n-1]==g2) return TRUE;
return FALSE;
}
/*
* Returns true if the player's grid is dark
*/
bool no_lite(void)
{
return (!player_can_see_bold(p_ptr->loc.y, p_ptr->loc.x));
}
/**
* Determine if a given location may be "destroyed"
*
* Used by destruction spells, and for placing stairs, etc.
*/
bool cave_valid_bold(int y, int x)
{
object_type *o_ptr;
/* Forbid perma-grids */
if (cave_perma_bold(y, x)) return (FALSE);
/* Check objects */
for (o_ptr = get_first_object(y, x); o_ptr; o_ptr = get_next_object(o_ptr))
{
/* Forbid artifact grids */
if (o_ptr->is_artifact()) return (FALSE);
}
/* Accept */
return (TRUE);
}
/**
* Hack -- Hallucinatory monster
*/
static attr_char hallucinatory_monster(void)
{
while (1)
{
/* Select a random monster */
const monster_race* const r_ptr = &monster_type::r_info[rand_int(z_info->r_max)];
/* Skip non-entries */
if (!r_ptr->_name) continue;
return r_ptr->x;
}
}
/**
* Hack -- Hallucinatory object
*/
static attr_char hallucinatory_object(void)
{
while (1)
{
/* Select a random object */
const object_kind* const k_ptr = &object_type::k_info[rand_int(z_info->k_max - 1) + 1];
/* Skip non-entries */
if (!k_ptr->_name) continue;
/* Skip empty entries (ignoring flavors) */
if ((0 == k_ptr->x._attr) || (0 == k_ptr->x._char)) continue;
/* Encode */
return k_ptr->x;
}
}
/**
* The 16x16 tile of the terrain supports lighting
*/
bool feat_supports_lighting(int feat)
{
/* Pseudo graphics don't support lighting */
if (use_graphics == GRAPHICS_PSEUDO) return FALSE;
if ((use_graphics != GRAPHICS_DAVID_GERVAIS) &&
(feat >= FEAT_TRAP_HEAD) && (feat <= FEAT_TRAP_TAIL))
{
return TRUE;
}
switch (feat)
{
case FEAT_FLOOR:
case FEAT_INVIS:
case FEAT_SECRET:
case FEAT_MAGMA:
case FEAT_QUARTZ:
case FEAT_MAGMA_H:
case FEAT_QUARTZ_H:
case FEAT_WALL_EXTRA:
case FEAT_WALL_INNER:
case FEAT_WALL_OUTER:
case FEAT_WALL_SOLID:
case FEAT_PERM_EXTRA:
case FEAT_PERM_INNER:
case FEAT_PERM_OUTER:
case FEAT_PERM_SOLID:
return TRUE;
default:
return FALSE;
}
}
/**
* This function modifies the attr/char pair for an empty floor space
* to reflect the various lighting options available.
*
* For text, this means changing the colouring for view_yellow_lite or
* view_bright_lite, and for graphics it means modifying the char to
* use a different tile in the tileset. These modifications are different
* for different sets, depending on the tiles available, and their position
* in the set.
*/
static void special_lighting_floor(attr_char& ref, enum grid_light_level lighting, bool in_view)
{
/* The floor starts off "lit" - i.e. rendered in white or the default
* tile. */
if (lighting == LIGHT_TORCH && OPTION(view_yellow_lite))
{
/*
* OPTION(view_yellow_lite) distinguishes between torchlit and
* permanently-lit areas
*/
switch (use_graphics)
{
case GRAPHICS_NONE:
case GRAPHICS_PSEUDO:
/* Use "yellow" */
if (ref._attr == TERM_WHITE) ref._attr = TERM_YELLOW;
break;
case GRAPHICS_ADAM_BOLT:
ref._char += 2;
break;
case GRAPHICS_DAVID_GERVAIS:
ref._char -= 1;
break;
}
}
else if (lighting == LIGHT_DARK)
{
/* Use a dark tile */
switch (use_graphics)
{
case GRAPHICS_NONE:
case GRAPHICS_PSEUDO:
/* Use "dark gray" */
if (ref._attr == TERM_WHITE) ref._attr = TERM_L_DARK;
break;
case GRAPHICS_ADAM_BOLT:
case GRAPHICS_DAVID_GERVAIS:
ref._char += 1;
break;
}
}
else
{
/*
* view_bright_lite makes tiles that aren't in the "eyeline"
* of the player show up dimmer than those that are.
*/
if (OPTION(view_bright_lite) && !in_view)
{
switch (use_graphics)
{
case GRAPHICS_NONE:
case GRAPHICS_PSEUDO:
/* Use "gray" */
if (ref._attr == TERM_WHITE) ref._attr = TERM_SLATE;
break;
case GRAPHICS_ADAM_BOLT:
case GRAPHICS_DAVID_GERVAIS:
ref._char += 1;
break;
}
}
}
}
/**
* This function modifies the attr/char pair for a wall (or other "interesting"
* grids to show them as more-or-less lit. Note that how walls are drawn
* isn't directly related to how they are lit - walls are always "lit".
* The lighting effects we use are as a visual cue to emphasise blindness
* and to show field-of-view (OPTION(view_bright_lite)).
*
* For text, we change the attr and for graphics we modify the char to
* use a different tile in the tileset. These modifications are different
* for different sets, depending on the tiles available, and their position
* in the set.
*/
static void special_wall_display(attr_char& ref, bool in_view, int feat)
{
/* Grids currently in view are left alone, rendered as "white" */
if (in_view) return;
/* When blind, we make walls and other "white" things dark */
if (p_ptr->timed[TMD_BLIND])
{
switch (use_graphics)
{
case GRAPHICS_NONE:
case GRAPHICS_PSEUDO:
/* Use "dark gray" */
if (ref._attr == TERM_WHITE) ref._attr = TERM_L_DARK;
break;
case GRAPHICS_ADAM_BOLT:
case GRAPHICS_DAVID_GERVAIS:
if (feat_supports_lighting(feat)) ref._char += 1;
break;
}
}
/* Handle "OPTION(view_bright_lite)" by dimming walls not "in view" */
else if (OPTION(view_bright_lite))
{
switch (use_graphics)
{
case GRAPHICS_NONE:
case GRAPHICS_PSEUDO:
/* Use "gray" */
if (ref._attr == TERM_WHITE) ref._attr = TERM_SLATE;
break;
case GRAPHICS_ADAM_BOLT:
case GRAPHICS_DAVID_GERVAIS:
if (feat_supports_lighting(feat)) ref._char += 1;
break;
}
}
else
{
/* Use a brightly lit tile */
switch (use_graphics)
{
case GRAPHICS_ADAM_BOLT:
if (feat_supports_lighting(feat)) ref._char += 2;
break;
case GRAPHICS_DAVID_GERVAIS:
if (feat_supports_lighting(feat)) ref._char -= 1;
break;
}
}
}
/**
* This function takes a pointer to a grid info struct describing the
* contents of a grid location (as obtained through the grid_data constructor)
* and fills in the character and attr pairs for display.
*
* ap and cp are filled with the attr/char pair for the monster, object or
* floor tile that is at the "top" of the grid (monsters covering objects,
* which cover floor, assuming all are present).
*
* tap and tcp are filled with the attr/char pair for the floor, regardless
* of what is on it. This can be used by graphical displays with
* transparency to place an object onto a floor tile, is desired.
*
* Any lighting effects are also applied to these pairs, clear monsters allow
* the underlying colour or feature to show through (ATTR_CLEAR and
* CHAR_CLEAR), multi-hued colour-changing (ATTR_MULTI) is applied, and so on.
* Technically, the flag "CHAR_MULTI" is supposed to indicate that a monster
* looks strange when examined, but this flag is currently ignored.
*
* NOTES:
* This is called pretty frequently, whenever a grid on the map display
* needs updating, so don't overcomplicate it.
*
* The "zero" entry in the feature/object/monster arrays are
* used to provide "special" attr/char codes, with "monster zero" being
* used for the player attr/char, "object zero" being used for the "pile"
* attr/char, and "feature zero" being used for the "darkness" attr/char.
*
* TODO:
* The transformations for tile colors, or brightness for the 16x16
* tiles should be handled differently. One possibility would be to
* extend feature_type with attr/char definitions for the different states.
* This will probably be done outside of the current text->graphics mappings
* though.
*/
void
grid_data::as_text(byte& ap, char& cp, byte& tap, char& tcp) const
{
const feature_type* const f_ptr = &feature_type::f_info[f_idx];
/* Normal attr and char */
attr_char ref = f_ptr->x;
/* Special lighting effects */
if (f_idx <= FEAT_INVIS && OPTION(view_special_lite))
special_lighting_floor(ref, lighting, in_view);
/* Special lighting effects (walls only) */
if (f_idx > FEAT_INVIS && OPTION(view_granite_lite))
special_wall_display(ref, in_view, f_idx);
/* Save the terrain info for the transparency effects */
tap = ref._attr;
tcp = ref._char;
/* If there's an object, deal with that. */
if (first_k_idx)
{
if (hallucinate)
{ /* Just pick a random object to display. */
ref = hallucinatory_object();
}
else
{
/* Get the "pile" feature instead, if more than one and supposed to show it */
object_kind *k_ptr = &object_type::k_info[(OPTION(show_piles) && multiple_objects) ? 0
: first_k_idx];
/* Normal attr and char */
ref = k_ptr->user();
}
}
/* If there's a monster */
if (m_idx > 0)
{
if (hallucinate)
{ /* Just pick a random monster to display. */
ref = hallucinatory_monster();
}
else
{
const monster_race* const r_ptr = m_ptr_from_m_idx(m_idx)->race();
/* Desired attr & char*/
attr_char d = r_ptr->x;
/* Special attr/char codes */
if ((d._attr & 0x80) && (d._char & 0x80))
{
ref = d; /* Use attr, char */
}
/* Multi-hued monster */
else if (r_ptr->flags[0] & RF0_ATTR_MULTI)
{
/* Multi-hued attr */
ref._attr = randint(15);
/* Normal char */
ref._char = d._char;
}
/* Normal monster (not "clear" in any way) */
else if (!(r_ptr->flags[0] & (RF0_ATTR_CLEAR | RF0_CHAR_CLEAR)))
{
/* Use attr */
ref._attr = d._attr;
/* Desired attr & char */
d = r_ptr->x;
/* Use char */
ref._char = d._char;
}
/* Hack -- Bizarre grid under monster */
else if ((ref._attr & 0x80) || (ref._char & 0x80))
{
ref = d; /* use attr, char */
}
/* Normal char, Clear attr, monster */
else if (!(r_ptr->flags[0] & RF0_CHAR_CLEAR))
{
/* Normal char */
ref._char = d._char;
}
/* Normal attr, Clear char, monster */
else if (!(r_ptr->flags[0] & RF0_ATTR_CLEAR))
{
/* Normal attr */
ref._attr = d._attr;
}
}
}
/* Handle "player" */
#ifdef MAP_INFO_MULTIPLE_PLAYERS
/* Players */
else if (is_player)
#else /* MAP_INFO_MULTIPLE_PLAYERS */
/* Handle "player" */
else if (is_player && !(p_ptr->running && OPTION(hidden_player)))
#endif /* MAP_INFO_MULTIPLE_PLAYERS */
{
monster_race *r_ptr = &monster_type::r_info[0];
/* Get the "player" attr */
ref._attr = r_ptr->x._attr;
#if 0
if ((hp_changes_color) && (arg_graphics == GRAPHICS_NONE))
{
switch(p_ptr->chp * 10 / p_ptr->mhp)
{
case 10:
case 9:
{
a = TERM_WHITE;
break;
}
case 8:
case 7:
{
a = TERM_YELLOW;
break;
}
case 6:
case 5:
{
a = TERM_ORANGE;
break;
}
case 4:
case 3:
{
a = TERM_L_RED;
break;
}
case 2:
case 1:
case 0:
{
a = TERM_RED;
break;
}
default:
{
a = TERM_WHITE;
break;
}
}
}
#endif
/* Get the "player" char */
ref._char = r_ptr->x._char;
}
/* Result */
ap = ref._attr;
cp = ref._char;
}
/**
* This constructor takes a grid location (x, y) and extracts information the
* player is allowed to know about it, initializing itself with it.
*
* The information filled in is as follows:
* - f_idx is filled in with the terrain's feature type, or FEAT_NONE
* if the player doesn't know anything about the grid. The function
* makes use of the "mimic" field in terrain in order to allow one
* feature to look like another (hiding secret doors, invisible traps,
* etc). This will return the terrain type the player "Knows" about,
* not necessarily the real terrain.
* - m_idx is set to the monster index, or 0 if there is none (or the
* player doesn't know it).
* - first_k_idx is set to the index of the first object in a grid
* that the player knows (and cares, as per hide_squelchable) about,
* or zero for no object in the grid.
* - multiple_objects is TRUE if there is more than one object in the
* grid that the player knows and cares about (to facilitate any special
* floor stack symbol that might be used).
* - in_view is TRUE if the player can currently see the grid - this can
* be used to indicate field-of-view, such as through OPTION(view_bright_lite).
* - lighting is set to indicate the lighting level for the grid:
* LIGHT_DARK for unlit grids, LIGHT_TORCH for those lit by the player's
* light source, and LIGHT_GLOW for inherently light grids (lit rooms, etc).
* Note that lighting is always LIGHT_GLOW for known "interesting" grids
* like walls.
* - is_player is TRUE if the player is on the given grid.
* - hallucinate is TRUE if the player is hallucinating something "strange"
* for this grid - this should pick a random monster to show if the m_idx
* is non-zero, and a random object if first_k_idx is non-zero.
*
* NOTES:
* This is called pretty frequently, whenever a grid on the map display
* needs updating, so don't overcomplicate it.
*
* Terrain is remembered separately from objects and monsters, so can be
* shown even when the player can't "see" it. This leads to things like
* doors out of the player's view still change from closed to open and so on.
*
* TODO:
* Hallucination is currently disabled (it was a display-level hack before,
* and we need it to be a knowledge-level hack). The idea is that objects
* may turn into different objects, monsters into different monsters, and
* terrain may be objects, monsters, or stay the same.
*/
grid_data::grid_data(unsigned int y, unsigned int x)
: first_k_idx(0), /* Default */
multiple_objects(false), /* Default */
lighting(LIGHT_GLOW), /* Default */
hallucinate(p_ptr->timed[TMD_IMAGE]) /* know this now */
{
assert(x < DUNGEON_WID);
assert(y < DUNGEON_HGT);
const object_type* o_ptr;
byte info = cave_info[y][x];
/* Set things we can work out right now */
f_idx = cave_feat[y][x];
in_view = (info & CAVE_SEEN);
is_player = (cave_m_idx[y][x] < 0);
m_idx = (is_player) ? 0 : cave_m_idx[y][x];
/* If the grid is memorised or can currently be seen */
if (info & (CAVE_MARK | CAVE_SEEN))
{
/* Apply "mimic" field */
f_idx = feature_type::f_info[f_idx].mimic;
/* Boring grids (floors, etc) */
if (f_idx <= FEAT_INVIS)
{
/* Get the floor feature */
f_idx = FEAT_FLOOR;
/* Handle currently visible grids */
if (info & CAVE_SEEN)
{
/* Only lit by "torch" lite */
if (info & CAVE_GLOW)
lighting = LIGHT_GLOW;
else
lighting = LIGHT_TORCH;
}
/* Handle "dark" grids and "blindness" */
else if (p_ptr->timed[TMD_BLIND] || !(info & CAVE_GLOW))
lighting = LIGHT_DARK;
}
}
/* Unknown */
else
{
f_idx = FEAT_NONE;
}
/* Objects */
for (o_ptr = get_first_object(y, x); o_ptr; o_ptr = get_next_object(o_ptr))
{
/* Memorized objects */
if (o_ptr->marked /* && !squelch_hide_item(o_ptr) */)
{
/* First item found */
if (first_k_idx == 0)
{
first_k_idx = o_ptr->k_idx;
}
else
{
multiple_objects = TRUE;
/* And we know all we need to know. */
break;
}
}
}
/* Monsters */
if (0 < m_idx)
{
/* If the monster isn't "visible", make sure we don't list it.*/
if (!m_ptr_from_m_idx(m_idx)->ml) m_idx = 0;
}
/* Rare random hallucination on non-outer walls */
if (hallucinate && 0 == m_idx && 0 == first_k_idx)
{
if ((f_idx < FEAT_PERM_SOLID) && one_in_(256))
{
/* Normally, make an imaginary monster */
if (!one_in_(4))
{
m_idx = 1;
}
/* Otherwise, an imaginary object */
else
{
first_k_idx = 1;
}
}
else
{
hallucinate = FALSE;
}
}
/* All other g fields are 'flags', mostly booleans. */
assert(m_idx < (u32b) mon_max);
assert(first_k_idx < z_info->k_max);
}
/**
* Move the cursor to a given map location.
*/
static void move_cursor_relative_map(coord g)
{
term *old;
int j;
coord k;
/* Scan windows */
for (j = 0; j < ANGBAND_TERM_MAX; j++)
{
term *t = angband_term[j];
/* No window */
if (!t) continue;
/* No relevant flags */
if (!(op_ptr->window_flag[j] & (PW_MAP))) continue;
/* Verify location */
if (g.y<t->offset_y || g.x<t->offset_x) continue;
/* Location relative to panel */
k.y = g.y - t->offset_y;
/* Verify location */
if (k.y >= t->hgt) continue;
/* Location relative to panel */
k.x = g.x - t->offset_x;
if (use_bigtile) k.x += k.x;
/* Verify location */
if (k.x >= t->wid) continue;
/* Go there */
old = Term;
Term_activate(t);
(void)Term_gotoxy(k.x, k.y);
Term_activate(old);
}
}
/**
* Move the cursor to a given map location.
*
* The main screen will always be at least 24x80 in size.
*/
void move_cursor_relative(coord g)
{
coord k,v;
/* Move the cursor on map sub-windows */
move_cursor_relative_map(g);
/* Verify location */
if (g.y<Term->offset_y || g.x<Term->offset_x) return;
/* Location relative to panel */
k.y = g.y - Term->offset_y;
/* Verify location */
if (k.y >= SCREEN_HGT) return;
/* Location relative to panel */
k.x = g.x - Term->offset_x;
/* Verify location */
if (k.x >= SCREEN_WID) return;
/* Location in window */
v = k + coord(COL_MAP,ROW_MAP);
if (use_bigtile) v.x += k.x;
/* Go there */
(void)Term_gotoxy(v.x, v.y);
}
/**
* Display an attr/char pair at the given map location
*
* Note the inline use of "panel_contains()" for efficiency.
*
* Note the use of "Term_queue_char()" for efficiency.
*/
static void print_rel_map(attr_char n, coord g)
{
coord k;
int j;
/* Scan windows */
for (j = 0; j < ANGBAND_TERM_MAX; j++)
{
term *t = angband_term[j];
/* No window */
if (!t) continue;
/* No relevant flags */
if (!(op_ptr->window_flag[j] & (PW_MAP))) continue;
/* Verify location */
if (g.y<t->offset_y || g.x<t->offset_x) continue;
/* Location relative to panel */
k.y = g.y - t->offset_y;
/* Verify location */
if (k.y >= t->hgt) continue;
/* Location relative to panel */
k.x = g.x - t->offset_x;
if (use_bigtile)
{
k.x += k.x;
if (k.x + 1 >= t->wid) continue;
}
/* Verify location */
if (k.x >= t->wid) continue;
/* Hack -- Queue it */
Term_queue_char(t, k.x, k.y, n._attr, n._char, 0, 0);
if (use_bigtile)
{
/* Mega-Hack : Queue dummy char */
if (n._attr & 0x80)
Term_queue_char(t, k.x+1, k.y, 255, -1, 0, 0);
else
Term_queue_char(t, k.x+1, k.y, TERM_WHITE, ' ', 0, 0);
}
/* Redraw map */
p_ptr->redraw |= (PR_MAP);
}
}
/**
* Display an attr/char pair at the given map location
*
* Note the inline use of "panel_contains()" for efficiency.
*
* Note the use of "Term_queue_char()" for efficiency.
*
* The main screen will always be at least 24x80 in size.
*/
void print_rel(attr_char n, coord g)
{
coord k,v;
/* Print on map sub-windows */
print_rel_map(n, g);
/* Verify location */
if (g.y<Term->offset_y || g.x<Term->offset_x) return;
/* Location relative to panel */
k.y = g.y - Term->offset_y;
/* Verify location */
if (k.y >= SCREEN_HGT) return;
/* Location relative to panel */
k.x = g.x - Term->offset_x;
/* Verify location */
if (k.x >= SCREEN_WID) return;
/* Location in window */
v = k + coord(COL_MAP,ROW_MAP);
if (use_bigtile) v.x += k.x;
/* Hack -- Queue it */
Term_queue_char(Term, v.x, v.y, n._attr, n._char, 0, 0);
if (use_bigtile)
{
/* Mega-Hack : Queue dummy char */
if (n._attr & 0x80)
Term_queue_char(Term, v.x+1, v.y, 255, -1, 0, 0);
else
Term_queue_char(Term, v.x+1, v.y, TERM_WHITE, ' ', 0, 0);
}
}
/**
* Memorize interesting viewable object/features in the given grid
*
* This function should only be called on "legal" grids.
*
* This function will memorize the object and/or feature in the given grid,
* if they are (1) see-able and (2) interesting. Note that all objects are
* interesting, all terrain features except floors (and invisible traps) are
* interesting, and floors (and invisible traps) are interesting sometimes
* (depending on various options involving the illumination of floor grids).
*
* The automatic memorization of all objects and non-floor terrain features
* as soon as they are displayed allows incredible amounts of optimization
* in various places, especially "map_info()" and this function itself.
*
* Note that the memorization of objects is completely separate from the
* memorization of terrain features, preventing annoying floor memorization
* when a detected object is picked up from a dark floor, and object
* memorization when an object is dropped into a floor grid which is
* memorized but out-of-sight.
*
* This function should be called every time the "memorization" of a grid
* (or the object in a grid) is called into question, such as when an object
* is created in a grid, when a terrain feature "changes" from "floor" to
* "non-floor", and when any grid becomes "see-able" for any reason.
*
* This function is called primarily from the "update_view()" function, for
* each grid which becomes newly "see-able".
*/
void note_spot(coord g)
{
byte info = cave_info[g.y][g.x]; /* Get cave info */
object_type *o_ptr;
/* Require "seen" flag */
if (!(info & (CAVE_SEEN))) return;
/* Hack -- memorize objects */
for (o_ptr = get_first_object(g.y, g.x); o_ptr; o_ptr = get_next_object(o_ptr))
{
/* Memorize objects */
o_ptr->marked = TRUE;
}
/* Hack -- memorize grids */
if (!(info & (CAVE_MARK)))
{
/* Memorize some "boring" grids */
if (cave_feat[g.y][g.x] <= FEAT_INVIS)
{
/* Option -- memorize certain floors */
if (((info & (CAVE_GLOW)) && OPTION(view_perma_grids)) ||
OPTION(view_torch_grids))
{
/* Memorize */
cave_info[g.y][g.x] |= (CAVE_MARK);
}
}
/* Memorize all "interesting" grids */
else
{
/* Memorize */
cave_info[g.y][g.x] |= (CAVE_MARK);
}
}
}
static void lite_spot_map(coord g)
{
byte a, ta;
char c, tc;
int ky, kx;
int j;
/* Scan windows */
for (j = 0; j < ANGBAND_TERM_MAX; j++)
{
term *t = angband_term[j];
/* No window */
if (!t) continue;
/* No relevant flags */
if (!(op_ptr->window_flag[j] & (PW_MAP))) continue;
/* Verify location */
if (g.y<t->offset_y || g.x<t->offset_x) continue;
/* Location relative to panel */
ky = g.y - t->offset_y;
kx = g.x - t->offset_x;
if (use_bigtile)
{
kx += kx;
if (kx + 1 >= t->wid) continue;
}
/* Verify location */
if (ky >= t->hgt) continue;
if (kx >= t->wid) continue;
/* Hack -- redraw the grid */
grid_data(g.y, g.x).as_text(a, c, ta, tc);
/* Hack -- Queue it */
Term_queue_char(t, kx, ky, a, c, ta, tc);
if (use_bigtile)
{
kx++;
/* Mega-Hack : Queue dummy char */
if (a & 0x80)
Term_queue_char(t, kx, ky, 255, -1, 0, 0);
else
Term_queue_char(t, kx, ky, TERM_WHITE, ' ', TERM_WHITE, ' ');
}
/* Redraw map */
p_ptr->redraw |= (PR_MAP);
}
}
/**
* Redraw (on the screen) a given map location
*
* This function should only be called on "legal" grids.
*
* Note the inline use of "print_rel()" for efficiency.
*
* The main screen will always be at least 24x80 in size.
*/
void lite_spot(coord g)
{
byte a;
char c;
byte ta;
char tc;
coord k,v;
/* Update map sub-windows */
lite_spot_map(g);
/* Verify location */
if (g.y<Term->offset_y || g.x<Term->offset_x) return;
/* Location relative to panel */
k.y = g.y - Term->offset_y;
/* Verify location */
if (k.y >= SCREEN_HGT) return;
/* Location relative to panel */
k.x = g.x - Term->offset_x;
/* Verify location */
if (k.x >= SCREEN_WID) return;
/* Location in window */
v = k + coord(COL_MAP,ROW_MAP);
if (use_bigtile) v.x += k.x;
/* Hack -- redraw the grid */
grid_data(g.y, g.x).as_text(a, c, ta, tc);
/* Hack -- Queue it */
Term_queue_char(Term, v.x, v.y, a, c, ta, tc);
if (use_bigtile)
{
v.x++;
/* Mega-Hack : Queue dummy char */
if (a & 0x80)
Term_queue_char(Term, v.x, v.y, 255, -1, 0, 0);
else
Term_queue_char(Term, v.x, v.y, TERM_WHITE, ' ', TERM_WHITE, ' ');
}
}
static void prt_map_aux(void)
{
byte a;
char c;
byte ta;
char tc;
int y, x;
int vy, vx;
int ty, tx;
int j;
/* Scan windows */
for (j = 0; j < ANGBAND_TERM_MAX; j++)
{
term *t = angband_term[j];
/* No window */
if (!t) continue;
/* No relevant flags */
if (!(op_ptr->window_flag[j] & (PW_MAP))) continue;
/* Assume screen */
ty = t->offset_y + t->hgt;
tx = t->offset_x + t->wid;
if (use_bigtile) tx = t->offset_x + (t->wid / 2);
/* Dump the map */
for (y = t->offset_y, vy = 0; y < ty; vy++, y++)
{
for (x = t->offset_x, vx = 0; x < tx; vx++, x++)
{
/* Check bounds */
if (!in_bounds(y, x)) continue;
if (use_bigtile && (vx + 1 >= t->wid)) continue;
/* Determine what is there */
grid_data(y, x).as_text(a, c, ta, tc);
/* Hack -- Queue it */
Term_queue_char(t, vx, vy, a, c, ta, tc);
if (use_bigtile)
{
vx++;
/* Mega-Hack : Queue dummy char */
if (a & 0x80)
Term_queue_char(t, vx, vy, 255, -1, 0, 0);
else
Term_queue_char(t, vx, vy, TERM_WHITE, ' ', TERM_WHITE, ' ');
}
}
}
/* Redraw map */
p_ptr->redraw |= (PR_MAP);
}
}
/**
* Redraw (on the screen) the current map panel
*
* Note the inline use of "lite_spot()" for efficiency.
*
* The main screen will always be at least 24x80 in size.
*/
void prt_map(void)
{
byte a;
char c;
byte ta;
char tc;
int y, x;
int vy, vx;
int ty, tx;
/* Redraw map sub-windows */
prt_map_aux();
/* Assume screen */
ty = Term->offset_y + SCREEN_HGT;
tx = Term->offset_x + SCREEN_WID;
/* Dump the map */
for (y = Term->offset_y, vy = ROW_MAP; y < ty; vy++, y++)
{
for (x = Term->offset_x, vx = COL_MAP; x < tx; vx++, x++)
{
/* Check bounds */
if (!in_bounds(y, x)) continue;
/* Determine what is there */
grid_data(y, x).as_text(a, c, ta, tc);
/* Hack -- Queue it */
Term_queue_char(Term, vx, vy, a, c, ta, tc);
if (use_bigtile)
{
vx++;
/* Mega-Hack : Queue dummy char */
if (a & 0x80)
Term_queue_char(Term, vx, vy, 255, -1, 0, 0);
else
Term_queue_char(Term, vx, vy, TERM_WHITE, ' ', TERM_WHITE, ' ');
}
}
}
}
/**
* Hack -- priority array (see below)
*
* Note that all "walls" always look like "secret doors" (see "map_info()").
*/
static const int priority_table[14][2] =
{
/* Dark */
{ FEAT_NONE, 2 },
/* Floors */
{ FEAT_FLOOR, 5 },
/* Walls */
{ FEAT_SECRET, 10 },
/* Quartz */
{ FEAT_QUARTZ, 11 },
/* Magma */
{ FEAT_MAGMA, 12 },
/* Rubble */
{ FEAT_RUBBLE, 13 },
/* Open doors */
{ FEAT_OPEN, 15 },
{ FEAT_BROKEN, 15 },
/* Closed doors */
{ FEAT_DOOR_HEAD + 0x00, 17 },
/* Hidden gold */
{ FEAT_QUARTZ_K, 19 },
{ FEAT_MAGMA_K, 19 },
/* Stairs */
{ FEAT_LESS, 25 },
{ FEAT_MORE, 25 },
/* End */
{ 0, 0 }
};
/**
* Hack -- a priority function (see below)
*/
static byte priority(byte a, char c)
{
int i, p0, p1;
feature_type *f_ptr;
/* Scan the table */
for (i = 0; TRUE; i++)
{
/* Priority level */
p1 = priority_table[i][1];
/* End of table */
if (!p1) break;
/* Feature index */
p0 = priority_table[i][0];
/* Get the feature */
f_ptr = &feature_type::f_info[p0];
/* Check character and attribute, accept matches */
if ((f_ptr->x._char == c) && (f_ptr->x._attr == a)) return (p1);
}
/* Default */
return (20);
}
/**
* Display a "small-scale" map of the dungeon in the active Term.
*
* Note that this function must "disable" the special lighting effects so
* that the "priority" function will work.
*
* Note the use of a specialized "priority" function to allow this function
* to work with any graphic attr/char mappings, and the attempts to optimize
* this function where possible.
*
* If "cy" and "cx" are not NULL, then returns the screen location at which
* the player was displayed, so the cursor can be moved to that location,
* and restricts the horizontal map size to SCREEN_WID. Otherwise, nothing
* is returned (obviously), and no restrictions are enforced.
*/
void display_map(int *cy, int *cx)
{
int py = p_ptr->loc.y;
int px = p_ptr->loc.x;
/* Desired map height */
int map_hgt = Term->hgt - 2;
int map_wid = Term->wid - 2;
int dungeon_hgt = (p_ptr->depth == 0) ? TOWN_HGT : DUNGEON_HGT;
int dungeon_wid = (p_ptr->depth == 0) ? TOWN_WID : DUNGEON_WID;
int row, col;
int x, y;
byte ta;
char tc;
byte tp;
/* Large array on the stack */
byte mp[DUNGEON_HGT][DUNGEON_WID];
/* Save lighting effects */
bool old_view_special_lite = OPTION(view_special_lite);
bool old_view_granite_lite = OPTION(view_granite_lite);
monster_race *r_ptr = &monster_type::r_info[0];
/* Prevent accidents */
if (map_hgt > dungeon_hgt) map_hgt = dungeon_hgt;
if (map_wid > dungeon_wid) map_wid = dungeon_wid;
/* Prevent accidents */
if ((map_wid < 1) || (map_hgt < 1)) return;
/* Disable lighting effects */
OPTION(view_special_lite) = FALSE;
OPTION(view_granite_lite) = FALSE;
/* Nothing here */
ta = TERM_WHITE;
tc = ' ';
/* Clear the priorities */
for (y = 0; y < map_hgt; ++y)
{
for (x = 0; x < map_wid; ++x)
{
/* No priority */
mp[y][x] = 0;
}
}
/* Clear the screen (but don't force a redraw) */
clear_from(0);
/* Corners */
x = map_wid + 1;
y = map_hgt + 1;
/* Draw the corners */
Term_putch(0, 0, ta, '+');
Term_putch(x, 0, ta, '+');
Term_putch(0, y, ta, '+');
Term_putch(x, y, ta, '+');
/* Draw the horizontal edges */
for (x = 1; x <= map_wid; x++)
{
Term_putch(x, 0, ta, '-');
Term_putch(x, y, ta, '-');
}
/* Draw the vertical edges */
for (y = 1; y <= map_hgt; y++)
{
Term_putch(0, y, ta, '|');
Term_putch(x, y, ta, '|');
}
/* Analyze the actual map */
for (y = 0; y < dungeon_hgt; y++)
{
for (x = 0; x < dungeon_wid; x++)
{
row = (y * map_hgt / dungeon_hgt);
col = (x * map_wid / dungeon_wid);
if (use_bigtile)
col = col & ~1;
/* Get the attr/char at that map location */
grid_data(y, x).as_text(ta, tc, ta, tc);
/* Get the priority of that attr/char */
tp = priority(ta, tc);
/* Save "best" */
if (mp[row][col] < tp)
{
/* Add the character */
Term_putch(col + 1, row + 1, ta, tc);
if (use_bigtile)
{
if (ta & 0x80)
Term_putch(col + 2, row + 1, 255, -1);
else
Term_putch(col + 2, row + 1, TERM_WHITE, ' ');
}
/* Save priority */
mp[row][col] = tp;
}
}
}
/* Player location */
row = (py * map_hgt / dungeon_hgt);
col = (px * map_wid / dungeon_wid);
if (use_bigtile) col = col & ~1;
/*** Make sure the player is visible ***/
/* Get the "player" */
attr_char t = r_ptr->x;
/* Draw the player */
Term_putch(col + 1, row + 1, t._attr, t._char);
/* Return player location */
if (cy != NULL) (*cy) = row + 1;
if (cx != NULL) (*cx) = col + 1;
/* Restore lighting effects */
OPTION(view_special_lite) = old_view_special_lite;
OPTION(view_granite_lite) = old_view_granite_lite;
}
/**
* Display a "small-scale" map of the dungeon.
*
* Note that the "player" is always displayed on the map.
*/
void do_cmd_view_map(void)
{
int cy, cx;
const char* prompt = "Hit any key to continue";
/* Save screen */
screen_save();
/* Note */
prt("Please wait...", 0, 0);
/* Flush */
Term_fresh();
/* Clear the screen */
Term_clear();
/* Display the map */
display_map(&cy, &cx);
/* Show the prompt */
put_str(prompt, Term->hgt - 1, Term->wid / 2 - strlen(prompt) / 2);
/* Hilite the player */
Term_gotoxy(cx, cy);
/* Get any key */
(void)inkey();
/* Load screen */
screen_load();
}
/*
* Some comments on the dungeon related data structures and functions...
*
* Angband is primarily a dungeon exploration game, and it should come as
* no surprise that the internal representation of the dungeon has evolved
* over time in much the same way as the game itself, to provide semantic
* changes to the game itself, to make the code simpler to understand, and
* to make the executable itself faster or more efficient in various ways.
*
* There are a variety of dungeon related data structures, and associated
* functions, which store information about the dungeon, and provide methods
* by which this information can be accessed or modified.
*
* Some of this information applies to the dungeon as a whole, such as the
* list of unique monsters which are still alive. Some of this information
* only applies to the current dungeon level, such as the current depth, or
* the list of monsters currently inhabiting the level. And some of the
* information only applies to a single grid of the current dungeon level,
* such as whether the grid is illuminated, or whether the grid contains a
* monster, or whether the grid can be seen by the player. If Angband was
* to be turned into a multi-player game, some of the information currently
* associated with the dungeon should really be associated with the player,
* such as whether a given grid is viewable by a given player.
*
* One of the major bottlenecks in ancient versions of Angband was in the
* calculation of "line of sight" from the player to various grids, such
* as those containing monsters, using the relatively expensive "los()"
* function. This was such a nasty bottleneck that a lot of silly things
* were done to reduce the dependancy on "line of sight", for example, you
* could not "see" any grids in a lit room until you actually entered the
* room, at which point every grid in the room became "illuminated" and
* all of the grids in the room were "memorized" forever. Other major
* bottlenecks involved the determination of whether a grid was lit by the
* player's torch, and whether a grid blocked the player's line of sight.
* These bottlenecks led to the development of special new functions to
* optimize issues involved with "line of sight" and "torch lit grids".
* These optimizations led to entirely new additions to the game, such as
* the ability to display the player's entire field of view using different
* colors than were used for the "memorized" portions of the dungeon, and
* the ability to memorize dark floor grids, but to indicate by the way in
* which they are displayed that they are not actually illuminated. And
* of course many of them simply made the game itself faster or more fun.
* Also, over time, the definition of "line of sight" has been relaxed to
* allow the player to see a wider "field of view", which is slightly more
* realistic, and only slightly more expensive to maintain.
*
* Currently, a lot of the information about the dungeon is stored in ways
* that make it very efficient to access or modify the information, while
* still attempting to be relatively conservative about memory usage, even
* if this means that some information is stored in multiple places, or in
* ways which require the use of special code idioms. For example, each
* monster record in the monster array contains the location of the monster,
* and each cave grid has an index into the monster array, or a zero if no
* monster is in the grid. This allows the monster code to efficiently see
* where the monster is located, while allowing the dungeon code to quickly
* determine not only if a monster is present in a given grid, but also to
* find out which monster. The extra space used to store the information
* twice is inconsequential compared to the speed increase.
*
* Some of the information about the dungeon is used by functions which can
* constitute the "critical efficiency path" of the game itself, and so the
* way in which they are stored and accessed has been optimized in order to
* optimize the game itself. For example, the "update_view()" function was
* originally created to speed up the game itself (when the player was not
* running), but then it took on extra responsibility as the provider of the
* new "special effects lighting code", and became one of the most important
* bottlenecks when the player was running. So many rounds of optimization
* were performed on both the function itself, and the data structures which
* it uses, resulting eventually in a function which not only made the game
* faster than before, but which was responsible for even more calculations
* (including the determination of which grids are "viewable" by the player,
* which grids are illuminated by the player's torch, and which grids can be
* "seen" in some way by the player), as well as for providing the guts of
* the special effects lighting code, and for the efficient redisplay of any
* grids whose visual representation may have changed.
*
* Several pieces of information about each cave grid are stored in various
* two dimensional arrays, with one unit of information for each grid in the
* dungeon. Some of these arrays have been intentionally expanded by a small
* factor to make the two dimensional array accesses faster by allowing the
* use of shifting instead of multiplication.
*
* Several pieces of information about each cave grid are stored in the
* "cave_info" array, which is a special two dimensional array of bytes,
* one for each cave grid, each containing eight separate "flags" which
* describe some property of the cave grid. These flags can be checked and
* modified extremely quickly, especially when special idioms are used to
* force the compiler to keep a local register pointing to the base of the
* array. Special location offset macros can be used to minimize the number
* of computations which must be performed at runtime. Note that using a
* byte for each flag set may be slightly more efficient than using a larger
* unit, so if another flag (or two) is needed later, and it must be fast,
* then the two existing flags which do not have to be fast should be moved
* out into some other data structure and the new flags should take their
* place. This may require a few minor changes in the savefile code.
*
* The "CAVE_ROOM" flag is saved in the savefile and is used to determine
* which grids are part of "rooms", and thus which grids are affected by
* "illumination" spells. This flag does not have to be very fast.
*
* The "CAVE_ICKY" flag is saved in the savefile and is used to determine
* which grids are part of "vaults", and thus which grids cannot serve as
* the destinations of player teleportation. This flag does not have to
* be very fast.
*
* The "CAVE_MARK" flag is saved in the savefile and is used to determine
* which grids have been "memorized" by the player. This flag is used by
* the "map_info()" function to determine if a grid should be displayed.
* This flag is used in a few other places to determine if the player can
* "know" about a given grid. This flag must be very fast.
*
* The "CAVE_GLOW" flag is saved in the savefile and is used to determine
* which grids are "permanently illuminated". This flag is used by the
* "update_view()" function to help determine which viewable flags may
* be "seen" by the player. This flag is used by the "map_info" function
* to determine if a grid is only lit by the player's torch. This flag
* has special semantics for wall grids (see "update_view()"). This flag
* must be very fast.
*
* The "CAVE_WALL" flag is used to determine which grids block the player's
* line of sight. This flag is used by the "update_view()" function to
* determine which grids block line of sight, and to help determine which
* grids can be "seen" by the player. This flag must be very fast.
*
* The "CAVE_VIEW" flag is used to determine which grids are currently in
* line of sight of the player. This flag is set by (and used by) the
* "update_view()" function. This flag is used by any code which needs to
* know if the player can "view" a given grid. This flag is used by the
* "map_info()" function for some optional special lighting effects. The
* "player_has_los_bold()" macro wraps an abstraction around this flag, but
* certain code idioms are much more efficient. This flag is used to check
* if a modification to a terrain feature might affect the player's field of
* view. This flag is used to see if certain monsters are "visible" to the
* player. This flag is used to allow any monster in the player's field of
* view to "sense" the presence of the player. This flag must be very fast.
*
* The "CAVE_SEEN" flag is used to determine which grids are currently in
* line of sight of the player and also illuminated in some way. This flag
* is set by the "update_view()" function, using computations based on the
* "CAVE_VIEW" and "CAVE_WALL" and "CAVE_GLOW" flags of various grids. This
* flag is used by any code which needs to know if the player can "see" a
* given grid. This flag is used by the "map_info()" function both to see
* if a given "boring" grid can be seen by the player, and for some optional
* special lighting effects. The "player_can_see_bold()" macro wraps an
* abstraction around this flag, but certain code idioms are much more
* efficient. This flag is used to see if certain monsters are "visible" to
* the player. This flag is never set for a grid unless "CAVE_VIEW" is also
* set for the grid. Whenever the "CAVE_WALL" or "CAVE_GLOW" flag changes
* for a grid which has the "CAVE_VIEW" flag set, the "CAVE_SEEN" flag must
* be recalculated. The simplest way to do this is to call "forget_view()"
* and "update_view()" whenever the "CAVE_WALL" or "CAVE_GLOW" flags change
* for a grid which has "CAVE_VIEW" set. This flag must be very fast.
*
* The "CAVE_TEMP" flag is used for a variety of temporary purposes. This
* flag is used to determine if the "CAVE_SEEN" flag for a grid has changed
* during the "update_view()" function. This flag is used to "spread" light
* or darkness through a room. This flag is used by the "monster flow code".
* This flag must always be cleared by any code which sets it, often, this
* can be optimized by the use of the special "temp_g", "temp_y", "temp_x"
* arrays (and the special "temp_n" global). This flag must be very fast.
*
* Note that the "CAVE_MARK" flag is used for many reasons, some of which
* are strictly for optimization purposes. The "CAVE_MARK" flag means that
* even if the player cannot "see" the grid, he "knows" about the terrain in
* that grid. This is used to "memorize" grids when they are first "seen" by
* the player, and to allow certain grids to be "detected" by certain magic.
* Note that most grids are always memorized when they are first "seen", but
* "boring" grids (floor grids) are only memorized if the "OPTION(view_torch_grids)"
* option is set, or if the "OPTION(view_perma_grids)" option is set, and the grid
* in question has the "CAVE_GLOW" flag set.
*
* Objects are "memorized" in a different way, using a special "marked" flag
* on the object itself, which is set when an object is observed or detected.
* This allows objects to be "memorized" independant of the terrain features.
*
* The "update_view()" function is an extremely important function. It is
* called only when the player moves, significant terrain changes, or the
* player's blindness or torch radius changes. Note that when the player
* is resting, or performing any repeated actions (like digging, disarming,
* farming, etc), there is no need to call the "update_view()" function, so
* even if it was not very efficient, this would really only matter when the
* player was "running" through the dungeon. It sets the "CAVE_VIEW" flag
* on every cave grid in the player's field of view. It also checks the torch
* radius of the player, and sets the "CAVE_SEEN" flag for every grid which
* is in the "field of view" of the player and which is also "illuminated",
* either by the players torch (if any) or by any permanent light source.
* It could use and help maintain information about multiple light sources,
* which would be helpful in a multi-player version of Angband.
*
* Note that the "update_view()" function allows, among other things, a room
* to be "partially" seen as the player approaches it, with a growing cone
* of floor appearing as the player gets closer to the door. Also, by not
* turning on the "memorize perma-lit grids" option, the player will only
* "see" those floor grids which are actually in line of sight. And best
* of all, you can now activate the special lighting effects to indicate
* which grids are actually in the player's field of view by using dimmer
* colors for grids which are not in the player's field of view, and/or to
* indicate which grids are illuminated only by the player's torch by using
* the color yellow for those grids.
*
* The old "update_view()" algorithm uses the special "CAVE_EASY" flag as a
* temporary internal flag to mark those grids which are not only in view,
* but which are also "easily" in line of sight of the player. This flag
* is actually just the "CAVE_SEEN" flag, and the "update_view()" function
* makes sure to clear it for all old "CAVE_SEEN" grids, and then use it in
* the algorithm as "CAVE_EASY", and then clear it for all "CAVE_EASY" grids,
* and then reset it as appropriate for all new "CAVE_SEEN" grids. This is
* kind of messy, but it works. The old algorithm may disappear eventually.
*
* The new "update_view()" algorithm uses a faster and more mathematically
* correct algorithm, assisted by a large machine generated static array, to
* determine the "CAVE_VIEW" and "CAVE_SEEN" flags simultaneously. See below.
*
* It seems as though slight modifications to the "update_view()" functions
* would allow us to determine "reverse" line-of-sight as well as "normal"
* line-of-sight", which would allow monsters to have a more "correct" way
* to determine if they can "see" the player, since right now, they "cheat"
* somewhat and assume that if the player has "line of sight" to them, then
* they can "pretend" that they have "line of sight" to the player. But if
* such a change was attempted, the monsters would actually start to exhibit
* some undesirable behavior, such as "freezing" near the entrances to long
* hallways containing the player, and code would have to be added to make
* the monsters move around even if the player was not detectable, and to
* "remember" where the player was last seen, to avoid looking stupid.
*
* Note that the "CAVE_GLOW" flag means that a grid is permanently lit in
* some way. However, for the player to "see" the grid, as determined by
* the "CAVE_SEEN" flag, the player must not be blind, the grid must have
* the "CAVE_VIEW" flag set, and if the grid is a "wall" grid, and it is
* not lit by the player's torch, then it must touch a grid which does not
* have the "CAVE_WALL" flag set, but which does have both the "CAVE_GLOW"
* and "CAVE_VIEW" flags set. This last part about wall grids is induced
* by the semantics of "CAVE_GLOW" as applied to wall grids, and checking
* the technical requirements can be very expensive, especially since the
* grid may be touching some "illegal" grids. Luckily, it is more or less
* correct to restrict the "touching" grids from the eight "possible" grids
* to the (at most) three grids which are touching the grid, and which are
* closer to the player than the grid itself, which eliminates more than
* half of the work, including all of the potentially "illegal" grids, if
* at most one of the three grids is a "diagonal" grid. In addition, in
* almost every situation, it is possible to ignore the "CAVE_VIEW" flag
* on these three "touching" grids, for a variety of technical reasons.
* Finally, note that in most situations, it is only necessary to check
* a single "touching" grid, in fact, the grid which is strictly closest
* to the player of all the touching grids, and in fact, it is normally
* only necessary to check the "CAVE_GLOW" flag of that grid, again, for
* various technical reasons. However, one of the situations which does
* not work with this last reduction is the very common one in which the
* player approaches an illuminated room from a dark hallway, in which the
* two wall grids which form the "entrance" to the room would not be marked
* as "CAVE_SEEN", since of the three "touching" grids nearer to the player
* than each wall grid, only the farthest of these grids is itself marked
* "CAVE_GLOW".
*
*
* Here are some pictures of the legal "light source" radius values, in
* which the numbers indicate the "order" in which the grids could have
* been calculated, if desired. Note that the code will work with larger
* radiuses, though currently yields such a radius, and the game would
* become slower in some situations if it did.
*
* Rad=0 Rad=1 Rad=2 Rad=3
* No-Lite Torch,etc Lantern Artifacts
*
* 333
* 333 43334
* 212 32123 3321233
* @ 1@1 31@13 331@133
* 212 32123 3321233
* 333 43334
* 333
*
*
* Here is an illustration of the two different "update_view()" algorithms,
* in which the grids marked "%" are pillars, and the grids marked "?" are
* not in line of sight of the player.
*
*
* Sample situation
*
* #####################
* ############.%.%.%.%#
* #...@..#####........#
* #............%.%.%.%#
* #......#####........#
* ############........#
* #####################
*
*
* New Algorithm Old Algorithm
*
* ########????????????? ########?????????????
* #...@..#????????????? #...@..#?????????????
* #...........????????? #.........???????????
* #......#####.....???? #......####??????????
* ########?????????...# ########?????????????
*
* ########????????????? ########?????????????
* #.@....#????????????? #.@....#?????????????
* #............%??????? #...........?????????
* #......#####........? #......#####?????????
* ########??????????..# ########?????????????
*
* ########????????????? ########?????%???????
* #......#####........# #......#####..???????
* #.@..........%??????? #.@..........%???????
* #......#####........# #......#####..???????
* ########????????????? ########?????????????
*
* ########??????????..# ########?????????????
* #......#####........? #......#####?????????
* #............%??????? #...........?????????
* #.@....#????????????? #.@....#?????????????
* ########????????????? ########?????????????
*
* ########?????????%??? ########?????????????
* #......#####.....???? #......####??????????
* #...........????????? #.........???????????
* #...@..#????????????? #...@..#?????????????
* ########????????????? ########?????????????
*/
/**
* Forget the "CAVE_VIEW" grids, redrawing as needed
*/
void forget_view(void)
{
coord g;
for(g.y = 0; g.y < DUNGEON_HGT; ++g.y)
{
for (g.x = 0; g.x < DUNGEON_WID; ++g.x)
{
/* Clear "CAVE_VIEW" and "CAVE_SEEN" flags */
cave_info[g.y][g.x] &= ~(CAVE_VIEW | CAVE_SEEN);
/* Redraw */
lite_spot(g);
}
}
}
/**
* Zaiband: change view to be equivalent to projectability
*/
void view_sieve(coord* coord_list,coord src, int range, size_t& StrictUB)
{ /* define viewability in terms of projectability by a Wand/Rod of Light */
assert(NULL!=coord_list);
assert(0<range);
assert(in_bounds_fully(src.y,src.x));
assert(coord_list[0]==src);
/* first one in : src */
/* next 8 in: cardinal directions, 1 distant */
/* first questionable test square is 9th */
if (9>=StrictUB) return;
{ /* C-ish blocking brace */
coord grid_g[MAX(DUNGEON_HGT,DUNGEON_WID)];
size_t TestIdx = 9;
size_t ScanIdx = StrictUB;
/* XXX could get some more testing out of 8 cardinal directions, using PROJECT_THRU XXX */
while(TestIdx <= --ScanIdx)
{
/* check the projection path for a lightbeam */
/* note that grid_n is merely the last illuminated grid on this path, grids are valid out to distance range in Zaiband implementation */
int grid_n = project_path(grid_g, range, src, coord_list[ScanIdx], true, &wall_stop);
if (0>=grid_n || grid_g[grid_n-1]!=coord_list[ScanIdx])
{ /* did not reach target; dark */
if (ScanIdx+1<StrictUB) memmove(coord_list+ScanIdx,coord_list+ScanIdx+1,sizeof(coord)*(StrictUB-(ScanIdx+1)));
--StrictUB;
}
/* reached target, illuminated: do nothing */
}
} /* end C-ish blocking brace */
}
void update_view(void)
{
/* set up coordinate lists */
/* perhaps these should be explicit caches in p_ptr? */
const size_t coord_strict_ub = squares_in_view_octagon(MAX_SIGHT);
coord* coord_list = (coord*)calloc(coord_strict_ub,sizeof(coord));
coord* old_seen_list = (coord*)calloc(coord_strict_ub,sizeof(coord));
size_t StrictUB = 0; /* technically redundant, will be set correctly anyway later */
size_t StrictUB_old_seen = 0;
size_t i;
coord g;
byte info;
assert(NULL!=coord_list);
assert(NULL!=old_seen_list);
/* archive old seen grids */
for(g.y = 0; g.y < DUNGEON_HGT; ++g.y)
{
for (g.x = 0; g.x < DUNGEON_WID; ++g.x)
{
info = cave_info[g.y][g.x];
if (info & (CAVE_SEEN))
{
/* Set "CAVE_TEMP" flag */
info |= (CAVE_TEMP);
/* Save grid for later */
C_ARRAY_PUSH(old_seen_list,coord_strict_ub,StrictUB_old_seen,g);
}
/* Clear "CAVE_VIEW" and "CAVE_SEEN" flags */
info &= ~(CAVE_VIEW | CAVE_SEEN);
/* Save cave info */
cave_info[g.y][g.x] = info;
}
}
check_these_for_view(coord_list,p_ptr->loc,MAX_SIGHT,StrictUB,DUNGEON_HGT,DUNGEON_WID);
view_sieve(coord_list,p_ptr->loc,MAX_SIGHT,StrictUB);
/* actually use coord_list */
assert(coord_list[0]==p_ptr->loc);
/* Process "new" grids */
i = StrictUB;
while(0<i)
{
--i;
info = cave_info[coord_list[i].y][coord_list[i].x];
info |= (CAVE_VIEW); /* Assume viewable */
if (!p_ptr->timed[TMD_BLIND])
{
if ( (info & (CAVE_GLOW)) /* perma-lit grid */
|| (distance(p_ptr->loc.y,p_ptr->loc.x,coord_list[i].y,coord_list[i].x)<=p_ptr->cur_lite)) /* torch-lit grid */
{
/* Mark as "CAVE_SEEN" */
info |= (CAVE_SEEN);
}
}
/* Save cave info */
cave_info[coord_list[i].y][coord_list[i].x] = info;
/* Was not "CAVE_SEEN", is now "CAVE_SEEN" */
if ((info & (CAVE_SEEN)) && !(info & (CAVE_TEMP)))
{
/* Note */
note_spot(coord_list[i]);
/* Redraw */
lite_spot(coord_list[i]);
}
}
/* Process "old" grids */
i = StrictUB_old_seen;
while(0<i)
{
--i;
info = cave_info[old_seen_list[i].y][old_seen_list[i].x];
/* Clear "CAVE_TEMP" flag */
info &= ~(CAVE_TEMP);
/* Save cave info */
cave_info[old_seen_list[i].y][old_seen_list[i].x] = info;
/* Was "CAVE_SEEN", is now not "CAVE_SEEN": Redraw */
if (!(info & (CAVE_SEEN))) lite_spot(old_seen_list[i]);
}
free(coord_list);
free(old_seen_list);
}
/**
* Size of the circular queue used by "update_flow()"
*/
#define FLOW_MAX 2048
/**
* Hack -- provide some "speed" for the "flow" code
* This entry is the "current index" for the "when" field
* Note that a "when" value of "zero" means "not used".
*
* Note that the "cost" indexes from 1 to 127 are for
* "old" data, and from 128 to 255 are for "new" data.
*
* This means that as long as the player does not "teleport",
* then any monster up to 128 + MONSTER_FLOW_DEPTH will be
* able to track down the player, and in general, will be
* able to track down either the player or a position recently
* occupied by the player.
*/
static int flow_save = 0;
/**
* Hack -- forget the "flow" information
*/
void forget_flow(void)
{
int x, y;
/* Nothing to forget */
if (!flow_save) return;
/* Check the entire dungeon */
for (y = 0; y < DUNGEON_HGT; y++)
{
for (x = 0; x < DUNGEON_WID; x++)
{
/* Forget the old data */
cave_cost[y][x] = 0;
cave_when[y][x] = 0;
}
}
/* Start over */
flow_save = 0;
}
/**
* Hack -- fill in the "cost" field of every grid that the player can
* "reach" with the number of steps needed to reach that grid. This
* also yields the "distance" of the player from every grid.
*
* In addition, mark the "when" of the grids that can reach the player
* with the incremented value of "flow_save".
*
* Hack -- use the local "flow_c" array as a circular queue of cave grids.
*
* We do not need a priority queue because the cost from grid to grid
* is always "one" (even along diagonals) and we process them in order.
*/
void update_flow(void)
{
int py = p_ptr->loc.y;
int px = p_ptr->loc.x;
int y, x;
int n, d;
int flow_n;
int flow_tail = 0;
int flow_head = 0;
coord flow_c[FLOW_MAX];
/* Hack -- disabled */
if (!OPTION(adult_flow_by_sound)) return;
/*** Cycle the flow ***/
/* Cycle the flow */
if (flow_save++ == 255)
{
/* Cycle the flow */
for (y = 0; y < DUNGEON_HGT; y++)
{
for (x = 0; x < DUNGEON_WID; x++)
{
int w = cave_when[y][x];
cave_when[y][x] = (w >= 128) ? (w - 128) : 0;
}
}
/* Restart */
flow_save = 128;
}
/* Local variable */
flow_n = flow_save;
/*** Player Grid ***/
/* Save the time-stamp */
cave_when[py][px] = flow_n;
/* Save the flow cost */
cave_cost[py][px] = 0;
/* Enqueue that entry */
flow_c[flow_head] = p_ptr->loc;
/* Advance the queue */
++flow_tail;
/*** Process Queue ***/
/* Now process the queue */
while (flow_head != flow_tail)
{
/* Extract the next entry */
coord t = flow_c[flow_head];
/* Forget that entry (with wrap) */
flow_head = (flow_head+1)%FLOW_MAX;
/* Child cost */
n = cave_cost[t.y][t.x] + 1;
/* Hack -- Limit flow depth */
if (n == MONSTER_FLOW_DEPTH) continue;
/* Add the "children" */
for (d = 0; d < KEYPAD_DIR_MAX; d++)
{
int old_head = flow_tail;
/* Child location */
coord new_coord = t+dd_coord_ddd[d];
/* Ignore "pre-stamped" entries */
if (cave_when[new_coord.y][new_coord.x] == flow_n) continue;
/* Ignore "walls" and "rubble" */
if (cave_feat[new_coord.y][new_coord.x] >= FEAT_RUBBLE) continue;
/* Save the time-stamp */
cave_when[new_coord.y][new_coord.x] = flow_n;
/* Save the flow cost */
cave_cost[new_coord.y][new_coord.x] = n;
/* Enqueue that entry */
flow_c[flow_tail] = new_coord;
/* Advance the queue */
flow_tail = (flow_tail+1)%FLOW_MAX;
/* Hack -- Overflow by forgetting new entry */
if (flow_tail == flow_head) flow_tail = old_head;
}
}
}
/**
* Map the current panel (plus some) ala "magic mapping"
*
* We must never attempt to map the outer dungeon walls, or we
* might induce illegal cave grid references.
*/
void map_area(void)
{
int i, x, y, y1, y2, x1, x2;
/* Pick an area to map */
y1 = Term->offset_y - randint(10);
y2 = Term->offset_y + SCREEN_HGT + randint(10);
x1 = Term->offset_x - randint(20);
x2 = Term->offset_x + SCREEN_WID + randint(20);
/* Efficiency -- shrink to fit legal bounds */
if (y1 < 1) y1 = 1;
if (y2 > DUNGEON_HGT-1) y2 = DUNGEON_HGT-1;
if (x1 < 1) x1 = 1;
if (x2 > DUNGEON_WID-1) x2 = DUNGEON_WID-1;
/* Scan that area */
for (y = y1; y < y2; y++)
{
for (x = x1; x < x2; x++)
{
/* All non-walls are "checked" */
if (cave_feat[y][x] < FEAT_SECRET)
{
/* Memorize normal features */
if (cave_feat[y][x] > FEAT_INVIS)
{
/* Memorize the object */
cave_info[y][x] |= (CAVE_MARK);
}
/* Memorize known walls */
for (i = 0; i < KEYPAD_DIR_MAX; i++)
{
int yy = y + ddy_ddd[i];
int xx = x + ddx_ddd[i];
/* Memorize walls (etc) */
if (cave_feat[yy][xx] >= FEAT_SECRET)
{
/* Memorize the walls */
cave_info[yy][xx] |= (CAVE_MARK);
}
}
}
}
}
/* Redraw map */
p_ptr->redraw |= (PR_MAP);
}
static bool wiz_lite_object(object_type& o)
{
/* Memorize non-held objects */
if (!o.held_m_idx) o.marked = TRUE;
return false;
}
/**
* Light up the dungeon using "clairvoyance"
*
* This function "illuminates" every grid in the dungeon, memorizes all
* "objects", memorizes all grids as with magic mapping, and, under the
* standard option settings (OPTION(view_perma_grids) but not OPTION(view_torch_grids))
* memorizes all floor grids too.
*
* Note that if "OPTION(view_perma_grids)" is not set, we do not memorize floor
* grids, since this would defeat the purpose of "OPTION(view_perma_grids)", not
* that anyone seems to play without this option.
*
* Note that if "OPTION(view_torch_grids)" is set, we do not memorize floor grids,
* since this would prevent the use of "OPTION(view_torch_grids)" as a method to
* keep track of what grids have been observed directly.
*/
void wiz_lite(void)
{
int i, y, x;
/* Memorize objects */
object_scan(wiz_lite_object);
/* Scan all normal grids */
for (y = 1; y < DUNGEON_HGT-1; y++)
{
/* Scan all normal grids */
for (x = 1; x < DUNGEON_WID-1; x++)
{
/* Process all non-walls */
if (cave_feat[y][x] < FEAT_SECRET)
{
/* Scan all neighbors */
for (i = 0; i < KEYPAD_DIR_MAX+1; i++)
{
int yy = y + ddy_ddd[i];
int xx = x + ddx_ddd[i];
/* Perma-lite the grid */
cave_info[yy][xx] |= (CAVE_GLOW);
/* Memorize normal features */
if (cave_feat[yy][xx] > FEAT_INVIS)
{
/* Memorize the grid */
cave_info[yy][xx] |= (CAVE_MARK);
}
/* Normally, memorize floors (see above) */
if (OPTION(view_perma_grids) && !OPTION(view_torch_grids))
{
/* Memorize the grid */
cave_info[yy][xx] |= (CAVE_MARK);
}
}
}
}
}
/* Fully update the visuals */
p_ptr->update |= (PU_FORGET_VIEW | PU_UPDATE_VIEW | PU_MONSTERS);
/* Redraw map, monster list */
p_ptr->redraw |= (PR_MAP | PR_MONLIST);
}
static bool wiz_dark_object(object_type& o)
{
/* Forget non-held objects */
if (!o.held_m_idx) o.marked = FALSE;
return false;
}
/**
* Forget the dungeon map (ala "Thinking of Maud...").
*/
void wiz_dark(void)
{
int y, x;
/* Forget every grid */
for (y = 0; y < DUNGEON_HGT; y++)
{
for (x = 0; x < DUNGEON_WID; x++)
{
/* Process the grid */
cave_info[y][x] &= ~(CAVE_MARK);
}
}
/* Forget all objects */
object_scan(wiz_dark_object);
/* Fully update the visuals */
p_ptr->update |= (PU_FORGET_VIEW | PU_UPDATE_VIEW | PU_MONSTERS);
/* Redraw map, monster list */
p_ptr->redraw |= (PR_MAP | PR_MONLIST);
}
/**
* Light or Darken the town
*/
void town_illuminate(bool daytime)
{
int y, x, i;
/* Apply light or darkness */
for (y = 0; y < TOWN_HGT; y++)
{
for (x = 0; x < TOWN_WID; x++)
{
/* Interesting grids */
if (cave_feat[y][x] > FEAT_INVIS)
{
/* Illuminate the grid */
cave_info[y][x] |= (CAVE_GLOW);
/* Memorize the grid */
cave_info[y][x] |= (CAVE_MARK);
}
/* Boring grids (light) */
else if (daytime)
{
/* Illuminate the grid */
cave_info[y][x] |= (CAVE_GLOW);
/* Hack -- Memorize grids */
if (OPTION(view_perma_grids))
{
cave_info[y][x] |= (CAVE_MARK);
}
}
/* Boring grids (dark) */
else
{
/* Darken the grid */
cave_info[y][x] &= ~(CAVE_GLOW);
/* Hack -- Forget grids */
if (OPTION(view_perma_grids))
{
cave_info[y][x] &= ~(CAVE_MARK);
}
}
}
}
/* Handle shop doorways */
for (y = 0; y < TOWN_HGT; y++)
{
for (x = 0; x < TOWN_WID; x++)
{
/* Track shop doorways */
if (cave_feat_in_range(y,x,FEAT_SHOP_HEAD,FEAT_SHOP_TAIL))
{
for (i = 0; i < KEYPAD_DIR_MAX; i++)
{
int yy = y + ddy_ddd[i];
int xx = x + ddx_ddd[i];
/* Illuminate the grid */
cave_info[yy][xx] |= (CAVE_GLOW);
/* Hack -- Memorize grids */
if (OPTION(view_perma_grids)) cave_info[yy][xx] |= (CAVE_MARK);
}
}
}
}
/* Fully update the visuals */
p_ptr->update |= (PU_FORGET_VIEW | PU_UPDATE_VIEW | PU_MONSTERS);
/* Redraw map, monster list */
p_ptr->redraw |= (PR_MAP | PR_MONLIST);
}
/**
* Change the "feat" flag for a grid, and notice/redraw the grid
*/
void cave_set_feat(int y, int x, int feat)
{
assert(0 <= feat && feat < z_info->f_max);
/* Change the feature */
cave_feat[y][x] = feat;
/* Handle "wall/door" grids */
if (feat >= FEAT_DOOR_HEAD)
{
cave_info[y][x] |= (CAVE_WALL);
}
/* Handle "floor"/etc grids */
else
{
cave_info[y][x] &= ~(CAVE_WALL);
}
/* Notice/Redraw */
if (character_dungeon)
{
/* Notice */
note_spot(coord(x, y));
/* Redraw */
lite_spot(coord(x, y));
}
}
bool wall_stop(coord g)
{
/* Always stop at non-initial wall grids */
if (!cave_floor_bold(g.y, g.x)) return true;
return false;
}
bool wall_mon_stop(coord g)
{
/* Always stop at non-initial wall grids */
if (!cave_floor_bold(g.y, g.x)) return true;
/* stop at non-initial monsters/players */
if (cave_m_idx[g.y][g.x] != 0) return true;
return false;
}
/**
* Determine if a bolt spell cast from (y1,x1) to (y2,x2) will arrive
* at the final destination, assuming that no monster gets in the way,
* using the "project_path()" function to check the projection path.
*
* Note that no grid is ever "projectable()" from itself.
*
* This function is used to determine if the player can (easily) target
* a given grid, and if a monster can target the player.
*/
bool projectable(coord g1, coord g2)
{
coord grid_g[MAX(DUNGEON_HGT,DUNGEON_WID)];
int grid_n = project_path(grid_g, MAX_RANGE, g1, g2, true, &wall_stop); /* Check the projection path */
/* No grid is ever projectable from itself */
if (!grid_n) return (FALSE);
/* May not end in an unrequested grid */
if (grid_g[grid_n-1]!=g2) return (FALSE);
/* May not end in a wall grid */
if (!cave_floor_bold(g2.y, g2.x)) return (FALSE);
/* Assume okay */
return (TRUE);
}
/**
* Standard "find me a location" function
*
* Obtains a legal location within the given distance of the initial
* location, and with "los()" from the source to destination location.
*
* This function is often called from inside a loop which searches for
* locations while increasing the "d" distance.
*
* Currently the "m" parameter is unused.
*/
void scatter(coord& g, coord g2, int d, int m)
{
coord_scan n;
/* Unused parameter */
(void)m;
/* Pick a location */
do {
/* Pick a new location */
n.y = rand_spread(g2.y, d);
n.x = rand_spread(g2.x, d);
/* Ignore annoying locations */
if (!in_bounds_fully(n.y, n.x)) continue;
/* Ignore "excessively distant" locations */
if ((d > 1) && (distance(g2.y, g2.x, n.y, n.x) > d)) continue;
}
while(!los(g2,n)); /* Require "line of sight" */
/* Save the location */
g = n;
}
/**
* Track a new monster
*/
void health_track(int m_idx)
{
p_ptr->health_who = m_idx; /* Track a new guy */
p_ptr->redraw |= (PR_HEALTH); /* Redraw (later) */
}
/**
* Hack -- track the given monster race
*/
void monster_race_track(int r_idx)
{
p_ptr->monster_race_idx = r_idx; /* Save this monster ID */
p_ptr->redraw |= (PR_MONSTER); /* Redraw (later) */
}
/**
* Hack -- track the given object kind
*/
void object_kind_track(int k_idx)
{
p_ptr->object_kind_idx = k_idx; /* Save this object ID */
p_ptr->redraw |= (PR_OBJECT); /* Redraw (later) */
}
/**
* Something has happened to disturb the player.
*
* The first arg indicates a major disturbance, which affects search.
*
* The second arg is currently unused, but could induce output flush.
*
* All disturbance cancels repeated commands, resting, and running.
*/
void disturb(int stop_search, int unused_flag)
{
/* Unused parameter */
(void)unused_flag;
/* Cancel auto-commands */
/* p_ptr->command_new = 0; */
/* Cancel repeated commands */
if (p_ptr->command_rep)
{
/* Cancel */
p_ptr->command_rep = 0;
/* Redraw the state (later) */
p_ptr->redraw |= (PR_STATE);
}
/* Cancel Resting */
if (p_ptr->resting)
{
/* Cancel */
p_ptr->resting = 0;
/* Redraw the state (later) */
p_ptr->redraw |= (PR_STATE);
}
/* Cancel running */
if (p_ptr->running)
{
/* Cancel */
p_ptr->running = 0;
/* Check for new panel if appropriate */
if (OPTION(center_player) && OPTION(run_avoid_center)) event_signal(EVENT_PLAYERMOVED);
/* Calculate torch radius */
p_ptr->update |= (PU_TORCH);
/* Redraw the player, if needed */
if (OPTION(hidden_player)) lite_spot(p_ptr->loc);
}
/* Cancel searching if requested */
if (stop_search && p_ptr->searching)
{
/* Cancel */
p_ptr->searching = FALSE;
/* Recalculate bonuses */
p_ptr->update |= (PU_BONUS);
/* Redraw the state */
p_ptr->redraw |= (PR_STATE);
}
/* Flush the input if requested */
if (OPTION(flush_disturb)) flush();
}
/**
* Hack -- Check if a level is a "quest" level
*/
bool is_quest(int level)
{
int i;
/* Town is never a quest */
if (!level) return (FALSE);
/* Check quests */
for (i = 0; i < MAX_Q_IDX; i++)
{
/* Check for quest */
if (q_list[i].level == level) return (TRUE);
}
/* Nope */
return (FALSE);
}
| 28.051507 | 139 | 0.617983 | [
"object"
] |
cf2bba440b209221aaec3927bf8c56b36e05d963 | 51,535 | h | C | node_modules/raylib/src/node-raylib.h | Googcoon/Better-Raylib | 65f5a3f5a9fc5c68660f630358a13ffd095866de | [
"Apache-2.0"
] | 131 | 2019-01-17T23:52:06.000Z | 2022-03-23T15:57:48.000Z | node_modules/raylib/src/node-raylib.h | Googcoon/Better-Raylib | 65f5a3f5a9fc5c68660f630358a13ffd095866de | [
"Apache-2.0"
] | 77 | 2019-01-07T03:37:27.000Z | 2022-03-16T02:06:29.000Z | node_modules/raylib/src/node-raylib.h | Googcoon/Better-Raylib | 65f5a3f5a9fc5c68660f630358a13ffd095866de | [
"Apache-2.0"
] | 21 | 2019-06-16T06:48:04.000Z | 2022-02-09T01:43:02.000Z | #ifndef NODE_RAYLIB_NODE_RAYLIB_H
#define NODE_RAYLIB_NODE_RAYLIB_H
#include <string>
#include <napi.h>
#include "raylib.h"
#include "lib/AddDefine.h"
#include "lib/AddFunction.h"
void node_raylib_bindings_defines(Napi::Env& env, Napi::Object& exports) {
AddDefineInteger(env, exports, "FLAG_VSYNC_HINT", FLAG_VSYNC_HINT);
AddDefineInteger(env, exports, "FLAG_FULLSCREEN_MODE", FLAG_FULLSCREEN_MODE);
AddDefineInteger(env, exports, "FLAG_WINDOW_RESIZABLE", FLAG_WINDOW_RESIZABLE);
AddDefineInteger(env, exports, "FLAG_WINDOW_UNDECORATED", FLAG_WINDOW_UNDECORATED);
AddDefineInteger(env, exports, "FLAG_WINDOW_HIDDEN", FLAG_WINDOW_HIDDEN);
AddDefineInteger(env, exports, "FLAG_WINDOW_MINIMIZED", FLAG_WINDOW_MINIMIZED);
AddDefineInteger(env, exports, "FLAG_WINDOW_MAXIMIZED", FLAG_WINDOW_MAXIMIZED);
AddDefineInteger(env, exports, "FLAG_WINDOW_UNFOCUSED", FLAG_WINDOW_UNFOCUSED);
AddDefineInteger(env, exports, "FLAG_WINDOW_TOPMOST", FLAG_WINDOW_TOPMOST);
AddDefineInteger(env, exports, "FLAG_WINDOW_ALWAYS_RUN", FLAG_WINDOW_ALWAYS_RUN);
AddDefineInteger(env, exports, "FLAG_WINDOW_TRANSPARENT", FLAG_WINDOW_TRANSPARENT);
AddDefineInteger(env, exports, "FLAG_WINDOW_HIGHDPI", FLAG_WINDOW_HIGHDPI);
AddDefineInteger(env, exports, "FLAG_MSAA_4X_HINT", FLAG_MSAA_4X_HINT);
AddDefineInteger(env, exports, "FLAG_INTERLACED_HINT", FLAG_INTERLACED_HINT);
AddDefineInteger(env, exports, "LOG_ALL", LOG_ALL);
AddDefineInteger(env, exports, "LOG_TRACE", LOG_TRACE);
AddDefineInteger(env, exports, "LOG_DEBUG", LOG_DEBUG);
AddDefineInteger(env, exports, "LOG_INFO", LOG_INFO);
AddDefineInteger(env, exports, "LOG_WARNING", LOG_WARNING);
AddDefineInteger(env, exports, "LOG_ERROR", LOG_ERROR);
AddDefineInteger(env, exports, "LOG_FATAL", LOG_FATAL);
AddDefineInteger(env, exports, "LOG_NONE", LOG_NONE);
AddDefineInteger(env, exports, "KEY_APOSTROPHE", KEY_APOSTROPHE);
AddDefineInteger(env, exports, "KEY_COMMA", KEY_COMMA);
AddDefineInteger(env, exports, "KEY_MINUS", KEY_MINUS);
AddDefineInteger(env, exports, "KEY_PERIOD", KEY_PERIOD);
AddDefineInteger(env, exports, "KEY_SLASH", KEY_SLASH);
AddDefineInteger(env, exports, "KEY_ZERO", KEY_ZERO);
AddDefineInteger(env, exports, "KEY_ONE", KEY_ONE);
AddDefineInteger(env, exports, "KEY_TWO", KEY_TWO);
AddDefineInteger(env, exports, "KEY_THREE", KEY_THREE);
AddDefineInteger(env, exports, "KEY_FOUR", KEY_FOUR);
AddDefineInteger(env, exports, "KEY_FIVE", KEY_FIVE);
AddDefineInteger(env, exports, "KEY_SIX", KEY_SIX);
AddDefineInteger(env, exports, "KEY_SEVEN", KEY_SEVEN);
AddDefineInteger(env, exports, "KEY_EIGHT", KEY_EIGHT);
AddDefineInteger(env, exports, "KEY_NINE", KEY_NINE);
AddDefineInteger(env, exports, "KEY_SEMICOLON", KEY_SEMICOLON);
AddDefineInteger(env, exports, "KEY_EQUAL", KEY_EQUAL);
AddDefineInteger(env, exports, "KEY_A", KEY_A);
AddDefineInteger(env, exports, "KEY_B", KEY_B);
AddDefineInteger(env, exports, "KEY_C", KEY_C);
AddDefineInteger(env, exports, "KEY_D", KEY_D);
AddDefineInteger(env, exports, "KEY_E", KEY_E);
AddDefineInteger(env, exports, "KEY_F", KEY_F);
AddDefineInteger(env, exports, "KEY_G", KEY_G);
AddDefineInteger(env, exports, "KEY_H", KEY_H);
AddDefineInteger(env, exports, "KEY_I", KEY_I);
AddDefineInteger(env, exports, "KEY_J", KEY_J);
AddDefineInteger(env, exports, "KEY_K", KEY_K);
AddDefineInteger(env, exports, "KEY_L", KEY_L);
AddDefineInteger(env, exports, "KEY_M", KEY_M);
AddDefineInteger(env, exports, "KEY_N", KEY_N);
AddDefineInteger(env, exports, "KEY_O", KEY_O);
AddDefineInteger(env, exports, "KEY_P", KEY_P);
AddDefineInteger(env, exports, "KEY_Q", KEY_Q);
AddDefineInteger(env, exports, "KEY_R", KEY_R);
AddDefineInteger(env, exports, "KEY_S", KEY_S);
AddDefineInteger(env, exports, "KEY_T", KEY_T);
AddDefineInteger(env, exports, "KEY_U", KEY_U);
AddDefineInteger(env, exports, "KEY_V", KEY_V);
AddDefineInteger(env, exports, "KEY_W", KEY_W);
AddDefineInteger(env, exports, "KEY_X", KEY_X);
AddDefineInteger(env, exports, "KEY_Y", KEY_Y);
AddDefineInteger(env, exports, "KEY_Z", KEY_Z);
AddDefineInteger(env, exports, "KEY_SPACE", KEY_SPACE);
AddDefineInteger(env, exports, "KEY_ESCAPE", KEY_ESCAPE);
AddDefineInteger(env, exports, "KEY_ENTER", KEY_ENTER);
AddDefineInteger(env, exports, "KEY_TAB", KEY_TAB);
AddDefineInteger(env, exports, "KEY_BACKSPACE", KEY_BACKSPACE);
AddDefineInteger(env, exports, "KEY_INSERT", KEY_INSERT);
AddDefineInteger(env, exports, "KEY_DELETE", KEY_DELETE);
AddDefineInteger(env, exports, "KEY_RIGHT", KEY_RIGHT);
AddDefineInteger(env, exports, "KEY_LEFT", KEY_LEFT);
AddDefineInteger(env, exports, "KEY_DOWN", KEY_DOWN);
AddDefineInteger(env, exports, "KEY_UP", KEY_UP);
AddDefineInteger(env, exports, "KEY_PAGE_UP", KEY_PAGE_UP);
AddDefineInteger(env, exports, "KEY_PAGE_DOWN", KEY_PAGE_DOWN);
AddDefineInteger(env, exports, "KEY_HOME", KEY_HOME);
AddDefineInteger(env, exports, "KEY_END", KEY_END);
AddDefineInteger(env, exports, "KEY_CAPS_LOCK", KEY_CAPS_LOCK);
AddDefineInteger(env, exports, "KEY_SCROLL_LOCK", KEY_SCROLL_LOCK);
AddDefineInteger(env, exports, "KEY_NUM_LOCK", KEY_NUM_LOCK);
AddDefineInteger(env, exports, "KEY_PRINT_SCREEN", KEY_PRINT_SCREEN);
AddDefineInteger(env, exports, "KEY_PAUSE", KEY_PAUSE);
AddDefineInteger(env, exports, "KEY_F1", KEY_F1);
AddDefineInteger(env, exports, "KEY_F2", KEY_F2);
AddDefineInteger(env, exports, "KEY_F3", KEY_F3);
AddDefineInteger(env, exports, "KEY_F4", KEY_F4);
AddDefineInteger(env, exports, "KEY_F5", KEY_F5);
AddDefineInteger(env, exports, "KEY_F6", KEY_F6);
AddDefineInteger(env, exports, "KEY_F7", KEY_F7);
AddDefineInteger(env, exports, "KEY_F8", KEY_F8);
AddDefineInteger(env, exports, "KEY_F9", KEY_F9);
AddDefineInteger(env, exports, "KEY_F10", KEY_F10);
AddDefineInteger(env, exports, "KEY_F11", KEY_F11);
AddDefineInteger(env, exports, "KEY_F12", KEY_F12);
AddDefineInteger(env, exports, "KEY_LEFT_SHIFT", KEY_LEFT_SHIFT);
AddDefineInteger(env, exports, "KEY_LEFT_CONTROL", KEY_LEFT_CONTROL);
AddDefineInteger(env, exports, "KEY_LEFT_ALT", KEY_LEFT_ALT);
AddDefineInteger(env, exports, "KEY_LEFT_SUPER", KEY_LEFT_SUPER);
AddDefineInteger(env, exports, "KEY_RIGHT_SHIFT", KEY_RIGHT_SHIFT);
AddDefineInteger(env, exports, "KEY_RIGHT_CONTROL", KEY_RIGHT_CONTROL);
AddDefineInteger(env, exports, "KEY_RIGHT_ALT", KEY_RIGHT_ALT);
AddDefineInteger(env, exports, "KEY_RIGHT_SUPER", KEY_RIGHT_SUPER);
AddDefineInteger(env, exports, "KEY_KB_MENU", KEY_KB_MENU);
AddDefineInteger(env, exports, "KEY_LEFT_BRACKET", KEY_LEFT_BRACKET);
AddDefineInteger(env, exports, "KEY_BACKSLASH", KEY_BACKSLASH);
AddDefineInteger(env, exports, "KEY_RIGHT_BRACKET", KEY_RIGHT_BRACKET);
AddDefineInteger(env, exports, "KEY_GRAVE", KEY_GRAVE);
AddDefineInteger(env, exports, "KEY_KP_0", KEY_KP_0);
AddDefineInteger(env, exports, "KEY_KP_1", KEY_KP_1);
AddDefineInteger(env, exports, "KEY_KP_2", KEY_KP_2);
AddDefineInteger(env, exports, "KEY_KP_3", KEY_KP_3);
AddDefineInteger(env, exports, "KEY_KP_4", KEY_KP_4);
AddDefineInteger(env, exports, "KEY_KP_5", KEY_KP_5);
AddDefineInteger(env, exports, "KEY_KP_6", KEY_KP_6);
AddDefineInteger(env, exports, "KEY_KP_7", KEY_KP_7);
AddDefineInteger(env, exports, "KEY_KP_8", KEY_KP_8);
AddDefineInteger(env, exports, "KEY_KP_9", KEY_KP_9);
AddDefineInteger(env, exports, "KEY_KP_DECIMAL", KEY_KP_DECIMAL);
AddDefineInteger(env, exports, "KEY_KP_DIVIDE", KEY_KP_DIVIDE);
AddDefineInteger(env, exports, "KEY_KP_MULTIPLY", KEY_KP_MULTIPLY);
AddDefineInteger(env, exports, "KEY_KP_SUBTRACT", KEY_KP_SUBTRACT);
AddDefineInteger(env, exports, "KEY_KP_ADD", KEY_KP_ADD);
AddDefineInteger(env, exports, "KEY_KP_ENTER", KEY_KP_ENTER);
AddDefineInteger(env, exports, "KEY_KP_EQUAL", KEY_KP_EQUAL);
AddDefineInteger(env, exports, "KEY_BACK", KEY_BACK);
AddDefineInteger(env, exports, "KEY_MENU", KEY_MENU);
AddDefineInteger(env, exports, "KEY_VOLUME_UP", KEY_VOLUME_UP);
AddDefineInteger(env, exports, "KEY_VOLUME_DOWN", KEY_VOLUME_DOWN);
AddDefineInteger(env, exports, "MOUSE_LEFT_BUTTON", MOUSE_LEFT_BUTTON);
AddDefineInteger(env, exports, "MOUSE_RIGHT_BUTTON", MOUSE_RIGHT_BUTTON);
AddDefineInteger(env, exports, "MOUSE_MIDDLE_BUTTON", MOUSE_MIDDLE_BUTTON);
AddDefineInteger(env, exports, "MOUSE_CURSOR_DEFAULT", MOUSE_CURSOR_DEFAULT);
AddDefineInteger(env, exports, "MOUSE_CURSOR_ARROW", MOUSE_CURSOR_ARROW);
AddDefineInteger(env, exports, "MOUSE_CURSOR_IBEAM", MOUSE_CURSOR_IBEAM);
AddDefineInteger(env, exports, "MOUSE_CURSOR_CROSSHAIR", MOUSE_CURSOR_CROSSHAIR);
AddDefineInteger(env, exports, "MOUSE_CURSOR_POINTING_HAND", MOUSE_CURSOR_POINTING_HAND);
AddDefineInteger(env, exports, "MOUSE_CURSOR_RESIZE_EW", MOUSE_CURSOR_RESIZE_EW);
AddDefineInteger(env, exports, "MOUSE_CURSOR_RESIZE_NS", MOUSE_CURSOR_RESIZE_NS);
AddDefineInteger(env, exports, "MOUSE_CURSOR_RESIZE_NWSE", MOUSE_CURSOR_RESIZE_NWSE);
AddDefineInteger(env, exports, "MOUSE_CURSOR_RESIZE_NESW", MOUSE_CURSOR_RESIZE_NESW);
AddDefineInteger(env, exports, "MOUSE_CURSOR_RESIZE_ALL", MOUSE_CURSOR_RESIZE_ALL);
AddDefineInteger(env, exports, "MOUSE_CURSOR_NOT_ALLOWED", MOUSE_CURSOR_NOT_ALLOWED);
AddDefineInteger(env, exports, "GAMEPAD_PLAYER1", GAMEPAD_PLAYER1);
AddDefineInteger(env, exports, "GAMEPAD_PLAYER2", GAMEPAD_PLAYER2);
AddDefineInteger(env, exports, "GAMEPAD_PLAYER3", GAMEPAD_PLAYER3);
AddDefineInteger(env, exports, "GAMEPAD_PLAYER4", GAMEPAD_PLAYER4);
AddDefineInteger(env, exports, "GAMEPAD_BUTTON_UNKNOWN", GAMEPAD_BUTTON_UNKNOWN);
AddDefineInteger(env, exports, "GAMEPAD_BUTTON_LEFT_FACE_UP", GAMEPAD_BUTTON_LEFT_FACE_UP);
AddDefineInteger(env, exports, "GAMEPAD_BUTTON_LEFT_FACE_RIGHT", GAMEPAD_BUTTON_LEFT_FACE_RIGHT);
AddDefineInteger(env, exports, "GAMEPAD_BUTTON_LEFT_FACE_DOWN", GAMEPAD_BUTTON_LEFT_FACE_DOWN);
AddDefineInteger(env, exports, "GAMEPAD_BUTTON_LEFT_FACE_LEFT", GAMEPAD_BUTTON_LEFT_FACE_LEFT);
AddDefineInteger(env, exports, "GAMEPAD_BUTTON_RIGHT_FACE_UP", GAMEPAD_BUTTON_RIGHT_FACE_UP);
AddDefineInteger(env, exports, "GAMEPAD_BUTTON_RIGHT_FACE_RIGHT", GAMEPAD_BUTTON_RIGHT_FACE_RIGHT);
AddDefineInteger(env, exports, "GAMEPAD_BUTTON_RIGHT_FACE_DOWN", GAMEPAD_BUTTON_RIGHT_FACE_DOWN);
AddDefineInteger(env, exports, "GAMEPAD_BUTTON_RIGHT_FACE_LEFT", GAMEPAD_BUTTON_RIGHT_FACE_LEFT);
AddDefineInteger(env, exports, "GAMEPAD_BUTTON_LEFT_TRIGGER_1", GAMEPAD_BUTTON_LEFT_TRIGGER_1);
AddDefineInteger(env, exports, "GAMEPAD_BUTTON_LEFT_TRIGGER_2", GAMEPAD_BUTTON_LEFT_TRIGGER_2);
AddDefineInteger(env, exports, "GAMEPAD_BUTTON_RIGHT_TRIGGER_1", GAMEPAD_BUTTON_RIGHT_TRIGGER_1);
AddDefineInteger(env, exports, "GAMEPAD_BUTTON_RIGHT_TRIGGER_2", GAMEPAD_BUTTON_RIGHT_TRIGGER_2);
AddDefineInteger(env, exports, "GAMEPAD_BUTTON_MIDDLE_LEFT", GAMEPAD_BUTTON_MIDDLE_LEFT);
AddDefineInteger(env, exports, "GAMEPAD_BUTTON_MIDDLE", GAMEPAD_BUTTON_MIDDLE);
AddDefineInteger(env, exports, "GAMEPAD_BUTTON_MIDDLE_RIGHT", GAMEPAD_BUTTON_MIDDLE_RIGHT);
AddDefineInteger(env, exports, "GAMEPAD_BUTTON_LEFT_THUMB", GAMEPAD_BUTTON_LEFT_THUMB);
AddDefineInteger(env, exports, "GAMEPAD_BUTTON_RIGHT_THUMB", GAMEPAD_BUTTON_RIGHT_THUMB);
AddDefineInteger(env, exports, "GAMEPAD_AXIS_LEFT_X", GAMEPAD_AXIS_LEFT_X);
AddDefineInteger(env, exports, "GAMEPAD_AXIS_LEFT_Y", GAMEPAD_AXIS_LEFT_Y);
AddDefineInteger(env, exports, "GAMEPAD_AXIS_RIGHT_X", GAMEPAD_AXIS_RIGHT_X);
AddDefineInteger(env, exports, "GAMEPAD_AXIS_RIGHT_Y", GAMEPAD_AXIS_RIGHT_Y);
AddDefineInteger(env, exports, "GAMEPAD_AXIS_LEFT_TRIGGER", GAMEPAD_AXIS_LEFT_TRIGGER);
AddDefineInteger(env, exports, "GAMEPAD_AXIS_RIGHT_TRIGGER", GAMEPAD_AXIS_RIGHT_TRIGGER);
AddDefineInteger(env, exports, "LOC_VERTEX_POSITION", LOC_VERTEX_POSITION);
AddDefineInteger(env, exports, "LOC_VERTEX_TEXCOORD01", LOC_VERTEX_TEXCOORD01);
AddDefineInteger(env, exports, "LOC_VERTEX_TEXCOORD02", LOC_VERTEX_TEXCOORD02);
AddDefineInteger(env, exports, "LOC_VERTEX_NORMAL", LOC_VERTEX_NORMAL);
AddDefineInteger(env, exports, "LOC_VERTEX_TANGENT", LOC_VERTEX_TANGENT);
AddDefineInteger(env, exports, "LOC_VERTEX_COLOR", LOC_VERTEX_COLOR);
AddDefineInteger(env, exports, "LOC_MATRIX_MVP", LOC_MATRIX_MVP);
AddDefineInteger(env, exports, "LOC_MATRIX_MODEL", LOC_MATRIX_MODEL);
AddDefineInteger(env, exports, "LOC_MATRIX_VIEW", LOC_MATRIX_VIEW);
AddDefineInteger(env, exports, "LOC_MATRIX_PROJECTION", LOC_MATRIX_PROJECTION);
AddDefineInteger(env, exports, "LOC_VECTOR_VIEW", LOC_VECTOR_VIEW);
AddDefineInteger(env, exports, "LOC_COLOR_DIFFUSE", LOC_COLOR_DIFFUSE);
AddDefineInteger(env, exports, "LOC_COLOR_SPECULAR", LOC_COLOR_SPECULAR);
AddDefineInteger(env, exports, "LOC_COLOR_AMBIENT", LOC_COLOR_AMBIENT);
AddDefineInteger(env, exports, "LOC_MAP_ALBEDO", LOC_MAP_ALBEDO);
AddDefineInteger(env, exports, "LOC_MAP_METALNESS", LOC_MAP_METALNESS);
AddDefineInteger(env, exports, "LOC_MAP_NORMAL", LOC_MAP_NORMAL);
AddDefineInteger(env, exports, "LOC_MAP_ROUGHNESS", LOC_MAP_ROUGHNESS);
AddDefineInteger(env, exports, "LOC_MAP_OCCLUSION", LOC_MAP_OCCLUSION);
AddDefineInteger(env, exports, "LOC_MAP_EMISSION", LOC_MAP_EMISSION);
AddDefineInteger(env, exports, "LOC_MAP_HEIGHT", LOC_MAP_HEIGHT);
AddDefineInteger(env, exports, "LOC_MAP_CUBEMAP", LOC_MAP_CUBEMAP);
AddDefineInteger(env, exports, "LOC_MAP_IRRADIANCE", LOC_MAP_IRRADIANCE);
AddDefineInteger(env, exports, "LOC_MAP_PREFILTER", LOC_MAP_PREFILTER);
AddDefineInteger(env, exports, "LOC_MAP_BRDF", LOC_MAP_BRDF);
AddDefineInteger(env, exports, "LOC_MAP_DIFFUSE", LOC_MAP_DIFFUSE);
AddDefineInteger(env, exports, "LOC_MAP_SPECULAR", LOC_MAP_SPECULAR);
AddDefineInteger(env, exports, "UNIFORM_FLOAT", UNIFORM_FLOAT);
AddDefineInteger(env, exports, "UNIFORM_VEC2", UNIFORM_VEC2);
AddDefineInteger(env, exports, "UNIFORM_VEC3", UNIFORM_VEC3);
AddDefineInteger(env, exports, "UNIFORM_VEC4", UNIFORM_VEC4);
AddDefineInteger(env, exports, "UNIFORM_INT", UNIFORM_INT);
AddDefineInteger(env, exports, "UNIFORM_IVEC2", UNIFORM_IVEC2);
AddDefineInteger(env, exports, "UNIFORM_IVEC3", UNIFORM_IVEC3);
AddDefineInteger(env, exports, "UNIFORM_IVEC4", UNIFORM_IVEC4);
AddDefineInteger(env, exports, "UNIFORM_SAMPLER2D", UNIFORM_SAMPLER2D);
AddDefineInteger(env, exports, "MAP_ALBEDO", MAP_ALBEDO);
AddDefineInteger(env, exports, "MAP_METALNESS", MAP_METALNESS);
AddDefineInteger(env, exports, "MAP_NORMAL", MAP_NORMAL);
AddDefineInteger(env, exports, "MAP_ROUGHNESS", MAP_ROUGHNESS);
AddDefineInteger(env, exports, "MAP_OCCLUSION", MAP_OCCLUSION);
AddDefineInteger(env, exports, "MAP_EMISSION", MAP_EMISSION);
AddDefineInteger(env, exports, "MAP_HEIGHT", MAP_HEIGHT);
AddDefineInteger(env, exports, "MAP_CUBEMAP", MAP_CUBEMAP);
AddDefineInteger(env, exports, "MAP_IRRADIANCE", MAP_IRRADIANCE);
AddDefineInteger(env, exports, "MAP_PREFILTER", MAP_PREFILTER);
AddDefineInteger(env, exports, "MAP_BRDF", MAP_BRDF);
AddDefineInteger(env, exports, "MAP_DIFFUSE", MAP_DIFFUSE);
AddDefineInteger(env, exports, "MAP_SPECULAR", MAP_SPECULAR);
AddDefineInteger(env, exports, "UNCOMPRESSED_GRAYSCALE", UNCOMPRESSED_GRAYSCALE);
AddDefineInteger(env, exports, "UNCOMPRESSED_GRAY_ALPHA", UNCOMPRESSED_GRAY_ALPHA);
AddDefineInteger(env, exports, "UNCOMPRESSED_R5G6B5", UNCOMPRESSED_R5G6B5);
AddDefineInteger(env, exports, "UNCOMPRESSED_R8G8B8", UNCOMPRESSED_R8G8B8);
AddDefineInteger(env, exports, "UNCOMPRESSED_R5G5B5A1", UNCOMPRESSED_R5G5B5A1);
AddDefineInteger(env, exports, "UNCOMPRESSED_R4G4B4A4", UNCOMPRESSED_R4G4B4A4);
AddDefineInteger(env, exports, "UNCOMPRESSED_R8G8B8A8", UNCOMPRESSED_R8G8B8A8);
AddDefineInteger(env, exports, "UNCOMPRESSED_R32", UNCOMPRESSED_R32);
AddDefineInteger(env, exports, "UNCOMPRESSED_R32G32B32", UNCOMPRESSED_R32G32B32);
AddDefineInteger(env, exports, "UNCOMPRESSED_R32G32B32A32", UNCOMPRESSED_R32G32B32A32);
AddDefineInteger(env, exports, "COMPRESSED_DXT1_RGB", COMPRESSED_DXT1_RGB);
AddDefineInteger(env, exports, "COMPRESSED_DXT1_RGBA", COMPRESSED_DXT1_RGBA);
AddDefineInteger(env, exports, "COMPRESSED_DXT3_RGBA", COMPRESSED_DXT3_RGBA);
AddDefineInteger(env, exports, "COMPRESSED_DXT5_RGBA", COMPRESSED_DXT5_RGBA);
AddDefineInteger(env, exports, "COMPRESSED_ETC1_RGB", COMPRESSED_ETC1_RGB);
AddDefineInteger(env, exports, "COMPRESSED_ETC2_RGB", COMPRESSED_ETC2_RGB);
AddDefineInteger(env, exports, "COMPRESSED_ETC2_EAC_RGBA", COMPRESSED_ETC2_EAC_RGBA);
AddDefineInteger(env, exports, "COMPRESSED_PVRT_RGB", COMPRESSED_PVRT_RGB);
AddDefineInteger(env, exports, "COMPRESSED_PVRT_RGBA", COMPRESSED_PVRT_RGBA);
AddDefineInteger(env, exports, "COMPRESSED_ASTC_4x4_RGBA", COMPRESSED_ASTC_4x4_RGBA);
AddDefineInteger(env, exports, "COMPRESSED_ASTC_8x8_RGBA", COMPRESSED_ASTC_8x8_RGBA);
AddDefineInteger(env, exports, "FILTER_POINT", FILTER_POINT);
AddDefineInteger(env, exports, "FILTER_BILINEAR", FILTER_BILINEAR);
AddDefineInteger(env, exports, "FILTER_TRILINEAR", FILTER_TRILINEAR);
AddDefineInteger(env, exports, "FILTER_ANISOTROPIC_4X", FILTER_ANISOTROPIC_4X);
AddDefineInteger(env, exports, "FILTER_ANISOTROPIC_8X", FILTER_ANISOTROPIC_8X);
AddDefineInteger(env, exports, "FILTER_ANISOTROPIC_16X", FILTER_ANISOTROPIC_16X);
AddDefineInteger(env, exports, "WRAP_REPEAT", WRAP_REPEAT);
AddDefineInteger(env, exports, "WRAP_CLAMP", WRAP_CLAMP);
AddDefineInteger(env, exports, "WRAP_MIRROR_REPEAT", WRAP_MIRROR_REPEAT);
AddDefineInteger(env, exports, "WRAP_MIRROR_CLAMP", WRAP_MIRROR_CLAMP);
AddDefineInteger(env, exports, "CUBEMAP_AUTO_DETECT", CUBEMAP_AUTO_DETECT);
AddDefineInteger(env, exports, "CUBEMAP_LINE_VERTICAL", CUBEMAP_LINE_VERTICAL);
AddDefineInteger(env, exports, "CUBEMAP_LINE_HORIZONTAL", CUBEMAP_LINE_HORIZONTAL);
AddDefineInteger(env, exports, "CUBEMAP_CROSS_THREE_BY_FOUR", CUBEMAP_CROSS_THREE_BY_FOUR);
AddDefineInteger(env, exports, "CUBEMAP_CROSS_FOUR_BY_THREE", CUBEMAP_CROSS_FOUR_BY_THREE);
AddDefineInteger(env, exports, "CUBEMAP_PANORAMA", CUBEMAP_PANORAMA);
AddDefineInteger(env, exports, "FONT_DEFAULT", FONT_DEFAULT);
AddDefineInteger(env, exports, "FONT_BITMAP", FONT_BITMAP);
AddDefineInteger(env, exports, "FONT_SDF", FONT_SDF);
AddDefineInteger(env, exports, "BLEND_ALPHA", BLEND_ALPHA);
AddDefineInteger(env, exports, "BLEND_ADDITIVE", BLEND_ADDITIVE);
AddDefineInteger(env, exports, "BLEND_MULTIPLIED", BLEND_MULTIPLIED);
AddDefineInteger(env, exports, "BLEND_ADD_COLORS", BLEND_ADD_COLORS);
AddDefineInteger(env, exports, "BLEND_SUBTRACT_COLORS", BLEND_SUBTRACT_COLORS);
AddDefineInteger(env, exports, "BLEND_CUSTOM", BLEND_CUSTOM);
AddDefineInteger(env, exports, "GESTURE_NONE", GESTURE_NONE);
AddDefineInteger(env, exports, "GESTURE_TAP", GESTURE_TAP);
AddDefineInteger(env, exports, "GESTURE_DOUBLETAP", GESTURE_DOUBLETAP);
AddDefineInteger(env, exports, "GESTURE_HOLD", GESTURE_HOLD);
AddDefineInteger(env, exports, "GESTURE_DRAG", GESTURE_DRAG);
AddDefineInteger(env, exports, "GESTURE_SWIPE_RIGHT", GESTURE_SWIPE_RIGHT);
AddDefineInteger(env, exports, "GESTURE_SWIPE_LEFT", GESTURE_SWIPE_LEFT);
AddDefineInteger(env, exports, "GESTURE_SWIPE_UP", GESTURE_SWIPE_UP);
AddDefineInteger(env, exports, "GESTURE_SWIPE_DOWN", GESTURE_SWIPE_DOWN);
AddDefineInteger(env, exports, "GESTURE_PINCH_IN", GESTURE_PINCH_IN);
AddDefineInteger(env, exports, "GESTURE_PINCH_OUT", GESTURE_PINCH_OUT);
AddDefineInteger(env, exports, "CAMERA_CUSTOM", CAMERA_CUSTOM);
AddDefineInteger(env, exports, "CAMERA_FREE", CAMERA_FREE);
AddDefineInteger(env, exports, "CAMERA_ORBITAL", CAMERA_ORBITAL);
AddDefineInteger(env, exports, "CAMERA_FIRST_PERSON", CAMERA_FIRST_PERSON);
AddDefineInteger(env, exports, "CAMERA_THIRD_PERSON", CAMERA_THIRD_PERSON);
AddDefineInteger(env, exports, "CAMERA_PERSPECTIVE", CAMERA_PERSPECTIVE);
AddDefineInteger(env, exports, "CAMERA_ORTHOGRAPHIC", CAMERA_ORTHOGRAPHIC);
AddDefineInteger(env, exports, "NPT_9PATCH", NPT_9PATCH);
AddDefineInteger(env, exports, "NPT_3PATCH_VERTICAL", NPT_3PATCH_VERTICAL);
AddDefineInteger(env, exports, "NPT_3PATCH_HORIZONTAL", NPT_3PATCH_HORIZONTAL);
}
void node_raylib_bindings_functions(Napi::Env& env, Napi::Object& exports) {
AddFunction(env, exports, "InitWindow", &InitWindow);
AddFunction(env, exports, "WindowShouldClose", &WindowShouldClose);
AddFunction(env, exports, "CloseWindow", &CloseWindow);
AddFunction(env, exports, "IsWindowReady", &IsWindowReady);
AddFunction(env, exports, "IsWindowFullscreen", &IsWindowFullscreen);
AddFunction(env, exports, "IsWindowHidden", &IsWindowHidden);
AddFunction(env, exports, "IsWindowMinimized", &IsWindowMinimized);
AddFunction(env, exports, "IsWindowMaximized", &IsWindowMaximized);
AddFunction(env, exports, "IsWindowFocused", &IsWindowFocused);
AddFunction(env, exports, "IsWindowResized", &IsWindowResized);
AddFunction(env, exports, "IsWindowState", &IsWindowState);
AddFunction(env, exports, "SetWindowState", &SetWindowState);
AddFunction(env, exports, "ClearWindowState", &ClearWindowState);
AddFunction(env, exports, "ToggleFullscreen", &ToggleFullscreen);
AddFunction(env, exports, "MaximizeWindow", &MaximizeWindow);
AddFunction(env, exports, "MinimizeWindow", &MinimizeWindow);
AddFunction(env, exports, "RestoreWindow", &RestoreWindow);
AddFunction(env, exports, "SetWindowIcon", &SetWindowIcon);
AddFunction(env, exports, "SetWindowTitle", &SetWindowTitle);
AddFunction(env, exports, "SetWindowPosition", &SetWindowPosition);
AddFunction(env, exports, "SetWindowMonitor", &SetWindowMonitor);
AddFunction(env, exports, "SetWindowMinSize", &SetWindowMinSize);
AddFunction(env, exports, "SetWindowSize", &SetWindowSize);
AddFunction(env, exports, "GetScreenWidth", &GetScreenWidth);
AddFunction(env, exports, "GetScreenHeight", &GetScreenHeight);
AddFunction(env, exports, "GetMonitorCount", &GetMonitorCount);
AddFunction(env, exports, "GetMonitorPosition", &GetMonitorPosition);
AddFunction(env, exports, "GetMonitorWidth", &GetMonitorWidth);
AddFunction(env, exports, "GetMonitorHeight", &GetMonitorHeight);
AddFunction(env, exports, "GetMonitorPhysicalWidth", &GetMonitorPhysicalWidth);
AddFunction(env, exports, "GetMonitorPhysicalHeight", &GetMonitorPhysicalHeight);
AddFunction(env, exports, "GetMonitorRefreshRate", &GetMonitorRefreshRate);
AddFunction(env, exports, "GetWindowPosition", &GetWindowPosition);
AddFunction(env, exports, "GetWindowScaleDPI", &GetWindowScaleDPI);
AddFunction(env, exports, "GetMonitorName", &GetMonitorName);
AddFunction(env, exports, "SetClipboardText", &SetClipboardText);
AddFunction(env, exports, "GetClipboardText", &GetClipboardText);
AddFunction(env, exports, "ShowCursor", &ShowCursor);
AddFunction(env, exports, "HideCursor", &HideCursor);
AddFunction(env, exports, "IsCursorHidden", &IsCursorHidden);
AddFunction(env, exports, "EnableCursor", &EnableCursor);
AddFunction(env, exports, "DisableCursor", &DisableCursor);
AddFunction(env, exports, "IsCursorOnScreen", &IsCursorOnScreen);
AddFunction(env, exports, "ClearBackground", &ClearBackground);
AddFunction(env, exports, "BeginDrawing", &BeginDrawing);
AddFunction(env, exports, "EndDrawing", &EndDrawing);
AddFunction(env, exports, "BeginMode2D", &BeginMode2D);
AddFunction(env, exports, "EndMode2D", &EndMode2D);
AddFunction(env, exports, "BeginMode3D", &BeginMode3D);
AddFunction(env, exports, "EndMode3D", &EndMode3D);
AddFunction(env, exports, "BeginTextureMode", &BeginTextureMode);
AddFunction(env, exports, "EndTextureMode", &EndTextureMode);
AddFunction(env, exports, "BeginScissorMode", &BeginScissorMode);
AddFunction(env, exports, "EndScissorMode", &EndScissorMode);
AddFunction(env, exports, "GetMouseRay", &GetMouseRay);
AddFunction(env, exports, "GetCameraMatrix", &GetCameraMatrix);
AddFunction(env, exports, "GetCameraMatrix2D", &GetCameraMatrix2D);
AddFunction(env, exports, "GetWorldToScreen", &GetWorldToScreen);
AddFunction(env, exports, "GetWorldToScreenEx", &GetWorldToScreenEx);
AddFunction(env, exports, "GetWorldToScreen2D", &GetWorldToScreen2D);
AddFunction(env, exports, "GetScreenToWorld2D", &GetScreenToWorld2D);
AddFunction(env, exports, "SetTargetFPS", &SetTargetFPS);
AddFunction(env, exports, "GetFPS", &GetFPS);
AddFunction(env, exports, "GetFrameTime", &GetFrameTime);
AddFunction(env, exports, "GetTime", &GetTime);
AddFunction(env, exports, "SetConfigFlags", &SetConfigFlags);
AddFunction(env, exports, "SetTraceLogLevel", &SetTraceLogLevel);
AddFunction(env, exports, "SetTraceLogExit", &SetTraceLogExit);
AddFunction(env, exports, "MemAlloc", &MemAlloc);
AddFunction(env, exports, "MemFree", &MemFree);
AddFunction(env, exports, "TakeScreenshot", &TakeScreenshot);
AddFunction(env, exports, "GetRandomValue", &GetRandomValue);
AddFunction(env, exports, "LoadFileData", &LoadFileData);
AddFunction(env, exports, "UnloadFileData", &UnloadFileData);
AddFunction(env, exports, "SaveFileData", &SaveFileData);
AddFunction(env, exports, "LoadFileText", &LoadFileText);
AddFunction(env, exports, "UnloadFileText", &UnloadFileText);
AddFunction(env, exports, "SaveFileText", &SaveFileText);
AddFunction(env, exports, "FileExists", &FileExists);
AddFunction(env, exports, "DirectoryExists", &DirectoryExists);
AddFunction(env, exports, "IsFileExtension", &IsFileExtension);
AddFunction(env, exports, "GetFileExtension", &GetFileExtension);
AddFunction(env, exports, "GetFileName", &GetFileName);
AddFunction(env, exports, "GetFileNameWithoutExt", &GetFileNameWithoutExt);
AddFunction(env, exports, "GetDirectoryPath", &GetDirectoryPath);
AddFunction(env, exports, "GetPrevDirectoryPath", &GetPrevDirectoryPath);
AddFunction(env, exports, "GetWorkingDirectory", &GetWorkingDirectory);
AddFunction(env, exports, "GetDirectoryFiles", &GetDirectoryFiles);
AddFunction(env, exports, "ClearDirectoryFiles", &ClearDirectoryFiles);
AddFunction(env, exports, "ChangeDirectory", &ChangeDirectory);
AddFunction(env, exports, "IsFileDropped", &IsFileDropped);
AddFunction(env, exports, "GetDroppedFiles", &GetDroppedFiles);
AddFunction(env, exports, "ClearDroppedFiles", &ClearDroppedFiles);
AddFunction(env, exports, "GetFileModTime", &GetFileModTime);
AddFunction(env, exports, "CompressData", &CompressData);
AddFunction(env, exports, "DecompressData", &DecompressData);
AddFunction(env, exports, "SaveStorageValue", &SaveStorageValue);
AddFunction(env, exports, "LoadStorageValue", &LoadStorageValue);
AddFunction(env, exports, "OpenURL", &OpenURL);
AddFunction(env, exports, "IsKeyPressed", &IsKeyPressed);
AddFunction(env, exports, "IsKeyDown", &IsKeyDown);
AddFunction(env, exports, "IsKeyReleased", &IsKeyReleased);
AddFunction(env, exports, "IsKeyUp", &IsKeyUp);
AddFunction(env, exports, "SetExitKey", &SetExitKey);
AddFunction(env, exports, "GetKeyPressed", &GetKeyPressed);
AddFunction(env, exports, "GetCharPressed", &GetCharPressed);
AddFunction(env, exports, "IsGamepadAvailable", &IsGamepadAvailable);
AddFunction(env, exports, "IsGamepadName", &IsGamepadName);
AddFunction(env, exports, "GetGamepadName", &GetGamepadName);
AddFunction(env, exports, "IsGamepadButtonPressed", &IsGamepadButtonPressed);
AddFunction(env, exports, "IsGamepadButtonDown", &IsGamepadButtonDown);
AddFunction(env, exports, "IsGamepadButtonReleased", &IsGamepadButtonReleased);
AddFunction(env, exports, "IsGamepadButtonUp", &IsGamepadButtonUp);
AddFunction(env, exports, "GetGamepadButtonPressed", &GetGamepadButtonPressed);
AddFunction(env, exports, "GetGamepadAxisCount", &GetGamepadAxisCount);
AddFunction(env, exports, "GetGamepadAxisMovement", &GetGamepadAxisMovement);
AddFunction(env, exports, "IsMouseButtonPressed", &IsMouseButtonPressed);
AddFunction(env, exports, "IsMouseButtonDown", &IsMouseButtonDown);
AddFunction(env, exports, "IsMouseButtonReleased", &IsMouseButtonReleased);
AddFunction(env, exports, "IsMouseButtonUp", &IsMouseButtonUp);
AddFunction(env, exports, "GetMouseX", &GetMouseX);
AddFunction(env, exports, "GetMouseY", &GetMouseY);
AddFunction(env, exports, "GetMousePosition", &GetMousePosition);
AddFunction(env, exports, "SetMousePosition", &SetMousePosition);
AddFunction(env, exports, "SetMouseOffset", &SetMouseOffset);
AddFunction(env, exports, "SetMouseScale", &SetMouseScale);
AddFunction(env, exports, "GetMouseWheelMove", &GetMouseWheelMove);
AddFunction(env, exports, "GetMouseCursor", &GetMouseCursor);
AddFunction(env, exports, "SetMouseCursor", &SetMouseCursor);
AddFunction(env, exports, "GetTouchX", &GetTouchX);
AddFunction(env, exports, "GetTouchY", &GetTouchY);
AddFunction(env, exports, "GetTouchPosition", &GetTouchPosition);
AddFunction(env, exports, "SetGesturesEnabled", &SetGesturesEnabled);
AddFunction(env, exports, "IsGestureDetected", &IsGestureDetected);
AddFunction(env, exports, "GetGestureDetected", &GetGestureDetected);
AddFunction(env, exports, "GetTouchPointsCount", &GetTouchPointsCount);
AddFunction(env, exports, "GetGestureHoldDuration", &GetGestureHoldDuration);
AddFunction(env, exports, "GetGestureDragVector", &GetGestureDragVector);
AddFunction(env, exports, "GetGestureDragAngle", &GetGestureDragAngle);
AddFunction(env, exports, "GetGesturePinchVector", &GetGesturePinchVector);
AddFunction(env, exports, "GetGesturePinchAngle", &GetGesturePinchAngle);
AddFunction(env, exports, "SetCameraMode", &SetCameraMode);
// AddFunction(env, exports, "UpdateCamera", &UpdateCamera);
AddFunction(env, exports, "SetCameraPanControl", &SetCameraPanControl);
AddFunction(env, exports, "SetCameraAltControl", &SetCameraAltControl);
AddFunction(env, exports, "SetCameraSmoothZoomControl", &SetCameraSmoothZoomControl);
AddFunction(env, exports, "SetCameraMoveControls", &SetCameraMoveControls);
AddFunction(env, exports, "DrawPixel", &DrawPixel);
AddFunction(env, exports, "DrawPixelV", &DrawPixelV);
AddFunction(env, exports, "DrawLine", &DrawLine);
AddFunction(env, exports, "DrawLineV", &DrawLineV);
AddFunction(env, exports, "DrawLineEx", &DrawLineEx);
AddFunction(env, exports, "DrawLineBezier", &DrawLineBezier);
AddFunction(env, exports, "DrawLineStrip", &DrawLineStrip);
AddFunction(env, exports, "DrawCircle", &DrawCircle);
AddFunction(env, exports, "DrawCircleSector", &DrawCircleSector);
AddFunction(env, exports, "DrawCircleSectorLines", &DrawCircleSectorLines);
AddFunction(env, exports, "DrawCircleGradient", &DrawCircleGradient);
AddFunction(env, exports, "DrawCircleV", &DrawCircleV);
AddFunction(env, exports, "DrawCircleLines", &DrawCircleLines);
AddFunction(env, exports, "DrawEllipse", &DrawEllipse);
AddFunction(env, exports, "DrawEllipseLines", &DrawEllipseLines);
AddFunction(env, exports, "DrawRing", &DrawRing);
AddFunction(env, exports, "DrawRingLines", &DrawRingLines);
AddFunction(env, exports, "DrawRectangle", &DrawRectangle);
AddFunction(env, exports, "DrawRectangleV", &DrawRectangleV);
AddFunction(env, exports, "DrawRectangleRec", &DrawRectangleRec);
AddFunction(env, exports, "DrawRectanglePro", &DrawRectanglePro);
AddFunction(env, exports, "DrawRectangleGradientV", &DrawRectangleGradientV);
AddFunction(env, exports, "DrawRectangleGradientH", &DrawRectangleGradientH);
AddFunction(env, exports, "DrawRectangleGradientEx", &DrawRectangleGradientEx);
AddFunction(env, exports, "DrawRectangleLines", &DrawRectangleLines);
AddFunction(env, exports, "DrawRectangleLinesEx", &DrawRectangleLinesEx);
AddFunction(env, exports, "DrawRectangleRounded", &DrawRectangleRounded);
AddFunction(env, exports, "DrawRectangleRoundedLines", &DrawRectangleRoundedLines);
AddFunction(env, exports, "DrawTriangle", &DrawTriangle);
AddFunction(env, exports, "DrawTriangleLines", &DrawTriangleLines);
AddFunction(env, exports, "DrawTriangleFan", &DrawTriangleFan);
AddFunction(env, exports, "DrawTriangleStrip", &DrawTriangleStrip);
AddFunction(env, exports, "DrawPoly", &DrawPoly);
AddFunction(env, exports, "DrawPolyLines", &DrawPolyLines);
AddFunction(env, exports, "CheckCollisionRecs", &CheckCollisionRecs);
AddFunction(env, exports, "CheckCollisionCircles", &CheckCollisionCircles);
AddFunction(env, exports, "CheckCollisionCircleRec", &CheckCollisionCircleRec);
AddFunction(env, exports, "CheckCollisionPointRec", &CheckCollisionPointRec);
AddFunction(env, exports, "CheckCollisionPointCircle", &CheckCollisionPointCircle);
AddFunction(env, exports, "CheckCollisionPointTriangle", &CheckCollisionPointTriangle);
AddFunction(env, exports, "CheckCollisionLines", &CheckCollisionLines);
AddFunction(env, exports, "GetCollisionRec", &GetCollisionRec);
AddFunction(env, exports, "LoadImage", &LoadImage);
AddFunction(env, exports, "LoadImageRaw", &LoadImageRaw);
AddFunction(env, exports, "LoadImageAnim", &LoadImageAnim);
AddFunction(env, exports, "LoadImageFromMemory", &LoadImageFromMemory);
AddFunction(env, exports, "UnloadImage", &UnloadImage);
AddFunction(env, exports, "ExportImage", &ExportImage);
AddFunction(env, exports, "ExportImageAsCode", &ExportImageAsCode);
AddFunction(env, exports, "GenImageColor", &GenImageColor);
AddFunction(env, exports, "GenImageGradientV", &GenImageGradientV);
AddFunction(env, exports, "GenImageGradientH", &GenImageGradientH);
AddFunction(env, exports, "GenImageGradientRadial", &GenImageGradientRadial);
AddFunction(env, exports, "GenImageChecked", &GenImageChecked);
AddFunction(env, exports, "GenImageWhiteNoise", &GenImageWhiteNoise);
AddFunction(env, exports, "GenImagePerlinNoise", &GenImagePerlinNoise);
AddFunction(env, exports, "GenImageCellular", &GenImageCellular);
AddFunction(env, exports, "ImageCopy", &ImageCopy);
AddFunction(env, exports, "ImageFromImage", &ImageFromImage);
AddFunction(env, exports, "ImageText", &ImageText);
AddFunction(env, exports, "ImageTextEx", &ImageTextEx);
AddFunction(env, exports, "ImageFormat", &ImageFormat);
AddFunction(env, exports, "ImageToPOT", &ImageToPOT);
AddFunction(env, exports, "ImageCrop", &ImageCrop);
AddFunction(env, exports, "ImageAlphaCrop", &ImageAlphaCrop);
AddFunction(env, exports, "ImageAlphaClear", &ImageAlphaClear);
AddFunction(env, exports, "ImageAlphaMask", &ImageAlphaMask);
AddFunction(env, exports, "ImageAlphaPremultiply", &ImageAlphaPremultiply);
AddFunction(env, exports, "ImageResize", &ImageResize);
AddFunction(env, exports, "ImageResizeNN", &ImageResizeNN);
AddFunction(env, exports, "ImageResizeCanvas", &ImageResizeCanvas);
AddFunction(env, exports, "ImageMipmaps", &ImageMipmaps);
AddFunction(env, exports, "ImageDither", &ImageDither);
AddFunction(env, exports, "ImageFlipVertical", &ImageFlipVertical);
AddFunction(env, exports, "ImageFlipHorizontal", &ImageFlipHorizontal);
AddFunction(env, exports, "ImageRotateCW", &ImageRotateCW);
AddFunction(env, exports, "ImageRotateCCW", &ImageRotateCCW);
AddFunction(env, exports, "ImageColorTint", &ImageColorTint);
AddFunction(env, exports, "ImageColorInvert", &ImageColorInvert);
AddFunction(env, exports, "ImageColorGrayscale", &ImageColorGrayscale);
AddFunction(env, exports, "ImageColorContrast", &ImageColorContrast);
AddFunction(env, exports, "ImageColorBrightness", &ImageColorBrightness);
AddFunction(env, exports, "ImageColorReplace", &ImageColorReplace);
AddFunction(env, exports, "LoadImageColors", &LoadImageColors);
AddFunction(env, exports, "LoadImagePalette", &LoadImagePalette);
AddFunction(env, exports, "UnloadImageColors", &UnloadImageColors);
AddFunction(env, exports, "UnloadImagePalette", &UnloadImagePalette);
AddFunction(env, exports, "GetImageAlphaBorder", &GetImageAlphaBorder);
AddFunction(env, exports, "ImageClearBackground", &ImageClearBackground);
AddFunction(env, exports, "ImageDrawPixel", &ImageDrawPixel);
AddFunction(env, exports, "ImageDrawPixelV", &ImageDrawPixelV);
AddFunction(env, exports, "ImageDrawLine", &ImageDrawLine);
AddFunction(env, exports, "ImageDrawLineV", &ImageDrawLineV);
AddFunction(env, exports, "ImageDrawCircle", &ImageDrawCircle);
AddFunction(env, exports, "ImageDrawCircleV", &ImageDrawCircleV);
AddFunction(env, exports, "ImageDrawRectangle", &ImageDrawRectangle);
AddFunction(env, exports, "ImageDrawRectangleV", &ImageDrawRectangleV);
AddFunction(env, exports, "ImageDrawRectangleRec", &ImageDrawRectangleRec);
AddFunction(env, exports, "ImageDrawRectangleLines", &ImageDrawRectangleLines);
AddFunction(env, exports, "ImageDraw", &ImageDraw);
AddFunction(env, exports, "ImageDrawText", &ImageDrawText);
AddFunction(env, exports, "ImageDrawTextEx", &ImageDrawTextEx);
AddFunction(env, exports, "LoadTexture", &LoadTexture);
AddFunction(env, exports, "LoadTextureFromImage", &LoadTextureFromImage);
AddFunction(env, exports, "LoadTextureCubemap", &LoadTextureCubemap);
AddFunction(env, exports, "LoadRenderTexture", &LoadRenderTexture);
AddFunction(env, exports, "UnloadTexture", &UnloadTexture);
AddFunction(env, exports, "UnloadRenderTexture", &UnloadRenderTexture);
AddFunction(env, exports, "UpdateTexture", &UpdateTexture);
AddFunction(env, exports, "UpdateTextureRec", &UpdateTextureRec);
AddFunction(env, exports, "GetTextureData", &GetTextureData);
AddFunction(env, exports, "GetScreenData", &GetScreenData);
AddFunction(env, exports, "GenTextureMipmaps", &GenTextureMipmaps);
AddFunction(env, exports, "SetTextureFilter", &SetTextureFilter);
AddFunction(env, exports, "SetTextureWrap", &SetTextureWrap);
AddFunction(env, exports, "DrawTexture", &DrawTexture);
AddFunction(env, exports, "DrawTextureV", &DrawTextureV);
AddFunction(env, exports, "DrawTextureEx", &DrawTextureEx);
AddFunction(env, exports, "DrawTextureRec", &DrawTextureRec);
AddFunction(env, exports, "DrawTextureQuad", &DrawTextureQuad);
AddFunction(env, exports, "DrawTextureTiled", &DrawTextureTiled);
AddFunction(env, exports, "DrawTexturePro", &DrawTexturePro);
AddFunction(env, exports, "DrawTextureNPatch", &DrawTextureNPatch);
AddFunction(env, exports, "Fade", &Fade);
AddFunction(env, exports, "ColorToInt", &ColorToInt);
AddFunction(env, exports, "ColorNormalize", &ColorNormalize);
AddFunction(env, exports, "ColorFromNormalized", &ColorFromNormalized);
AddFunction(env, exports, "ColorToHSV", &ColorToHSV);
AddFunction(env, exports, "ColorFromHSV", &ColorFromHSV);
AddFunction(env, exports, "ColorAlpha", &ColorAlpha);
AddFunction(env, exports, "ColorAlphaBlend", &ColorAlphaBlend);
AddFunction(env, exports, "GetColor", &GetColor);
AddFunction(env, exports, "GetPixelColor", &GetPixelColor);
AddFunction(env, exports, "SetPixelColor", &SetPixelColor);
AddFunction(env, exports, "GetPixelDataSize", &GetPixelDataSize);
AddFunction(env, exports, "GetFontDefault", &GetFontDefault);
AddFunction(env, exports, "LoadFont", &LoadFont);
AddFunction(env, exports, "LoadFontEx", &LoadFontEx);
AddFunction(env, exports, "LoadFontFromImage", &LoadFontFromImage);
AddFunction(env, exports, "LoadFontFromMemory", &LoadFontFromMemory);
AddFunction(env, exports, "LoadFontData", &LoadFontData);
AddFunction(env, exports, "GenImageFontAtlas", &GenImageFontAtlas);
AddFunction(env, exports, "UnloadFontData", &UnloadFontData);
AddFunction(env, exports, "UnloadFont", &UnloadFont);
AddFunction(env, exports, "DrawFPS", &DrawFPS);
AddFunction(env, exports, "DrawText", &DrawText);
AddFunction(env, exports, "DrawTextEx", &DrawTextEx);
AddFunction(env, exports, "DrawTextRec", &DrawTextRec);
AddFunction(env, exports, "DrawTextRecEx", &DrawTextRecEx);
AddFunction(env, exports, "DrawTextCodepoint", &DrawTextCodepoint);
AddFunction(env, exports, "MeasureText", &MeasureText);
AddFunction(env, exports, "MeasureTextEx", &MeasureTextEx);
AddFunction(env, exports, "GetGlyphIndex", &GetGlyphIndex);
AddFunction(env, exports, "TextCopy", &TextCopy);
AddFunction(env, exports, "TextIsEqual", &TextIsEqual);
AddFunction(env, exports, "TextLength", &TextLength);
// AddFunction(env, exports, "TextFormat", &TextFormat);
AddFunction(env, exports, "TextSubtext", &TextSubtext);
AddFunction(env, exports, "TextReplace", &TextReplace);
AddFunction(env, exports, "TextInsert", &TextInsert);
AddFunction(env, exports, "TextJoin", &TextJoin);
AddFunction(env, exports, "TextSplit", &TextSplit);
AddFunction(env, exports, "TextAppend", &TextAppend);
AddFunction(env, exports, "TextFindIndex", &TextFindIndex);
AddFunction(env, exports, "TextToUpper", &TextToUpper);
AddFunction(env, exports, "TextToLower", &TextToLower);
AddFunction(env, exports, "TextToPascal", &TextToPascal);
AddFunction(env, exports, "TextToInteger", &TextToInteger);
AddFunction(env, exports, "TextToUtf8", &TextToUtf8);
AddFunction(env, exports, "GetCodepoints", &GetCodepoints);
AddFunction(env, exports, "GetCodepointsCount", &GetCodepointsCount);
AddFunction(env, exports, "GetNextCodepoint", &GetNextCodepoint);
AddFunction(env, exports, "CodepointToUtf8", &CodepointToUtf8);
AddFunction(env, exports, "DrawLine3D", &DrawLine3D);
AddFunction(env, exports, "DrawPoint3D", &DrawPoint3D);
AddFunction(env, exports, "DrawCircle3D", &DrawCircle3D);
AddFunction(env, exports, "DrawTriangle3D", &DrawTriangle3D);
AddFunction(env, exports, "DrawTriangleStrip3D", &DrawTriangleStrip3D);
AddFunction(env, exports, "DrawCube", &DrawCube);
AddFunction(env, exports, "DrawCubeV", &DrawCubeV);
AddFunction(env, exports, "DrawCubeWires", &DrawCubeWires);
AddFunction(env, exports, "DrawCubeWiresV", &DrawCubeWiresV);
AddFunction(env, exports, "DrawCubeTexture", &DrawCubeTexture);
AddFunction(env, exports, "DrawSphere", &DrawSphere);
AddFunction(env, exports, "DrawSphereEx", &DrawSphereEx);
AddFunction(env, exports, "DrawSphereWires", &DrawSphereWires);
AddFunction(env, exports, "DrawCylinder", &DrawCylinder);
AddFunction(env, exports, "DrawCylinderWires", &DrawCylinderWires);
AddFunction(env, exports, "DrawPlane", &DrawPlane);
AddFunction(env, exports, "DrawRay", &DrawRay);
AddFunction(env, exports, "DrawGrid", &DrawGrid);
AddFunction(env, exports, "DrawGizmo", &DrawGizmo);
// AddFunction(env, exports, "LoadModel", &LoadModel);
// AddFunction(env, exports, "LoadModelFromMesh", &LoadModelFromMesh);
// AddFunction(env, exports, "UnloadModel", &UnloadModel);
// AddFunction(env, exports, "UnloadModelKeepMeshes", &UnloadModelKeepMeshes);
// AddFunction(env, exports, "LoadMeshes", &LoadMeshes);
// AddFunction(env, exports, "UnloadMesh", &UnloadMesh);
// AddFunction(env, exports, "ExportMesh", &ExportMesh);
// AddFunction(env, exports, "LoadMaterials", &LoadMaterials);
// AddFunction(env, exports, "LoadMaterialDefault", &LoadMaterialDefault);
// AddFunction(env, exports, "UnloadMaterial", &UnloadMaterial);
// AddFunction(env, exports, "SetMaterialTexture", &SetMaterialTexture);
// AddFunction(env, exports, "SetModelMeshMaterial", &SetModelMeshMaterial);
// AddFunction(env, exports, "LoadModelAnimations", &LoadModelAnimations);
// AddFunction(env, exports, "UpdateModelAnimation", &UpdateModelAnimation);
// AddFunction(env, exports, "UnloadModelAnimation", &UnloadModelAnimation);
// AddFunction(env, exports, "IsModelAnimationValid", &IsModelAnimationValid);
// AddFunction(env, exports, "GenMeshPoly", &GenMeshPoly);
// AddFunction(env, exports, "GenMeshPlane", &GenMeshPlane);
// AddFunction(env, exports, "GenMeshCube", &GenMeshCube);
// AddFunction(env, exports, "GenMeshSphere", &GenMeshSphere);
// AddFunction(env, exports, "GenMeshHemiSphere", &GenMeshHemiSphere);
// AddFunction(env, exports, "GenMeshCylinder", &GenMeshCylinder);
// AddFunction(env, exports, "GenMeshTorus", &GenMeshTorus);
// AddFunction(env, exports, "GenMeshKnot", &GenMeshKnot);
// AddFunction(env, exports, "GenMeshHeightmap", &GenMeshHeightmap);
// AddFunction(env, exports, "GenMeshCubicmap", &GenMeshCubicmap);
// AddFunction(env, exports, "MeshBoundingBox", &MeshBoundingBox);
// AddFunction(env, exports, "MeshTangents", &MeshTangents);
// AddFunction(env, exports, "MeshBinormals", &MeshBinormals);
// AddFunction(env, exports, "MeshNormalsSmooth", &MeshNormalsSmooth);
// AddFunction(env, exports, "DrawModel", &DrawModel);
// AddFunction(env, exports, "DrawModelEx", &DrawModelEx);
// AddFunction(env, exports, "DrawModelWires", &DrawModelWires);
// AddFunction(env, exports, "DrawModelWiresEx", &DrawModelWiresEx);
AddFunction(env, exports, "DrawBoundingBox", &DrawBoundingBox);
AddFunction(env, exports, "DrawBillboard", &DrawBillboard);
AddFunction(env, exports, "DrawBillboardRec", &DrawBillboardRec);
AddFunction(env, exports, "CheckCollisionSpheres", &CheckCollisionSpheres);
AddFunction(env, exports, "CheckCollisionBoxes", &CheckCollisionBoxes);
AddFunction(env, exports, "CheckCollisionBoxSphere", &CheckCollisionBoxSphere);
AddFunction(env, exports, "CheckCollisionRaySphere", &CheckCollisionRaySphere);
AddFunction(env, exports, "CheckCollisionRaySphereEx", &CheckCollisionRaySphereEx);
AddFunction(env, exports, "CheckCollisionRayBox", &CheckCollisionRayBox);
// AddFunction(env, exports, "GetCollisionRayMesh", &GetCollisionRayMesh);
// AddFunction(env, exports, "GetCollisionRayModel", &GetCollisionRayModel);
AddFunction(env, exports, "GetCollisionRayTriangle", &GetCollisionRayTriangle);
AddFunction(env, exports, "GetCollisionRayGround", &GetCollisionRayGround);
AddFunction(env, exports, "LoadShader", &LoadShader);
AddFunction(env, exports, "LoadShaderCode", &LoadShaderCode);
AddFunction(env, exports, "UnloadShader", &UnloadShader);
AddFunction(env, exports, "GetShaderDefault", &GetShaderDefault);
AddFunction(env, exports, "GetTextureDefault", &GetTextureDefault);
AddFunction(env, exports, "GetShapesTexture", &GetShapesTexture);
AddFunction(env, exports, "GetShapesTextureRec", &GetShapesTextureRec);
AddFunction(env, exports, "SetShapesTexture", &SetShapesTexture);
AddFunction(env, exports, "GetShaderLocation", &GetShaderLocation);
AddFunction(env, exports, "GetShaderLocationAttrib", &GetShaderLocationAttrib);
// AddFunction(env, exports, "SetShaderValue", &SetShaderValue);
// AddFunction(env, exports, "SetShaderValueV", &SetShaderValueV);
AddFunction(env, exports, "SetShaderValueMatrix", &SetShaderValueMatrix);
AddFunction(env, exports, "SetShaderValueTexture", &SetShaderValueTexture);
AddFunction(env, exports, "SetMatrixProjection", &SetMatrixProjection);
AddFunction(env, exports, "SetMatrixModelview", &SetMatrixModelview);
AddFunction(env, exports, "GetMatrixModelview", &GetMatrixModelview);
AddFunction(env, exports, "GetMatrixProjection", &GetMatrixProjection);
AddFunction(env, exports, "GenTextureCubemap", &GenTextureCubemap);
AddFunction(env, exports, "GenTextureIrradiance", &GenTextureIrradiance);
AddFunction(env, exports, "GenTexturePrefilter", &GenTexturePrefilter);
AddFunction(env, exports, "GenTextureBRDF", &GenTextureBRDF);
AddFunction(env, exports, "BeginShaderMode", &BeginShaderMode);
AddFunction(env, exports, "EndShaderMode", &EndShaderMode);
AddFunction(env, exports, "BeginBlendMode", &BeginBlendMode);
AddFunction(env, exports, "EndBlendMode", &EndBlendMode);
AddFunction(env, exports, "InitVrSimulator", &InitVrSimulator);
AddFunction(env, exports, "CloseVrSimulator", &CloseVrSimulator);
// AddFunction(env, exports, "UpdateVrTracking", &UpdateVrTracking);
AddFunction(env, exports, "SetVrConfiguration", &SetVrConfiguration);
AddFunction(env, exports, "IsVrSimulatorReady", &IsVrSimulatorReady);
AddFunction(env, exports, "ToggleVrMode", &ToggleVrMode);
AddFunction(env, exports, "BeginVrDrawing", &BeginVrDrawing);
AddFunction(env, exports, "EndVrDrawing", &EndVrDrawing);
AddFunction(env, exports, "InitAudioDevice", &InitAudioDevice);
AddFunction(env, exports, "CloseAudioDevice", &CloseAudioDevice);
AddFunction(env, exports, "IsAudioDeviceReady", &IsAudioDeviceReady);
AddFunction(env, exports, "SetMasterVolume", &SetMasterVolume);
AddFunction(env, exports, "LoadWave", &LoadWave);
AddFunction(env, exports, "LoadWaveFromMemory", &LoadWaveFromMemory);
AddFunction(env, exports, "LoadSound", &LoadSound);
AddFunction(env, exports, "LoadSoundFromWave", &LoadSoundFromWave);
AddFunction(env, exports, "UpdateSound", &UpdateSound);
AddFunction(env, exports, "UnloadWave", &UnloadWave);
AddFunction(env, exports, "UnloadSound", &UnloadSound);
AddFunction(env, exports, "ExportWave", &ExportWave);
AddFunction(env, exports, "ExportWaveAsCode", &ExportWaveAsCode);
AddFunction(env, exports, "PlaySound", &PlaySound);
AddFunction(env, exports, "StopSound", &StopSound);
AddFunction(env, exports, "PauseSound", &PauseSound);
AddFunction(env, exports, "ResumeSound", &ResumeSound);
AddFunction(env, exports, "PlaySoundMulti", &PlaySoundMulti);
AddFunction(env, exports, "StopSoundMulti", &StopSoundMulti);
AddFunction(env, exports, "GetSoundsPlaying", &GetSoundsPlaying);
AddFunction(env, exports, "IsSoundPlaying", &IsSoundPlaying);
AddFunction(env, exports, "SetSoundVolume", &SetSoundVolume);
AddFunction(env, exports, "SetSoundPitch", &SetSoundPitch);
AddFunction(env, exports, "WaveFormat", &WaveFormat);
AddFunction(env, exports, "WaveCopy", &WaveCopy);
AddFunction(env, exports, "WaveCrop", &WaveCrop);
AddFunction(env, exports, "LoadWaveSamples", &LoadWaveSamples);
AddFunction(env, exports, "UnloadWaveSamples", &UnloadWaveSamples);
AddFunction(env, exports, "LoadMusicStream", &LoadMusicStream);
AddFunction(env, exports, "UnloadMusicStream", &UnloadMusicStream);
AddFunction(env, exports, "PlayMusicStream", &PlayMusicStream);
AddFunction(env, exports, "UpdateMusicStream", &UpdateMusicStream);
AddFunction(env, exports, "StopMusicStream", &StopMusicStream);
AddFunction(env, exports, "PauseMusicStream", &PauseMusicStream);
AddFunction(env, exports, "ResumeMusicStream", &ResumeMusicStream);
AddFunction(env, exports, "IsMusicPlaying", &IsMusicPlaying);
AddFunction(env, exports, "SetMusicVolume", &SetMusicVolume);
AddFunction(env, exports, "SetMusicPitch", &SetMusicPitch);
AddFunction(env, exports, "GetMusicTimeLength", &GetMusicTimeLength);
AddFunction(env, exports, "GetMusicTimePlayed", &GetMusicTimePlayed);
AddFunction(env, exports, "InitAudioStream", &InitAudioStream);
AddFunction(env, exports, "UpdateAudioStream", &UpdateAudioStream);
AddFunction(env, exports, "CloseAudioStream", &CloseAudioStream);
AddFunction(env, exports, "IsAudioStreamProcessed", &IsAudioStreamProcessed);
AddFunction(env, exports, "PlayAudioStream", &PlayAudioStream);
AddFunction(env, exports, "PauseAudioStream", &PauseAudioStream);
AddFunction(env, exports, "ResumeAudioStream", &ResumeAudioStream);
AddFunction(env, exports, "IsAudioStreamPlaying", &IsAudioStreamPlaying);
AddFunction(env, exports, "StopAudioStream", &StopAudioStream);
AddFunction(env, exports, "SetAudioStreamVolume", &SetAudioStreamVolume);
AddFunction(env, exports, "SetAudioStreamPitch", &SetAudioStreamPitch);
AddFunction(env, exports, "SetAudioStreamBufferSizeDefault", &SetAudioStreamBufferSizeDefault);
}
void node_raylib_bindings(Napi::Env& env, Napi::Object& exports) {
node_raylib_bindings_defines(env, exports);
node_raylib_bindings_functions(env, exports);
}
#endif
| 65.733418 | 101 | 0.77949 | [
"object"
] |
cf2e304d19e9aaefb07365c646180d2296fa02b7 | 12,052 | h | C | libraries/shared/src/SpatiallyNestable.h | neurealdesktop/hifi | 22c2954423dd352a0703bb400722bedb12e8271f | [
"Apache-2.0"
] | null | null | null | libraries/shared/src/SpatiallyNestable.h | neurealdesktop/hifi | 22c2954423dd352a0703bb400722bedb12e8271f | [
"Apache-2.0"
] | null | null | null | libraries/shared/src/SpatiallyNestable.h | neurealdesktop/hifi | 22c2954423dd352a0703bb400722bedb12e8271f | [
"Apache-2.0"
] | null | null | null | //
// SpatiallyNestable.h
// libraries/shared/src/
//
// Created by Seth Alves on 2015-10-18
// Copyright 2015 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#ifndef hifi_SpatiallyNestable_h
#define hifi_SpatiallyNestable_h
#include <QUuid>
#include "Transform.h"
#include "AACube.h"
#include "SpatialParentFinder.h"
#include "shared/ReadWriteLockable.h"
class SpatiallyNestable;
using SpatiallyNestableWeakPointer = std::weak_ptr<SpatiallyNestable>;
using SpatiallyNestableWeakConstPointer = std::weak_ptr<const SpatiallyNestable>;
using SpatiallyNestablePointer = std::shared_ptr<SpatiallyNestable>;
using SpatiallyNestableConstPointer = std::shared_ptr<const SpatiallyNestable>;
static const uint16_t INVALID_JOINT_INDEX = -1;
enum class NestableType {
Entity,
Avatar,
Overlay
};
class SpatiallyNestable : public std::enable_shared_from_this<SpatiallyNestable> {
public:
SpatiallyNestable(NestableType nestableType, QUuid id);
virtual ~SpatiallyNestable();
virtual const QUuid getID() const;
virtual void setID(const QUuid& id);
virtual QString getName() const { return "SpatiallyNestable"; }
virtual const QUuid getParentID() const;
virtual void setParentID(const QUuid& parentID);
virtual quint16 getParentJointIndex() const { return _parentJointIndex; }
virtual void setParentJointIndex(quint16 parentJointIndex);
static glm::vec3 worldToLocal(const glm::vec3& position, const QUuid& parentID, int parentJointIndex,
bool scalesWithParent, bool& success);
static glm::quat worldToLocal(const glm::quat& orientation, const QUuid& parentID, int parentJointIndex,
bool scalesWithParent, bool& success);
static glm::vec3 worldToLocalVelocity(const glm::vec3& velocity, const QUuid& parentID,
int parentJointIndex, bool scalesWithParent, bool& success);
static glm::vec3 worldToLocalAngularVelocity(const glm::vec3& angularVelocity, const QUuid& parentID,
int parentJointIndex, bool scalesWithParent, bool& success);
static glm::vec3 worldToLocalDimensions(const glm::vec3& dimensions, const QUuid& parentID,
int parentJointIndex, bool scalesWithParent, bool& success);
static glm::vec3 localToWorld(const glm::vec3& position, const QUuid& parentID, int parentJointIndex,
bool scalesWithParent, bool& success);
static glm::quat localToWorld(const glm::quat& orientation, const QUuid& parentID, int parentJointIndex,
bool scalesWithParent, bool& success);
static glm::vec3 localToWorldVelocity(const glm::vec3& velocity,
const QUuid& parentID, int parentJointIndex, bool scalesWithParent, bool& success);
static glm::vec3 localToWorldAngularVelocity(const glm::vec3& angularVelocity,
const QUuid& parentID, int parentJointIndex,
bool scalesWithParent, bool& success);
static glm::vec3 localToWorldDimensions(const glm::vec3& dimensions, const QUuid& parentID,
int parentJointIndex, bool scalesWithParent, bool& success);
static QString nestableTypeToString(NestableType nestableType);
virtual bool isParentPathComplete(int depth = 0) const;
// world frame
virtual const Transform getTransform(bool& success, int depth = 0) const;
virtual const Transform getTransform() const;
virtual void setTransform(const Transform& transform, bool& success);
virtual bool setTransform(const Transform& transform);
virtual Transform getParentTransform(bool& success, int depth = 0) const;
void setWorldTransform(const glm::vec3& position, const glm::quat& orientation);
virtual glm::vec3 getWorldPosition(bool& success) const;
virtual glm::vec3 getWorldPosition() const;
virtual void setWorldPosition(const glm::vec3& position, bool& success, bool tellPhysics = true);
virtual void setWorldPosition(const glm::vec3& position);
virtual glm::quat getWorldOrientation(bool& success) const;
virtual glm::quat getWorldOrientation() const;
virtual glm::quat getWorldOrientation(int jointIndex, bool& success) const;
virtual void setWorldOrientation(const glm::quat& orientation, bool& success, bool tellPhysics = true);
virtual void setWorldOrientation(const glm::quat& orientation);
virtual glm::vec3 getWorldVelocity(bool& success) const;
virtual glm::vec3 getWorldVelocity() const;
virtual void setWorldVelocity(const glm::vec3& velocity, bool& success);
virtual void setWorldVelocity(const glm::vec3& velocity);
virtual glm::vec3 getParentVelocity(bool& success) const;
virtual glm::vec3 getWorldAngularVelocity(bool& success) const;
virtual glm::vec3 getWorldAngularVelocity() const;
virtual void setWorldAngularVelocity(const glm::vec3& angularVelocity, bool& success);
virtual void setWorldAngularVelocity(const glm::vec3& angularVelocity);
virtual glm::vec3 getParentAngularVelocity(bool& success) const;
virtual AACube getMaximumAACube(bool& success) const;
virtual AACube calculateInitialQueryAACube(bool& success);
virtual void setQueryAACube(const AACube& queryAACube);
virtual bool queryAACubeNeedsUpdate() const;
virtual bool shouldPuffQueryAACube() const { return false; }
bool updateQueryAACube();
void forceQueryAACubeUpdate() { _queryAACubeSet = false; }
virtual AACube getQueryAACube(bool& success) const;
virtual AACube getQueryAACube() const;
virtual glm::vec3 getSNScale() const;
virtual glm::vec3 getSNScale(bool& success) const;
virtual void setSNScale(const glm::vec3& scale);
virtual void setSNScale(const glm::vec3& scale, bool& success);
// get world-frame values for a specific joint
virtual const Transform getTransform(int jointIndex, bool& success, int depth = 0) const;
virtual glm::vec3 getWorldPosition(int jointIndex, bool& success) const;
virtual glm::vec3 getSNScale(int jointIndex, bool& success) const;
// object's parent's frame
virtual Transform getLocalTransform() const;
virtual void setLocalTransform(const Transform& transform);
virtual glm::vec3 getLocalPosition() const;
virtual void setLocalPosition(const glm::vec3& position, bool tellPhysics = true);
virtual glm::quat getLocalOrientation() const;
virtual void setLocalOrientation(const glm::quat& orientation);
virtual glm::vec3 getLocalVelocity() const;
virtual void setLocalVelocity(const glm::vec3& velocity);
virtual glm::vec3 getLocalAngularVelocity() const;
virtual void setLocalAngularVelocity(const glm::vec3& angularVelocity);
virtual glm::vec3 getLocalSNScale() const;
virtual void setLocalSNScale(const glm::vec3& scale);
virtual bool getScalesWithParent() const { return false; }
virtual glm::vec3 scaleForChildren() const { return glm::vec3(1.0f); }
QList<SpatiallyNestablePointer> getChildren() const;
bool hasChildren() const;
NestableType getNestableType() const { return _nestableType; }
// this object's frame
virtual const Transform getAbsoluteJointTransformInObjectFrame(int jointIndex) const;
virtual glm::vec3 getAbsoluteJointScaleInObjectFrame(int index) const { return glm::vec3(1.0f); }
virtual glm::quat getAbsoluteJointRotationInObjectFrame(int index) const { return glm::quat(); }
virtual glm::vec3 getAbsoluteJointTranslationInObjectFrame(int index) const { return glm::vec3(); }
virtual int getJointParent(int index) const { return -1; }
virtual bool setAbsoluteJointRotationInObjectFrame(int index, const glm::quat& rotation) { return false; }
virtual bool setAbsoluteJointTranslationInObjectFrame(int index, const glm::vec3& translation) {return false; }
virtual glm::quat getLocalJointRotation(int index) const {return glm::quat(); }
virtual glm::vec3 getLocalJointTranslation(int index) const {return glm::vec3(); }
virtual bool setLocalJointRotation(int index, const glm::quat& rotation) { return false; }
virtual bool setLocalJointTranslation(int index, const glm::vec3& translation) { return false; }
SpatiallyNestablePointer getThisPointer() const;
using ChildLambda = std::function<void(const SpatiallyNestablePointer&)>;
using ChildLambdaTest = std::function<bool(const SpatiallyNestablePointer&)>;
void forEachChild(const ChildLambda& actor) const;
void forEachDescendant(const ChildLambda& actor) const;
void forEachChildTest(const ChildLambdaTest& actor) const;
void forEachDescendantTest(const ChildLambdaTest& actor) const;
void die() { _isDead = true; }
bool isDead() const { return _isDead; }
bool isParentIDValid() const { bool success = false; getParentPointer(success); return success; }
virtual SpatialParentTree* getParentTree() const { return nullptr; }
bool hasAncestorOfType(NestableType nestableType, int depth = 0) const;
const QUuid findAncestorOfType(NestableType nestableType, int depth = 0) const;
SpatiallyNestablePointer getParentPointer(bool& success) const;
static SpatiallyNestablePointer findByID(QUuid id, bool& success);
void getLocalTransformAndVelocities(Transform& localTransform,
glm::vec3& localVelocity,
glm::vec3& localAngularVelocity) const;
void setLocalTransformAndVelocities(
const Transform& localTransform,
const glm::vec3& localVelocity,
const glm::vec3& localAngularVelocity);
bool scaleChangedSince(quint64 time) const { return _scaleChanged > time; }
bool tranlationChangedSince(quint64 time) const { return _translationChanged > time; }
bool rotationChangedSince(quint64 time) const { return _rotationChanged > time; }
void dump(const QString& prefix = "") const;
virtual void locationChanged(bool tellPhysics = true); // called when a this object's location has changed
virtual void dimensionsChanged() { _queryAACubeSet = false; } // called when a this object's dimensions have changed
virtual void parentDeleted() { } // called on children of a deleted parent
protected:
QUuid _id;
mutable SpatiallyNestableWeakPointer _parent;
virtual void beParentOfChild(SpatiallyNestablePointer newChild) const;
virtual void forgetChild(SpatiallyNestablePointer newChild) const;
virtual void recalculateChildCauterization() const { }
mutable ReadWriteLockable _childrenLock;
mutable QHash<QUuid, SpatiallyNestableWeakPointer> _children;
// _queryAACube is used to decide where something lives in the octree
mutable AACube _queryAACube;
mutable bool _queryAACubeSet { false };
quint64 _scaleChanged { 0 };
quint64 _translationChanged { 0 };
quint64 _rotationChanged { 0 };
private:
SpatiallyNestable() = delete;
const NestableType _nestableType; // EntityItem or an AvatarData
QUuid _parentID; // what is this thing's transform relative to?
quint16 _parentJointIndex { INVALID_JOINT_INDEX }; // which joint of the parent is this relative to?
mutable ReadWriteLockable _transformLock;
mutable ReadWriteLockable _idLock;
mutable ReadWriteLockable _velocityLock;
mutable ReadWriteLockable _angularVelocityLock;
Transform _transform; // this is to be combined with parent's world-transform to produce this' world-transform.
glm::vec3 _velocity;
glm::vec3 _angularVelocity;
mutable bool _parentKnowsMe { false };
bool _isDead { false };
bool _queryAACubeIsPuffed { false };
void breakParentingLoop() const;
};
#endif // hifi_SpatiallyNestable_h
| 46.894942 | 125 | 0.726269 | [
"object",
"transform"
] |
cf2f2b8854e948cdfa769425bb2f9b026078b7c4 | 35,370 | h | C | application_sandbox/sample_application_framework/sample_application.h | iburinoc/vulkan_test_applications | f1c8ed9660c446fe04cb9fd9a51ad96417ea1801 | [
"Apache-2.0"
] | null | null | null | application_sandbox/sample_application_framework/sample_application.h | iburinoc/vulkan_test_applications | f1c8ed9660c446fe04cb9fd9a51ad96417ea1801 | [
"Apache-2.0"
] | null | null | null | application_sandbox/sample_application_framework/sample_application.h | iburinoc/vulkan_test_applications | f1c8ed9660c446fe04cb9fd9a51ad96417ea1801 | [
"Apache-2.0"
] | null | null | null | // Copyright 2017 Google 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 SAMPLE_APPLICATION_FRAMEWORK_SAMPLE_APPLICATION_H_
#define SAMPLE_APPLICATION_FRAMEWORK_SAMPLE_APPLICATION_H_
#include "support/entry/entry.h"
#include "vulkan_helpers/helper_functions.h"
#include "vulkan_helpers/vulkan_application.h"
#include <chrono>
#include <cstddef>
namespace sample_application {
const static VkSampleCountFlagBits kVkMultiSampledSampleCount =
VK_SAMPLE_COUNT_4_BIT;
const static VkFormat kDepthFormat = VK_FORMAT_D16_UNORM;
struct SampleOptions {
bool enable_multisampling = false;
bool enable_depth_buffer = false;
bool verbose_output = false;
bool async_compute = false;
bool sparse_binding = false;
SampleOptions& EnableMultisampling() {
enable_multisampling = true;
return *this;
}
SampleOptions& EnableDepthBuffer() {
enable_depth_buffer = true;
return *this;
}
SampleOptions& EnableVerbose() {
verbose_output = true;
return *this;
}
SampleOptions& EnableAsyncCompute() {
async_compute = true;
return *this;
}
SampleOptions& EnableSparseBinding() {
sparse_binding = true;
return *this;
}
};
const VkCommandBufferBeginInfo kBeginCommandBuffer = {
VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, // sType
nullptr, // pNext
0, // flags
nullptr // pInheritanceInfo
};
const VkCommandBufferInheritanceInfo kInheritanceCommandBuffer = {
VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO, // sType
nullptr, // pNext
::VkRenderPass(VK_NULL_HANDLE), // renderPass
0, // subPass
::VkFramebuffer(VK_NULL_HANDLE), // framebuffer
VK_FALSE, // occlusionQueryEnable
0, // queryFlags
};
const VkSubmitInfo kEmptySubmitInfo{
VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType
nullptr, // pNext
0, // waitSemaphoreCount
nullptr, // pWaitSemaphores
nullptr, // pWaitDstStageMask,
0, // commandBufferCount
nullptr,
0, // signalSemaphoreCount
nullptr // pSignalSemaphores
};
template <typename FrameData>
class Sample {
// The per-frame data for an application.
struct SampleFrameData {
// The swapchain-image that this frame will use for rendering
::VkImage swapchain_image_;
// The view for the image that is to be rendered to on this frame.
containers::unique_ptr<vulkan::VkImageView> image_view;
// The view for the depth that is to be rendered to on this frame
containers::unique_ptr<vulkan::VkImageView> depth_view_;
// A commandbuffer to transfer the swapchain from the present queue to
// the main queue.
containers::unique_ptr<vulkan::VkCommandBuffer>
transfer_from_present_command_buffer_;
// A commandbuffer to setup the rendering for this frame
containers::unique_ptr<vulkan::VkCommandBuffer> setup_command_buffer_;
// The commandbuffer that resolves the images and gets them ready for
// present
containers::unique_ptr<vulkan::VkCommandBuffer> resolve_command_buffer_;
// The commandbuffer that transfers the images from the graphics
// queue to the present queue.
containers::unique_ptr<vulkan::VkCommandBuffer>
transfer_from_graphics_command_buffer_;
// The semaphore that handles transfering the swapchain image
// between the present and render queues.
containers::unique_ptr<vulkan::VkSemaphore> transfer_semaphore_;
// The depth_stencil image, if it exists.
vulkan::ImagePointer depth_stencil_;
// The multisampled render target if it exists.
vulkan::ImagePointer multisampled_target_;
// The semaphore controlling access to the swapchain.
containers::unique_ptr<vulkan::VkSemaphore> ready_semaphore_;
// The fence that signals that the resources for this frame are free.
containers::unique_ptr<vulkan::VkFence> ready_fence_;
// The application-specific data for this frame.
FrameData child_data_;
};
public:
Sample(containers::Allocator* allocator, const entry::entry_data* entry_data,
uint32_t host_buffer_size_in_MB, uint32_t image_memory_size_in_MB,
uint32_t device_buffer_size_in_MB, uint32_t coherent_buffer_size_in_MB,
const SampleOptions& options,
const VkPhysicalDeviceFeatures& physical_device_features = {0})
: options_(options),
data_(entry_data),
allocator_(allocator),
application_(allocator, entry_data->log.get(), entry_data, {},
physical_device_features,
host_buffer_size_in_MB * 1024 * 1024,
image_memory_size_in_MB * 1024 * 1024,
device_buffer_size_in_MB * 1024 * 1024,
coherent_buffer_size_in_MB * 1024 * 1024,
options.async_compute, options.sparse_binding),
frame_data_(allocator),
swapchain_images_(application_.swapchain_images()),
last_frame_time_(std::chrono::high_resolution_clock::now()),
initialization_command_buffer_(application_.GetCommandBuffer()),
average_frame_time_(0),
is_valid_(true) {
if (data_->options.fixed_timestep) {
app()->GetLogger()->LogInfo("Running with a fixed timestep of 0.1s");
}
frame_data_.reserve(swapchain_images_.size());
// TODO: The image format used by the swapchain image may not suppport
// multi-sampling. Fix this later by adding a vkCmdBlitImage command
// after the vkCmdResolveImage.
render_target_format_ = application_.swapchain().format();
num_samples_ = options.enable_multisampling ? kVkMultiSampledSampleCount
: VK_SAMPLE_COUNT_1_BIT;
default_viewport_ = {0.0f,
0.0f,
static_cast<float>(application_.swapchain().width()),
static_cast<float>(application_.swapchain().height()),
0.0f,
1.0f};
default_scissor_ = {
{0, 0},
{application_.swapchain().width(), application_.swapchain().height()}};
}
// This must be called before any other methods on this class. It initializes
// all of the data for this application. It calls InitializeApplicationData
// on the subclass, as well as InitializeLocalFrameData for every
// image in the swapchain.
void Initialize() {
initialization_command_buffer_->vkBeginCommandBuffer(
initialization_command_buffer_, &kBeginCommandBuffer);
InitializeApplicationData(&initialization_command_buffer_,
swapchain_images_.size());
for (size_t i = 0; i < swapchain_images_.size(); ++i) {
frame_data_.push_back(SampleFrameData());
InitializeLocalFrameData(&frame_data_.back(),
&initialization_command_buffer_, i);
}
initialization_command_buffer_->vkEndCommandBuffer(
initialization_command_buffer_);
VkSubmitInfo submit_info = kEmptySubmitInfo;
submit_info.commandBufferCount = 1;
submit_info.pCommandBuffers =
&(initialization_command_buffer_.get_command_buffer());
vulkan::VkFence init_fence = vulkan::CreateFence(&application_.device());
application_.render_queue()->vkQueueSubmit(application_.render_queue(), 1,
&submit_info,
init_fence.get_raw_object());
application_.device()->vkWaitForFences(application_.device(), 1,
&init_fence.get_raw_object(), false,
0xFFFFFFFFFFFFFFFF);
// Bit gross but submit all of the fences here
for (auto& frame_data : frame_data_) {
application_.render_queue()->vkQueueSubmit(
application_.render_queue(), 0, nullptr, *frame_data.ready_fence_);
}
InitializationComplete();
}
void WaitIdle() { app()->device()->vkDeviceWaitIdle(app()->device()); }
// The format that we are using to render. This will be either the swapchain
// format if we are not rendering multi-sampled, or the multisampled image
// format if we are rendering multi-sampled.
VkFormat render_format() const { return render_target_format_; }
VkFormat depth_format() const { return kDepthFormat; }
// The number of samples that we are rendering with.
VkSampleCountFlagBits num_samples() const { return num_samples_; }
vulkan::VulkanApplication* app() { return &application_; }
const vulkan::VulkanApplication* app() const { return &application_; }
const VkViewport& viewport() const { return default_viewport_; }
const VkRect2D& scissor() const { return default_scissor_; }
// This calls both Update(time) and Render() for the subclass.
// The update is meant to update all of the non-graphics state of the
// application. Render() is used to actually process the commands
// for rendering this particular frame.
void ProcessFrame() {
auto current_time = std::chrono::high_resolution_clock::now();
std::chrono::duration<float> elapsed_time = current_time - last_frame_time_;
last_frame_time_ = current_time;
Update(data_->options.fixed_timestep ? 0.1f : elapsed_time.count());
// Smooth this out, so that it is more sensible.
average_frame_time_ =
elapsed_time.count() * 0.05f + average_frame_time_ * 0.95f;
uint32_t image_idx;
// This is a bit weird as we have to make new semaphores every frame, but
// for now this will do. It will get cleaned up the next time
// this image is used.
vulkan::VkSemaphore temp_semaphore =
vulkan::CreateSemaphore(&app()->device());
LOG_ASSERT(==, app()->GetLogger(), VK_SUCCESS,
app()->device()->vkAcquireNextImageKHR(
app()->device(), app()->swapchain(), 0xFFFFFFFFFFFFFFFF,
temp_semaphore.get_raw_object(),
static_cast<::VkFence>(VK_NULL_HANDLE), &image_idx));
::VkFence ready_fence = *frame_data_[image_idx].ready_fence_;
LOG_ASSERT(
==, app()->GetLogger(), VK_SUCCESS,
app()->device()->vkWaitForFences(app()->device(), 1, &ready_fence,
VK_FALSE, 0xFFFFFFFFFFFFFFFF));
LOG_ASSERT(
==, app()->GetLogger(), VK_SUCCESS,
app()->device()->vkResetFences(app()->device(), 1, &ready_fence));
if (options_.verbose_output) {
app()->GetLogger()->LogInfo("Rendering frame <", elapsed_time.count(),
">: <", image_idx, ">", " Average: <",
average_frame_time_, ">");
}
frame_data_[image_idx].ready_semaphore_ =
containers::make_unique<vulkan::VkSemaphore>(allocator_,
std::move(temp_semaphore));
::VkSemaphore ready_semaphore = *frame_data_[image_idx].ready_semaphore_;
::VkSemaphore render_wait_semaphore = ready_semaphore;
VkPipelineStageFlags flags =
VkPipelineStageFlags(VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT);
if (application_.HasSeparatePresentQueue()) {
render_wait_semaphore = *frame_data_[image_idx].transfer_semaphore_;
VkSubmitInfo transfer_submit_info{
VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType
nullptr, // pNext
1, // waitSemaphoreCount
&ready_semaphore, // pWaitSemaphores
&flags, // pWaitDstStageMask,
1, // commandBufferCount
&(frame_data_[image_idx]
.transfer_from_present_command_buffer_->get_command_buffer()),
1, // signalSemaphoreCount
&render_wait_semaphore // pSignalSemaphores
};
app()->present_queue()->vkQueueSubmit(
app()->present_queue(), 1, &transfer_submit_info,
static_cast<::VkFence>(VK_NULL_HANDLE));
}
VkSubmitInfo init_submit_info{
VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType
nullptr, // pNext
1, // waitSemaphoreCount
&render_wait_semaphore, // pWaitSemaphores
&flags, // pWaitDstStageMask,
1, // commandBufferCount
&(frame_data_[image_idx].setup_command_buffer_->get_command_buffer()),
0, // signalSemaphoreCount
nullptr // pSignalSemaphores
};
::VkSemaphore present_ready_semaphore = render_wait_semaphore;
if (application_.HasSeparatePresentQueue()) {
present_ready_semaphore = *frame_data_[image_idx].transfer_semaphore_;
}
app()->render_queue()->vkQueueSubmit(
app()->render_queue(), 1, &init_submit_info,
static_cast<::VkFence>(VK_NULL_HANDLE));
Render(&app()->render_queue(), image_idx,
&frame_data_[image_idx].child_data_);
init_submit_info.pCommandBuffers =
&(frame_data_[image_idx].resolve_command_buffer_->get_command_buffer());
init_submit_info.waitSemaphoreCount = 0;
init_submit_info.pWaitSemaphores = nullptr;
init_submit_info.pWaitDstStageMask = nullptr;
init_submit_info.signalSemaphoreCount = 1;
init_submit_info.pSignalSemaphores = &present_ready_semaphore;
app()->render_queue()->vkQueueSubmit(
app()->render_queue(), 1, &init_submit_info, ::VkFence(ready_fence));
if (application_.HasSeparatePresentQueue()) {
::VkSemaphore transfer_semaphore =
*frame_data_[image_idx].transfer_semaphore_;
present_ready_semaphore = render_wait_semaphore;
VkSubmitInfo transfer_submit_info{
VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType
nullptr, // pNext
1, // waitSemaphoreCount
&transfer_semaphore, // pWaitSemaphores
&flags, // pWaitDstStageMask,
1, // commandBufferCount
&(frame_data_[image_idx]
.transfer_from_graphics_command_buffer_->get_command_buffer()),
1, // signalSemaphoreCount
&present_ready_semaphore // pSignalSemaphores
};
app()->present_queue()->vkQueueSubmit(
app()->present_queue(), 1, &transfer_submit_info,
static_cast<::VkFence>(VK_NULL_HANDLE));
}
VkPresentInfoKHR present_info{
VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, // sType
nullptr, // pNext
1, // waitSemaphoreCount
&present_ready_semaphore, // pWaitSemaphores
1, // swapchainCount
&app()->swapchain().get_raw_object(), // pSwapchains
&image_idx, // pImageIndices
nullptr, // pResults
};
LOG_ASSERT(==, app()->GetLogger(),
app()->present_queue()->vkQueuePresentKHR(app()->present_queue(),
&present_info),
VK_SUCCESS);
}
void set_invalid(bool invaid) { is_valid_ = false; }
const bool is_valid() { return is_valid_; }
bool should_exit() const { return app()->should_exit(); }
private:
const size_t sample_frame_data_offset =
reinterpret_cast<size_t>(
&(reinterpret_cast<SampleFrameData*>(4096)->child_data_)) -
4096;
public:
const ::VkImageView& depth_view(FrameData* data) {
SampleFrameData* base = reinterpret_cast<SampleFrameData*>(
reinterpret_cast<uint8_t*>(data) - sample_frame_data_offset);
return base->depth_view_->get_raw_object();
}
const ::VkImageView& color_view(FrameData* data) {
SampleFrameData* base = reinterpret_cast<SampleFrameData*>(
reinterpret_cast<uint8_t*>(data) - sample_frame_data_offset);
return base->image_view->get_raw_object();
}
const ::VkImage& swapchain_image(FrameData* data) {
SampleFrameData* base = reinterpret_cast<SampleFrameData*>(
reinterpret_cast<uint8_t*>(data) - sample_frame_data_offset);
return base->swapchain_image_;
}
const ::VkImage& depth_image(FrameData* data) {
SampleFrameData* base = reinterpret_cast<SampleFrameData*>(
reinterpret_cast<uint8_t*>(data) - sample_frame_data_offset);
return base->depth_stencil_->get_raw_image();
}
private:
// This will be called during Initialize(). The application is expected
// to initialize any frame-specific data that it needs.
virtual void InitializeFrameData(
FrameData* data, vulkan::VkCommandBuffer* initialization_buffer,
size_t frame_index) = 0;
// This will be called during Initialize(). The application is expected
// to intialize any non frame-specific data here, such as images and
// buffers.
virtual void InitializeApplicationData(
vulkan::VkCommandBuffer* initialization_buffer,
size_t num_swapchain_images) = 0;
// This will be called during Initialize(). The application is expected
// to intialize any non frame-specific data here, such as images and
// buffers.
virtual void InitializationComplete() {}
// Will be called to instruct the application to update it's non
// frame-specific data.
virtual void Update(float time_since_last_render) = 0;
// Will be called to instruct the application to enqueue the necessary
// commands for rendering frame <frame_index> into the provided queue
virtual void Render(vulkan::VkQueue* queue, size_t frame_index,
FrameData* data) = 0;
// This initializes the per-frame data for the sample application framework.
// This is equivalent to the InitializeFrameData(), except this handles
// all of the under-the-hood data that the application itself should not
// have to worry about.
void InitializeLocalFrameData(SampleFrameData* data,
vulkan::VkCommandBuffer* initialization_buffer,
size_t frame_index) {
data->swapchain_image_ = swapchain_images_[frame_index];
data->ready_semaphore_ = containers::make_unique<vulkan::VkSemaphore>(
allocator_, vulkan::CreateSemaphore(&application_.device()));
data->ready_fence_ = containers::make_unique<vulkan::VkFence>(
allocator_, vulkan::CreateFence(&application_.device()));
VkImageCreateInfo image_create_info{
/* sType = */
VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
/* pNext = */ nullptr,
/* flags = */ 0,
/* imageType = */ VK_IMAGE_TYPE_2D,
/* format = */ kDepthFormat,
/* extent = */
{
/* width = */ application_.swapchain().width(),
/* height = */ application_.swapchain().height(),
/* depth = */ application_.swapchain().depth(),
},
/* mipLevels = */ 1,
/* arrayLayers = */ 1,
/* samples = */ num_samples_,
/* tiling = */
VK_IMAGE_TILING_OPTIMAL,
/* usage = */
VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT |
VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT |
VK_IMAGE_USAGE_TRANSFER_DST_BIT,
/* sharingMode = */
VK_SHARING_MODE_EXCLUSIVE,
/* queueFamilyIndexCount = */ 0,
/* pQueueFamilyIndices = */ nullptr,
/* initialLayout = */
VK_IMAGE_LAYOUT_UNDEFINED,
};
VkImageViewCreateInfo view_create_info = {
VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, // sType
nullptr, // pNext
0, // flags
VK_NULL_HANDLE, // image
VK_IMAGE_VIEW_TYPE_2D, // viewType
kDepthFormat, // format
{VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B,
VK_COMPONENT_SWIZZLE_A},
{VK_IMAGE_ASPECT_DEPTH_BIT, 0, 1, 0, 1}};
::VkImageView raw_view;
if (options_.enable_depth_buffer) {
data->depth_stencil_ =
application_.CreateAndBindImage(&image_create_info);
view_create_info.image = *data->depth_stencil_;
LOG_ASSERT(
==, data_->log.get(), VK_SUCCESS,
application_.device()->vkCreateImageView(
application_.device(), &view_create_info, nullptr, &raw_view));
data->depth_view_ = containers::make_unique<vulkan::VkImageView>(
allocator_,
vulkan::VkImageView(raw_view, nullptr, &application_.device()));
}
if (options_.enable_multisampling) {
image_create_info.format = render_target_format_;
image_create_info.usage =
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
data->multisampled_target_ =
application_.CreateAndBindImage(&image_create_info);
}
view_create_info.image = options_.enable_multisampling
? *data->multisampled_target_
: data->swapchain_image_;
view_create_info.format = render_target_format_;
view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
LOG_ASSERT(
==, data_->log.get(), VK_SUCCESS,
application_.device()->vkCreateImageView(
application_.device(), &view_create_info, nullptr, &raw_view));
data->image_view = containers::make_unique<vulkan::VkImageView>(
allocator_,
vulkan::VkImageView(raw_view, nullptr, &application_.device()));
VkImageMemoryBarrier barriers[2] = {
{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // sType
nullptr, // pNext
0, // srcAccessMask
VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, // dstAccessMask
VK_IMAGE_LAYOUT_UNDEFINED, // oldLayout
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, // newLayout
VK_QUEUE_FAMILY_IGNORED, // srcQueueFamilyIndex
VK_QUEUE_FAMILY_IGNORED, // dstQueueFamilyIndex
options_.enable_depth_buffer
? static_cast<::VkImage>(*data->depth_stencil_)
: static_cast<::VkImage>(VK_NULL_HANDLE), // image
{VK_IMAGE_ASPECT_DEPTH_BIT, 0, 1, 0, 1}},
{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // sType
nullptr, // pNext
0, // srcAccessMask
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // dstAccessMask
VK_IMAGE_LAYOUT_UNDEFINED, // oldLayout
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // newLayout
VK_QUEUE_FAMILY_IGNORED, // srcQueueFamilyIndex
VK_QUEUE_FAMILY_IGNORED, // dstQueueFamilyIndex
options_.enable_multisampling ? *data->multisampled_target_
: data->swapchain_image_, // image
{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}};
(*initialization_buffer)
->vkCmdPipelineBarrier(
(*initialization_buffer), VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,
VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, 0, nullptr, 0, nullptr,
options_.enable_depth_buffer ? 2 : 1,
&barriers[options_.enable_depth_buffer ? 0 : 1]);
uint32_t srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
uint32_t dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED;
if (application_.HasSeparatePresentQueue()) {
data->transfer_semaphore_ = containers::make_unique<vulkan::VkSemaphore>(
allocator_, vulkan::CreateSemaphore(&application_.device()));
srcQueueFamilyIndex = application_.present_queue().index();
dstQueueFamilyIndex = application_.render_queue().index();
VkImageMemoryBarrier barrier = {
VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // sType
nullptr, // pNext
0, // srcAccessMask
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // dstAccessMask
VK_IMAGE_LAYOUT_UNDEFINED, // oldLayout
VK_IMAGE_LAYOUT_UNDEFINED, // newLayout
srcQueueFamilyIndex, // srcQueueFamilyIndex
dstQueueFamilyIndex, // dstQueueFamilyIndex
data->swapchain_image_, // image
{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
data->transfer_from_present_command_buffer_ =
containers::make_unique<vulkan::VkCommandBuffer>(
allocator_, app()->GetCommandBuffer());
(*data->transfer_from_present_command_buffer_)
->vkBeginCommandBuffer((*data->transfer_from_present_command_buffer_),
&kBeginCommandBuffer);
(*data->transfer_from_present_command_buffer_)
->vkCmdPipelineBarrier((*data->transfer_from_present_command_buffer_),
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
0, 0, nullptr, 0, nullptr, 1, &barrier);
(*data->transfer_from_present_command_buffer_)
->vkEndCommandBuffer(*data->transfer_from_present_command_buffer_);
barrier.srcQueueFamilyIndex = dstQueueFamilyIndex;
barrier.dstQueueFamilyIndex = srcQueueFamilyIndex;
barrier.oldLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
barrier.newLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
data->transfer_from_graphics_command_buffer_ =
containers::make_unique<vulkan::VkCommandBuffer>(
allocator_, app()->GetCommandBuffer());
(*data->transfer_from_graphics_command_buffer_)
->vkBeginCommandBuffer((*data->setup_command_buffer_),
&kBeginCommandBuffer);
(*data->transfer_from_graphics_command_buffer_)
->vkCmdPipelineBarrier((*data->setup_command_buffer_),
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
0, 0, nullptr, 0, nullptr, 1, &barrier);
(*data->transfer_from_graphics_command_buffer_)
->vkEndCommandBuffer(*data->setup_command_buffer_);
}
VkImageMemoryBarrier barrier = {
VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // sType
nullptr, // pNext
0, // srcAccessMask
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // dstAccessMask
VK_IMAGE_LAYOUT_UNDEFINED, // oldLayout
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // newLayout
srcQueueFamilyIndex, // srcQueueFamilyIndex
dstQueueFamilyIndex, // dstQueueFamilyIndex
options_.enable_multisampling ? *data->multisampled_target_
: data->swapchain_image_, // image
{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
data->setup_command_buffer_ =
containers::make_unique<vulkan::VkCommandBuffer>(
allocator_, app()->GetCommandBuffer());
(*data->setup_command_buffer_)
->vkBeginCommandBuffer((*data->setup_command_buffer_),
&kBeginCommandBuffer);
(*data->setup_command_buffer_)
->vkCmdPipelineBarrier((*data->setup_command_buffer_),
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, 0,
0, nullptr, 0, nullptr, 1, &barrier);
(*data->setup_command_buffer_)
->vkEndCommandBuffer(*data->setup_command_buffer_);
data->resolve_command_buffer_ =
containers::make_unique<vulkan::VkCommandBuffer>(
allocator_, app()->GetCommandBuffer());
(*data->resolve_command_buffer_)
->vkBeginCommandBuffer((*data->resolve_command_buffer_),
&kBeginCommandBuffer);
VkImageLayout old_layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkAccessFlags old_access = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
if (options_.enable_multisampling) {
old_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;
old_access = VK_ACCESS_TRANSFER_WRITE_BIT;
VkImageMemoryBarrier resolve_barrier[2] = {
{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // sType
nullptr, // pNext
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // srcAccessMask
VK_ACCESS_TRANSFER_READ_BIT, // dstAccessMask
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // oldLayout
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, // newLayout
VK_QUEUE_FAMILY_IGNORED, // srcQueueFamilyIndex
VK_QUEUE_FAMILY_IGNORED, // dstQueueFamilyIndex
*data->multisampled_target_, // image
{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}},
{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // sType
nullptr, // pNext
0, // srcAccessMask
VK_ACCESS_TRANSFER_WRITE_BIT, // dstAccessMask
VK_IMAGE_LAYOUT_UNDEFINED, // oldLayout
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, // newLayout
VK_QUEUE_FAMILY_IGNORED, // srcQueueFamilyIndex
VK_QUEUE_FAMILY_IGNORED, // dstQueueFamilyIndex
data->swapchain_image_, // image
{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}}};
(*data->resolve_command_buffer_)
->vkCmdPipelineBarrier(*data->resolve_command_buffer_,
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr,
0, nullptr, 2, resolve_barrier);
VkImageResolve region = {
{
VK_IMAGE_ASPECT_COLOR_BIT, // aspectMask
0, // mipLevel
0, // baseArrayLayer
1, // layerCount
}, // srcSubresource
{
0, // x
0, // y
0 // z
}, // srcOffset
{
VK_IMAGE_ASPECT_COLOR_BIT, // aspectMask
0, // mipLevel
0, // baseArrayLayer
1, // layerCount
}, // dstSubresource
{
0, // x
0, // y
0 // z
}, // dstOffset
{
app()->swapchain().width(), // width
app()->swapchain().height(), // height
1 // depth
} // extent
};
(*data->resolve_command_buffer_)
->vkCmdResolveImage(
(*data->resolve_command_buffer_), *data->multisampled_target_,
VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, data->swapchain_image_,
VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, ®ion);
}
VkImageMemoryBarrier present_barrier = {
VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // sType
nullptr, // pNext
old_access, // srcAccessMask
VK_ACCESS_MEMORY_READ_BIT, // dstAccessMask
old_layout, // oldLayout
VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, // newLayout
dstQueueFamilyIndex, // srcQueueFamilyIndex
srcQueueFamilyIndex, // dstQueueFamilyIndex
data->swapchain_image_, // image
{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
(*data->resolve_command_buffer_)
->vkCmdPipelineBarrier((*data->resolve_command_buffer_),
VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0,
nullptr, 0, nullptr, 1, &present_barrier);
(*data->resolve_command_buffer_)
->vkEndCommandBuffer(*data->resolve_command_buffer_);
InitializeFrameData(&data->child_data_, initialization_buffer, frame_index);
}
SampleOptions options_;
const entry::entry_data* data_;
containers::Allocator* allocator_;
// The VulkanApplication that we build on, we want this to be the
// last thing deleted, it goes at the top.
vulkan::VulkanApplication application_;
// This contains one SampleFrameData per swapchain image. It will be used
// to render frames to the appropriate swapchains
containers::vector<SampleFrameData> frame_data_;
// The number of samples that we will render with
VkSampleCountFlagBits num_samples_;
// The format of our render_target
VkFormat render_target_format_;
// The viewport we use to render
VkViewport default_viewport_;
// The scissor we use to render
VkRect2D default_scissor_;
// The last time ProcessFrame was called. This is used to calculate the
// delta
// to be passed to Update.
std::chrono::time_point<std::chrono::high_resolution_clock> last_frame_time_;
// Do not move these above application_, they rely on the fact that
// application_ will be initialized first.
const containers::vector<::VkImage>& swapchain_images_;
// The command buffer used to intialize all of the data.
vulkan::VkCommandBuffer initialization_command_buffer_;
// The exponentially smoothed average frame time.
float average_frame_time_;
// If this is set to false, the application cannot be safely run.
bool is_valid_;
}; // namespace sample_application
} // namespace sample_application
#endif // SAMPLE_APPLICATION_FRAMEWORK_SAMPLE_APPLICATION_H_
| 45.057325 | 80 | 0.618688 | [
"render",
"vector"
] |
659fa315460cf85e08b35f80bd0a25d29adffa60 | 6,357 | h | C | oneflow/user/data/coco_data_reader.h | LiPengze97/oneflow | 1c1d2d3faa1c02d20e009046a290cf1095ee12e0 | [
"Apache-2.0"
] | null | null | null | oneflow/user/data/coco_data_reader.h | LiPengze97/oneflow | 1c1d2d3faa1c02d20e009046a290cf1095ee12e0 | [
"Apache-2.0"
] | null | null | null | oneflow/user/data/coco_data_reader.h | LiPengze97/oneflow | 1c1d2d3faa1c02d20e009046a290cf1095ee12e0 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2020 The OneFlow 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.
*/
#ifndef ONEFLOW_USER_DATA_COCO_DATA_READER_H_
#define ONEFLOW_USER_DATA_COCO_DATA_READER_H_
#include "oneflow/user/data/data_reader.h"
#include "oneflow/user/data/coco_parser.h"
#include "oneflow/core/common/str_util.h"
#include <json.hpp>
namespace oneflow {
namespace data {
class COCODataReader final : public DataReader<COCOImage> {
public:
COCODataReader(user_op::KernelInitContext* ctx);
~COCODataReader() = default;
protected:
using DataReader<COCOImage>::loader_;
using DataReader<COCOImage>::parser_;
};
class COCOMeta final {
public:
COCOMeta(int64_t session_id, const std::string& annotation_file, const std::string& image_dir,
bool remove_images_without_annotations);
~COCOMeta() = default;
int64_t Size() const { return image_ids_.size(); }
int64_t GetImageId(int64_t index) const { return image_ids_.at(index); }
int32_t GetImageHeight(int64_t index) const {
int64_t image_id = image_ids_.at(index);
return image_id2image_.at(image_id)["height"].get<int32_t>();
}
int32_t GetImageWidth(int64_t index) const {
int64_t image_id = image_ids_.at(index);
return image_id2image_.at(image_id)["width"].get<int32_t>();
}
std::string GetImageFilePath(int64_t index) const {
int64_t image_id = image_ids_.at(index);
const auto& image_json = image_id2image_.at(image_id);
return JoinPath(image_dir_, image_json["file_name"].get<std::string>());
}
template<typename T>
std::vector<T> GetBboxVec(int64_t index) const;
template<typename T>
std::vector<T> GetLabelVec(int64_t index) const;
template<typename T>
void ReadSegmentationsToTensorBuffer(int64_t index, TensorBuffer* segm,
TensorBuffer* segm_offset_mat) const;
private:
bool ImageHasValidAnnotations(int64_t image_id) const;
static constexpr int kMinKeypointsPerImage = 10;
nlohmann::json annotation_json_;
std::string image_dir_;
std::vector<int64_t> image_ids_;
HashMap<int64_t, const nlohmann::json&> image_id2image_;
HashMap<int64_t, const nlohmann::json&> anno_id2anno_;
HashMap<int64_t, std::vector<int64_t>> image_id2anno_ids_;
HashMap<int32_t, int32_t> category_id2contiguous_id_;
};
template<typename T>
std::vector<T> COCOMeta::GetBboxVec(int64_t index) const {
std::vector<T> bbox_vec;
int64_t image_id = image_ids_.at(index);
const auto& anno_ids = image_id2anno_ids_.at(image_id);
for (int64_t anno_id : anno_ids) {
const auto& bbox_json = anno_id2anno_.at(anno_id)["bbox"];
CHECK(bbox_json.is_array());
CHECK_EQ(bbox_json.size(), 4);
// COCO bounding box format is [left, top, width, height]
// we need format xyxy
const T alginment = static_cast<T>(1);
const T min_size = static_cast<T>(0);
T left = bbox_json[0].get<T>();
T top = bbox_json[1].get<T>();
T width = bbox_json[2].get<T>();
T height = bbox_json[3].get<T>();
T right = left + std::max(width - alginment, min_size);
T bottom = top + std::max(height - alginment, min_size);
// clip to image
int32_t image_height = GetImageHeight(index);
int32_t image_width = GetImageWidth(index);
left = std::min(std::max(left, min_size), image_width - alginment);
top = std::min(std::max(top, min_size), image_height - alginment);
right = std::min(std::max(right, min_size), image_width - alginment);
bottom = std::min(std::max(bottom, min_size), image_height - alginment);
// ensure bbox is not empty
if (right > left && bottom > top) {
bbox_vec.insert(bbox_vec.end(), {left, top, right, bottom});
}
}
return bbox_vec;
}
template<typename T>
std::vector<T> COCOMeta::GetLabelVec(int64_t index) const {
std::vector<T> label_vec;
int64_t image_id = image_ids_.at(index);
const auto& anno_ids = image_id2anno_ids_.at(image_id);
for (int64_t anno_id : anno_ids) {
int32_t category_id = anno_id2anno_.at(anno_id)["category_id"].get<int32_t>();
label_vec.emplace_back(category_id2contiguous_id_.at(category_id));
}
return label_vec;
}
template<typename T>
void COCOMeta::ReadSegmentationsToTensorBuffer(int64_t index, TensorBuffer* segm,
TensorBuffer* segm_index) const {
if (segm == nullptr || segm_index == nullptr) { return; }
int64_t image_id = image_ids_.at(index);
const auto& anno_ids = image_id2anno_ids_.at(image_id);
std::vector<T> segm_vec;
for (int64_t anno_id : anno_ids) {
const auto& segm_json = anno_id2anno_.at(anno_id)["segmentation"];
if (!segm_json.is_array()) { continue; }
for (const auto& poly_json : segm_json) {
CHECK(poly_json.is_array());
for (const auto& elem : poly_json) { segm_vec.emplace_back(elem.get<T>()); }
}
}
CHECK_EQ(segm_vec.size() % 2, 0);
int64_t num_pts = segm_vec.size() / 2;
segm->Resize(Shape({num_pts, 2}), GetDataType<T>::value);
std::copy(segm_vec.begin(), segm_vec.end(), segm->mut_data<T>());
segm_index->Resize(Shape({num_pts, 3}), DataType::kInt32);
int32_t* index_ptr = segm_index->mut_data<int32_t>();
int i = 0;
int32_t segm_idx = 0;
for (int64_t anno_id : anno_ids) {
const auto& segm_json = anno_id2anno_.at(anno_id)["segmentation"];
CHECK(segm_json.is_array());
FOR_RANGE(int32_t, poly_idx, 0, segm_json.size()) {
const auto& poly_json = segm_json[poly_idx];
CHECK(poly_json.is_array());
CHECK_EQ(poly_json.size() % 2, 0);
FOR_RANGE(int32_t, pt_idx, 0, poly_json.size() / 2) {
index_ptr[i * 3 + 0] = pt_idx;
index_ptr[i * 3 + 1] = poly_idx;
index_ptr[i * 3 + 2] = segm_idx;
i += 1;
}
}
segm_idx += 1;
}
CHECK_EQ(i, num_pts);
}
} // namespace data
} // namespace oneflow
#endif // ONEFLOW_USER_DATA_COCO_DATA_READER_H_
| 36.959302 | 96 | 0.699544 | [
"shape",
"vector"
] |
65a11bf0f39b9bc83e8f131f08327ca84c00dbcc | 8,094 | h | C | INET_EC/transportlayer/tcp/TCP.h | LarryNguyen/ECSim- | 0d3f848642e49845ed7e4c7b97dd16bd3d65ede5 | [
"Apache-2.0"
] | 12 | 2020-11-30T08:04:23.000Z | 2022-03-23T11:49:26.000Z | INET_EC/transportlayer/tcp/TCP.h | LarryNguyen/ECSim- | 0d3f848642e49845ed7e4c7b97dd16bd3d65ede5 | [
"Apache-2.0"
] | 1 | 2021-01-26T10:49:56.000Z | 2021-01-31T16:58:52.000Z | INET_EC/transportlayer/tcp/TCP.h | LarryNguyen/ECSim- | 0d3f848642e49845ed7e4c7b97dd16bd3d65ede5 | [
"Apache-2.0"
] | 8 | 2021-03-15T02:05:51.000Z | 2022-03-21T13:14:02.000Z | //
// Copyright (C) 2004 Andras Varga
// Copyright (C) 2010-2011 Zoltan Bojthe
//
// 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_TCP_H
#define __INET_TCP_H
#include <map>
#include <set>
#include "inet/common/INETDefs.h"
#include "inet/common/lifecycle/ILifecycle.h"
#include "inet/networklayer/common/L3Address.h"
#include "inet/transportlayer/contract/tcp/TCPCommand_m.h"
namespace inet {
namespace tcp {
// Forward declarations:
class TCPConnection;
class TCPSegment;
class TCPSendQueue;
class TCPReceiveQueue;
/**
* Implements the TCP protocol. This section describes the internal
* architecture of the TCP model.
*
* Usage and compliance with various RFCs are discussed in the corresponding
* NED documentation for TCP. Also, you may want to check the TCPSocket
* class which makes it easier to use TCP from applications.
*
* The TCP protocol implementation is composed of several classes (discussion
* follows below):
* - TCP: the module class
* - TCPConnection: manages a connection
* - TCPSendQueue, TCPReceiveQueue: abstract base classes for various types
* of send and receive queues
* - TCPVirtualDataSendQueue and TCPVirtualDataRcvQueue which implement
* queues with "virtual" bytes (byte counts only)
* - TCPAlgorithm: abstract base class for TCP algorithms, and subclasses:
* DumbTCP, TCPBaseAlg, TCPTahoeRenoFamily, TCPTahoe, TCPReno, TCPNewReno.
*
* TCP subclassed from cSimpleModule. It manages socketpair-to-connection
* mapping, and dispatches segments and user commands to the appropriate
* TCPConnection object.
*
* TCPConnection manages the connection, with the help of other objects.
* TCPConnection itself implements the basic TCP "machinery": takes care
* of the state machine, stores the state variables (TCB), sends/receives
* SYN, FIN, RST, ACKs, etc.
*
* TCPConnection internally relies on 3 objects. The first two are subclassed
* from TCPSendQueue and TCPReceiveQueue. They manage the actual data stream,
* so TCPConnection itself only works with sequence number variables.
* This makes it possible to easily accomodate need for various types of
* simulated data transfer: real byte stream, "virtual" bytes (byte counts
* only), and sequence of cMessage objects (where every message object is
* mapped to a TCP sequence number range).
*
* Currently implemented send queue and receive queue classes are
* TCPVirtualDataSendQueue and TCPVirtualDataRcvQueue which implement
* queues with "virtual" bytes (byte counts only).
*
* The third object is subclassed from TCPAlgorithm. Control over
* retransmissions, congestion control and ACK sending are "outsourced"
* from TCPConnection into TCPAlgorithm: delayed acks, slow start, fast rexmit,
* etc. are all implemented in TCPAlgorithm subclasses. This simplifies the
* design of TCPConnection and makes it a lot easier to implement new TCP
* variations such as NewReno, Vegas or LinuxTCP as TCPAlgorithm subclasses.
*
* Currently implemented TCPAlgorithm classes are TCPReno, TCPTahoe, TCPNewReno,
* TCPNoCongestionControl and DumbTCP.
*
* The concrete TCPAlgorithm class to use can be chosen per connection (in OPEN)
* or in a module parameter.
*/
class INET_API TCP : public cSimpleModule, public ILifecycle
{
public:
static simsignal_t tcpConnectionAddedSignal;
static simsignal_t tcpConnectionRemovedSignal;
struct AppConnKey // XXX this class is redundant since connId is already globally unique
{
int appGateIndex;
int connId;
inline bool operator<(const AppConnKey& b) const
{
if (appGateIndex != b.appGateIndex)
return appGateIndex < b.appGateIndex;
else
return connId < b.connId;
}
};
struct SockPair
{
L3Address localAddr;
L3Address remoteAddr;
int localPort; // -1: unspec
int remotePort; // -1: unspec
inline bool operator<(const SockPair& b) const
{
if (remoteAddr != b.remoteAddr)
return remoteAddr < b.remoteAddr;
else if (localAddr != b.localAddr)
return localAddr < b.localAddr;
else if (remotePort != b.remotePort)
return remotePort < b.remotePort;
else
return localPort < b.localPort;
}
};
protected:
typedef std::map<AppConnKey, TCPConnection *> TcpAppConnMap;
typedef std::map<SockPair, TCPConnection *> TcpConnMap;
TcpAppConnMap tcpAppConnMap;
TcpConnMap tcpConnMap;
ushort lastEphemeralPort = (ushort)-1;
std::multiset<ushort> usedEphemeralPorts;
protected:
/** Factory method; may be overriden for customizing TCP */
virtual TCPConnection *createConnection(int appGateIndex, int connId);
// utility methods
virtual TCPConnection *findConnForSegment(TCPSegment *tcpseg, L3Address srcAddr, L3Address destAddr);
virtual TCPConnection *findConnForApp(int appGateIndex, int connId);
virtual void segmentArrivalWhileClosed(TCPSegment *tcpseg, L3Address src, L3Address dest);
virtual void removeConnection(TCPConnection *conn);
virtual void refreshDisplay() const override;
public:
static bool testing; // switches between tcpEV and testingEV
static bool logverbose; // if !testing, turns on more verbose logging
bool recordStatistics = false; // output vectors on/off
bool isOperational = false; // lifecycle: node is up/down
bool useDataNotification = false;
public:
TCP() {}
virtual ~TCP();
protected:
virtual void initialize(int stage) override;
virtual int numInitStages() const override { return NUM_INIT_STAGES; }
virtual void handleMessage(cMessage *msg) override;
virtual void finish() override;
public:
/**
* To be called from TCPConnection when a new connection gets created,
* during processing of OPEN_ACTIVE or OPEN_PASSIVE.
*/
virtual void addSockPair(TCPConnection *conn, L3Address localAddr, L3Address remoteAddr, int localPort, int remotePort);
/**
* To be called from TCPConnection when socket pair (key for TcpConnMap) changes
* (e.g. becomes fully qualified).
*/
virtual void updateSockPair(TCPConnection *conn, L3Address localAddr, L3Address remoteAddr, int localPort, int remotePort);
/**
* Update conn's socket pair, and register newConn (which'll keep LISTENing).
* Also, conn will get a new connId (and newConn will live on with its old connId).
*/
virtual void addForkedConnection(TCPConnection *conn, TCPConnection *newConn, L3Address localAddr, L3Address remoteAddr, int localPort, int remotePort);
/**
* To be called from TCPConnection: reserves an ephemeral port for the connection.
*/
virtual ushort getEphemeralPort();
/**
* To be called from TCPConnection: create a new send queue.
*/
virtual TCPSendQueue *createSendQueue(TCPDataTransferMode transferModeP);
/**
* To be called from TCPConnection: create a new receive queue.
*/
virtual TCPReceiveQueue *createReceiveQueue(TCPDataTransferMode transferModeP);
// ILifeCycle:
virtual bool handleOperationStage(LifecycleOperation *operation, int stage, IDoneCallback *doneCallback) override;
// called at shutdown/crash
virtual void reset();
};
} // namespace tcp
} // namespace inet
#endif // ifndef __INET_TCP_H
| 36.790909 | 156 | 0.721893 | [
"object",
"model"
] |
65a1e4edad03d58335a6afb7a4440474ce0067e5 | 1,308 | h | C | divi/src/CachedBIP9ActivationStateTracker.h | smcneilly4/xCoin | e4f9fa4af1ad07e03fdad792be3b5d4288947b7e | [
"MIT"
] | 56 | 2019-05-16T21:31:18.000Z | 2022-03-16T16:13:02.000Z | divi/src/CachedBIP9ActivationStateTracker.h | smcneilly4/xCoin | e4f9fa4af1ad07e03fdad792be3b5d4288947b7e | [
"MIT"
] | 98 | 2018-03-07T19:30:42.000Z | 2019-04-29T14:17:12.000Z | divi/src/CachedBIP9ActivationStateTracker.h | smcneilly4/xCoin | e4f9fa4af1ad07e03fdad792be3b5d4288947b7e | [
"MIT"
] | 38 | 2019-05-07T11:08:41.000Z | 2022-03-02T20:06:12.000Z | #ifndef CACHED_BIP9_ACTIVATION_STATE_TRACKER_H
#define CACHED_BIP9_ACTIVATION_STATE_TRACKER_H
#include <I_BIP9ActivationStateTracker.h>
#include <vector>
class CBlockIndex;
class BIP9Deployment;
struct ThresholdConditionCache;
class CachedBIP9ActivationStateTracker: public I_BIP9ActivationStateTracker
{
private:
const BIP9Deployment& bip_;
ThresholdConditionCache& thresholdCache_;
const bool bipIsViable_;
const CBlockIndex* getMostRecentStartingBlock(const CBlockIndex* shallowBlockIndex) const;
void getStartingBlocksForPeriodsPreceedingBlockIndex(
std::vector<const CBlockIndex*>& startingBlocksForPeriods
) const;
bool enoughBipSignalsToLockIn(const CBlockIndex* endingBlockIndex) const;
void computeStateTransition(
ThresholdState& lastKnownState,
const CBlockIndex* previousBlockIndex) const;
public:
CachedBIP9ActivationStateTracker(
const BIP9Deployment& bip,
ThresholdConditionCache& thresholdCache
);
virtual bool bipIsSignaledFor(const CBlockIndex* shallowBlockIndex) const;
virtual bool update(const CBlockIndex* shallowBlockIndex);
virtual ThresholdState getLastCachedStatePriorToBlockIndex(const CBlockIndex* shallowBlockIndex) const;
};
#endif // CACHED_BIP9_ACTIVATION_STATE_TRACKER_H | 36.333333 | 107 | 0.805046 | [
"vector"
] |
65ad3672459080172a1cbd311170c8ca63a434fd | 2,444 | h | C | source/AmbisonicZoomer.h | truthiswill/ambisonic-lib | 0207bdf3f692306ac07b381c480883289222b95b | [
"MIT"
] | 41 | 2015-02-28T05:18:46.000Z | 2021-07-21T07:24:13.000Z | source/AmbisonicZoomer.h | whitemike889/ambisonic-lib | 0207bdf3f692306ac07b381c480883289222b95b | [
"MIT"
] | 1 | 2019-03-27T14:33:30.000Z | 2019-03-27T14:33:30.000Z | source/AmbisonicZoomer.h | whitemike889/ambisonic-lib | 0207bdf3f692306ac07b381c480883289222b95b | [
"MIT"
] | 16 | 2016-02-21T19:24:57.000Z | 2022-02-23T03:33:38.000Z | /*############################################################################*/
/*# #*/
/*# Ambisonic C++ Library #*/
/*# CAmbisonicZoomer - Ambisonic Zoomer #*/
/*# Copyright � 2007 Aristotel Digenis #*/
/*# #*/
/*# Filename: AmbisonicZoomer.h #*/
/*# Version: 0.1 #*/
/*# Date: 19/05/2007 #*/
/*# Author(s): Aristotel Digenis #*/
/*# Licence: MIT #*/
/*# #*/
/*############################################################################*/
#ifndef _AMBISONIC_ZOOMER_H
#define _AMBISONIC_ZOOMER_H
#include "AmbisonicBase.h"
#include "BFormat.h"
/// Ambisonic zoomer.
/** This object is used to apply a zoom effect into BFormat soundfields. */
class CAmbisonicZoomer : public CAmbisonicBase
{
public:
CAmbisonicZoomer();
~CAmbisonicZoomer();
/**
Re-create the object for the given configuration. Previous data is
lost. The last argument is not used, it is just there to match with
the base class's form. Returns true if successful.
*/
bool Create(AmbUInt nOrder, AmbBool b3D, AmbUInt nMisc);
/**
Not implemented.
*/
void Reset();
/**
Recalculate coefficients.
*/
void Refresh();
/**
Set zoom factor. This is in a range from -1 to 1, with 0 being no zoom,
1 full forward zoom, and -1 full forward backwards.
*/
void SetZoom(AmbFloat fZoom);
/**
Get zoom factor.
*/
AmbFloat GetZoom();
/**
Zoom into B-Format stream.
*/
void Process(CBFormat* pBFSrcDst, AmbUInt nSamples);
protected:
AmbFloat m_fZoom;
AmbFloat m_fWCoeff;
AmbFloat m_fXCoeff;
AmbFloat m_fYZCoeff;
void Process2D(CBFormat* pBFSrcDst, AmbUInt nSamples);
void Process3D(CBFormat* pBFSrcDst, AmbUInt nSamples);
void (CAmbisonicZoomer::*m_pProcessFunction)(CBFormat* pBFSrcDst, AmbUInt nSamples);
};
#endif // _AMBISONIC_ZOOMER_H | 34.914286 | 89 | 0.452946 | [
"object"
] |
65b1bc37ace50b71d92a32a8cae439c9bfb22051 | 7,223 | h | C | src/rocksdb/db/compaction_picker.h | SingaporeLMC/LMC | b8734f7c67c829f69ae06c1217b9f64e2c078a1a | [
"BSL-1.0"
] | 1 | 2015-11-05T18:37:27.000Z | 2015-11-05T18:37:27.000Z | db/compaction_picker.h | waderly/rocksdb | f799c8be5fee3bf98b4558cc588ae1072d41bc34 | [
"BSD-3-Clause"
] | null | null | null | db/compaction_picker.h | waderly/rocksdb | f799c8be5fee3bf98b4558cc588ae1072d41bc34 | [
"BSD-3-Clause"
] | 1 | 2018-11-23T01:30:41.000Z | 2018-11-23T01:30:41.000Z | // Copyright (c) 2013, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#pragma once
#include "db/version_set.h"
#include "db/compaction.h"
#include "rocksdb/status.h"
#include "rocksdb/options.h"
#include "rocksdb/env.h"
#include <vector>
#include <memory>
#include <set>
namespace rocksdb {
class LogBuffer;
class Compaction;
class Version;
class CompactionPicker {
public:
CompactionPicker(const Options* options, const InternalKeyComparator* icmp);
virtual ~CompactionPicker();
// Pick level and inputs for a new compaction.
// Returns nullptr if there is no compaction to be done.
// Otherwise returns a pointer to a heap-allocated object that
// describes the compaction. Caller should delete the result.
virtual Compaction* PickCompaction(Version* version,
LogBuffer* log_buffer) = 0;
// Return a compaction object for compacting the range [begin,end] in
// the specified level. Returns nullptr if there is nothing in that
// level that overlaps the specified range. Caller should delete
// the result.
//
// The returned Compaction might not include the whole requested range.
// In that case, compaction_end will be set to the next key that needs
// compacting. In case the compaction will compact the whole range,
// compaction_end will be set to nullptr.
// Client is responsible for compaction_end storage -- when called,
// *compaction_end should point to valid InternalKey!
virtual Compaction* CompactRange(Version* version, int input_level,
int output_level, const InternalKey* begin,
const InternalKey* end,
InternalKey** compaction_end);
// Free up the files that participated in a compaction
void ReleaseCompactionFiles(Compaction* c, Status status);
// Return the total amount of data that is undergoing
// compactions per level
void SizeBeingCompacted(std::vector<uint64_t>& sizes);
// Returns maximum total overlap bytes with grandparent
// level (i.e., level+2) before we stop building a single
// file in level->level+1 compaction.
uint64_t MaxGrandParentOverlapBytes(int level);
// Returns maximum total bytes of data on a given level.
double MaxBytesForLevel(int level);
// Get the max file size in a given level.
uint64_t MaxFileSizeForLevel(int level) const;
protected:
int NumberLevels() const { return num_levels_; }
// Stores the minimal range that covers all entries in inputs in
// *smallest, *largest.
// REQUIRES: inputs is not empty
void GetRange(const std::vector<FileMetaData*>& inputs, InternalKey* smallest,
InternalKey* largest);
// Stores the minimal range that covers all entries in inputs1 and inputs2
// in *smallest, *largest.
// REQUIRES: inputs is not empty
void GetRange(const std::vector<FileMetaData*>& inputs1,
const std::vector<FileMetaData*>& inputs2,
InternalKey* smallest, InternalKey* largest);
// Add more files to the inputs on "level" to make sure that
// no newer version of a key is compacted to "level+1" while leaving an older
// version in a "level". Otherwise, any Get() will search "level" first,
// and will likely return an old/stale value for the key, since it always
// searches in increasing order of level to find the value. This could
// also scramble the order of merge operands. This function should be
// called any time a new Compaction is created, and its inputs_[0] are
// populated.
//
// Will return false if it is impossible to apply this compaction.
bool ExpandWhileOverlapping(Compaction* c);
uint64_t ExpandedCompactionByteSizeLimit(int level);
// Returns true if any one of the specified files are being compacted
bool FilesInCompaction(std::vector<FileMetaData*>& files);
// Returns true if any one of the parent files are being compacted
bool ParentRangeInCompaction(Version* version, const InternalKey* smallest,
const InternalKey* largest, int level,
int* index);
void SetupOtherInputs(Compaction* c);
// record all the ongoing compactions for all levels
std::vector<std::set<Compaction*>> compactions_in_progress_;
// Per-level target file size.
std::unique_ptr<uint64_t[]> max_file_size_;
// Per-level max bytes
std::unique_ptr<uint64_t[]> level_max_bytes_;
const Options* const options_;
private:
int num_levels_;
const InternalKeyComparator* const icmp_;
};
class UniversalCompactionPicker : public CompactionPicker {
public:
UniversalCompactionPicker(const Options* options,
const InternalKeyComparator* icmp)
: CompactionPicker(options, icmp) {}
virtual Compaction* PickCompaction(Version* version,
LogBuffer* log_buffer) override;
private:
// Pick Universal compaction to limit read amplification
Compaction* PickCompactionUniversalReadAmp(Version* version, double score,
unsigned int ratio,
unsigned int num_files,
LogBuffer* log_buffer);
// Pick Universal compaction to limit space amplification.
Compaction* PickCompactionUniversalSizeAmp(Version* version, double score,
LogBuffer* log_buffer);
};
class LevelCompactionPicker : public CompactionPicker {
public:
LevelCompactionPicker(const Options* options,
const InternalKeyComparator* icmp)
: CompactionPicker(options, icmp) {}
virtual Compaction* PickCompaction(Version* version,
LogBuffer* log_buffer) override;
private:
// For the specfied level, pick a compaction.
// Returns nullptr if there is no compaction to be done.
// If level is 0 and there is already a compaction on that level, this
// function will return nullptr.
Compaction* PickCompactionBySize(Version* version, int level, double score);
};
class FIFOCompactionPicker : public CompactionPicker {
public:
FIFOCompactionPicker(const Options* options,
const InternalKeyComparator* icmp)
: CompactionPicker(options, icmp) {}
virtual Compaction* PickCompaction(Version* version,
LogBuffer* log_buffer) override;
virtual Compaction* CompactRange(Version* version, int input_level,
int output_level, const InternalKey* begin,
const InternalKey* end,
InternalKey** compaction_end) override;
};
} // namespace rocksdb
| 39.686813 | 80 | 0.681988 | [
"object",
"vector"
] |
65b3e5e06a84010002656fdf83b929d83a376aeb | 20,504 | h | C | maistra/vendor/com_github_google_quiche/quic/core/http/quic_spdy_stream.h | Maistra/proxy | 96b6aa184db650ec8c3a4b4e82eb54b0b9ab411f | [
"Apache-2.0"
] | null | null | null | maistra/vendor/com_github_google_quiche/quic/core/http/quic_spdy_stream.h | Maistra/proxy | 96b6aa184db650ec8c3a4b4e82eb54b0b9ab411f | [
"Apache-2.0"
] | 11 | 2019-10-15T23:03:57.000Z | 2020-06-14T16:10:12.000Z | maistra/vendor/com_github_google_quiche/quic/core/http/quic_spdy_stream.h | Maistra/proxy | 96b6aa184db650ec8c3a4b4e82eb54b0b9ab411f | [
"Apache-2.0"
] | 7 | 2019-07-04T14:23:54.000Z | 2020-04-27T08:52:51.000Z | // Copyright 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.
// The base class for streams which deliver data to/from an application.
// In each direction, the data on such a stream first contains compressed
// headers then body data.
#ifndef QUICHE_QUIC_CORE_HTTP_QUIC_SPDY_STREAM_H_
#define QUICHE_QUIC_CORE_HTTP_QUIC_SPDY_STREAM_H_
#include <sys/types.h>
#include <cstddef>
#include <list>
#include <memory>
#include <string>
#include "absl/base/attributes.h"
#include "absl/strings/string_view.h"
#include "absl/types/span.h"
#include "quic/core/http/http_decoder.h"
#include "quic/core/http/http_encoder.h"
#include "quic/core/http/quic_header_list.h"
#include "quic/core/http/quic_spdy_stream_body_manager.h"
#include "quic/core/qpack/qpack_decoded_headers_accumulator.h"
#include "quic/core/quic_error_codes.h"
#include "quic/core/quic_packets.h"
#include "quic/core/quic_stream.h"
#include "quic/core/quic_stream_sequencer.h"
#include "quic/core/quic_types.h"
#include "quic/core/web_transport_interface.h"
#include "quic/core/web_transport_stream_adapter.h"
#include "quic/platform/api/quic_export.h"
#include "quic/platform/api/quic_flags.h"
#include "quic/platform/api/quic_socket_address.h"
#include "spdy/core/spdy_framer.h"
#include "spdy/core/spdy_header_block.h"
namespace quic {
namespace test {
class QuicSpdyStreamPeer;
class QuicStreamPeer;
} // namespace test
class QuicSpdySession;
class WebTransportHttp3;
class QUIC_EXPORT_PRIVATE Http3DatagramContextExtensions {};
// A QUIC stream that can send and receive HTTP2 (SPDY) headers.
class QUIC_EXPORT_PRIVATE QuicSpdyStream
: public QuicStream,
public QpackDecodedHeadersAccumulator::Visitor {
public:
// Visitor receives callbacks from the stream.
class QUIC_EXPORT_PRIVATE Visitor {
public:
Visitor() {}
Visitor(const Visitor&) = delete;
Visitor& operator=(const Visitor&) = delete;
// Called when the stream is closed.
virtual void OnClose(QuicSpdyStream* stream) = 0;
// Allows subclasses to override and do work.
virtual void OnPromiseHeadersComplete(QuicStreamId /*promised_id*/,
size_t /*frame_len*/) {}
protected:
virtual ~Visitor() {}
};
QuicSpdyStream(QuicStreamId id,
QuicSpdySession* spdy_session,
StreamType type);
QuicSpdyStream(PendingStream* pending, QuicSpdySession* spdy_session);
QuicSpdyStream(const QuicSpdyStream&) = delete;
QuicSpdyStream& operator=(const QuicSpdyStream&) = delete;
~QuicSpdyStream() override;
// QuicStream implementation
void OnClose() override;
// Override to maybe close the write side after writing.
void OnCanWrite() override;
// Called by the session when headers with a priority have been received
// for this stream. This method will only be called for server streams.
virtual void OnStreamHeadersPriority(
const spdy::SpdyStreamPrecedence& precedence);
// Called by the session when decompressed headers have been completely
// delivered to this stream. If |fin| is true, then this stream
// should be closed; no more data will be sent by the peer.
virtual void OnStreamHeaderList(bool fin,
size_t frame_len,
const QuicHeaderList& header_list);
// Called by the session when decompressed push promise headers have
// been completely delivered to this stream.
virtual void OnPromiseHeaderList(QuicStreamId promised_id,
size_t frame_len,
const QuicHeaderList& header_list);
// Called by the session when a PRIORITY frame has been been received for this
// stream. This method will only be called for server streams.
void OnPriorityFrame(const spdy::SpdyStreamPrecedence& precedence);
// Override the base class to not discard response when receiving
// QUIC_STREAM_NO_ERROR.
void OnStreamReset(const QuicRstStreamFrame& frame) override;
void ResetWithError(QuicResetStreamError error) override;
bool OnStopSending(QuicResetStreamError error) override;
// Called by the sequencer when new data is available. Decodes the data and
// calls OnBodyAvailable() to pass to the upper layer.
void OnDataAvailable() override;
// Called in OnDataAvailable() after it finishes the decoding job.
virtual void OnBodyAvailable() = 0;
// Writes the headers contained in |header_block| on the dedicated headers
// stream or on this stream, depending on VersionUsesHttp3(). Returns the
// number of bytes sent, including data sent on the encoder stream when using
// QPACK.
virtual size_t WriteHeaders(
spdy::SpdyHeaderBlock header_block,
bool fin,
QuicReferenceCountedPointer<QuicAckListenerInterface> ack_listener);
// Sends |data| to the peer, or buffers if it can't be sent immediately.
void WriteOrBufferBody(absl::string_view data, bool fin);
// Writes the trailers contained in |trailer_block| on the dedicated headers
// stream or on this stream, depending on VersionUsesHttp3(). Trailers will
// always have the FIN flag set. Returns the number of bytes sent, including
// data sent on the encoder stream when using QPACK.
virtual size_t WriteTrailers(
spdy::SpdyHeaderBlock trailer_block,
QuicReferenceCountedPointer<QuicAckListenerInterface> ack_listener);
// Override to report newly acked bytes via ack_listener_.
bool OnStreamFrameAcked(QuicStreamOffset offset,
QuicByteCount data_length,
bool fin_acked,
QuicTime::Delta ack_delay_time,
QuicTime receive_timestamp,
QuicByteCount* newly_acked_length) override;
// Override to report bytes retransmitted via ack_listener_.
void OnStreamFrameRetransmitted(QuicStreamOffset offset,
QuicByteCount data_length,
bool fin_retransmitted) override;
// Does the same thing as WriteOrBufferBody except this method takes iovec
// as the data input. Right now it only calls WritevData.
QuicConsumedData WritevBody(const struct iovec* iov, int count, bool fin);
// Does the same thing as WriteOrBufferBody except this method takes
// memslicespan as the data input. Right now it only calls WriteMemSlices.
QuicConsumedData WriteBodySlices(absl::Span<QuicMemSlice> slices, bool fin);
// Marks the trailers as consumed. This applies to the case where this object
// receives headers and trailers as QuicHeaderLists via calls to
// OnStreamHeaderList(). Trailer data will be consumed from the sequencer only
// once all body data has been consumed.
void MarkTrailersConsumed();
// Clears |header_list_|.
void ConsumeHeaderList();
// This block of functions wraps the sequencer's functions of the same
// name. These methods return uncompressed data until that has
// been fully processed. Then they simply delegate to the sequencer.
virtual size_t Readv(const struct iovec* iov, size_t iov_len);
virtual int GetReadableRegions(iovec* iov, size_t iov_len) const;
void MarkConsumed(size_t num_bytes);
// Returns true if header contains a valid 3-digit status and parse the status
// code to |status_code|.
static bool ParseHeaderStatusCode(const spdy::SpdyHeaderBlock& header,
int* status_code);
// Returns true when all data from the peer has been read and consumed,
// including the fin.
bool IsDoneReading() const;
bool HasBytesToRead() const;
void set_visitor(Visitor* visitor) { visitor_ = visitor; }
bool headers_decompressed() const { return headers_decompressed_; }
// Returns total amount of body bytes that have been read.
uint64_t total_body_bytes_read() const;
const QuicHeaderList& header_list() const { return header_list_; }
bool trailers_decompressed() const { return trailers_decompressed_; }
// Returns whatever trailers have been received for this stream.
const spdy::SpdyHeaderBlock& received_trailers() const {
return received_trailers_;
}
// Returns true if headers have been fully read and consumed.
bool FinishedReadingHeaders() const;
// Returns true if FIN has been received and either trailers have been fully
// read and consumed or there are no trailers.
bool FinishedReadingTrailers() const;
// Returns true if the sequencer has delivered the FIN, and no more body bytes
// will be available.
bool IsSequencerClosed() { return sequencer()->IsClosed(); }
// QpackDecodedHeadersAccumulator::Visitor implementation.
void OnHeadersDecoded(QuicHeaderList headers,
bool header_list_size_limit_exceeded) override;
void OnHeaderDecodingError(QuicErrorCode error_code,
absl::string_view error_message) override;
QuicSpdySession* spdy_session() const { return spdy_session_; }
// Send PRIORITY_UPDATE frame and update |last_sent_urgency_| if
// |last_sent_urgency_| is different from current priority.
void MaybeSendPriorityUpdateFrame() override;
// Returns the WebTransport session owned by this stream, if one exists.
WebTransportHttp3* web_transport() { return web_transport_.get(); }
// Returns the WebTransport data stream associated with this QUIC stream, or
// null if this is not a WebTransport data stream.
WebTransportStream* web_transport_stream() {
if (web_transport_data_ == nullptr) {
return nullptr;
}
return &web_transport_data_->adapter;
}
// Sends a WEBTRANSPORT_STREAM frame and sets up the appropriate metadata.
void ConvertToWebTransportDataStream(WebTransportSessionId session_id);
void OnCanWriteNewData() override;
// If this stream is a WebTransport data stream, closes the connection with an
// error, and returns false.
bool AssertNotWebTransportDataStream(absl::string_view operation);
// Indicates whether a call to WriteBodySlices will be successful and not
// rejected due to buffer being full. |write_size| must be non-zero.
bool CanWriteNewBodyData(QuicByteCount write_size) const;
// Sends an HTTP/3 datagram. The stream and context IDs are not part of
// |payload|.
MessageStatus SendHttp3Datagram(
absl::optional<QuicDatagramContextId> context_id,
absl::string_view payload);
class QUIC_EXPORT_PRIVATE Http3DatagramVisitor {
public:
virtual ~Http3DatagramVisitor() {}
// Called when an HTTP/3 datagram is received. |payload| does not contain
// the stream or context IDs. Note that this contains the stream ID even if
// flow IDs from draft-ietf-masque-h3-datagram-00 are in use.
virtual void OnHttp3Datagram(
QuicStreamId stream_id,
absl::optional<QuicDatagramContextId> context_id,
absl::string_view payload) = 0;
};
class QUIC_EXPORT_PRIVATE Http3DatagramRegistrationVisitor {
public:
virtual ~Http3DatagramRegistrationVisitor() {}
// Called when a REGISTER_DATAGRAM_CONTEXT or REGISTER_DATAGRAM_NO_CONTEXT
// capsule is received. Note that this contains the stream ID even if flow
// IDs from draft-ietf-masque-h3-datagram-00 are in use.
virtual void OnContextReceived(
QuicStreamId stream_id,
absl::optional<QuicDatagramContextId> context_id,
const Http3DatagramContextExtensions& extensions) = 0;
// Called when a CLOSE_DATAGRAM_CONTEXT capsule is received. Note that this
// contains the stream ID even if flow IDs from
// draft-ietf-masque-h3-datagram-00 are in use.
virtual void OnContextClosed(
QuicStreamId stream_id,
absl::optional<QuicDatagramContextId> context_id,
const Http3DatagramContextExtensions& extensions) = 0;
};
// Registers |visitor| to receive HTTP/3 datagram context registrations. This
// must not be called without first calling
// UnregisterHttp3DatagramRegistrationVisitor. |visitor| must be valid until a
// corresponding call to UnregisterHttp3DatagramRegistrationVisitor.
void RegisterHttp3DatagramRegistrationVisitor(
Http3DatagramRegistrationVisitor* visitor);
// Unregisters for HTTP/3 datagram context registrations. Must not be called
// unless previously registered.
void UnregisterHttp3DatagramRegistrationVisitor();
// Moves an HTTP/3 datagram registration to a different visitor. Mainly meant
// to be used by the visitors' move operators.
void MoveHttp3DatagramRegistration(Http3DatagramRegistrationVisitor* visitor);
// Registers |visitor| to receive HTTP/3 datagrams for optional context ID
// |context_id|. This must not be called on a previously registered context ID
// without first calling UnregisterHttp3DatagramContextId. |visitor| must be
// valid until a corresponding call to UnregisterHttp3DatagramContextId. If
// this method is called multiple times, the context ID MUST either be always
// present, or always absent.
void RegisterHttp3DatagramContextId(
absl::optional<QuicDatagramContextId> context_id,
const Http3DatagramContextExtensions& extensions,
Http3DatagramVisitor* visitor);
// Unregisters an HTTP/3 datagram context ID. Must be called on a previously
// registered context.
void UnregisterHttp3DatagramContextId(
absl::optional<QuicDatagramContextId> context_id);
// Moves an HTTP/3 datagram context ID to a different visitor. Mainly meant
// to be used by the visitors' move operators.
void MoveHttp3DatagramContextIdRegistration(
absl::optional<QuicDatagramContextId> context_id,
Http3DatagramVisitor* visitor);
// Sets max datagram time in queue.
void SetMaxDatagramTimeInQueue(QuicTime::Delta max_time_in_queue);
// Generates a new HTTP/3 datagram context ID for this stream. A datagram
// registration visitor must be currently registered on this stream.
QuicDatagramContextId GetNextDatagramContextId();
void OnDatagramReceived(QuicDataReader* reader);
void RegisterHttp3DatagramFlowId(QuicDatagramStreamId flow_id);
protected:
// Called when the received headers are too large. By default this will
// reset the stream.
virtual void OnHeadersTooLarge();
virtual void OnInitialHeadersComplete(bool fin,
size_t frame_len,
const QuicHeaderList& header_list);
virtual void OnTrailingHeadersComplete(bool fin,
size_t frame_len,
const QuicHeaderList& header_list);
virtual size_t WriteHeadersImpl(
spdy::SpdyHeaderBlock header_block,
bool fin,
QuicReferenceCountedPointer<QuicAckListenerInterface> ack_listener);
Visitor* visitor() { return visitor_; }
void set_headers_decompressed(bool val) { headers_decompressed_ = val; }
void set_ack_listener(
QuicReferenceCountedPointer<QuicAckListenerInterface> ack_listener) {
ack_listener_ = std::move(ack_listener);
}
void OnWriteSideInDataRecvdState() override;
private:
friend class test::QuicSpdyStreamPeer;
friend class test::QuicStreamPeer;
friend class QuicStreamUtils;
class HttpDecoderVisitor;
struct QUIC_EXPORT_PRIVATE WebTransportDataStream {
WebTransportDataStream(QuicSpdyStream* stream,
WebTransportSessionId session_id);
WebTransportSessionId session_id;
WebTransportStreamAdapter adapter;
};
// Called by HttpDecoderVisitor.
bool OnDataFrameStart(QuicByteCount header_length,
QuicByteCount payload_length);
bool OnDataFramePayload(absl::string_view payload);
bool OnDataFrameEnd();
bool OnHeadersFrameStart(QuicByteCount header_length,
QuicByteCount payload_length);
bool OnHeadersFramePayload(absl::string_view payload);
bool OnHeadersFrameEnd();
void OnWebTransportStreamFrameType(QuicByteCount header_length,
WebTransportSessionId session_id);
bool OnUnknownFrameStart(uint64_t frame_type,
QuicByteCount header_length,
QuicByteCount payload_length);
bool OnUnknownFramePayload(absl::string_view payload);
bool OnUnknownFrameEnd();
// Given the interval marked by [|offset|, |offset| + |data_length|), return
// the number of frame header bytes contained in it.
QuicByteCount GetNumFrameHeadersInInterval(QuicStreamOffset offset,
QuicByteCount data_length) const;
void MaybeProcessSentWebTransportHeaders(spdy::SpdyHeaderBlock& headers);
void MaybeProcessReceivedWebTransportHeaders();
// Writes HTTP/3 DATA frame header. If |force_write| is true, use
// WriteOrBufferData if send buffer cannot accomodate the header + data.
ABSL_MUST_USE_RESULT bool WriteDataFrameHeader(QuicByteCount data_length,
bool force_write);
QuicSpdySession* spdy_session_;
bool on_body_available_called_because_sequencer_is_closed_;
Visitor* visitor_;
// True if read side processing is blocked while waiting for callback from
// QPACK decoder.
bool blocked_on_decoding_headers_;
// True if the headers have been completely decompressed.
bool headers_decompressed_;
// True if uncompressed headers or trailers exceed maximum allowed size
// advertised to peer via SETTINGS_MAX_HEADER_LIST_SIZE.
bool header_list_size_limit_exceeded_;
// Contains a copy of the decompressed header (name, value) pairs until they
// are consumed via Readv.
QuicHeaderList header_list_;
// Length of most recently received HEADERS frame payload.
QuicByteCount headers_payload_length_;
// True if the trailers have been completely decompressed.
bool trailers_decompressed_;
// True if the trailers have been consumed.
bool trailers_consumed_;
// The parsed trailers received from the peer.
spdy::SpdyHeaderBlock received_trailers_;
// Headers accumulator for decoding HEADERS frame payload.
std::unique_ptr<QpackDecodedHeadersAccumulator>
qpack_decoded_headers_accumulator_;
// Visitor of the HttpDecoder.
std::unique_ptr<HttpDecoderVisitor> http_decoder_visitor_;
// HttpDecoder for processing raw incoming stream frames.
HttpDecoder decoder_;
// Object that manages references to DATA frame payload fragments buffered by
// the sequencer and calculates how much data should be marked consumed with
// the sequencer each time new stream data is processed.
QuicSpdyStreamBodyManager body_manager_;
// Sequencer offset keeping track of how much data HttpDecoder has processed.
// Initial value is zero for fresh streams, or sequencer()->NumBytesConsumed()
// at time of construction if a PendingStream is converted to account for the
// length of the unidirectional stream type at the beginning of the stream.
QuicStreamOffset sequencer_offset_;
// True when inside an HttpDecoder::ProcessInput() call.
// Used for detecting reentrancy.
bool is_decoder_processing_input_;
// Ack listener of this stream, and it is notified when any of written bytes
// are acked or retransmitted.
QuicReferenceCountedPointer<QuicAckListenerInterface> ack_listener_;
// Offset of unacked frame headers.
QuicIntervalSet<QuicStreamOffset> unacked_frame_headers_offsets_;
// Urgency value sent in the last PRIORITY_UPDATE frame, or default urgency
// defined by the spec if no PRIORITY_UPDATE frame has been sent.
int last_sent_urgency_;
// If this stream is a WebTransport extended CONNECT stream, contains the
// WebTransport session associated with this stream.
std::unique_ptr<WebTransportHttp3> web_transport_;
// If this stream is a WebTransport data stream, |web_transport_data_|
// contains all of the associated metadata.
std::unique_ptr<WebTransportDataStream> web_transport_data_;
// HTTP/3 Datagram support.
Http3DatagramRegistrationVisitor* datagram_registration_visitor_ = nullptr;
Http3DatagramVisitor* datagram_no_context_visitor_ = nullptr;
absl::optional<QuicDatagramStreamId> datagram_flow_id_;
QuicDatagramContextId datagram_next_available_context_id_;
absl::flat_hash_map<QuicDatagramContextId, Http3DatagramVisitor*>
datagram_context_visitors_;
};
} // namespace quic
#endif // QUICHE_QUIC_CORE_HTTP_QUIC_SPDY_STREAM_H_
| 41.422222 | 80 | 0.742294 | [
"object"
] |
65b7629ea20cd6b4bd2daa1a3420a0a306039fc9 | 3,436 | h | C | Modules/Learning/DempsterShafer/include/otbJointMassOfBeliefFilter.h | heralex/OTB | c52b504b64dc89c8fe9cac8af39b8067ca2c3a57 | [
"Apache-2.0"
] | 317 | 2015-01-19T08:40:58.000Z | 2022-03-17T11:55:48.000Z | Modules/Learning/DempsterShafer/include/otbJointMassOfBeliefFilter.h | guandd/OTB | 707ce4c6bb4c7186e3b102b2b00493a5050872cb | [
"Apache-2.0"
] | 18 | 2015-07-29T14:13:45.000Z | 2021-03-29T12:36:24.000Z | Modules/Learning/DempsterShafer/include/otbJointMassOfBeliefFilter.h | guandd/OTB | 707ce4c6bb4c7186e3b102b2b00493a5050872cb | [
"Apache-2.0"
] | 132 | 2015-02-21T23:57:25.000Z | 2022-03-25T16:03:16.000Z | /*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 otbJointMassOfBeliefFilter_h
#define otbJointMassOfBeliefFilter_h
#include "itkProcessObject.h"
namespace otb
{
/** \class JointMassOfBeliefFilter
* \brief Performs Dempster-Shafer combination of n masses function.
*
* This filter computes the joint mass of n input masses using
* Dempster-Shafer rule of combination.
*
* Input masses can be added by using the PushBackInput() method.
*
* \sa MassOfBelief
*
* \ingroup OTBDempsterShafer
*/
template <class TMassFunction>
class ITK_EXPORT JointMassOfBeliefFilter : public itk::ProcessObject
{
public:
/** Standard class typedefs */
typedef JointMassOfBeliefFilter Self;
typedef itk::ProcessObject Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Method for creation through the object factory. */
itkNewMacro(Self);
/** Run-time type information (and related methods). */
itkTypeMacro(JointMassOfBeliefFilter, ProcessObject);
/** Standard class typedefs */
typedef TMassFunction MassFunctionType;
typedef typename MassFunctionType::Pointer MassFunctionPointerType;
typedef typename MassFunctionType::LabelType LabelType;
typedef typename MassFunctionType::MassType MassType;
typedef typename MassFunctionType::LabelSetType LabelSetType;
typedef typename MassFunctionType::LabelSetOfSetType LabelSetOfSetType;
/** Add an input to the end */
using Superclass::PushBackInput;
virtual void PushBackInput(const MassFunctionType* input);
/** Add an input to the front */
using Superclass::PushFrontInput;
virtual void PushFrontInput(const MassFunctionType* input);
/** Remove the last input */
using Superclass::PopBackInput;
void PopBackInput() override;
/** Remove the first input */
using Superclass::PopFrontInput;
void PopFrontInput() override;
/** Get the idx th input */
const MassFunctionType* GetInput(unsigned int idx);
/** Get the output joint mass */
MassFunctionType* GetOutput();
protected:
/** Constructor */
JointMassOfBeliefFilter();
/** Destructor */
~JointMassOfBeliefFilter() override
{
}
/** GenerateData */
void GenerateData() override;
/** PrintSelf method */
void PrintSelf(std::ostream& os, itk::Indent indent) const override;
private:
JointMassOfBeliefFilter(const Self&) = delete;
void operator=(const Self&) = delete;
/** Combine masses from input and output into output */
void CombineMasses(const MassFunctionType* input, MassFunctionType* output);
};
} // end namespace otb
#ifndef OTB_MANUAL_INSTANTIATION
#include "otbJointMassOfBeliefFilter.hxx"
#endif
#endif
| 29.62069 | 79 | 0.729045 | [
"object"
] |
65b8de0fd79c2f7f2e034b753905371343e66903 | 14,183 | h | C | features/FEATURE_CLIENT/mbed-client/source/include/m2minterfaceimpl.h | matthewelse/mbed-os | dce72d52fbb106eac148e00cbc20e03259c40425 | [
"Apache-2.0"
] | 3 | 2018-03-13T13:42:12.000Z | 2019-05-17T11:48:04.000Z | features/FEATURE_CLIENT/mbed-client/source/include/m2minterfaceimpl.h | matthewelse/mbed-os | dce72d52fbb106eac148e00cbc20e03259c40425 | [
"Apache-2.0"
] | null | null | null | features/FEATURE_CLIENT/mbed-client/source/include/m2minterfaceimpl.h | matthewelse/mbed-os | dce72d52fbb106eac148e00cbc20e03259c40425 | [
"Apache-2.0"
] | 8 | 2018-01-28T02:23:18.000Z | 2021-02-26T01:15:55.000Z | /*
* Copyright (c) 2015 ARM Limited. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
* 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 M2M_INTERFACE_IMPL_H
#define M2M_INTERFACE_IMPL_H
#include "mbed-client/m2minterface.h"
#include "mbed-client/m2mserver.h"
#include "mbed-client/m2mconnectionobserver.h"
#include "mbed-client/m2mconnectionsecurity.h"
#include "include/m2mnsdlobserver.h"
#include "mbed-client/m2mtimerobserver.h"
//FORWARD DECLARATION
class M2MNsdlInterface;
class M2MConnectionHandler;
class M2MConnectionSecurity;
class EventData;
class M2MTimer;
/**
* @brief M2MInterfaceImpl.
* This class implements handling of all mbed Client Interface operations
* defined in OMA LWM2M specifications.
* This includes Bootstrapping, Client Registration, Device Management &
* Service Enablement and Information Reporting.
*/
class M2MInterfaceImpl : public M2MInterface,
public M2MNsdlObserver,
public M2MConnectionObserver,
public M2MTimerObserver
{
private:
// Prevents the use of assignment operator by accident.
M2MInterfaceImpl& operator=( const M2MInterfaceImpl& /*other*/ );
// Prevents the use of copy constructor by accident
M2MInterfaceImpl( const M2MInterfaceImpl& /*other*/ );
friend class M2MInterfaceFactory;
private:
/**
* @brief Constructor
* @param observer, Observer to pass the event callbacks for various
* interface operations.
* @param endpoint_name, Endpoint name of the client.
* @param endpoint_type, Endpoint type of the client.
* @param life_time, Life time of the client in seconds
* @param listen_port, Listening port for the endpoint, default is 8000.
* @param domain, Domain of the client.
* @param mode, Binding mode of the client, default is UDP
* @param stack, Network Stack to be used for connection, default is LwIP_IPv4
* @param context_address, Context address default is empty.
*/
M2MInterfaceImpl(M2MInterfaceObserver& observer,
const String &endpoint_name,
const String &endpoint_type,
const int32_t life_time,
const uint16_t listen_port,
const String &domain = "",
BindingMode mode = M2MInterface::NOT_SET,
M2MInterface::NetworkStack stack = M2MInterface::LwIP_IPv4,
const String &context_address = "");
public:
/**
* @brief Destructor
*/
virtual ~M2MInterfaceImpl();
/**
* @brief Initiates bootstrapping of the client with the provided Bootstrap
* server information.
* @param security_object, Security object which contains information
* required for successful bootstrapping of the client.
*/
virtual void bootstrap(M2MSecurity *security);
/**
* @brief Cancels on going bootstrapping operation of the client. If the client has
* already successfully bootstrapped then this function deletes existing
* bootstrap information from the client.
*/
virtual void cancel_bootstrap();
/**
* @brief Initiates registration of the provided Security object to the
* corresponding LWM2M server.
* @param security_object, Security object which contains information
* required for registering to the LWM2M server.
* If client wants to register to multiple LWM2M servers then it has call
* this function once for each of LWM2M server object separately.
* @param object_list, Objects which contains information
* which the client want to register to the LWM2M server.
*/
virtual void register_object(M2MSecurity *security_object, const M2MObjectList &object_list);
/**
* @brief Updates or refreshes the client's registration on the LWM2M
* server.
* @param security_object, Security object from which the device object
* needs to update registration, if there is only one LWM2M server registered
* then this parameter can be NULL.
* @param lifetime, Lifetime for the endpoint client in seconds.
*/
virtual void update_registration(M2MSecurity *security_object, const uint32_t lifetime = 0);
/**
* @brief Unregisters the registered object from the LWM2M server
* @param security_object, Security object from which the device object
* needs to be unregistered, if there is only one LWM2M server registered
* then this parameter can be NULL.
*/
virtual void unregister_object(M2MSecurity* security = NULL);
/**
* @brief Sets the function which will be called indicating client
* is going to sleep when the Binding mode is selected with Queue mode.
* @param callback, Function pointer which will be called when client
* goes to seleep.
*/
virtual void set_queue_sleep_handler(callback_handler handler);
/**
* @brief Sets the network interface handler that is used by client to connect
* to a network over IP..
* @param handler A network interface handler that is used by client to connect.
* This API is optional but provides a mechanism for different platforms to
* manage usage of underlying network interface by client.
*/
virtual void set_platform_network_handler(void *handler = NULL);
/**
* \brief Sets the function callback that will be called by mbed-client for
* fetching random number from application for ensuring strong entropy.
* \param random_callback A function pointer that will be called by mbed-client
* while performing secure handshake.
* Function signature should be uint32_t (*random_number_callback)(void);
*/
virtual void set_random_number_callback(random_number_cb callback);
/**
* \brief Sets the function callback that will be called by mbed-client for
* providing entropy source from application for ensuring strong entropy.
* \param entropy_callback A function pointer that will be called by mbed-client
* while performing secure handshake.
* Function signature , if using mbed-client-mbedtls should be
* int (*mbedtls_entropy_f_source_ptr)(void *data, unsigned char *output,
* size_t len, size_t *olen);
*/
virtual void set_entropy_callback(entropy_cb callback);
protected: // From M2MNsdlObserver
virtual void coap_message_ready(uint8_t *data_ptr,
uint16_t data_len,
sn_nsdl_addr_s *address_ptr);
virtual void client_registered(M2MServer *server_object);
virtual void registration_updated(const M2MServer &server_object);
virtual void registration_error(uint8_t error_code, bool retry = false);
virtual void client_unregistered();
virtual void bootstrap_done(M2MSecurity *security_object);
virtual void bootstrap_error();
virtual void coap_data_processed();
virtual void value_updated(M2MBase *base);
protected: // From M2MConnectionObserver
virtual void data_available(uint8_t* data,
uint16_t data_size,
const M2MConnectionObserver::SocketAddress &address);
virtual void socket_error(uint8_t error_code, bool retry = true);
virtual void address_ready(const M2MConnectionObserver::SocketAddress &address,
M2MConnectionObserver::ServerType server_type,
const uint16_t server_port);
virtual void data_sent();
protected: // from M2MTimerObserver
virtual void timer_expired(M2MTimerObserver::Type type);
private: // state machine state functions
/**
* When the state is Idle.
*/
void state_idle(EventData* data);
/**
* When the client starts bootstrap.
*/
void state_bootstrap( EventData *data);
/**
* When the bootstrap server address is resolved.
*/
void state_bootstrap_address_resolved( EventData *data);
/**
* When the bootstrap resource is created.
*/
void state_bootstrap_resource_created( EventData *data);
/**
* When the server has sent response and bootstrapping is done.
*/
void state_bootstrapped( EventData *data);
/**
* When the client starts register.
*/
void state_register( EventData *data);
/**
* When the server address for register is resolved.
*/
void state_register_address_resolved( EventData *data);
/**
* When the register resource is created.
*/
void state_register_resource_created( EventData *data);
/**
* When the client is registered.
*/
void state_registered( EventData *data);
/**
* When the client is updating registration.
*/
void state_update_registration( EventData *data);
/**
* When the client starts unregister.
*/
void state_unregister( EventData *data);
/**
* When the client has been unregistered.
*/
void state_unregistered( EventData *data);
/**
* When the coap data is been sent through socket.
*/
void state_sending_coap_data( EventData *data);
/**
* When the coap data is sent successfully.
*/
void state_coap_data_sent( EventData *data);
/**
* When the socket is receiving coap data.
*/
void state_receiving_coap_data( EventData *data);
/**
* When the socket has received coap data.
*/
void state_coap_data_received( EventData *data);
/**
* When the coap message is being processed.
*/
void state_processing_coap_data( EventData *data);
/**
* When the coap message has been processed.
*/
void state_coap_data_processed( EventData *data);
/**
* When the client is waiting to receive or send data.
*/
void state_waiting( EventData *data);
/**
* State enumeration order must match the order of state
* method entries in the state map
*/
enum E_States {
STATE_IDLE = 0,
STATE_BOOTSTRAP,
STATE_BOOTSTRAP_ADDRESS_RESOLVED,
STATE_BOOTSTRAP_RESOURCE_CREATED,
STATE_BOOTSTRAPPED,
STATE_REGISTER, //5
STATE_REGISTER_ADDRESS_RESOLVED,
STATE_REGISTER_RESOURCE_CREATED,
STATE_REGISTERED,
STATE_UPDATE_REGISTRATION,
STATE_UNREGISTER, //10
STATE_UNREGISTERED,
STATE_SENDING_COAP_DATA,
STATE_COAP_DATA_SENT,
STATE_COAP_DATA_RECEIVED,
STATE_PROCESSING_COAP_DATA, //15
STATE_COAP_DATA_PROCESSED,
STATE_WAITING,
STATE_MAX_STATES
};
/**
* @brief Redirects the state machine to right function.
* @param current_state Current state to be set.
* @param data, Data to be passed to the state function.
*/
void state_function( uint8_t current_state, EventData* data );
/**
* @brief State Engine maintaining state machine logic.
*/
void state_engine(void);
/**
* External event which can trigger the state machine.
* @param New State which the state machine should go to.
* @param data to be passed to the state machine.
*/
void external_event(uint8_t, EventData* = NULL);
/**
* Internal event generated by state machine.
* @param New State which the state machine should go to.
* @param data to be passed to the state machine.
*/
void internal_event(uint8_t, EventData* = NULL);
enum
{
EVENT_IGNORED = 0xFE,
CANNOT_HAPPEN
};
/**
* Helper method for extracting the IP address part and port from the
* given server address.
* @param server_address source url (without "coap" or "coaps" prefix)
* @param ip_address extracted IP
* @param port extracted port
*/
static void process_address(const String& server_address, String& ip_address, uint16_t& port);
private:
M2MInterfaceObserver &_observer;
M2MConnectionHandler *_connection_handler;
M2MConnectionSecurity *_security_connection; // Doesn't own
M2MNsdlInterface *_nsdl_interface;
uint8_t _current_state;
const int _max_states;
bool _event_generated;
EventData *_event_data;
String _endpoint_type;
String _domain;
int32_t _life_time;
BindingMode _binding_mode;
String _context_address;
uint16_t _listen_port;
uint16_t _server_port;
String _server_ip_address;
M2MSecurity *_register_server; //TODO: to be the list not owned
bool _event_ignored;
bool _register_ongoing;
bool _update_register_ongoing;
M2MTimer *_queue_sleep_timer;
M2MTimer *_retry_timer;
M2MTimer *_bootstrap_timer;
callback_handler _callback_handler;
M2MSecurity *_security;
uint8_t _retry_count;
bool _reconnecting;
bool _retry_timer_expired;
friend class Test_M2MInterfaceImpl;
};
#define BEGIN_TRANSITION_MAP \
static const uint8_t TRANSITIONS[] = {\
#define TRANSITION_MAP_ENTRY(entry)\
entry,
#define END_TRANSITION_MAP(data) \
0 };\
external_event(TRANSITIONS[_current_state], data);
#endif //M2M_INTERFACE_IMPL_H
| 33.529551 | 98 | 0.661285 | [
"object"
] |
65bc8505e2820f07e8f621ec3b6fbeecac75e562 | 8,088 | c | C | tests/pcduino/test_stab_cycle.c | YaoQ/wilddog-sdk-on-pcduino | e93ed39f8a2d9431c0c287e71962771dd61714ca | [
"MIT"
] | null | null | null | tests/pcduino/test_stab_cycle.c | YaoQ/wilddog-sdk-on-pcduino | e93ed39f8a2d9431c0c287e71962771dd61714ca | [
"MIT"
] | null | null | null | tests/pcduino/test_stab_cycle.c | YaoQ/wilddog-sdk-on-pcduino | e93ed39f8a2d9431c0c287e71962771dd61714ca | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2014-2016 Wilddog Technologies. All Rights Reserved.
*
* FileName: test_stab.c
*
* Description: connection functions.
*
* History:
* Version Author Date Description
*
* 0.4.0 lxs 2015-07-18 Create file.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#if defined(WILDDOG_PORT_TYPE_WICED)
#include "wiced.h"
#include "wifi_config_dct.h"
#else
#include <unistd.h>
#endif
#include "wilddog.h"
#include "wilddog_url_parser.h"
#include "wilddog_api.h"
#include "wilddog_ct.h"
#include "test_lib.h"
#include "test_config.h"
#ifdef WILDDOG_SELFTEST
#define STABTEST_ONEHOUR (3600000)
#define STAB_DEBUG 0
#define STABTEST_PATH "stabtest/"
#define STAB_KEY "K"
#define STAB_DATA "D"
#define STABTEST_KEY "stability_key"
#define STABTEST_VALUE "stability_value:"
#define STABTEST_ONREQUEST(cmd) ((cmd) == STABTEST_CMD_ON)
#define STABTEST_OFFREQUEST(cmd) ((cmd) == STABTEST_CMD_OFF)
#define STABTEST_NEXTREQUEST(cmd) ((cmd) = ((cmd) == STABTEST_CMD_OFF)? \
STABTEST_CMD_ON:((cmd)+1))
typedef enum _STABTEST_CMD_TYPE
{
STABTEST_CMD_NON = 0,
STABTEST_CMD_ON,
STABTEST_CMD_GET,
STABTEST_CMD_SET,
STABTEST_CMD_PUSH,
STABTEST_CMD_DELE,
STABTEST_CMD_OFF
}STABTEST_CMD_TYPE;
typedef struct STAB_SETDATA_T
{
u8 key[10];
u8 data[10];
u8 setfault;
Wilddog_Node_T *p_node;
Wilddog_T client;
}Stab_Setdata_T;
STATIC u32 stab_runtime;
STATIC u32 stab_requests;
STATIC u32 stab_requestFault;
STATIC u32 stab_recvFault;
STATIC u32 stab_recvSucc;
STATIC u32 stab_pushSuccess;
STATIC u32 stab_changetime;
STATIC u32 stab_cmd;
STATIC void stab_set_runtime(void)
{
#if defined(WILDDOG_PORT_TYPE_WICED)
static u32 stab_startime =0;
u32 currentTm_ms =0;
wiced_time_t t1;
wiced_time_get_time(&t1);
currentTm_ms = (u32)t1;
if(stab_startime == 0 )
stab_startime = currentTm_ms;
stab_runtime = currentTm_ms - stab_startime;
#endif
}
STATIC void stab_get_requestRes(Wilddog_Return_T res)
{
if(res < 0 )
{
printf("\tin %lu; send %lu requestErr= %d\n",stab_runtime,stab_cmd,res);
stab_requestFault++;
}
else
{
/* off with no recv callback*/
if(stab_cmd == STABTEST_CMD_OFF)
{
stab_recvSucc++;
}
}
stab_requests++;
}
STATIC void stab_get_recvErr(Wilddog_Return_T err,u32 methtype)
{
if(err < WILDDOG_HTTP_OK || err >= WILDDOG_HTTP_NOT_MODIFIED)
{
printf("in %lu; methtype = %lu recvErr= %d \n",stab_runtime,methtype,err);
if(err == WILDDOG_ERR_RECVTIMEOUT)
stab_recvFault++;
}
else
{
if(methtype != STABTEST_CMD_GET )
stab_changetime++;
stab_recvSucc++;
}
}
STATIC void stab_getValueFunc
(
const Wilddog_Node_T* p_snapshot,
void* arg,
Wilddog_Return_T err
)
{
stab_get_recvErr(err,STABTEST_CMD_GET);
*(BOOL*)arg = TRUE;
return;
}
STATIC void stab_removeValueFunc(void* arg, Wilddog_Return_T err)
{
stab_get_recvErr(err,STABTEST_CMD_DELE);
*(BOOL*)arg = TRUE;
return;
}
STATIC void stab_setValueFunc(void* arg, Wilddog_Return_T err)
{
stab_get_recvErr(err,STABTEST_CMD_SET);
*(BOOL*)arg = TRUE;
return;
}
STATIC void stab_pushFunc(u8 *p_path,void* arg, Wilddog_Return_T err)
{
stab_get_recvErr(err,STABTEST_CMD_PUSH);
*(BOOL*)arg = TRUE;
return;
}
STATIC void stab_addObserverFunc
(
const Wilddog_Node_T* p_snapshot,
void* arg,
Wilddog_Return_T err
)
{
stab_get_recvErr(err,STABTEST_CMD_ON);
if(err < WILDDOG_HTTP_OK || err >= WILDDOG_HTTP_NOT_MODIFIED)
;
else
stab_pushSuccess++;
*(BOOL*)arg = TRUE;
return;
}
int stabtest_request(STABTEST_CMD_TYPE type,Wilddog_T client,BOOL *p_finishFlag)
{
Wilddog_Node_T *p_head = NULL,*p_node = NULL;
int res = 0;
/*Create an node which type is an object*/
p_head = wilddog_node_createObject(NULL);
/*Create an node which type is UTF-8 Sring*/
p_node = wilddog_node_createUString((Wilddog_Str_T *)STABTEST_KEY,(Wilddog_Str_T *)STABTEST_VALUE);
/*Add p_node to p_head, then p_node is the p_head's child node*/
wilddog_node_addChild(p_head, p_node);
stab_cmd = type;
switch(type)
{
case STABTEST_CMD_GET:
/*Send the query method*/
res = wilddog_getValue(client, (onQueryFunc)stab_getValueFunc, (void*)p_finishFlag);
break;
case STABTEST_CMD_SET:
/*Send the set method*/
res = wilddog_setValue(client,p_head,stab_setValueFunc,(void*)p_finishFlag);
break;
case STABTEST_CMD_PUSH:
/*Send the push method*/
res = wilddog_push(client, p_head, stab_pushFunc, (void *)p_finishFlag);
break;
case STABTEST_CMD_DELE:
/*Send the remove method*/
res = wilddog_removeValue(client, stab_removeValueFunc, (void*)p_finishFlag);
break;
case STABTEST_CMD_ON:
/*Observe on*/
res = wilddog_addObserver(client, WD_ET_VALUECHANGE, stab_addObserverFunc, (void*)p_finishFlag);
break;
case STABTEST_CMD_OFF:
res = wilddog_removeObserver(client, WD_ET_VALUECHANGE);
break;
case STABTEST_CMD_NON:
default:
break;
}
/*Delete the node*/
wilddog_node_delete(p_head);
return res;
}
STATIC void stab_trysync(void)
{
stab_set_runtime();
ramtest_getAveragesize();
/*Handle the event and callback function, it must be called in a special frequency*/
wilddog_trySync();
}
int stab_oneCrcuRequest(void)
{
int res = 0;
BOOL otherFinish = FALSE,onFinish = FALSE;
BOOL *p_finish = &onFinish;
Wilddog_T client = 0;
STABTEST_CMD_TYPE cmd = STABTEST_CMD_ON;
/* mark star time*/
stab_set_runtime();
/*Init a wilddog client*/
client = wilddog_initWithUrl((Wilddog_Str_T *)TEST_URL);
stab_get_requestRes(stabtest_request(cmd,client,p_finish));
while(1)
{
if(TRUE == *p_finish)
{
if(STABTEST_ONREQUEST(cmd))
p_finish = &otherFinish;
onFinish = FALSE;
otherFinish = FALSE;
STABTEST_NEXTREQUEST(cmd);
stab_get_requestRes(stabtest_request(cmd,client,p_finish));
if(STABTEST_OFFREQUEST(cmd))
{
break;
}
}
stab_trysync();
}
/*Destroy the wilddog clent and release the memory*/
res = wilddog_destroy(&client);
return res;
}
void stab_titlePrint(void)
{
printf("\t>----------------------------------------------------<\n");
printf("\tcount\truntime\tram\tUnlaunchRatio\tLostRatio \n");
}
void stab_endPrint(void)
{
printf("\t>----------------------------------------------------<\n");
}
void stab_resultPrint(void)
{
char unlaunchRatio[20];
char lossRatio[20];
char successRatio[20];
char settest_succRatio[20];
static u32 run_cnt =0;
#if defined(WILDDOG_PORT_TYPE_WICED)
if(stab_runtime/STABTEST_ONEHOUR <= run_cnt)
return ;
#endif
memset(unlaunchRatio,0,20);
memset(lossRatio,0,20);
memset(successRatio,0,20);
memset(settest_succRatio,0,20);
sprintf(unlaunchRatio,"%lu/%lu",stab_requestFault,stab_requests);
sprintf(lossRatio,"%lu/%lu",stab_recvFault,stab_requests);
//sprintf(successRatio,"%lu/%lu",stab_pushSuccess,stab_changetime);
printf("\t%lu",++run_cnt);
printf("\t%lu",stab_runtime);
printf("\t%lu",(u32)ramtest_get_averageRam());
printf("\t%s",unlaunchRatio);
printf("\t\t%s",lossRatio);
//printf("\t\t%s",successRatio);
printf("\n");
return;
}
void stab_test_cycle(void)
{
ramtest_init(1,1);
stab_titlePrint();
while(1)
{
stab_oneCrcuRequest();
stab_resultPrint();
}
stab_endPrint();
}
int main(void)
{
stab_test_cycle();
return 0;
}
#endif /* WILDDOG_SELFTEST*/
| 23.443478 | 109 | 0.644659 | [
"object"
] |
65c17dd5dfa04223e5ab25bb444567fa34a8a26b | 6,982 | h | C | include/core/input.h | AlejandroC1983/cvrtgi | 9894fc79d4036a0490dbc194b9d04654574f16d4 | [
"Apache-2.0"
] | 2 | 2022-03-25T00:37:25.000Z | 2022-03-26T00:13:53.000Z | include/core/input.h | AlejandroC1983/cvrtgi | 9894fc79d4036a0490dbc194b9d04654574f16d4 | [
"Apache-2.0"
] | null | null | null | include/core/input.h | AlejandroC1983/cvrtgi | 9894fc79d4036a0490dbc194b9d04654574f16d4 | [
"Apache-2.0"
] | 1 | 2022-03-02T21:11:29.000Z | 2022-03-02T21:11:29.000Z | /*
Copyright 2022 Alejandro Cosin & Gustavo Patow
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 _INPUT_H_
#define _INPUT_H_
// GLOBAL INCLUDES
#include "../../external/nano-signal-slot/nano_signal_slot.hpp"
// PROJECT INCLUDES
#include "../headers.h"
#include "../../include/util/singleton.h"
#include "../../include/util/getsetmacros.h"
#include "../../include/core/eventsignalslot.h"
#include "../../include/core/coreenum.h"
#include "../../include/util/containerutilities.h"
// CLASS FORWARDING
// NAMESPACE
using namespace coreenum;
// DEFINES
#define inputM s_pInputSingleton->instance()
/////////////////////////////////////////////////////////////////////////////////////////////
class Input : public Singleton<Input>
{
public:
/** Default constructor
* @return nothing */
Input();
/** Default destructor
* @return nothing */
~Input();
/** Update input according to the Windows message given by message
* @param message [in] message to process
* @return nothing */
void updateInput(MSG& message);
/** Update keyboard input from user
* @return nothing */
void updateKeyboard();
/** Returns the cursor position
* @param x [out] x posiiton of the cursor
* @param y [out] y posiiton of the cursor
* @return nothing */
void getCursorPos(int32_t &x, int32_t &y);
/** Sets the cursor position
* @param x [out] x position of the cursor
* @param y [out] y position of the cursor
* @return nothing */
void setCursorPos(int32_t x, int32_t y);
/** Method called in updateInput when there're events of mouse movement of mouse button
* down / up
* @param action [in] Type of event regarding the mouse
* @param x [in] Mouse x screen coordinate
* @param y [in] Mouse y screen coordinate
* @param btn [in] Mouse button pressed / released
* @param wheelDelta [in] Mouse wheel delta sign (if any)
* @return nothing */
void MouseEvent(ActionCode action, int32_t x, int32_t y, uint8_t btn, int8_t wheelDelta);
/** Method called in updateInput when there're events of key down / up
* @param action [in] Type of event regarding the key given by the key parameter
* @param key [in] Key involved in the event
* @return nothing */
void KeyEvent(ActionCode action, uint8_t key);
/** Returns the state of the buttons of the mouse
* @param button [in] Button to test
* @return true of pressed, false if released */
bool ButtonState(uint8_t button);
/** Returns the state of the buttons of the mouse for the single press version
* @param button [in] Button to test
* @return true of pressed, false if released */
bool ButtonSinglePressState(uint8_t button);
GETCOPY(int32_t, m_mouseX, MouseX)
GETCOPY(int32_t, m_mouseY, MouseY)
REF(EventSignalSlot, m_eventSignalSlot, EventSignalSlot)
REF(EventSignalSlot, m_eventSinglePressSignalSlot, EventSinglePressSignalSlot)
protected:
int32_t m_mouseX; //!< Mouse position x
int32_t m_mouseY; //!< Mouse position y
bool m_buttonState[5]; //!< mouse button state
bool m_buttonSinglePressState[5]; //!< mouse button state for single press events
bool m_keyState[256]; //!< Mapping of each key's state
bool m_keySinglePressState[256]; //!< Mapping of each key's state for single press events
bool m_settingCursorPosition; //!< To know when the application is setting the cursor position, to avoid processing events regarding this particular event
int8_t m_mouseWheelDelta; //!< Mouse wheel delta event value (if any)
bool m_leftMouseButtonDown; //!< Flag to register left mouse button down
bool m_centerMouseButtonDown; //!< Flag to register center mouse button down
bool m_rightMouseButtonDown; //!< Flag to register right mouse button down
bool m_leftMouseButtonUp; //!< Flag to register left mouse button up
bool m_centerMouseButtonUp; //!< Flag to register center mouse button up
bool m_rightMouseButtonUp; //!< Flag to register right mouse button up
EventSignalSlot m_eventSignalSlot; //!< To notify for mouse movement and mouse and keyboard down and up events
EventSignalSlot m_eventSinglePressSignalSlot; //!< To notify for mouse movement and mouse and keyboard down and up events for single press events
vector<KeyCode> m_vectorPressedKey; //!< Vector with the currently pressed keys
vector<KeyCode> m_vectorSingleStatePressedKey; //!< Vector with the currently pressed keys for single press events
vector<KeyCode> m_vectorSingleStateReleaseddKey; //!< Vector with the currently released keys for single press events
};
static Input* s_pInputSingleton;
/////////////////////////////////////////////////////////////////////////////////////////////
// INLINE FUNCTIONS
/////////////////////////////////////////////////////////////////////////////////////////////
inline void Input::KeyEvent(ActionCode action, uint8_t key)
{
if ((action == ActionCode::ACTION_CODE_DOWN) && !m_keySinglePressState[key] &&
m_eventSinglePressSignalSlot.isKeyDownRegistered(static_cast<KeyCode>(key)))
{
addIfNoPresent(static_cast<KeyCode>(key), m_vectorSingleStatePressedKey);
m_keySinglePressState[key] = true;
}
if ((action == ActionCode::ACTION_CODE_UP) && !m_keySinglePressState[key] &&
m_eventSinglePressSignalSlot.isKeyUpRegistered(static_cast<KeyCode>(key)))
{
addIfNoPresent(static_cast<KeyCode>(key), m_vectorSingleStateReleaseddKey);
m_keySinglePressState[key] = false;
}
m_keyState[key] = (action == ActionCode::ACTION_CODE_DOWN);
if (action == ActionCode::ACTION_CODE_DOWN)
{
addIfNoPresent(static_cast<KeyCode>(key), m_vectorPressedKey);
}
else
{
removeIfPresent(static_cast<KeyCode>(key), m_vectorPressedKey);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////
inline bool Input::ButtonState(uint8_t button)
{
if (button < 3)
{
return m_buttonState[button];
}
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////
inline bool Input::ButtonSinglePressState(uint8_t button)
{
if (button < 3)
{
return m_buttonSinglePressState[button];
}
return 0;
}
/////////////////////////////////////////////////////////////////////////////////////////////
#endif _INPUT_H_
| 36.941799 | 174 | 0.65053 | [
"vector"
] |
65c2db74f177634cd98cdf1aceba6b4e2e8dcabd | 19,786 | c | C | sb-forwarder/metis/ccnx/forwarder/metis/processor/test/test_metis_ContentStore.c | cherouvim/cicn-nrs | 440d6a7f56e7240f179205ed5ce1fe8000d03b83 | [
"Apache-2.0"
] | 10 | 2018-11-04T06:37:14.000Z | 2022-02-18T00:26:34.000Z | sb-forwarder/metis/ccnx/forwarder/metis/processor/test/test_metis_ContentStore.c | cherouvim/cicn-nrs | 440d6a7f56e7240f179205ed5ce1fe8000d03b83 | [
"Apache-2.0"
] | null | null | null | sb-forwarder/metis/ccnx/forwarder/metis/processor/test/test_metis_ContentStore.c | cherouvim/cicn-nrs | 440d6a7f56e7240f179205ed5ce1fe8000d03b83 | [
"Apache-2.0"
] | 3 | 2019-01-17T19:47:55.000Z | 2022-02-18T00:28:18.000Z | /*
* Copyright (c) 2017 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Include the file(s) containing the functions to be tested.
// This permits internal static functions to be visible to this Test Framework.
#include "../metis_ContentStore.c"
#include <LongBow/unit-test.h>
#include <parc/algol/parc_SafeMemory.h>
#include <parc/logging/parc_LogReporterTextStdout.h>
#include <ccnx/forwarder/metis/testdata/metis_TestDataV0.h>
#include <ccnx/forwarder/metis/testdata/metis_TestDataV1.h>
LONGBOW_TEST_RUNNER(metis_ContentStore)
{
parcMemory_SetInterface(&PARCSafeMemoryAsPARCMemory);
LONGBOW_RUN_TEST_FIXTURE(Global);
LONGBOW_RUN_TEST_FIXTURE(Local);
}
// The Test Runner calls this function once before any Test Fixtures are run.
LONGBOW_TEST_RUNNER_SETUP(metis_ContentStore)
{
return LONGBOW_STATUS_SUCCEEDED;
}
// The Test Runner calls this function once after all the Test Fixtures are run.
LONGBOW_TEST_RUNNER_TEARDOWN(metis_ContentStore)
{
return LONGBOW_STATUS_SUCCEEDED;
}
// ============================================================================
LONGBOW_TEST_FIXTURE(Global)
{
LONGBOW_RUN_TEST_CASE(Global, metisContentStore_Create_Destroy);
LONGBOW_RUN_TEST_CASE(Global, metisContentStore_Create_ZeroCapacity);
LONGBOW_RUN_TEST_CASE(Global, metisContentStore_Fetch_ByName);
LONGBOW_RUN_TEST_CASE(Global, metisContentStore_Fetch_ByNameAndKeyId);
LONGBOW_RUN_TEST_CASE(Global, metisContentStore_Fetch_ByNameAndObjectHash);
LONGBOW_RUN_TEST_CASE(Global, metisContentStore_Fetch_Lru);
LONGBOW_RUN_TEST_CASE(Global, metisContentStore_Save_ZeroCapacity);
LONGBOW_RUN_TEST_CASE(Global, metisContentStore_Save_CapacityLimit);
LONGBOW_RUN_TEST_CASE(Global, metisContentStore_Save_WithoutEviction);
LONGBOW_RUN_TEST_CASE(Global, metisContentStore_Save_WithEviction);
LONGBOW_RUN_TEST_CASE(Global, metisContentStore_Save_DuplicateHash);
}
LONGBOW_TEST_FIXTURE_SETUP(Global)
{
return LONGBOW_STATUS_SUCCEEDED;
}
LONGBOW_TEST_FIXTURE_TEARDOWN(Global)
{
uint32_t outstandingAllocations = parcSafeMemory_ReportAllocation(STDERR_FILENO);
if (outstandingAllocations != 0) {
printf("%s leaks memory by %d allocations\n", longBowTestCase_GetName(testCase), outstandingAllocations);
return LONGBOW_STATUS_MEMORYLEAK;
}
return LONGBOW_STATUS_SUCCEEDED;
}
LONGBOW_TEST_CASE(Global, metisContentStore_Create_Destroy)
{
size_t objectCapacity = 10;
PARCLogReporter *reporter = parcLogReporterTextStdout_Create();
MetisLogger *logger = metisLogger_Create(reporter, parcClock_Wallclock());
parcLogReporter_Release(&reporter);
MetisContentStore *store = metisContentStore_Create(objectCapacity, logger);
metisLogger_Release(&logger);
assertTrue(store->objectCapacity == objectCapacity, "Wrong capacity, expected %zu got %zu", objectCapacity, store->objectCapacity);
assertTrue(store->objectCount == 0, "Wrong initial count, expected %u got %zu", 0, store->objectCount);
metisContentStore_Destroy(&store);
assertTrue(parcSafeMemory_ReportAllocation(STDOUT_FILENO) == 0, "Memory imbalance after create/destroy, expected %u got %u", 0, parcMemory_Outstanding());
}
LONGBOW_TEST_CASE(Global, metisContentStore_Create_ZeroCapacity)
{
size_t objectCapacity = 0;
PARCLogReporter *reporter = parcLogReporterTextStdout_Create();
MetisLogger *logger = metisLogger_Create(reporter, parcClock_Wallclock());
parcLogReporter_Release(&reporter);
MetisContentStore *store = metisContentStore_Create(objectCapacity, logger);
assertTrue(store->objectCapacity == objectCapacity, "Wrong capacity, expected %zu got %zu", objectCapacity, store->objectCapacity);
assertTrue(store->objectCount == 0, "Wrong initial count, expected %u got %zu", 0, store->objectCount);
metisLogger_Release(&logger);
metisContentStore_Destroy(&store);
}
LONGBOW_TEST_CASE(Global, metisContentStore_Fetch_ByName)
{
size_t objectCapacity = 10;
PARCLogReporter *reporter = parcLogReporterTextStdout_Create();
MetisLogger *logger = metisLogger_Create(reporter, parcClock_Wallclock());
parcLogReporter_Release(&reporter);
MetisContentStore *store = metisContentStore_Create(objectCapacity, logger);
MetisMessage *object_1 = metisMessage_CreateFromArray(metisTestDataV0_EncodedObject, sizeof(metisTestDataV0_EncodedObject), 1, 2, logger);
MetisMessage *object_2 = metisMessage_CreateFromArray(metisTestDataV0_SecondObject, sizeof(metisTestDataV0_SecondObject), 1, 2, logger);
metisContentStore_Save(store, object_1);
metisContentStore_Save(store, object_2);
MetisMessage *interestByName = metisMessage_CreateFromArray(metisTestDataV0_InterestWithName, sizeof(metisTestDataV0_InterestWithName), 3, 5, logger);
MetisMessage *testObject = metisContentStore_Fetch(store, interestByName);
assertNotNull(testObject, "Fetch did not find match when it should have");
// two objects with same name, 1st one will win
assertTrue(testObject == object_1, "Fetch returned wrong object, expecting %p got %p", (void *) object_1, (void *) testObject);
metisLogger_Release(&logger);
metisContentStore_Destroy(&store);
metisMessage_Release(&object_1);
metisMessage_Release(&object_2);
metisMessage_Release(&testObject);
metisMessage_Release(&interestByName);
}
LONGBOW_TEST_CASE(Global, metisContentStore_Fetch_ByNameAndKeyId)
{
size_t objectCapacity = 10;
PARCLogReporter *reporter = parcLogReporterTextStdout_Create();
MetisLogger *logger = metisLogger_Create(reporter, parcClock_Wallclock());
parcLogReporter_Release(&reporter);
MetisContentStore *store = metisContentStore_Create(objectCapacity, logger);
MetisMessage *object_1 = metisMessage_CreateFromArray(metisTestDataV0_EncodedObject, sizeof(metisTestDataV0_EncodedObject), 1, 2, logger);
MetisMessage *object_2 = metisMessage_CreateFromArray(metisTestDataV0_SecondObject, sizeof(metisTestDataV0_SecondObject), 1, 2, logger);
metisContentStore_Save(store, object_1);
metisContentStore_Save(store, object_2);
MetisMessage *interestByNameKeyId = metisMessage_CreateFromArray(metisTestDataV0_InterestWithName_keyid, sizeof(metisTestDataV0_InterestWithName_keyid), 3, 5, logger);
MetisMessage *testObject = metisContentStore_Fetch(store, interestByNameKeyId);
assertNotNull(testObject, "Fetch did not find match when it should have");
// two objects with same name, 1st one will win
assertTrue(testObject == object_1, "Fetch returned wrong object, expecting %p got %p", (void *) object_1, (void *) testObject);
metisLogger_Release(&logger);
metisContentStore_Destroy(&store);
metisMessage_Release(&object_1);
metisMessage_Release(&object_2);
metisMessage_Release(&testObject);
metisMessage_Release(&interestByNameKeyId);
}
LONGBOW_TEST_CASE(Global, metisContentStore_Fetch_ByNameAndObjectHash)
{
size_t objectCapacity = 10;
PARCLogReporter *reporter = parcLogReporterTextStdout_Create();
MetisLogger *logger = metisLogger_Create(reporter, parcClock_Wallclock());
parcLogReporter_Release(&reporter);
MetisContentStore *store = metisContentStore_Create(objectCapacity, logger);
MetisMessage *object_1 = metisMessage_CreateFromArray(metisTestDataV0_EncodedObject, sizeof(metisTestDataV0_EncodedObject), 1, 2, logger);
MetisMessage *object_2 = metisMessage_CreateFromArray(metisTestDataV0_SecondObject, sizeof(metisTestDataV0_SecondObject), 1, 2, logger);
metisContentStore_Save(store, object_1);
metisContentStore_Save(store, object_2);
MetisMessage *interestByNameObjectHash = metisMessage_CreateFromArray(metisTestDataV0_InterestWithName_objecthash, sizeof(metisTestDataV0_InterestWithName_objecthash), 3, 5, logger);
// this should retrieve object_1 because that is the one whose
// content object hash matches the interest
MetisMessage *testObject = metisContentStore_Fetch(store, interestByNameObjectHash);
assertNotNull(testObject, "Fetch did not find match when it should have");
// two objects with same name, 1st one will win
assertTrue(testObject == object_1, "Fetch returned wrong object, expecting %p got %p", (void *) object_1, (void *) testObject);
metisLogger_Release(&logger);
metisContentStore_Destroy(&store);
metisMessage_Release(&object_1);
metisMessage_Release(&object_2);
metisMessage_Release(&testObject);
metisMessage_Release(&interestByNameObjectHash);
}
/*
* Create an cache and access objects to make sure the LRU is evicting the right way
*/
LONGBOW_TEST_CASE(Global, metisContentStore_Fetch_Lru)
{
const size_t objectCapacity = 2;
PARCLogReporter *reporter = parcLogReporterTextStdout_Create();
MetisLogger *logger = metisLogger_Create(reporter, parcClock_Wallclock());
metisLogger_SetLogLevel(logger, MetisLoggerFacility_Processor, PARCLogLevel_Debug);
parcLogReporter_Release(&reporter);
MetisContentStore *store = metisContentStore_Create(objectCapacity, logger);
MetisMessage *object1 = metisMessage_CreateFromArray(metisTestDataV0_EncodedObject, sizeof(metisTestDataV0_EncodedObject), 1, 2, logger);
MetisMessage *object2 = metisMessage_CreateFromArray(metisTestDataV0_object_with_othername, sizeof(metisTestDataV0_object_with_othername), 2, 2, logger);
metisContentStore_Save(store, object1);
metisContentStore_Save(store, object2);
// object 2 sould be at top of LRU (was saved last). Fetch object 1, then evict object 2.
// interest_with_name will match the name in object1.
MetisMessage *interestByName = metisMessage_CreateFromArray(metisTestDataV0_InterestWithName, sizeof(metisTestDataV0_InterestWithName), 3, 5, logger);
MetisMessage *testObject = metisContentStore_Fetch(store, interestByName);
assertTrue(testObject == object1, "Fetch returned wrong object, expecting %p got %p", (void *) object1, (void *) testObject);
// objectcapacity = 2, so object 3 will evict bottom of LRU
MetisMessage *object3 = metisMessage_CreateFromArray(metisTestDataV0_SecondObject, sizeof(metisTestDataV0_SecondObject), 4, 2, logger);
metisContentStore_Save(store, object3);
// object 2 should be evicted
MetisMessage *interestOtherName = metisMessage_CreateFromArray(metisTestDataV0_InterestWithOtherName, sizeof(metisTestDataV0_InterestWithOtherName), 5, 5, logger);
MetisMessage *testEvictedObject = metisContentStore_Fetch(store, interestOtherName);
assertNull(testEvictedObject, "object with othername should have been evicted");
// as final sanity check, make sure object 1 is still in the list
MetisMessage *testObject1Again = metisContentStore_Fetch(store, interestByName);
assertNotNull(testObject1Again, "Did not retrieve object1 from the content store");
metisLogger_Release(&logger);
metisContentStore_Destroy(&store);
metisMessage_Release(&testObject1Again);
metisMessage_Release(&object1);
metisMessage_Release(&object2);
metisMessage_Release(&object3);
metisMessage_Release(&testObject);
metisMessage_Release(&interestByName);
metisMessage_Release(&interestOtherName);
}
LONGBOW_TEST_CASE(Global, metisContentStore_Save_WithoutEviction)
{
size_t objectCapacity = 10;
PARCLogReporter *reporter = parcLogReporterTextStdout_Create();
MetisLogger *logger = metisLogger_Create(reporter, parcClock_Wallclock());
parcLogReporter_Release(&reporter);
MetisContentStore *store = metisContentStore_Create(objectCapacity, logger);
MetisMessage *object_1 = metisMessage_CreateFromArray(metisTestDataV0_EncodedObject, sizeof(metisTestDataV0_EncodedObject), 1, 2, logger);
MetisMessage *object_2 = metisMessage_CreateFromArray(metisTestDataV0_SecondObject, sizeof(metisTestDataV0_SecondObject), 1, 2, logger);
metisContentStore_Save(store, object_1);
metisContentStore_Save(store, object_2);
assertTrue(store->stats.countAdds == 2, "Wrong countAdds, expected %u got %" PRIu64, 2, store->stats.countAdds);
assertTrue(store->stats.countLruEvictions == 0, "Wrong countLruEvictions, expected %u got %" PRIu64, 0, store->stats.countLruEvictions);
assertTrue(metisLruList_Length(store->lruList) == 2, "Wrong metisLruList_Length, expected %u got %zu", 2, metisLruList_Length(store->lruList));
metisLogger_Release(&logger);
metisContentStore_Destroy(&store);
metisMessage_Release(&object_1);
metisMessage_Release(&object_2);
}
LONGBOW_TEST_CASE(Global, metisContentStore_Save_WithEviction)
{
size_t objectCapacity = 1;
PARCLogReporter *reporter = parcLogReporterTextStdout_Create();
MetisLogger *logger = metisLogger_Create(reporter, parcClock_Wallclock());
parcLogReporter_Release(&reporter);
MetisContentStore *store = metisContentStore_Create(objectCapacity, logger);
MetisMessage *object_1 = metisMessage_CreateFromArray(metisTestDataV0_EncodedObject, sizeof(metisTestDataV0_EncodedObject), 1, 2, logger);
MetisMessage *object_2 = metisMessage_CreateFromArray(metisTestDataV0_SecondObject, sizeof(metisTestDataV0_SecondObject), 1, 2, logger);
metisContentStore_Save(store, object_1);
assertTrue(store->objectCount == 1, "Wrong objectCount. Expected %u, got %zu", 1, store->objectCount);
metisContentStore_Save(store, object_2);
// Capacity is 1, so we should never grow bigger than that.
assertTrue(store->objectCount == 1, "Wrong objectCount. Expected %u, got %zu", 1, store->objectCount);
assertTrue(store->stats.countAdds == 2, "Wrong countAdds, expected %u got %" PRIu64, 2, store->stats.countAdds);
assertTrue(store->stats.countLruEvictions == 1, "Wrong countLruEvictions, expected %u got %" PRIu64, 1, store->stats.countLruEvictions);
assertTrue(metisLruList_Length(store->lruList) == 1, "Wrong metisLruList_Length, expected %u got %zu", 1, metisLruList_Length(store->lruList));
metisLogger_Release(&logger);
metisContentStore_Destroy(&store);
metisMessage_Release(&object_1);
metisMessage_Release(&object_2);
}
LONGBOW_TEST_CASE(Global, metisContentStore_Save_ZeroCapacity)
{
size_t objectCapacity = 0;
PARCLogReporter *reporter = parcLogReporterTextStdout_Create();
MetisLogger *logger = metisLogger_Create(reporter, parcClock_Wallclock());
parcLogReporter_Release(&reporter);
MetisContentStore *store = metisContentStore_Create(objectCapacity, logger);
MetisMessage *object_1 = metisMessage_CreateFromArray(metisTestDataV0_EncodedObject, sizeof(metisTestDataV0_EncodedObject), 1, 2, logger);
bool success = metisContentStore_Save(store, object_1);
assertFalse(success, "Should have returned failure with 0 capacity object store saving something");
metisLogger_Release(&logger);
metisMessage_Release(&object_1);
metisContentStore_Destroy(&store);
}
static MetisMessage *
_createUniqueMetisMessage(int tweakNumber, uint8_t *template, size_t templateSize, int nameOffset)
{
PARCLogReporter *reporter = parcLogReporterTextStdout_Create();
MetisLogger *logger = metisLogger_Create(reporter, parcClock_Wallclock());
parcLogReporter_Release(&reporter);
PARCBuffer *buffer = parcBuffer_Allocate(templateSize);
memcpy(parcBuffer_Overlay(buffer, 0), template, templateSize); // Copy the template to new memory
// Tweak the encoded object's name so the name hash varies each time.
uint8_t *bufPtr = parcBuffer_Overlay(buffer, 0);
bufPtr[nameOffset] = 'a' + tweakNumber;
MetisMessage *result = metisMessage_CreateFromArray(bufPtr, templateSize, 1, 2, logger);
metisLogger_Release(&logger);
parcBuffer_Release(&buffer);
return result;
}
LONGBOW_TEST_CASE(Global, metisContentStore_Save_CapacityLimit)
{
size_t storeCapacity = 5;
PARCLogReporter *reporter = parcLogReporterTextStdout_Create();
MetisLogger *logger = metisLogger_Create(reporter, parcClock_Wallclock());
parcLogReporter_Release(&reporter);
MetisContentStore *store = metisContentStore_Create(storeCapacity, logger);
for (int i = 1; i < storeCapacity * 2; i++) {
int offsetOfNameInEncodedObject = metisTestDataV0_EncodedObject.offset + 4;
MetisMessage *object = _createUniqueMetisMessage(i, metisTestDataV0_EncodedObject, sizeof(metisTestDataV0_EncodedObject), offsetOfNameInEncodedObject);
bool success = metisContentStore_Save(store, object);
assertTrue(success, "Unexpectedly failed to add entry to ContentStore");
if (i < store->objectCapacity) {
assertTrue(store->objectCount == i, "Unexpected value for store->objectCount");
} else {
assertTrue(store->objectCount == store->objectCapacity, "Unexpected value (%zu) for store->objectCount (%zu)",
store->objectCount, store->objectCapacity);
}
if (success) {
metisMessage_Release(&object);
}
}
metisLogger_Release(&logger);
metisContentStore_Destroy(&store);
}
LONGBOW_TEST_CASE(Global, metisContentStore_Save_DuplicateHash)
{
size_t storeCapacity = 5;
PARCLogReporter *reporter = parcLogReporterTextStdout_Create();
MetisLogger *logger = metisLogger_Create(reporter, parcClock_Wallclock());
parcLogReporter_Release(&reporter);
MetisContentStore *store = metisContentStore_Create(storeCapacity, logger);
MetisMessage *object_1 = metisMessage_CreateFromArray(metisTestDataV0_EncodedObject, sizeof(metisTestDataV0_EncodedObject), 1, 2, logger);
bool success = metisContentStore_Save(store, object_1);
for (int i = 0; i < 10; i++) {
MetisMessage *object_1_dup = metisMessage_CreateFromArray(metisTestDataV0_EncodedObject, sizeof(metisTestDataV0_EncodedObject), 1, 2, logger);
success = metisContentStore_Save(store, object_1_dup);
assertFalse(success, "Unexpectedly added duplicated entry to ContentStore");
assertTrue(store->objectCount == 1, "ObjectCount should be 1");
metisMessage_Release(&object_1_dup);
}
metisLogger_Release(&logger);
metisMessage_Release(&object_1);
metisContentStore_Destroy(&store);
}
// ============================================================================
LONGBOW_TEST_FIXTURE(Local)
{
LONGBOW_RUN_TEST_CASE(Local, hashTableFunction_ContentStoreEntryDestroyer);
}
LONGBOW_TEST_FIXTURE_SETUP(Local)
{
return LONGBOW_STATUS_SUCCEEDED;
}
LONGBOW_TEST_FIXTURE_TEARDOWN(Local)
{
uint32_t outstandingAllocations = parcSafeMemory_ReportAllocation(STDERR_FILENO);
if (outstandingAllocations != 0) {
printf("%s leaks memory by %d allocations\n", longBowTestCase_GetName(testCase), outstandingAllocations);
return LONGBOW_STATUS_MEMORYLEAK;
}
return LONGBOW_STATUS_SUCCEEDED;
}
LONGBOW_TEST_CASE(Local, hashTableFunction_ContentStoreEntryDestroyer)
{
testUnimplemented("This test is unimplemented");
}
// ============================================================================
int
main(int argc, char *argv[])
{
LongBowRunner *testRunner = LONGBOW_TEST_RUNNER_CREATE(metis_ContentStore);
int exitStatus = longBowMain(argc, argv, testRunner, NULL);
longBowTestRunner_Destroy(&testRunner);
exit(exitStatus);
}
| 45.173516 | 186 | 0.766956 | [
"object"
] |
65c8c7213a0bc91375b37c1e898ffb3e6ce6148e | 2,486 | h | C | Plugins/MaxQ/Source/SpiceUncooked/Private/K2Conversion.h | gamergenic/Spaceflight-Toolkit-For-Unreal-Engine-5 | 11d81127dd296595bca30cb1565ff3b813210230 | [
"MIT"
] | 2 | 2022-01-04T04:36:04.000Z | 2022-01-06T09:22:53.000Z | Plugins/MaxQ/Source/SpiceUncooked/Private/K2Conversion.h | gamergenic/Spaceflight-Toolkit-For-Unreal-Engine-5 | 11d81127dd296595bca30cb1565ff3b813210230 | [
"MIT"
] | null | null | null | Plugins/MaxQ/Source/SpiceUncooked/Private/K2Conversion.h | gamergenic/Spaceflight-Toolkit-For-Unreal-Engine-5 | 11d81127dd296595bca30cb1565ff3b813210230 | [
"MIT"
] | 1 | 2021-12-28T03:05:12.000Z | 2021-12-28T03:05:12.000Z | // Copyright 2021 Gamergenic. See full copyright notice in Spice.h.
// Author: chucknoble@gamergenic.com | https://www.gamergenic.com
//
// Project page: https://www.gamergenic.com/project/maxq/
// Documentation: https://maxq.gamergenic.com/
// GitHub: https://github.com/Gamergenic1/MaxQ/
#pragma once
#include "CoreMinimal.h"
#include "K2Type.h"
#include "K2Conversion.generated.h"
UENUM(BlueprintType)
enum class EK2_ComponentSelector : uint8
{
All UMETA(DisplayName = "*"),
X UMETA(DisplayName = "X Only"),
Y UMETA(DisplayName = "Y Only"),
Z UMETA(DisplayName = "Z Only"),
};
USTRUCT()
struct FK2Conversion
{
GENERATED_BODY()
UPROPERTY() FName ConversionName;
UPROPERTY() FK2Type In;
UPROPERTY() EK2_ComponentSelector Selector;
UPROPERTY() FK2Type Out;
FK2Conversion()
{
ConversionName = FName();
In = FK2Type();
Out = FK2Type();
Selector = EK2_ComponentSelector::All;
}
FK2Conversion(FName name, const FK2Type& _in, const FK2Type& _out, EK2_ComponentSelector _selector = EK2_ComponentSelector::All)
{
ConversionName = name;
In = _in;
Out = _out;
Selector = _selector;
}
FK2Conversion(const FK2Conversion& other)
{
ConversionName = other.ConversionName;
In = FK2Type(other.In);
Selector = other.Selector;
Out = FK2Type(other.Out);
}
FK2Conversion& operator= (const FK2Conversion& other)
{
// self-assignment guard
if (this == &other)
return *this;
// do the copy
ConversionName = other.ConversionName;
In = other.In;
Selector = other.Selector;
Out = other.Out;
// return the existing object so we can chain this operator
return *this;
}
static SPICEUNCOOKED_API FK2Conversion None();
static SPICEUNCOOKED_API FK2Conversion DoubleToSMassConstant();
static SPICEUNCOOKED_API FK2Conversion DegreesToSAngle();
static SPICEUNCOOKED_API FK2Conversion DoubleToSDistance();
static SPICEUNCOOKED_API FK2Conversion SDimensionlessVectorXToSDistance();
static SPICEUNCOOKED_API FK2Conversion SDimensionlessVectorYToSDistance();
static SPICEUNCOOKED_API FK2Conversion SDimensionlessVectorZToSDistance();
static SPICEUNCOOKED_API FK2Conversion SDimensionlessVectorToSDistanceVector();
static SPICEUNCOOKED_API FK2Conversion SDimensionlessVectorToSVelocityVector();
};
| 29.247059 | 132 | 0.685841 | [
"object"
] |
65ca4f08fc97babcef25c953d71e2e8259b8e2bb | 5,627 | h | C | DataCollector/mozilla/xulrunner-sdk/include/nsIQuotaManager.h | andrasigneczi/TravelOptimiser | b08805f97f0823fd28975a36db67193386aceb22 | [
"Apache-2.0"
] | 1 | 2016-04-20T08:35:44.000Z | 2016-04-20T08:35:44.000Z | DataCollector/mozilla/xulrunner-sdk/include/nsIQuotaManager.h | andrasigneczi/TravelOptimiser | b08805f97f0823fd28975a36db67193386aceb22 | [
"Apache-2.0"
] | null | null | null | DataCollector/mozilla/xulrunner-sdk/include/nsIQuotaManager.h | andrasigneczi/TravelOptimiser | b08805f97f0823fd28975a36db67193386aceb22 | [
"Apache-2.0"
] | null | null | null | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM ../../../dist/idl\nsIQuotaManager.idl
*/
#ifndef __gen_nsIQuotaManager_h__
#define __gen_nsIQuotaManager_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIQuotaRequest; /* forward declaration */
class nsIURI; /* forward declaration */
class nsIUsageCallback; /* forward declaration */
/* starting interface: nsIQuotaManager */
#define NS_IQUOTAMANAGER_IID_STR "2968fcd5-1872-4ddc-8c16-62b27e357f31"
#define NS_IQUOTAMANAGER_IID \
{0x2968fcd5, 0x1872, 0x4ddc, \
{ 0x8c, 0x16, 0x62, 0xb2, 0x7e, 0x35, 0x7f, 0x31 }}
class NS_NO_VTABLE nsIQuotaManager : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IQUOTAMANAGER_IID)
/* [optional_argc] nsIQuotaRequest getUsageForURI (in nsIURI aURI, in nsIUsageCallback aCallback, [optional] in unsigned long aAppId, [optional] in boolean aInMozBrowserOnly); */
NS_IMETHOD GetUsageForURI(nsIURI *aURI, nsIUsageCallback *aCallback, uint32_t aAppId, bool aInMozBrowserOnly, uint8_t _argc, nsIQuotaRequest * *_retval) = 0;
/* void clear (); */
NS_IMETHOD Clear(void) = 0;
/* [optional_argc] void clearStoragesForURI (in nsIURI aURI, [optional] in unsigned long aAppId, [optional] in boolean aInMozBrowserOnly, [optional] in ACString aPersistenceType); */
NS_IMETHOD ClearStoragesForURI(nsIURI *aURI, uint32_t aAppId, bool aInMozBrowserOnly, const nsACString & aPersistenceType, uint8_t _argc) = 0;
/* void reset (); */
NS_IMETHOD Reset(void) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIQuotaManager, NS_IQUOTAMANAGER_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIQUOTAMANAGER \
NS_IMETHOD GetUsageForURI(nsIURI *aURI, nsIUsageCallback *aCallback, uint32_t aAppId, bool aInMozBrowserOnly, uint8_t _argc, nsIQuotaRequest * *_retval) override; \
NS_IMETHOD Clear(void) override; \
NS_IMETHOD ClearStoragesForURI(nsIURI *aURI, uint32_t aAppId, bool aInMozBrowserOnly, const nsACString & aPersistenceType, uint8_t _argc) override; \
NS_IMETHOD Reset(void) override;
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIQUOTAMANAGER(_to) \
NS_IMETHOD GetUsageForURI(nsIURI *aURI, nsIUsageCallback *aCallback, uint32_t aAppId, bool aInMozBrowserOnly, uint8_t _argc, nsIQuotaRequest * *_retval) override { return _to GetUsageForURI(aURI, aCallback, aAppId, aInMozBrowserOnly, _argc, _retval); } \
NS_IMETHOD Clear(void) override { return _to Clear(); } \
NS_IMETHOD ClearStoragesForURI(nsIURI *aURI, uint32_t aAppId, bool aInMozBrowserOnly, const nsACString & aPersistenceType, uint8_t _argc) override { return _to ClearStoragesForURI(aURI, aAppId, aInMozBrowserOnly, aPersistenceType, _argc); } \
NS_IMETHOD Reset(void) override { return _to Reset(); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIQUOTAMANAGER(_to) \
NS_IMETHOD GetUsageForURI(nsIURI *aURI, nsIUsageCallback *aCallback, uint32_t aAppId, bool aInMozBrowserOnly, uint8_t _argc, nsIQuotaRequest * *_retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetUsageForURI(aURI, aCallback, aAppId, aInMozBrowserOnly, _argc, _retval); } \
NS_IMETHOD Clear(void) override { return !_to ? NS_ERROR_NULL_POINTER : _to->Clear(); } \
NS_IMETHOD ClearStoragesForURI(nsIURI *aURI, uint32_t aAppId, bool aInMozBrowserOnly, const nsACString & aPersistenceType, uint8_t _argc) override { return !_to ? NS_ERROR_NULL_POINTER : _to->ClearStoragesForURI(aURI, aAppId, aInMozBrowserOnly, aPersistenceType, _argc); } \
NS_IMETHOD Reset(void) override { return !_to ? NS_ERROR_NULL_POINTER : _to->Reset(); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsQuotaManager : public nsIQuotaManager
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIQUOTAMANAGER
nsQuotaManager();
private:
~nsQuotaManager();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS(nsQuotaManager, nsIQuotaManager)
nsQuotaManager::nsQuotaManager()
{
/* member initializers and constructor code */
}
nsQuotaManager::~nsQuotaManager()
{
/* destructor code */
}
/* [optional_argc] nsIQuotaRequest getUsageForURI (in nsIURI aURI, in nsIUsageCallback aCallback, [optional] in unsigned long aAppId, [optional] in boolean aInMozBrowserOnly); */
NS_IMETHODIMP nsQuotaManager::GetUsageForURI(nsIURI *aURI, nsIUsageCallback *aCallback, uint32_t aAppId, bool aInMozBrowserOnly, uint8_t _argc, nsIQuotaRequest * *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void clear (); */
NS_IMETHODIMP nsQuotaManager::Clear()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* [optional_argc] void clearStoragesForURI (in nsIURI aURI, [optional] in unsigned long aAppId, [optional] in boolean aInMozBrowserOnly, [optional] in ACString aPersistenceType); */
NS_IMETHODIMP nsQuotaManager::ClearStoragesForURI(nsIURI *aURI, uint32_t aAppId, bool aInMozBrowserOnly, const nsACString & aPersistenceType, uint8_t _argc)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void reset (); */
NS_IMETHODIMP nsQuotaManager::Reset()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIQuotaManager_h__ */
| 41.992537 | 289 | 0.756176 | [
"object"
] |
65cafe2ec2812489f8fa496a21977c0fb2967046 | 9,760 | h | C | llvm/3.4.2/llvm-3.4.2.src/include/llvm/Transforms/Utils/BasicBlockUtils.h | tangyibin/goblin-core | 1940db6e95908c81687b2b22ddd9afbc8db9cdfe | [
"BSD-3-Clause"
] | 36 | 2015-01-13T19:34:04.000Z | 2022-03-07T22:22:15.000Z | llvm/3.4.2/llvm-3.4.2.src/include/llvm/Transforms/Utils/BasicBlockUtils.h | tangyibin/goblin-core | 1940db6e95908c81687b2b22ddd9afbc8db9cdfe | [
"BSD-3-Clause"
] | 7 | 2015-10-20T19:05:01.000Z | 2021-11-13T14:55:47.000Z | llvm/3.4.2/llvm-3.4.2.src/include/llvm/Transforms/Utils/BasicBlockUtils.h | tangyibin/goblin-core | 1940db6e95908c81687b2b22ddd9afbc8db9cdfe | [
"BSD-3-Clause"
] | 18 | 2015-04-23T20:59:52.000Z | 2021-11-18T20:06:39.000Z | //===-- Transform/Utils/BasicBlockUtils.h - BasicBlock Utils ----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This family of functions perform manipulations on basic blocks, and
// instructions contained within basic blocks.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
#define LLVM_TRANSFORMS_UTILS_BASICBLOCKUTILS_H
// FIXME: Move to this file: BasicBlock::removePredecessor, BB::splitBasicBlock
#include "llvm/IR/BasicBlock.h"
#include "llvm/Support/CFG.h"
namespace llvm {
class AliasAnalysis;
class Instruction;
class MDNode;
class Pass;
class ReturnInst;
class TargetLibraryInfo;
class TerminatorInst;
/// DeleteDeadBlock - Delete the specified block, which must have no
/// predecessors.
void DeleteDeadBlock(BasicBlock *BB);
/// FoldSingleEntryPHINodes - We know that BB has one predecessor. If there are
/// any single-entry PHI nodes in it, fold them away. This handles the case
/// when all entries to the PHI nodes in a block are guaranteed equal, such as
/// when the block has exactly one predecessor.
void FoldSingleEntryPHINodes(BasicBlock *BB, Pass *P = 0);
/// DeleteDeadPHIs - Examine each PHI in the given block and delete it if it
/// is dead. Also recursively delete any operands that become dead as
/// a result. This includes tracing the def-use list from the PHI to see if
/// it is ultimately unused or if it reaches an unused cycle. Return true
/// if any PHIs were deleted.
bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI = 0);
/// MergeBlockIntoPredecessor - Attempts to merge a block into its predecessor,
/// if possible. The return value indicates success or failure.
bool MergeBlockIntoPredecessor(BasicBlock *BB, Pass *P = 0);
// ReplaceInstWithValue - Replace all uses of an instruction (specified by BI)
// with a value, then remove and delete the original instruction.
//
void ReplaceInstWithValue(BasicBlock::InstListType &BIL,
BasicBlock::iterator &BI, Value *V);
// ReplaceInstWithInst - Replace the instruction specified by BI with the
// instruction specified by I. The original instruction is deleted and BI is
// updated to point to the new instruction.
//
void ReplaceInstWithInst(BasicBlock::InstListType &BIL,
BasicBlock::iterator &BI, Instruction *I);
// ReplaceInstWithInst - Replace the instruction specified by From with the
// instruction specified by To.
//
void ReplaceInstWithInst(Instruction *From, Instruction *To);
/// SplitCriticalEdge - If this edge is a critical edge, insert a new node to
/// split the critical edge. This will update DominatorTree and
/// DominatorFrontier information if it is available, thus calling this pass
/// will not invalidate either of them. This returns the new block if the edge
/// was split, null otherwise.
///
/// If MergeIdenticalEdges is true (not the default), *all* edges from TI to the
/// specified successor will be merged into the same critical edge block.
/// This is most commonly interesting with switch instructions, which may
/// have many edges to any one destination. This ensures that all edges to that
/// dest go to one block instead of each going to a different block, but isn't
/// the standard definition of a "critical edge".
///
/// It is invalid to call this function on a critical edge that starts at an
/// IndirectBrInst. Splitting these edges will almost always create an invalid
/// program because the address of the new block won't be the one that is jumped
/// to.
///
BasicBlock *SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum,
Pass *P = 0, bool MergeIdenticalEdges = false,
bool DontDeleteUselessPHIs = false,
bool SplitLandingPads = false);
inline BasicBlock *SplitCriticalEdge(BasicBlock *BB, succ_iterator SI,
Pass *P = 0) {
return SplitCriticalEdge(BB->getTerminator(), SI.getSuccessorIndex(), P);
}
/// SplitCriticalEdge - If the edge from *PI to BB is not critical, return
/// false. Otherwise, split all edges between the two blocks and return true.
/// This updates all of the same analyses as the other SplitCriticalEdge
/// function. If P is specified, it updates the analyses
/// described above.
inline bool SplitCriticalEdge(BasicBlock *Succ, pred_iterator PI, Pass *P = 0) {
bool MadeChange = false;
TerminatorInst *TI = (*PI)->getTerminator();
for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
if (TI->getSuccessor(i) == Succ)
MadeChange |= !!SplitCriticalEdge(TI, i, P);
return MadeChange;
}
/// SplitCriticalEdge - If an edge from Src to Dst is critical, split the edge
/// and return true, otherwise return false. This method requires that there be
/// an edge between the two blocks. If P is specified, it updates the analyses
/// described above.
inline BasicBlock *SplitCriticalEdge(BasicBlock *Src, BasicBlock *Dst,
Pass *P = 0,
bool MergeIdenticalEdges = false,
bool DontDeleteUselessPHIs = false) {
TerminatorInst *TI = Src->getTerminator();
unsigned i = 0;
while (1) {
assert(i != TI->getNumSuccessors() && "Edge doesn't exist!");
if (TI->getSuccessor(i) == Dst)
return SplitCriticalEdge(TI, i, P, MergeIdenticalEdges,
DontDeleteUselessPHIs);
++i;
}
}
/// SplitEdge - Split the edge connecting specified block. Pass P must
/// not be NULL.
BasicBlock *SplitEdge(BasicBlock *From, BasicBlock *To, Pass *P);
/// SplitBlock - Split the specified block at the specified instruction - every
/// thing before SplitPt stays in Old and everything starting with SplitPt moves
/// to a new block. The two blocks are joined by an unconditional branch and
/// the loop info is updated.
///
BasicBlock *SplitBlock(BasicBlock *Old, Instruction *SplitPt, Pass *P);
/// SplitBlockPredecessors - This method transforms BB by introducing a new
/// basic block into the function, and moving some of the predecessors of BB to
/// be predecessors of the new block. The new predecessors are indicated by the
/// Preds array, which has NumPreds elements in it. The new block is given a
/// suffix of 'Suffix'. This function returns the new block.
///
/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
/// DominanceFrontier, LoopInfo, and LCCSA but no other analyses.
/// In particular, it does not preserve LoopSimplify (because it's
/// complicated to handle the case where one of the edges being split
/// is an exit of a loop with other exits).
///
BasicBlock *SplitBlockPredecessors(BasicBlock *BB, ArrayRef<BasicBlock*> Preds,
const char *Suffix, Pass *P = 0);
/// SplitLandingPadPredecessors - This method transforms the landing pad,
/// OrigBB, by introducing two new basic blocks into the function. One of those
/// new basic blocks gets the predecessors listed in Preds. The other basic
/// block gets the remaining predecessors of OrigBB. The landingpad instruction
/// OrigBB is clone into both of the new basic blocks. The new blocks are given
/// the suffixes 'Suffix1' and 'Suffix2', and are returned in the NewBBs vector.
///
/// This currently updates the LLVM IR, AliasAnalysis, DominatorTree,
/// DominanceFrontier, LoopInfo, and LCCSA but no other analyses. In particular,
/// it does not preserve LoopSimplify (because it's complicated to handle the
/// case where one of the edges being split is an exit of a loop with other
/// exits).
///
void SplitLandingPadPredecessors(BasicBlock *OrigBB,ArrayRef<BasicBlock*> Preds,
const char *Suffix, const char *Suffix2,
Pass *P, SmallVectorImpl<BasicBlock*> &NewBBs);
/// FoldReturnIntoUncondBranch - This method duplicates the specified return
/// instruction into a predecessor which ends in an unconditional branch. If
/// the return instruction returns a value defined by a PHI, propagate the
/// right value into the return. It returns the new return instruction in the
/// predecessor.
ReturnInst *FoldReturnIntoUncondBranch(ReturnInst *RI, BasicBlock *BB,
BasicBlock *Pred);
/// SplitBlockAndInsertIfThen - Split the containing block at the
/// specified instruction - everything before and including Cmp stays
/// in the old basic block, and everything after Cmp is moved to a
/// new block. The two blocks are connected by a conditional branch
/// (with value of Cmp being the condition).
/// Before:
/// Head
/// Cmp
/// Tail
/// After:
/// Head
/// Cmp
/// if (Cmp)
/// ThenBlock
/// Tail
///
/// If Unreachable is true, then ThenBlock ends with
/// UnreachableInst, otherwise it branches to Tail.
/// Returns the NewBasicBlock's terminator.
TerminatorInst *SplitBlockAndInsertIfThen(Instruction *Cmp,
bool Unreachable, MDNode *BranchWeights = 0);
///
/// GetIfCondition - Check whether BB is the merge point of a if-region.
/// If so, return the boolean condition that determines which entry into
/// BB will be taken. Also, return by references the block that will be
/// entered from if the condition is true, and the block that will be
/// entered if the condition is false.
Value *GetIfCondition(BasicBlock *BB, BasicBlock *&IfTrue,
BasicBlock *&IfFalse);
} // End llvm namespace
#endif
| 44.363636 | 80 | 0.697029 | [
"vector",
"transform"
] |
65d4aa3d6ce358d0b4ed306013e19d2ea9640f47 | 1,365 | h | C | src/Fluids.h | Trietch/test | 7b1293e47c9f21e58f32b0416a829edc23b64625 | [
"MIT"
] | 1 | 2021-09-14T13:14:00.000Z | 2021-09-14T13:14:00.000Z | src/Fluids.h | Trietch/test | 7b1293e47c9f21e58f32b0416a829edc23b64625 | [
"MIT"
] | null | null | null | src/Fluids.h | Trietch/test | 7b1293e47c9f21e58f32b0416a829edc23b64625 | [
"MIT"
] | 1 | 2021-09-09T12:03:11.000Z | 2021-09-09T12:03:11.000Z | #pragma once
#include <chrono>
#include <unordered_map>
#include <algorithm>
#include <execution>
#include <vector>
#include <memory>
#include "./types.h"
#include "./config.h"
#include "./StaggeredGrid.h"
#include "./Advect.h"
#include "./Project.h"
class Fluids
{
public:
explicit Fluids();
void update(const std::uint64_t iteration);
const std::vector<std::uint8_t>& texture() const;
const std::vector<double>& X() const;
const std::vector<double>& Y() const;
const Field<double, std::uint16_t>& surface() const;
bool isCellActive(
const std::uint16_t i,
const std::uint16_t j,
const std::uint16_t k
) const;
private:
void step();
void addForces();
void redistancing(
const std::uint64_t nbIte,
Field<double, std::uint16_t>& field,
Field<double, std::uint16_t>& fieldTemp
) const;
void extrapolate(
Field<double, std::uint16_t>& F,
Field<double, std::uint16_t>& Ftemp,
std::uint16_t nbIte = 0
) const;
void updateTexture2D();
void updateTexture3D();
std::uint64_t _iteration = 0;
std::vector<std::uint8_t> _texture;
StaggeredGrid<double, std::uint16_t> _grid {Config::N};
std::unique_ptr<Advect> _advection;
std::unique_ptr<Project> _projection;
};
| 24.818182 | 59 | 0.620513 | [
"vector"
] |
65d54c65d74d0ea85326551afc893655d2a23c5e | 279 | h | C | Vendor/TableKit/Private/TKTableModel+Private.h | mille2004/NoteItIOS | effe3a811b9d80ac19f26b4aab182223c990adfc | [
"Apache-2.0"
] | 60 | 2015-01-02T09:42:21.000Z | 2022-03-29T06:36:49.000Z | Vendor/TableKit/Private/TKTableModel+Private.h | mille2004/NoteItIOS | effe3a811b9d80ac19f26b4aab182223c990adfc | [
"Apache-2.0"
] | null | null | null | Vendor/TableKit/Private/TKTableModel+Private.h | mille2004/NoteItIOS | effe3a811b9d80ac19f26b4aab182223c990adfc | [
"Apache-2.0"
] | 20 | 2015-02-10T07:56:05.000Z | 2021-09-30T18:58:43.000Z | //
// Private+TKTableModel.h
// TableKitDemo
//
// Created by Bruno Wernimont on 9/07/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import "TKTableModel.h"
@interface TKTableModel (Private)
- (TKCellMapping *)cellMappingForObject:(id)object;
@end
| 17.4375 | 62 | 0.72043 | [
"object"
] |
65d8664dae30fec466d2859a145772ac78f64a17 | 104,403 | c | C | kernels/haswell/3/sup/s6x16/bli_gemmsup_rv_haswell_asm_sMx12.c | jeffhammond/blis | 1c733402a95ab08b20f3332c2397fd52a2627cf6 | [
"BSD-3-Clause"
] | null | null | null | kernels/haswell/3/sup/s6x16/bli_gemmsup_rv_haswell_asm_sMx12.c | jeffhammond/blis | 1c733402a95ab08b20f3332c2397fd52a2627cf6 | [
"BSD-3-Clause"
] | null | null | null | kernels/haswell/3/sup/s6x16/bli_gemmsup_rv_haswell_asm_sMx12.c | jeffhammond/blis | 1c733402a95ab08b20f3332c2397fd52a2627cf6 | [
"BSD-3-Clause"
] | null | null | null | /*
BLIS
An object-based framework for developing high-performance BLAS-like
libraries.
Copyright (C) 2014, The University of Texas at Austin
Copyright (C) 2019, Advanced Micro Devices, Inc.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name(s) of the copyright holder(s) nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "blis.h"
#define BLIS_ASM_SYNTAX_ATT
#include "bli_x86_asm_macros.h"
/*
rrr:
-------- ------ --------
-------- ------ --------
-------- += ------ ... --------
-------- ------ --------
-------- ------ :
-------- ------ :
rcr:
-------- | | | | --------
-------- | | | | --------
-------- += | | | | ... --------
-------- | | | | --------
-------- | | | | :
-------- | | | | :
Assumptions:
- B is row-stored;
- A is row- or column-stored;
- m0 and n0 are at most MR and NR, respectively.
Therefore, this (r)ow-preferential kernel is well-suited for contiguous
(v)ector loads on B and single-element broadcasts from A.
NOTE: These kernels explicitly support column-oriented IO, implemented
via an in-register transpose. And thus they also support the crr and
ccr cases, though only crr is ever utilized (because ccr is handled by
transposing the operation and executing rcr, which does not incur the
cost of the in-register transpose).
crr:
| | | | | | | | ------ --------
| | | | | | | | ------ --------
| | | | | | | | += ------ ... --------
| | | | | | | | ------ --------
| | | | | | | | ------ :
| | | | | | | | ------ :
*/
// Prototype reference microkernels.
GEMMSUP_KER_PROT( float, s, gemmsup_r_haswell_ref )
void bli_sgemmsup_rv_haswell_asm_6x12
(
conj_t conja,
conj_t conjb,
dim_t m0,
dim_t n0,
dim_t k0,
float* restrict alpha,
float* restrict a, inc_t rs_a0, inc_t cs_a0,
float* restrict b, inc_t rs_b0, inc_t cs_b0,
float* restrict beta,
float* restrict c, inc_t rs_c0, inc_t cs_c0,
auxinfo_t* data,
cntx_t* cntx
)
{
//void* a_next = bli_auxinfo_next_a( data );
//void* b_next = bli_auxinfo_next_b( data );
// Typecast local copies of integers in case dim_t and inc_t are a
// different size than is expected by load instructions.
uint64_t k_iter = k0 / 4;
uint64_t k_left = k0 % 4;
uint64_t rs_a = rs_a0;
uint64_t cs_a = cs_a0;
uint64_t rs_b = rs_b0;
uint64_t cs_b = cs_b0;
uint64_t rs_c = rs_c0;
uint64_t cs_c = cs_c0;
// -------------------------------------------------------------------------
begin_asm()
vzeroall() // zero all xmm/ymm registers.
mov(var(a), rax) // load address of a.
mov(var(rs_a), r8) // load rs_a
mov(var(cs_a), r9) // load cs_a
lea(mem(, r8, 4), r8) // rs_a *= sizeof(float)
lea(mem(, r9, 4), r9) // cs_a *= sizeof(float)
lea(mem(r8, r8, 2), r13) // r13 = 3*rs_a
lea(mem(r8, r8, 4), r15) // r15 = 5*rs_a
mov(var(b), rbx) // load address of b.
mov(var(rs_b), r10) // load rs_b
//mov(var(cs_b), r11) // load cs_b
lea(mem(, r10, 4), r10) // rs_b *= sizeof(float)
//lea(mem(, r11, 4), r11) // cs_b *= sizeof(float)
// NOTE: We cannot pre-load elements of a or b
// because it could eventually, in the last
// unrolled iter or the cleanup loop, result
// in reading beyond the bounds allocated mem
// (the likely result: a segmentation fault).
mov(var(c), rcx) // load address of c
mov(var(rs_c), rdi) // load rs_c
lea(mem(, rdi, 4), rdi) // rs_c *= sizeof(float)
cmp(imm(4), rdi) // set ZF if (4*rs_c) == 4.
jz(.SCOLPFETCH) // jump to column storage case
label(.SROWPFETCH) // row-stored prefetching on c
lea(mem(rcx, rdi, 2), rdx) //
lea(mem(rdx, rdi, 1), rdx) // rdx = c + 3*rs_c;
prefetch(0, mem(rcx, 7*8)) // prefetch c + 0*rs_c
prefetch(0, mem(rcx, rdi, 1, 7*8)) // prefetch c + 1*rs_c
prefetch(0, mem(rcx, rdi, 2, 7*8)) // prefetch c + 2*rs_c
prefetch(0, mem(rdx, 7*8)) // prefetch c + 3*rs_c
prefetch(0, mem(rdx, rdi, 1, 7*8)) // prefetch c + 4*rs_c
prefetch(0, mem(rdx, rdi, 2, 7*8)) // prefetch c + 5*rs_c
jmp(.SPOSTPFETCH) // jump to end of prefetching c
label(.SCOLPFETCH) // column-stored prefetching c
mov(var(cs_c), rsi) // load cs_c to rsi (temporarily)
lea(mem(, rsi, 4), rsi) // cs_c *= sizeof(float)
lea(mem(rsi, rsi, 2), rbp) // rbp = 3*cs_c;
prefetch(0, mem(rcx, 5*8)) // prefetch c + 0*cs_c
prefetch(0, mem(rcx, rsi, 1, 5*8)) // prefetch c + 1*cs_c
prefetch(0, mem(rcx, rsi, 2, 5*8)) // prefetch c + 2*cs_c
prefetch(0, mem(rcx, rbp, 1, 5*8)) // prefetch c + 3*cs_c
prefetch(0, mem(rcx, rsi, 4, 5*8)) // prefetch c + 4*cs_c
lea(mem(rcx, rsi, 4), rdx) // rdx = c + 4*cs_c;
prefetch(0, mem(rdx, rsi, 1, 5*8)) // prefetch c + 5*cs_c
prefetch(0, mem(rdx, rsi, 2, 5*8)) // prefetch c + 6*cs_c
prefetch(0, mem(rdx, rbp, 1, 5*8)) // prefetch c + 7*cs_c
prefetch(0, mem(rdx, rsi, 4, 5*8)) // prefetch c + 8*cs_c
lea(mem(rcx, rsi, 8), rdx) // rdx = c + 8*cs_c;
prefetch(0, mem(rdx, rsi, 1, 5*8)) // prefetch c + 9*cs_c
prefetch(0, mem(rdx, rsi, 2, 5*8)) // prefetch c + 10*cs_c
prefetch(0, mem(rdx, rbp, 1, 5*8)) // prefetch c + 11*cs_c
label(.SPOSTPFETCH) // done prefetching c
#if 1
lea(mem(rax, r9, 8), rdx) //
lea(mem(rdx, r9, 8), rdx) // rdx = a + 16*cs_a;
#endif
mov(var(k_iter), rsi) // i = k_iter;
test(rsi, rsi) // check i via logical AND.
je(.SCONSIDKLEFT) // if i == 0, jump to code that
// contains the k_left loop.
label(.SLOOPKITER) // MAIN LOOP
// ---------------------------------- iteration 0
#if 1
prefetch(0, mem(rdx, 5*8))
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
vbroadcastss(mem(rax, r8, 2), ymm2)
vbroadcastss(mem(rax, r13, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm8)
vfmadd231ps(ymm1, ymm2, ymm9)
vfmadd231ps(ymm0, ymm3, ymm10)
vfmadd231ps(ymm1, ymm3, ymm11)
vbroadcastss(mem(rax, r8, 4), ymm2)
vbroadcastss(mem(rax, r15, 1), ymm3)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm12)
vfmadd231ps(ymm1, ymm2, ymm13)
vfmadd231ps(ymm0, ymm3, ymm14)
vfmadd231ps(ymm1, ymm3, ymm15)
// ---------------------------------- iteration 1
#if 0
prefetch(0, mem(rdx, r9, 1, 5*8))
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
vbroadcastss(mem(rax, r8, 2), ymm2)
vbroadcastss(mem(rax, r13, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm8)
vfmadd231ps(ymm1, ymm2, ymm9)
vfmadd231ps(ymm0, ymm3, ymm10)
vfmadd231ps(ymm1, ymm3, ymm11)
vbroadcastss(mem(rax, r8, 4), ymm2)
vbroadcastss(mem(rax, r15, 1), ymm3)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm12)
vfmadd231ps(ymm1, ymm2, ymm13)
vfmadd231ps(ymm0, ymm3, ymm14)
vfmadd231ps(ymm1, ymm3, ymm15)
// ---------------------------------- iteration 2
#if 1
prefetch(0, mem(rdx, r9, 2, 5*8))
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
vbroadcastss(mem(rax, r8, 2), ymm2)
vbroadcastss(mem(rax, r13, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm8)
vfmadd231ps(ymm1, ymm2, ymm9)
vfmadd231ps(ymm0, ymm3, ymm10)
vfmadd231ps(ymm1, ymm3, ymm11)
vbroadcastss(mem(rax, r8, 4), ymm2)
vbroadcastss(mem(rax, r15, 1), ymm3)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm12)
vfmadd231ps(ymm1, ymm2, ymm13)
vfmadd231ps(ymm0, ymm3, ymm14)
vfmadd231ps(ymm1, ymm3, ymm15)
// ---------------------------------- iteration 3
#if 1
lea(mem(rdx, r9, 4), rdx) // a_prefetch += 4*cs_a;
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
vbroadcastss(mem(rax, r8, 2), ymm2)
vbroadcastss(mem(rax, r13, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm8)
vfmadd231ps(ymm1, ymm2, ymm9)
vfmadd231ps(ymm0, ymm3, ymm10)
vfmadd231ps(ymm1, ymm3, ymm11)
vbroadcastss(mem(rax, r8, 4), ymm2)
vbroadcastss(mem(rax, r15, 1), ymm3)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm12)
vfmadd231ps(ymm1, ymm2, ymm13)
vfmadd231ps(ymm0, ymm3, ymm14)
vfmadd231ps(ymm1, ymm3, ymm15)
dec(rsi) // i -= 1;
jne(.SLOOPKITER) // iterate again if i != 0.
label(.SCONSIDKLEFT)
mov(var(k_left), rsi) // i = k_left;
test(rsi, rsi) // check i via logical AND.
je(.SPOSTACCUM) // if i == 0, we're done; jump to end.
// else, we prepare to enter k_left loop.
label(.SLOOPKLEFT) // EDGE LOOP
#if 0
prefetch(0, mem(rdx, 5*8))
add(r9, rdx)
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
vbroadcastss(mem(rax, r8, 2), ymm2)
vbroadcastss(mem(rax, r13, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm8)
vfmadd231ps(ymm1, ymm2, ymm9)
vfmadd231ps(ymm0, ymm3, ymm10)
vfmadd231ps(ymm1, ymm3, ymm11)
vbroadcastss(mem(rax, r8, 4), ymm2)
vbroadcastss(mem(rax, r15, 1), ymm3)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm12)
vfmadd231ps(ymm1, ymm2, ymm13)
vfmadd231ps(ymm0, ymm3, ymm14)
vfmadd231ps(ymm1, ymm3, ymm15)
dec(rsi) // i -= 1;
jne(.SLOOPKLEFT) // iterate again if i != 0.
label(.SPOSTACCUM)
mov(var(alpha), rax) // load address of alpha
mov(var(beta), rbx) // load address of beta
vbroadcastss(mem(rax), ymm0) // load alpha and duplicate
vbroadcastss(mem(rbx), ymm3) // load beta and duplicate
vmulps(ymm0, ymm4, ymm4) // scale by alpha
vmulps(xmm0, xmm5, xmm5)
vmulps(ymm0, ymm6, ymm6)
vmulps(xmm0, xmm7, xmm7)
vmulps(ymm0, ymm8, ymm8)
vmulps(xmm0, xmm9, xmm9)
vmulps(ymm0, ymm10, ymm10)
vmulps(xmm0, xmm11, xmm11)
vmulps(ymm0, ymm12, ymm12)
vmulps(xmm0, xmm13, xmm13)
vmulps(ymm0, ymm14, ymm14)
vmulps(xmm0, xmm15, xmm15)
mov(var(cs_c), rsi) // load cs_c
lea(mem(, rsi, 4), rsi) // rsi = cs_c * sizeof(float)
//lea(mem(rcx, rsi, 4), rdx) // load address of c + 4*cs_c;
lea(mem(rcx, rdi, 4), rdx) // load address of c + 4*rs_c;
lea(mem(rsi, rsi, 2), rax) // rax = 3*cs_c;
lea(mem(rsi, rsi, 4), rbx) // rbx = 5*cs_c;
lea(mem(rax, rsi, 4), rbp) // rbp = 7*cs_c;
// now avoid loading C if beta == 0
vxorps(ymm0, ymm0, ymm0) // set ymm0 to zero.
vucomiss(xmm0, xmm3) // set ZF if beta == 0.
je(.SBETAZERO) // if ZF = 1, jump to beta == 0 case
cmp(imm(4), rdi) // set ZF if (4*rs_c) == 4.
jz(.SCOLSTORED) // jump to column storage case
label(.SROWSTORED)
vfmadd231ps(mem(rcx, 0*32), ymm3, ymm4)
vmovups(ymm4, mem(rcx, 0*32))
vfmadd231ps(mem(rcx, 1*32), xmm3, xmm5)
vmovups(xmm5, mem(rcx, 1*32))
add(rdi, rcx)
vfmadd231ps(mem(rcx, 0*32), ymm3, ymm6)
vmovups(ymm6, mem(rcx, 0*32))
vfmadd231ps(mem(rcx, 1*32), xmm3, xmm7)
vmovups(xmm7, mem(rcx, 1*32))
add(rdi, rcx)
vfmadd231ps(mem(rcx, 0*32), ymm3, ymm8)
vmovups(ymm8, mem(rcx, 0*32))
vfmadd231ps(mem(rcx, 1*32), xmm3, xmm9)
vmovups(xmm9, mem(rcx, 1*32))
add(rdi, rcx)
vfmadd231ps(mem(rcx, 0*32), ymm3, ymm10)
vmovups(ymm10, mem(rcx, 0*32))
vfmadd231ps(mem(rcx, 1*32), xmm3, xmm11)
vmovups(xmm11, mem(rcx, 1*32))
add(rdi, rcx)
vfmadd231ps(mem(rcx, 0*32), ymm3, ymm12)
vmovups(ymm12, mem(rcx, 0*32))
vfmadd231ps(mem(rcx, 1*32), xmm3, xmm13)
vmovups(xmm13, mem(rcx, 1*32))
add(rdi, rcx)
vfmadd231ps(mem(rcx, 0*32), ymm3, ymm14)
vmovups(ymm14, mem(rcx, 0*32))
vfmadd231ps(mem(rcx, 1*32), xmm3, xmm15)
vmovups(xmm15, mem(rcx, 1*32))
//add(rdi, rcx)
jmp(.SDONE) // jump to end.
label(.SCOLSTORED)
// begin I/O on columns 0-7
vunpcklps(ymm6, ymm4, ymm0)
vunpcklps(ymm10, ymm8, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vextractf128(imm(0x1), ymm0, xmm2)
vfmadd231ps(mem(rcx ), xmm3, xmm0)
vfmadd231ps(mem(rcx, rsi, 4), xmm3, xmm2)
vmovups(xmm0, mem(rcx )) // store ( gamma00..gamma30 )
vmovups(xmm2, mem(rcx, rsi, 4)) // store ( gamma04..gamma34 )
vextractf128(imm(0x1), ymm1, xmm2)
vfmadd231ps(mem(rcx, rsi, 1), xmm3, xmm1)
vfmadd231ps(mem(rcx, rbx, 1), xmm3, xmm2)
vmovups(xmm1, mem(rcx, rsi, 1)) // store ( gamma01..gamma31 )
vmovups(xmm2, mem(rcx, rbx, 1)) // store ( gamma05..gamma35 )
vunpckhps(ymm6, ymm4, ymm0)
vunpckhps(ymm10, ymm8, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vextractf128(imm(0x1), ymm0, xmm2)
vfmadd231ps(mem(rcx, rsi, 2), xmm3, xmm0)
vfmadd231ps(mem(rcx, rax, 2), xmm3, xmm2)
vmovups(xmm0, mem(rcx, rsi, 2)) // store ( gamma02..gamma32 )
vmovups(xmm2, mem(rcx, rax, 2)) // store ( gamma06..gamma36 )
vextractf128(imm(0x1), ymm1, xmm2)
vfmadd231ps(mem(rcx, rax, 1), xmm3, xmm1)
vfmadd231ps(mem(rcx, rbp, 1), xmm3, xmm2)
vmovups(xmm1, mem(rcx, rax, 1)) // store ( gamma03..gamma33 )
vmovups(xmm2, mem(rcx, rbp, 1)) // store ( gamma07..gamma37 )
lea(mem(rcx, rsi, 8), rcx) // rcx += 8*cs_c
vunpcklps(ymm14, ymm12, ymm0)
vextractf128(imm(0x1), ymm0, xmm2)
vmovlpd(mem(rdx ), xmm1, xmm1)
vmovhpd(mem(rdx, rsi, 1), xmm1, xmm1)
vfmadd231ps(xmm1, xmm3, xmm0)
vmovlpd(xmm0, mem(rdx )) // store ( gamma40..gamma50 )
vmovhpd(xmm0, mem(rdx, rsi, 1)) // store ( gamma41..gamma51 )
vmovlpd(mem(rdx, rsi, 4), xmm1, xmm1)
vmovhpd(mem(rdx, rbx, 1), xmm1, xmm1)
vfmadd231ps(xmm1, xmm3, xmm2)
vmovlpd(xmm2, mem(rdx, rsi, 4)) // store ( gamma44..gamma54 )
vmovhpd(xmm2, mem(rdx, rbx, 1)) // store ( gamma45..gamma55 )
vunpckhps(ymm14, ymm12, ymm0)
vextractf128(imm(0x1), ymm0, xmm2)
vmovlpd(mem(rdx, rsi, 2), xmm1, xmm1)
vmovhpd(mem(rdx, rax, 1), xmm1, xmm1)
vfmadd231ps(xmm1, xmm3, xmm0)
vmovlpd(xmm0, mem(rdx, rsi, 2)) // store ( gamma42..gamma52 )
vmovhpd(xmm0, mem(rdx, rax, 1)) // store ( gamma43..gamma53 )
vmovlpd(mem(rdx, rax, 2), xmm1, xmm1)
vmovhpd(mem(rdx, rbp, 1), xmm1, xmm1)
vfmadd231ps(xmm1, xmm3, xmm2)
vmovlpd(xmm2, mem(rdx, rax, 2)) // store ( gamma46..gamma56 )
vmovhpd(xmm2, mem(rdx, rbp, 1)) // store ( gamma47..gamma57 )
lea(mem(rdx, rsi, 8), rdx) // rdx += 8*cs_c
// begin I/O on columns 8-11
vunpcklps(ymm7, ymm5, ymm0)
vunpcklps(ymm11, ymm9, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vfmadd231ps(mem(rcx ), xmm3, xmm0)
vmovups(xmm0, mem(rcx )) // store ( gamma00..gamma30 )
vfmadd231ps(mem(rcx, rsi, 1), xmm3, xmm1)
vmovups(xmm1, mem(rcx, rsi, 1)) // store ( gamma01..gamma31 )
vunpckhps(ymm7, ymm5, ymm0)
vunpckhps(ymm11, ymm9, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vfmadd231ps(mem(rcx, rsi, 2), xmm3, xmm0)
vmovups(xmm0, mem(rcx, rsi, 2)) // store ( gamma02..gamma32 )
vfmadd231ps(mem(rcx, rax, 1), xmm3, xmm1)
vmovups(xmm1, mem(rcx, rax, 1)) // store ( gamma03..gamma33 )
//lea(mem(rcx, rsi, 8), rcx) // rcx += 8*cs_c
vunpcklps(ymm15, ymm13, ymm0)
vmovlpd(mem(rdx ), xmm1, xmm1)
vmovhpd(mem(rdx, rsi, 1), xmm1, xmm1)
vfmadd231ps(xmm1, xmm3, xmm0)
vmovlpd(xmm0, mem(rdx )) // store ( gamma40..gamma50 )
vmovhpd(xmm0, mem(rdx, rsi, 1)) // store ( gamma41..gamma51 )
vunpckhps(ymm15, ymm13, ymm0)
vmovlpd(mem(rdx, rsi, 2), xmm1, xmm1)
vmovhpd(mem(rdx, rax, 1), xmm1, xmm1)
vfmadd231ps(xmm1, xmm3, xmm0)
vmovlpd(xmm0, mem(rdx, rsi, 2)) // store ( gamma42..gamma52 )
vmovhpd(xmm0, mem(rdx, rax, 1)) // store ( gamma43..gamma53 )
//lea(mem(rdx, rsi, 8), rdx) // rdx += 8*cs_c
jmp(.SDONE) // jump to end.
label(.SBETAZERO)
cmp(imm(4), rdi) // set ZF if (4*rs_c) == 4.
jz(.SCOLSTORBZ) // jump to column storage case
label(.SROWSTORBZ)
vmovups(ymm4, mem(rcx, 0*32))
vmovups(xmm5, mem(rcx, 1*32))
add(rdi, rcx)
vmovups(ymm6, mem(rcx, 0*32))
vmovups(xmm7, mem(rcx, 1*32))
add(rdi, rcx)
vmovups(ymm8, mem(rcx, 0*32))
vmovups(xmm9, mem(rcx, 1*32))
add(rdi, rcx)
vmovups(ymm10, mem(rcx, 0*32))
vmovups(xmm11, mem(rcx, 1*32))
add(rdi, rcx)
vmovups(ymm12, mem(rcx, 0*32))
vmovups(xmm13, mem(rcx, 1*32))
add(rdi, rcx)
vmovups(ymm14, mem(rcx, 0*32))
vmovups(xmm15, mem(rcx, 1*32))
//add(rdi, rcx)
jmp(.SDONE) // jump to end.
label(.SCOLSTORBZ)
// begin I/O on columns 0-7
vunpcklps(ymm6, ymm4, ymm0)
vunpcklps(ymm10, ymm8, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vextractf128(imm(0x1), ymm0, xmm2)
vmovups(xmm0, mem(rcx )) // store ( gamma00..gamma30 )
vmovups(xmm2, mem(rcx, rsi, 4)) // store ( gamma04..gamma34 )
vextractf128(imm(0x1), ymm1, xmm2)
vmovups(xmm1, mem(rcx, rsi, 1)) // store ( gamma01..gamma31 )
vmovups(xmm2, mem(rcx, rbx, 1)) // store ( gamma05..gamma35 )
vunpckhps(ymm6, ymm4, ymm0)
vunpckhps(ymm10, ymm8, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vextractf128(imm(0x1), ymm0, xmm2)
vmovups(xmm0, mem(rcx, rsi, 2)) // store ( gamma02..gamma32 )
vmovups(xmm2, mem(rcx, rax, 2)) // store ( gamma06..gamma36 )
vextractf128(imm(0x1), ymm1, xmm2)
vmovups(xmm1, mem(rcx, rax, 1)) // store ( gamma03..gamma33 )
vmovups(xmm2, mem(rcx, rbp, 1)) // store ( gamma07..gamma37 )
lea(mem(rcx, rsi, 8), rcx) // rcx += 8*cs_c
vunpcklps(ymm14, ymm12, ymm0)
vextractf128(imm(0x1), ymm0, xmm2)
vmovlpd(xmm0, mem(rdx )) // store ( gamma40..gamma50 )
vmovhpd(xmm0, mem(rdx, rsi, 1)) // store ( gamma41..gamma51 )
vmovlpd(xmm2, mem(rdx, rsi, 4)) // store ( gamma44..gamma54 )
vmovhpd(xmm2, mem(rdx, rbx, 1)) // store ( gamma45..gamma55 )
vunpckhps(ymm14, ymm12, ymm0)
vextractf128(imm(0x1), ymm0, xmm2)
vmovlpd(xmm0, mem(rdx, rsi, 2)) // store ( gamma42..gamma52 )
vmovhpd(xmm0, mem(rdx, rax, 1)) // store ( gamma43..gamma53 )
vmovlpd(xmm2, mem(rdx, rax, 2)) // store ( gamma46..gamma56 )
vmovhpd(xmm2, mem(rdx, rbp, 1)) // store ( gamma47..gamma57 )
lea(mem(rdx, rsi, 8), rdx) // rdx += 8*cs_c
// begin I/O on columns 8-11
vunpcklps(ymm7, ymm5, ymm0)
vunpcklps(ymm11, ymm9, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vmovups(xmm0, mem(rcx )) // store ( gamma00..gamma30 )
vmovups(xmm1, mem(rcx, rsi, 1)) // store ( gamma01..gamma31 )
vunpckhps(ymm7, ymm5, ymm0)
vunpckhps(ymm11, ymm9, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vmovups(xmm0, mem(rcx, rsi, 2)) // store ( gamma02..gamma32 )
vmovups(xmm1, mem(rcx, rax, 1)) // store ( gamma03..gamma33 )
//lea(mem(rcx, rsi, 8), rcx) // rcx += 8*cs_c
vunpcklps(ymm15, ymm13, ymm0)
vmovlpd(xmm0, mem(rdx )) // store ( gamma40..gamma50 )
vmovhpd(xmm0, mem(rdx, rsi, 1)) // store ( gamma41..gamma51 )
vunpckhps(ymm15, ymm13, ymm0)
vmovlpd(xmm0, mem(rdx, rsi, 2)) // store ( gamma42..gamma52 )
vmovhpd(xmm0, mem(rdx, rax, 1)) // store ( gamma43..gamma53 )
//lea(mem(rdx, rsi, 8), rdx) // rdx += 8*cs_c
label(.SDONE)
end_asm(
: // output operands (none)
: // input operands
[k_iter] "m" (k_iter),
[k_left] "m" (k_left),
[a] "m" (a),
[rs_a] "m" (rs_a),
[cs_a] "m" (cs_a),
[b] "m" (b),
[rs_b] "m" (rs_b),
[cs_b] "m" (cs_b),
[alpha] "m" (alpha),
[beta] "m" (beta),
[c] "m" (c),
[rs_c] "m" (rs_c),
[cs_c] "m" (cs_c)/*,
[a_next] "m" (a_next),
[b_next] "m" (b_next)*/
: // register clobber list
"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "rbp",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
"xmm0", "xmm1", "xmm2", "xmm3",
"xmm4", "xmm5", "xmm6", "xmm7",
"xmm8", "xmm9", "xmm10", "xmm11",
"xmm12", "xmm13", "xmm14", "xmm15",
"memory"
)
}
void bli_sgemmsup_rv_haswell_asm_5x12
(
conj_t conja,
conj_t conjb,
dim_t m0,
dim_t n0,
dim_t k0,
float* restrict alpha,
float* restrict a, inc_t rs_a0, inc_t cs_a0,
float* restrict b, inc_t rs_b0, inc_t cs_b0,
float* restrict beta,
float* restrict c, inc_t rs_c0, inc_t cs_c0,
auxinfo_t* data,
cntx_t* cntx
)
{
//void* a_next = bli_auxinfo_next_a( data );
//void* b_next = bli_auxinfo_next_b( data );
// Typecast local copies of integers in case dim_t and inc_t are a
// different size than is expected by load instructions.
uint64_t k_iter = k0 / 4;
uint64_t k_left = k0 % 4;
uint64_t rs_a = rs_a0;
uint64_t cs_a = cs_a0;
uint64_t rs_b = rs_b0;
uint64_t cs_b = cs_b0;
uint64_t rs_c = rs_c0;
uint64_t cs_c = cs_c0;
// -------------------------------------------------------------------------
begin_asm()
vzeroall() // zero all xmm/ymm registers.
mov(var(a), rax) // load address of a.
mov(var(rs_a), r8) // load rs_a
mov(var(cs_a), r9) // load cs_a
lea(mem(, r8, 4), r8) // rs_a *= sizeof(float)
lea(mem(, r9, 4), r9) // cs_a *= sizeof(float)
lea(mem(r8, r8, 2), r13) // r13 = 3*rs_a
//lea(mem(r8, r8, 4), r15) // r15 = 5*rs_a
mov(var(b), rbx) // load address of b.
mov(var(rs_b), r10) // load rs_b
//mov(var(cs_b), r11) // load cs_b
lea(mem(, r10, 4), r10) // rs_b *= sizeof(float)
//lea(mem(, r11, 4), r11) // cs_b *= sizeof(float)
// NOTE: We cannot pre-load elements of a or b
// because it could eventually, in the last
// unrolled iter or the cleanup loop, result
// in reading beyond the bounds allocated mem
// (the likely result: a segmentation fault).
mov(var(c), rcx) // load address of c
mov(var(rs_c), rdi) // load rs_c
lea(mem(, rdi, 4), rdi) // rs_c *= sizeof(float)
cmp(imm(4), rdi) // set ZF if (4*rs_c) == 4.
jz(.SCOLPFETCH) // jump to column storage case
label(.SROWPFETCH) // row-stored prefetching on c
lea(mem(rcx, rdi, 2), rdx) //
lea(mem(rdx, rdi, 1), rdx) // rdx = c + 3*rs_c;
prefetch(0, mem(rcx, 7*8)) // prefetch c + 0*rs_c
prefetch(0, mem(rcx, rdi, 1, 7*8)) // prefetch c + 1*rs_c
prefetch(0, mem(rcx, rdi, 2, 7*8)) // prefetch c + 2*rs_c
prefetch(0, mem(rdx, 7*8)) // prefetch c + 3*rs_c
prefetch(0, mem(rdx, rdi, 1, 7*8)) // prefetch c + 4*rs_c
jmp(.SPOSTPFETCH) // jump to end of prefetching c
label(.SCOLPFETCH) // column-stored prefetching c
mov(var(cs_c), rsi) // load cs_c to rsi (temporarily)
lea(mem(, rsi, 4), rsi) // cs_c *= sizeof(float)
lea(mem(rsi, rsi, 2), rbp) // rbp = 3*cs_c;
prefetch(0, mem(rcx, 4*8)) // prefetch c + 0*cs_c
prefetch(0, mem(rcx, rsi, 1, 4*8)) // prefetch c + 1*cs_c
prefetch(0, mem(rcx, rsi, 2, 4*8)) // prefetch c + 2*cs_c
prefetch(0, mem(rcx, rbp, 1, 4*8)) // prefetch c + 3*cs_c
prefetch(0, mem(rcx, rsi, 4, 4*8)) // prefetch c + 4*cs_c
lea(mem(rcx, rsi, 4), rdx) // rdx = c + 4*cs_c;
prefetch(0, mem(rdx, rsi, 1, 4*8)) // prefetch c + 5*cs_c
prefetch(0, mem(rdx, rsi, 2, 4*8)) // prefetch c + 6*cs_c
prefetch(0, mem(rdx, rbp, 1, 4*8)) // prefetch c + 7*cs_c
prefetch(0, mem(rdx, rsi, 4, 4*8)) // prefetch c + 8*cs_c
lea(mem(rcx, rsi, 8), rdx) // rdx = c + 8*cs_c;
prefetch(0, mem(rdx, rsi, 1, 4*8)) // prefetch c + 9*cs_c
prefetch(0, mem(rdx, rsi, 2, 4*8)) // prefetch c + 10*cs_c
prefetch(0, mem(rdx, rbp, 1, 4*8)) // prefetch c + 11*cs_c
label(.SPOSTPFETCH) // done prefetching c
#if 1
lea(mem(rax, r9, 8), rdx) //
lea(mem(rdx, r9, 8), rdx) // rdx = a + 16*cs_a;
#endif
mov(var(k_iter), rsi) // i = k_iter;
test(rsi, rsi) // check i via logical AND.
je(.SCONSIDKLEFT) // if i == 0, jump to code that
// contains the k_left loop.
label(.SLOOPKITER) // MAIN LOOP
// ---------------------------------- iteration 0
#if 1
prefetch(0, mem(rdx, 4*8))
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
vbroadcastss(mem(rax, r8, 2), ymm2)
vbroadcastss(mem(rax, r13, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm8)
vfmadd231ps(ymm1, ymm2, ymm9)
vfmadd231ps(ymm0, ymm3, ymm10)
vfmadd231ps(ymm1, ymm3, ymm11)
vbroadcastss(mem(rax, r8, 4), ymm2)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm12)
vfmadd231ps(ymm1, ymm2, ymm13)
// ---------------------------------- iteration 1
#if 0
prefetch(0, mem(rdx, r9, 1, 4*8))
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
vbroadcastss(mem(rax, r8, 2), ymm2)
vbroadcastss(mem(rax, r13, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm8)
vfmadd231ps(ymm1, ymm2, ymm9)
vfmadd231ps(ymm0, ymm3, ymm10)
vfmadd231ps(ymm1, ymm3, ymm11)
vbroadcastss(mem(rax, r8, 4), ymm2)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm12)
vfmadd231ps(ymm1, ymm2, ymm13)
// ---------------------------------- iteration 2
#if 1
prefetch(0, mem(rdx, r9, 2, 4*8))
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
vbroadcastss(mem(rax, r8, 2), ymm2)
vbroadcastss(mem(rax, r13, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm8)
vfmadd231ps(ymm1, ymm2, ymm9)
vfmadd231ps(ymm0, ymm3, ymm10)
vfmadd231ps(ymm1, ymm3, ymm11)
vbroadcastss(mem(rax, r8, 4), ymm2)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm12)
vfmadd231ps(ymm1, ymm2, ymm13)
// ---------------------------------- iteration 3
#if 1
lea(mem(rdx, r9, 4), rdx) // a_prefetch += 4*cs_a;
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
vbroadcastss(mem(rax, r8, 2), ymm2)
vbroadcastss(mem(rax, r13, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm8)
vfmadd231ps(ymm1, ymm2, ymm9)
vfmadd231ps(ymm0, ymm3, ymm10)
vfmadd231ps(ymm1, ymm3, ymm11)
vbroadcastss(mem(rax, r8, 4), ymm2)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm12)
vfmadd231ps(ymm1, ymm2, ymm13)
dec(rsi) // i -= 1;
jne(.SLOOPKITER) // iterate again if i != 0.
label(.SCONSIDKLEFT)
mov(var(k_left), rsi) // i = k_left;
test(rsi, rsi) // check i via logical AND.
je(.SPOSTACCUM) // if i == 0, we're done; jump to end.
// else, we prepare to enter k_left loop.
label(.SLOOPKLEFT) // EDGE LOOP
#if 0
prefetch(0, mem(rdx, 5*8))
add(r9, rdx)
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
vbroadcastss(mem(rax, r8, 2), ymm2)
vbroadcastss(mem(rax, r13, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm8)
vfmadd231ps(ymm1, ymm2, ymm9)
vfmadd231ps(ymm0, ymm3, ymm10)
vfmadd231ps(ymm1, ymm3, ymm11)
vbroadcastss(mem(rax, r8, 4), ymm2)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm12)
vfmadd231ps(ymm1, ymm2, ymm13)
dec(rsi) // i -= 1;
jne(.SLOOPKLEFT) // iterate again if i != 0.
label(.SPOSTACCUM)
mov(var(alpha), rax) // load address of alpha
mov(var(beta), rbx) // load address of beta
vbroadcastss(mem(rax), ymm0) // load alpha and duplicate
vbroadcastss(mem(rbx), ymm3) // load beta and duplicate
vmulps(ymm0, ymm4, ymm4) // scale by alpha
vmulps(xmm0, xmm5, xmm5)
vmulps(ymm0, ymm6, ymm6)
vmulps(xmm0, xmm7, xmm7)
vmulps(ymm0, ymm8, ymm8)
vmulps(xmm0, xmm9, xmm9)
vmulps(ymm0, ymm10, ymm10)
vmulps(xmm0, xmm11, xmm11)
vmulps(ymm0, ymm12, ymm12)
vmulps(xmm0, xmm13, xmm13)
mov(var(cs_c), rsi) // load cs_c
lea(mem(, rsi, 4), rsi) // rsi = cs_c * sizeof(float)
//lea(mem(rcx, rsi, 4), rdx) // load address of c + 4*cs_c;
lea(mem(rcx, rdi, 4), rdx) // load address of c + 4*rs_c;
lea(mem(rsi, rsi, 2), rax) // rax = 3*cs_c;
lea(mem(rsi, rsi, 4), rbx) // rbx = 5*cs_c;
lea(mem(rax, rsi, 4), rbp) // rbp = 7*cs_c;
// now avoid loading C if beta == 0
vxorps(ymm0, ymm0, ymm0) // set ymm0 to zero.
vucomiss(xmm0, xmm3) // set ZF if beta == 0.
je(.SBETAZERO) // if ZF = 1, jump to beta == 0 case
cmp(imm(4), rdi) // set ZF if (4*rs_c) == 4.
jz(.SCOLSTORED) // jump to column storage case
label(.SROWSTORED)
vfmadd231ps(mem(rcx, 0*32), ymm3, ymm4)
vmovups(ymm4, mem(rcx, 0*32))
vfmadd231ps(mem(rcx, 1*32), xmm3, xmm5)
vmovups(xmm5, mem(rcx, 1*32))
add(rdi, rcx)
vfmadd231ps(mem(rcx, 0*32), ymm3, ymm6)
vmovups(ymm6, mem(rcx, 0*32))
vfmadd231ps(mem(rcx, 1*32), xmm3, xmm7)
vmovups(xmm7, mem(rcx, 1*32))
add(rdi, rcx)
vfmadd231ps(mem(rcx, 0*32), ymm3, ymm8)
vmovups(ymm8, mem(rcx, 0*32))
vfmadd231ps(mem(rcx, 1*32), xmm3, xmm9)
vmovups(xmm9, mem(rcx, 1*32))
add(rdi, rcx)
vfmadd231ps(mem(rcx, 0*32), ymm3, ymm10)
vmovups(ymm10, mem(rcx, 0*32))
vfmadd231ps(mem(rcx, 1*32), xmm3, xmm11)
vmovups(xmm11, mem(rcx, 1*32))
add(rdi, rcx)
vfmadd231ps(mem(rcx, 0*32), ymm3, ymm12)
vmovups(ymm12, mem(rcx, 0*32))
vfmadd231ps(mem(rcx, 1*32), xmm3, xmm13)
vmovups(xmm13, mem(rcx, 1*32))
//add(rdi, rcx)
jmp(.SDONE) // jump to end.
label(.SCOLSTORED)
// begin I/O on columns 0-7
vunpcklps(ymm6, ymm4, ymm0)
vunpcklps(ymm10, ymm8, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vextractf128(imm(0x1), ymm0, xmm2)
vfmadd231ps(mem(rcx ), xmm3, xmm0)
vfmadd231ps(mem(rcx, rsi, 4), xmm3, xmm2)
vmovups(xmm0, mem(rcx )) // store ( gamma00..gamma30 )
vmovups(xmm2, mem(rcx, rsi, 4)) // store ( gamma04..gamma34 )
vextractf128(imm(0x1), ymm1, xmm2)
vfmadd231ps(mem(rcx, rsi, 1), xmm3, xmm1)
vfmadd231ps(mem(rcx, rbx, 1), xmm3, xmm2)
vmovups(xmm1, mem(rcx, rsi, 1)) // store ( gamma01..gamma31 )
vmovups(xmm2, mem(rcx, rbx, 1)) // store ( gamma05..gamma35 )
vunpckhps(ymm6, ymm4, ymm0)
vunpckhps(ymm10, ymm8, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vextractf128(imm(0x1), ymm0, xmm2)
vfmadd231ps(mem(rcx, rsi, 2), xmm3, xmm0)
vfmadd231ps(mem(rcx, rax, 2), xmm3, xmm2)
vmovups(xmm0, mem(rcx, rsi, 2)) // store ( gamma02..gamma32 )
vmovups(xmm2, mem(rcx, rax, 2)) // store ( gamma06..gamma36 )
vextractf128(imm(0x1), ymm1, xmm2)
vfmadd231ps(mem(rcx, rax, 1), xmm3, xmm1)
vfmadd231ps(mem(rcx, rbp, 1), xmm3, xmm2)
vmovups(xmm1, mem(rcx, rax, 1)) // store ( gamma03..gamma33 )
vmovups(xmm2, mem(rcx, rbp, 1)) // store ( gamma07..gamma37 )
lea(mem(rcx, rsi, 8), rcx) // rcx += 8*cs_c
vmovups(ymm12, ymm0)
vextractf128(imm(0x1), ymm0, xmm8)
vpermilps(imm(0xe4), xmm0, xmm2)
vpermilps(imm(0x39), xmm0, xmm4)
vmovss(mem(rdx ), xmm1)
vmovss(mem(rdx, rsi, 1), xmm6)
vfmadd231ps(xmm1, xmm3, xmm2)
vfmadd231ps(xmm6, xmm3, xmm4)
vmovss(xmm2, mem(rdx )) // store ( gamma40 )
vmovss(xmm4, mem(rdx, rsi, 1)) // store ( gamma41 )
vpermilps(imm(0x4e), xmm0, xmm2)
vpermilps(imm(0x93), xmm0, xmm4)
vmovss(mem(rdx, rsi, 2), xmm1)
vmovss(mem(rdx, rax, 1), xmm6)
vfmadd231ps(xmm1, xmm3, xmm2)
vfmadd231ps(xmm6, xmm3, xmm4)
vmovss(xmm2, mem(rdx, rsi, 2)) // store ( gamma42 )
vmovss(xmm4, mem(rdx, rax, 1)) // store ( gamma43 )
vpermilps(imm(0xe4), xmm8, xmm2)
vpermilps(imm(0x39), xmm8, xmm4)
vmovss(mem(rdx, rsi, 4), xmm1)
vmovss(mem(rdx, rbx, 1), xmm6)
vfmadd231ps(xmm1, xmm3, xmm2)
vfmadd231ps(xmm6, xmm3, xmm4)
vmovss(xmm2, mem(rdx, rsi, 4)) // store ( gamma44 )
vmovss(xmm4, mem(rdx, rbx, 1)) // store ( gamma45 )
vpermilps(imm(0x4e), xmm8, xmm2)
vpermilps(imm(0x93), xmm8, xmm4)
vmovss(mem(rdx, rax, 2), xmm1)
vmovss(mem(rdx, rbp, 1), xmm6)
vfmadd231ps(xmm1, xmm3, xmm2)
vfmadd231ps(xmm6, xmm3, xmm4)
vmovss(xmm2, mem(rdx, rax, 2)) // store ( gamma46 )
vmovss(xmm4, mem(rdx, rbp, 1)) // store ( gamma47 )
lea(mem(rdx, rsi, 8), rdx) // rdx += 8*cs_c
// begin I/O on columns 8-11
vunpcklps(ymm7, ymm5, ymm0)
vunpcklps(ymm11, ymm9, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vfmadd231ps(mem(rcx ), xmm3, xmm0)
vmovups(xmm0, mem(rcx )) // store ( gamma00..gamma30 )
vfmadd231ps(mem(rcx, rsi, 1), xmm3, xmm1)
vmovups(xmm1, mem(rcx, rsi, 1)) // store ( gamma01..gamma31 )
vunpckhps(ymm7, ymm5, ymm0)
vunpckhps(ymm11, ymm9, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vfmadd231ps(mem(rcx, rsi, 2), xmm3, xmm0)
vmovups(xmm0, mem(rcx, rsi, 2)) // store ( gamma02..gamma32 )
vfmadd231ps(mem(rcx, rax, 1), xmm3, xmm1)
vmovups(xmm1, mem(rcx, rax, 1)) // store ( gamma03..gamma33 )
//lea(mem(rcx, rsi, 8), rcx) // rcx += 8*cs_c
vmovups(ymm13, ymm0)
vpermilps(imm(0xe4), xmm0, xmm2)
vpermilps(imm(0x39), xmm0, xmm4)
vmovss(mem(rdx ), xmm1)
vmovss(mem(rdx, rsi, 1), xmm6)
vfmadd231ps(xmm1, xmm3, xmm2)
vfmadd231ps(xmm6, xmm3, xmm4)
vmovss(xmm2, mem(rdx )) // store ( gamma40 )
vmovss(xmm4, mem(rdx, rsi, 1)) // store ( gamma41 )
vpermilps(imm(0x4e), xmm0, xmm2)
vpermilps(imm(0x93), xmm0, xmm4)
vmovss(mem(rdx, rsi, 2), xmm1)
vmovss(mem(rdx, rax, 1), xmm6)
vfmadd231ps(xmm1, xmm3, xmm2)
vfmadd231ps(xmm6, xmm3, xmm4)
vmovss(xmm2, mem(rdx, rsi, 2)) // store ( gamma42 )
vmovss(xmm4, mem(rdx, rax, 1)) // store ( gamma43 )
//lea(mem(rdx, rsi, 8), rdx) // rdx += 8*cs_c
jmp(.SDONE) // jump to end.
label(.SBETAZERO)
cmp(imm(4), rdi) // set ZF if (4*rs_c) == 4.
jz(.SCOLSTORBZ) // jump to column storage case
label(.SROWSTORBZ)
vmovups(ymm4, mem(rcx, 0*32))
vmovups(xmm5, mem(rcx, 1*32))
add(rdi, rcx)
vmovups(ymm6, mem(rcx, 0*32))
vmovups(xmm7, mem(rcx, 1*32))
add(rdi, rcx)
vmovups(ymm8, mem(rcx, 0*32))
vmovups(xmm9, mem(rcx, 1*32))
add(rdi, rcx)
vmovups(ymm10, mem(rcx, 0*32))
vmovups(xmm11, mem(rcx, 1*32))
add(rdi, rcx)
vmovups(ymm12, mem(rcx, 0*32))
vmovups(xmm13, mem(rcx, 1*32))
//add(rdi, rcx)
jmp(.SDONE) // jump to end.
label(.SCOLSTORBZ)
// begin I/O on columns 0-7
vunpcklps(ymm6, ymm4, ymm0)
vunpcklps(ymm10, ymm8, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vextractf128(imm(0x1), ymm0, xmm2)
vmovups(xmm0, mem(rcx )) // store ( gamma00..gamma30 )
vmovups(xmm2, mem(rcx, rsi, 4)) // store ( gamma04..gamma34 )
vextractf128(imm(0x1), ymm1, xmm2)
vmovups(xmm1, mem(rcx, rsi, 1)) // store ( gamma01..gamma31 )
vmovups(xmm2, mem(rcx, rbx, 1)) // store ( gamma05..gamma35 )
vunpckhps(ymm6, ymm4, ymm0)
vunpckhps(ymm10, ymm8, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vextractf128(imm(0x1), ymm0, xmm2)
vmovups(xmm0, mem(rcx, rsi, 2)) // store ( gamma02..gamma32 )
vmovups(xmm2, mem(rcx, rax, 2)) // store ( gamma06..gamma36 )
vextractf128(imm(0x1), ymm1, xmm2)
vmovups(xmm1, mem(rcx, rax, 1)) // store ( gamma03..gamma33 )
vmovups(xmm2, mem(rcx, rbp, 1)) // store ( gamma07..gamma37 )
lea(mem(rcx, rsi, 8), rcx) // rcx += 8*cs_c
vmovups(ymm12, ymm0)
vextractf128(imm(0x1), ymm0, xmm8)
vpermilps(imm(0xe4), xmm0, xmm2)
vpermilps(imm(0x39), xmm0, xmm4)
vmovss(xmm2, mem(rdx )) // store ( gamma40 )
vmovss(xmm4, mem(rdx, rsi, 1)) // store ( gamma41 )
vpermilps(imm(0x4e), xmm0, xmm2)
vpermilps(imm(0x93), xmm0, xmm4)
vmovss(xmm2, mem(rdx, rsi, 2)) // store ( gamma42 )
vmovss(xmm4, mem(rdx, rax, 1)) // store ( gamma43 )
vpermilps(imm(0xe4), xmm8, xmm2)
vpermilps(imm(0x39), xmm8, xmm4)
vmovss(xmm2, mem(rdx, rsi, 4)) // store ( gamma44 )
vmovss(xmm4, mem(rdx, rbx, 1)) // store ( gamma45 )
vpermilps(imm(0x4e), xmm8, xmm2)
vpermilps(imm(0x93), xmm8, xmm4)
vmovss(xmm2, mem(rdx, rax, 2)) // store ( gamma46 )
vmovss(xmm4, mem(rdx, rbp, 1)) // store ( gamma47 )
lea(mem(rdx, rsi, 8), rdx) // rdx += 8*cs_c
// begin I/O on columns 8-11
vunpcklps(ymm7, ymm5, ymm0)
vunpcklps(ymm11, ymm9, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vmovups(xmm0, mem(rcx )) // store ( gamma00..gamma30 )
vmovups(xmm1, mem(rcx, rsi, 1)) // store ( gamma01..gamma31 )
vunpckhps(ymm7, ymm5, ymm0)
vunpckhps(ymm11, ymm9, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vmovups(xmm0, mem(rcx, rsi, 2)) // store ( gamma02..gamma32 )
vmovups(xmm1, mem(rcx, rax, 1)) // store ( gamma03..gamma33 )
//lea(mem(rcx, rsi, 8), rcx) // rcx += 8*cs_c
vmovups(ymm13, ymm0)
vpermilps(imm(0xe4), xmm0, xmm2)
vpermilps(imm(0x39), xmm0, xmm4)
vmovss(xmm2, mem(rdx )) // store ( gamma40 )
vmovss(xmm4, mem(rdx, rsi, 1)) // store ( gamma41 )
vpermilps(imm(0x4e), xmm0, xmm2)
vpermilps(imm(0x93), xmm0, xmm4)
vmovss(xmm2, mem(rdx, rsi, 2)) // store ( gamma42 )
vmovss(xmm4, mem(rdx, rax, 1)) // store ( gamma43 )
//lea(mem(rdx, rsi, 8), rdx) // rdx += 8*cs_c
label(.SDONE)
end_asm(
: // output operands (none)
: // input operands
[k_iter] "m" (k_iter),
[k_left] "m" (k_left),
[a] "m" (a),
[rs_a] "m" (rs_a),
[cs_a] "m" (cs_a),
[b] "m" (b),
[rs_b] "m" (rs_b),
[cs_b] "m" (cs_b),
[alpha] "m" (alpha),
[beta] "m" (beta),
[c] "m" (c),
[rs_c] "m" (rs_c),
[cs_c] "m" (cs_c)/*,
[a_next] "m" (a_next),
[b_next] "m" (b_next)*/
: // register clobber list
"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "rbp",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
"xmm0", "xmm1", "xmm2", "xmm3",
"xmm4", "xmm5", "xmm6", "xmm7",
"xmm8", "xmm9", "xmm10", "xmm11",
"xmm12", "xmm13", "xmm14", "xmm15",
"memory"
)
}
void bli_sgemmsup_rv_haswell_asm_4x12
(
conj_t conja,
conj_t conjb,
dim_t m0,
dim_t n0,
dim_t k0,
float* restrict alpha,
float* restrict a, inc_t rs_a0, inc_t cs_a0,
float* restrict b, inc_t rs_b0, inc_t cs_b0,
float* restrict beta,
float* restrict c, inc_t rs_c0, inc_t cs_c0,
auxinfo_t* data,
cntx_t* cntx
)
{
//void* a_next = bli_auxinfo_next_a( data );
//void* b_next = bli_auxinfo_next_b( data );
// Typecast local copies of integers in case dim_t and inc_t are a
// different size than is expected by load instructions.
uint64_t k_iter = k0 / 4;
uint64_t k_left = k0 % 4;
uint64_t rs_a = rs_a0;
uint64_t cs_a = cs_a0;
uint64_t rs_b = rs_b0;
uint64_t cs_b = cs_b0;
uint64_t rs_c = rs_c0;
uint64_t cs_c = cs_c0;
// -------------------------------------------------------------------------
begin_asm()
vzeroall() // zero all xmm/ymm registers.
mov(var(a), rax) // load address of a.
mov(var(rs_a), r8) // load rs_a
mov(var(cs_a), r9) // load cs_a
lea(mem(, r8, 4), r8) // rs_a *= sizeof(float)
lea(mem(, r9, 4), r9) // cs_a *= sizeof(float)
lea(mem(r8, r8, 2), r13) // r13 = 3*rs_a
//lea(mem(r8, r8, 4), r15) // r15 = 5*rs_a
mov(var(b), rbx) // load address of b.
mov(var(rs_b), r10) // load rs_b
//mov(var(cs_b), r11) // load cs_b
lea(mem(, r10, 4), r10) // rs_b *= sizeof(float)
//lea(mem(, r11, 4), r11) // cs_b *= sizeof(float)
// NOTE: We cannot pre-load elements of a or b
// because it could eventually, in the last
// unrolled iter or the cleanup loop, result
// in reading beyond the bounds allocated mem
// (the likely result: a segmentation fault).
mov(var(c), rcx) // load address of c
mov(var(rs_c), rdi) // load rs_c
lea(mem(, rdi, 4), rdi) // rs_c *= sizeof(float)
cmp(imm(8), rdi) // set ZF if (8*rs_c) == 8.
jz(.SCOLPFETCH) // jump to column storage case
label(.SROWPFETCH) // row-stored prefetching on c
lea(mem(rcx, rdi, 2), rdx) //
lea(mem(rdx, rdi, 1), rdx) // rdx = c + 3*rs_c;
prefetch(0, mem(rcx, 7*8)) // prefetch c + 0*rs_c
prefetch(0, mem(rcx, rdi, 1, 7*8)) // prefetch c + 1*rs_c
prefetch(0, mem(rcx, rdi, 2, 7*8)) // prefetch c + 2*rs_c
prefetch(0, mem(rdx, 7*8)) // prefetch c + 3*rs_c
jmp(.SPOSTPFETCH) // jump to end of prefetching c
label(.SCOLPFETCH) // column-stored prefetching c
mov(var(cs_c), rsi) // load cs_c to rsi (temporarily)
lea(mem(, rsi, 4), rsi) // cs_c *= sizeof(float)
lea(mem(rsi, rsi, 2), rbp) // rbp = 3*cs_c;
prefetch(0, mem(rcx, 3*8)) // prefetch c + 0*cs_c
prefetch(0, mem(rcx, rsi, 1, 3*8)) // prefetch c + 1*cs_c
prefetch(0, mem(rcx, rsi, 2, 3*8)) // prefetch c + 2*cs_c
prefetch(0, mem(rcx, rbp, 1, 3*8)) // prefetch c + 3*cs_c
prefetch(0, mem(rcx, rsi, 4, 3*8)) // prefetch c + 4*cs_c
lea(mem(rcx, rsi, 4), rdx) // rdx = c + 4*cs_c;
prefetch(0, mem(rdx, rsi, 1, 3*8)) // prefetch c + 5*cs_c
prefetch(0, mem(rdx, rsi, 2, 3*8)) // prefetch c + 6*cs_c
prefetch(0, mem(rdx, rbp, 1, 3*8)) // prefetch c + 7*cs_c
prefetch(0, mem(rdx, rsi, 4, 3*8)) // prefetch c + 8*cs_c
lea(mem(rcx, rsi, 8), rdx) // rdx = c + 8*cs_c;
prefetch(0, mem(rdx, rsi, 1, 3*8)) // prefetch c + 9*cs_c
prefetch(0, mem(rdx, rsi, 2, 3*8)) // prefetch c + 10*cs_c
prefetch(0, mem(rdx, rbp, 1, 3*8)) // prefetch c + 11*cs_c
label(.SPOSTPFETCH) // done prefetching c
#if 1
lea(mem(rax, r9, 8), rdx) //
lea(mem(rdx, r9, 8), rdx) // rdx = a + 16*cs_a;
#endif
mov(var(k_iter), rsi) // i = k_iter;
test(rsi, rsi) // check i via logical AND.
je(.SCONSIDKLEFT) // if i == 0, jump to code that
// contains the k_left loop.
label(.SLOOPKITER) // MAIN LOOP
// ---------------------------------- iteration 0
#if 1
prefetch(0, mem(rdx, 4*8))
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
vbroadcastss(mem(rax, r8, 2), ymm2)
vbroadcastss(mem(rax, r13, 1), ymm3)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm8)
vfmadd231ps(ymm1, ymm2, ymm9)
vfmadd231ps(ymm0, ymm3, ymm10)
vfmadd231ps(ymm1, ymm3, ymm11)
// ---------------------------------- iteration 1
#if 0
prefetch(0, mem(rdx, r9, 1, 4*8))
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
vbroadcastss(mem(rax, r8, 2), ymm2)
vbroadcastss(mem(rax, r13, 1), ymm3)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm8)
vfmadd231ps(ymm1, ymm2, ymm9)
vfmadd231ps(ymm0, ymm3, ymm10)
vfmadd231ps(ymm1, ymm3, ymm11)
// ---------------------------------- iteration 2
#if 1
prefetch(0, mem(rdx, r9, 2, 4*8))
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
vbroadcastss(mem(rax, r8, 2), ymm2)
vbroadcastss(mem(rax, r13, 1), ymm3)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm8)
vfmadd231ps(ymm1, ymm2, ymm9)
vfmadd231ps(ymm0, ymm3, ymm10)
vfmadd231ps(ymm1, ymm3, ymm11)
// ---------------------------------- iteration 3
#if 1
lea(mem(rdx, r9, 4), rdx) // a_prefetch += 4*cs_a;
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
vbroadcastss(mem(rax, r8, 2), ymm2)
vbroadcastss(mem(rax, r13, 1), ymm3)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm8)
vfmadd231ps(ymm1, ymm2, ymm9)
vfmadd231ps(ymm0, ymm3, ymm10)
vfmadd231ps(ymm1, ymm3, ymm11)
dec(rsi) // i -= 1;
jne(.SLOOPKITER) // iterate again if i != 0.
label(.SCONSIDKLEFT)
mov(var(k_left), rsi) // i = k_left;
test(rsi, rsi) // check i via logical AND.
je(.SPOSTACCUM) // if i == 0, we're done; jump to end.
// else, we prepare to enter k_left loop.
label(.SLOOPKLEFT) // EDGE LOOP
#if 0
prefetch(0, mem(rdx, 5*8))
add(r9, rdx)
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
vbroadcastss(mem(rax, r8, 2), ymm2)
vbroadcastss(mem(rax, r13, 1), ymm3)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm8)
vfmadd231ps(ymm1, ymm2, ymm9)
vfmadd231ps(ymm0, ymm3, ymm10)
vfmadd231ps(ymm1, ymm3, ymm11)
dec(rsi) // i -= 1;
jne(.SLOOPKLEFT) // iterate again if i != 0.
label(.SPOSTACCUM)
mov(var(alpha), rax) // load address of alpha
mov(var(beta), rbx) // load address of beta
vbroadcastss(mem(rax), ymm0) // load alpha and duplicate
vbroadcastss(mem(rbx), ymm3) // load beta and duplicate
vmulps(ymm0, ymm4, ymm4) // scale by alpha
vmulps(xmm0, xmm5, xmm5)
vmulps(ymm0, ymm6, ymm6)
vmulps(xmm0, xmm7, xmm7)
vmulps(ymm0, ymm8, ymm8)
vmulps(xmm0, xmm9, xmm9)
vmulps(ymm0, ymm10, ymm10)
vmulps(xmm0, xmm11, xmm11)
mov(var(cs_c), rsi) // load cs_c
lea(mem(, rsi, 4), rsi) // rsi = cs_c * sizeof(float)
//lea(mem(rcx, rsi, 4), rdx) // load address of c + 4*cs_c;
//lea(mem(rcx, rdi, 4), rdx) // load address of c + 4*rs_c;
lea(mem(rsi, rsi, 2), rax) // rax = 3*cs_c;
lea(mem(rsi, rsi, 4), rbx) // rbx = 5*cs_c;
lea(mem(rax, rsi, 4), rbp) // rbp = 7*cs_c;
// now avoid loading C if beta == 0
vxorps(ymm0, ymm0, ymm0) // set ymm0 to zero.
vucomiss(xmm0, xmm3) // set ZF if beta == 0.
je(.SBETAZERO) // if ZF = 1, jump to beta == 0 case
cmp(imm(4), rdi) // set ZF if (4*rs_c) == 4.
jz(.SCOLSTORED) // jump to column storage case
label(.SROWSTORED)
vfmadd231ps(mem(rcx, 0*32), ymm3, ymm4)
vmovups(ymm4, mem(rcx, 0*32))
vfmadd231ps(mem(rcx, 1*32), xmm3, xmm5)
vmovups(xmm5, mem(rcx, 1*32))
add(rdi, rcx)
vfmadd231ps(mem(rcx, 0*32), ymm3, ymm6)
vmovups(ymm6, mem(rcx, 0*32))
vfmadd231ps(mem(rcx, 1*32), xmm3, xmm7)
vmovups(xmm7, mem(rcx, 1*32))
add(rdi, rcx)
vfmadd231ps(mem(rcx, 0*32), ymm3, ymm8)
vmovups(ymm8, mem(rcx, 0*32))
vfmadd231ps(mem(rcx, 1*32), xmm3, xmm9)
vmovups(xmm9, mem(rcx, 1*32))
add(rdi, rcx)
vfmadd231ps(mem(rcx, 0*32), ymm3, ymm10)
vmovups(ymm10, mem(rcx, 0*32))
vfmadd231ps(mem(rcx, 1*32), xmm3, xmm11)
vmovups(xmm11, mem(rcx, 1*32))
//add(rdi, rcx)
jmp(.SDONE) // jump to end.
label(.SCOLSTORED)
// begin I/O on columns 0-7
vunpcklps(ymm6, ymm4, ymm0)
vunpcklps(ymm10, ymm8, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vextractf128(imm(0x1), ymm0, xmm2)
vfmadd231ps(mem(rcx ), xmm3, xmm0)
vfmadd231ps(mem(rcx, rsi, 4), xmm3, xmm2)
vmovups(xmm0, mem(rcx )) // store ( gamma00..gamma30 )
vmovups(xmm2, mem(rcx, rsi, 4)) // store ( gamma04..gamma34 )
vextractf128(imm(0x1), ymm1, xmm2)
vfmadd231ps(mem(rcx, rsi, 1), xmm3, xmm1)
vfmadd231ps(mem(rcx, rbx, 1), xmm3, xmm2)
vmovups(xmm1, mem(rcx, rsi, 1)) // store ( gamma01..gamma31 )
vmovups(xmm2, mem(rcx, rbx, 1)) // store ( gamma05..gamma35 )
vunpckhps(ymm6, ymm4, ymm0)
vunpckhps(ymm10, ymm8, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vextractf128(imm(0x1), ymm0, xmm2)
vfmadd231ps(mem(rcx, rsi, 2), xmm3, xmm0)
vfmadd231ps(mem(rcx, rax, 2), xmm3, xmm2)
vmovups(xmm0, mem(rcx, rsi, 2)) // store ( gamma02..gamma32 )
vmovups(xmm2, mem(rcx, rax, 2)) // store ( gamma06..gamma36 )
vextractf128(imm(0x1), ymm1, xmm2)
vfmadd231ps(mem(rcx, rax, 1), xmm3, xmm1)
vfmadd231ps(mem(rcx, rbp, 1), xmm3, xmm2)
vmovups(xmm1, mem(rcx, rax, 1)) // store ( gamma03..gamma33 )
vmovups(xmm2, mem(rcx, rbp, 1)) // store ( gamma07..gamma37 )
lea(mem(rcx, rsi, 8), rcx) // rcx += 8*cs_c
// begin I/O on columns 8-11
vunpcklps(ymm7, ymm5, ymm0)
vunpcklps(ymm11, ymm9, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vfmadd231ps(mem(rcx ), xmm3, xmm0)
vmovups(xmm0, mem(rcx )) // store ( gamma00..gamma30 )
vfmadd231ps(mem(rcx, rsi, 1), xmm3, xmm1)
vmovups(xmm1, mem(rcx, rsi, 1)) // store ( gamma01..gamma31 )
vunpckhps(ymm7, ymm5, ymm0)
vunpckhps(ymm11, ymm9, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vfmadd231ps(mem(rcx, rsi, 2), xmm3, xmm0)
vmovups(xmm0, mem(rcx, rsi, 2)) // store ( gamma02..gamma32 )
vfmadd231ps(mem(rcx, rax, 1), xmm3, xmm1)
vmovups(xmm1, mem(rcx, rax, 1)) // store ( gamma03..gamma33 )
//lea(mem(rcx, rsi, 8), rcx) // rcx += 8*cs_c
jmp(.SDONE) // jump to end.
label(.SBETAZERO)
cmp(imm(4), rdi) // set ZF if (8*rs_c) == 8.
jz(.SCOLSTORBZ) // jump to column storage case
label(.SROWSTORBZ)
vmovups(ymm4, mem(rcx, 0*32))
vmovups(xmm5, mem(rcx, 1*32))
add(rdi, rcx)
vmovups(ymm6, mem(rcx, 0*32))
vmovups(xmm7, mem(rcx, 1*32))
add(rdi, rcx)
vmovups(ymm8, mem(rcx, 0*32))
vmovups(xmm9, mem(rcx, 1*32))
add(rdi, rcx)
vmovups(ymm10, mem(rcx, 0*32))
vmovups(xmm11, mem(rcx, 1*32))
//add(rdi, rcx)
jmp(.SDONE) // jump to end.
label(.SCOLSTORBZ)
// begin I/O on columns 0-7
vunpcklps(ymm6, ymm4, ymm0)
vunpcklps(ymm10, ymm8, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vextractf128(imm(0x1), ymm0, xmm2)
vmovups(xmm0, mem(rcx )) // store ( gamma00..gamma30 )
vmovups(xmm2, mem(rcx, rsi, 4)) // store ( gamma04..gamma34 )
vextractf128(imm(0x1), ymm1, xmm2)
vmovups(xmm1, mem(rcx, rsi, 1)) // store ( gamma01..gamma31 )
vmovups(xmm2, mem(rcx, rbx, 1)) // store ( gamma05..gamma35 )
vunpckhps(ymm6, ymm4, ymm0)
vunpckhps(ymm10, ymm8, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vextractf128(imm(0x1), ymm0, xmm2)
vmovups(xmm0, mem(rcx, rsi, 2)) // store ( gamma02..gamma32 )
vmovups(xmm2, mem(rcx, rax, 2)) // store ( gamma06..gamma36 )
vextractf128(imm(0x1), ymm1, xmm2)
vmovups(xmm1, mem(rcx, rax, 1)) // store ( gamma03..gamma33 )
vmovups(xmm2, mem(rcx, rbp, 1)) // store ( gamma07..gamma37 )
lea(mem(rcx, rsi, 8), rcx) // rcx += 8*cs_c
// begin I/O on columns 8-11
vunpcklps(ymm7, ymm5, ymm0)
vunpcklps(ymm11, ymm9, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vmovups(xmm0, mem(rcx )) // store ( gamma00..gamma30 )
vmovups(xmm1, mem(rcx, rsi, 1)) // store ( gamma01..gamma31 )
vunpckhps(ymm7, ymm5, ymm0)
vunpckhps(ymm11, ymm9, ymm1)
vshufps(imm(0x4e), ymm1, ymm0, ymm2)
vblendps(imm(0xcc), ymm2, ymm0, ymm0)
vblendps(imm(0x33), ymm2, ymm1, ymm1)
vmovups(xmm0, mem(rcx, rsi, 2)) // store ( gamma02..gamma32 )
vmovups(xmm1, mem(rcx, rax, 1)) // store ( gamma03..gamma33 )
//lea(mem(rcx, rsi, 4), rcx)
label(.SDONE)
end_asm(
: // output operands (none)
: // input operands
[k_iter] "m" (k_iter),
[k_left] "m" (k_left),
[a] "m" (a),
[rs_a] "m" (rs_a),
[cs_a] "m" (cs_a),
[b] "m" (b),
[rs_b] "m" (rs_b),
[cs_b] "m" (cs_b),
[alpha] "m" (alpha),
[beta] "m" (beta),
[c] "m" (c),
[rs_c] "m" (rs_c),
[cs_c] "m" (cs_c)/*,
[a_next] "m" (a_next),
[b_next] "m" (b_next)*/
: // register clobber list
"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "rbp",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
"xmm0", "xmm1", "xmm2", "xmm3",
"xmm4", "xmm5", "xmm6", "xmm7",
"xmm8", "xmm9", "xmm10", "xmm11",
"xmm12", "xmm13", "xmm14", "xmm15",
"memory"
)
}
void bli_sgemmsup_rv_haswell_asm_3x12
(
conj_t conja,
conj_t conjb,
dim_t m0,
dim_t n0,
dim_t k0,
float* restrict alpha,
float* restrict a, inc_t rs_a0, inc_t cs_a0,
float* restrict b, inc_t rs_b0, inc_t cs_b0,
float* restrict beta,
float* restrict c, inc_t rs_c0, inc_t cs_c0,
auxinfo_t* data,
cntx_t* cntx
)
{
//void* a_next = bli_auxinfo_next_a( data );
//void* b_next = bli_auxinfo_next_b( data );
// Typecast local copies of integers in case dim_t and inc_t are a
// different size than is expected by load instructions.
uint64_t k_iter = k0 / 4;
uint64_t k_left = k0 % 4;
uint64_t rs_a = rs_a0;
uint64_t cs_a = cs_a0;
uint64_t rs_b = rs_b0;
uint64_t cs_b = cs_b0;
uint64_t rs_c = rs_c0;
uint64_t cs_c = cs_c0;
// -------------------------------------------------------------------------
begin_asm()
vzeroall() // zero all xmm/ymm registers.
mov(var(a), rax) // load address of a.
mov(var(rs_a), r8) // load rs_a
mov(var(cs_a), r9) // load cs_a
lea(mem(, r8, 4), r8) // rs_a *= sizeof(float)
lea(mem(, r9, 4), r9) // cs_a *= sizeof(float)
//lea(mem(r8, r8, 2), r13) // r13 = 3*rs_a
//lea(mem(r8, r8, 4), r15) // r15 = 5*rs_a
mov(var(b), rbx) // load address of b.
mov(var(rs_b), r10) // load rs_b
//mov(var(cs_b), r11) // load cs_b
lea(mem(, r10, 4), r10) // rs_b *= sizeof(float)
//lea(mem(, r11, 4), r11) // cs_b *= sizeof(float)
// NOTE: We cannot pre-load elements of a or b
// because it could eventually, in the last
// unrolled iter or the cleanup loop, result
// in reading beyond the bounds allocated mem
// (the likely result: a segmentation fault).
mov(var(c), rcx) // load address of c
mov(var(rs_c), rdi) // load rs_c
lea(mem(, rdi, 4), rdi) // rs_c *= sizeof(float)
cmp(imm(8), rdi) // set ZF if (8*rs_c) == 8.
jz(.SCOLPFETCH) // jump to column storage case
label(.SROWPFETCH) // row-stored prefetching on c
//lea(mem(rcx, rdi, 2), rdx) //
//lea(mem(rdx, rdi, 1), rdx) // rdx = c + 3*rs_c;
prefetch(0, mem(rcx, 7*8)) // prefetch c + 0*rs_c
prefetch(0, mem(rcx, rdi, 1, 7*8)) // prefetch c + 1*rs_c
prefetch(0, mem(rcx, rdi, 2, 7*8)) // prefetch c + 2*rs_c
jmp(.SPOSTPFETCH) // jump to end of prefetching c
label(.SCOLPFETCH) // column-stored prefetching c
mov(var(cs_c), rsi) // load cs_c to rsi (temporarily)
lea(mem(, rsi, 4), rsi) // cs_c *= sizeof(float)
lea(mem(rsi, rsi, 2), rbp) // rbp = 3*cs_c;
prefetch(0, mem(rcx, 2*8)) // prefetch c + 0*cs_c
prefetch(0, mem(rcx, rsi, 1, 2*8)) // prefetch c + 1*cs_c
prefetch(0, mem(rcx, rsi, 2, 2*8)) // prefetch c + 2*cs_c
prefetch(0, mem(rcx, rbp, 1, 2*8)) // prefetch c + 3*cs_c
prefetch(0, mem(rcx, rsi, 4, 2*8)) // prefetch c + 4*cs_c
lea(mem(rcx, rsi, 4), rdx) // rdx = c + 4*cs_c;
prefetch(0, mem(rdx, rsi, 1, 2*8)) // prefetch c + 5*cs_c
prefetch(0, mem(rdx, rsi, 2, 2*8)) // prefetch c + 6*cs_c
prefetch(0, mem(rdx, rbp, 1, 2*8)) // prefetch c + 7*cs_c
prefetch(0, mem(rdx, rsi, 4, 2*8)) // prefetch c + 8*cs_c
lea(mem(rcx, rsi, 8), rdx) // rdx = c + 8*cs_c;
prefetch(0, mem(rdx, rsi, 1, 2*8)) // prefetch c + 9*cs_c
prefetch(0, mem(rdx, rsi, 2, 2*8)) // prefetch c + 10*cs_c
prefetch(0, mem(rdx, rbp, 1, 2*8)) // prefetch c + 11*cs_c
label(.SPOSTPFETCH) // done prefetching c
#if 1
lea(mem(rax, r9, 8), rdx) //
lea(mem(rdx, r9, 8), rdx) // rdx = a + 16*cs_a;
#endif
mov(var(k_iter), rsi) // i = k_iter;
test(rsi, rsi) // check i via logical AND.
je(.SCONSIDKLEFT) // if i == 0, jump to code that
// contains the k_left loop.
label(.SLOOPKITER) // MAIN LOOP
// ---------------------------------- iteration 0
#if 1
prefetch(0, mem(rdx, 4*8))
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
vbroadcastss(mem(rax, r8, 2), ymm2)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm8)
vfmadd231ps(ymm1, ymm2, ymm9)
// ---------------------------------- iteration 1
#if 0
prefetch(0, mem(rdx, r9, 1, 4*8))
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
vbroadcastss(mem(rax, r8, 2), ymm2)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm8)
vfmadd231ps(ymm1, ymm2, ymm9)
// ---------------------------------- iteration 2
#if 1
prefetch(0, mem(rdx, r9, 2, 4*8))
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
vbroadcastss(mem(rax, r8, 2), ymm2)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm8)
vfmadd231ps(ymm1, ymm2, ymm9)
// ---------------------------------- iteration 3
#if 1
lea(mem(rdx, r9, 4), rdx) // a_prefetch += 4*cs_a;
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
vbroadcastss(mem(rax, r8, 2), ymm2)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm8)
vfmadd231ps(ymm1, ymm2, ymm9)
dec(rsi) // i -= 1;
jne(.SLOOPKITER) // iterate again if i != 0.
label(.SCONSIDKLEFT)
mov(var(k_left), rsi) // i = k_left;
test(rsi, rsi) // check i via logical AND.
je(.SPOSTACCUM) // if i == 0, we're done; jump to end.
// else, we prepare to enter k_left loop.
label(.SLOOPKLEFT) // EDGE LOOP
#if 0
prefetch(0, mem(rdx, 5*8))
add(r9, rdx)
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
vbroadcastss(mem(rax, r8, 2), ymm2)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm8)
vfmadd231ps(ymm1, ymm2, ymm9)
dec(rsi) // i -= 1;
jne(.SLOOPKLEFT) // iterate again if i != 0.
label(.SPOSTACCUM)
mov(var(alpha), rax) // load address of alpha
mov(var(beta), rbx) // load address of beta
vbroadcastss(mem(rax), ymm0) // load alpha and duplicate
vbroadcastss(mem(rbx), ymm3) // load beta and duplicate
vmulps(ymm0, ymm4, ymm4) // scale by alpha
vmulps(xmm0, xmm5, xmm5)
vmulps(ymm0, ymm6, ymm6)
vmulps(xmm0, xmm7, xmm7)
vmulps(ymm0, ymm8, ymm8)
vmulps(xmm0, xmm9, xmm9)
mov(var(cs_c), rsi) // load cs_c
lea(mem(, rsi, 4), rsi) // rsi = cs_c * sizeof(float)
//lea(mem(rcx, rsi, 4), rdx) // load address of c + 4*cs_c;
lea(mem(rcx, rdi, 2), rdx) // load address of c + 2*rs_c;
lea(mem(rsi, rsi, 2), rax) // rax = 3*cs_c;
lea(mem(rsi, rsi, 4), rbx) // rbx = 5*cs_c;
lea(mem(rax, rsi, 4), rbp) // rbp = 7*cs_c;
// now avoid loading C if beta == 0
vxorps(ymm0, ymm0, ymm0) // set ymm0 to zero.
vucomiss(xmm0, xmm3) // set ZF if beta == 0.
je(.SBETAZERO) // if ZF = 1, jump to beta == 0 case
cmp(imm(4), rdi) // set ZF if (4*rs_c) == 4.
jz(.SCOLSTORED) // jump to column storage case
label(.SROWSTORED)
vfmadd231ps(mem(rcx, 0*32), ymm3, ymm4)
vmovups(ymm4, mem(rcx, 0*32))
vfmadd231ps(mem(rcx, 1*32), xmm3, xmm5)
vmovups(xmm5, mem(rcx, 1*32))
add(rdi, rcx)
vfmadd231ps(mem(rcx, 0*32), ymm3, ymm6)
vmovups(ymm6, mem(rcx, 0*32))
vfmadd231ps(mem(rcx, 1*32), xmm3, xmm7)
vmovups(xmm7, mem(rcx, 1*32))
add(rdi, rcx)
vfmadd231ps(mem(rcx, 0*32), ymm3, ymm8)
vmovups(ymm8, mem(rcx, 0*32))
vfmadd231ps(mem(rcx, 1*32), xmm3, xmm9)
vmovups(xmm9, mem(rcx, 1*32))
//add(rdi, rcx)
jmp(.SDONE) // jump to end.
label(.SCOLSTORED)
// begin I/O on columns 0-7
vunpcklps(ymm6, ymm4, ymm0)
vextractf128(imm(0x1), ymm0, xmm2)
vmovlpd(mem(rcx ), xmm1, xmm1)
vmovhpd(mem(rcx, rsi, 1), xmm1, xmm1)
vfmadd231ps(xmm1, xmm3, xmm0)
vmovlpd(xmm0, mem(rcx )) // store ( gamma00..gamma10 )
vmovhpd(xmm0, mem(rcx, rsi, 1)) // store ( gamma01..gamma11 )
vmovlpd(mem(rcx, rsi, 4), xmm1, xmm1)
vmovhpd(mem(rcx, rbx, 1), xmm1, xmm1)
vfmadd231ps(xmm1, xmm3, xmm2)
vmovlpd(xmm2, mem(rcx, rsi, 4)) // store ( gamma04..gamma14 )
vmovhpd(xmm2, mem(rcx, rbx, 1)) // store ( gamma05..gamma15 )
vunpckhps(ymm6, ymm4, ymm0)
vextractf128(imm(0x1), ymm0, xmm2)
vmovlpd(mem(rcx, rsi, 2), xmm1, xmm1)
vmovhpd(mem(rcx, rax, 1), xmm1, xmm1)
vfmadd231ps(xmm1, xmm3, xmm0)
vmovlpd(xmm0, mem(rcx, rsi, 2)) // store ( gamma02..gamma12 )
vmovhpd(xmm0, mem(rcx, rax, 1)) // store ( gamma03..gamma13 )
vmovlpd(mem(rcx, rax, 2), xmm1, xmm1)
vmovhpd(mem(rcx, rbp, 1), xmm1, xmm1)
vfmadd231ps(xmm1, xmm3, xmm2)
vmovlpd(xmm2, mem(rcx, rax, 2)) // store ( gamma06..gamma16 )
vmovhpd(xmm2, mem(rcx, rbp, 1)) // store ( gamma07..gamma17 )
lea(mem(rcx, rsi, 8), rcx) // rcx += 8*cs_c
vmovups(ymm8, ymm0)
vextractf128(imm(0x1), ymm0, xmm8)
vpermilps(imm(0xe4), xmm0, xmm2)
vpermilps(imm(0x39), xmm0, xmm4)
vmovss(mem(rdx ), xmm1)
vmovss(mem(rdx, rsi, 1), xmm6)
vfmadd231ps(xmm1, xmm3, xmm2)
vfmadd231ps(xmm6, xmm3, xmm4)
vmovss(xmm2, mem(rdx )) // store ( gamma40 )
vmovss(xmm4, mem(rdx, rsi, 1)) // store ( gamma41 )
vpermilps(imm(0x4e), xmm0, xmm2)
vpermilps(imm(0x93), xmm0, xmm4)
vmovss(mem(rdx, rsi, 2), xmm1)
vmovss(mem(rdx, rax, 1), xmm6)
vfmadd231ps(xmm1, xmm3, xmm2)
vfmadd231ps(xmm6, xmm3, xmm4)
vmovss(xmm2, mem(rdx, rsi, 2)) // store ( gamma42 )
vmovss(xmm4, mem(rdx, rax, 1)) // store ( gamma43 )
vpermilps(imm(0xe4), xmm8, xmm2)
vpermilps(imm(0x39), xmm8, xmm4)
vmovss(mem(rdx, rsi, 4), xmm1)
vmovss(mem(rdx, rbx, 1), xmm6)
vfmadd231ps(xmm1, xmm3, xmm2)
vfmadd231ps(xmm6, xmm3, xmm4)
vmovss(xmm2, mem(rdx, rsi, 4)) // store ( gamma44 )
vmovss(xmm4, mem(rdx, rbx, 1)) // store ( gamma45 )
vpermilps(imm(0x4e), xmm8, xmm2)
vpermilps(imm(0x93), xmm8, xmm4)
vmovss(mem(rdx, rax, 2), xmm1)
vmovss(mem(rdx, rbp, 1), xmm6)
vfmadd231ps(xmm1, xmm3, xmm2)
vfmadd231ps(xmm6, xmm3, xmm4)
vmovss(xmm2, mem(rdx, rax, 2)) // store ( gamma46 )
vmovss(xmm4, mem(rdx, rbp, 1)) // store ( gamma47 )
lea(mem(rdx, rsi, 8), rdx) // rdx += 8*cs_c
// begin I/O on columns 8-11
vunpcklps(ymm7, ymm5, ymm0)
vmovlpd(mem(rcx ), xmm1, xmm1)
vmovhpd(mem(rcx, rsi, 1), xmm1, xmm1)
vfmadd231ps(xmm1, xmm3, xmm0)
vmovlpd(xmm0, mem(rcx )) // store ( gamma00..gamma10 )
vmovhpd(xmm0, mem(rcx, rsi, 1)) // store ( gamma01..gamma11 )
vunpckhps(ymm7, ymm5, ymm0)
vmovlpd(mem(rcx, rsi, 2), xmm1, xmm1)
vmovhpd(mem(rcx, rax, 1), xmm1, xmm1)
vfmadd231ps(xmm1, xmm3, xmm0)
vmovlpd(xmm0, mem(rcx, rsi, 2)) // store ( gamma02..gamma12 )
vmovhpd(xmm0, mem(rcx, rax, 1)) // store ( gamma03..gamma13 )
//lea(mem(rcx, rsi, 8), rcx) // rcx += 8*cs_c
vmovups(ymm9, ymm0)
vpermilps(imm(0xe4), xmm0, xmm2)
vpermilps(imm(0x39), xmm0, xmm4)
vmovss(mem(rdx ), xmm1)
vmovss(mem(rdx, rsi, 1), xmm6)
vfmadd231ps(xmm1, xmm3, xmm2)
vfmadd231ps(xmm6, xmm3, xmm4)
vmovss(xmm2, mem(rdx )) // store ( gamma40 )
vmovss(xmm4, mem(rdx, rsi, 1)) // store ( gamma41 )
vpermilps(imm(0x4e), xmm0, xmm2)
vpermilps(imm(0x93), xmm0, xmm4)
vmovss(mem(rdx, rsi, 2), xmm1)
vmovss(mem(rdx, rax, 1), xmm6)
vfmadd231ps(xmm1, xmm3, xmm2)
vfmadd231ps(xmm6, xmm3, xmm4)
vmovss(xmm2, mem(rdx, rsi, 2)) // store ( gamma42 )
vmovss(xmm4, mem(rdx, rax, 1)) // store ( gamma43 )
//lea(mem(rdx, rsi, 8), rdx) // rdx += 8*cs_c
jmp(.SDONE) // jump to end.
label(.SBETAZERO)
cmp(imm(4), rdi) // set ZF if (8*rs_c) == 8.
jz(.SCOLSTORBZ) // jump to column storage case
label(.SROWSTORBZ)
vmovups(ymm4, mem(rcx, 0*32))
vmovups(xmm5, mem(rcx, 1*32))
add(rdi, rcx)
vmovups(ymm6, mem(rcx, 0*32))
vmovups(xmm7, mem(rcx, 1*32))
add(rdi, rcx)
vmovups(ymm8, mem(rcx, 0*32))
vmovups(xmm9, mem(rcx, 1*32))
//add(rdi, rcx)
jmp(.SDONE) // jump to end.
label(.SCOLSTORBZ)
// begin I/O on columns 0-7
vunpcklps(ymm6, ymm4, ymm0)
vextractf128(imm(0x1), ymm0, xmm2)
vmovlpd(xmm0, mem(rcx )) // store ( gamma00..gamma10 )
vmovhpd(xmm0, mem(rcx, rsi, 1)) // store ( gamma01..gamma11 )
vmovlpd(xmm2, mem(rcx, rsi, 4)) // store ( gamma04..gamma14 )
vmovhpd(xmm2, mem(rcx, rbx, 1)) // store ( gamma05..gamma15 )
vunpckhps(ymm6, ymm4, ymm0)
vextractf128(imm(0x1), ymm0, xmm2)
vmovlpd(xmm0, mem(rcx, rsi, 2)) // store ( gamma02..gamma12 )
vmovhpd(xmm0, mem(rcx, rax, 1)) // store ( gamma03..gamma13 )
vmovlpd(xmm2, mem(rcx, rax, 2)) // store ( gamma06..gamma16 )
vmovhpd(xmm2, mem(rcx, rbp, 1)) // store ( gamma07..gamma17 )
lea(mem(rcx, rsi, 8), rcx) // rcx += 8*cs_c
vmovups(ymm8, ymm0)
vextractf128(imm(0x1), ymm0, xmm8)
vpermilps(imm(0xe4), xmm0, xmm2)
vpermilps(imm(0x39), xmm0, xmm4)
vmovss(xmm2, mem(rdx )) // store ( gamma40 )
vmovss(xmm4, mem(rdx, rsi, 1)) // store ( gamma41 )
vpermilps(imm(0x4e), xmm0, xmm2)
vpermilps(imm(0x93), xmm0, xmm4)
vmovss(xmm2, mem(rdx, rsi, 2)) // store ( gamma42 )
vmovss(xmm4, mem(rdx, rax, 1)) // store ( gamma43 )
vpermilps(imm(0xe4), xmm8, xmm2)
vpermilps(imm(0x39), xmm8, xmm4)
vmovss(xmm2, mem(rdx, rsi, 4)) // store ( gamma44 )
vmovss(xmm4, mem(rdx, rbx, 1)) // store ( gamma45 )
vpermilps(imm(0x4e), xmm8, xmm2)
vpermilps(imm(0x93), xmm8, xmm4)
vmovss(xmm2, mem(rdx, rax, 2)) // store ( gamma46 )
vmovss(xmm4, mem(rdx, rbp, 1)) // store ( gamma47 )
lea(mem(rdx, rsi, 8), rdx) // rdx += 8*cs_c
// begin I/O on columns 8-11
vunpcklps(ymm7, ymm5, ymm0)
vmovlpd(xmm0, mem(rcx )) // store ( gamma00..gamma10 )
vmovhpd(xmm0, mem(rcx, rsi, 1)) // store ( gamma01..gamma11 )
vunpckhps(ymm7, ymm5, ymm0)
vmovlpd(xmm0, mem(rcx, rsi, 2)) // store ( gamma02..gamma12 )
vmovhpd(xmm0, mem(rcx, rax, 1)) // store ( gamma03..gamma13 )
//lea(mem(rcx, rsi, 8), rcx) // rcx += 8*cs_c
vmovups(ymm9, ymm0)
vpermilps(imm(0xe4), xmm0, xmm2)
vpermilps(imm(0x39), xmm0, xmm4)
vmovss(xmm2, mem(rdx )) // store ( gamma40 )
vmovss(xmm4, mem(rdx, rsi, 1)) // store ( gamma41 )
vpermilps(imm(0x4e), xmm0, xmm2)
vpermilps(imm(0x93), xmm0, xmm4)
vmovss(xmm2, mem(rdx, rsi, 2)) // store ( gamma42 )
vmovss(xmm4, mem(rdx, rax, 1)) // store ( gamma43 )
//lea(mem(rcx, rsi, 4), rcx)
label(.SDONE)
end_asm(
: // output operands (none)
: // input operands
[k_iter] "m" (k_iter),
[k_left] "m" (k_left),
[a] "m" (a),
[rs_a] "m" (rs_a),
[cs_a] "m" (cs_a),
[b] "m" (b),
[rs_b] "m" (rs_b),
[cs_b] "m" (cs_b),
[alpha] "m" (alpha),
[beta] "m" (beta),
[c] "m" (c),
[rs_c] "m" (rs_c),
[cs_c] "m" (cs_c)/*,
[a_next] "m" (a_next),
[b_next] "m" (b_next)*/
: // register clobber list
"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "rbp",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
"xmm0", "xmm1", "xmm2", "xmm3",
"xmm4", "xmm5", "xmm6", "xmm7",
"xmm8", "xmm9", "xmm10", "xmm11",
"xmm12", "xmm13", "xmm14", "xmm15",
"memory"
)
}
void bli_sgemmsup_rv_haswell_asm_2x12
(
conj_t conja,
conj_t conjb,
dim_t m0,
dim_t n0,
dim_t k0,
float* restrict alpha,
float* restrict a, inc_t rs_a0, inc_t cs_a0,
float* restrict b, inc_t rs_b0, inc_t cs_b0,
float* restrict beta,
float* restrict c, inc_t rs_c0, inc_t cs_c0,
auxinfo_t* data,
cntx_t* cntx
)
{
//void* a_next = bli_auxinfo_next_a( data );
//void* b_next = bli_auxinfo_next_b( data );
// Typecast local copies of integers in case dim_t and inc_t are a
// different size than is expected by load instructions.
uint64_t k_iter = k0 / 4;
uint64_t k_left = k0 % 4;
uint64_t rs_a = rs_a0;
uint64_t cs_a = cs_a0;
uint64_t rs_b = rs_b0;
uint64_t cs_b = cs_b0;
uint64_t rs_c = rs_c0;
uint64_t cs_c = cs_c0;
// -------------------------------------------------------------------------
begin_asm()
vzeroall() // zero all xmm/ymm registers.
mov(var(a), rax) // load address of a.
mov(var(rs_a), r8) // load rs_a
mov(var(cs_a), r9) // load cs_a
lea(mem(, r8, 4), r8) // rs_a *= sizeof(float)
lea(mem(, r9, 4), r9) // cs_a *= sizeof(float)
//lea(mem(r8, r8, 2), r13) // r13 = 3*rs_a
//lea(mem(r8, r8, 4), r15) // r15 = 5*rs_a
mov(var(b), rbx) // load address of b.
mov(var(rs_b), r10) // load rs_b
//mov(var(cs_b), r11) // load cs_b
lea(mem(, r10, 4), r10) // rs_b *= sizeof(float)
//lea(mem(, r11, 4), r11) // cs_b *= sizeof(float)
// NOTE: We cannot pre-load elements of a or b
// because it could eventually, in the last
// unrolled iter or the cleanup loop, result
// in reading beyond the bounds allocated mem
// (the likely result: a segmentation fault).
mov(var(c), rcx) // load address of c
mov(var(rs_c), rdi) // load rs_c
lea(mem(, rdi, 4), rdi) // rs_c *= sizeof(float)
cmp(imm(8), rdi) // set ZF if (8*rs_c) == 8.
jz(.SCOLPFETCH) // jump to column storage case
label(.SROWPFETCH) // row-stored prefetching on c
//lea(mem(rcx, rdi, 2), rdx) //
//lea(mem(rdx, rdi, 1), rdx) // rdx = c + 3*rs_c;
prefetch(0, mem(rcx, 7*8)) // prefetch c + 0*rs_c
prefetch(0, mem(rcx, rdi, 1, 7*8)) // prefetch c + 1*rs_c
jmp(.SPOSTPFETCH) // jump to end of prefetching c
label(.SCOLPFETCH) // column-stored prefetching c
mov(var(cs_c), rsi) // load cs_c to rsi (temporarily)
lea(mem(, rsi, 4), rsi) // cs_c *= sizeof(float)
lea(mem(rsi, rsi, 2), rbp) // rbp = 3*cs_c;
prefetch(0, mem(rcx, 1*8)) // prefetch c + 0*cs_c
prefetch(0, mem(rcx, rsi, 1, 1*8)) // prefetch c + 1*cs_c
prefetch(0, mem(rcx, rsi, 2, 1*8)) // prefetch c + 2*cs_c
prefetch(0, mem(rcx, rbp, 1, 1*8)) // prefetch c + 3*cs_c
prefetch(0, mem(rcx, rsi, 4, 1*8)) // prefetch c + 4*cs_c
lea(mem(rcx, rsi, 4), rdx) // rdx = c + 4*cs_c;
prefetch(0, mem(rdx, rsi, 1, 1*8)) // prefetch c + 5*cs_c
prefetch(0, mem(rdx, rsi, 2, 1*8)) // prefetch c + 6*cs_c
prefetch(0, mem(rdx, rbp, 1, 1*8)) // prefetch c + 7*cs_c
prefetch(0, mem(rdx, rsi, 4, 1*8)) // prefetch c + 8*cs_c
lea(mem(rcx, rsi, 8), rdx) // rdx = c + 8*cs_c;
prefetch(0, mem(rdx, rsi, 1, 1*8)) // prefetch c + 9*cs_c
prefetch(0, mem(rdx, rsi, 2, 1*8)) // prefetch c + 10*cs_c
prefetch(0, mem(rdx, rbp, 1, 1*8)) // prefetch c + 11*cs_c
label(.SPOSTPFETCH) // done prefetching c
#if 1
lea(mem(rax, r9, 8), rdx) //
lea(mem(rdx, r9, 8), rdx) // rdx = a + 16*cs_a;
#endif
mov(var(k_iter), rsi) // i = k_iter;
test(rsi, rsi) // check i via logical AND.
je(.SCONSIDKLEFT) // if i == 0, jump to code that
// contains the k_left loop.
label(.SLOOPKITER) // MAIN LOOP
// ---------------------------------- iteration 0
#if 1
prefetch(0, mem(rdx, 4*8))
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
// ---------------------------------- iteration 1
#if 0
prefetch(0, mem(rdx, r9, 1, 4*8))
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
// ---------------------------------- iteration 2
#if 1
prefetch(0, mem(rdx, r9, 2, 4*8))
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
// ---------------------------------- iteration 3
#if 1
lea(mem(rdx, r9, 4), rdx) // a_prefetch += 4*cs_a;
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
dec(rsi) // i -= 1;
jne(.SLOOPKITER) // iterate again if i != 0.
label(.SCONSIDKLEFT)
mov(var(k_left), rsi) // i = k_left;
test(rsi, rsi) // check i via logical AND.
je(.SPOSTACCUM) // if i == 0, we're done; jump to end.
// else, we prepare to enter k_left loop.
label(.SLOOPKLEFT) // EDGE LOOP
#if 0
prefetch(0, mem(rdx, 5*8))
add(r9, rdx)
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
vbroadcastss(mem(rax, r8, 1), ymm3)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
vfmadd231ps(ymm0, ymm3, ymm6)
vfmadd231ps(ymm1, ymm3, ymm7)
dec(rsi) // i -= 1;
jne(.SLOOPKLEFT) // iterate again if i != 0.
label(.SPOSTACCUM)
mov(var(alpha), rax) // load address of alpha
mov(var(beta), rbx) // load address of beta
vbroadcastss(mem(rax), ymm0) // load alpha and duplicate
vbroadcastss(mem(rbx), ymm3) // load beta and duplicate
vmulps(ymm0, ymm4, ymm4) // scale by alpha
vmulps(xmm0, xmm5, xmm5)
vmulps(ymm0, ymm6, ymm6)
vmulps(xmm0, xmm7, xmm7)
mov(var(cs_c), rsi) // load cs_c
lea(mem(, rsi, 4), rsi) // rsi = cs_c * sizeof(float)
//lea(mem(rcx, rsi, 4), rdx) // load address of c + 4*cs_c;
//lea(mem(rcx, rdi, 2), rdx) // load address of c + 2*rs_c;
lea(mem(rsi, rsi, 2), rax) // rax = 3*cs_c;
lea(mem(rsi, rsi, 4), rbx) // rbx = 5*cs_c;
lea(mem(rax, rsi, 4), rbp) // rbp = 7*cs_c;
// now avoid loading C if beta == 0
vxorps(ymm0, ymm0, ymm0) // set ymm0 to zero.
vucomiss(xmm0, xmm3) // set ZF if beta == 0.
je(.SBETAZERO) // if ZF = 1, jump to beta == 0 case
cmp(imm(4), rdi) // set ZF if (4*rs_c) == 4.
jz(.SCOLSTORED) // jump to column storage case
label(.SROWSTORED)
vfmadd231ps(mem(rcx, 0*32), ymm3, ymm4)
vmovups(ymm4, mem(rcx, 0*32))
vfmadd231ps(mem(rcx, 1*32), xmm3, xmm5)
vmovups(xmm5, mem(rcx, 1*32))
add(rdi, rcx)
vfmadd231ps(mem(rcx, 0*32), ymm3, ymm6)
vmovups(ymm6, mem(rcx, 0*32))
vfmadd231ps(mem(rcx, 1*32), xmm3, xmm7)
vmovups(xmm7, mem(rcx, 1*32))
//add(rdi, rcx)
jmp(.SDONE) // jump to end.
label(.SCOLSTORED)
// begin I/O on columns 0-7
vunpcklps(ymm6, ymm4, ymm0)
vextractf128(imm(0x1), ymm0, xmm2)
vmovlpd(mem(rcx ), xmm1, xmm1)
vmovhpd(mem(rcx, rsi, 1), xmm1, xmm1)
vfmadd231ps(xmm1, xmm3, xmm0)
vmovlpd(xmm0, mem(rcx )) // store ( gamma00..gamma10 )
vmovhpd(xmm0, mem(rcx, rsi, 1)) // store ( gamma01..gamma11 )
vmovlpd(mem(rcx, rsi, 4), xmm1, xmm1)
vmovhpd(mem(rcx, rbx, 1), xmm1, xmm1)
vfmadd231ps(xmm1, xmm3, xmm2)
vmovlpd(xmm2, mem(rcx, rsi, 4)) // store ( gamma04..gamma14 )
vmovhpd(xmm2, mem(rcx, rbx, 1)) // store ( gamma05..gamma15 )
vunpckhps(ymm6, ymm4, ymm0)
vextractf128(imm(0x1), ymm0, xmm2)
vmovlpd(mem(rcx, rsi, 2), xmm1, xmm1)
vmovhpd(mem(rcx, rax, 1), xmm1, xmm1)
vfmadd231ps(xmm1, xmm3, xmm0)
vmovlpd(xmm0, mem(rcx, rsi, 2)) // store ( gamma02..gamma12 )
vmovhpd(xmm0, mem(rcx, rax, 1)) // store ( gamma03..gamma13 )
vmovlpd(mem(rcx, rax, 2), xmm1, xmm1)
vmovhpd(mem(rcx, rbp, 1), xmm1, xmm1)
vfmadd231ps(xmm1, xmm3, xmm2)
vmovlpd(xmm2, mem(rcx, rax, 2)) // store ( gamma06..gamma16 )
vmovhpd(xmm2, mem(rcx, rbp, 1)) // store ( gamma07..gamma17 )
lea(mem(rcx, rsi, 8), rcx) // rcx += 8*cs_c
// begin I/O on columns 8-11
vunpcklps(ymm7, ymm5, ymm0)
vmovlpd(mem(rcx ), xmm1, xmm1)
vmovhpd(mem(rcx, rsi, 1), xmm1, xmm1)
vfmadd231ps(xmm1, xmm3, xmm0)
vmovlpd(xmm0, mem(rcx )) // store ( gamma00..gamma10 )
vmovhpd(xmm0, mem(rcx, rsi, 1)) // store ( gamma01..gamma11 )
vunpckhps(ymm7, ymm5, ymm0)
vmovlpd(mem(rcx, rsi, 2), xmm1, xmm1)
vmovhpd(mem(rcx, rax, 1), xmm1, xmm1)
vfmadd231ps(xmm1, xmm3, xmm0)
vmovlpd(xmm0, mem(rcx, rsi, 2)) // store ( gamma02..gamma12 )
vmovhpd(xmm0, mem(rcx, rax, 1)) // store ( gamma03..gamma13 )
//lea(mem(rcx, rsi, 8), rcx) // rcx += 8*cs_c
jmp(.SDONE) // jump to end.
label(.SBETAZERO)
cmp(imm(4), rdi) // set ZF if (8*rs_c) == 8.
jz(.SCOLSTORBZ) // jump to column storage case
label(.SROWSTORBZ)
vmovups(ymm4, mem(rcx, 0*32))
vmovups(xmm5, mem(rcx, 1*32))
add(rdi, rcx)
vmovups(ymm6, mem(rcx, 0*32))
vmovups(xmm7, mem(rcx, 1*32))
//add(rdi, rcx)
jmp(.SDONE) // jump to end.
label(.SCOLSTORBZ)
// begin I/O on columns 0-7
vunpcklps(ymm6, ymm4, ymm0)
vextractf128(imm(0x1), ymm0, xmm2)
vmovlpd(xmm0, mem(rcx )) // store ( gamma00..gamma10 )
vmovhpd(xmm0, mem(rcx, rsi, 1)) // store ( gamma01..gamma11 )
vmovlpd(xmm2, mem(rcx, rsi, 4)) // store ( gamma04..gamma14 )
vmovhpd(xmm2, mem(rcx, rbx, 1)) // store ( gamma05..gamma15 )
vunpckhps(ymm6, ymm4, ymm0)
vextractf128(imm(0x1), ymm0, xmm2)
vmovlpd(xmm0, mem(rcx, rsi, 2)) // store ( gamma02..gamma12 )
vmovhpd(xmm0, mem(rcx, rax, 1)) // store ( gamma03..gamma13 )
vmovlpd(xmm2, mem(rcx, rax, 2)) // store ( gamma06..gamma16 )
vmovhpd(xmm2, mem(rcx, rbp, 1)) // store ( gamma07..gamma17 )
lea(mem(rcx, rsi, 8), rcx) // rcx += 8*cs_c
// begin I/O on columns 8-11
vunpcklps(ymm7, ymm5, ymm0)
vmovlpd(xmm0, mem(rcx )) // store ( gamma00..gamma10 )
vmovhpd(xmm0, mem(rcx, rsi, 1)) // store ( gamma01..gamma11 )
vunpckhps(ymm7, ymm5, ymm0)
vmovlpd(xmm0, mem(rcx, rsi, 2)) // store ( gamma02..gamma12 )
vmovhpd(xmm0, mem(rcx, rax, 1)) // store ( gamma03..gamma13 )
//lea(mem(rcx, rsi, 8), rcx) // rcx += 8*cs_c
label(.SDONE)
end_asm(
: // output operands (none)
: // input operands
[k_iter] "m" (k_iter),
[k_left] "m" (k_left),
[a] "m" (a),
[rs_a] "m" (rs_a),
[cs_a] "m" (cs_a),
[b] "m" (b),
[rs_b] "m" (rs_b),
[cs_b] "m" (cs_b),
[alpha] "m" (alpha),
[beta] "m" (beta),
[c] "m" (c),
[rs_c] "m" (rs_c),
[cs_c] "m" (cs_c)/*,
[a_next] "m" (a_next),
[b_next] "m" (b_next)*/
: // register clobber list
"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "rbp",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
"xmm0", "xmm1", "xmm2", "xmm3",
"xmm4", "xmm5", "xmm6", "xmm7",
"xmm8", "xmm9", "xmm10", "xmm11",
"xmm12", "xmm13", "xmm14", "xmm15",
"memory"
)
}
void bli_sgemmsup_rv_haswell_asm_1x12
(
conj_t conja,
conj_t conjb,
dim_t m0,
dim_t n0,
dim_t k0,
float* restrict alpha,
float* restrict a, inc_t rs_a0, inc_t cs_a0,
float* restrict b, inc_t rs_b0, inc_t cs_b0,
float* restrict beta,
float* restrict c, inc_t rs_c0, inc_t cs_c0,
auxinfo_t* data,
cntx_t* cntx
)
{
//void* a_next = bli_auxinfo_next_a( data );
//void* b_next = bli_auxinfo_next_b( data );
// Typecast local copies of integers in case dim_t and inc_t are a
// different size than is expected by load instructions.
uint64_t k_iter = k0 / 4;
uint64_t k_left = k0 % 4;
uint64_t rs_a = rs_a0;
uint64_t cs_a = cs_a0;
uint64_t rs_b = rs_b0;
uint64_t cs_b = cs_b0;
uint64_t rs_c = rs_c0;
uint64_t cs_c = cs_c0;
// -------------------------------------------------------------------------
begin_asm()
vzeroall() // zero all xmm/ymm registers.
mov(var(a), rax) // load address of a.
mov(var(rs_a), r8) // load rs_a
mov(var(cs_a), r9) // load cs_a
lea(mem(, r8, 4), r8) // rs_a *= sizeof(float)
lea(mem(, r9, 4), r9) // cs_a *= sizeof(float)
//lea(mem(r8, r8, 2), r13) // r13 = 3*rs_a
//lea(mem(r8, r8, 4), r15) // r15 = 5*rs_a
mov(var(b), rbx) // load address of b.
mov(var(rs_b), r10) // load rs_b
//mov(var(cs_b), r11) // load cs_b
lea(mem(, r10, 4), r10) // rs_b *= sizeof(float)
//lea(mem(, r11, 4), r11) // cs_b *= sizeof(float)
// NOTE: We cannot pre-load elements of a or b
// because it could eventually, in the last
// unrolled iter or the cleanup loop, result
// in reading beyond the bounds allocated mem
// (the likely result: a segmentation fault).
mov(var(c), rcx) // load address of c
mov(var(rs_c), rdi) // load rs_c
lea(mem(, rdi, 4), rdi) // rs_c *= sizeof(float)
cmp(imm(8), rdi) // set ZF if (8*rs_c) == 8.
jz(.SCOLPFETCH) // jump to column storage case
label(.SROWPFETCH) // row-stored prefetching on c
//lea(mem(rcx, rdi, 2), rdx) //
//lea(mem(rdx, rdi, 1), rdx) // rdx = c + 3*rs_c;
prefetch(0, mem(rcx, 7*8)) // prefetch c + 0*rs_c
jmp(.SPOSTPFETCH) // jump to end of prefetching c
label(.SCOLPFETCH) // column-stored prefetching c
mov(var(cs_c), rsi) // load cs_c to rsi (temporarily)
lea(mem(, rsi, 4), rsi) // cs_c *= sizeof(float)
lea(mem(rsi, rsi, 2), rbp) // rbp = 3*cs_c;
prefetch(0, mem(rcx, 0*8)) // prefetch c + 0*cs_c
prefetch(0, mem(rcx, rsi, 1, 0*8)) // prefetch c + 1*cs_c
prefetch(0, mem(rcx, rsi, 2, 0*8)) // prefetch c + 2*cs_c
prefetch(0, mem(rcx, rbp, 1, 0*8)) // prefetch c + 3*cs_c
prefetch(0, mem(rcx, rsi, 4, 0*8)) // prefetch c + 4*cs_c
lea(mem(rcx, rsi, 4), rdx) // rdx = c + 4*cs_c;
prefetch(0, mem(rdx, rsi, 1, 0*8)) // prefetch c + 5*cs_c
prefetch(0, mem(rdx, rsi, 2, 0*8)) // prefetch c + 6*cs_c
prefetch(0, mem(rdx, rbp, 1, 0*8)) // prefetch c + 7*cs_c
prefetch(0, mem(rdx, rsi, 4, 0*8)) // prefetch c + 8*cs_c
lea(mem(rcx, rsi, 8), rdx) // rdx = c + 8*cs_c;
prefetch(0, mem(rdx, rsi, 1, 0*8)) // prefetch c + 9*cs_c
prefetch(0, mem(rdx, rsi, 2, 0*8)) // prefetch c + 10*cs_c
prefetch(0, mem(rdx, rbp, 1, 0*8)) // prefetch c + 11*cs_c
label(.SPOSTPFETCH) // done prefetching c
#if 1
lea(mem(rax, r9, 8), rdx) //
lea(mem(rdx, r9, 8), rdx) // rdx = a + 16*cs_a;
#endif
mov(var(k_iter), rsi) // i = k_iter;
test(rsi, rsi) // check i via logical AND.
je(.SCONSIDKLEFT) // if i == 0, jump to code that
// contains the k_left loop.
label(.SLOOPKITER) // MAIN LOOP
// ---------------------------------- iteration 0
#if 1
prefetch(0, mem(rdx, 4*8))
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
// ---------------------------------- iteration 1
#if 0
prefetch(0, mem(rdx, r9, 1, 4*8))
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
// ---------------------------------- iteration 2
#if 1
prefetch(0, mem(rdx, r9, 2, 4*8))
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
// ---------------------------------- iteration 3
#if 1
lea(mem(rdx, r9, 4), rdx) // a_prefetch += 4*cs_a;
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
dec(rsi) // i -= 1;
jne(.SLOOPKITER) // iterate again if i != 0.
label(.SCONSIDKLEFT)
mov(var(k_left), rsi) // i = k_left;
test(rsi, rsi) // check i via logical AND.
je(.SPOSTACCUM) // if i == 0, we're done; jump to end.
// else, we prepare to enter k_left loop.
label(.SLOOPKLEFT) // EDGE LOOP
#if 0
prefetch(0, mem(rdx, 5*8))
add(r9, rdx)
#endif
vmovups(mem(rbx, 0*32), ymm0)
vmovups(mem(rbx, 1*32), xmm1)
add(r10, rbx) // b += rs_b;
vbroadcastss(mem(rax ), ymm2)
add(r9, rax) // a += cs_a;
vfmadd231ps(ymm0, ymm2, ymm4)
vfmadd231ps(ymm1, ymm2, ymm5)
dec(rsi) // i -= 1;
jne(.SLOOPKLEFT) // iterate again if i != 0.
label(.SPOSTACCUM)
mov(var(alpha), rax) // load address of alpha
mov(var(beta), rbx) // load address of beta
vbroadcastss(mem(rax), ymm0) // load alpha and duplicate
vbroadcastss(mem(rbx), ymm3) // load beta and duplicate
vmulps(ymm0, ymm4, ymm4) // scale by alpha
vmulps(xmm0, xmm5, xmm5)
mov(var(cs_c), rsi) // load cs_c
lea(mem(, rsi, 4), rsi) // rsi = cs_c * sizeof(float)
//lea(mem(rcx, rsi, 4), rdx) // load address of c + 4*cs_c;
//lea(mem(rcx, rdi, 2), rdx) // load address of c + 2*rs_c;
lea(mem(rsi, rsi, 2), rax) // rax = 3*cs_c;
lea(mem(rsi, rsi, 4), rbx) // rbx = 5*cs_c;
lea(mem(rax, rsi, 4), rbp) // rbp = 7*cs_c;
// now avoid loading C if beta == 0
vxorps(ymm0, ymm0, ymm0) // set ymm0 to zero.
vucomiss(xmm0, xmm3) // set ZF if beta == 0.
je(.SBETAZERO) // if ZF = 1, jump to beta == 0 case
cmp(imm(4), rdi) // set ZF if (4*rs_c) == 4.
jz(.SCOLSTORED) // jump to column storage case
label(.SROWSTORED)
vfmadd231ps(mem(rcx, 0*32), ymm3, ymm4)
vmovups(ymm4, mem(rcx, 0*32))
vfmadd231ps(mem(rcx, 1*32), xmm3, xmm5)
vmovups(xmm5, mem(rcx, 1*32))
//add(rdi, rcx)
jmp(.SDONE) // jump to end.
label(.SCOLSTORED)
// begin I/O on columns 0-7
vmovups(ymm4, ymm0)
vextractf128(imm(0x1), ymm0, xmm8)
vpermilps(imm(0xe4), xmm0, xmm2)
vpermilps(imm(0x39), xmm0, xmm4)
vmovss(mem(rcx ), xmm1)
vmovss(mem(rcx, rsi, 1), xmm6)
vfmadd231ps(xmm1, xmm3, xmm2)
vfmadd231ps(xmm6, xmm3, xmm4)
vmovss(xmm2, mem(rcx )) // store ( gamma40 )
vmovss(xmm4, mem(rcx, rsi, 1)) // store ( gamma41 )
vpermilps(imm(0x4e), xmm0, xmm2)
vpermilps(imm(0x93), xmm0, xmm4)
vmovss(mem(rcx, rsi, 2), xmm1)
vmovss(mem(rcx, rax, 1), xmm6)
vfmadd231ps(xmm1, xmm3, xmm2)
vfmadd231ps(xmm6, xmm3, xmm4)
vmovss(xmm2, mem(rcx, rsi, 2)) // store ( gamma42 )
vmovss(xmm4, mem(rcx, rax, 1)) // store ( gamma43 )
vpermilps(imm(0xe4), xmm8, xmm2)
vpermilps(imm(0x39), xmm8, xmm4)
vmovss(mem(rcx, rsi, 4), xmm1)
vmovss(mem(rcx, rbx, 1), xmm6)
vfmadd231ps(xmm1, xmm3, xmm2)
vfmadd231ps(xmm6, xmm3, xmm4)
vmovss(xmm2, mem(rcx, rsi, 4)) // store ( gamma44 )
vmovss(xmm4, mem(rcx, rbx, 1)) // store ( gamma45 )
vpermilps(imm(0x4e), xmm8, xmm2)
vpermilps(imm(0x93), xmm8, xmm4)
vmovss(mem(rcx, rax, 2), xmm1)
vmovss(mem(rcx, rbp, 1), xmm6)
vfmadd231ps(xmm1, xmm3, xmm2)
vfmadd231ps(xmm6, xmm3, xmm4)
vmovss(xmm2, mem(rcx, rax, 2)) // store ( gamma46 )
vmovss(xmm4, mem(rcx, rbp, 1)) // store ( gamma47 )
lea(mem(rcx, rsi, 8), rcx) // rcx += 8*cs_c
// begin I/O on columns 8-11
vmovups(ymm5, ymm0)
vpermilps(imm(0xe4), xmm0, xmm2)
vpermilps(imm(0x39), xmm0, xmm4)
vmovss(mem(rcx ), xmm1)
vmovss(mem(rcx, rsi, 1), xmm6)
vfmadd231ps(xmm1, xmm3, xmm2)
vfmadd231ps(xmm6, xmm3, xmm4)
vmovss(xmm2, mem(rcx )) // store ( gamma40 )
vmovss(xmm4, mem(rcx, rsi, 1)) // store ( gamma41 )
vpermilps(imm(0x4e), xmm0, xmm2)
vpermilps(imm(0x93), xmm0, xmm4)
vmovss(mem(rcx, rsi, 2), xmm1)
vmovss(mem(rcx, rax, 1), xmm6)
vfmadd231ps(xmm1, xmm3, xmm2)
vfmadd231ps(xmm6, xmm3, xmm4)
vmovss(xmm2, mem(rcx, rsi, 2)) // store ( gamma42 )
vmovss(xmm4, mem(rcx, rax, 1)) // store ( gamma43 )
//lea(mem(rcx, rsi, 8), rcx) // rcx += 8*cs_c
jmp(.SDONE) // jump to end.
label(.SBETAZERO)
cmp(imm(4), rdi) // set ZF if (8*rs_c) == 8.
jz(.SCOLSTORBZ) // jump to column storage case
label(.SROWSTORBZ)
vmovups(ymm4, mem(rcx, 0*32))
vmovups(xmm5, mem(rcx, 1*32))
//add(rdi, rcx)
jmp(.SDONE) // jump to end.
label(.SCOLSTORBZ)
// begin I/O on columns 0-7
vmovups(ymm4, ymm0)
vextractf128(imm(0x1), ymm0, xmm8)
vpermilps(imm(0xe4), xmm0, xmm2)
vpermilps(imm(0x39), xmm0, xmm4)
vmovss(xmm2, mem(rcx )) // store ( gamma40 )
vmovss(xmm4, mem(rcx, rsi, 1)) // store ( gamma41 )
vpermilps(imm(0x4e), xmm0, xmm2)
vpermilps(imm(0x93), xmm0, xmm4)
vmovss(xmm2, mem(rcx, rsi, 2)) // store ( gamma42 )
vmovss(xmm4, mem(rcx, rax, 1)) // store ( gamma43 )
vpermilps(imm(0xe4), xmm8, xmm2)
vpermilps(imm(0x39), xmm8, xmm4)
vmovss(xmm2, mem(rcx, rsi, 4)) // store ( gamma44 )
vmovss(xmm4, mem(rcx, rbx, 1)) // store ( gamma45 )
vpermilps(imm(0x4e), xmm8, xmm2)
vpermilps(imm(0x93), xmm8, xmm4)
vmovss(xmm2, mem(rcx, rax, 2)) // store ( gamma46 )
vmovss(xmm4, mem(rcx, rbp, 1)) // store ( gamma47 )
lea(mem(rcx, rsi, 8), rcx) // rcx += 8*cs_c
// begin I/O on columns 8-11
vmovups(ymm5, ymm0)
vpermilps(imm(0xe4), xmm0, xmm2)
vpermilps(imm(0x39), xmm0, xmm4)
vmovss(xmm2, mem(rcx )) // store ( gamma40 )
vmovss(xmm4, mem(rcx, rsi, 1)) // store ( gamma41 )
vpermilps(imm(0x4e), xmm0, xmm2)
vpermilps(imm(0x93), xmm0, xmm4)
vmovss(xmm2, mem(rcx, rsi, 2)) // store ( gamma42 )
vmovss(xmm4, mem(rcx, rax, 1)) // store ( gamma43 )
//lea(mem(rcx, rsi, 8), rcx) // rcx += 8*cs_c
label(.SDONE)
end_asm(
: // output operands (none)
: // input operands
[k_iter] "m" (k_iter),
[k_left] "m" (k_left),
[a] "m" (a),
[rs_a] "m" (rs_a),
[cs_a] "m" (cs_a),
[b] "m" (b),
[rs_b] "m" (rs_b),
[cs_b] "m" (cs_b),
[alpha] "m" (alpha),
[beta] "m" (beta),
[c] "m" (c),
[rs_c] "m" (rs_c),
[cs_c] "m" (cs_c)/*,
[a_next] "m" (a_next),
[b_next] "m" (b_next)*/
: // register clobber list
"rax", "rbx", "rcx", "rdx", "rsi", "rdi", "rbp",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
"xmm0", "xmm1", "xmm2", "xmm3",
"xmm4", "xmm5", "xmm6", "xmm7",
"xmm8", "xmm9", "xmm10", "xmm11",
"xmm12", "xmm13", "xmm14", "xmm15",
"memory"
)
}
| 29.668372 | 82 | 0.544649 | [
"object"
] |
65d8bb5c37f2b3a681ba15eca29505e449c389f6 | 4,713 | h | C | 3DEngine/src/Shader/Shader.h | tobbep1997/Bitfrost_2.0 | a092db19d4658062554b7df759f28439fc1ad4f8 | [
"Apache-2.0"
] | null | null | null | 3DEngine/src/Shader/Shader.h | tobbep1997/Bitfrost_2.0 | a092db19d4658062554b7df759f28439fc1ad4f8 | [
"Apache-2.0"
] | null | null | null | 3DEngine/src/Shader/Shader.h | tobbep1997/Bitfrost_2.0 | a092db19d4658062554b7df759f28439fc1ad4f8 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <string>
#include <d3d11_1.h>
#include <d3dcompiler.h>
#include <debugapi.h>
#include <comdef.h>
#pragma comment (lib, "d3d11.lib")
#pragma comment (lib, "d3dcompiler.lib")
#include "../ShaderCreator.h"
#include "../3D Engine/Extern.h"
namespace Shaders
{
enum ShaderType
{
Vertex,
domain,
Hull,
Geometry,
Pixel,
Compute
};
///<summery>
/*
Store the acual shader
*/
///</summery>
class Shader
{
private:
//There is no better way of doing this ._.
ID3D11VertexShader * m_vertexShader;
ID3D11DomainShader * m_domainShader;
ID3D11HullShader * m_hullShader;
ID3D11GeometryShader * m_geometryShader;
ID3D11PixelShader * m_pixelShader;
ID3D11ComputeShader * m_computeShader;
ID3D11InputLayout * m_inputLayout;
//-------------------------------------------------------------------------------------------
//identifier
std::wstring m_path;
unsigned int m_key;
ShaderType m_type;
std::string m_entryPoint;
//Light quaris? light ocluion google fucking lights TODO
public:
Shader();
~Shader();
//-------------------------------------------------------------------------------------------
//Get/Set functions
void SetPath(const std::wstring & path);
std::wstring GetPath() const;
void SetKey(const unsigned int key);
unsigned int GetKey() const;
void SetType(const ShaderType & shaderType);
ShaderType GetType() const;
void SetEntryPoint(const std::string & entryPoint);
std::string GetEntryPoint() const;
//-------------------------------------------------------------------------------------------
/*
Default load shader function
This dosen't do anything... It's just needed to create the other ones ._.
*/
template <typename T> HRESULT LoadShader(const std::wstring path, const std::string entryPoint = "main");
ID3D11VertexShader * VertexInputLayout(const std::wstring path, const std::string entryPoint, D3D11_INPUT_ELEMENT_DESC inputDesc[], unsigned int size);
void SetInputLayout(ID3D11InputLayout *& inputLayout);
ID3D11InputLayout * GetInputLayout();
/*
Loads the correct shader
*/
template <> HRESULT LoadShader<ID3D11VertexShader>(const std::wstring path, const std::string entryPoint);
//-------------------------------------------------------------------------------------------
//Get Shaders
template <typename T> T* GetShader() const {
return nullptr;
}
template <> ID3D11VertexShader * GetShader<ID3D11VertexShader>() const {
return this->m_vertexShader;
}
template <> ID3D11DomainShader * GetShader<ID3D11DomainShader>() const {
return this->m_domainShader;
}
template <> ID3D11HullShader * GetShader<ID3D11HullShader>() const {
return this->m_hullShader;
}
template <> ID3D11GeometryShader * GetShader<ID3D11GeometryShader>() const {
return this->m_geometryShader;
}
template <> ID3D11PixelShader * GetShader<ID3D11PixelShader>() const {
return this->m_pixelShader;
}
template <> ID3D11ComputeShader * GetShader<ID3D11ComputeShader>() const {
return this->m_computeShader;
}
//-------------------------------------------------------------------------------------------
//Relese the shader
void Release();
void ReleaseWithoutInputLayout();
HRESULT ReloadShader();
};
template<>
inline HRESULT Shader::LoadShader<ID3D11VertexShader>(const std::wstring path, const std::string entryPoint)
{
return ShaderCreator::CreateVertexShader(DX::g_device, m_vertexShader, path.c_str(), entryPoint.c_str());
}
template<>
inline HRESULT Shader::LoadShader<ID3D11DomainShader>(const std::wstring path, const std::string entryPoint)
{
return ShaderCreator::CreateDomainShader(DX::g_device, m_domainShader, path.c_str(), entryPoint.c_str());
}
template<>
inline HRESULT Shader::LoadShader<ID3D11HullShader>(const std::wstring path, const std::string entryPoint)
{
return ShaderCreator::CreateHullShader(DX::g_device, m_hullShader, path.c_str(), entryPoint.c_str());
}
template<>
inline HRESULT Shader::LoadShader<ID3D11GeometryShader>(const std::wstring path, const std::string entryPoint)
{
return ShaderCreator::CreateGeometryShader(DX::g_device, m_geometryShader, path.c_str(), entryPoint.c_str());
}
template<>
inline HRESULT Shader::LoadShader<ID3D11PixelShader>(const std::wstring path, const std::string entryPoint)
{
return ShaderCreator::CreatePixelShader(DX::g_device, m_pixelShader, path.c_str(), entryPoint.c_str());
}
template<>
inline HRESULT Shader::LoadShader<ID3D11ComputeShader>(const std::wstring path, const std::string entryPoint)
{
return ShaderCreator::CreateComputeShader(DX::g_device, m_computeShader, path.c_str(), entryPoint.c_str());
}
};
| 31.006579 | 153 | 0.663908 | [
"geometry",
"3d"
] |
65d92e3a5d8583c89618ad6e914b3477e3f43e7e | 10,939 | h | C | include/atres/FontDynamic.h | borisblizzard/atres | af9d5e0bad12da97a2f2ce79d124bb6805bc253e | [
"BSD-3-Clause"
] | null | null | null | include/atres/FontDynamic.h | borisblizzard/atres | af9d5e0bad12da97a2f2ce79d124bb6805bc253e | [
"BSD-3-Clause"
] | null | null | null | include/atres/FontDynamic.h | borisblizzard/atres | af9d5e0bad12da97a2f2ce79d124bb6805bc253e | [
"BSD-3-Clause"
] | null | null | null | /// @file
/// @version 5.0
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause
///
/// @section DESCRIPTION
///
/// Defines a font with a dynamically created character map.
#ifndef ATRESTTF_FONT_DYNAMIC_H
#define ATRESTTF_FONT_DYNAMIC_H
#include <hltypes/harray.h>
#include <hltypes/hstring.h>
#include "atresExport.h"
#include "Font.h"
namespace april
{
class Texture;
}
namespace atres
{
/// @brief Special font definition type that dynamically loads symbols on demand.
class atresExport FontDynamic : public Font
{
public:
/// @brief Basic constructor.
/// @param[in] filename The filename of the font definition.
FontDynamic(chstr name);
/// @brief Constructor.
/// @param[in] filename The filename of the font definition.
/// @param[in] textureSize The filename texture size.
FontDynamic(chstr name, int textureSize);
/// @brief Destructor.
~FontDynamic();
/// @brief The texture size of the font.
HL_DEFINE_GET(int, textureSize, textureSize);
/// @brief Sets the border rendering mode.
/// @param[in] value The border rendering mode.
void setBorderMode(const BorderMode& value) override;
/// @brief Get the texture where the character definition for a specific char code is currently contained.
/// @param[in] charCode Character unicode value.
/// @return The texture.
april::Texture* getTexture(unsigned int charCode) override;
/// @brief Get the texture where the border character definition for a specific char code is currently contained.
/// @param[in] charCode Character unicode value.
/// @param[in] borderThickness Thickness of the border.
/// @return The texture.
april::Texture* getBorderTexture(unsigned int charCode, float borderThickness) override;
/// @brief Get the texture where the icon definition for a specific icon name is currently contained.
/// @param[in] iconName Icon name.
/// @return The texture.
april::Texture* getTexture(chstr iconName) override;
/// @brief Get the texture where the border icon definition for a specific icon name is currently contained.
/// @param[in] iconName Icon name.
/// @param[in] borderThickness Thickness of the border.
/// @return The texture.
april::Texture* getBorderTexture(chstr iconName, float borderThickness) override;
/// @brief Checks if a character definition has been loaded already.
/// @param[in] charCode Character unicode value.
/// @return True if character is loaded.
bool hasCharacter(unsigned int charCode) override;
/// @brief Checks if a border character definition has been loaded already.
/// @param[in] charCode Character unicode value.
/// @param[in] borderThickness Thickness of the border.
/// @return True if border character is loaded.
bool hasBorderCharacter(unsigned int charCode, float borderThickness) override;
/// @brief Checks if a icon definition has been loaded already.
/// @param[in] iconName Icon name.
/// @return True if icon is loaded.
bool hasIcon(chstr iconName) override;
/// @brief Checks if a border icon definition has been loaded already.
/// @param[in] iconName Icon name.
/// @param[in] borderThickness Thickness of the border.
/// @return True if border icon is loaded.
bool hasBorderIcon(chstr iconName, float borderThickness) override;
/// @brief Loads basic ASCII range of characters.
/// @param[in] iconName Icon name.
/// @return True if icon is loaded.
void loadBasicAsciiCharacters() override;
/// @brief Loads basic ASCII range of border characters.
/// @param[in] borderThickness Thickness of the border.
void loadBasicAsciiBorderCharacters(float borderThickness) override;
protected:
/// @brief Helper class for structuring images when using a prerendered border rendering mode.
class StructuringImageContainer
{
public:
/// @brief The actual structuring image.
april::Image* image;
/// @brief The border render mode.
BorderMode borderMode;
/// @brief The thickness of the border.
float borderThickness;
/// @brief Basic constructor.
/// @param[in] image The actual structuring image.
/// @param[in] borderMode The border render mode.
/// @param[in] borderThickness The thickness of the border.
StructuringImageContainer(april::Image* image, const BorderMode& borderMode, float borderThickness);
/// @brief Basic destructor.
~StructuringImageContainer();
};
/// @brief Font texture size.
int textureSize;
/// @brief All structuring image containers.
harray<StructuringImageContainer*> structuringImageContainers;
/// @brief Checks if alpha-textures can be used for this font.
/// @return True if alpha-textures can be used for this font.
virtual bool _isAllowAlphaTextures() const;
/// @brief Creates a texture contaner if there are none yet.
void _tryCreateFirstTextureContainer();
/// @brief Creates a texture contaner for border images if there are none yet.
/// @param[in] borderThickness The thickness of the border.
void _tryCreateFirstBorderTextureContainer(float borderThickness);
/// @brief Finds the given structuring image container for a given border render mode and thickness.
/// @param[in] borderMode The border render mode.
/// @param[in] borderThickness The thickness of the border.
StructuringImageContainer* _findStructuringImageContainer(const BorderMode& borderMode, float borderThickness);
/// @brief Creates a new texture for the font symbols.
/// @return A new texture.
april::Texture* _createTexture();
/// @brief Attempts to add the character bitmap to the texture.
/// @param[in] charCode Character unicode value.
/// @param[in] initial Whether this is the first attempt to write on the texture (used for internal optimization).
/// @return True if successful.
/// @note Usually false is returned when the character couldn't be loaded or created properly from the font definition.
bool _tryAddCharacterBitmap(unsigned int charCode, bool initial = false);
/// @brief Attempts to add the border character bitmap to the texture.
/// @param[in] charCode Character unicode value.
/// @param[in] borderThickness Thickness of the border.
/// @return True if successful.
/// @note Usually false is returned when the border character couldn't be or created loaded properly from the font definition.
bool _tryAddBorderCharacterBitmap(unsigned int charCode, float borderThickness);
/// @brief Attempts to add the icon bitmap to the texture.
/// @param[in] iconName Icon name.
/// @param[in] initial Whether this is the first attempt to write on the texture (used for internal optimization).
/// @return True if successful.
/// @note Usually false is returned when the icon couldn't be loaded or created properly from the font definition.
bool _tryAddIconBitmap(chstr iconName, bool initial = false);
/// @brief Attempts to add the border icon bitmap to the texture.
/// @param[in] iconName Icon name.
/// @param[in] borderThickness Thickness of the border.
/// @return True if successful.
/// @note Usually false is returned when the border icon couldn't be loaded or created properly from the font definition.
bool _tryAddBorderIconBitmap(chstr iconName, float borderThickness);
/// @brief Add the symbol bitmap to the texture.
/// @param[in] textureContainers Proper symbol type texture containers.
/// @param[in] initial Whether this is the first attempt to write on the texture (used for internal optimization).
/// @param[in] image The symbol bitmap image.
/// @param[in] usedWidth The used width on the texture so far.
/// @param[in] usedHeight The used height on the texture so far.
/// @param[in] symbol The symbol value.
/// @param[in] offsetX Horizontal offset used between symbols.
/// @param[in] offsetY Vertical offset used between symbols.
/// @param[in] safeSpace Safe space between all symbols used when rendering.
/// @return The texture container of the texture where the symbol bitmap was written.
TextureContainer* _addBitmap(harray<TextureContainer*>& textureContainers, bool initial, april::Image* image, int usedWidth, int usedHeight, chstr symbol,
int offsetX = 0, int offsetY = 0, int safeSpace = 0);
/// @brief Loads an character image.
/// @param[in] charCode Character unicode value.
/// @param[in] initial Whether this is the first attempt to write on the texture (used for internal optimization).
/// @param[out] advance Horizontal advance value.
/// @param[out] leftOffset Horizontal offset from the left boundary of the bitmap.
/// @param[out] topOffset Vertical offset from the top boundary of the bitmap.
/// @param[out] ascender Ascender value.
/// @param[out] descender Descender value.
/// @param[out] bearingX Horizontal bearing.
/// @return The loaded image.
virtual april::Image* _loadCharacterImage(unsigned int charCode, bool initial, float& advance, int& leftOffset, int& topOffset, float& ascender, float& descender, float& bearingX);
/// @brief Loads a border character image.
/// @param[in] charCode Character unicode value.
/// @param[in] borderThickness Thickness of the border.
/// @return The loaded image.
virtual april::Image* _loadBorderCharacterImage(unsigned int charCode, float borderThickness);
/// @brief Generates a border character image.
/// @param[in] charCode Character unicode value.
/// @param[in] borderThickness Thickness of the border.
/// @return The loaded image.
virtual april::Image* _generateBorderCharacterImage(unsigned int charCode, float borderThickness);
/// @brief Loads an icon image.
/// @param[in] iconName Name of the icon image to load.
/// @param[in] initial Whether this is the first attempt to write on the texture (used for internal optimization).
/// @param[out] advance Horizontal advance value.
/// @return The loaded image.
virtual april::Image* _loadIconImage(chstr iconName, bool initial, float& advance);
/// @brief Loads a border icon image.
/// @param[in] iconName Name of the border icon image to load.
/// @param[in] borderThickness Thickness of the border.
/// @return The loaded image.
virtual april::Image* _loadBorderIconImage(chstr iconName, float borderThickness);
/// @brief Generates a border icon image.
/// @param[in] iconName Name of the border icon image to load.
/// @param[in] borderThickness Thickness of the border.
/// @return The loaded image.
virtual april::Image* _generateBorderIconImage(chstr iconName, float borderThickness);
/// @brief Creates a structuring image for a given border rendering mode and thickness.
/// @param[in] borderThickness Thickness of the border.
/// @return A container for the structuring image.
StructuringImageContainer* _createStructuringImageContainer(const BorderMode& borderMode, float borderThickness);
};
}
#endif
| 48.834821 | 182 | 0.737453 | [
"render"
] |
65db6a163ac1588b5dc4984cd4dd0ee1fde9cabd | 255,942 | h | C | src/nuklear.h | aisonzk/Nuklear | 73a2062d707735e06964e77d4d10007af0252089 | [
"MIT",
"Unlicense"
] | 1 | 2021-09-10T07:04:01.000Z | 2021-09-10T07:04:01.000Z | src/nuklear.h | aisonzk/Nuklear | 73a2062d707735e06964e77d4d10007af0252089 | [
"MIT",
"Unlicense"
] | null | null | null | src/nuklear.h | aisonzk/Nuklear | 73a2062d707735e06964e77d4d10007af0252089 | [
"MIT",
"Unlicense"
] | null | null | null | #ifndef NK_NUKLEAR_H_
#define NK_NUKLEAR_H_
#ifdef __cplusplus
extern "C" {
#endif
/*
* ==============================================================
*
* CONSTANTS
*
* ===============================================================
*/
#define NK_UNDEFINED (-1.0f)
#define NK_UTF_INVALID 0xFFFD /* internal invalid utf8 rune */
#define NK_UTF_SIZE 4 /* describes the number of bytes a glyph consists of*/
#ifndef NK_INPUT_MAX
#define NK_INPUT_MAX 16
#endif
#ifndef NK_MAX_NUMBER_BUFFER
#define NK_MAX_NUMBER_BUFFER 64
#endif
#ifndef NK_SCROLLBAR_HIDING_TIMEOUT
#define NK_SCROLLBAR_HIDING_TIMEOUT 4.0f
#endif
/*
* ==============================================================
*
* HELPER
*
* ===============================================================
*/
#ifndef NK_API
#ifdef NK_PRIVATE
#if (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199409L))
#define NK_API static inline
#elif defined(__cplusplus)
#define NK_API static inline
#else
#define NK_API static
#endif
#else
#define NK_API extern
#endif
#endif
#ifndef NK_LIB
#ifdef NK_SINGLE_FILE
#define NK_LIB static
#else
#define NK_LIB extern
#endif
#endif
#define NK_INTERN static
#define NK_STORAGE static
#define NK_GLOBAL static
#define NK_FLAG(x) (1 << (x))
#define NK_STRINGIFY(x) #x
#define NK_MACRO_STRINGIFY(x) NK_STRINGIFY(x)
#define NK_STRING_JOIN_IMMEDIATE(arg1, arg2) arg1 ## arg2
#define NK_STRING_JOIN_DELAY(arg1, arg2) NK_STRING_JOIN_IMMEDIATE(arg1, arg2)
#define NK_STRING_JOIN(arg1, arg2) NK_STRING_JOIN_DELAY(arg1, arg2)
#ifdef _MSC_VER
#define NK_UNIQUE_NAME(name) NK_STRING_JOIN(name,__COUNTER__)
#else
#define NK_UNIQUE_NAME(name) NK_STRING_JOIN(name,__LINE__)
#endif
#ifndef NK_STATIC_ASSERT
#define NK_STATIC_ASSERT(exp) typedef char NK_UNIQUE_NAME(_dummy_array)[(exp)?1:-1]
#endif
#ifndef NK_FILE_LINE
#ifdef _MSC_VER
#define NK_FILE_LINE __FILE__ ":" NK_MACRO_STRINGIFY(__COUNTER__)
#else
#define NK_FILE_LINE __FILE__ ":" NK_MACRO_STRINGIFY(__LINE__)
#endif
#endif
#define NK_MIN(a,b) ((a) < (b) ? (a) : (b))
#define NK_MAX(a,b) ((a) < (b) ? (b) : (a))
#define NK_CLAMP(i,v,x) (NK_MAX(NK_MIN(v,x), i))
#ifdef NK_INCLUDE_STANDARD_VARARGS
#include <stdarg.h>
#if defined(_MSC_VER) && (_MSC_VER >= 1600) /* VS 2010 and above */
#include <sal.h>
#define NK_PRINTF_FORMAT_STRING _Printf_format_string_
#else
#define NK_PRINTF_FORMAT_STRING
#endif
#if defined(__GNUC__)
#define NK_PRINTF_VARARG_FUNC(fmtargnumber) __attribute__((format(__printf__, fmtargnumber, fmtargnumber+1)))
#define NK_PRINTF_VALIST_FUNC(fmtargnumber) __attribute__((format(__printf__, fmtargnumber, 0)))
#else
#define NK_PRINTF_VARARG_FUNC(fmtargnumber)
#define NK_PRINTF_VALIST_FUNC(fmtargnumber)
#endif
#endif
/*
* ===============================================================
*
* BASIC
*
* ===============================================================
*/
#ifdef NK_INCLUDE_FIXED_TYPES
#include <stdint.h>
#define NK_INT8 int8_t
#define NK_UINT8 uint8_t
#define NK_INT16 int16_t
#define NK_UINT16 uint16_t
#define NK_INT32 int32_t
#define NK_UINT32 uint32_t
#define NK_SIZE_TYPE uintptr_t
#define NK_POINTER_TYPE uintptr_t
#else
#ifndef NK_INT8
#define NK_INT8 signed char
#endif
#ifndef NK_UINT8
#define NK_UINT8 unsigned char
#endif
#ifndef NK_INT16
#define NK_INT16 signed short
#endif
#ifndef NK_UINT16
#define NK_UINT16 unsigned short
#endif
#ifndef NK_INT32
#if defined(_MSC_VER)
#define NK_INT32 __int32
#else
#define NK_INT32 signed int
#endif
#endif
#ifndef NK_UINT32
#if defined(_MSC_VER)
#define NK_UINT32 unsigned __int32
#else
#define NK_UINT32 unsigned int
#endif
#endif
#ifndef NK_SIZE_TYPE
#if defined(_WIN64) && defined(_MSC_VER)
#define NK_SIZE_TYPE unsigned __int64
#elif (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
#define NK_SIZE_TYPE unsigned __int32
#elif defined(__GNUC__) || defined(__clang__)
#if defined(__x86_64__) || defined(__ppc64__)
#define NK_SIZE_TYPE unsigned long
#else
#define NK_SIZE_TYPE unsigned int
#endif
#else
#define NK_SIZE_TYPE unsigned long
#endif
#endif
#ifndef NK_POINTER_TYPE
#if defined(_WIN64) && defined(_MSC_VER)
#define NK_POINTER_TYPE unsigned __int64
#elif (defined(_WIN32) || defined(WIN32)) && defined(_MSC_VER)
#define NK_POINTER_TYPE unsigned __int32
#elif defined(__GNUC__) || defined(__clang__)
#if defined(__x86_64__) || defined(__ppc64__)
#define NK_POINTER_TYPE unsigned long
#else
#define NK_POINTER_TYPE unsigned int
#endif
#else
#define NK_POINTER_TYPE unsigned long
#endif
#endif
#endif
#ifndef NK_BOOL
#ifdef NK_INCLUDE_STANDARD_BOOL
#include <stdbool.h>
#define NK_BOOL bool
#else
#define NK_BOOL int /* could be char, use int for drop-in replacement backwards compatibility */
#endif
#endif
typedef NK_INT8 nk_char;
typedef NK_UINT8 nk_uchar;
typedef NK_UINT8 nk_byte;
typedef NK_INT16 nk_short;
typedef NK_UINT16 nk_ushort;
typedef NK_INT32 nk_int;
typedef NK_UINT32 nk_uint;
typedef NK_SIZE_TYPE nk_size;
typedef NK_POINTER_TYPE nk_ptr;
typedef NK_BOOL nk_bool;
typedef nk_uint nk_hash;
typedef nk_uint nk_flags;
typedef nk_uint nk_rune;
/* Make sure correct type size:
* This will fire with a negative subscript error if the type sizes
* are set incorrectly by the compiler, and compile out if not */
NK_STATIC_ASSERT(sizeof(nk_short) == 2);
NK_STATIC_ASSERT(sizeof(nk_ushort) == 2);
NK_STATIC_ASSERT(sizeof(nk_uint) == 4);
NK_STATIC_ASSERT(sizeof(nk_int) == 4);
NK_STATIC_ASSERT(sizeof(nk_byte) == 1);
NK_STATIC_ASSERT(sizeof(nk_flags) >= 4);
NK_STATIC_ASSERT(sizeof(nk_rune) >= 4);
NK_STATIC_ASSERT(sizeof(nk_size) >= sizeof(void*));
NK_STATIC_ASSERT(sizeof(nk_ptr) >= sizeof(void*));
#ifdef NK_INCLUDE_STANDARD_BOOL
NK_STATIC_ASSERT(sizeof(nk_bool) == sizeof(bool));
#else
NK_STATIC_ASSERT(sizeof(nk_bool) >= 2);
#endif
/* ============================================================================
*
* API
*
* =========================================================================== */
struct nk_buffer;
struct nk_allocator;
struct nk_command_buffer;
struct nk_draw_command;
struct nk_convert_config;
struct nk_style_item;
struct nk_text_edit;
struct nk_draw_list;
struct nk_user_font;
struct nk_panel;
struct nk_context;
struct nk_draw_vertex_layout_element;
struct nk_style_button;
struct nk_style_toggle;
struct nk_style_selectable;
struct nk_style_slide;
struct nk_style_progress;
struct nk_style_scrollbar;
struct nk_style_edit;
struct nk_style_property;
struct nk_style_chart;
struct nk_style_combo;
struct nk_style_tab;
struct nk_style_window_header;
struct nk_style_window;
enum {nk_false, nk_true};
struct nk_color {nk_byte r,g,b,a;};
struct nk_colorf {float r,g,b,a;};
struct nk_vec2 {float x,y;};
struct nk_vec2i {short x, y;};
struct nk_rect {float x,y,w,h;};
struct nk_recti {short x,y,w,h;};
typedef char nk_glyph[NK_UTF_SIZE];
typedef union {void *ptr; int id;} nk_handle;
struct nk_image {nk_handle handle; nk_ushort w, h; nk_ushort region[4];};
struct nk_nine_slice {struct nk_image img; nk_ushort l, t, r, b;};
struct nk_cursor {struct nk_image img; struct nk_vec2 size, offset;};
struct nk_scroll {nk_uint x, y;};
enum nk_heading {NK_UP, NK_RIGHT, NK_DOWN, NK_LEFT};
enum nk_button_behavior {NK_BUTTON_DEFAULT, NK_BUTTON_REPEATER};
enum nk_modify {NK_FIXED = nk_false, NK_MODIFIABLE = nk_true};
enum nk_orientation {NK_VERTICAL, NK_HORIZONTAL};
enum nk_collapse_states {NK_MINIMIZED = nk_false, NK_MAXIMIZED = nk_true};
enum nk_show_states {NK_HIDDEN = nk_false, NK_SHOWN = nk_true};
enum nk_chart_type {NK_CHART_LINES, NK_CHART_COLUMN, NK_CHART_MAX};
enum nk_chart_event {NK_CHART_HOVERING = 0x01, NK_CHART_CLICKED = 0x02};
enum nk_color_format {NK_RGB, NK_RGBA};
enum nk_popup_type {NK_POPUP_STATIC, NK_POPUP_DYNAMIC};
enum nk_layout_format {NK_DYNAMIC, NK_STATIC};
enum nk_tree_type {NK_TREE_NODE, NK_TREE_TAB};
typedef void*(*nk_plugin_alloc)(nk_handle, void *old, nk_size);
typedef void (*nk_plugin_free)(nk_handle, void *old);
typedef nk_bool(*nk_plugin_filter)(const struct nk_text_edit*, nk_rune unicode);
typedef void(*nk_plugin_paste)(nk_handle, struct nk_text_edit*);
typedef void(*nk_plugin_copy)(nk_handle, const char*, int len);
struct nk_allocator {
nk_handle userdata;
nk_plugin_alloc alloc;
nk_plugin_free free;
};
enum nk_symbol_type {
NK_SYMBOL_NONE,
NK_SYMBOL_X,
NK_SYMBOL_UNDERSCORE,
NK_SYMBOL_CIRCLE_SOLID,
NK_SYMBOL_CIRCLE_OUTLINE,
NK_SYMBOL_RECT_SOLID,
NK_SYMBOL_RECT_OUTLINE,
NK_SYMBOL_TRIANGLE_UP,
NK_SYMBOL_TRIANGLE_DOWN,
NK_SYMBOL_TRIANGLE_LEFT,
NK_SYMBOL_TRIANGLE_RIGHT,
NK_SYMBOL_PLUS,
NK_SYMBOL_MINUS,
NK_SYMBOL_MAX
};
/* =============================================================================
*
* CONTEXT
*
* =============================================================================*/
/*/// ### Context
/// Contexts are the main entry point and the majestro of nuklear and contain all required state.
/// They are used for window, memory, input, style, stack, commands and time management and need
/// to be passed into all nuklear GUI specific functions.
///
/// #### Usage
/// To use a context it first has to be initialized which can be achieved by calling
/// one of either `nk_init_default`, `nk_init_fixed`, `nk_init`, `nk_init_custom`.
/// Each takes in a font handle and a specific way of handling memory. Memory control
/// hereby ranges from standard library to just specifying a fixed sized block of memory
/// which nuklear has to manage itself from.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// struct nk_context ctx;
/// nk_init_xxx(&ctx, ...);
/// while (1) {
/// // [...]
/// nk_clear(&ctx);
/// }
/// nk_free(&ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// #### Reference
/// Function | Description
/// --------------------|-------------------------------------------------------
/// __nk_init_default__ | Initializes context with standard library memory allocation (malloc,free)
/// __nk_init_fixed__ | Initializes context from single fixed size memory block
/// __nk_init__ | Initializes context with memory allocator callbacks for alloc and free
/// __nk_init_custom__ | Initializes context from two buffers. One for draw commands the other for window/panel/table allocations
/// __nk_clear__ | Called at the end of the frame to reset and prepare the context for the next frame
/// __nk_free__ | Shutdown and free all memory allocated inside the context
/// __nk_set_user_data__| Utility function to pass user data to draw command
*/
#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR
/*/// #### nk_init_default
/// Initializes a `nk_context` struct with a default standard library allocator.
/// Should be used if you don't want to be bothered with memory management in nuklear.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_bool nk_init_default(struct nk_context *ctx, const struct nk_user_font *font);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|---------------------------------------------------------------
/// __ctx__ | Must point to an either stack or heap allocated `nk_context` struct
/// __font__ | Must point to a previously initialized font handle for more info look at font documentation
///
/// Returns either `false(0)` on failure or `true(1)` on success.
///
*/
NK_API nk_bool nk_init_default(struct nk_context*, const struct nk_user_font*);
#endif
/*/// #### nk_init_fixed
/// Initializes a `nk_context` struct from single fixed size memory block
/// Should be used if you want complete control over nuklear's memory management.
/// Especially recommended for system with little memory or systems with virtual memory.
/// For the later case you can just allocate for example 16MB of virtual memory
/// and only the required amount of memory will actually be committed.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_bool nk_init_fixed(struct nk_context *ctx, void *memory, nk_size size, const struct nk_user_font *font);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// !!! Warning
/// make sure the passed memory block is aligned correctly for `nk_draw_commands`.
///
/// Parameter | Description
/// ------------|--------------------------------------------------------------
/// __ctx__ | Must point to an either stack or heap allocated `nk_context` struct
/// __memory__ | Must point to a previously allocated memory block
/// __size__ | Must contain the total size of __memory__
/// __font__ | Must point to a previously initialized font handle for more info look at font documentation
///
/// Returns either `false(0)` on failure or `true(1)` on success.
*/
NK_API nk_bool nk_init_fixed(struct nk_context*, void *memory, nk_size size, const struct nk_user_font*);
/*/// #### nk_init
/// Initializes a `nk_context` struct with memory allocation callbacks for nuklear to allocate
/// memory from. Used internally for `nk_init_default` and provides a kitchen sink allocation
/// interface to nuklear. Can be useful for cases like monitoring memory consumption.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_bool nk_init(struct nk_context *ctx, struct nk_allocator *alloc, const struct nk_user_font *font);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|---------------------------------------------------------------
/// __ctx__ | Must point to an either stack or heap allocated `nk_context` struct
/// __alloc__ | Must point to a previously allocated memory allocator
/// __font__ | Must point to a previously initialized font handle for more info look at font documentation
///
/// Returns either `false(0)` on failure or `true(1)` on success.
*/
NK_API nk_bool nk_init(struct nk_context*, struct nk_allocator*, const struct nk_user_font*);
/*/// #### nk_init_custom
/// Initializes a `nk_context` struct from two different either fixed or growing
/// buffers. The first buffer is for allocating draw commands while the second buffer is
/// used for allocating windows, panels and state tables.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_bool nk_init_custom(struct nk_context *ctx, struct nk_buffer *cmds, struct nk_buffer *pool, const struct nk_user_font *font);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|---------------------------------------------------------------
/// __ctx__ | Must point to an either stack or heap allocated `nk_context` struct
/// __cmds__ | Must point to a previously initialized memory buffer either fixed or dynamic to store draw commands into
/// __pool__ | Must point to a previously initialized memory buffer either fixed or dynamic to store windows, panels and tables
/// __font__ | Must point to a previously initialized font handle for more info look at font documentation
///
/// Returns either `false(0)` on failure or `true(1)` on success.
*/
NK_API nk_bool nk_init_custom(struct nk_context*, struct nk_buffer *cmds, struct nk_buffer *pool, const struct nk_user_font*);
/*/// #### nk_clear
/// Resets the context state at the end of the frame. This includes mostly
/// garbage collector tasks like removing windows or table not called and therefore
/// used anymore.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_clear(struct nk_context *ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to a previously initialized `nk_context` struct
*/
NK_API void nk_clear(struct nk_context*);
/*/// #### nk_free
/// Frees all memory allocated by nuklear. Not needed if context was
/// initialized with `nk_init_fixed`.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_free(struct nk_context *ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to a previously initialized `nk_context` struct
*/
NK_API void nk_free(struct nk_context*);
#ifdef NK_INCLUDE_COMMAND_USERDATA
/*/// #### nk_set_user_data
/// Sets the currently passed userdata passed down into each draw command.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_set_user_data(struct nk_context *ctx, nk_handle data);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|--------------------------------------------------------------
/// __ctx__ | Must point to a previously initialized `nk_context` struct
/// __data__ | Handle with either pointer or index to be passed into every draw commands
*/
NK_API void nk_set_user_data(struct nk_context*, nk_handle handle);
#endif
/* =============================================================================
*
* INPUT
*
* =============================================================================*/
/*/// ### Input
/// The input API is responsible for holding the current input state composed of
/// mouse, key and text input states.
/// It is worth noting that no direct OS or window handling is done in nuklear.
/// Instead all input state has to be provided by platform specific code. This on one hand
/// expects more work from the user and complicates usage but on the other hand
/// provides simple abstraction over a big number of platforms, libraries and other
/// already provided functionality.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_input_begin(&ctx);
/// while (GetEvent(&evt)) {
/// if (evt.type == MOUSE_MOVE)
/// nk_input_motion(&ctx, evt.motion.x, evt.motion.y);
/// else if (evt.type == [...]) {
/// // [...]
/// }
/// } nk_input_end(&ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// #### Usage
/// Input state needs to be provided to nuklear by first calling `nk_input_begin`
/// which resets internal state like delta mouse position and button transistions.
/// After `nk_input_begin` all current input state needs to be provided. This includes
/// mouse motion, button and key pressed and released, text input and scrolling.
/// Both event- or state-based input handling are supported by this API
/// and should work without problems. Finally after all input state has been
/// mirrored `nk_input_end` needs to be called to finish input process.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// struct nk_context ctx;
/// nk_init_xxx(&ctx, ...);
/// while (1) {
/// Event evt;
/// nk_input_begin(&ctx);
/// while (GetEvent(&evt)) {
/// if (evt.type == MOUSE_MOVE)
/// nk_input_motion(&ctx, evt.motion.x, evt.motion.y);
/// else if (evt.type == [...]) {
/// // [...]
/// }
/// }
/// nk_input_end(&ctx);
/// // [...]
/// nk_clear(&ctx);
/// } nk_free(&ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// #### Reference
/// Function | Description
/// --------------------|-------------------------------------------------------
/// __nk_input_begin__ | Begins the input mirroring process. Needs to be called before all other `nk_input_xxx` calls
/// __nk_input_motion__ | Mirrors mouse cursor position
/// __nk_input_key__ | Mirrors key state with either pressed or released
/// __nk_input_button__ | Mirrors mouse button state with either pressed or released
/// __nk_input_scroll__ | Mirrors mouse scroll values
/// __nk_input_char__ | Adds a single ASCII text character into an internal text buffer
/// __nk_input_glyph__ | Adds a single multi-byte UTF-8 character into an internal text buffer
/// __nk_input_unicode__| Adds a single unicode rune into an internal text buffer
/// __nk_input_end__ | Ends the input mirroring process by calculating state changes. Don't call any `nk_input_xxx` function referenced above after this call
*/
enum nk_keys {
NK_KEY_NONE,
NK_KEY_SHIFT,
NK_KEY_CTRL,
NK_KEY_DEL,
NK_KEY_ENTER,
NK_KEY_TAB,
NK_KEY_BACKSPACE,
NK_KEY_COPY,
NK_KEY_CUT,
NK_KEY_PASTE,
NK_KEY_UP,
NK_KEY_DOWN,
NK_KEY_LEFT,
NK_KEY_RIGHT,
/* Shortcuts: text field */
NK_KEY_TEXT_INSERT_MODE,
NK_KEY_TEXT_REPLACE_MODE,
NK_KEY_TEXT_RESET_MODE,
NK_KEY_TEXT_LINE_START,
NK_KEY_TEXT_LINE_END,
NK_KEY_TEXT_START,
NK_KEY_TEXT_END,
NK_KEY_TEXT_UNDO,
NK_KEY_TEXT_REDO,
NK_KEY_TEXT_SELECT_ALL,
NK_KEY_TEXT_WORD_LEFT,
NK_KEY_TEXT_WORD_RIGHT,
/* Shortcuts: scrollbar */
NK_KEY_SCROLL_START,
NK_KEY_SCROLL_END,
NK_KEY_SCROLL_DOWN,
NK_KEY_SCROLL_UP,
NK_KEY_MAX
};
enum nk_buttons {
NK_BUTTON_LEFT,
NK_BUTTON_MIDDLE,
NK_BUTTON_RIGHT,
NK_BUTTON_DOUBLE,
NK_BUTTON_MAX
};
/*/// #### nk_input_begin
/// Begins the input mirroring process by resetting text, scroll
/// mouse, previous mouse position and movement as well as key state transitions,
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_input_begin(struct nk_context*);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to a previously initialized `nk_context` struct
*/
NK_API void nk_input_begin(struct nk_context*);
/*/// #### nk_input_motion
/// Mirrors current mouse position to nuklear
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_input_motion(struct nk_context *ctx, int x, int y);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to a previously initialized `nk_context` struct
/// __x__ | Must hold an integer describing the current mouse cursor x-position
/// __y__ | Must hold an integer describing the current mouse cursor y-position
*/
NK_API void nk_input_motion(struct nk_context*, int x, int y);
/*/// #### nk_input_key
/// Mirrors the state of a specific key to nuklear
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_input_key(struct nk_context*, enum nk_keys key, nk_bool down);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to a previously initialized `nk_context` struct
/// __key__ | Must be any value specified in enum `nk_keys` that needs to be mirrored
/// __down__ | Must be 0 for key is up and 1 for key is down
*/
NK_API void nk_input_key(struct nk_context*, enum nk_keys, nk_bool down);
/*/// #### nk_input_button
/// Mirrors the state of a specific mouse button to nuklear
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_input_button(struct nk_context *ctx, enum nk_buttons btn, int x, int y, nk_bool down);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to a previously initialized `nk_context` struct
/// __btn__ | Must be any value specified in enum `nk_buttons` that needs to be mirrored
/// __x__ | Must contain an integer describing mouse cursor x-position on click up/down
/// __y__ | Must contain an integer describing mouse cursor y-position on click up/down
/// __down__ | Must be 0 for key is up and 1 for key is down
*/
NK_API void nk_input_button(struct nk_context*, enum nk_buttons, int x, int y, nk_bool down);
/*/// #### nk_input_scroll
/// Copies the last mouse scroll value to nuklear. Is generally
/// a scroll value. So does not have to come from mouse and could also originate
/// TODO finish this sentence
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_input_scroll(struct nk_context *ctx, struct nk_vec2 val);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to a previously initialized `nk_context` struct
/// __val__ | vector with both X- as well as Y-scroll value
*/
NK_API void nk_input_scroll(struct nk_context*, struct nk_vec2 val);
/*/// #### nk_input_char
/// Copies a single ASCII character into an internal text buffer
/// This is basically a helper function to quickly push ASCII characters into
/// nuklear.
///
/// !!! Note
/// Stores up to NK_INPUT_MAX bytes between `nk_input_begin` and `nk_input_end`.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_input_char(struct nk_context *ctx, char c);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to a previously initialized `nk_context` struct
/// __c__ | Must be a single ASCII character preferable one that can be printed
*/
NK_API void nk_input_char(struct nk_context*, char);
/*/// #### nk_input_glyph
/// Converts an encoded unicode rune into UTF-8 and copies the result into an
/// internal text buffer.
///
/// !!! Note
/// Stores up to NK_INPUT_MAX bytes between `nk_input_begin` and `nk_input_end`.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_input_glyph(struct nk_context *ctx, const nk_glyph g);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to a previously initialized `nk_context` struct
/// __g__ | UTF-32 unicode codepoint
*/
NK_API void nk_input_glyph(struct nk_context*, const nk_glyph);
/*/// #### nk_input_unicode
/// Converts a unicode rune into UTF-8 and copies the result
/// into an internal text buffer.
/// !!! Note
/// Stores up to NK_INPUT_MAX bytes between `nk_input_begin` and `nk_input_end`.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_input_unicode(struct nk_context*, nk_rune rune);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to a previously initialized `nk_context` struct
/// __rune__ | UTF-32 unicode codepoint
*/
NK_API void nk_input_unicode(struct nk_context*, nk_rune);
/*/// #### nk_input_end
/// End the input mirroring process by resetting mouse grabbing
/// state to ensure the mouse cursor is not grabbed indefinitely.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_input_end(struct nk_context *ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to a previously initialized `nk_context` struct
*/
NK_API void nk_input_end(struct nk_context*);
/* =============================================================================
*
* DRAWING
*
* =============================================================================*/
/*/// ### Drawing
/// This library was designed to be render backend agnostic so it does
/// not draw anything to screen directly. Instead all drawn shapes, widgets
/// are made of, are buffered into memory and make up a command queue.
/// Each frame therefore fills the command buffer with draw commands
/// that then need to be executed by the user and his own render backend.
/// After that the command buffer needs to be cleared and a new frame can be
/// started. It is probably important to note that the command buffer is the main
/// drawing API and the optional vertex buffer API only takes this format and
/// converts it into a hardware accessible format.
///
/// #### Usage
/// To draw all draw commands accumulated over a frame you need your own render
/// backend able to draw a number of 2D primitives. This includes at least
/// filled and stroked rectangles, circles, text, lines, triangles and scissors.
/// As soon as this criterion is met you can iterate over each draw command
/// and execute each draw command in a interpreter like fashion:
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// const struct nk_command *cmd = 0;
/// nk_foreach(cmd, &ctx) {
/// switch (cmd->type) {
/// case NK_COMMAND_LINE:
/// your_draw_line_function(...)
/// break;
/// case NK_COMMAND_RECT
/// your_draw_rect_function(...)
/// break;
/// case //...:
/// //[...]
/// }
/// }
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// In program flow context draw commands need to be executed after input has been
/// gathered and the complete UI with windows and their contained widgets have
/// been executed and before calling `nk_clear` which frees all previously
/// allocated draw commands.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// struct nk_context ctx;
/// nk_init_xxx(&ctx, ...);
/// while (1) {
/// Event evt;
/// nk_input_begin(&ctx);
/// while (GetEvent(&evt)) {
/// if (evt.type == MOUSE_MOVE)
/// nk_input_motion(&ctx, evt.motion.x, evt.motion.y);
/// else if (evt.type == [...]) {
/// [...]
/// }
/// }
/// nk_input_end(&ctx);
/// //
/// // [...]
/// //
/// const struct nk_command *cmd = 0;
/// nk_foreach(cmd, &ctx) {
/// switch (cmd->type) {
/// case NK_COMMAND_LINE:
/// your_draw_line_function(...)
/// break;
/// case NK_COMMAND_RECT
/// your_draw_rect_function(...)
/// break;
/// case ...:
/// // [...]
/// }
/// nk_clear(&ctx);
/// }
/// nk_free(&ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// You probably noticed that you have to draw all of the UI each frame which is
/// quite wasteful. While the actual UI updating loop is quite fast rendering
/// without actually needing it is not. So there are multiple things you could do.
///
/// First is only update on input. This of course is only an option if your
/// application only depends on the UI and does not require any outside calculations.
/// If you actually only update on input make sure to update the UI two times each
/// frame and call `nk_clear` directly after the first pass and only draw in
/// the second pass. In addition it is recommended to also add additional timers
/// to make sure the UI is not drawn more than a fixed number of frames per second.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// struct nk_context ctx;
/// nk_init_xxx(&ctx, ...);
/// while (1) {
/// // [...wait for input ]
/// // [...do two UI passes ...]
/// do_ui(...)
/// nk_clear(&ctx);
/// do_ui(...)
/// //
/// // draw
/// const struct nk_command *cmd = 0;
/// nk_foreach(cmd, &ctx) {
/// switch (cmd->type) {
/// case NK_COMMAND_LINE:
/// your_draw_line_function(...)
/// break;
/// case NK_COMMAND_RECT
/// your_draw_rect_function(...)
/// break;
/// case ...:
/// //[...]
/// }
/// nk_clear(&ctx);
/// }
/// nk_free(&ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// The second probably more applicable trick is to only draw if anything changed.
/// It is not really useful for applications with continuous draw loop but
/// quite useful for desktop applications. To actually get nuklear to only
/// draw on changes you first have to define `NK_ZERO_COMMAND_MEMORY` and
/// allocate a memory buffer that will store each unique drawing output.
/// After each frame you compare the draw command memory inside the library
/// with your allocated buffer by memcmp. If memcmp detects differences
/// you have to copy the command buffer into the allocated buffer
/// and then draw like usual (this example uses fixed memory but you could
/// use dynamically allocated memory).
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// //[... other defines ...]
/// #define NK_ZERO_COMMAND_MEMORY
/// #include "nuklear.h"
/// //
/// // setup context
/// struct nk_context ctx;
/// void *last = calloc(1,64*1024);
/// void *buf = calloc(1,64*1024);
/// nk_init_fixed(&ctx, buf, 64*1024);
/// //
/// // loop
/// while (1) {
/// // [...input...]
/// // [...ui...]
/// void *cmds = nk_buffer_memory(&ctx.memory);
/// if (memcmp(cmds, last, ctx.memory.allocated)) {
/// memcpy(last,cmds,ctx.memory.allocated);
/// const struct nk_command *cmd = 0;
/// nk_foreach(cmd, &ctx) {
/// switch (cmd->type) {
/// case NK_COMMAND_LINE:
/// your_draw_line_function(...)
/// break;
/// case NK_COMMAND_RECT
/// your_draw_rect_function(...)
/// break;
/// case ...:
/// // [...]
/// }
/// }
/// }
/// nk_clear(&ctx);
/// }
/// nk_free(&ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Finally while using draw commands makes sense for higher abstracted platforms like
/// X11 and Win32 or drawing libraries it is often desirable to use graphics
/// hardware directly. Therefore it is possible to just define
/// `NK_INCLUDE_VERTEX_BUFFER_OUTPUT` which includes optional vertex output.
/// To access the vertex output you first have to convert all draw commands into
/// vertexes by calling `nk_convert` which takes in your preferred vertex format.
/// After successfully converting all draw commands just iterate over and execute all
/// vertex draw commands:
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// // fill configuration
/// struct your_vertex
/// {
/// float pos[2]; // important to keep it to 2 floats
/// float uv[2];
/// unsigned char col[4];
/// };
/// struct nk_convert_config cfg = {};
/// static const struct nk_draw_vertex_layout_element vertex_layout[] = {
/// {NK_VERTEX_POSITION, NK_FORMAT_FLOAT, NK_OFFSETOF(struct your_vertex, pos)},
/// {NK_VERTEX_TEXCOORD, NK_FORMAT_FLOAT, NK_OFFSETOF(struct your_vertex, uv)},
/// {NK_VERTEX_COLOR, NK_FORMAT_R8G8B8A8, NK_OFFSETOF(struct your_vertex, col)},
/// {NK_VERTEX_LAYOUT_END}
/// };
/// cfg.shape_AA = NK_ANTI_ALIASING_ON;
/// cfg.line_AA = NK_ANTI_ALIASING_ON;
/// cfg.vertex_layout = vertex_layout;
/// cfg.vertex_size = sizeof(struct your_vertex);
/// cfg.vertex_alignment = NK_ALIGNOF(struct your_vertex);
/// cfg.circle_segment_count = 22;
/// cfg.curve_segment_count = 22;
/// cfg.arc_segment_count = 22;
/// cfg.global_alpha = 1.0f;
/// cfg.null = dev->null;
/// //
/// // setup buffers and convert
/// struct nk_buffer cmds, verts, idx;
/// nk_buffer_init_default(&cmds);
/// nk_buffer_init_default(&verts);
/// nk_buffer_init_default(&idx);
/// nk_convert(&ctx, &cmds, &verts, &idx, &cfg);
/// //
/// // draw
/// nk_draw_foreach(cmd, &ctx, &cmds) {
/// if (!cmd->elem_count) continue;
/// //[...]
/// }
/// nk_buffer_free(&cms);
/// nk_buffer_free(&verts);
/// nk_buffer_free(&idx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// #### Reference
/// Function | Description
/// --------------------|-------------------------------------------------------
/// __nk__begin__ | Returns the first draw command in the context draw command list to be drawn
/// __nk__next__ | Increments the draw command iterator to the next command inside the context draw command list
/// __nk_foreach__ | Iterates over each draw command inside the context draw command list
/// __nk_convert__ | Converts from the abstract draw commands list into a hardware accessible vertex format
/// __nk_draw_begin__ | Returns the first vertex command in the context vertex draw list to be executed
/// __nk__draw_next__ | Increments the vertex command iterator to the next command inside the context vertex command list
/// __nk__draw_end__ | Returns the end of the vertex draw list
/// __nk_draw_foreach__ | Iterates over each vertex draw command inside the vertex draw list
*/
enum nk_anti_aliasing {NK_ANTI_ALIASING_OFF, NK_ANTI_ALIASING_ON};
enum nk_convert_result {
NK_CONVERT_SUCCESS = 0,
NK_CONVERT_INVALID_PARAM = 1,
NK_CONVERT_COMMAND_BUFFER_FULL = NK_FLAG(1),
NK_CONVERT_VERTEX_BUFFER_FULL = NK_FLAG(2),
NK_CONVERT_ELEMENT_BUFFER_FULL = NK_FLAG(3)
};
struct nk_draw_null_texture {
nk_handle texture; /* texture handle to a texture with a white pixel */
struct nk_vec2 uv; /* coordinates to a white pixel in the texture */
};
struct nk_convert_config {
float global_alpha; /* global alpha value */
enum nk_anti_aliasing line_AA; /* line anti-aliasing flag can be turned off if you are tight on memory */
enum nk_anti_aliasing shape_AA; /* shape anti-aliasing flag can be turned off if you are tight on memory */
unsigned circle_segment_count; /* number of segments used for circles: default to 22 */
unsigned arc_segment_count; /* number of segments used for arcs: default to 22 */
unsigned curve_segment_count; /* number of segments used for curves: default to 22 */
struct nk_draw_null_texture null; /* handle to texture with a white pixel for shape drawing */
const struct nk_draw_vertex_layout_element *vertex_layout; /* describes the vertex output format and packing */
nk_size vertex_size; /* sizeof one vertex for vertex packing */
nk_size vertex_alignment; /* vertex alignment: Can be obtained by NK_ALIGNOF */
};
/*/// #### nk__begin
/// Returns a draw command list iterator to iterate all draw
/// commands accumulated over one frame.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// const struct nk_command* nk__begin(struct nk_context*);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | must point to an previously initialized `nk_context` struct at the end of a frame
///
/// Returns draw command pointer pointing to the first command inside the draw command list
*/
NK_API const struct nk_command* nk__begin(struct nk_context*);
/*/// #### nk__next
/// Returns draw command pointer pointing to the next command inside the draw command list
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// const struct nk_command* nk__next(struct nk_context*, const struct nk_command*);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct at the end of a frame
/// __cmd__ | Must point to an previously a draw command either returned by `nk__begin` or `nk__next`
///
/// Returns draw command pointer pointing to the next command inside the draw command list
*/
NK_API const struct nk_command* nk__next(struct nk_context*, const struct nk_command*);
/*/// #### nk_foreach
/// Iterates over each draw command inside the context draw command list
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// #define nk_foreach(c, ctx)
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct at the end of a frame
/// __cmd__ | Command pointer initialized to NULL
///
/// Iterates over each draw command inside the context draw command list
*/
#define nk_foreach(c, ctx) for((c) = nk__begin(ctx); (c) != 0; (c) = nk__next(ctx,c))
#ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT
/*/// #### nk_convert
/// Converts all internal draw commands into vertex draw commands and fills
/// three buffers with vertexes, vertex draw commands and vertex indices. The vertex format
/// as well as some other configuration values have to be configured by filling out a
/// `nk_convert_config` struct.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_flags nk_convert(struct nk_context *ctx, struct nk_buffer *cmds,
/// struct nk_buffer *vertices, struct nk_buffer *elements, const struct nk_convert_config*);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct at the end of a frame
/// __cmds__ | Must point to a previously initialized buffer to hold converted vertex draw commands
/// __vertices__| Must point to a previously initialized buffer to hold all produced vertices
/// __elements__| Must point to a previously initialized buffer to hold all produced vertex indices
/// __config__ | Must point to a filled out `nk_config` struct to configure the conversion process
///
/// Returns one of enum nk_convert_result error codes
///
/// Parameter | Description
/// --------------------------------|-----------------------------------------------------------
/// NK_CONVERT_SUCCESS | Signals a successful draw command to vertex buffer conversion
/// NK_CONVERT_INVALID_PARAM | An invalid argument was passed in the function call
/// NK_CONVERT_COMMAND_BUFFER_FULL | The provided buffer for storing draw commands is full or failed to allocate more memory
/// NK_CONVERT_VERTEX_BUFFER_FULL | The provided buffer for storing vertices is full or failed to allocate more memory
/// NK_CONVERT_ELEMENT_BUFFER_FULL | The provided buffer for storing indicies is full or failed to allocate more memory
*/
NK_API nk_flags nk_convert(struct nk_context*, struct nk_buffer *cmds, struct nk_buffer *vertices, struct nk_buffer *elements, const struct nk_convert_config*);
/*/// #### nk__draw_begin
/// Returns a draw vertex command buffer iterator to iterate over the vertex draw command buffer
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// const struct nk_draw_command* nk__draw_begin(const struct nk_context*, const struct nk_buffer*);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct at the end of a frame
/// __buf__ | Must point to an previously by `nk_convert` filled out vertex draw command buffer
///
/// Returns vertex draw command pointer pointing to the first command inside the vertex draw command buffer
*/
NK_API const struct nk_draw_command* nk__draw_begin(const struct nk_context*, const struct nk_buffer*);
/*/// #### nk__draw_end
/// Returns the vertex draw command at the end of the vertex draw command buffer
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// const struct nk_draw_command* nk__draw_end(const struct nk_context *ctx, const struct nk_buffer *buf);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct at the end of a frame
/// __buf__ | Must point to an previously by `nk_convert` filled out vertex draw command buffer
///
/// Returns vertex draw command pointer pointing to the end of the last vertex draw command inside the vertex draw command buffer
*/
NK_API const struct nk_draw_command* nk__draw_end(const struct nk_context*, const struct nk_buffer*);
/*/// #### nk__draw_next
/// Increments the vertex draw command buffer iterator
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// const struct nk_draw_command* nk__draw_next(const struct nk_draw_command*, const struct nk_buffer*, const struct nk_context*);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __cmd__ | Must point to an previously either by `nk__draw_begin` or `nk__draw_next` returned vertex draw command
/// __buf__ | Must point to an previously by `nk_convert` filled out vertex draw command buffer
/// __ctx__ | Must point to an previously initialized `nk_context` struct at the end of a frame
///
/// Returns vertex draw command pointer pointing to the end of the last vertex draw command inside the vertex draw command buffer
*/
NK_API const struct nk_draw_command* nk__draw_next(const struct nk_draw_command*, const struct nk_buffer*, const struct nk_context*);
/*/// #### nk_draw_foreach
/// Iterates over each vertex draw command inside a vertex draw command buffer
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// #define nk_draw_foreach(cmd,ctx, b)
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __cmd__ | `nk_draw_command`iterator set to NULL
/// __buf__ | Must point to an previously by `nk_convert` filled out vertex draw command buffer
/// __ctx__ | Must point to an previously initialized `nk_context` struct at the end of a frame
*/
#define nk_draw_foreach(cmd,ctx, b) for((cmd)=nk__draw_begin(ctx, b); (cmd)!=0; (cmd)=nk__draw_next(cmd, b, ctx))
#endif
/* =============================================================================
*
* WINDOW
*
* =============================================================================
/// ### Window
/// Windows are the main persistent state used inside nuklear and are life time
/// controlled by simply "retouching" (i.e. calling) each window each frame.
/// All widgets inside nuklear can only be added inside the function pair `nk_begin_xxx`
/// and `nk_end`. Calling any widgets outside these two functions will result in an
/// assert in debug or no state change in release mode.<br /><br />
///
/// Each window holds frame persistent state like position, size, flags, state tables,
/// and some garbage collected internal persistent widget state. Each window
/// is linked into a window stack list which determines the drawing and overlapping
/// order. The topmost window thereby is the currently active window.<br /><br />
///
/// To change window position inside the stack occurs either automatically by
/// user input by being clicked on or programmatically by calling `nk_window_focus`.
/// Windows by default are visible unless explicitly being defined with flag
/// `NK_WINDOW_HIDDEN`, the user clicked the close button on windows with flag
/// `NK_WINDOW_CLOSABLE` or if a window was explicitly hidden by calling
/// `nk_window_show`. To explicitly close and destroy a window call `nk_window_close`.<br /><br />
///
/// #### Usage
/// To create and keep a window you have to call one of the two `nk_begin_xxx`
/// functions to start window declarations and `nk_end` at the end. Furthermore it
/// is recommended to check the return value of `nk_begin_xxx` and only process
/// widgets inside the window if the value is not 0. Either way you have to call
/// `nk_end` at the end of window declarations. Furthermore, do not attempt to
/// nest `nk_begin_xxx` calls which will hopefully result in an assert or if not
/// in a segmentation fault.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// if (nk_begin_xxx(...) {
/// // [... widgets ...]
/// }
/// nk_end(ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// In the grand concept window and widget declarations need to occur after input
/// handling and before drawing to screen. Not doing so can result in higher
/// latency or at worst invalid behavior. Furthermore make sure that `nk_clear`
/// is called at the end of the frame. While nuklear's default platform backends
/// already call `nk_clear` for you if you write your own backend not calling
/// `nk_clear` can cause asserts or even worse undefined behavior.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// struct nk_context ctx;
/// nk_init_xxx(&ctx, ...);
/// while (1) {
/// Event evt;
/// nk_input_begin(&ctx);
/// while (GetEvent(&evt)) {
/// if (evt.type == MOUSE_MOVE)
/// nk_input_motion(&ctx, evt.motion.x, evt.motion.y);
/// else if (evt.type == [...]) {
/// nk_input_xxx(...);
/// }
/// }
/// nk_input_end(&ctx);
///
/// if (nk_begin_xxx(...) {
/// //[...]
/// }
/// nk_end(ctx);
///
/// const struct nk_command *cmd = 0;
/// nk_foreach(cmd, &ctx) {
/// case NK_COMMAND_LINE:
/// your_draw_line_function(...)
/// break;
/// case NK_COMMAND_RECT
/// your_draw_rect_function(...)
/// break;
/// case //...:
/// //[...]
/// }
/// nk_clear(&ctx);
/// }
/// nk_free(&ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// #### Reference
/// Function | Description
/// ------------------------------------|----------------------------------------
/// nk_begin | Starts a new window; needs to be called every frame for every window (unless hidden) or otherwise the window gets removed
/// nk_begin_titled | Extended window start with separated title and identifier to allow multiple windows with same name but not title
/// nk_end | Needs to be called at the end of the window building process to process scaling, scrollbars and general cleanup
//
/// nk_window_find | Finds and returns the window with give name
/// nk_window_get_bounds | Returns a rectangle with screen position and size of the currently processed window.
/// nk_window_get_position | Returns the position of the currently processed window
/// nk_window_get_size | Returns the size with width and height of the currently processed window
/// nk_window_get_width | Returns the width of the currently processed window
/// nk_window_get_height | Returns the height of the currently processed window
/// nk_window_get_panel | Returns the underlying panel which contains all processing state of the current window
/// nk_window_get_content_region | Returns the position and size of the currently visible and non-clipped space inside the currently processed window
/// nk_window_get_content_region_min | Returns the upper rectangle position of the currently visible and non-clipped space inside the currently processed window
/// nk_window_get_content_region_max | Returns the upper rectangle position of the currently visible and non-clipped space inside the currently processed window
/// nk_window_get_content_region_size | Returns the size of the currently visible and non-clipped space inside the currently processed window
/// nk_window_get_canvas | Returns the draw command buffer. Can be used to draw custom widgets
/// nk_window_get_scroll | Gets the scroll offset of the current window
/// nk_window_has_focus | Returns if the currently processed window is currently active
/// nk_window_is_collapsed | Returns if the window with given name is currently minimized/collapsed
/// nk_window_is_closed | Returns if the currently processed window was closed
/// nk_window_is_hidden | Returns if the currently processed window was hidden
/// nk_window_is_active | Same as nk_window_has_focus for some reason
/// nk_window_is_hovered | Returns if the currently processed window is currently being hovered by mouse
/// nk_window_is_any_hovered | Return if any window currently hovered
/// nk_item_is_any_active | Returns if any window or widgets is currently hovered or active
//
/// nk_window_set_bounds | Updates position and size of the currently processed window
/// nk_window_set_position | Updates position of the currently process window
/// nk_window_set_size | Updates the size of the currently processed window
/// nk_window_set_focus | Set the currently processed window as active window
/// nk_window_set_scroll | Sets the scroll offset of the current window
//
/// nk_window_close | Closes the window with given window name which deletes the window at the end of the frame
/// nk_window_collapse | Collapses the window with given window name
/// nk_window_collapse_if | Collapses the window with given window name if the given condition was met
/// nk_window_show | Hides a visible or reshows a hidden window
/// nk_window_show_if | Hides/shows a window depending on condition
*/
/*
/// #### nk_panel_flags
/// Flag | Description
/// ----------------------------|----------------------------------------
/// NK_WINDOW_BORDER | Draws a border around the window to visually separate window from the background
/// NK_WINDOW_MOVABLE | The movable flag indicates that a window can be moved by user input or by dragging the window header
/// NK_WINDOW_SCALABLE | The scalable flag indicates that a window can be scaled by user input by dragging a scaler icon at the button of the window
/// NK_WINDOW_CLOSABLE | Adds a closable icon into the header
/// NK_WINDOW_MINIMIZABLE | Adds a minimize icon into the header
/// NK_WINDOW_NO_SCROLLBAR | Removes the scrollbar from the window
/// NK_WINDOW_TITLE | Forces a header at the top at the window showing the title
/// NK_WINDOW_SCROLL_AUTO_HIDE | Automatically hides the window scrollbar if no user interaction: also requires delta time in `nk_context` to be set each frame
/// NK_WINDOW_BACKGROUND | Always keep window in the background
/// NK_WINDOW_SCALE_LEFT | Puts window scaler in the left-bottom corner instead right-bottom
/// NK_WINDOW_NO_INPUT | Prevents window of scaling, moving or getting focus
///
/// #### nk_collapse_states
/// State | Description
/// ----------------|-----------------------------------------------------------
/// __NK_MINIMIZED__| UI section is collased and not visibile until maximized
/// __NK_MAXIMIZED__| UI section is extended and visibile until minimized
/// <br /><br />
*/
enum nk_panel_flags {
NK_WINDOW_BORDER = NK_FLAG(0),
NK_WINDOW_MOVABLE = NK_FLAG(1),
NK_WINDOW_SCALABLE = NK_FLAG(2),
NK_WINDOW_CLOSABLE = NK_FLAG(3),
NK_WINDOW_MINIMIZABLE = NK_FLAG(4),
NK_WINDOW_NO_SCROLLBAR = NK_FLAG(5),
NK_WINDOW_TITLE = NK_FLAG(6),
NK_WINDOW_SCROLL_AUTO_HIDE = NK_FLAG(7),
NK_WINDOW_BACKGROUND = NK_FLAG(8),
NK_WINDOW_SCALE_LEFT = NK_FLAG(9),
NK_WINDOW_NO_INPUT = NK_FLAG(10)
};
/*/// #### nk_begin
/// Starts a new window; needs to be called every frame for every
/// window (unless hidden) or otherwise the window gets removed
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_bool nk_begin(struct nk_context *ctx, const char *title, struct nk_rect bounds, nk_flags flags);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __title__ | Window title and identifier. Needs to be persistent over frames to identify the window
/// __bounds__ | Initial position and window size. However if you do not define `NK_WINDOW_SCALABLE` or `NK_WINDOW_MOVABLE` you can set window position and size every frame
/// __flags__ | Window flags defined in the nk_panel_flags section with a number of different window behaviors
///
/// Returns `true(1)` if the window can be filled up with widgets from this point
/// until `nk_end` or `false(0)` otherwise for example if minimized
*/
NK_API nk_bool nk_begin(struct nk_context *ctx, const char *title, struct nk_rect bounds, nk_flags flags);
/*/// #### nk_begin_titled
/// Extended window start with separated title and identifier to allow multiple
/// windows with same title but not name
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_bool nk_begin_titled(struct nk_context *ctx, const char *name, const char *title, struct nk_rect bounds, nk_flags flags);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __name__ | Window identifier. Needs to be persistent over frames to identify the window
/// __title__ | Window title displayed inside header if flag `NK_WINDOW_TITLE` or either `NK_WINDOW_CLOSABLE` or `NK_WINDOW_MINIMIZED` was set
/// __bounds__ | Initial position and window size. However if you do not define `NK_WINDOW_SCALABLE` or `NK_WINDOW_MOVABLE` you can set window position and size every frame
/// __flags__ | Window flags defined in the nk_panel_flags section with a number of different window behaviors
///
/// Returns `true(1)` if the window can be filled up with widgets from this point
/// until `nk_end` or `false(0)` otherwise for example if minimized
*/
NK_API nk_bool nk_begin_titled(struct nk_context *ctx, const char *name, const char *title, struct nk_rect bounds, nk_flags flags);
/*/// #### nk_end
/// Needs to be called at the end of the window building process to process scaling, scrollbars and general cleanup.
/// All widget calls after this functions will result in asserts or no state changes
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_end(struct nk_context *ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
*/
NK_API void nk_end(struct nk_context *ctx);
/*/// #### nk_window_find
/// Finds and returns a window from passed name
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// struct nk_window *nk_window_find(struct nk_context *ctx, const char *name);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __name__ | Window identifier
///
/// Returns a `nk_window` struct pointing to the identified window or NULL if
/// no window with the given name was found
*/
NK_API struct nk_window *nk_window_find(struct nk_context *ctx, const char *name);
/*/// #### nk_window_get_bounds
/// Returns a rectangle with screen position and size of the currently processed window
///
/// !!! WARNING
/// Only call this function between calls `nk_begin_xxx` and `nk_end`
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// struct nk_rect nk_window_get_bounds(const struct nk_context *ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
///
/// Returns a `nk_rect` struct with window upper left window position and size
*/
NK_API struct nk_rect nk_window_get_bounds(const struct nk_context *ctx);
/*/// #### nk_window_get_position
/// Returns the position of the currently processed window.
///
/// !!! WARNING
/// Only call this function between calls `nk_begin_xxx` and `nk_end`
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// struct nk_vec2 nk_window_get_position(const struct nk_context *ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
///
/// Returns a `nk_vec2` struct with window upper left position
*/
NK_API struct nk_vec2 nk_window_get_position(const struct nk_context *ctx);
/*/// #### nk_window_get_size
/// Returns the size with width and height of the currently processed window.
///
/// !!! WARNING
/// Only call this function between calls `nk_begin_xxx` and `nk_end`
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// struct nk_vec2 nk_window_get_size(const struct nk_context *ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
///
/// Returns a `nk_vec2` struct with window width and height
*/
NK_API struct nk_vec2 nk_window_get_size(const struct nk_context*);
/*/// #### nk_window_get_width
/// Returns the width of the currently processed window.
///
/// !!! WARNING
/// Only call this function between calls `nk_begin_xxx` and `nk_end`
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// float nk_window_get_width(const struct nk_context *ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
///
/// Returns the current window width
*/
NK_API float nk_window_get_width(const struct nk_context*);
/*/// #### nk_window_get_height
/// Returns the height of the currently processed window.
///
/// !!! WARNING
/// Only call this function between calls `nk_begin_xxx` and `nk_end`
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// float nk_window_get_height(const struct nk_context *ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
///
/// Returns the current window height
*/
NK_API float nk_window_get_height(const struct nk_context*);
/*/// #### nk_window_get_panel
/// Returns the underlying panel which contains all processing state of the current window.
///
/// !!! WARNING
/// Only call this function between calls `nk_begin_xxx` and `nk_end`
/// !!! WARNING
/// Do not keep the returned panel pointer around, it is only valid until `nk_end`
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// struct nk_panel* nk_window_get_panel(struct nk_context *ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
///
/// Returns a pointer to window internal `nk_panel` state.
*/
NK_API struct nk_panel* nk_window_get_panel(struct nk_context*);
/*/// #### nk_window_get_content_region
/// Returns the position and size of the currently visible and non-clipped space
/// inside the currently processed window.
///
/// !!! WARNING
/// Only call this function between calls `nk_begin_xxx` and `nk_end`
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// struct nk_rect nk_window_get_content_region(struct nk_context *ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
///
/// Returns `nk_rect` struct with screen position and size (no scrollbar offset)
/// of the visible space inside the current window
*/
NK_API struct nk_rect nk_window_get_content_region(struct nk_context*);
/*/// #### nk_window_get_content_region_min
/// Returns the upper left position of the currently visible and non-clipped
/// space inside the currently processed window.
///
/// !!! WARNING
/// Only call this function between calls `nk_begin_xxx` and `nk_end`
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// struct nk_vec2 nk_window_get_content_region_min(struct nk_context *ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
///
/// returns `nk_vec2` struct with upper left screen position (no scrollbar offset)
/// of the visible space inside the current window
*/
NK_API struct nk_vec2 nk_window_get_content_region_min(struct nk_context*);
/*/// #### nk_window_get_content_region_max
/// Returns the lower right screen position of the currently visible and
/// non-clipped space inside the currently processed window.
///
/// !!! WARNING
/// Only call this function between calls `nk_begin_xxx` and `nk_end`
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// struct nk_vec2 nk_window_get_content_region_max(struct nk_context *ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
///
/// Returns `nk_vec2` struct with lower right screen position (no scrollbar offset)
/// of the visible space inside the current window
*/
NK_API struct nk_vec2 nk_window_get_content_region_max(struct nk_context*);
/*/// #### nk_window_get_content_region_size
/// Returns the size of the currently visible and non-clipped space inside the
/// currently processed window
///
/// !!! WARNING
/// Only call this function between calls `nk_begin_xxx` and `nk_end`
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// struct nk_vec2 nk_window_get_content_region_size(struct nk_context *ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
///
/// Returns `nk_vec2` struct with size the visible space inside the current window
*/
NK_API struct nk_vec2 nk_window_get_content_region_size(struct nk_context*);
/*/// #### nk_window_get_canvas
/// Returns the draw command buffer. Can be used to draw custom widgets
/// !!! WARNING
/// Only call this function between calls `nk_begin_xxx` and `nk_end`
/// !!! WARNING
/// Do not keep the returned command buffer pointer around it is only valid until `nk_end`
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// struct nk_command_buffer* nk_window_get_canvas(struct nk_context *ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
///
/// Returns a pointer to window internal `nk_command_buffer` struct used as
/// drawing canvas. Can be used to do custom drawing.
*/
NK_API struct nk_command_buffer* nk_window_get_canvas(struct nk_context*);
/*/// #### nk_window_get_scroll
/// Gets the scroll offset for the current window
/// !!! WARNING
/// Only call this function between calls `nk_begin_xxx` and `nk_end`
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_window_get_scroll(struct nk_context *ctx, nk_uint *offset_x, nk_uint *offset_y);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// -------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __offset_x__ | A pointer to the x offset output (or NULL to ignore)
/// __offset_y__ | A pointer to the y offset output (or NULL to ignore)
*/
NK_API void nk_window_get_scroll(struct nk_context*, nk_uint *offset_x, nk_uint *offset_y);
/*/// #### nk_window_has_focus
/// Returns if the currently processed window is currently active
/// !!! WARNING
/// Only call this function between calls `nk_begin_xxx` and `nk_end`
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_bool nk_window_has_focus(const struct nk_context *ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
///
/// Returns `false(0)` if current window is not active or `true(1)` if it is
*/
NK_API nk_bool nk_window_has_focus(const struct nk_context*);
/*/// #### nk_window_is_hovered
/// Return if the current window is being hovered
/// !!! WARNING
/// Only call this function between calls `nk_begin_xxx` and `nk_end`
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_bool nk_window_is_hovered(struct nk_context *ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
///
/// Returns `true(1)` if current window is hovered or `false(0)` otherwise
*/
NK_API nk_bool nk_window_is_hovered(struct nk_context*);
/*/// #### nk_window_is_collapsed
/// Returns if the window with given name is currently minimized/collapsed
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_bool nk_window_is_collapsed(struct nk_context *ctx, const char *name);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __name__ | Identifier of window you want to check if it is collapsed
///
/// Returns `true(1)` if current window is minimized and `false(0)` if window not
/// found or is not minimized
*/
NK_API nk_bool nk_window_is_collapsed(struct nk_context *ctx, const char *name);
/*/// #### nk_window_is_closed
/// Returns if the window with given name was closed by calling `nk_close`
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_bool nk_window_is_closed(struct nk_context *ctx, const char *name);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __name__ | Identifier of window you want to check if it is closed
///
/// Returns `true(1)` if current window was closed or `false(0)` window not found or not closed
*/
NK_API nk_bool nk_window_is_closed(struct nk_context*, const char*);
/*/// #### nk_window_is_hidden
/// Returns if the window with given name is hidden
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_bool nk_window_is_hidden(struct nk_context *ctx, const char *name);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __name__ | Identifier of window you want to check if it is hidden
///
/// Returns `true(1)` if current window is hidden or `false(0)` window not found or visible
*/
NK_API nk_bool nk_window_is_hidden(struct nk_context*, const char*);
/*/// #### nk_window_is_active
/// Same as nk_window_has_focus for some reason
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_bool nk_window_is_active(struct nk_context *ctx, const char *name);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __name__ | Identifier of window you want to check if it is active
///
/// Returns `true(1)` if current window is active or `false(0)` window not found or not active
*/
NK_API nk_bool nk_window_is_active(struct nk_context*, const char*);
/*/// #### nk_window_is_any_hovered
/// Returns if the any window is being hovered
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_bool nk_window_is_any_hovered(struct nk_context*);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
///
/// Returns `true(1)` if any window is hovered or `false(0)` otherwise
*/
NK_API nk_bool nk_window_is_any_hovered(struct nk_context*);
/*/// #### nk_item_is_any_active
/// Returns if the any window is being hovered or any widget is currently active.
/// Can be used to decide if input should be processed by UI or your specific input handling.
/// Example could be UI and 3D camera to move inside a 3D space.
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_bool nk_item_is_any_active(struct nk_context*);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
///
/// Returns `true(1)` if any window is hovered or any item is active or `false(0)` otherwise
*/
NK_API nk_bool nk_item_is_any_active(struct nk_context*);
/*/// #### nk_window_set_bounds
/// Updates position and size of window with passed in name
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_window_set_bounds(struct nk_context*, const char *name, struct nk_rect bounds);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __name__ | Identifier of the window to modify both position and size
/// __bounds__ | Must point to a `nk_rect` struct with the new position and size
*/
NK_API void nk_window_set_bounds(struct nk_context*, const char *name, struct nk_rect bounds);
/*/// #### nk_window_set_position
/// Updates position of window with passed name
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_window_set_position(struct nk_context*, const char *name, struct nk_vec2 pos);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __name__ | Identifier of the window to modify both position
/// __pos__ | Must point to a `nk_vec2` struct with the new position
*/
NK_API void nk_window_set_position(struct nk_context*, const char *name, struct nk_vec2 pos);
/*/// #### nk_window_set_size
/// Updates size of window with passed in name
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_window_set_size(struct nk_context*, const char *name, struct nk_vec2);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __name__ | Identifier of the window to modify both window size
/// __size__ | Must point to a `nk_vec2` struct with new window size
*/
NK_API void nk_window_set_size(struct nk_context*, const char *name, struct nk_vec2);
/*/// #### nk_window_set_focus
/// Sets the window with given name as active
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_window_set_focus(struct nk_context*, const char *name);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __name__ | Identifier of the window to set focus on
*/
NK_API void nk_window_set_focus(struct nk_context*, const char *name);
/*/// #### nk_window_set_scroll
/// Sets the scroll offset for the current window
/// !!! WARNING
/// Only call this function between calls `nk_begin_xxx` and `nk_end`
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_window_set_scroll(struct nk_context *ctx, nk_uint offset_x, nk_uint offset_y);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// -------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __offset_x__ | The x offset to scroll to
/// __offset_y__ | The y offset to scroll to
*/
NK_API void nk_window_set_scroll(struct nk_context*, nk_uint offset_x, nk_uint offset_y);
/*/// #### nk_window_close
/// Closes a window and marks it for being freed at the end of the frame
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_window_close(struct nk_context *ctx, const char *name);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __name__ | Identifier of the window to close
*/
NK_API void nk_window_close(struct nk_context *ctx, const char *name);
/*/// #### nk_window_collapse
/// Updates collapse state of a window with given name
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_window_collapse(struct nk_context*, const char *name, enum nk_collapse_states state);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __name__ | Identifier of the window to close
/// __state__ | value out of nk_collapse_states section
*/
NK_API void nk_window_collapse(struct nk_context*, const char *name, enum nk_collapse_states state);
/*/// #### nk_window_collapse_if
/// Updates collapse state of a window with given name if given condition is met
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_window_collapse_if(struct nk_context*, const char *name, enum nk_collapse_states, int cond);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __name__ | Identifier of the window to either collapse or maximize
/// __state__ | value out of nk_collapse_states section the window should be put into
/// __cond__ | condition that has to be met to actually commit the collapse state change
*/
NK_API void nk_window_collapse_if(struct nk_context*, const char *name, enum nk_collapse_states, int cond);
/*/// #### nk_window_show
/// updates visibility state of a window with given name
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_window_show(struct nk_context*, const char *name, enum nk_show_states);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __name__ | Identifier of the window to either collapse or maximize
/// __state__ | state with either visible or hidden to modify the window with
*/
NK_API void nk_window_show(struct nk_context*, const char *name, enum nk_show_states);
/*/// #### nk_window_show_if
/// Updates visibility state of a window with given name if a given condition is met
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_window_show_if(struct nk_context*, const char *name, enum nk_show_states, int cond);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __name__ | Identifier of the window to either hide or show
/// __state__ | state with either visible or hidden to modify the window with
/// __cond__ | condition that has to be met to actually commit the visbility state change
*/
NK_API void nk_window_show_if(struct nk_context*, const char *name, enum nk_show_states, int cond);
/* =============================================================================
*
* LAYOUT
*
* =============================================================================
/// ### Layouting
/// Layouting in general describes placing widget inside a window with position and size.
/// While in this particular implementation there are five different APIs for layouting
/// each with different trade offs between control and ease of use. <br /><br />
///
/// All layouting methods in this library are based around the concept of a row.
/// A row has a height the window content grows by and a number of columns and each
/// layouting method specifies how each widget is placed inside the row.
/// After a row has been allocated by calling a layouting functions and then
/// filled with widgets will advance an internal pointer over the allocated row. <br /><br />
///
/// To actually define a layout you just call the appropriate layouting function
/// and each subsequent widget call will place the widget as specified. Important
/// here is that if you define more widgets then columns defined inside the layout
/// functions it will allocate the next row without you having to make another layouting <br /><br />
/// call.
///
/// Biggest limitation with using all these APIs outside the `nk_layout_space_xxx` API
/// is that you have to define the row height for each. However the row height
/// often depends on the height of the font. <br /><br />
///
/// To fix that internally nuklear uses a minimum row height that is set to the
/// height plus padding of currently active font and overwrites the row height
/// value if zero. <br /><br />
///
/// If you manually want to change the minimum row height then
/// use nk_layout_set_min_row_height, and use nk_layout_reset_min_row_height to
/// reset it back to be derived from font height. <br /><br />
///
/// Also if you change the font in nuklear it will automatically change the minimum
/// row height for you and. This means if you change the font but still want
/// a minimum row height smaller than the font you have to repush your value. <br /><br />
///
/// For actually more advanced UI I would even recommend using the `nk_layout_space_xxx`
/// layouting method in combination with a cassowary constraint solver (there are
/// some versions on github with permissive license model) to take over all control over widget
/// layouting yourself. However for quick and dirty layouting using all the other layouting
/// functions should be fine.
///
/// #### Usage
/// 1. __nk_layout_row_dynamic__<br /><br />
/// The easiest layouting function is `nk_layout_row_dynamic`. It provides each
/// widgets with same horizontal space inside the row and dynamically grows
/// if the owning window grows in width. So the number of columns dictates
/// the size of each widget dynamically by formula:
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// widget_width = (window_width - padding - spacing) * (1/colum_count)
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Just like all other layouting APIs if you define more widget than columns this
/// library will allocate a new row and keep all layouting parameters previously
/// defined.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// if (nk_begin_xxx(...) {
/// // first row with height: 30 composed of two widgets
/// nk_layout_row_dynamic(&ctx, 30, 2);
/// nk_widget(...);
/// nk_widget(...);
/// //
/// // second row with same parameter as defined above
/// nk_widget(...);
/// nk_widget(...);
/// //
/// // third row uses 0 for height which will use auto layouting
/// nk_layout_row_dynamic(&ctx, 0, 2);
/// nk_widget(...);
/// nk_widget(...);
/// }
/// nk_end(...);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// 2. __nk_layout_row_static__<br /><br />
/// Another easy layouting function is `nk_layout_row_static`. It provides each
/// widget with same horizontal pixel width inside the row and does not grow
/// if the owning window scales smaller or bigger.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// if (nk_begin_xxx(...) {
/// // first row with height: 30 composed of two widgets with width: 80
/// nk_layout_row_static(&ctx, 30, 80, 2);
/// nk_widget(...);
/// nk_widget(...);
/// //
/// // second row with same parameter as defined above
/// nk_widget(...);
/// nk_widget(...);
/// //
/// // third row uses 0 for height which will use auto layouting
/// nk_layout_row_static(&ctx, 0, 80, 2);
/// nk_widget(...);
/// nk_widget(...);
/// }
/// nk_end(...);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// 3. __nk_layout_row_xxx__<br /><br />
/// A little bit more advanced layouting API are functions `nk_layout_row_begin`,
/// `nk_layout_row_push` and `nk_layout_row_end`. They allow to directly
/// specify each column pixel or window ratio in a row. It supports either
/// directly setting per column pixel width or widget window ratio but not
/// both. Furthermore it is a immediate mode API so each value is directly
/// pushed before calling a widget. Therefore the layout is not automatically
/// repeating like the last two layouting functions.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// if (nk_begin_xxx(...) {
/// // first row with height: 25 composed of two widgets with width 60 and 40
/// nk_layout_row_begin(ctx, NK_STATIC, 25, 2);
/// nk_layout_row_push(ctx, 60);
/// nk_widget(...);
/// nk_layout_row_push(ctx, 40);
/// nk_widget(...);
/// nk_layout_row_end(ctx);
/// //
/// // second row with height: 25 composed of two widgets with window ratio 0.25 and 0.75
/// nk_layout_row_begin(ctx, NK_DYNAMIC, 25, 2);
/// nk_layout_row_push(ctx, 0.25f);
/// nk_widget(...);
/// nk_layout_row_push(ctx, 0.75f);
/// nk_widget(...);
/// nk_layout_row_end(ctx);
/// //
/// // third row with auto generated height: composed of two widgets with window ratio 0.25 and 0.75
/// nk_layout_row_begin(ctx, NK_DYNAMIC, 0, 2);
/// nk_layout_row_push(ctx, 0.25f);
/// nk_widget(...);
/// nk_layout_row_push(ctx, 0.75f);
/// nk_widget(...);
/// nk_layout_row_end(ctx);
/// }
/// nk_end(...);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// 4. __nk_layout_row__<br /><br />
/// The array counterpart to API nk_layout_row_xxx is the single nk_layout_row
/// functions. Instead of pushing either pixel or window ratio for every widget
/// it allows to define it by array. The trade of for less control is that
/// `nk_layout_row` is automatically repeating. Otherwise the behavior is the
/// same.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// if (nk_begin_xxx(...) {
/// // two rows with height: 30 composed of two widgets with width 60 and 40
/// const float size[] = {60,40};
/// nk_layout_row(ctx, NK_STATIC, 30, 2, ratio);
/// nk_widget(...);
/// nk_widget(...);
/// nk_widget(...);
/// nk_widget(...);
/// //
/// // two rows with height: 30 composed of two widgets with window ratio 0.25 and 0.75
/// const float ratio[] = {0.25, 0.75};
/// nk_layout_row(ctx, NK_DYNAMIC, 30, 2, ratio);
/// nk_widget(...);
/// nk_widget(...);
/// nk_widget(...);
/// nk_widget(...);
/// //
/// // two rows with auto generated height composed of two widgets with window ratio 0.25 and 0.75
/// const float ratio[] = {0.25, 0.75};
/// nk_layout_row(ctx, NK_DYNAMIC, 30, 2, ratio);
/// nk_widget(...);
/// nk_widget(...);
/// nk_widget(...);
/// nk_widget(...);
/// }
/// nk_end(...);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// 5. __nk_layout_row_template_xxx__<br /><br />
/// The most complex and second most flexible API is a simplified flexbox version without
/// line wrapping and weights for dynamic widgets. It is an immediate mode API but
/// unlike `nk_layout_row_xxx` it has auto repeat behavior and needs to be called
/// before calling the templated widgets.
/// The row template layout has three different per widget size specifier. The first
/// one is the `nk_layout_row_template_push_static` with fixed widget pixel width.
/// They do not grow if the row grows and will always stay the same.
/// The second size specifier is `nk_layout_row_template_push_variable`
/// which defines a minimum widget size but it also can grow if more space is available
/// not taken by other widgets.
/// Finally there are dynamic widgets with `nk_layout_row_template_push_dynamic`
/// which are completely flexible and unlike variable widgets can even shrink
/// to zero if not enough space is provided.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// if (nk_begin_xxx(...) {
/// // two rows with height: 30 composed of three widgets
/// nk_layout_row_template_begin(ctx, 30);
/// nk_layout_row_template_push_dynamic(ctx);
/// nk_layout_row_template_push_variable(ctx, 80);
/// nk_layout_row_template_push_static(ctx, 80);
/// nk_layout_row_template_end(ctx);
/// //
/// // first row
/// nk_widget(...); // dynamic widget can go to zero if not enough space
/// nk_widget(...); // variable widget with min 80 pixel but can grow bigger if enough space
/// nk_widget(...); // static widget with fixed 80 pixel width
/// //
/// // second row same layout
/// nk_widget(...);
/// nk_widget(...);
/// nk_widget(...);
/// }
/// nk_end(...);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// 6. __nk_layout_space_xxx__<br /><br />
/// Finally the most flexible API directly allows you to place widgets inside the
/// window. The space layout API is an immediate mode API which does not support
/// row auto repeat and directly sets position and size of a widget. Position
/// and size hereby can be either specified as ratio of allocated space or
/// allocated space local position and pixel size. Since this API is quite
/// powerful there are a number of utility functions to get the available space
/// and convert between local allocated space and screen space.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// if (nk_begin_xxx(...) {
/// // static row with height: 500 (you can set column count to INT_MAX if you don't want to be bothered)
/// nk_layout_space_begin(ctx, NK_STATIC, 500, INT_MAX);
/// nk_layout_space_push(ctx, nk_rect(0,0,150,200));
/// nk_widget(...);
/// nk_layout_space_push(ctx, nk_rect(200,200,100,200));
/// nk_widget(...);
/// nk_layout_space_end(ctx);
/// //
/// // dynamic row with height: 500 (you can set column count to INT_MAX if you don't want to be bothered)
/// nk_layout_space_begin(ctx, NK_DYNAMIC, 500, INT_MAX);
/// nk_layout_space_push(ctx, nk_rect(0.5,0.5,0.1,0.1));
/// nk_widget(...);
/// nk_layout_space_push(ctx, nk_rect(0.7,0.6,0.1,0.1));
/// nk_widget(...);
/// }
/// nk_end(...);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// #### Reference
/// Function | Description
/// ----------------------------------------|------------------------------------
/// nk_layout_set_min_row_height | Set the currently used minimum row height to a specified value
/// nk_layout_reset_min_row_height | Resets the currently used minimum row height to font height
/// nk_layout_widget_bounds | Calculates current width a static layout row can fit inside a window
/// nk_layout_ratio_from_pixel | Utility functions to calculate window ratio from pixel size
//
/// nk_layout_row_dynamic | Current layout is divided into n same sized growing columns
/// nk_layout_row_static | Current layout is divided into n same fixed sized columns
/// nk_layout_row_begin | Starts a new row with given height and number of columns
/// nk_layout_row_push | Pushes another column with given size or window ratio
/// nk_layout_row_end | Finished previously started row
/// nk_layout_row | Specifies row columns in array as either window ratio or size
//
/// nk_layout_row_template_begin | Begins the row template declaration
/// nk_layout_row_template_push_dynamic | Adds a dynamic column that dynamically grows and can go to zero if not enough space
/// nk_layout_row_template_push_variable | Adds a variable column that dynamically grows but does not shrink below specified pixel width
/// nk_layout_row_template_push_static | Adds a static column that does not grow and will always have the same size
/// nk_layout_row_template_end | Marks the end of the row template
//
/// nk_layout_space_begin | Begins a new layouting space that allows to specify each widgets position and size
/// nk_layout_space_push | Pushes position and size of the next widget in own coordinate space either as pixel or ratio
/// nk_layout_space_end | Marks the end of the layouting space
//
/// nk_layout_space_bounds | Callable after nk_layout_space_begin and returns total space allocated
/// nk_layout_space_to_screen | Converts vector from nk_layout_space coordinate space into screen space
/// nk_layout_space_to_local | Converts vector from screen space into nk_layout_space coordinates
/// nk_layout_space_rect_to_screen | Converts rectangle from nk_layout_space coordinate space into screen space
/// nk_layout_space_rect_to_local | Converts rectangle from screen space into nk_layout_space coordinates
*/
/*/// #### nk_layout_set_min_row_height
/// Sets the currently used minimum row height.
/// !!! WARNING
/// The passed height needs to include both your preferred row height
/// as well as padding. No internal padding is added.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_layout_set_min_row_height(struct nk_context*, float height);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
/// __height__ | New minimum row height to be used for auto generating the row height
*/
NK_API void nk_layout_set_min_row_height(struct nk_context*, float height);
/*/// #### nk_layout_reset_min_row_height
/// Reset the currently used minimum row height back to `font_height + text_padding + padding`
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_layout_reset_min_row_height(struct nk_context*);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
*/
NK_API void nk_layout_reset_min_row_height(struct nk_context*);
/*/// #### nk_layout_widget_bounds
/// Returns the width of the next row allocate by one of the layouting functions
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// struct nk_rect nk_layout_widget_bounds(struct nk_context*);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
///
/// Return `nk_rect` with both position and size of the next row
*/
NK_API struct nk_rect nk_layout_widget_bounds(struct nk_context*);
/*/// #### nk_layout_ratio_from_pixel
/// Utility functions to calculate window ratio from pixel size
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// float nk_layout_ratio_from_pixel(struct nk_context*, float pixel_width);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
/// __pixel__ | Pixel_width to convert to window ratio
///
/// Returns `nk_rect` with both position and size of the next row
*/
NK_API float nk_layout_ratio_from_pixel(struct nk_context*, float pixel_width);
/*/// #### nk_layout_row_dynamic
/// Sets current row layout to share horizontal space
/// between @cols number of widgets evenly. Once called all subsequent widget
/// calls greater than @cols will allocate a new row with same layout.
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_layout_row_dynamic(struct nk_context *ctx, float height, int cols);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
/// __height__ | Holds height of each widget in row or zero for auto layouting
/// __columns__ | Number of widget inside row
*/
NK_API void nk_layout_row_dynamic(struct nk_context *ctx, float height, int cols);
/*/// #### nk_layout_row_static
/// Sets current row layout to fill @cols number of widgets
/// in row with same @item_width horizontal size. Once called all subsequent widget
/// calls greater than @cols will allocate a new row with same layout.
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_layout_row_static(struct nk_context *ctx, float height, int item_width, int cols);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
/// __height__ | Holds height of each widget in row or zero for auto layouting
/// __width__ | Holds pixel width of each widget in the row
/// __columns__ | Number of widget inside row
*/
NK_API void nk_layout_row_static(struct nk_context *ctx, float height, int item_width, int cols);
/*/// #### nk_layout_row_begin
/// Starts a new dynamic or fixed row with given height and columns.
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_layout_row_begin(struct nk_context *ctx, enum nk_layout_format fmt, float row_height, int cols);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
/// __fmt__ | either `NK_DYNAMIC` for window ratio or `NK_STATIC` for fixed size columns
/// __height__ | holds height of each widget in row or zero for auto layouting
/// __columns__ | Number of widget inside row
*/
NK_API void nk_layout_row_begin(struct nk_context *ctx, enum nk_layout_format fmt, float row_height, int cols);
/*/// #### nk_layout_row_push
/// Specifies either window ratio or width of a single column
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_layout_row_push(struct nk_context*, float value);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
/// __value__ | either a window ratio or fixed width depending on @fmt in previous `nk_layout_row_begin` call
*/
NK_API void nk_layout_row_push(struct nk_context*, float value);
/*/// #### nk_layout_row_end
/// Finished previously started row
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_layout_row_end(struct nk_context*);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
*/
NK_API void nk_layout_row_end(struct nk_context*);
/*/// #### nk_layout_row
/// Specifies row columns in array as either window ratio or size
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_layout_row(struct nk_context*, enum nk_layout_format, float height, int cols, const float *ratio);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
/// __fmt__ | Either `NK_DYNAMIC` for window ratio or `NK_STATIC` for fixed size columns
/// __height__ | Holds height of each widget in row or zero for auto layouting
/// __columns__ | Number of widget inside row
*/
NK_API void nk_layout_row(struct nk_context*, enum nk_layout_format, float height, int cols, const float *ratio);
/*/// #### nk_layout_row_template_begin
/// Begins the row template declaration
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_layout_row_template_begin(struct nk_context*, float row_height);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
/// __height__ | Holds height of each widget in row or zero for auto layouting
*/
NK_API void nk_layout_row_template_begin(struct nk_context*, float row_height);
/*/// #### nk_layout_row_template_push_dynamic
/// Adds a dynamic column that dynamically grows and can go to zero if not enough space
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_layout_row_template_push_dynamic(struct nk_context*);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
/// __height__ | Holds height of each widget in row or zero for auto layouting
*/
NK_API void nk_layout_row_template_push_dynamic(struct nk_context*);
/*/// #### nk_layout_row_template_push_variable
/// Adds a variable column that dynamically grows but does not shrink below specified pixel width
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_layout_row_template_push_variable(struct nk_context*, float min_width);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
/// __width__ | Holds the minimum pixel width the next column must always be
*/
NK_API void nk_layout_row_template_push_variable(struct nk_context*, float min_width);
/*/// #### nk_layout_row_template_push_static
/// Adds a static column that does not grow and will always have the same size
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_layout_row_template_push_static(struct nk_context*, float width);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
/// __width__ | Holds the absolute pixel width value the next column must be
*/
NK_API void nk_layout_row_template_push_static(struct nk_context*, float width);
/*/// #### nk_layout_row_template_end
/// Marks the end of the row template
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_layout_row_template_end(struct nk_context*);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
*/
NK_API void nk_layout_row_template_end(struct nk_context*);
/*/// #### nk_layout_space_begin
/// Begins a new layouting space that allows to specify each widgets position and size.
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_layout_space_begin(struct nk_context*, enum nk_layout_format, float height, int widget_count);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_begin_xxx`
/// __fmt__ | Either `NK_DYNAMIC` for window ratio or `NK_STATIC` for fixed size columns
/// __height__ | Holds height of each widget in row or zero for auto layouting
/// __columns__ | Number of widgets inside row
*/
NK_API void nk_layout_space_begin(struct nk_context*, enum nk_layout_format, float height, int widget_count);
/*/// #### nk_layout_space_push
/// Pushes position and size of the next widget in own coordinate space either as pixel or ratio
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_layout_space_push(struct nk_context *ctx, struct nk_rect bounds);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin`
/// __bounds__ | Position and size in laoyut space local coordinates
*/
NK_API void nk_layout_space_push(struct nk_context*, struct nk_rect bounds);
/*/// #### nk_layout_space_end
/// Marks the end of the layout space
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_layout_space_end(struct nk_context*);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin`
*/
NK_API void nk_layout_space_end(struct nk_context*);
/*/// #### nk_layout_space_bounds
/// Utility function to calculate total space allocated for `nk_layout_space`
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// struct nk_rect nk_layout_space_bounds(struct nk_context*);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin`
///
/// Returns `nk_rect` holding the total space allocated
*/
NK_API struct nk_rect nk_layout_space_bounds(struct nk_context*);
/*/// #### nk_layout_space_to_screen
/// Converts vector from nk_layout_space coordinate space into screen space
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// struct nk_vec2 nk_layout_space_to_screen(struct nk_context*, struct nk_vec2);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin`
/// __vec__ | Position to convert from layout space into screen coordinate space
///
/// Returns transformed `nk_vec2` in screen space coordinates
*/
NK_API struct nk_vec2 nk_layout_space_to_screen(struct nk_context*, struct nk_vec2);
/*/// #### nk_layout_space_to_local
/// Converts vector from layout space into screen space
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// struct nk_vec2 nk_layout_space_to_local(struct nk_context*, struct nk_vec2);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin`
/// __vec__ | Position to convert from screen space into layout coordinate space
///
/// Returns transformed `nk_vec2` in layout space coordinates
*/
NK_API struct nk_vec2 nk_layout_space_to_local(struct nk_context*, struct nk_vec2);
/*/// #### nk_layout_space_rect_to_screen
/// Converts rectangle from screen space into layout space
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// struct nk_rect nk_layout_space_rect_to_screen(struct nk_context*, struct nk_rect);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin`
/// __bounds__ | Rectangle to convert from layout space into screen space
///
/// Returns transformed `nk_rect` in screen space coordinates
*/
NK_API struct nk_rect nk_layout_space_rect_to_screen(struct nk_context*, struct nk_rect);
/*/// #### nk_layout_space_rect_to_local
/// Converts rectangle from layout space into screen space
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// struct nk_rect nk_layout_space_rect_to_local(struct nk_context*, struct nk_rect);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after call `nk_layout_space_begin`
/// __bounds__ | Rectangle to convert from layout space into screen space
///
/// Returns transformed `nk_rect` in layout space coordinates
*/
NK_API struct nk_rect nk_layout_space_rect_to_local(struct nk_context*, struct nk_rect);
/* =============================================================================
*
* GROUP
*
* =============================================================================
/// ### Groups
/// Groups are basically windows inside windows. They allow to subdivide space
/// in a window to layout widgets as a group. Almost all more complex widget
/// layouting requirements can be solved using groups and basic layouting
/// fuctionality. Groups just like windows are identified by an unique name and
/// internally keep track of scrollbar offsets by default. However additional
/// versions are provided to directly manage the scrollbar.
///
/// #### Usage
/// To create a group you have to call one of the three `nk_group_begin_xxx`
/// functions to start group declarations and `nk_group_end` at the end. Furthermore it
/// is required to check the return value of `nk_group_begin_xxx` and only process
/// widgets inside the window if the value is not 0.
/// Nesting groups is possible and even encouraged since many layouting schemes
/// can only be achieved by nesting. Groups, unlike windows, need `nk_group_end`
/// to be only called if the corosponding `nk_group_begin_xxx` call does not return 0:
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// if (nk_group_begin_xxx(ctx, ...) {
/// // [... widgets ...]
/// nk_group_end(ctx);
/// }
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// In the grand concept groups can be called after starting a window
/// with `nk_begin_xxx` and before calling `nk_end`:
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// struct nk_context ctx;
/// nk_init_xxx(&ctx, ...);
/// while (1) {
/// // Input
/// Event evt;
/// nk_input_begin(&ctx);
/// while (GetEvent(&evt)) {
/// if (evt.type == MOUSE_MOVE)
/// nk_input_motion(&ctx, evt.motion.x, evt.motion.y);
/// else if (evt.type == [...]) {
/// nk_input_xxx(...);
/// }
/// }
/// nk_input_end(&ctx);
/// //
/// // Window
/// if (nk_begin_xxx(...) {
/// // [...widgets...]
/// nk_layout_row_dynamic(...);
/// if (nk_group_begin_xxx(ctx, ...) {
/// //[... widgets ...]
/// nk_group_end(ctx);
/// }
/// }
/// nk_end(ctx);
/// //
/// // Draw
/// const struct nk_command *cmd = 0;
/// nk_foreach(cmd, &ctx) {
/// switch (cmd->type) {
/// case NK_COMMAND_LINE:
/// your_draw_line_function(...)
/// break;
/// case NK_COMMAND_RECT
/// your_draw_rect_function(...)
/// break;
/// case ...:
/// // [...]
/// }
/// nk_clear(&ctx);
/// }
/// nk_free(&ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// #### Reference
/// Function | Description
/// --------------------------------|-------------------------------------------
/// nk_group_begin | Start a new group with internal scrollbar handling
/// nk_group_begin_titled | Start a new group with separeted name and title and internal scrollbar handling
/// nk_group_end | Ends a group. Should only be called if nk_group_begin returned non-zero
/// nk_group_scrolled_offset_begin | Start a new group with manual separated handling of scrollbar x- and y-offset
/// nk_group_scrolled_begin | Start a new group with manual scrollbar handling
/// nk_group_scrolled_end | Ends a group with manual scrollbar handling. Should only be called if nk_group_begin returned non-zero
/// nk_group_get_scroll | Gets the scroll offset for the given group
/// nk_group_set_scroll | Sets the scroll offset for the given group
*/
/*/// #### nk_group_begin
/// Starts a new widget group. Requires a previous layouting function to specify a pos/size.
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_bool nk_group_begin(struct nk_context*, const char *title, nk_flags);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __title__ | Must be an unique identifier for this group that is also used for the group header
/// __flags__ | Window flags defined in the nk_panel_flags section with a number of different group behaviors
///
/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
*/
NK_API nk_bool nk_group_begin(struct nk_context*, const char *title, nk_flags);
/*/// #### nk_group_begin_titled
/// Starts a new widget group. Requires a previous layouting function to specify a pos/size.
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_bool nk_group_begin_titled(struct nk_context*, const char *name, const char *title, nk_flags);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __id__ | Must be an unique identifier for this group
/// __title__ | Group header title
/// __flags__ | Window flags defined in the nk_panel_flags section with a number of different group behaviors
///
/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
*/
NK_API nk_bool nk_group_begin_titled(struct nk_context*, const char *name, const char *title, nk_flags);
/*/// #### nk_group_end
/// Ends a widget group
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_group_end(struct nk_context*);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
*/
NK_API void nk_group_end(struct nk_context*);
/*/// #### nk_group_scrolled_offset_begin
/// starts a new widget group. requires a previous layouting function to specify
/// a size. Does not keep track of scrollbar.
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_bool nk_group_scrolled_offset_begin(struct nk_context*, nk_uint *x_offset, nk_uint *y_offset, const char *title, nk_flags flags);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __x_offset__| Scrollbar x-offset to offset all widgets inside the group horizontally.
/// __y_offset__| Scrollbar y-offset to offset all widgets inside the group vertically
/// __title__ | Window unique group title used to both identify and display in the group header
/// __flags__ | Window flags from the nk_panel_flags section
///
/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
*/
NK_API nk_bool nk_group_scrolled_offset_begin(struct nk_context*, nk_uint *x_offset, nk_uint *y_offset, const char *title, nk_flags flags);
/*/// #### nk_group_scrolled_begin
/// Starts a new widget group. requires a previous
/// layouting function to specify a size. Does not keep track of scrollbar.
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_bool nk_group_scrolled_begin(struct nk_context*, struct nk_scroll *off, const char *title, nk_flags);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __off__ | Both x- and y- scroll offset. Allows for manual scrollbar control
/// __title__ | Window unique group title used to both identify and display in the group header
/// __flags__ | Window flags from nk_panel_flags section
///
/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
*/
NK_API nk_bool nk_group_scrolled_begin(struct nk_context*, struct nk_scroll *off, const char *title, nk_flags);
/*/// #### nk_group_scrolled_end
/// Ends a widget group after calling nk_group_scrolled_offset_begin or nk_group_scrolled_begin.
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_group_scrolled_end(struct nk_context*);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
*/
NK_API void nk_group_scrolled_end(struct nk_context*);
/*/// #### nk_group_get_scroll
/// Gets the scroll position of the given group.
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_group_get_scroll(struct nk_context*, const char *id, nk_uint *x_offset, nk_uint *y_offset);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// -------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __id__ | The id of the group to get the scroll position of
/// __x_offset__ | A pointer to the x offset output (or NULL to ignore)
/// __y_offset__ | A pointer to the y offset output (or NULL to ignore)
*/
NK_API void nk_group_get_scroll(struct nk_context*, const char *id, nk_uint *x_offset, nk_uint *y_offset);
/*/// #### nk_group_set_scroll
/// Sets the scroll position of the given group.
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_group_set_scroll(struct nk_context*, const char *id, nk_uint x_offset, nk_uint y_offset);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// -------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __id__ | The id of the group to scroll
/// __x_offset__ | The x offset to scroll to
/// __y_offset__ | The y offset to scroll to
*/
NK_API void nk_group_set_scroll(struct nk_context*, const char *id, nk_uint x_offset, nk_uint y_offset);
/* =============================================================================
*
* TREE
*
* =============================================================================
/// ### Tree
/// Trees represent two different concept. First the concept of a collapsable
/// UI section that can be either in a hidden or visibile state. They allow the UI
/// user to selectively minimize the current set of visible UI to comprehend.
/// The second concept are tree widgets for visual UI representation of trees.<br /><br />
///
/// Trees thereby can be nested for tree representations and multiple nested
/// collapsable UI sections. All trees are started by calling of the
/// `nk_tree_xxx_push_tree` functions and ended by calling one of the
/// `nk_tree_xxx_pop_xxx()` functions. Each starting functions takes a title label
/// and optionally an image to be displayed and the initial collapse state from
/// the nk_collapse_states section.<br /><br />
///
/// The runtime state of the tree is either stored outside the library by the caller
/// or inside which requires a unique ID. The unique ID can either be generated
/// automatically from `__FILE__` and `__LINE__` with function `nk_tree_push`,
/// by `__FILE__` and a user provided ID generated for example by loop index with
/// function `nk_tree_push_id` or completely provided from outside by user with
/// function `nk_tree_push_hashed`.
///
/// #### Usage
/// To create a tree you have to call one of the seven `nk_tree_xxx_push_xxx`
/// functions to start a collapsable UI section and `nk_tree_xxx_pop` to mark the
/// end.
/// Each starting function will either return `false(0)` if the tree is collapsed
/// or hidden and therefore does not need to be filled with content or `true(1)`
/// if visible and required to be filled.
///
/// !!! Note
/// The tree header does not require and layouting function and instead
/// calculates a auto height based on the currently used font size
///
/// The tree ending functions only need to be called if the tree content is
/// actually visible. So make sure the tree push function is guarded by `if`
/// and the pop call is only taken if the tree is visible.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// if (nk_tree_push(ctx, NK_TREE_TAB, "Tree", NK_MINIMIZED)) {
/// nk_layout_row_dynamic(...);
/// nk_widget(...);
/// nk_tree_pop(ctx);
/// }
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// #### Reference
/// Function | Description
/// ----------------------------|-------------------------------------------
/// nk_tree_push | Start a collapsable UI section with internal state management
/// nk_tree_push_id | Start a collapsable UI section with internal state management callable in a look
/// nk_tree_push_hashed | Start a collapsable UI section with internal state management with full control over internal unique ID use to store state
/// nk_tree_image_push | Start a collapsable UI section with image and label header
/// nk_tree_image_push_id | Start a collapsable UI section with image and label header and internal state management callable in a look
/// nk_tree_image_push_hashed | Start a collapsable UI section with image and label header and internal state management with full control over internal unique ID use to store state
/// nk_tree_pop | Ends a collapsable UI section
//
/// nk_tree_state_push | Start a collapsable UI section with external state management
/// nk_tree_state_image_push | Start a collapsable UI section with image and label header and external state management
/// nk_tree_state_pop | Ends a collapsabale UI section
///
/// #### nk_tree_type
/// Flag | Description
/// ----------------|----------------------------------------
/// NK_TREE_NODE | Highlighted tree header to mark a collapsable UI section
/// NK_TREE_TAB | Non-highighted tree header closer to tree representations
*/
/*/// #### nk_tree_push
/// Starts a collapsable UI section with internal state management
/// !!! WARNING
/// To keep track of the runtime tree collapsable state this function uses
/// defines `__FILE__` and `__LINE__` to generate a unique ID. If you want
/// to call this function in a loop please use `nk_tree_push_id` or
/// `nk_tree_push_hashed` instead.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// #define nk_tree_push(ctx, type, title, state)
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node
/// __title__ | Label printed in the tree header
/// __state__ | Initial tree state value out of nk_collapse_states
///
/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
*/
#define nk_tree_push(ctx, type, title, state) nk_tree_push_hashed(ctx, type, title, state, NK_FILE_LINE,nk_strlen(NK_FILE_LINE),__LINE__)
/*/// #### nk_tree_push_id
/// Starts a collapsable UI section with internal state management callable in a look
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// #define nk_tree_push_id(ctx, type, title, state, id)
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node
/// __title__ | Label printed in the tree header
/// __state__ | Initial tree state value out of nk_collapse_states
/// __id__ | Loop counter index if this function is called in a loop
///
/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
*/
#define nk_tree_push_id(ctx, type, title, state, id) nk_tree_push_hashed(ctx, type, title, state, NK_FILE_LINE,nk_strlen(NK_FILE_LINE),id)
/*/// #### nk_tree_push_hashed
/// Start a collapsable UI section with internal state management with full
/// control over internal unique ID used to store state
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_bool nk_tree_push_hashed(struct nk_context*, enum nk_tree_type, const char *title, enum nk_collapse_states initial_state, const char *hash, int len,int seed);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node
/// __title__ | Label printed in the tree header
/// __state__ | Initial tree state value out of nk_collapse_states
/// __hash__ | Memory block or string to generate the ID from
/// __len__ | Size of passed memory block or string in __hash__
/// __seed__ | Seeding value if this function is called in a loop or default to `0`
///
/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
*/
NK_API nk_bool nk_tree_push_hashed(struct nk_context*, enum nk_tree_type, const char *title, enum nk_collapse_states initial_state, const char *hash, int len,int seed);
/*/// #### nk_tree_image_push
/// Start a collapsable UI section with image and label header
/// !!! WARNING
/// To keep track of the runtime tree collapsable state this function uses
/// defines `__FILE__` and `__LINE__` to generate a unique ID. If you want
/// to call this function in a loop please use `nk_tree_image_push_id` or
/// `nk_tree_image_push_hashed` instead.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// #define nk_tree_image_push(ctx, type, img, title, state)
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node
/// __img__ | Image to display inside the header on the left of the label
/// __title__ | Label printed in the tree header
/// __state__ | Initial tree state value out of nk_collapse_states
///
/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
*/
#define nk_tree_image_push(ctx, type, img, title, state) nk_tree_image_push_hashed(ctx, type, img, title, state, NK_FILE_LINE,nk_strlen(NK_FILE_LINE),__LINE__)
/*/// #### nk_tree_image_push_id
/// Start a collapsable UI section with image and label header and internal state
/// management callable in a look
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// #define nk_tree_image_push_id(ctx, type, img, title, state, id)
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node
/// __img__ | Image to display inside the header on the left of the label
/// __title__ | Label printed in the tree header
/// __state__ | Initial tree state value out of nk_collapse_states
/// __id__ | Loop counter index if this function is called in a loop
///
/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
*/
#define nk_tree_image_push_id(ctx, type, img, title, state, id) nk_tree_image_push_hashed(ctx, type, img, title, state, NK_FILE_LINE,nk_strlen(NK_FILE_LINE),id)
/*/// #### nk_tree_image_push_hashed
/// Start a collapsable UI section with internal state management with full
/// control over internal unique ID used to store state
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_bool nk_tree_image_push_hashed(struct nk_context*, enum nk_tree_type, struct nk_image, const char *title, enum nk_collapse_states initial_state, const char *hash, int len,int seed);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct
/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node
/// __img__ | Image to display inside the header on the left of the label
/// __title__ | Label printed in the tree header
/// __state__ | Initial tree state value out of nk_collapse_states
/// __hash__ | Memory block or string to generate the ID from
/// __len__ | Size of passed memory block or string in __hash__
/// __seed__ | Seeding value if this function is called in a loop or default to `0`
///
/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
*/
NK_API nk_bool nk_tree_image_push_hashed(struct nk_context*, enum nk_tree_type, struct nk_image, const char *title, enum nk_collapse_states initial_state, const char *hash, int len,int seed);
/*/// #### nk_tree_pop
/// Ends a collapsabale UI section
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_tree_pop(struct nk_context*);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling `nk_tree_xxx_push_xxx`
*/
NK_API void nk_tree_pop(struct nk_context*);
/*/// #### nk_tree_state_push
/// Start a collapsable UI section with external state management
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_bool nk_tree_state_push(struct nk_context*, enum nk_tree_type, const char *title, enum nk_collapse_states *state);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling `nk_tree_xxx_push_xxx`
/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node
/// __title__ | Label printed in the tree header
/// __state__ | Persistent state to update
///
/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
*/
NK_API nk_bool nk_tree_state_push(struct nk_context*, enum nk_tree_type, const char *title, enum nk_collapse_states *state);
/*/// #### nk_tree_state_image_push
/// Start a collapsable UI section with image and label header and external state management
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// nk_bool nk_tree_state_image_push(struct nk_context*, enum nk_tree_type, struct nk_image, const char *title, enum nk_collapse_states *state);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling `nk_tree_xxx_push_xxx`
/// __img__ | Image to display inside the header on the left of the label
/// __type__ | Value from the nk_tree_type section to visually mark a tree node header as either a collapseable UI section or tree node
/// __title__ | Label printed in the tree header
/// __state__ | Persistent state to update
///
/// Returns `true(1)` if visible and fillable with widgets or `false(0)` otherwise
*/
NK_API nk_bool nk_tree_state_image_push(struct nk_context*, enum nk_tree_type, struct nk_image, const char *title, enum nk_collapse_states *state);
/*/// #### nk_tree_state_pop
/// Ends a collapsabale UI section
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_tree_state_pop(struct nk_context*);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// ------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling `nk_tree_xxx_push_xxx`
*/
NK_API void nk_tree_state_pop(struct nk_context*);
#define nk_tree_element_push(ctx, type, title, state, sel) nk_tree_element_push_hashed(ctx, type, title, state, sel, NK_FILE_LINE,nk_strlen(NK_FILE_LINE),__LINE__)
#define nk_tree_element_push_id(ctx, type, title, state, sel, id) nk_tree_element_push_hashed(ctx, type, title, state, sel, NK_FILE_LINE,nk_strlen(NK_FILE_LINE),id)
NK_API nk_bool nk_tree_element_push_hashed(struct nk_context*, enum nk_tree_type, const char *title, enum nk_collapse_states initial_state, nk_bool *selected, const char *hash, int len, int seed);
NK_API nk_bool nk_tree_element_image_push_hashed(struct nk_context*, enum nk_tree_type, struct nk_image, const char *title, enum nk_collapse_states initial_state, nk_bool *selected, const char *hash, int len,int seed);
NK_API void nk_tree_element_pop(struct nk_context*);
/* =============================================================================
*
* LIST VIEW
*
* ============================================================================= */
struct nk_list_view {
/* public: */
int begin, end, count;
/* private: */
int total_height;
struct nk_context *ctx;
nk_uint *scroll_pointer;
nk_uint scroll_value;
};
NK_API nk_bool nk_list_view_begin(struct nk_context*, struct nk_list_view *out, const char *id, nk_flags, int row_height, int row_count);
NK_API void nk_list_view_end(struct nk_list_view*);
/* =============================================================================
*
* WIDGET
*
* ============================================================================= */
enum nk_widget_layout_states {
NK_WIDGET_INVALID, /* The widget cannot be seen and is completely out of view */
NK_WIDGET_VALID, /* The widget is completely inside the window and can be updated and drawn */
NK_WIDGET_ROM /* The widget is partially visible and cannot be updated */
};
enum nk_widget_states {
NK_WIDGET_STATE_MODIFIED = NK_FLAG(1),
NK_WIDGET_STATE_INACTIVE = NK_FLAG(2), /* widget is neither active nor hovered */
NK_WIDGET_STATE_ENTERED = NK_FLAG(3), /* widget has been hovered on the current frame */
NK_WIDGET_STATE_HOVER = NK_FLAG(4), /* widget is being hovered */
NK_WIDGET_STATE_ACTIVED = NK_FLAG(5),/* widget is currently activated */
NK_WIDGET_STATE_LEFT = NK_FLAG(6), /* widget is from this frame on not hovered anymore */
NK_WIDGET_STATE_HOVERED = NK_WIDGET_STATE_HOVER|NK_WIDGET_STATE_MODIFIED, /* widget is being hovered */
NK_WIDGET_STATE_ACTIVE = NK_WIDGET_STATE_ACTIVED|NK_WIDGET_STATE_MODIFIED /* widget is currently activated */
};
NK_API enum nk_widget_layout_states nk_widget(struct nk_rect*, const struct nk_context*);
NK_API enum nk_widget_layout_states nk_widget_fitting(struct nk_rect*, struct nk_context*, struct nk_vec2);
NK_API struct nk_rect nk_widget_bounds(struct nk_context*);
NK_API struct nk_vec2 nk_widget_position(struct nk_context*);
NK_API struct nk_vec2 nk_widget_size(struct nk_context*);
NK_API float nk_widget_width(struct nk_context*);
NK_API float nk_widget_height(struct nk_context*);
NK_API nk_bool nk_widget_is_hovered(struct nk_context*);
NK_API nk_bool nk_widget_is_mouse_clicked(struct nk_context*, enum nk_buttons);
NK_API nk_bool nk_widget_has_mouse_click_down(struct nk_context*, enum nk_buttons, nk_bool down);
NK_API void nk_spacing(struct nk_context*, int cols);
/* =============================================================================
*
* TEXT
*
* ============================================================================= */
enum nk_text_align {
NK_TEXT_ALIGN_LEFT = 0x01,
NK_TEXT_ALIGN_CENTERED = 0x02,
NK_TEXT_ALIGN_RIGHT = 0x04,
NK_TEXT_ALIGN_TOP = 0x08,
NK_TEXT_ALIGN_MIDDLE = 0x10,
NK_TEXT_ALIGN_BOTTOM = 0x20
};
enum nk_text_alignment {
NK_TEXT_LEFT = NK_TEXT_ALIGN_MIDDLE|NK_TEXT_ALIGN_LEFT,
NK_TEXT_CENTERED = NK_TEXT_ALIGN_MIDDLE|NK_TEXT_ALIGN_CENTERED,
NK_TEXT_RIGHT = NK_TEXT_ALIGN_MIDDLE|NK_TEXT_ALIGN_RIGHT
};
NK_API void nk_text(struct nk_context*, const char*, int, nk_flags);
NK_API void nk_text_colored(struct nk_context*, const char*, int, nk_flags, struct nk_color);
NK_API void nk_text_wrap(struct nk_context*, const char*, int);
NK_API void nk_text_wrap_colored(struct nk_context*, const char*, int, struct nk_color);
NK_API void nk_label(struct nk_context*, const char*, nk_flags align);
NK_API void nk_label_colored(struct nk_context*, const char*, nk_flags align, struct nk_color);
NK_API void nk_label_wrap(struct nk_context*, const char*);
NK_API void nk_label_colored_wrap(struct nk_context*, const char*, struct nk_color);
NK_API void nk_image(struct nk_context*, struct nk_image);
NK_API void nk_image_color(struct nk_context*, struct nk_image, struct nk_color);
#ifdef NK_INCLUDE_STANDARD_VARARGS
NK_API void nk_labelf(struct nk_context*, nk_flags, NK_PRINTF_FORMAT_STRING const char*, ...) NK_PRINTF_VARARG_FUNC(3);
NK_API void nk_labelf_colored(struct nk_context*, nk_flags, struct nk_color, NK_PRINTF_FORMAT_STRING const char*,...) NK_PRINTF_VARARG_FUNC(4);
NK_API void nk_labelf_wrap(struct nk_context*, NK_PRINTF_FORMAT_STRING const char*,...) NK_PRINTF_VARARG_FUNC(2);
NK_API void nk_labelf_colored_wrap(struct nk_context*, struct nk_color, NK_PRINTF_FORMAT_STRING const char*,...) NK_PRINTF_VARARG_FUNC(3);
NK_API void nk_labelfv(struct nk_context*, nk_flags, NK_PRINTF_FORMAT_STRING const char*, va_list) NK_PRINTF_VALIST_FUNC(3);
NK_API void nk_labelfv_colored(struct nk_context*, nk_flags, struct nk_color, NK_PRINTF_FORMAT_STRING const char*, va_list) NK_PRINTF_VALIST_FUNC(4);
NK_API void nk_labelfv_wrap(struct nk_context*, NK_PRINTF_FORMAT_STRING const char*, va_list) NK_PRINTF_VALIST_FUNC(2);
NK_API void nk_labelfv_colored_wrap(struct nk_context*, struct nk_color, NK_PRINTF_FORMAT_STRING const char*, va_list) NK_PRINTF_VALIST_FUNC(3);
NK_API void nk_value_bool(struct nk_context*, const char *prefix, int);
NK_API void nk_value_int(struct nk_context*, const char *prefix, int);
NK_API void nk_value_uint(struct nk_context*, const char *prefix, unsigned int);
NK_API void nk_value_float(struct nk_context*, const char *prefix, float);
NK_API void nk_value_color_byte(struct nk_context*, const char *prefix, struct nk_color);
NK_API void nk_value_color_float(struct nk_context*, const char *prefix, struct nk_color);
NK_API void nk_value_color_hex(struct nk_context*, const char *prefix, struct nk_color);
#endif
/* =============================================================================
*
* BUTTON
*
* ============================================================================= */
NK_API nk_bool nk_button_text(struct nk_context*, const char *title, int len);
NK_API nk_bool nk_button_label(struct nk_context*, const char *title);
NK_API nk_bool nk_button_color(struct nk_context*, struct nk_color);
NK_API nk_bool nk_button_symbol(struct nk_context*, enum nk_symbol_type);
NK_API nk_bool nk_button_image(struct nk_context*, struct nk_image img);
NK_API nk_bool nk_button_symbol_label(struct nk_context*, enum nk_symbol_type, const char*, nk_flags text_alignment);
NK_API nk_bool nk_button_symbol_text(struct nk_context*, enum nk_symbol_type, const char*, int, nk_flags alignment);
NK_API nk_bool nk_button_image_label(struct nk_context*, struct nk_image img, const char*, nk_flags text_alignment);
NK_API nk_bool nk_button_image_text(struct nk_context*, struct nk_image img, const char*, int, nk_flags alignment);
NK_API nk_bool nk_button_text_styled(struct nk_context*, const struct nk_style_button*, const char *title, int len);
NK_API nk_bool nk_button_label_styled(struct nk_context*, const struct nk_style_button*, const char *title);
NK_API nk_bool nk_button_symbol_styled(struct nk_context*, const struct nk_style_button*, enum nk_symbol_type);
NK_API nk_bool nk_button_image_styled(struct nk_context*, const struct nk_style_button*, struct nk_image img);
NK_API nk_bool nk_button_symbol_text_styled(struct nk_context*,const struct nk_style_button*, enum nk_symbol_type, const char*, int, nk_flags alignment);
NK_API nk_bool nk_button_symbol_label_styled(struct nk_context *ctx, const struct nk_style_button *style, enum nk_symbol_type symbol, const char *title, nk_flags align);
NK_API nk_bool nk_button_image_label_styled(struct nk_context*,const struct nk_style_button*, struct nk_image img, const char*, nk_flags text_alignment);
NK_API nk_bool nk_button_image_text_styled(struct nk_context*,const struct nk_style_button*, struct nk_image img, const char*, int, nk_flags alignment);
NK_API void nk_button_set_behavior(struct nk_context*, enum nk_button_behavior);
NK_API nk_bool nk_button_push_behavior(struct nk_context*, enum nk_button_behavior);
NK_API nk_bool nk_button_pop_behavior(struct nk_context*);
/* =============================================================================
*
* CHECKBOX
*
* ============================================================================= */
NK_API nk_bool nk_check_label(struct nk_context*, const char*, nk_bool active);
NK_API nk_bool nk_check_text(struct nk_context*, const char*, int, nk_bool active);
NK_API unsigned nk_check_flags_label(struct nk_context*, const char*, unsigned int flags, unsigned int value);
NK_API unsigned nk_check_flags_text(struct nk_context*, const char*, int, unsigned int flags, unsigned int value);
NK_API nk_bool nk_checkbox_label(struct nk_context*, const char*, nk_bool *active);
NK_API nk_bool nk_checkbox_text(struct nk_context*, const char*, int, nk_bool *active);
NK_API nk_bool nk_checkbox_flags_label(struct nk_context*, const char*, unsigned int *flags, unsigned int value);
NK_API nk_bool nk_checkbox_flags_text(struct nk_context*, const char*, int, unsigned int *flags, unsigned int value);
/* =============================================================================
*
* RADIO BUTTON
*
* ============================================================================= */
NK_API nk_bool nk_radio_label(struct nk_context*, const char*, nk_bool *active);
NK_API nk_bool nk_radio_text(struct nk_context*, const char*, int, nk_bool *active);
NK_API nk_bool nk_option_label(struct nk_context*, const char*, nk_bool active);
NK_API nk_bool nk_option_text(struct nk_context*, const char*, int, nk_bool active);
/* =============================================================================
*
* SELECTABLE
*
* ============================================================================= */
NK_API nk_bool nk_selectable_label(struct nk_context*, const char*, nk_flags align, nk_bool *value);
NK_API nk_bool nk_selectable_text(struct nk_context*, const char*, int, nk_flags align, nk_bool *value);
NK_API nk_bool nk_selectable_image_label(struct nk_context*,struct nk_image, const char*, nk_flags align, nk_bool *value);
NK_API nk_bool nk_selectable_image_text(struct nk_context*,struct nk_image, const char*, int, nk_flags align, nk_bool *value);
NK_API nk_bool nk_selectable_symbol_label(struct nk_context*,enum nk_symbol_type, const char*, nk_flags align, nk_bool *value);
NK_API nk_bool nk_selectable_symbol_text(struct nk_context*,enum nk_symbol_type, const char*, int, nk_flags align, nk_bool *value);
NK_API nk_bool nk_select_label(struct nk_context*, const char*, nk_flags align, nk_bool value);
NK_API nk_bool nk_select_text(struct nk_context*, const char*, int, nk_flags align, nk_bool value);
NK_API nk_bool nk_select_image_label(struct nk_context*, struct nk_image,const char*, nk_flags align, nk_bool value);
NK_API nk_bool nk_select_image_text(struct nk_context*, struct nk_image,const char*, int, nk_flags align, nk_bool value);
NK_API nk_bool nk_select_symbol_label(struct nk_context*,enum nk_symbol_type, const char*, nk_flags align, nk_bool value);
NK_API nk_bool nk_select_symbol_text(struct nk_context*,enum nk_symbol_type, const char*, int, nk_flags align, nk_bool value);
/* =============================================================================
*
* SLIDER
*
* ============================================================================= */
NK_API float nk_slide_float(struct nk_context*, float min, float val, float max, float step);
NK_API int nk_slide_int(struct nk_context*, int min, int val, int max, int step);
NK_API nk_bool nk_slider_float(struct nk_context*, float min, float *val, float max, float step);
NK_API nk_bool nk_slider_int(struct nk_context*, int min, int *val, int max, int step);
/* =============================================================================
*
* PROGRESSBAR
*
* ============================================================================= */
NK_API nk_bool nk_progress(struct nk_context*, nk_size *cur, nk_size max, nk_bool modifyable);
NK_API nk_size nk_prog(struct nk_context*, nk_size cur, nk_size max, nk_bool modifyable);
/* =============================================================================
*
* COLOR PICKER
*
* ============================================================================= */
NK_API struct nk_colorf nk_color_picker(struct nk_context*, struct nk_colorf, enum nk_color_format);
NK_API nk_bool nk_color_pick(struct nk_context*, struct nk_colorf*, enum nk_color_format);
/* =============================================================================
*
* PROPERTIES
*
* =============================================================================
/// ### Properties
/// Properties are the main value modification widgets in Nuklear. Changing a value
/// can be achieved by dragging, adding/removing incremental steps on button click
/// or by directly typing a number.
///
/// #### Usage
/// Each property requires a unique name for identifaction that is also used for
/// displaying a label. If you want to use the same name multiple times make sure
/// add a '#' before your name. The '#' will not be shown but will generate a
/// unique ID. Each propery also takes in a minimum and maximum value. If you want
/// to make use of the complete number range of a type just use the provided
/// type limits from `limits.h`. For example `INT_MIN` and `INT_MAX` for
/// `nk_property_int` and `nk_propertyi`. In additional each property takes in
/// a increment value that will be added or subtracted if either the increment
/// decrement button is clicked. Finally there is a value for increment per pixel
/// dragged that is added or subtracted from the value.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// int value = 0;
/// struct nk_context ctx;
/// nk_init_xxx(&ctx, ...);
/// while (1) {
/// // Input
/// Event evt;
/// nk_input_begin(&ctx);
/// while (GetEvent(&evt)) {
/// if (evt.type == MOUSE_MOVE)
/// nk_input_motion(&ctx, evt.motion.x, evt.motion.y);
/// else if (evt.type == [...]) {
/// nk_input_xxx(...);
/// }
/// }
/// nk_input_end(&ctx);
/// //
/// // Window
/// if (nk_begin_xxx(...) {
/// // Property
/// nk_layout_row_dynamic(...);
/// nk_property_int(ctx, "ID", INT_MIN, &value, INT_MAX, 1, 1);
/// }
/// nk_end(ctx);
/// //
/// // Draw
/// const struct nk_command *cmd = 0;
/// nk_foreach(cmd, &ctx) {
/// switch (cmd->type) {
/// case NK_COMMAND_LINE:
/// your_draw_line_function(...)
/// break;
/// case NK_COMMAND_RECT
/// your_draw_rect_function(...)
/// break;
/// case ...:
/// // [...]
/// }
/// nk_clear(&ctx);
/// }
/// nk_free(&ctx);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// #### Reference
/// Function | Description
/// --------------------|-------------------------------------------
/// nk_property_int | Integer property directly modifing a passed in value
/// nk_property_float | Float property directly modifing a passed in value
/// nk_property_double | Double property directly modifing a passed in value
/// nk_propertyi | Integer property returning the modified int value
/// nk_propertyf | Float property returning the modified float value
/// nk_propertyd | Double property returning the modified double value
///
*/
/*/// #### nk_property_int
/// Integer property directly modifing a passed in value
/// !!! WARNING
/// To generate a unique property ID using the same label make sure to insert
/// a `#` at the beginning. It will not be shown but guarantees correct behavior.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_property_int(struct nk_context *ctx, const char *name, int min, int *val, int max, int step, float inc_per_pixel);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// --------------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling a layouting function
/// __name__ | String used both as a label as well as a unique identifier
/// __min__ | Minimum value not allowed to be underflown
/// __val__ | Integer pointer to be modified
/// __max__ | Maximum value not allowed to be overflown
/// __step__ | Increment added and subtracted on increment and decrement button
/// __inc_per_pixel__ | Value per pixel added or subtracted on dragging
*/
NK_API void nk_property_int(struct nk_context*, const char *name, int min, int *val, int max, int step, float inc_per_pixel);
/*/// #### nk_property_float
/// Float property directly modifing a passed in value
/// !!! WARNING
/// To generate a unique property ID using the same label make sure to insert
/// a `#` at the beginning. It will not be shown but guarantees correct behavior.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_property_float(struct nk_context *ctx, const char *name, float min, float *val, float max, float step, float inc_per_pixel);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// --------------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling a layouting function
/// __name__ | String used both as a label as well as a unique identifier
/// __min__ | Minimum value not allowed to be underflown
/// __val__ | Float pointer to be modified
/// __max__ | Maximum value not allowed to be overflown
/// __step__ | Increment added and subtracted on increment and decrement button
/// __inc_per_pixel__ | Value per pixel added or subtracted on dragging
*/
NK_API void nk_property_float(struct nk_context*, const char *name, float min, float *val, float max, float step, float inc_per_pixel);
/*/// #### nk_property_double
/// Double property directly modifing a passed in value
/// !!! WARNING
/// To generate a unique property ID using the same label make sure to insert
/// a `#` at the beginning. It will not be shown but guarantees correct behavior.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// void nk_property_double(struct nk_context *ctx, const char *name, double min, double *val, double max, double step, double inc_per_pixel);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// --------------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling a layouting function
/// __name__ | String used both as a label as well as a unique identifier
/// __min__ | Minimum value not allowed to be underflown
/// __val__ | Double pointer to be modified
/// __max__ | Maximum value not allowed to be overflown
/// __step__ | Increment added and subtracted on increment and decrement button
/// __inc_per_pixel__ | Value per pixel added or subtracted on dragging
*/
NK_API void nk_property_double(struct nk_context*, const char *name, double min, double *val, double max, double step, float inc_per_pixel);
/*/// #### nk_propertyi
/// Integer property modifing a passed in value and returning the new value
/// !!! WARNING
/// To generate a unique property ID using the same label make sure to insert
/// a `#` at the beginning. It will not be shown but guarantees correct behavior.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// int nk_propertyi(struct nk_context *ctx, const char *name, int min, int val, int max, int step, float inc_per_pixel);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// --------------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling a layouting function
/// __name__ | String used both as a label as well as a unique identifier
/// __min__ | Minimum value not allowed to be underflown
/// __val__ | Current integer value to be modified and returned
/// __max__ | Maximum value not allowed to be overflown
/// __step__ | Increment added and subtracted on increment and decrement button
/// __inc_per_pixel__ | Value per pixel added or subtracted on dragging
///
/// Returns the new modified integer value
*/
NK_API int nk_propertyi(struct nk_context*, const char *name, int min, int val, int max, int step, float inc_per_pixel);
/*/// #### nk_propertyf
/// Float property modifing a passed in value and returning the new value
/// !!! WARNING
/// To generate a unique property ID using the same label make sure to insert
/// a `#` at the beginning. It will not be shown but guarantees correct behavior.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// float nk_propertyf(struct nk_context *ctx, const char *name, float min, float val, float max, float step, float inc_per_pixel);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// --------------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling a layouting function
/// __name__ | String used both as a label as well as a unique identifier
/// __min__ | Minimum value not allowed to be underflown
/// __val__ | Current float value to be modified and returned
/// __max__ | Maximum value not allowed to be overflown
/// __step__ | Increment added and subtracted on increment and decrement button
/// __inc_per_pixel__ | Value per pixel added or subtracted on dragging
///
/// Returns the new modified float value
*/
NK_API float nk_propertyf(struct nk_context*, const char *name, float min, float val, float max, float step, float inc_per_pixel);
/*/// #### nk_propertyd
/// Float property modifing a passed in value and returning the new value
/// !!! WARNING
/// To generate a unique property ID using the same label make sure to insert
/// a `#` at the beginning. It will not be shown but guarantees correct behavior.
///
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~c
/// float nk_propertyd(struct nk_context *ctx, const char *name, double min, double val, double max, double step, double inc_per_pixel);
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///
/// Parameter | Description
/// --------------------|-----------------------------------------------------------
/// __ctx__ | Must point to an previously initialized `nk_context` struct after calling a layouting function
/// __name__ | String used both as a label as well as a unique identifier
/// __min__ | Minimum value not allowed to be underflown
/// __val__ | Current double value to be modified and returned
/// __max__ | Maximum value not allowed to be overflown
/// __step__ | Increment added and subtracted on increment and decrement button
/// __inc_per_pixel__ | Value per pixel added or subtracted on dragging
///
/// Returns the new modified double value
*/
NK_API double nk_propertyd(struct nk_context*, const char *name, double min, double val, double max, double step, float inc_per_pixel);
/* =============================================================================
*
* TEXT EDIT
*
* ============================================================================= */
enum nk_edit_flags {
NK_EDIT_DEFAULT = 0,
NK_EDIT_READ_ONLY = NK_FLAG(0),
NK_EDIT_AUTO_SELECT = NK_FLAG(1),
NK_EDIT_SIG_ENTER = NK_FLAG(2),
NK_EDIT_ALLOW_TAB = NK_FLAG(3),
NK_EDIT_NO_CURSOR = NK_FLAG(4),
NK_EDIT_SELECTABLE = NK_FLAG(5),
NK_EDIT_CLIPBOARD = NK_FLAG(6),
NK_EDIT_CTRL_ENTER_NEWLINE = NK_FLAG(7),
NK_EDIT_NO_HORIZONTAL_SCROLL = NK_FLAG(8),
NK_EDIT_ALWAYS_INSERT_MODE = NK_FLAG(9),
NK_EDIT_MULTILINE = NK_FLAG(10),
NK_EDIT_GOTO_END_ON_ACTIVATE = NK_FLAG(11)
};
enum nk_edit_types {
NK_EDIT_SIMPLE = NK_EDIT_ALWAYS_INSERT_MODE,
NK_EDIT_FIELD = NK_EDIT_SIMPLE|NK_EDIT_SELECTABLE|NK_EDIT_CLIPBOARD,
NK_EDIT_BOX = NK_EDIT_ALWAYS_INSERT_MODE| NK_EDIT_SELECTABLE| NK_EDIT_MULTILINE|NK_EDIT_ALLOW_TAB|NK_EDIT_CLIPBOARD,
NK_EDIT_EDITOR = NK_EDIT_SELECTABLE|NK_EDIT_MULTILINE|NK_EDIT_ALLOW_TAB| NK_EDIT_CLIPBOARD
};
enum nk_edit_events {
NK_EDIT_ACTIVE = NK_FLAG(0), /* edit widget is currently being modified */
NK_EDIT_INACTIVE = NK_FLAG(1), /* edit widget is not active and is not being modified */
NK_EDIT_ACTIVATED = NK_FLAG(2), /* edit widget went from state inactive to state active */
NK_EDIT_DEACTIVATED = NK_FLAG(3), /* edit widget went from state active to state inactive */
NK_EDIT_COMMITED = NK_FLAG(4) /* edit widget has received an enter and lost focus */
};
NK_API nk_flags nk_edit_string(struct nk_context*, nk_flags, char *buffer, int *len, int max, nk_plugin_filter);
NK_API nk_flags nk_edit_string_zero_terminated(struct nk_context*, nk_flags, char *buffer, int max, nk_plugin_filter);
NK_API nk_flags nk_edit_buffer(struct nk_context*, nk_flags, struct nk_text_edit*, nk_plugin_filter);
NK_API void nk_edit_focus(struct nk_context*, nk_flags flags);
NK_API void nk_edit_unfocus(struct nk_context*);
/* =============================================================================
*
* CHART
*
* ============================================================================= */
NK_API nk_bool nk_chart_begin(struct nk_context*, enum nk_chart_type, int num, float min, float max);
NK_API nk_bool nk_chart_begin_colored(struct nk_context*, enum nk_chart_type, struct nk_color, struct nk_color active, int num, float min, float max);
NK_API void nk_chart_add_slot(struct nk_context *ctx, const enum nk_chart_type, int count, float min_value, float max_value);
NK_API void nk_chart_add_slot_colored(struct nk_context *ctx, const enum nk_chart_type, struct nk_color, struct nk_color active, int count, float min_value, float max_value);
NK_API nk_flags nk_chart_push(struct nk_context*, float);
NK_API nk_flags nk_chart_push_slot(struct nk_context*, float, int);
NK_API void nk_chart_end(struct nk_context*);
NK_API void nk_plot(struct nk_context*, enum nk_chart_type, const float *values, int count, int offset);
NK_API void nk_plot_function(struct nk_context*, enum nk_chart_type, void *userdata, float(*value_getter)(void* user, int index), int count, int offset);
/* =============================================================================
*
* POPUP
*
* ============================================================================= */
NK_API nk_bool nk_popup_begin(struct nk_context*, enum nk_popup_type, const char*, nk_flags, struct nk_rect bounds);
NK_API void nk_popup_close(struct nk_context*);
NK_API void nk_popup_end(struct nk_context*);
NK_API void nk_popup_get_scroll(struct nk_context*, nk_uint *offset_x, nk_uint *offset_y);
NK_API void nk_popup_set_scroll(struct nk_context*, nk_uint offset_x, nk_uint offset_y);
/* =============================================================================
*
* COMBOBOX
*
* ============================================================================= */
NK_API int nk_combo(struct nk_context*, const char **items, int count, int selected, int item_height, struct nk_vec2 size);
NK_API int nk_combo_separator(struct nk_context*, const char *items_separated_by_separator, int separator, int selected, int count, int item_height, struct nk_vec2 size);
NK_API int nk_combo_string(struct nk_context*, const char *items_separated_by_zeros, int selected, int count, int item_height, struct nk_vec2 size);
NK_API int nk_combo_callback(struct nk_context*, void(*item_getter)(void*, int, const char**), void *userdata, int selected, int count, int item_height, struct nk_vec2 size);
NK_API void nk_combobox(struct nk_context*, const char **items, int count, int *selected, int item_height, struct nk_vec2 size);
NK_API void nk_combobox_string(struct nk_context*, const char *items_separated_by_zeros, int *selected, int count, int item_height, struct nk_vec2 size);
NK_API void nk_combobox_separator(struct nk_context*, const char *items_separated_by_separator, int separator, int *selected, int count, int item_height, struct nk_vec2 size);
NK_API void nk_combobox_callback(struct nk_context*, void(*item_getter)(void*, int, const char**), void*, int *selected, int count, int item_height, struct nk_vec2 size);
/* =============================================================================
*
* ABSTRACT COMBOBOX
*
* ============================================================================= */
NK_API nk_bool nk_combo_begin_text(struct nk_context*, const char *selected, int, struct nk_vec2 size);
NK_API nk_bool nk_combo_begin_label(struct nk_context*, const char *selected, struct nk_vec2 size);
NK_API nk_bool nk_combo_begin_color(struct nk_context*, struct nk_color color, struct nk_vec2 size);
NK_API nk_bool nk_combo_begin_symbol(struct nk_context*, enum nk_symbol_type, struct nk_vec2 size);
NK_API nk_bool nk_combo_begin_symbol_label(struct nk_context*, const char *selected, enum nk_symbol_type, struct nk_vec2 size);
NK_API nk_bool nk_combo_begin_symbol_text(struct nk_context*, const char *selected, int, enum nk_symbol_type, struct nk_vec2 size);
NK_API nk_bool nk_combo_begin_image(struct nk_context*, struct nk_image img, struct nk_vec2 size);
NK_API nk_bool nk_combo_begin_image_label(struct nk_context*, const char *selected, struct nk_image, struct nk_vec2 size);
NK_API nk_bool nk_combo_begin_image_text(struct nk_context*, const char *selected, int, struct nk_image, struct nk_vec2 size);
NK_API nk_bool nk_combo_item_label(struct nk_context*, const char*, nk_flags alignment);
NK_API nk_bool nk_combo_item_text(struct nk_context*, const char*,int, nk_flags alignment);
NK_API nk_bool nk_combo_item_image_label(struct nk_context*, struct nk_image, const char*, nk_flags alignment);
NK_API nk_bool nk_combo_item_image_text(struct nk_context*, struct nk_image, const char*, int,nk_flags alignment);
NK_API nk_bool nk_combo_item_symbol_label(struct nk_context*, enum nk_symbol_type, const char*, nk_flags alignment);
NK_API nk_bool nk_combo_item_symbol_text(struct nk_context*, enum nk_symbol_type, const char*, int, nk_flags alignment);
NK_API void nk_combo_close(struct nk_context*);
NK_API void nk_combo_end(struct nk_context*);
/* =============================================================================
*
* CONTEXTUAL
*
* ============================================================================= */
NK_API nk_bool nk_contextual_begin(struct nk_context*, nk_flags, struct nk_vec2, struct nk_rect trigger_bounds);
NK_API nk_bool nk_contextual_item_text(struct nk_context*, const char*, int,nk_flags align);
NK_API nk_bool nk_contextual_item_label(struct nk_context*, const char*, nk_flags align);
NK_API nk_bool nk_contextual_item_image_label(struct nk_context*, struct nk_image, const char*, nk_flags alignment);
NK_API nk_bool nk_contextual_item_image_text(struct nk_context*, struct nk_image, const char*, int len, nk_flags alignment);
NK_API nk_bool nk_contextual_item_symbol_label(struct nk_context*, enum nk_symbol_type, const char*, nk_flags alignment);
NK_API nk_bool nk_contextual_item_symbol_text(struct nk_context*, enum nk_symbol_type, const char*, int, nk_flags alignment);
NK_API void nk_contextual_close(struct nk_context*);
NK_API void nk_contextual_end(struct nk_context*);
/* =============================================================================
*
* TOOLTIP
*
* ============================================================================= */
NK_API void nk_tooltip(struct nk_context*, const char*);
#ifdef NK_INCLUDE_STANDARD_VARARGS
NK_API void nk_tooltipf(struct nk_context*, NK_PRINTF_FORMAT_STRING const char*, ...) NK_PRINTF_VARARG_FUNC(2);
NK_API void nk_tooltipfv(struct nk_context*, NK_PRINTF_FORMAT_STRING const char*, va_list) NK_PRINTF_VALIST_FUNC(2);
#endif
NK_API nk_bool nk_tooltip_begin(struct nk_context*, float width);
NK_API void nk_tooltip_end(struct nk_context*);
/* =============================================================================
*
* MENU
*
* ============================================================================= */
NK_API void nk_menubar_begin(struct nk_context*);
NK_API void nk_menubar_end(struct nk_context*);
NK_API nk_bool nk_menu_begin_text(struct nk_context*, const char* title, int title_len, nk_flags align, struct nk_vec2 size);
NK_API nk_bool nk_menu_begin_label(struct nk_context*, const char*, nk_flags align, struct nk_vec2 size);
NK_API nk_bool nk_menu_begin_image(struct nk_context*, const char*, struct nk_image, struct nk_vec2 size);
NK_API nk_bool nk_menu_begin_image_text(struct nk_context*, const char*, int,nk_flags align,struct nk_image, struct nk_vec2 size);
NK_API nk_bool nk_menu_begin_image_label(struct nk_context*, const char*, nk_flags align,struct nk_image, struct nk_vec2 size);
NK_API nk_bool nk_menu_begin_symbol(struct nk_context*, const char*, enum nk_symbol_type, struct nk_vec2 size);
NK_API nk_bool nk_menu_begin_symbol_text(struct nk_context*, const char*, int,nk_flags align,enum nk_symbol_type, struct nk_vec2 size);
NK_API nk_bool nk_menu_begin_symbol_label(struct nk_context*, const char*, nk_flags align,enum nk_symbol_type, struct nk_vec2 size);
NK_API nk_bool nk_menu_item_text(struct nk_context*, const char*, int,nk_flags align);
NK_API nk_bool nk_menu_item_label(struct nk_context*, const char*, nk_flags alignment);
NK_API nk_bool nk_menu_item_image_label(struct nk_context*, struct nk_image, const char*, nk_flags alignment);
NK_API nk_bool nk_menu_item_image_text(struct nk_context*, struct nk_image, const char*, int len, nk_flags alignment);
NK_API nk_bool nk_menu_item_symbol_text(struct nk_context*, enum nk_symbol_type, const char*, int, nk_flags alignment);
NK_API nk_bool nk_menu_item_symbol_label(struct nk_context*, enum nk_symbol_type, const char*, nk_flags alignment);
NK_API void nk_menu_close(struct nk_context*);
NK_API void nk_menu_end(struct nk_context*);
/* =============================================================================
*
* STYLE
*
* ============================================================================= */
enum nk_style_colors {
NK_COLOR_TEXT,
NK_COLOR_WINDOW,
NK_COLOR_HEADER,
NK_COLOR_BORDER,
NK_COLOR_BUTTON,
NK_COLOR_BUTTON_HOVER,
NK_COLOR_BUTTON_ACTIVE,
NK_COLOR_TOGGLE,
NK_COLOR_TOGGLE_HOVER,
NK_COLOR_TOGGLE_CURSOR,
NK_COLOR_SELECT,
NK_COLOR_SELECT_ACTIVE,
NK_COLOR_SLIDER,
NK_COLOR_SLIDER_CURSOR,
NK_COLOR_SLIDER_CURSOR_HOVER,
NK_COLOR_SLIDER_CURSOR_ACTIVE,
NK_COLOR_PROPERTY,
NK_COLOR_EDIT,
NK_COLOR_EDIT_CURSOR,
NK_COLOR_COMBO,
NK_COLOR_CHART,
NK_COLOR_CHART_COLOR,
NK_COLOR_CHART_COLOR_HIGHLIGHT,
NK_COLOR_SCROLLBAR,
NK_COLOR_SCROLLBAR_CURSOR,
NK_COLOR_SCROLLBAR_CURSOR_HOVER,
NK_COLOR_SCROLLBAR_CURSOR_ACTIVE,
NK_COLOR_TAB_HEADER,
NK_COLOR_COUNT
};
enum nk_style_cursor {
NK_CURSOR_ARROW,
NK_CURSOR_TEXT,
NK_CURSOR_MOVE,
NK_CURSOR_RESIZE_VERTICAL,
NK_CURSOR_RESIZE_HORIZONTAL,
NK_CURSOR_RESIZE_TOP_LEFT_DOWN_RIGHT,
NK_CURSOR_RESIZE_TOP_RIGHT_DOWN_LEFT,
NK_CURSOR_COUNT
};
NK_API void nk_style_default(struct nk_context*);
NK_API void nk_style_from_table(struct nk_context*, const struct nk_color*);
NK_API void nk_style_load_cursor(struct nk_context*, enum nk_style_cursor, const struct nk_cursor*);
NK_API void nk_style_load_all_cursors(struct nk_context*, struct nk_cursor*);
NK_API const char* nk_style_get_color_by_name(enum nk_style_colors);
NK_API void nk_style_set_font(struct nk_context*, const struct nk_user_font*);
NK_API nk_bool nk_style_set_cursor(struct nk_context*, enum nk_style_cursor);
NK_API void nk_style_show_cursor(struct nk_context*);
NK_API void nk_style_hide_cursor(struct nk_context*);
NK_API nk_bool nk_style_push_font(struct nk_context*, const struct nk_user_font*);
NK_API nk_bool nk_style_push_float(struct nk_context*, float*, float);
NK_API nk_bool nk_style_push_vec2(struct nk_context*, struct nk_vec2*, struct nk_vec2);
NK_API nk_bool nk_style_push_style_item(struct nk_context*, struct nk_style_item*, struct nk_style_item);
NK_API nk_bool nk_style_push_flags(struct nk_context*, nk_flags*, nk_flags);
NK_API nk_bool nk_style_push_color(struct nk_context*, struct nk_color*, struct nk_color);
NK_API nk_bool nk_style_pop_font(struct nk_context*);
NK_API nk_bool nk_style_pop_float(struct nk_context*);
NK_API nk_bool nk_style_pop_vec2(struct nk_context*);
NK_API nk_bool nk_style_pop_style_item(struct nk_context*);
NK_API nk_bool nk_style_pop_flags(struct nk_context*);
NK_API nk_bool nk_style_pop_color(struct nk_context*);
/* =============================================================================
*
* COLOR
*
* ============================================================================= */
NK_API struct nk_color nk_rgb(int r, int g, int b);
NK_API struct nk_color nk_rgb_iv(const int *rgb);
NK_API struct nk_color nk_rgb_bv(const nk_byte* rgb);
NK_API struct nk_color nk_rgb_f(float r, float g, float b);
NK_API struct nk_color nk_rgb_fv(const float *rgb);
NK_API struct nk_color nk_rgb_cf(struct nk_colorf c);
NK_API struct nk_color nk_rgb_hex(const char *rgb);
NK_API struct nk_color nk_rgba(int r, int g, int b, int a);
NK_API struct nk_color nk_rgba_u32(nk_uint);
NK_API struct nk_color nk_rgba_iv(const int *rgba);
NK_API struct nk_color nk_rgba_bv(const nk_byte *rgba);
NK_API struct nk_color nk_rgba_f(float r, float g, float b, float a);
NK_API struct nk_color nk_rgba_fv(const float *rgba);
NK_API struct nk_color nk_rgba_cf(struct nk_colorf c);
NK_API struct nk_color nk_rgba_hex(const char *rgb);
NK_API struct nk_colorf nk_hsva_colorf(float h, float s, float v, float a);
NK_API struct nk_colorf nk_hsva_colorfv(float *c);
NK_API void nk_colorf_hsva_f(float *out_h, float *out_s, float *out_v, float *out_a, struct nk_colorf in);
NK_API void nk_colorf_hsva_fv(float *hsva, struct nk_colorf in);
NK_API struct nk_color nk_hsv(int h, int s, int v);
NK_API struct nk_color nk_hsv_iv(const int *hsv);
NK_API struct nk_color nk_hsv_bv(const nk_byte *hsv);
NK_API struct nk_color nk_hsv_f(float h, float s, float v);
NK_API struct nk_color nk_hsv_fv(const float *hsv);
NK_API struct nk_color nk_hsva(int h, int s, int v, int a);
NK_API struct nk_color nk_hsva_iv(const int *hsva);
NK_API struct nk_color nk_hsva_bv(const nk_byte *hsva);
NK_API struct nk_color nk_hsva_f(float h, float s, float v, float a);
NK_API struct nk_color nk_hsva_fv(const float *hsva);
/* color (conversion nuklear --> user) */
NK_API void nk_color_f(float *r, float *g, float *b, float *a, struct nk_color);
NK_API void nk_color_fv(float *rgba_out, struct nk_color);
NK_API struct nk_colorf nk_color_cf(struct nk_color);
NK_API void nk_color_d(double *r, double *g, double *b, double *a, struct nk_color);
NK_API void nk_color_dv(double *rgba_out, struct nk_color);
NK_API nk_uint nk_color_u32(struct nk_color);
NK_API void nk_color_hex_rgba(char *output, struct nk_color);
NK_API void nk_color_hex_rgb(char *output, struct nk_color);
NK_API void nk_color_hsv_i(int *out_h, int *out_s, int *out_v, struct nk_color);
NK_API void nk_color_hsv_b(nk_byte *out_h, nk_byte *out_s, nk_byte *out_v, struct nk_color);
NK_API void nk_color_hsv_iv(int *hsv_out, struct nk_color);
NK_API void nk_color_hsv_bv(nk_byte *hsv_out, struct nk_color);
NK_API void nk_color_hsv_f(float *out_h, float *out_s, float *out_v, struct nk_color);
NK_API void nk_color_hsv_fv(float *hsv_out, struct nk_color);
NK_API void nk_color_hsva_i(int *h, int *s, int *v, int *a, struct nk_color);
NK_API void nk_color_hsva_b(nk_byte *h, nk_byte *s, nk_byte *v, nk_byte *a, struct nk_color);
NK_API void nk_color_hsva_iv(int *hsva_out, struct nk_color);
NK_API void nk_color_hsva_bv(nk_byte *hsva_out, struct nk_color);
NK_API void nk_color_hsva_f(float *out_h, float *out_s, float *out_v, float *out_a, struct nk_color);
NK_API void nk_color_hsva_fv(float *hsva_out, struct nk_color);
/* =============================================================================
*
* IMAGE
*
* ============================================================================= */
NK_API nk_handle nk_handle_ptr(void*);
NK_API nk_handle nk_handle_id(int);
NK_API struct nk_image nk_image_handle(nk_handle);
NK_API struct nk_image nk_image_ptr(void*);
NK_API struct nk_image nk_image_id(int);
NK_API nk_bool nk_image_is_subimage(const struct nk_image* img);
NK_API struct nk_image nk_subimage_ptr(void*, nk_ushort w, nk_ushort h, struct nk_rect sub_region);
NK_API struct nk_image nk_subimage_id(int, nk_ushort w, nk_ushort h, struct nk_rect sub_region);
NK_API struct nk_image nk_subimage_handle(nk_handle, nk_ushort w, nk_ushort h, struct nk_rect sub_region);
/* =============================================================================
*
* 9-SLICE
*
* ============================================================================= */
NK_API struct nk_nine_slice nk_nine_slice_handle(nk_handle, nk_ushort l, nk_ushort t, nk_ushort r, nk_ushort b);
NK_API struct nk_nine_slice nk_nine_slice_ptr(void*, nk_ushort l, nk_ushort t, nk_ushort r, nk_ushort b);
NK_API struct nk_nine_slice nk_nine_slice_id(int, nk_ushort l, nk_ushort t, nk_ushort r, nk_ushort b);
NK_API int nk_nine_slice_is_sub9slice(const struct nk_nine_slice* img);
NK_API struct nk_nine_slice nk_sub9slice_ptr(void*, nk_ushort w, nk_ushort h, struct nk_rect sub_region, nk_ushort l, nk_ushort t, nk_ushort r, nk_ushort b);
NK_API struct nk_nine_slice nk_sub9slice_id(int, nk_ushort w, nk_ushort h, struct nk_rect sub_region, nk_ushort l, nk_ushort t, nk_ushort r, nk_ushort b);
NK_API struct nk_nine_slice nk_sub9slice_handle(nk_handle, nk_ushort w, nk_ushort h, struct nk_rect sub_region, nk_ushort l, nk_ushort t, nk_ushort r, nk_ushort b);
/* =============================================================================
*
* MATH
*
* ============================================================================= */
NK_API nk_hash nk_murmur_hash(const void *key, int len, nk_hash seed);
NK_API void nk_triangle_from_direction(struct nk_vec2 *result, struct nk_rect r, float pad_x, float pad_y, enum nk_heading);
NK_API struct nk_vec2 nk_vec2(float x, float y);
NK_API struct nk_vec2 nk_vec2i(int x, int y);
NK_API struct nk_vec2 nk_vec2v(const float *xy);
NK_API struct nk_vec2 nk_vec2iv(const int *xy);
NK_API struct nk_rect nk_get_null_rect(void);
NK_API struct nk_rect nk_rect(float x, float y, float w, float h);
NK_API struct nk_rect nk_recti(int x, int y, int w, int h);
NK_API struct nk_rect nk_recta(struct nk_vec2 pos, struct nk_vec2 size);
NK_API struct nk_rect nk_rectv(const float *xywh);
NK_API struct nk_rect nk_rectiv(const int *xywh);
NK_API struct nk_vec2 nk_rect_pos(struct nk_rect);
NK_API struct nk_vec2 nk_rect_size(struct nk_rect);
/* =============================================================================
*
* STRING
*
* ============================================================================= */
NK_API int nk_strlen(const char *str);
NK_API int nk_stricmp(const char *s1, const char *s2);
NK_API int nk_stricmpn(const char *s1, const char *s2, int n);
NK_API int nk_strtoi(const char *str, const char **endptr);
NK_API float nk_strtof(const char *str, const char **endptr);
#ifndef NK_STRTOD
#define NK_STRTOD nk_strtod
NK_API double nk_strtod(const char *str, const char **endptr);
#endif
NK_API int nk_strfilter(const char *text, const char *regexp);
NK_API int nk_strmatch_fuzzy_string(char const *str, char const *pattern, int *out_score);
NK_API int nk_strmatch_fuzzy_text(const char *txt, int txt_len, const char *pattern, int *out_score);
/* =============================================================================
*
* UTF-8
*
* ============================================================================= */
NK_API int nk_utf_decode(const char*, nk_rune*, int);
NK_API int nk_utf_encode(nk_rune, char*, int);
NK_API int nk_utf_len(const char*, int byte_len);
NK_API const char* nk_utf_at(const char *buffer, int length, int index, nk_rune *unicode, int *len);
/* ===============================================================
*
* FONT
*
* ===============================================================*/
/* Font handling in this library was designed to be quite customizable and lets
you decide what you want to use and what you want to provide. There are three
different ways to use the font atlas. The first two will use your font
handling scheme and only requires essential data to run nuklear. The next
slightly more advanced features is font handling with vertex buffer output.
Finally the most complex API wise is using nuklear's font baking API.
1.) Using your own implementation without vertex buffer output
--------------------------------------------------------------
So first up the easiest way to do font handling is by just providing a
`nk_user_font` struct which only requires the height in pixel of the used
font and a callback to calculate the width of a string. This way of handling
fonts is best fitted for using the normal draw shape command API where you
do all the text drawing yourself and the library does not require any kind
of deeper knowledge about which font handling mechanism you use.
IMPORTANT: the `nk_user_font` pointer provided to nuklear has to persist
over the complete life time! I know this sucks but it is currently the only
way to switch between fonts.
float your_text_width_calculation(nk_handle handle, float height, const char *text, int len)
{
your_font_type *type = handle.ptr;
float text_width = ...;
return text_width;
}
struct nk_user_font font;
font.userdata.ptr = &your_font_class_or_struct;
font.height = your_font_height;
font.width = your_text_width_calculation;
struct nk_context ctx;
nk_init_default(&ctx, &font);
2.) Using your own implementation with vertex buffer output
--------------------------------------------------------------
While the first approach works fine if you don't want to use the optional
vertex buffer output it is not enough if you do. To get font handling working
for these cases you have to provide two additional parameters inside the
`nk_user_font`. First a texture atlas handle used to draw text as subimages
of a bigger font atlas texture and a callback to query a character's glyph
information (offset, size, ...). So it is still possible to provide your own
font and use the vertex buffer output.
float your_text_width_calculation(nk_handle handle, float height, const char *text, int len)
{
your_font_type *type = handle.ptr;
float text_width = ...;
return text_width;
}
void query_your_font_glyph(nk_handle handle, float font_height, struct nk_user_font_glyph *glyph, nk_rune codepoint, nk_rune next_codepoint)
{
your_font_type *type = handle.ptr;
glyph.width = ...;
glyph.height = ...;
glyph.xadvance = ...;
glyph.uv[0].x = ...;
glyph.uv[0].y = ...;
glyph.uv[1].x = ...;
glyph.uv[1].y = ...;
glyph.offset.x = ...;
glyph.offset.y = ...;
}
struct nk_user_font font;
font.userdata.ptr = &your_font_class_or_struct;
font.height = your_font_height;
font.width = your_text_width_calculation;
font.query = query_your_font_glyph;
font.texture.id = your_font_texture;
struct nk_context ctx;
nk_init_default(&ctx, &font);
3.) Nuklear font baker
------------------------------------
The final approach if you do not have a font handling functionality or don't
want to use it in this library is by using the optional font baker.
The font baker APIs can be used to create a font plus font atlas texture
and can be used with or without the vertex buffer output.
It still uses the `nk_user_font` struct and the two different approaches
previously stated still work. The font baker is not located inside
`nk_context` like all other systems since it can be understood as more of
an extension to nuklear and does not really depend on any `nk_context` state.
Font baker need to be initialized first by one of the nk_font_atlas_init_xxx
functions. If you don't care about memory just call the default version
`nk_font_atlas_init_default` which will allocate all memory from the standard library.
If you want to control memory allocation but you don't care if the allocated
memory is temporary and therefore can be freed directly after the baking process
is over or permanent you can call `nk_font_atlas_init`.
After successfully initializing the font baker you can add Truetype(.ttf) fonts from
different sources like memory or from file by calling one of the `nk_font_atlas_add_xxx`.
functions. Adding font will permanently store each font, font config and ttf memory block(!)
inside the font atlas and allows to reuse the font atlas. If you don't want to reuse
the font baker by for example adding additional fonts you can call
`nk_font_atlas_cleanup` after the baking process is over (after calling nk_font_atlas_end).
As soon as you added all fonts you wanted you can now start the baking process
for every selected glyph to image by calling `nk_font_atlas_bake`.
The baking process returns image memory, width and height which can be used to
either create your own image object or upload it to any graphics library.
No matter which case you finally have to call `nk_font_atlas_end` which
will free all temporary memory including the font atlas image so make sure
you created our texture beforehand. `nk_font_atlas_end` requires a handle
to your font texture or object and optionally fills a `struct nk_draw_null_texture`
which can be used for the optional vertex output. If you don't want it just
set the argument to `NULL`.
At this point you are done and if you don't want to reuse the font atlas you
can call `nk_font_atlas_cleanup` to free all truetype blobs and configuration
memory. Finally if you don't use the font atlas and any of it's fonts anymore
you need to call `nk_font_atlas_clear` to free all memory still being used.
struct nk_font_atlas atlas;
nk_font_atlas_init_default(&atlas);
nk_font_atlas_begin(&atlas);
nk_font *font = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font.ttf", 13, 0);
nk_font *font2 = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font2.ttf", 16, 0);
const void* img = nk_font_atlas_bake(&atlas, &img_width, &img_height, NK_FONT_ATLAS_RGBA32);
nk_font_atlas_end(&atlas, nk_handle_id(texture), 0);
struct nk_context ctx;
nk_init_default(&ctx, &font->handle);
while (1) {
}
nk_font_atlas_clear(&atlas);
The font baker API is probably the most complex API inside this library and
I would suggest reading some of my examples `example/` to get a grip on how
to use the font atlas. There are a number of details I left out. For example
how to merge fonts, configure a font with `nk_font_config` to use other languages,
use another texture coordinate format and a lot more:
struct nk_font_config cfg = nk_font_config(font_pixel_height);
cfg.merge_mode = nk_false or nk_true;
cfg.range = nk_font_korean_glyph_ranges();
cfg.coord_type = NK_COORD_PIXEL;
nk_font *font = nk_font_atlas_add_from_file(&atlas, "Path/To/Your/TTF_Font.ttf", 13, &cfg);
*/
struct nk_user_font_glyph;
typedef float(*nk_text_width_f)(nk_handle, float h, const char*, int len);
typedef void(*nk_query_font_glyph_f)(nk_handle handle, float font_height,
struct nk_user_font_glyph *glyph,
nk_rune codepoint, nk_rune next_codepoint);
#if defined(NK_INCLUDE_VERTEX_BUFFER_OUTPUT) || defined(NK_INCLUDE_SOFTWARE_FONT)
struct nk_user_font_glyph {
struct nk_vec2 uv[2];
/* texture coordinates */
struct nk_vec2 offset;
/* offset between top left and glyph */
float width, height;
/* size of the glyph */
float xadvance;
/* offset to the next glyph */
};
#endif
struct nk_user_font {
nk_handle userdata;
/* user provided font handle */
float height;
/* max height of the font */
nk_text_width_f width;
/* font string width in pixel callback */
#ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT
nk_query_font_glyph_f query;
/* font glyph callback to query drawing info */
nk_handle texture;
/* texture handle to the used font atlas or texture */
#endif
};
#ifdef NK_INCLUDE_FONT_BAKING
enum nk_font_coord_type {
NK_COORD_UV, /* texture coordinates inside font glyphs are clamped between 0-1 */
NK_COORD_PIXEL /* texture coordinates inside font glyphs are in absolute pixel */
};
struct nk_font;
struct nk_baked_font {
float height;
/* height of the font */
float ascent, descent;
/* font glyphs ascent and descent */
nk_rune glyph_offset;
/* glyph array offset inside the font glyph baking output array */
nk_rune glyph_count;
/* number of glyphs of this font inside the glyph baking array output */
const nk_rune *ranges;
/* font codepoint ranges as pairs of (from/to) and 0 as last element */
};
struct nk_font_config {
struct nk_font_config *next;
/* NOTE: only used internally */
void *ttf_blob;
/* pointer to loaded TTF file memory block.
* NOTE: not needed for nk_font_atlas_add_from_memory and nk_font_atlas_add_from_file. */
nk_size ttf_size;
/* size of the loaded TTF file memory block
* NOTE: not needed for nk_font_atlas_add_from_memory and nk_font_atlas_add_from_file. */
unsigned char ttf_data_owned_by_atlas;
/* used inside font atlas: default to: 0*/
unsigned char merge_mode;
/* merges this font into the last font */
unsigned char pixel_snap;
/* align every character to pixel boundary (if true set oversample (1,1)) */
unsigned char oversample_v, oversample_h;
/* rasterize at hight quality for sub-pixel position */
unsigned char padding[3];
float size;
/* baked pixel height of the font */
enum nk_font_coord_type coord_type;
/* texture coordinate format with either pixel or UV coordinates */
struct nk_vec2 spacing;
/* extra pixel spacing between glyphs */
const nk_rune *range;
/* list of unicode ranges (2 values per range, zero terminated) */
struct nk_baked_font *font;
/* font to setup in the baking process: NOTE: not needed for font atlas */
nk_rune fallback_glyph;
/* fallback glyph to use if a given rune is not found */
struct nk_font_config *n;
struct nk_font_config *p;
};
struct nk_font_glyph {
nk_rune codepoint;
float xadvance;
float x0, y0, x1, y1, w, h;
float u0, v0, u1, v1;
};
struct nk_font {
struct nk_font *next;
struct nk_user_font handle;
struct nk_baked_font info;
float scale;
struct nk_font_glyph *glyphs;
const struct nk_font_glyph *fallback;
nk_rune fallback_codepoint;
nk_handle texture;
struct nk_font_config *config;
};
enum nk_font_atlas_format {
NK_FONT_ATLAS_ALPHA8,
NK_FONT_ATLAS_RGBA32
};
struct nk_font_atlas {
void *pixel;
int tex_width;
int tex_height;
struct nk_allocator permanent;
struct nk_allocator temporary;
struct nk_recti custom;
struct nk_cursor cursors[NK_CURSOR_COUNT];
int glyph_count;
struct nk_font_glyph *glyphs;
struct nk_font *default_font;
struct nk_font *fonts;
struct nk_font_config *config;
int font_num;
};
/* some language glyph codepoint ranges */
NK_API const nk_rune *nk_font_default_glyph_ranges(void);
NK_API const nk_rune *nk_font_chinese_glyph_ranges(void);
NK_API const nk_rune *nk_font_cyrillic_glyph_ranges(void);
NK_API const nk_rune *nk_font_korean_glyph_ranges(void);
#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR
NK_API void nk_font_atlas_init_default(struct nk_font_atlas*);
#endif
NK_API void nk_font_atlas_init(struct nk_font_atlas*, struct nk_allocator*);
NK_API void nk_font_atlas_init_custom(struct nk_font_atlas*, struct nk_allocator *persistent, struct nk_allocator *transient);
NK_API void nk_font_atlas_begin(struct nk_font_atlas*);
NK_API struct nk_font_config nk_font_config(float pixel_height);
NK_API struct nk_font *nk_font_atlas_add(struct nk_font_atlas*, const struct nk_font_config*);
#ifdef NK_INCLUDE_DEFAULT_FONT
NK_API struct nk_font* nk_font_atlas_add_default(struct nk_font_atlas*, float height, const struct nk_font_config*);
#endif
NK_API struct nk_font* nk_font_atlas_add_from_memory(struct nk_font_atlas *atlas, void *memory, nk_size size, float height, const struct nk_font_config *config);
#ifdef NK_INCLUDE_STANDARD_IO
NK_API struct nk_font* nk_font_atlas_add_from_file(struct nk_font_atlas *atlas, const char *file_path, float height, const struct nk_font_config*);
#endif
NK_API struct nk_font *nk_font_atlas_add_compressed(struct nk_font_atlas*, void *memory, nk_size size, float height, const struct nk_font_config*);
NK_API struct nk_font* nk_font_atlas_add_compressed_base85(struct nk_font_atlas*, const char *data, float height, const struct nk_font_config *config);
NK_API const void* nk_font_atlas_bake(struct nk_font_atlas*, int *width, int *height, enum nk_font_atlas_format);
NK_API void nk_font_atlas_end(struct nk_font_atlas*, nk_handle tex, struct nk_draw_null_texture*);
NK_API const struct nk_font_glyph* nk_font_find_glyph(struct nk_font*, nk_rune unicode);
NK_API void nk_font_atlas_cleanup(struct nk_font_atlas *atlas);
NK_API void nk_font_atlas_clear(struct nk_font_atlas*);
#endif
/* ==============================================================
*
* MEMORY BUFFER
*
* ===============================================================*/
/* A basic (double)-buffer with linear allocation and resetting as only
freeing policy. The buffer's main purpose is to control all memory management
inside the GUI toolkit and still leave memory control as much as possible in
the hand of the user while also making sure the library is easy to use if
not as much control is needed.
In general all memory inside this library can be provided from the user in
three different ways.
The first way and the one providing most control is by just passing a fixed
size memory block. In this case all control lies in the hand of the user
since he can exactly control where the memory comes from and how much memory
the library should consume. Of course using the fixed size API removes the
ability to automatically resize a buffer if not enough memory is provided so
you have to take over the resizing. While being a fixed sized buffer sounds
quite limiting, it is very effective in this library since the actual memory
consumption is quite stable and has a fixed upper bound for a lot of cases.
If you don't want to think about how much memory the library should allocate
at all time or have a very dynamic UI with unpredictable memory consumption
habits but still want control over memory allocation you can use the dynamic
allocator based API. The allocator consists of two callbacks for allocating
and freeing memory and optional userdata so you can plugin your own allocator.
The final and easiest way can be used by defining
NK_INCLUDE_DEFAULT_ALLOCATOR which uses the standard library memory
allocation functions malloc and free and takes over complete control over
memory in this library.
*/
struct nk_memory_status {
void *memory;
unsigned int type;
nk_size size;
nk_size allocated;
nk_size needed;
nk_size calls;
};
enum nk_allocation_type {
NK_BUFFER_FIXED,
NK_BUFFER_DYNAMIC
};
enum nk_buffer_allocation_type {
NK_BUFFER_FRONT,
NK_BUFFER_BACK,
NK_BUFFER_MAX
};
struct nk_buffer_marker {
nk_bool active;
nk_size offset;
};
struct nk_memory {void *ptr;nk_size size;};
struct nk_buffer {
struct nk_buffer_marker marker[NK_BUFFER_MAX];
/* buffer marker to free a buffer to a certain offset */
struct nk_allocator pool;
/* allocator callback for dynamic buffers */
enum nk_allocation_type type;
/* memory management type */
struct nk_memory memory;
/* memory and size of the current memory block */
float grow_factor;
/* growing factor for dynamic memory management */
nk_size allocated;
/* total amount of memory allocated */
nk_size needed;
/* totally consumed memory given that enough memory is present */
nk_size calls;
/* number of allocation calls */
nk_size size;
/* current size of the buffer */
};
#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR
NK_API void nk_buffer_init_default(struct nk_buffer*);
#endif
NK_API void nk_buffer_init(struct nk_buffer*, const struct nk_allocator*, nk_size size);
NK_API void nk_buffer_init_fixed(struct nk_buffer*, void *memory, nk_size size);
NK_API void nk_buffer_info(struct nk_memory_status*, struct nk_buffer*);
NK_API void nk_buffer_push(struct nk_buffer*, enum nk_buffer_allocation_type type, const void *memory, nk_size size, nk_size align);
NK_API void nk_buffer_mark(struct nk_buffer*, enum nk_buffer_allocation_type type);
NK_API void nk_buffer_reset(struct nk_buffer*, enum nk_buffer_allocation_type type);
NK_API void nk_buffer_clear(struct nk_buffer*);
NK_API void nk_buffer_free(struct nk_buffer*);
NK_API void *nk_buffer_memory(struct nk_buffer*);
NK_API const void *nk_buffer_memory_const(const struct nk_buffer*);
NK_API nk_size nk_buffer_total(struct nk_buffer*);
/* ==============================================================
*
* STRING
*
* ===============================================================*/
/* Basic string buffer which is only used in context with the text editor
* to manage and manipulate dynamic or fixed size string content. This is _NOT_
* the default string handling method. The only instance you should have any contact
* with this API is if you interact with an `nk_text_edit` object inside one of the
* copy and paste functions and even there only for more advanced cases. */
struct nk_str {
struct nk_buffer buffer;
int len; /* in codepoints/runes/glyphs */
};
#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR
NK_API void nk_str_init_default(struct nk_str*);
#endif
NK_API void nk_str_init(struct nk_str*, const struct nk_allocator*, nk_size size);
NK_API void nk_str_init_fixed(struct nk_str*, void *memory, nk_size size);
NK_API void nk_str_clear(struct nk_str*);
NK_API void nk_str_free(struct nk_str*);
NK_API int nk_str_append_text_char(struct nk_str*, const char*, int);
NK_API int nk_str_append_str_char(struct nk_str*, const char*);
NK_API int nk_str_append_text_utf8(struct nk_str*, const char*, int);
NK_API int nk_str_append_str_utf8(struct nk_str*, const char*);
NK_API int nk_str_append_text_runes(struct nk_str*, const nk_rune*, int);
NK_API int nk_str_append_str_runes(struct nk_str*, const nk_rune*);
NK_API int nk_str_insert_at_char(struct nk_str*, int pos, const char*, int);
NK_API int nk_str_insert_at_rune(struct nk_str*, int pos, const char*, int);
NK_API int nk_str_insert_text_char(struct nk_str*, int pos, const char*, int);
NK_API int nk_str_insert_str_char(struct nk_str*, int pos, const char*);
NK_API int nk_str_insert_text_utf8(struct nk_str*, int pos, const char*, int);
NK_API int nk_str_insert_str_utf8(struct nk_str*, int pos, const char*);
NK_API int nk_str_insert_text_runes(struct nk_str*, int pos, const nk_rune*, int);
NK_API int nk_str_insert_str_runes(struct nk_str*, int pos, const nk_rune*);
NK_API void nk_str_remove_chars(struct nk_str*, int len);
NK_API void nk_str_remove_runes(struct nk_str *str, int len);
NK_API void nk_str_delete_chars(struct nk_str*, int pos, int len);
NK_API void nk_str_delete_runes(struct nk_str*, int pos, int len);
NK_API char *nk_str_at_char(struct nk_str*, int pos);
NK_API char *nk_str_at_rune(struct nk_str*, int pos, nk_rune *unicode, int *len);
NK_API nk_rune nk_str_rune_at(const struct nk_str*, int pos);
NK_API const char *nk_str_at_char_const(const struct nk_str*, int pos);
NK_API const char *nk_str_at_const(const struct nk_str*, int pos, nk_rune *unicode, int *len);
NK_API char *nk_str_get(struct nk_str*);
NK_API const char *nk_str_get_const(const struct nk_str*);
NK_API int nk_str_len(struct nk_str*);
NK_API int nk_str_len_char(struct nk_str*);
/*===============================================================
*
* TEXT EDITOR
*
* ===============================================================*/
/* Editing text in this library is handled by either `nk_edit_string` or
* `nk_edit_buffer`. But like almost everything in this library there are multiple
* ways of doing it and a balance between control and ease of use with memory
* as well as functionality controlled by flags.
*
* This library generally allows three different levels of memory control:
* First of is the most basic way of just providing a simple char array with
* string length. This method is probably the easiest way of handling simple
* user text input. Main upside is complete control over memory while the biggest
* downside in comparison with the other two approaches is missing undo/redo.
*
* For UIs that require undo/redo the second way was created. It is based on
* a fixed size nk_text_edit struct, which has an internal undo/redo stack.
* This is mainly useful if you want something more like a text editor but don't want
* to have a dynamically growing buffer.
*
* The final way is using a dynamically growing nk_text_edit struct, which
* has both a default version if you don't care where memory comes from and an
* allocator version if you do. While the text editor is quite powerful for its
* complexity I would not recommend editing gigabytes of data with it.
* It is rather designed for uses cases which make sense for a GUI library not for
* an full blown text editor.
*/
#ifndef NK_TEXTEDIT_UNDOSTATECOUNT
#define NK_TEXTEDIT_UNDOSTATECOUNT 99
#endif
#ifndef NK_TEXTEDIT_UNDOCHARCOUNT
#define NK_TEXTEDIT_UNDOCHARCOUNT 999
#endif
struct nk_text_edit;
struct nk_clipboard {
nk_handle userdata;
nk_plugin_paste paste;
nk_plugin_copy copy;
};
struct nk_text_undo_record {
int where;
short insert_length;
short delete_length;
short char_storage;
};
struct nk_text_undo_state {
struct nk_text_undo_record undo_rec[NK_TEXTEDIT_UNDOSTATECOUNT];
nk_rune undo_char[NK_TEXTEDIT_UNDOCHARCOUNT];
short undo_point;
short redo_point;
short undo_char_point;
short redo_char_point;
};
enum nk_text_edit_type {
NK_TEXT_EDIT_SINGLE_LINE,
NK_TEXT_EDIT_MULTI_LINE
};
enum nk_text_edit_mode {
NK_TEXT_EDIT_MODE_VIEW,
NK_TEXT_EDIT_MODE_INSERT,
NK_TEXT_EDIT_MODE_REPLACE
};
struct nk_text_edit {
struct nk_clipboard clip;
struct nk_str string;
nk_plugin_filter filter;
struct nk_vec2 scrollbar;
int cursor;
int select_start;
int select_end;
unsigned char mode;
unsigned char cursor_at_end_of_line;
unsigned char initialized;
unsigned char has_preferred_x;
unsigned char single_line;
unsigned char active;
unsigned char padding1;
float preferred_x;
struct nk_text_undo_state undo;
};
/* filter function */
NK_API nk_bool nk_filter_default(const struct nk_text_edit*, nk_rune unicode);
NK_API nk_bool nk_filter_ascii(const struct nk_text_edit*, nk_rune unicode);
NK_API nk_bool nk_filter_float(const struct nk_text_edit*, nk_rune unicode);
NK_API nk_bool nk_filter_decimal(const struct nk_text_edit*, nk_rune unicode);
NK_API nk_bool nk_filter_hex(const struct nk_text_edit*, nk_rune unicode);
NK_API nk_bool nk_filter_oct(const struct nk_text_edit*, nk_rune unicode);
NK_API nk_bool nk_filter_binary(const struct nk_text_edit*, nk_rune unicode);
/* text editor */
#ifdef NK_INCLUDE_DEFAULT_ALLOCATOR
NK_API void nk_textedit_init_default(struct nk_text_edit*);
#endif
NK_API void nk_textedit_init(struct nk_text_edit*, struct nk_allocator*, nk_size size);
NK_API void nk_textedit_init_fixed(struct nk_text_edit*, void *memory, nk_size size);
NK_API void nk_textedit_free(struct nk_text_edit*);
NK_API void nk_textedit_text(struct nk_text_edit*, const char*, int total_len);
NK_API void nk_textedit_delete(struct nk_text_edit*, int where, int len);
NK_API void nk_textedit_delete_selection(struct nk_text_edit*);
NK_API void nk_textedit_select_all(struct nk_text_edit*);
NK_API nk_bool nk_textedit_cut(struct nk_text_edit*);
NK_API nk_bool nk_textedit_paste(struct nk_text_edit*, char const*, int len);
NK_API void nk_textedit_undo(struct nk_text_edit*);
NK_API void nk_textedit_redo(struct nk_text_edit*);
/* ===============================================================
*
* DRAWING
*
* ===============================================================*/
/* This library was designed to be render backend agnostic so it does
not draw anything to screen. Instead all drawn shapes, widgets
are made of, are buffered into memory and make up a command queue.
Each frame therefore fills the command buffer with draw commands
that then need to be executed by the user and his own render backend.
After that the command buffer needs to be cleared and a new frame can be
started. It is probably important to note that the command buffer is the main
drawing API and the optional vertex buffer API only takes this format and
converts it into a hardware accessible format.
To use the command queue to draw your own widgets you can access the
command buffer of each window by calling `nk_window_get_canvas` after
previously having called `nk_begin`:
void draw_red_rectangle_widget(struct nk_context *ctx)
{
struct nk_command_buffer *canvas;
struct nk_input *input = &ctx->input;
canvas = nk_window_get_canvas(ctx);
struct nk_rect space;
enum nk_widget_layout_states state;
state = nk_widget(&space, ctx);
if (!state) return;
if (state != NK_WIDGET_ROM)
update_your_widget_by_user_input(...);
nk_fill_rect(canvas, space, 0, nk_rgb(255,0,0));
}
if (nk_begin(...)) {
nk_layout_row_dynamic(ctx, 25, 1);
draw_red_rectangle_widget(ctx);
}
nk_end(..)
Important to know if you want to create your own widgets is the `nk_widget`
call. It allocates space on the panel reserved for this widget to be used,
but also returns the state of the widget space. If your widget is not seen and does
not have to be updated it is '0' and you can just return. If it only has
to be drawn the state will be `NK_WIDGET_ROM` otherwise you can do both
update and draw your widget. The reason for separating is to only draw and
update what is actually necessary which is crucial for performance.
*/
enum nk_command_type {
NK_COMMAND_NOP,
NK_COMMAND_SCISSOR,
NK_COMMAND_LINE,
NK_COMMAND_CURVE,
NK_COMMAND_RECT,
NK_COMMAND_RECT_FILLED,
NK_COMMAND_RECT_MULTI_COLOR,
NK_COMMAND_CIRCLE,
NK_COMMAND_CIRCLE_FILLED,
NK_COMMAND_ARC,
NK_COMMAND_ARC_FILLED,
NK_COMMAND_TRIANGLE,
NK_COMMAND_TRIANGLE_FILLED,
NK_COMMAND_POLYGON,
NK_COMMAND_POLYGON_FILLED,
NK_COMMAND_POLYLINE,
NK_COMMAND_TEXT,
NK_COMMAND_IMAGE,
NK_COMMAND_CUSTOM
};
/* command base and header of every command inside the buffer */
struct nk_command {
enum nk_command_type type;
nk_size next;
#ifdef NK_INCLUDE_COMMAND_USERDATA
nk_handle userdata;
#endif
};
struct nk_command_scissor {
struct nk_command header;
short x, y;
unsigned short w, h;
};
struct nk_command_line {
struct nk_command header;
unsigned short line_thickness;
struct nk_vec2i begin;
struct nk_vec2i end;
struct nk_color color;
};
struct nk_command_curve {
struct nk_command header;
unsigned short line_thickness;
struct nk_vec2i begin;
struct nk_vec2i end;
struct nk_vec2i ctrl[2];
struct nk_color color;
};
struct nk_command_rect {
struct nk_command header;
unsigned short rounding;
unsigned short line_thickness;
short x, y;
unsigned short w, h;
struct nk_color color;
};
struct nk_command_rect_filled {
struct nk_command header;
unsigned short rounding;
short x, y;
unsigned short w, h;
struct nk_color color;
};
struct nk_command_rect_multi_color {
struct nk_command header;
short x, y;
unsigned short w, h;
struct nk_color left;
struct nk_color top;
struct nk_color bottom;
struct nk_color right;
};
struct nk_command_triangle {
struct nk_command header;
unsigned short line_thickness;
struct nk_vec2i a;
struct nk_vec2i b;
struct nk_vec2i c;
struct nk_color color;
};
struct nk_command_triangle_filled {
struct nk_command header;
struct nk_vec2i a;
struct nk_vec2i b;
struct nk_vec2i c;
struct nk_color color;
};
struct nk_command_circle {
struct nk_command header;
short x, y;
unsigned short line_thickness;
unsigned short w, h;
struct nk_color color;
};
struct nk_command_circle_filled {
struct nk_command header;
short x, y;
unsigned short w, h;
struct nk_color color;
};
struct nk_command_arc {
struct nk_command header;
short cx, cy;
unsigned short r;
unsigned short line_thickness;
float a[2];
struct nk_color color;
};
struct nk_command_arc_filled {
struct nk_command header;
short cx, cy;
unsigned short r;
float a[2];
struct nk_color color;
};
struct nk_command_polygon {
struct nk_command header;
struct nk_color color;
unsigned short line_thickness;
unsigned short point_count;
struct nk_vec2i points[1];
};
struct nk_command_polygon_filled {
struct nk_command header;
struct nk_color color;
unsigned short point_count;
struct nk_vec2i points[1];
};
struct nk_command_polyline {
struct nk_command header;
struct nk_color color;
unsigned short line_thickness;
unsigned short point_count;
struct nk_vec2i points[1];
};
struct nk_command_image {
struct nk_command header;
short x, y;
unsigned short w, h;
struct nk_image img;
struct nk_color col;
};
typedef void (*nk_command_custom_callback)(void *canvas, short x,short y,
unsigned short w, unsigned short h, nk_handle callback_data);
struct nk_command_custom {
struct nk_command header;
short x, y;
unsigned short w, h;
nk_handle callback_data;
nk_command_custom_callback callback;
};
struct nk_command_text {
struct nk_command header;
const struct nk_user_font *font;
struct nk_color background;
struct nk_color foreground;
short x, y;
unsigned short w, h;
float height;
int length;
char string[1];
};
enum nk_command_clipping {
NK_CLIPPING_OFF = nk_false,
NK_CLIPPING_ON = nk_true
};
struct nk_command_buffer {
struct nk_buffer *base;
struct nk_rect clip;
int use_clipping;
nk_handle userdata;
nk_size begin, end, last;
};
/* shape outlines */
NK_API void nk_stroke_line(struct nk_command_buffer *b, float x0, float y0, float x1, float y1, float line_thickness, struct nk_color);
NK_API void nk_stroke_curve(struct nk_command_buffer*, float, float, float, float, float, float, float, float, float line_thickness, struct nk_color);
NK_API void nk_stroke_rect(struct nk_command_buffer*, struct nk_rect, float rounding, float line_thickness, struct nk_color);
NK_API void nk_stroke_circle(struct nk_command_buffer*, struct nk_rect, float line_thickness, struct nk_color);
NK_API void nk_stroke_arc(struct nk_command_buffer*, float cx, float cy, float radius, float a_min, float a_max, float line_thickness, struct nk_color);
NK_API void nk_stroke_triangle(struct nk_command_buffer*, float, float, float, float, float, float, float line_thichness, struct nk_color);
NK_API void nk_stroke_polyline(struct nk_command_buffer*, float *points, int point_count, float line_thickness, struct nk_color col);
NK_API void nk_stroke_polygon(struct nk_command_buffer*, float*, int point_count, float line_thickness, struct nk_color);
/* filled shades */
NK_API void nk_fill_rect(struct nk_command_buffer*, struct nk_rect, float rounding, struct nk_color);
NK_API void nk_fill_rect_multi_color(struct nk_command_buffer*, struct nk_rect, struct nk_color left, struct nk_color top, struct nk_color right, struct nk_color bottom);
NK_API void nk_fill_circle(struct nk_command_buffer*, struct nk_rect, struct nk_color);
NK_API void nk_fill_arc(struct nk_command_buffer*, float cx, float cy, float radius, float a_min, float a_max, struct nk_color);
NK_API void nk_fill_triangle(struct nk_command_buffer*, float x0, float y0, float x1, float y1, float x2, float y2, struct nk_color);
NK_API void nk_fill_polygon(struct nk_command_buffer*, float*, int point_count, struct nk_color);
/* misc */
NK_API void nk_draw_image(struct nk_command_buffer*, struct nk_rect, const struct nk_image*, struct nk_color);
NK_API void nk_draw_nine_slice(struct nk_command_buffer*, struct nk_rect, const struct nk_nine_slice*, struct nk_color);
NK_API void nk_draw_text(struct nk_command_buffer*, struct nk_rect, const char *text, int len, const struct nk_user_font*, struct nk_color, struct nk_color);
NK_API void nk_push_scissor(struct nk_command_buffer*, struct nk_rect);
NK_API void nk_push_custom(struct nk_command_buffer*, struct nk_rect, nk_command_custom_callback, nk_handle usr);
/* ===============================================================
*
* INPUT
*
* ===============================================================*/
struct nk_mouse_button {
nk_bool down;
unsigned int clicked;
struct nk_vec2 clicked_pos;
};
struct nk_mouse {
struct nk_mouse_button buttons[NK_BUTTON_MAX];
struct nk_vec2 pos;
struct nk_vec2 prev;
struct nk_vec2 delta;
struct nk_vec2 scroll_delta;
unsigned char grab;
unsigned char grabbed;
unsigned char ungrab;
};
struct nk_key {
nk_bool down;
unsigned int clicked;
};
struct nk_keyboard {
struct nk_key keys[NK_KEY_MAX];
char text[NK_INPUT_MAX];
int text_len;
};
struct nk_input {
struct nk_keyboard keyboard;
struct nk_mouse mouse;
};
NK_API nk_bool nk_input_has_mouse_click(const struct nk_input*, enum nk_buttons);
NK_API nk_bool nk_input_has_mouse_click_in_rect(const struct nk_input*, enum nk_buttons, struct nk_rect);
NK_API nk_bool nk_input_has_mouse_click_down_in_rect(const struct nk_input*, enum nk_buttons, struct nk_rect, nk_bool down);
NK_API nk_bool nk_input_is_mouse_click_in_rect(const struct nk_input*, enum nk_buttons, struct nk_rect);
NK_API nk_bool nk_input_is_mouse_click_down_in_rect(const struct nk_input *i, enum nk_buttons id, struct nk_rect b, nk_bool down);
NK_API nk_bool nk_input_any_mouse_click_in_rect(const struct nk_input*, struct nk_rect);
NK_API nk_bool nk_input_is_mouse_prev_hovering_rect(const struct nk_input*, struct nk_rect);
NK_API nk_bool nk_input_is_mouse_hovering_rect(const struct nk_input*, struct nk_rect);
NK_API nk_bool nk_input_mouse_clicked(const struct nk_input*, enum nk_buttons, struct nk_rect);
NK_API nk_bool nk_input_is_mouse_down(const struct nk_input*, enum nk_buttons);
NK_API nk_bool nk_input_is_mouse_pressed(const struct nk_input*, enum nk_buttons);
NK_API nk_bool nk_input_is_mouse_released(const struct nk_input*, enum nk_buttons);
NK_API nk_bool nk_input_is_key_pressed(const struct nk_input*, enum nk_keys);
NK_API nk_bool nk_input_is_key_released(const struct nk_input*, enum nk_keys);
NK_API nk_bool nk_input_is_key_down(const struct nk_input*, enum nk_keys);
/* ===============================================================
*
* DRAW LIST
*
* ===============================================================*/
#ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT
/* The optional vertex buffer draw list provides a 2D drawing context
with antialiasing functionality which takes basic filled or outlined shapes
or a path and outputs vertexes, elements and draw commands.
The actual draw list API is not required to be used directly while using this
library since converting the default library draw command output is done by
just calling `nk_convert` but I decided to still make this library accessible
since it can be useful.
The draw list is based on a path buffering and polygon and polyline
rendering API which allows a lot of ways to draw 2D content to screen.
In fact it is probably more powerful than needed but allows even more crazy
things than this library provides by default.
*/
#ifdef NK_UINT_DRAW_INDEX
typedef nk_uint nk_draw_index;
#else
typedef nk_ushort nk_draw_index;
#endif
enum nk_draw_list_stroke {
NK_STROKE_OPEN = nk_false,
/* build up path has no connection back to the beginning */
NK_STROKE_CLOSED = nk_true
/* build up path has a connection back to the beginning */
};
enum nk_draw_vertex_layout_attribute {
NK_VERTEX_POSITION,
NK_VERTEX_COLOR,
NK_VERTEX_TEXCOORD,
NK_VERTEX_ATTRIBUTE_COUNT
};
enum nk_draw_vertex_layout_format {
NK_FORMAT_SCHAR,
NK_FORMAT_SSHORT,
NK_FORMAT_SINT,
NK_FORMAT_UCHAR,
NK_FORMAT_USHORT,
NK_FORMAT_UINT,
NK_FORMAT_FLOAT,
NK_FORMAT_DOUBLE,
NK_FORMAT_COLOR_BEGIN,
NK_FORMAT_R8G8B8 = NK_FORMAT_COLOR_BEGIN,
NK_FORMAT_R16G15B16,
NK_FORMAT_R32G32B32,
NK_FORMAT_R8G8B8A8,
NK_FORMAT_B8G8R8A8,
NK_FORMAT_R16G15B16A16,
NK_FORMAT_R32G32B32A32,
NK_FORMAT_R32G32B32A32_FLOAT,
NK_FORMAT_R32G32B32A32_DOUBLE,
NK_FORMAT_RGB32,
NK_FORMAT_RGBA32,
NK_FORMAT_COLOR_END = NK_FORMAT_RGBA32,
NK_FORMAT_COUNT
};
#define NK_VERTEX_LAYOUT_END NK_VERTEX_ATTRIBUTE_COUNT,NK_FORMAT_COUNT,0
struct nk_draw_vertex_layout_element {
enum nk_draw_vertex_layout_attribute attribute;
enum nk_draw_vertex_layout_format format;
nk_size offset;
};
struct nk_draw_command {
unsigned int elem_count;
/* number of elements in the current draw batch */
struct nk_rect clip_rect;
/* current screen clipping rectangle */
nk_handle texture;
/* current texture to set */
#ifdef NK_INCLUDE_COMMAND_USERDATA
nk_handle userdata;
#endif
};
struct nk_draw_list {
struct nk_rect clip_rect;
struct nk_vec2 circle_vtx[12];
struct nk_convert_config config;
struct nk_buffer *buffer;
struct nk_buffer *vertices;
struct nk_buffer *elements;
unsigned int element_count;
unsigned int vertex_count;
unsigned int cmd_count;
nk_size cmd_offset;
unsigned int path_count;
unsigned int path_offset;
enum nk_anti_aliasing line_AA;
enum nk_anti_aliasing shape_AA;
#ifdef NK_INCLUDE_COMMAND_USERDATA
nk_handle userdata;
#endif
};
/* draw list */
NK_API void nk_draw_list_init(struct nk_draw_list*);
NK_API void nk_draw_list_setup(struct nk_draw_list*, const struct nk_convert_config*, struct nk_buffer *cmds, struct nk_buffer *vertices, struct nk_buffer *elements, enum nk_anti_aliasing line_aa,enum nk_anti_aliasing shape_aa);
/* drawing */
#define nk_draw_list_foreach(cmd, can, b) for((cmd)=nk__draw_list_begin(can, b); (cmd)!=0; (cmd)=nk__draw_list_next(cmd, b, can))
NK_API const struct nk_draw_command* nk__draw_list_begin(const struct nk_draw_list*, const struct nk_buffer*);
NK_API const struct nk_draw_command* nk__draw_list_next(const struct nk_draw_command*, const struct nk_buffer*, const struct nk_draw_list*);
NK_API const struct nk_draw_command* nk__draw_list_end(const struct nk_draw_list*, const struct nk_buffer*);
/* path */
NK_API void nk_draw_list_path_clear(struct nk_draw_list*);
NK_API void nk_draw_list_path_line_to(struct nk_draw_list*, struct nk_vec2 pos);
NK_API void nk_draw_list_path_arc_to_fast(struct nk_draw_list*, struct nk_vec2 center, float radius, int a_min, int a_max);
NK_API void nk_draw_list_path_arc_to(struct nk_draw_list*, struct nk_vec2 center, float radius, float a_min, float a_max, unsigned int segments);
NK_API void nk_draw_list_path_rect_to(struct nk_draw_list*, struct nk_vec2 a, struct nk_vec2 b, float rounding);
NK_API void nk_draw_list_path_curve_to(struct nk_draw_list*, struct nk_vec2 p2, struct nk_vec2 p3, struct nk_vec2 p4, unsigned int num_segments);
NK_API void nk_draw_list_path_fill(struct nk_draw_list*, struct nk_color);
NK_API void nk_draw_list_path_stroke(struct nk_draw_list*, struct nk_color, enum nk_draw_list_stroke closed, float thickness);
/* stroke */
NK_API void nk_draw_list_stroke_line(struct nk_draw_list*, struct nk_vec2 a, struct nk_vec2 b, struct nk_color, float thickness);
NK_API void nk_draw_list_stroke_rect(struct nk_draw_list*, struct nk_rect rect, struct nk_color, float rounding, float thickness);
NK_API void nk_draw_list_stroke_triangle(struct nk_draw_list*, struct nk_vec2 a, struct nk_vec2 b, struct nk_vec2 c, struct nk_color, float thickness);
NK_API void nk_draw_list_stroke_circle(struct nk_draw_list*, struct nk_vec2 center, float radius, struct nk_color, unsigned int segs, float thickness);
NK_API void nk_draw_list_stroke_curve(struct nk_draw_list*, struct nk_vec2 p0, struct nk_vec2 cp0, struct nk_vec2 cp1, struct nk_vec2 p1, struct nk_color, unsigned int segments, float thickness);
NK_API void nk_draw_list_stroke_poly_line(struct nk_draw_list*, const struct nk_vec2 *pnts, const unsigned int cnt, struct nk_color, enum nk_draw_list_stroke, float thickness, enum nk_anti_aliasing);
/* fill */
NK_API void nk_draw_list_fill_rect(struct nk_draw_list*, struct nk_rect rect, struct nk_color, float rounding);
NK_API void nk_draw_list_fill_rect_multi_color(struct nk_draw_list*, struct nk_rect rect, struct nk_color left, struct nk_color top, struct nk_color right, struct nk_color bottom);
NK_API void nk_draw_list_fill_triangle(struct nk_draw_list*, struct nk_vec2 a, struct nk_vec2 b, struct nk_vec2 c, struct nk_color);
NK_API void nk_draw_list_fill_circle(struct nk_draw_list*, struct nk_vec2 center, float radius, struct nk_color col, unsigned int segs);
NK_API void nk_draw_list_fill_poly_convex(struct nk_draw_list*, const struct nk_vec2 *points, const unsigned int count, struct nk_color, enum nk_anti_aliasing);
/* misc */
NK_API void nk_draw_list_add_image(struct nk_draw_list*, struct nk_image texture, struct nk_rect rect, struct nk_color);
NK_API void nk_draw_list_add_text(struct nk_draw_list*, const struct nk_user_font*, struct nk_rect, const char *text, int len, float font_height, struct nk_color);
#ifdef NK_INCLUDE_COMMAND_USERDATA
NK_API void nk_draw_list_push_userdata(struct nk_draw_list*, nk_handle userdata);
#endif
#endif
/* ===============================================================
*
* GUI
*
* ===============================================================*/
enum nk_style_item_type {
NK_STYLE_ITEM_COLOR,
NK_STYLE_ITEM_IMAGE,
NK_STYLE_ITEM_NINE_SLICE
};
union nk_style_item_data {
struct nk_color color;
struct nk_image image;
struct nk_nine_slice slice;
};
struct nk_style_item {
enum nk_style_item_type type;
union nk_style_item_data data;
};
struct nk_style_text {
struct nk_color color;
struct nk_vec2 padding;
};
struct nk_style_button {
/* background */
struct nk_style_item normal;
struct nk_style_item hover;
struct nk_style_item active;
struct nk_color border_color;
/* text */
struct nk_color text_background;
struct nk_color text_normal;
struct nk_color text_hover;
struct nk_color text_active;
nk_flags text_alignment;
/* properties */
float border;
float rounding;
struct nk_vec2 padding;
struct nk_vec2 image_padding;
struct nk_vec2 touch_padding;
/* optional user callbacks */
nk_handle userdata;
void(*draw_begin)(struct nk_command_buffer*, nk_handle userdata);
void(*draw_end)(struct nk_command_buffer*, nk_handle userdata);
};
struct nk_style_toggle {
/* background */
struct nk_style_item normal;
struct nk_style_item hover;
struct nk_style_item active;
struct nk_color border_color;
/* cursor */
struct nk_style_item cursor_normal;
struct nk_style_item cursor_hover;
/* text */
struct nk_color text_normal;
struct nk_color text_hover;
struct nk_color text_active;
struct nk_color text_background;
nk_flags text_alignment;
/* properties */
struct nk_vec2 padding;
struct nk_vec2 touch_padding;
float spacing;
float border;
/* optional user callbacks */
nk_handle userdata;
void(*draw_begin)(struct nk_command_buffer*, nk_handle);
void(*draw_end)(struct nk_command_buffer*, nk_handle);
};
struct nk_style_selectable {
/* background (inactive) */
struct nk_style_item normal;
struct nk_style_item hover;
struct nk_style_item pressed;
/* background (active) */
struct nk_style_item normal_active;
struct nk_style_item hover_active;
struct nk_style_item pressed_active;
/* text color (inactive) */
struct nk_color text_normal;
struct nk_color text_hover;
struct nk_color text_pressed;
/* text color (active) */
struct nk_color text_normal_active;
struct nk_color text_hover_active;
struct nk_color text_pressed_active;
struct nk_color text_background;
nk_flags text_alignment;
/* properties */
float rounding;
struct nk_vec2 padding;
struct nk_vec2 touch_padding;
struct nk_vec2 image_padding;
/* optional user callbacks */
nk_handle userdata;
void(*draw_begin)(struct nk_command_buffer*, nk_handle);
void(*draw_end)(struct nk_command_buffer*, nk_handle);
};
struct nk_style_slider {
/* background */
struct nk_style_item normal;
struct nk_style_item hover;
struct nk_style_item active;
struct nk_color border_color;
/* background bar */
struct nk_color bar_normal;
struct nk_color bar_hover;
struct nk_color bar_active;
struct nk_color bar_filled;
/* cursor */
struct nk_style_item cursor_normal;
struct nk_style_item cursor_hover;
struct nk_style_item cursor_active;
/* properties */
float border;
float rounding;
float bar_height;
struct nk_vec2 padding;
struct nk_vec2 spacing;
struct nk_vec2 cursor_size;
/* optional buttons */
int show_buttons;
struct nk_style_button inc_button;
struct nk_style_button dec_button;
enum nk_symbol_type inc_symbol;
enum nk_symbol_type dec_symbol;
/* optional user callbacks */
nk_handle userdata;
void(*draw_begin)(struct nk_command_buffer*, nk_handle);
void(*draw_end)(struct nk_command_buffer*, nk_handle);
};
struct nk_style_progress {
/* background */
struct nk_style_item normal;
struct nk_style_item hover;
struct nk_style_item active;
struct nk_color border_color;
/* cursor */
struct nk_style_item cursor_normal;
struct nk_style_item cursor_hover;
struct nk_style_item cursor_active;
struct nk_color cursor_border_color;
/* properties */
float rounding;
float border;
float cursor_border;
float cursor_rounding;
struct nk_vec2 padding;
/* optional user callbacks */
nk_handle userdata;
void(*draw_begin)(struct nk_command_buffer*, nk_handle);
void(*draw_end)(struct nk_command_buffer*, nk_handle);
};
struct nk_style_scrollbar {
/* background */
struct nk_style_item normal;
struct nk_style_item hover;
struct nk_style_item active;
struct nk_color border_color;
/* cursor */
struct nk_style_item cursor_normal;
struct nk_style_item cursor_hover;
struct nk_style_item cursor_active;
struct nk_color cursor_border_color;
/* properties */
float border;
float rounding;
float border_cursor;
float rounding_cursor;
struct nk_vec2 padding;
/* optional buttons */
int show_buttons;
struct nk_style_button inc_button;
struct nk_style_button dec_button;
enum nk_symbol_type inc_symbol;
enum nk_symbol_type dec_symbol;
/* optional user callbacks */
nk_handle userdata;
void(*draw_begin)(struct nk_command_buffer*, nk_handle);
void(*draw_end)(struct nk_command_buffer*, nk_handle);
};
struct nk_style_edit {
/* background */
struct nk_style_item normal;
struct nk_style_item hover;
struct nk_style_item active;
struct nk_color border_color;
struct nk_style_scrollbar scrollbar;
/* cursor */
struct nk_color cursor_normal;
struct nk_color cursor_hover;
struct nk_color cursor_text_normal;
struct nk_color cursor_text_hover;
/* text (unselected) */
struct nk_color text_normal;
struct nk_color text_hover;
struct nk_color text_active;
/* text (selected) */
struct nk_color selected_normal;
struct nk_color selected_hover;
struct nk_color selected_text_normal;
struct nk_color selected_text_hover;
/* properties */
float border;
float rounding;
float cursor_size;
struct nk_vec2 scrollbar_size;
struct nk_vec2 padding;
float row_padding;
};
struct nk_style_property {
/* background */
struct nk_style_item normal;
struct nk_style_item hover;
struct nk_style_item active;
struct nk_color border_color;
/* text */
struct nk_color label_normal;
struct nk_color label_hover;
struct nk_color label_active;
/* symbols */
enum nk_symbol_type sym_left;
enum nk_symbol_type sym_right;
/* properties */
float border;
float rounding;
struct nk_vec2 padding;
struct nk_style_edit edit;
struct nk_style_button inc_button;
struct nk_style_button dec_button;
/* optional user callbacks */
nk_handle userdata;
void(*draw_begin)(struct nk_command_buffer*, nk_handle);
void(*draw_end)(struct nk_command_buffer*, nk_handle);
};
struct nk_style_chart {
/* colors */
struct nk_style_item background;
struct nk_color border_color;
struct nk_color selected_color;
struct nk_color color;
/* properties */
float border;
float rounding;
struct nk_vec2 padding;
};
struct nk_style_combo {
/* background */
struct nk_style_item normal;
struct nk_style_item hover;
struct nk_style_item active;
struct nk_color border_color;
/* label */
struct nk_color label_normal;
struct nk_color label_hover;
struct nk_color label_active;
/* symbol */
struct nk_color symbol_normal;
struct nk_color symbol_hover;
struct nk_color symbol_active;
/* button */
struct nk_style_button button;
enum nk_symbol_type sym_normal;
enum nk_symbol_type sym_hover;
enum nk_symbol_type sym_active;
/* properties */
float border;
float rounding;
struct nk_vec2 content_padding;
struct nk_vec2 button_padding;
struct nk_vec2 spacing;
};
struct nk_style_tab {
/* background */
struct nk_style_item background;
struct nk_color border_color;
struct nk_color text;
/* button */
struct nk_style_button tab_maximize_button;
struct nk_style_button tab_minimize_button;
struct nk_style_button node_maximize_button;
struct nk_style_button node_minimize_button;
enum nk_symbol_type sym_minimize;
enum nk_symbol_type sym_maximize;
/* properties */
float border;
float rounding;
float indent;
struct nk_vec2 padding;
struct nk_vec2 spacing;
};
enum nk_style_header_align {
NK_HEADER_LEFT,
NK_HEADER_RIGHT
};
struct nk_style_window_header {
/* background */
struct nk_style_item normal;
struct nk_style_item hover;
struct nk_style_item active;
/* button */
struct nk_style_button close_button;
struct nk_style_button minimize_button;
enum nk_symbol_type close_symbol;
enum nk_symbol_type minimize_symbol;
enum nk_symbol_type maximize_symbol;
/* title */
struct nk_color label_normal;
struct nk_color label_hover;
struct nk_color label_active;
/* properties */
enum nk_style_header_align align;
struct nk_vec2 padding;
struct nk_vec2 label_padding;
struct nk_vec2 spacing;
};
struct nk_style_window {
struct nk_style_window_header header;
struct nk_style_item fixed_background;
struct nk_color background;
struct nk_color border_color;
struct nk_color popup_border_color;
struct nk_color combo_border_color;
struct nk_color contextual_border_color;
struct nk_color menu_border_color;
struct nk_color group_border_color;
struct nk_color tooltip_border_color;
struct nk_style_item scaler;
float border;
float combo_border;
float contextual_border;
float menu_border;
float group_border;
float tooltip_border;
float popup_border;
float min_row_height_padding;
float rounding;
struct nk_vec2 spacing;
struct nk_vec2 scrollbar_size;
struct nk_vec2 min_size;
struct nk_vec2 padding;
struct nk_vec2 group_padding;
struct nk_vec2 popup_padding;
struct nk_vec2 combo_padding;
struct nk_vec2 contextual_padding;
struct nk_vec2 menu_padding;
struct nk_vec2 tooltip_padding;
};
struct nk_style {
const struct nk_user_font *font;
const struct nk_cursor *cursors[NK_CURSOR_COUNT];
const struct nk_cursor *cursor_active;
struct nk_cursor *cursor_last;
int cursor_visible;
struct nk_style_text text;
struct nk_style_button button;
struct nk_style_button contextual_button;
struct nk_style_button menu_button;
struct nk_style_toggle option;
struct nk_style_toggle checkbox;
struct nk_style_selectable selectable;
struct nk_style_slider slider;
struct nk_style_progress progress;
struct nk_style_property property;
struct nk_style_edit edit;
struct nk_style_chart chart;
struct nk_style_scrollbar scrollh;
struct nk_style_scrollbar scrollv;
struct nk_style_tab tab;
struct nk_style_combo combo;
struct nk_style_window window;
};
NK_API struct nk_style_item nk_style_item_color(struct nk_color);
NK_API struct nk_style_item nk_style_item_image(struct nk_image img);
NK_API struct nk_style_item nk_style_item_nine_slice(struct nk_nine_slice slice);
NK_API struct nk_style_item nk_style_item_hide(void);
/*==============================================================
* PANEL
* =============================================================*/
#ifndef NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS
#define NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS 16
#endif
#ifndef NK_CHART_MAX_SLOT
#define NK_CHART_MAX_SLOT 4
#endif
enum nk_panel_type {
NK_PANEL_NONE = 0,
NK_PANEL_WINDOW = NK_FLAG(0),
NK_PANEL_GROUP = NK_FLAG(1),
NK_PANEL_POPUP = NK_FLAG(2),
NK_PANEL_CONTEXTUAL = NK_FLAG(4),
NK_PANEL_COMBO = NK_FLAG(5),
NK_PANEL_MENU = NK_FLAG(6),
NK_PANEL_TOOLTIP = NK_FLAG(7)
};
enum nk_panel_set {
NK_PANEL_SET_NONBLOCK = NK_PANEL_CONTEXTUAL|NK_PANEL_COMBO|NK_PANEL_MENU|NK_PANEL_TOOLTIP,
NK_PANEL_SET_POPUP = NK_PANEL_SET_NONBLOCK|NK_PANEL_POPUP,
NK_PANEL_SET_SUB = NK_PANEL_SET_POPUP|NK_PANEL_GROUP
};
struct nk_chart_slot {
enum nk_chart_type type;
struct nk_color color;
struct nk_color highlight;
float min, max, range;
int count;
struct nk_vec2 last;
int index;
};
struct nk_chart {
int slot;
float x, y, w, h;
struct nk_chart_slot slots[NK_CHART_MAX_SLOT];
};
enum nk_panel_row_layout_type {
NK_LAYOUT_DYNAMIC_FIXED = 0,
NK_LAYOUT_DYNAMIC_ROW,
NK_LAYOUT_DYNAMIC_FREE,
NK_LAYOUT_DYNAMIC,
NK_LAYOUT_STATIC_FIXED,
NK_LAYOUT_STATIC_ROW,
NK_LAYOUT_STATIC_FREE,
NK_LAYOUT_STATIC,
NK_LAYOUT_TEMPLATE,
NK_LAYOUT_COUNT
};
struct nk_row_layout {
enum nk_panel_row_layout_type type;
int index;
float height;
float min_height;
int columns;
const float *ratio;
float item_width;
float item_height;
float item_offset;
float filled;
struct nk_rect item;
int tree_depth;
float templates[NK_MAX_LAYOUT_ROW_TEMPLATE_COLUMNS];
};
struct nk_popup_buffer {
nk_size begin;
nk_size parent;
nk_size last;
nk_size end;
nk_bool active;
};
struct nk_menu_state {
float x, y, w, h;
struct nk_scroll offset;
};
struct nk_panel {
enum nk_panel_type type;
nk_flags flags;
struct nk_rect bounds;
nk_uint *offset_x;
nk_uint *offset_y;
float at_x, at_y, max_x;
float footer_height;
float header_height;
float border;
unsigned int has_scrolling;
struct nk_rect clip;
struct nk_menu_state menu;
struct nk_row_layout row;
struct nk_chart chart;
struct nk_command_buffer *buffer;
struct nk_panel *parent;
};
/*==============================================================
* WINDOW
* =============================================================*/
#ifndef NK_WINDOW_MAX_NAME
#define NK_WINDOW_MAX_NAME 64
#endif
struct nk_table;
enum nk_window_flags {
NK_WINDOW_PRIVATE = NK_FLAG(11),
NK_WINDOW_DYNAMIC = NK_WINDOW_PRIVATE,
/* special window type growing up in height while being filled to a certain maximum height */
NK_WINDOW_ROM = NK_FLAG(12),
/* sets window widgets into a read only mode and does not allow input changes */
NK_WINDOW_NOT_INTERACTIVE = NK_WINDOW_ROM|NK_WINDOW_NO_INPUT,
/* prevents all interaction caused by input to either window or widgets inside */
NK_WINDOW_HIDDEN = NK_FLAG(13),
/* Hides window and stops any window interaction and drawing */
NK_WINDOW_CLOSED = NK_FLAG(14),
/* Directly closes and frees the window at the end of the frame */
NK_WINDOW_MINIMIZED = NK_FLAG(15),
/* marks the window as minimized */
NK_WINDOW_REMOVE_ROM = NK_FLAG(16)
/* Removes read only mode at the end of the window */
};
struct nk_popup_state {
struct nk_window *win;
enum nk_panel_type type;
struct nk_popup_buffer buf;
nk_hash name;
nk_bool active;
unsigned combo_count;
unsigned con_count, con_old;
unsigned active_con;
struct nk_rect header;
};
struct nk_edit_state {
nk_hash name;
unsigned int seq;
unsigned int old;
int active, prev;
int cursor;
int sel_start;
int sel_end;
struct nk_scroll scrollbar;
unsigned char mode;
unsigned char single_line;
};
struct nk_property_state {
int active, prev;
char buffer[NK_MAX_NUMBER_BUFFER];
int length;
int cursor;
int select_start;
int select_end;
nk_hash name;
unsigned int seq;
unsigned int old;
int state;
};
struct nk_window {
unsigned int seq;
nk_hash name;
char name_string[NK_WINDOW_MAX_NAME];
nk_flags flags;
struct nk_rect bounds;
struct nk_scroll scrollbar;
struct nk_command_buffer buffer;
struct nk_panel *layout;
float scrollbar_hiding_timer;
/* persistent widget state */
struct nk_property_state property;
struct nk_popup_state popup;
struct nk_edit_state edit;
unsigned int scrolled;
struct nk_table *tables;
unsigned int table_count;
/* window list hooks */
struct nk_window *next;
struct nk_window *prev;
struct nk_window *parent;
};
/*==============================================================
* STACK
* =============================================================*/
/* The style modifier stack can be used to temporarily change a
* property inside `nk_style`. For example if you want a special
* red button you can temporarily push the old button color onto a stack
* draw the button with a red color and then you just pop the old color
* back from the stack:
*
* nk_style_push_style_item(ctx, &ctx->style.button.normal, nk_style_item_color(nk_rgb(255,0,0)));
* nk_style_push_style_item(ctx, &ctx->style.button.hover, nk_style_item_color(nk_rgb(255,0,0)));
* nk_style_push_style_item(ctx, &ctx->style.button.active, nk_style_item_color(nk_rgb(255,0,0)));
* nk_style_push_vec2(ctx, &cx->style.button.padding, nk_vec2(2,2));
*
* nk_button(...);
*
* nk_style_pop_style_item(ctx);
* nk_style_pop_style_item(ctx);
* nk_style_pop_style_item(ctx);
* nk_style_pop_vec2(ctx);
*
* Nuklear has a stack for style_items, float properties, vector properties,
* flags, colors, fonts and for button_behavior. Each has it's own fixed size stack
* which can be changed at compile time.
*/
#ifndef NK_BUTTON_BEHAVIOR_STACK_SIZE
#define NK_BUTTON_BEHAVIOR_STACK_SIZE 8
#endif
#ifndef NK_FONT_STACK_SIZE
#define NK_FONT_STACK_SIZE 8
#endif
#ifndef NK_STYLE_ITEM_STACK_SIZE
#define NK_STYLE_ITEM_STACK_SIZE 16
#endif
#ifndef NK_FLOAT_STACK_SIZE
#define NK_FLOAT_STACK_SIZE 32
#endif
#ifndef NK_VECTOR_STACK_SIZE
#define NK_VECTOR_STACK_SIZE 16
#endif
#ifndef NK_FLAGS_STACK_SIZE
#define NK_FLAGS_STACK_SIZE 32
#endif
#ifndef NK_COLOR_STACK_SIZE
#define NK_COLOR_STACK_SIZE 32
#endif
#define NK_CONFIGURATION_STACK_TYPE(prefix, name, type)\
struct nk_config_stack_##name##_element {\
prefix##_##type *address;\
prefix##_##type old_value;\
}
#define NK_CONFIG_STACK(type,size)\
struct nk_config_stack_##type {\
int head;\
struct nk_config_stack_##type##_element elements[size];\
}
#define nk_float float
NK_CONFIGURATION_STACK_TYPE(struct nk, style_item, style_item);
NK_CONFIGURATION_STACK_TYPE(nk ,float, float);
NK_CONFIGURATION_STACK_TYPE(struct nk, vec2, vec2);
NK_CONFIGURATION_STACK_TYPE(nk ,flags, flags);
NK_CONFIGURATION_STACK_TYPE(struct nk, color, color);
NK_CONFIGURATION_STACK_TYPE(const struct nk, user_font, user_font*);
NK_CONFIGURATION_STACK_TYPE(enum nk, button_behavior, button_behavior);
NK_CONFIG_STACK(style_item, NK_STYLE_ITEM_STACK_SIZE);
NK_CONFIG_STACK(float, NK_FLOAT_STACK_SIZE);
NK_CONFIG_STACK(vec2, NK_VECTOR_STACK_SIZE);
NK_CONFIG_STACK(flags, NK_FLAGS_STACK_SIZE);
NK_CONFIG_STACK(color, NK_COLOR_STACK_SIZE);
NK_CONFIG_STACK(user_font, NK_FONT_STACK_SIZE);
NK_CONFIG_STACK(button_behavior, NK_BUTTON_BEHAVIOR_STACK_SIZE);
struct nk_configuration_stacks {
struct nk_config_stack_style_item style_items;
struct nk_config_stack_float floats;
struct nk_config_stack_vec2 vectors;
struct nk_config_stack_flags flags;
struct nk_config_stack_color colors;
struct nk_config_stack_user_font fonts;
struct nk_config_stack_button_behavior button_behaviors;
};
/*==============================================================
* CONTEXT
* =============================================================*/
#define NK_VALUE_PAGE_CAPACITY \
(((NK_MAX(sizeof(struct nk_window),sizeof(struct nk_panel)) / sizeof(nk_uint))) / 2)
struct nk_table {
unsigned int seq;
unsigned int size;
nk_hash keys[NK_VALUE_PAGE_CAPACITY];
nk_uint values[NK_VALUE_PAGE_CAPACITY];
struct nk_table *next, *prev;
};
union nk_page_data {
struct nk_table tbl;
struct nk_panel pan;
struct nk_window win;
};
struct nk_page_element {
union nk_page_data data;
struct nk_page_element *next;
struct nk_page_element *prev;
};
struct nk_page {
unsigned int size;
struct nk_page *next;
struct nk_page_element win[1];
};
struct nk_pool {
struct nk_allocator alloc;
enum nk_allocation_type type;
unsigned int page_count;
struct nk_page *pages;
struct nk_page_element *freelist;
unsigned capacity;
nk_size size;
nk_size cap;
};
struct nk_context {
/* public: can be accessed freely */
struct nk_input input;
struct nk_style style;
struct nk_buffer memory;
struct nk_clipboard clip;
nk_flags last_widget_state;
enum nk_button_behavior button_behavior;
struct nk_configuration_stacks stacks;
float delta_time_seconds;
/* private:
should only be accessed if you
know what you are doing */
#ifdef NK_INCLUDE_VERTEX_BUFFER_OUTPUT
struct nk_draw_list draw_list;
#endif
#ifdef NK_INCLUDE_COMMAND_USERDATA
nk_handle userdata;
#endif
/* text editor objects are quite big because of an internal
* undo/redo stack. Therefore it does not make sense to have one for
* each window for temporary use cases, so I only provide *one* instance
* for all windows. This works because the content is cleared anyway */
struct nk_text_edit text_edit;
/* draw buffer used for overlay drawing operation like cursor */
struct nk_command_buffer overlay;
/* windows */
int build;
int use_pool;
struct nk_pool pool;
struct nk_window *begin;
struct nk_window *end;
struct nk_window *active;
struct nk_window *current;
struct nk_page_element *freelist;
unsigned int count;
unsigned int seq;
};
/* ==============================================================
* MATH
* =============================================================== */
#define NK_PI 3.141592654f
#define NK_UTF_INVALID 0xFFFD
#define NK_MAX_FLOAT_PRECISION 2
#define NK_UNUSED(x) ((void)(x))
#define NK_SATURATE(x) (NK_MAX(0, NK_MIN(1.0f, x)))
#define NK_LEN(a) (sizeof(a)/sizeof(a)[0])
#define NK_ABS(a) (((a) < 0) ? -(a) : (a))
#define NK_BETWEEN(x, a, b) ((a) <= (x) && (x) < (b))
#define NK_INBOX(px, py, x, y, w, h)\
(NK_BETWEEN(px,x,x+w) && NK_BETWEEN(py,y,y+h))
#define NK_INTERSECT(x0, y0, w0, h0, x1, y1, w1, h1) \
((x1 < (x0 + w0)) && (x0 < (x1 + w1)) && \
(y1 < (y0 + h0)) && (y0 < (y1 + h1)))
#define NK_CONTAINS(x, y, w, h, bx, by, bw, bh)\
(NK_INBOX(x,y, bx, by, bw, bh) && NK_INBOX(x+w,y+h, bx, by, bw, bh))
#define nk_vec2_sub(a, b) nk_vec2((a).x - (b).x, (a).y - (b).y)
#define nk_vec2_add(a, b) nk_vec2((a).x + (b).x, (a).y + (b).y)
#define nk_vec2_len_sqr(a) ((a).x*(a).x+(a).y*(a).y)
#define nk_vec2_muls(a, t) nk_vec2((a).x * (t), (a).y * (t))
#define nk_ptr_add(t, p, i) ((t*)((void*)((nk_byte*)(p) + (i))))
#define nk_ptr_add_const(t, p, i) ((const t*)((const void*)((const nk_byte*)(p) + (i))))
#define nk_zero_struct(s) nk_zero(&s, sizeof(s))
/* ==============================================================
* ALIGNMENT
* =============================================================== */
/* Pointer to Integer type conversion for pointer alignment */
#if defined(__PTRDIFF_TYPE__) /* This case should work for GCC*/
# define NK_UINT_TO_PTR(x) ((void*)(__PTRDIFF_TYPE__)(x))
# define NK_PTR_TO_UINT(x) ((nk_size)(__PTRDIFF_TYPE__)(x))
#elif !defined(__GNUC__) /* works for compilers other than LLVM */
# define NK_UINT_TO_PTR(x) ((void*)&((char*)0)[x])
# define NK_PTR_TO_UINT(x) ((nk_size)(((char*)x)-(char*)0))
#elif defined(NK_USE_FIXED_TYPES) /* used if we have <stdint.h> */
# define NK_UINT_TO_PTR(x) ((void*)(uintptr_t)(x))
# define NK_PTR_TO_UINT(x) ((uintptr_t)(x))
#else /* generates warning but works */
# define NK_UINT_TO_PTR(x) ((void*)(x))
# define NK_PTR_TO_UINT(x) ((nk_size)(x))
#endif
#define NK_ALIGN_PTR(x, mask)\
(NK_UINT_TO_PTR((NK_PTR_TO_UINT((nk_byte*)(x) + (mask-1)) & ~(mask-1))))
#define NK_ALIGN_PTR_BACK(x, mask)\
(NK_UINT_TO_PTR((NK_PTR_TO_UINT((nk_byte*)(x)) & ~(mask-1))))
#if defined(__GNUC__) || defined(__clang__)
#define NK_OFFSETOF(st,m) (__builtin_offsetof(st,m))
#else
#define NK_OFFSETOF(st,m) ((nk_ptr)&(((st*)0)->m))
#endif
#ifdef __cplusplus
template<typename T> struct nk_alignof;
template<typename T, int size_diff> struct nk_helper{enum {value = size_diff};};
template<typename T> struct nk_helper<T,0>{enum {value = nk_alignof<T>::value};};
template<typename T> struct nk_alignof{struct Big {T x; char c;}; enum {
diff = sizeof(Big) - sizeof(T), value = nk_helper<Big, diff>::value};};
#define NK_ALIGNOF(t) (nk_alignof<t>::value)
#else
#define NK_ALIGNOF(t) NK_OFFSETOF(struct {char c; t _h;}, _h)
#endif
#define NK_CONTAINER_OF(ptr,type,member)\
(type*)((void*)((char*)(1 ? (ptr): &((type*)0)->member) - NK_OFFSETOF(type, member)))
#ifdef __cplusplus
}
#endif
#endif /* NK_NUKLEAR_H_ */
| 46.492643 | 228 | 0.628932 | [
"render",
"object",
"shape",
"vector",
"model",
"3d"
] |
65e0e6c8da33bd02e20d271ef79a0b79f743c6e3 | 3,126 | h | C | dataclasses/public/dataclasses/payload/I3SuperDSTUtils.h | hschwane/offline_production | e14a6493782f613b8bbe64217559765d5213dc1e | [
"MIT"
] | 1 | 2020-12-24T22:00:01.000Z | 2020-12-24T22:00:01.000Z | dataclasses/public/dataclasses/payload/I3SuperDSTUtils.h | hschwane/offline_production | e14a6493782f613b8bbe64217559765d5213dc1e | [
"MIT"
] | null | null | null | dataclasses/public/dataclasses/payload/I3SuperDSTUtils.h | hschwane/offline_production | e14a6493782f613b8bbe64217559765d5213dc1e | [
"MIT"
] | 3 | 2020-07-17T09:20:29.000Z | 2021-03-30T16:44:18.000Z | /**
* @file
* @brief
*
* (c) 2011 Jakob van Santen
* and the IceCube Collaboration
*
* $Id: I3SuperDSTUtils.h 146654 2016-06-01 18:31:33Z cweaver $
* @version $Revision: 146654 $
* @date $Date: 2016-06-01 12:31:33 -0600 (Wed, 01 Jun 2016) $
* @author Jakob van Santen <vansanten@wisc.edu>
*
*/
#ifndef I3SUPERDST_I3SUPERDSTUTILS_H_INCLUDED
#define I3SUPERDST_I3SUPERDSTUTILS_H_INCLUDED
#include <serialization/binary_object.hpp>
namespace I3SuperDSTUtils {
/*
* Variable-width integer encoding.
*
* Values up to 246 are encoded in 1 byte; larger values in the
* minimum required to represent the value, plus 1.
*/
struct SizeCodec {
typedef uint64_t size_type;
size_type size_;
SizeCodec() : size_(0) {};
SizeCodec(size_type size) : size_(size) {};
size_type value() { return size_; };
friend class icecube::serialization::access;
template <class Archive>
void load(Archive &ar, unsigned version);
template <class Archive>
void save(Archive &ar, unsigned version) const;
I3_SERIALIZATION_SPLIT_MEMBER();
};
/* Optimized serialization for short vectors */
template <typename T>
class CompactVector : public std::vector<T> {
private:
friend class icecube::serialization::access;
template <class Archive>
void load(Archive &ar, unsigned version) {
SizeCodec c;
ar >> make_nvp("Size", c);
this->resize(c.size_);
ar >> make_nvp("Contents",
icecube::serialization::make_binary_object(&this->front(),
this->size()*sizeof(T)));
}
template <class Archive>
void save(Archive &ar, unsigned version) const
{
SizeCodec c(this->size());
ar << make_nvp("Size", c);
ar << make_nvp("Contents",
icecube::serialization::make_binary_object((void*)(&this->front()),
this->size()*sizeof(T)));
}
I3_SERIALIZATION_SPLIT_MEMBER();
};
/*
* Hobo run-length encoding for 4-bit numbers.
*
* Runs of 4-bit codes are encoded in single-byte instructions.
* The lower 4 bits hold the code, and the upper 4 bits hold
* a run length. If successive bytes contain the same code, then
* the run lengths are concatenated to form a wider number. This
* way, a run of 16 fits in 1 byte, a run of 256 in 2 bytes,
* 4096 in 3, etc.
*
* As with any run-length encoding, this does worst when there
* are no runs to encode. In the worst case where the code
* switches at every element, this encoding exactly doubles
* the size of the data.
*/
struct RunCodec {
typedef std::vector<uint8_t> vector_t;
static void EncodeRun(vector_t &codes, uint8_t val, unsigned len);
static void DecodeRun(vector_t &target,
const vector_t::const_iterator &head,
const vector_t::const_iterator &tail);
static void Encode(const vector_t &runs, vector_t &codes);
static void Decode(const vector_t &codes, vector_t &runs);
};
inline int findlastset(uint32_t i)
{
return i == 0 ? 0 : (8*sizeof(i)-__builtin_clz(i));
}
inline int findlastset(uint64_t i)
{
return (i & 0xffffffff00000000LL) ? findlastset(uint32_t(i >> 32))+32
: findlastset(uint32_t(i & 0xffffffff));
}
}
#endif
| 28.162162 | 74 | 0.68874 | [
"vector"
] |
65e5c795041863af99c6ed459cbf5d824cd86f6f | 6,517 | c | C | paka/cmark/cmark_src/man.c | kapyshin/paka.cmark | e297fe3ca1855c40ba81f61ae7aa5989a4cce3ad | [
"BSD-3-Clause"
] | 22 | 2017-01-10T09:25:50.000Z | 2020-08-21T01:13:51.000Z | paka/cmark/cmark_src/man.c | PavloKapyshin/paka.cmark | e297fe3ca1855c40ba81f61ae7aa5989a4cce3ad | [
"BSD-3-Clause"
] | 5 | 2017-03-01T11:09:38.000Z | 2018-10-24T23:16:21.000Z | paka/cmark/cmark_src/man.c | kapyshin/paka.cmark | e297fe3ca1855c40ba81f61ae7aa5989a4cce3ad | [
"BSD-3-Clause"
] | 7 | 2017-01-07T15:48:25.000Z | 2020-11-15T00:58:59.000Z | #include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "config.h"
#include "cmark.h"
#include "node.h"
#include "buffer.h"
#include "utf8.h"
#include "render.h"
#define OUT(s, wrap, escaping) renderer->out(renderer, s, wrap, escaping)
#define LIT(s) renderer->out(renderer, s, false, LITERAL)
#define CR() renderer->cr(renderer)
#define BLANKLINE() renderer->blankline(renderer)
#define LIST_NUMBER_SIZE 20
// Functions to convert cmark_nodes to groff man strings.
static void S_outc(cmark_renderer *renderer, cmark_escaping escape, int32_t c,
unsigned char nextc) {
(void)(nextc);
if (escape == LITERAL) {
cmark_render_code_point(renderer, c);
return;
}
switch (c) {
case 46:
if (renderer->begin_line) {
cmark_render_ascii(renderer, "\\&.");
} else {
cmark_render_code_point(renderer, c);
}
break;
case 39:
if (renderer->begin_line) {
cmark_render_ascii(renderer, "\\&'");
} else {
cmark_render_code_point(renderer, c);
}
break;
case 45:
cmark_render_ascii(renderer, "\\-");
break;
case 92:
cmark_render_ascii(renderer, "\\e");
break;
case 8216: // left single quote
cmark_render_ascii(renderer, "\\[oq]");
break;
case 8217: // right single quote
cmark_render_ascii(renderer, "\\[cq]");
break;
case 8220: // left double quote
cmark_render_ascii(renderer, "\\[lq]");
break;
case 8221: // right double quote
cmark_render_ascii(renderer, "\\[rq]");
break;
case 8212: // em dash
cmark_render_ascii(renderer, "\\[em]");
break;
case 8211: // en dash
cmark_render_ascii(renderer, "\\[en]");
break;
default:
cmark_render_code_point(renderer, c);
}
}
static int S_render_node(cmark_renderer *renderer, cmark_node *node,
cmark_event_type ev_type, int options) {
cmark_node *tmp;
int list_number;
bool entering = (ev_type == CMARK_EVENT_ENTER);
bool allow_wrap = renderer->width > 0 && !(CMARK_OPT_NOBREAKS & options);
struct block_number *new_block_number;
cmark_mem *allocator = cmark_get_default_mem_allocator();
// avoid unused parameter error:
(void)(options);
// indent inside nested lists
if (renderer->block_number_in_list_item &&
node->type < CMARK_NODE_FIRST_INLINE) {
if (entering) {
renderer->block_number_in_list_item->number += 1;
if (renderer->block_number_in_list_item->number == 2) {
CR();
LIT(".RS"); // indent
CR();
}
}
}
switch (node->type) {
case CMARK_NODE_DOCUMENT:
break;
case CMARK_NODE_BLOCK_QUOTE:
if (entering) {
CR();
LIT(".RS");
CR();
} else {
CR();
LIT(".RE");
CR();
}
break;
case CMARK_NODE_LIST:
break;
case CMARK_NODE_ITEM:
if (entering) {
new_block_number = allocator->calloc(1, sizeof(struct block_number));
new_block_number->number = 0;
new_block_number->parent = renderer->block_number_in_list_item;
renderer->block_number_in_list_item = new_block_number;
CR();
LIT(".IP ");
if (cmark_node_get_list_type(node->parent) == CMARK_BULLET_LIST) {
LIT("\\[bu] 2");
} else {
list_number = cmark_node_get_list_start(node->parent);
tmp = node;
while (tmp->prev) {
tmp = tmp->prev;
list_number += 1;
}
char list_number_s[LIST_NUMBER_SIZE];
snprintf(list_number_s, LIST_NUMBER_SIZE, "\"%d.\" 4", list_number);
LIT(list_number_s);
}
CR();
} else {
if (renderer->block_number_in_list_item) {
if (renderer->block_number_in_list_item->number >= 2) {
CR();
LIT(".RE"); // de-indent
}
new_block_number = renderer->block_number_in_list_item;
renderer->block_number_in_list_item =
renderer->block_number_in_list_item->parent;
allocator->free(new_block_number);
}
CR();
}
break;
case CMARK_NODE_HEADING:
if (entering) {
CR();
LIT(cmark_node_get_heading_level(node) == 1 ? ".SH" : ".SS");
CR();
} else {
CR();
}
break;
case CMARK_NODE_CODE_BLOCK:
CR();
LIT(".IP\n.nf\n\\f[C]\n");
OUT(cmark_node_get_literal(node), false, NORMAL);
CR();
LIT("\\f[]\n.fi");
CR();
break;
case CMARK_NODE_HTML_BLOCK:
break;
case CMARK_NODE_CUSTOM_BLOCK:
CR();
OUT(entering ? cmark_node_get_on_enter(node) : cmark_node_get_on_exit(node),
false, LITERAL);
CR();
break;
case CMARK_NODE_THEMATIC_BREAK:
CR();
LIT(".PP\n * * * * *");
CR();
break;
case CMARK_NODE_PARAGRAPH:
if (entering) {
// no blank line if first paragraph in list:
if (node->parent && node->parent->type == CMARK_NODE_ITEM &&
node->prev == NULL) {
// no blank line or .PP
} else {
CR();
LIT(".PP");
CR();
}
} else {
CR();
}
break;
case CMARK_NODE_TEXT:
OUT(cmark_node_get_literal(node), allow_wrap, NORMAL);
break;
case CMARK_NODE_LINEBREAK:
LIT(".PD 0\n.P\n.PD");
CR();
break;
case CMARK_NODE_SOFTBREAK:
if (options & CMARK_OPT_HARDBREAKS) {
LIT(".PD 0\n.P\n.PD");
CR();
} else if (renderer->width == 0 && !(CMARK_OPT_NOBREAKS & options)) {
CR();
} else {
OUT(" ", allow_wrap, LITERAL);
}
break;
case CMARK_NODE_CODE:
LIT("\\f[C]");
OUT(cmark_node_get_literal(node), allow_wrap, NORMAL);
LIT("\\f[]");
break;
case CMARK_NODE_HTML_INLINE:
break;
case CMARK_NODE_CUSTOM_INLINE:
OUT(entering ? cmark_node_get_on_enter(node) : cmark_node_get_on_exit(node),
false, LITERAL);
break;
case CMARK_NODE_STRONG:
if (entering) {
LIT("\\f[B]");
} else {
LIT("\\f[]");
}
break;
case CMARK_NODE_EMPH:
if (entering) {
LIT("\\f[I]");
} else {
LIT("\\f[]");
}
break;
case CMARK_NODE_LINK:
if (!entering) {
LIT(" (");
OUT(cmark_node_get_url(node), allow_wrap, URL);
LIT(")");
}
break;
case CMARK_NODE_IMAGE:
if (entering) {
LIT("[IMAGE: ");
} else {
LIT("]");
}
break;
default:
assert(false);
break;
}
return 1;
}
char *cmark_render_man(cmark_node *root, int options, int width) {
return cmark_render(root, options, width, S_outc, S_render_node);
}
| 23.109929 | 80 | 0.593678 | [
"render"
] |
65ea74726fcb6478ca9631ed683b5e9007741ae4 | 2,999 | c | C | datapath/linux/compat/skbuff-openvswitch.c | noobcoderT/SDN-openvswitch-2.3.1 | 02333a0b7a85684f7112a8dab20e7af86466d32d | [
"Apache-2.0"
] | 17 | 2016-04-15T08:15:18.000Z | 2020-12-29T13:39:56.000Z | datapath/linux/compat/skbuff-openvswitch.c | noobcoderT/SDN-openvswitch-2.3.1 | 02333a0b7a85684f7112a8dab20e7af86466d32d | [
"Apache-2.0"
] | 5 | 2015-04-23T15:01:50.000Z | 2019-06-10T02:36:26.000Z | datapath/linux/compat/skbuff-openvswitch.c | noobcoderT/SDN-openvswitch-2.3.1 | 02333a0b7a85684f7112a8dab20e7af86466d32d | [
"Apache-2.0"
] | 7 | 2015-03-15T16:36:40.000Z | 2022-03-14T00:37:40.000Z | #include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#if !defined(HAVE_SKB_WARN_LRO) && defined(NETIF_F_LRO)
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
void __skb_warn_lro_forwarding(const struct sk_buff *skb)
{
if (net_ratelimit())
pr_warn("%s: received packets cannot be forwarded while LRO is enabled\n",
skb->dev->name);
}
#endif
#if LINUX_VERSION_CODE < KERNEL_VERSION(3,14,0)
static inline bool head_frag(const struct sk_buff *skb)
{
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,5,0)
return skb->head_frag;
#else
return false;
#endif
}
/**
* skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
* @from: source buffer
*
* Calculates the amount of linear headroom needed in the 'to' skb passed
* into skb_zerocopy().
*/
unsigned int
skb_zerocopy_headlen(const struct sk_buff *from)
{
unsigned int hlen = 0;
if (!head_frag(from) ||
skb_headlen(from) < L1_CACHE_BYTES ||
skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS)
hlen = skb_headlen(from);
if (skb_has_frag_list(from))
hlen = from->len;
return hlen;
}
#ifndef HAVE_SKB_ZEROCOPY
/**
* skb_zerocopy - Zero copy skb to skb
* @to: destination buffer
* @source: source buffer
* @len: number of bytes to copy from source buffer
* @hlen: size of linear headroom in destination buffer
*
* Copies up to `len` bytes from `from` to `to` by creating references
* to the frags in the source buffer.
*
* The `hlen` as calculated by skb_zerocopy_headlen() specifies the
* headroom in the `to` buffer.
*
* Return value:
* 0: everything is OK
* -ENOMEM: couldn't orphan frags of @from due to lack of memory
* -EFAULT: skb_copy_bits() found some problem with skb geometry
*/
int
skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
{
int i, j = 0;
int plen = 0; /* length of skb->head fragment */
int ret;
struct page *page;
unsigned int offset;
BUG_ON(!head_frag(from) && !hlen);
/* dont bother with small payloads */
if (len <= skb_tailroom(to))
return skb_copy_bits(from, 0, skb_put(to, len), len);
if (hlen) {
ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
if (unlikely(ret))
return ret;
len -= hlen;
} else {
plen = min_t(int, skb_headlen(from), len);
if (plen) {
page = virt_to_head_page(from->head);
offset = from->data - (unsigned char *)page_address(page);
__skb_fill_page_desc(to, 0, page, offset, plen);
get_page(page);
j = 1;
len -= plen;
}
}
to->truesize += len + plen;
to->len += len + plen;
to->data_len += len + plen;
if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
skb_tx_error(from);
return -ENOMEM;
}
for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
if (!len)
break;
skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
skb_shinfo(to)->frags[j].size = min_t(int, skb_shinfo(to)->frags[j].size, len);
len -= skb_shinfo(to)->frags[j].size;
skb_frag_ref(to, j);
j++;
}
skb_shinfo(to)->nr_frags = j;
return 0;
}
#endif
#endif
| 23.614173 | 81 | 0.681227 | [
"geometry"
] |
65ec8a03544e7d20e5cd16a282a54b24837ba97d | 2,427 | h | C | chrome/browser/ui/webui/settings/recent_site_settings_helper.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | chrome/browser/ui/webui/settings/recent_site_settings_helper.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chrome/browser/ui/webui/settings/recent_site_settings_helper.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 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_WEBUI_SETTINGS_RECENT_SITE_SETTINGS_HELPER_H_
#define CHROME_BROWSER_UI_WEBUI_SETTINGS_RECENT_SITE_SETTINGS_HELPER_H_
#include <vector>
#include "base/time/time.h"
#include "chrome/browser/ui/webui/settings/site_settings_helper.h"
#include "components/content_settings/core/common/content_settings.h"
#include "components/content_settings/core/common/content_settings_types.h"
#include "url/gurl.h"
class Profile;
namespace site_settings {
struct TimestampedSetting {
base::Time timestamp;
ContentSettingsType content_type;
ContentSetting content_setting;
site_settings::SiteSettingSource setting_source;
TimestampedSetting();
TimestampedSetting(const TimestampedSetting& other);
TimestampedSetting& operator=(const TimestampedSetting& other) = default;
TimestampedSetting(TimestampedSetting&& other) = default;
TimestampedSetting(base::Time timestamp,
ContentSettingsType content_type,
ContentSetting content_setting,
site_settings::SiteSettingSource setting_source);
~TimestampedSetting();
};
struct RecentSitePermissions {
GURL origin;
bool incognito;
std::vector<TimestampedSetting> settings;
RecentSitePermissions();
RecentSitePermissions(const RecentSitePermissions& other);
RecentSitePermissions& operator=(const RecentSitePermissions& other) =
default;
RecentSitePermissions(RecentSitePermissions&& other);
RecentSitePermissions(GURL origin,
bool incognito,
std::vector<TimestampedSetting> settings);
~RecentSitePermissions();
};
// Returns a list containing the most recent permission changes for the
// provided content types grouped by origin/profile (incognito, regular)
// combinations. Limited to |max_sources| origin/profile pairings and ordered
// from most recently adjusted site to least recently. Includes permissions
// changed by embargo, but not those changed by enterprise policy.
std::vector<RecentSitePermissions> GetRecentSitePermissions(
Profile* profile,
std::vector<ContentSettingsType> content_types,
size_t max_sources);
} // namespace site_settings
#endif // CHROME_BROWSER_UI_WEBUI_SETTINGS_RECENT_SITE_SETTINGS_HELPER_H_
| 36.772727 | 77 | 0.775855 | [
"vector"
] |
65f20e13b641b40be00419d956f591903d5a5223 | 6,140 | h | C | engine/source/2d/sceneobject/ShapeVector.h | Sednari/twitch-tutorial-flappy-birds | 9aaed1cea2ef24ef6a5212c3350db17a017142fe | [
"MIT"
] | 1 | 2015-07-20T17:00:25.000Z | 2015-07-20T17:00:25.000Z | engine/source/2d/sceneobject/ShapeVector.h | Sednari/twitch-tutorial-flappy-birds | 9aaed1cea2ef24ef6a5212c3350db17a017142fe | [
"MIT"
] | null | null | null | engine/source/2d/sceneobject/ShapeVector.h | Sednari/twitch-tutorial-flappy-birds | 9aaed1cea2ef24ef6a5212c3350db17a017142fe | [
"MIT"
] | null | null | null | //-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#ifndef _SHAPE_VECTOR_H_
#define _SHAPE_VECTOR_H_
#ifndef _SCENE_OBJECT_H_
#include "2d/sceneobject/SceneObject.h"
#endif
//-----------------------------------------------------------------------------
class ShapeVector : public SceneObject
{
typedef SceneObject Parent;
protected:
ColorF mLineColor;
ColorF mFillColor;
bool mFillMode;
Vector2 mPolygonScale; ///< Polygon Scale.
Vector<Vector2> mPolygonBasisList; ///< Polygon Basis List.
Vector<Vector2> mPolygonLocalList; ///< Polygon Local List.
bool mIsCircle;
F32 mCircleRadius;
bool mFlipX;
bool mFlipY;
public:
ShapeVector();
~ShapeVector();
static void initPersistFields();
/// Polygon Configuration.
void setPolyScale( const Vector2& scale );
void setPolyPrimitive( const U32 polyVertexCount );
void setPolyCustom( const U32 polyVertexCount, const char* pCustomPolygon );
U32 getPolyVertexCount( void ) { return U32(mPolygonBasisList.size()); };
inline const Vector2* getPolyBasis( void ) const { return &(mPolygonBasisList[0]); };
const char* getPoly( void );
const char* getWorldPoly( void );
inline void setLineColor( const ColorF& linecolor ) { mLineColor = linecolor; }
inline const ColorF& getLineColor( void ) const { return mLineColor; }
inline void setLineAlpha( const F32 alpha ) { mLineColor.alpha = alpha; }
inline void setFillColor( const ColorF& fillcolor ) { mFillColor = fillcolor; }
inline const ColorF& getFillColor( void ) const { return mFillColor; }
inline void setFillAlpha( const F32 alpha ) { mFillColor.alpha = alpha; }
inline void setFillMode( const bool fillMode ) { mFillMode = fillMode; }
inline bool getFillMode( void ) const { return mFillMode; }
inline void setIsCircle( const bool isCircle ) { mIsCircle = isCircle; }
inline bool getIsCircle( void ) const { return mIsCircle; }
inline void setCircleRadius( const F32 circleRadius ) { mCircleRadius = circleRadius; }
inline F32 getCircleRadius ( void ) const { return mCircleRadius; }
Vector2 getBoxFromPoints( void );
/// Internal Crunchers.
void generateLocalPoly( void );
void renderCircleShape(Vector2 position, F32 radius);
void renderPolygonShape(U32 vertexCount);
/// Render flipping.
inline void setFlip( const bool flipX, const bool flipY ) { mFlipX = flipX; mFlipY = flipY; generateLocalPoly(); }
inline void setFlipX( const bool flipX ) { setFlip( flipX, mFlipY ); }
inline void setFlipY( const bool flipY ) { setFlip( mFlipX, flipY ); }
inline bool getFlipX(void) const { return mFlipX; }
inline bool getFlipY(void) const { return mFlipY; }
virtual void setSize( const Vector2& size );
/// Core.
virtual bool onAdd();
virtual void onRemove();
virtual void sceneRender( const SceneRenderState* pSceneRenderState, const SceneRenderRequest* pSceneRenderRequest, BatchRender* pBatchRenderer );
virtual bool validRender( void ) const { return (mPolygonLocalList.size() > 0 || mIsCircle); }
virtual bool shouldRender( void ) const { return true; }
/// Render batching.
virtual bool isBatchRendered( void ) { return false; }
/// Clone support
void copyTo(SimObject* obj);
/// Declare Console Object.
DECLARE_CONOBJECT(ShapeVector);
protected:
static bool setPolyList(void* obj, const char* data)
{
const U32 count = Utility::mGetStringElementCount(data) >> 1;
static_cast<ShapeVector*>(obj)->setPolyCustom(count, data);
return false;
}
static bool writePolyList( void* obj, StringTableEntry pFieldName ) { return static_cast<ShapeVector*>(obj)->mPolygonBasisList.size() > 0; }
static bool writeLineColor( void* obj, StringTableEntry pFieldName ) { return static_cast<ShapeVector*>(obj)->mLineColor != ColorF(1.0f,1.0f,1.0f,1.0f); }
static bool writeFillColor( void* obj, StringTableEntry pFieldName ) { return static_cast<ShapeVector*>(obj)->mFillColor != ColorF(0.5f,0.5f,0.5f,1.0f); }
static bool writeFillMode( void* obj, StringTableEntry pFieldName ) { return static_cast<ShapeVector*>(obj)->mFillMode == true; }
static bool writeIsCircle( void* obj, StringTableEntry pFieldName ) { return static_cast<ShapeVector*>(obj)->mIsCircle == true; }
static bool writeCircleRadius( void* obj, StringTableEntry pFieldName ) { return static_cast<ShapeVector*>(obj)->mCircleRadius != 1; }
};
#endif // _SHAPE_VECTOR_H_
| 49.516129 | 159 | 0.647394 | [
"render",
"object",
"vector"
] |
65f2d2c630cb59db9b42bc738911c14979082a60 | 64,213 | c | C | Core/gb.c | OFFTKP/SameBoy | bef1529bb24b3299e3b1a8b5cb068c0d6d26953c | [
"MIT"
] | null | null | null | Core/gb.c | OFFTKP/SameBoy | bef1529bb24b3299e3b1a8b5cb068c0d6d26953c | [
"MIT"
] | null | null | null | Core/gb.c | OFFTKP/SameBoy | bef1529bb24b3299e3b1a8b5cb068c0d6d26953c | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <errno.h>
#include <stdarg.h>
#ifndef _WIN32
#include <sys/select.h>
#include <unistd.h>
#endif
#include "random.h"
#include "gb.h"
#ifdef GB_DISABLE_REWIND
#define GB_rewind_free(...)
#define GB_rewind_push(...)
#endif
void GB_attributed_logv(GB_gameboy_t *gb, GB_log_attributes attributes, const char *fmt, va_list args)
{
char *string = NULL;
vasprintf(&string, fmt, args);
if (string) {
if (gb->log_callback) {
gb->log_callback(gb, string, attributes);
}
else {
/* Todo: Add ANSI escape sequences for attributed text */
printf("%s", string);
}
}
free(string);
}
void GB_attributed_log(GB_gameboy_t *gb, GB_log_attributes attributes, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
GB_attributed_logv(gb, attributes, fmt, args);
va_end(args);
}
void GB_log(GB_gameboy_t *gb, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
GB_attributed_logv(gb, 0, fmt, args);
va_end(args);
}
#ifndef GB_DISABLE_DEBUGGER
static char *default_input_callback(GB_gameboy_t *gb)
{
char *expression = NULL;
size_t size = 0;
if (gb->debug_stopped) {
printf(">");
}
if (getline(&expression, &size, stdin) == -1) {
/* The user doesn't have STDIN or used ^D. We make sure the program keeps running. */
GB_set_async_input_callback(gb, NULL); /* Disable async input */
return strdup("c");
}
if (!expression) {
return strdup("");
}
size_t length = strlen(expression);
if (expression[length - 1] == '\n') {
expression[length - 1] = 0;
}
if (expression[0] == '\x03') {
gb->debug_stopped = true;
free(expression);
return strdup("");
}
return expression;
}
static char *default_async_input_callback(GB_gameboy_t *gb)
{
#ifndef _WIN32
fd_set set;
FD_ZERO(&set);
FD_SET(STDIN_FILENO, &set);
struct timeval time = {0,};
if (select(1, &set, NULL, NULL, &time) == 1) {
if (feof(stdin)) {
GB_set_async_input_callback(gb, NULL); /* Disable async input */
return NULL;
}
return default_input_callback(gb);
}
#endif
return NULL;
}
#endif
static void load_default_border(GB_gameboy_t *gb)
{
if (gb->has_sgb_border) return;
#define LOAD_BORDER() do { \
memcpy(gb->borrowed_border.map, tilemap, sizeof(tilemap));\
memcpy(gb->borrowed_border.palette, palette, sizeof(palette));\
memcpy(gb->borrowed_border.tiles, tiles, sizeof(tiles));\
} while (false);
#ifdef GB_BIG_ENDIAN
for (unsigned i = 0; i < sizeof(gb->borrowed_border.map) / 2; i++) {
gb->borrowed_border.map[i] = LE16(gb->borrowed_border.map[i]);
}
for (unsigned i = 0; i < sizeof(gb->borrowed_border.palette) / 2; i++) {
gb->borrowed_border.palette[i] = LE16(gb->borrowed_border.palette[i]);
}
#endif
if (gb->model > GB_MODEL_CGB_E) {
#include "graphics/agb_border.inc"
LOAD_BORDER();
}
else if (gb->model == GB_MODEL_MGB) {
#include "graphics/mgb_border.inc"
LOAD_BORDER();
if (gb->dmg_palette &&
gb->dmg_palette->colors[4].b > gb->dmg_palette->colors[4].r) {
for (unsigned i = 0; i < 7; i++) {
gb->borrowed_border.map[13 + 24 * 32 + i] = i + 1;
gb->borrowed_border.map[13 + 25 * 32 + i] = i + 8;
}
}
}
else if (GB_is_cgb(gb)) {
#include "graphics/cgb_border.inc"
LOAD_BORDER();
}
else {
#include "graphics/dmg_border.inc"
LOAD_BORDER();
}
}
void GB_init(GB_gameboy_t *gb, GB_model_t model)
{
memset(gb, 0, sizeof(*gb));
gb->model = model;
if (GB_is_cgb(gb)) {
gb->ram = malloc(gb->ram_size = 0x1000 * 8);
gb->vram = malloc(gb->vram_size = 0x2000 * 2);
}
else {
gb->ram = malloc(gb->ram_size = 0x2000);
gb->vram = malloc(gb->vram_size = 0x2000);
}
#ifndef GB_DISABLE_DEBUGGER
gb->input_callback = default_input_callback;
gb->async_input_callback = default_async_input_callback;
#endif
gb->cartridge_type = &GB_cart_defs[0]; // Default cartridge type
gb->clock_multiplier = 1.0;
if (model & GB_MODEL_NO_SFC_BIT) {
/* Disable time syncing. Timing should be done by the SFC emulator. */
gb->turbo = true;
}
GB_reset(gb);
load_default_border(gb);
}
GB_model_t GB_get_model(GB_gameboy_t *gb)
{
return gb->model;
}
void GB_free(GB_gameboy_t *gb)
{
gb->magic = 0;
if (gb->ram) {
free(gb->ram);
}
if (gb->vram) {
free(gb->vram);
}
if (gb->mbc_ram) {
free(gb->mbc_ram);
}
if (gb->rom) {
free(gb->rom);
}
if (gb->breakpoints) {
free(gb->breakpoints);
}
if (gb->sgb) {
free(gb->sgb);
}
if (gb->nontrivial_jump_state) {
free(gb->nontrivial_jump_state);
}
if (gb->undo_state) {
free(gb->undo_state);
}
#ifndef GB_DISABLE_DEBUGGER
GB_debugger_clear_symbols(gb);
#endif
GB_rewind_free(gb);
#ifndef GB_DISABLE_CHEATS
while (gb->cheats) {
GB_remove_cheat(gb, gb->cheats[0]);
}
#endif
memset(gb, 0, sizeof(*gb));
}
int GB_load_boot_rom(GB_gameboy_t *gb, const char *path)
{
FILE *f = fopen(path, "rb");
if (!f) {
GB_log(gb, "Could not open boot ROM: %s.\n", strerror(errno));
return errno;
}
fread(gb->boot_rom, sizeof(gb->boot_rom), 1, f);
fclose(f);
return 0;
}
void GB_load_boot_rom_from_buffer(GB_gameboy_t *gb, const unsigned char *buffer, size_t size)
{
if (size > sizeof(gb->boot_rom)) {
size = sizeof(gb->boot_rom);
}
memset(gb->boot_rom, 0xFF, sizeof(gb->boot_rom));
memcpy(gb->boot_rom, buffer, size);
}
void GB_borrow_sgb_border(GB_gameboy_t *gb)
{
if (GB_is_sgb(gb)) return;
if (gb->border_mode != GB_BORDER_ALWAYS) return;
if (gb->tried_loading_sgb_border) return;
gb->tried_loading_sgb_border = true;
if (gb->rom && gb->rom[0x146] != 3) return; // Not an SGB game, nothing to borrow
if (!gb->boot_rom_load_callback) return; // Can't borrow a border without this callback
GB_gameboy_t sgb;
GB_init(&sgb, GB_MODEL_SGB);
sgb.cartridge_type = gb->cartridge_type;
sgb.rom = gb->rom;
sgb.rom_size = gb->rom_size;
sgb.turbo = true;
sgb.turbo_dont_skip = true;
// sgb.disable_rendering = true;
/* Load the boot ROM using the existing gb object */
typeof(gb->boot_rom) boot_rom_backup;
memcpy(boot_rom_backup, gb->boot_rom, sizeof(gb->boot_rom));
gb->boot_rom_load_callback(gb, GB_BOOT_ROM_SGB);
memcpy(sgb.boot_rom, gb->boot_rom, sizeof(gb->boot_rom));
memcpy(gb->boot_rom, boot_rom_backup, sizeof(gb->boot_rom));
sgb.sgb->intro_animation = -1;
for (unsigned i = 600; i--;) {
GB_run_frame(&sgb);
if (sgb.sgb->border_animation) {
gb->has_sgb_border = true;
memcpy(&gb->borrowed_border, &sgb.sgb->pending_border, sizeof(gb->borrowed_border));
gb->borrowed_border.palette[0] = sgb.sgb->effective_palettes[0];
break;
}
}
sgb.rom = NULL;
sgb.rom_size = 0;
GB_free(&sgb);
}
int GB_load_rom(GB_gameboy_t *gb, const char *path)
{
FILE *f = fopen(path, "rb");
if (!f) {
GB_log(gb, "Could not open ROM: %s.\n", strerror(errno));
return errno;
}
fseek(f, 0, SEEK_END);
gb->rom_size = (ftell(f) + 0x3FFF) & ~0x3FFF; /* Round to bank */
/* And then round to a power of two */
while (gb->rom_size & (gb->rom_size - 1)) {
/* I promise this works. */
gb->rom_size |= gb->rom_size >> 1;
gb->rom_size++;
}
if (gb->rom_size < 0x8000) {
gb->rom_size = 0x8000;
}
fseek(f, 0, SEEK_SET);
if (gb->rom) {
free(gb->rom);
}
gb->rom = malloc(gb->rom_size);
memset(gb->rom, 0xFF, gb->rom_size); /* Pad with 0xFFs */
fread(gb->rom, 1, gb->rom_size, f);
fclose(f);
GB_configure_cart(gb);
gb->tried_loading_sgb_border = false;
gb->has_sgb_border = false;
load_default_border(gb);
return 0;
}
#define GBS_ENTRY 0x61
#define GBS_ENTRY_SIZE 13
static void generate_gbs_entry(GB_gameboy_t *gb, uint8_t *data)
{
memcpy(data, (uint8_t[]) {
0xCD, // Call $XXXX
LE16(gb->gbs_header.init_address),
LE16(gb->gbs_header.init_address) >> 8,
0x76, // HALT
0x00, // NOP
0xAF, // XOR a
0xE0, // LDH [$FFXX], a
GB_IO_IF,
0xCD, // Call $XXXX
LE16(gb->gbs_header.play_address),
LE16(gb->gbs_header.play_address) >> 8,
0x18, // JR pc ± $XX
-10 // To HALT
}, GBS_ENTRY_SIZE);
}
void GB_gbs_switch_track(GB_gameboy_t *gb, uint8_t track)
{
GB_reset(gb);
GB_write_memory(gb, 0xFF00 + GB_IO_LCDC, 0x80);
GB_write_memory(gb, 0xFF00 + GB_IO_TAC, gb->gbs_header.TAC);
GB_write_memory(gb, 0xFF00 + GB_IO_TMA, gb->gbs_header.TMA);
GB_write_memory(gb, 0xFF00 + GB_IO_NR52, 0x80);
GB_write_memory(gb, 0xFF00 + GB_IO_NR51, 0xFF);
GB_write_memory(gb, 0xFF00 + GB_IO_NR50, 0x77);
memset(gb->ram, 0, gb->ram_size);
memset(gb->hram, 0, sizeof(gb->hram));
memset(gb->oam, 0, sizeof(gb->oam));
if (gb->gbs_header.TAC || gb->gbs_header.TMA) {
GB_write_memory(gb, 0xFFFF, 0x04);
}
else {
GB_write_memory(gb, 0xFFFF, 0x01);
}
if (gb->gbs_header.TAC & 0x80) {
gb->cgb_double_speed = true; // Might mean double speed mode on a DMG
}
if (gb->gbs_header.load_address) {
gb->sp = LE16(gb->gbs_header.sp);
gb->pc = GBS_ENTRY;
}
else {
gb->pc = gb->sp = LE16(gb->gbs_header.sp - GBS_ENTRY_SIZE);
uint8_t entry[GBS_ENTRY_SIZE];
generate_gbs_entry(gb, entry);
for (unsigned i = 0; i < sizeof(entry); i++) {
GB_write_memory(gb, gb->pc + i, entry[i]);
}
}
gb->boot_rom_finished = true;
gb->a = track;
if (gb->sgb) {
gb->sgb->intro_animation = GB_SGB_INTRO_ANIMATION_LENGTH;
gb->sgb->disable_commands = true;
}
if (gb->gbs_header.TAC & 0x40) {
gb->interrupt_enable = true;
}
}
int GB_load_gbs_from_buffer(GB_gameboy_t *gb, const uint8_t *buffer, size_t size, GB_gbs_info_t *info)
{
if (size < sizeof(gb->gbs_header)) {
GB_log(gb, "Not a valid GBS file.\n");
return -1;
}
memcpy(&gb->gbs_header, buffer, sizeof(gb->gbs_header));
if (gb->gbs_header.magic != BE32('GBS\x01') ||
((LE16(gb->gbs_header.load_address) < GBS_ENTRY + GBS_ENTRY_SIZE ||
LE16(gb->gbs_header.load_address) >= 0x8000) &&
LE16(gb->gbs_header.load_address) != 0)) {
GB_log(gb, "Not a valid GBS file.\n");
return -1;
}
size_t data_size = size - sizeof(gb->gbs_header);
gb->rom_size = (data_size + LE16(gb->gbs_header.load_address) + 0x3FFF) & ~0x3FFF; /* Round to bank */
/* And then round to a power of two */
while (gb->rom_size & (gb->rom_size - 1)) {
/* I promise this works. */
gb->rom_size |= gb->rom_size >> 1;
gb->rom_size++;
}
if (gb->rom_size < 0x8000) {
gb->rom_size = 0x8000;
}
if (gb->rom) {
free(gb->rom);
}
gb->rom = malloc(gb->rom_size);
memset(gb->rom, 0xFF, gb->rom_size); /* Pad with 0xFFs */
memcpy(gb->rom + LE16(gb->gbs_header.load_address), buffer + sizeof(gb->gbs_header), data_size);
gb->cartridge_type = &GB_cart_defs[0x11];
if (gb->mbc_ram) {
free(gb->mbc_ram);
gb->mbc_ram = NULL;
gb->mbc_ram_size = 0;
}
if (gb->cartridge_type->has_ram) {
gb->mbc_ram_size = 0x2000;
gb->mbc_ram = malloc(gb->mbc_ram_size);
memset(gb->mbc_ram, 0xFF, gb->mbc_ram_size);
}
bool has_interrupts = gb->gbs_header.TAC & 0x40;
if (gb->gbs_header.load_address) {
// Generate interrupt handlers
for (unsigned i = 0; i <= (has_interrupts? 0x50 : 0x38); i += 8) {
gb->rom[i] = 0xC3; // jp $XXXX
gb->rom[i + 1] = (LE16(gb->gbs_header.load_address) + i);
gb->rom[i + 2] = (LE16(gb->gbs_header.load_address) + i) >> 8;
}
for (unsigned i = has_interrupts? 0x58 : 0x40; i <= 0x60; i += 8) {
gb->rom[i] = 0xC9; // ret
}
// Generate entry
generate_gbs_entry(gb, gb->rom + GBS_ENTRY);
}
GB_gbs_switch_track(gb, gb->gbs_header.first_track - 1);
if (info) {
memset(info, 0, sizeof(*info));
info->first_track = gb->gbs_header.first_track - 1;
info->track_count = gb->gbs_header.track_count;
memcpy(info->title, gb->gbs_header.title, sizeof(gb->gbs_header.title));
memcpy(info->author, gb->gbs_header.author, sizeof(gb->gbs_header.author));
memcpy(info->copyright, gb->gbs_header.copyright, sizeof(gb->gbs_header.copyright));
}
gb->tried_loading_sgb_border = true; // Don't even attempt on GBS files
gb->has_sgb_border = false;
load_default_border(gb);
return 0;
}
int GB_load_gbs(GB_gameboy_t *gb, const char *path, GB_gbs_info_t *info)
{
FILE *f = fopen(path, "rb");
if (!f) {
GB_log(gb, "Could not open GBS: %s.\n", strerror(errno));
return errno;
}
fseek(f, 0, SEEK_END);
size_t file_size = MIN(ftell(f), sizeof(GB_gbs_header_t) + 0x4000 * 0x100); // Cap with the maximum MBC3 ROM size + GBS header
fseek(f, 0, SEEK_SET);
uint8_t *file_data = malloc(file_size);
fread(file_data, 1, file_size, f);
fclose(f);
int r = GB_load_gbs_from_buffer(gb, file_data, file_size, info);
free(file_data);
return r;
}
int GB_load_isx(GB_gameboy_t *gb, const char *path)
{
FILE *f = fopen(path, "rb");
if (!f) {
GB_log(gb, "Could not open ISX file: %s.\n", strerror(errno));
return errno;
}
char magic[4];
#define READ(x) if (fread(&x, sizeof(x), 1, f) != 1) goto error
fread(magic, 1, sizeof(magic), f);
bool extended = *(uint32_t *)&magic == BE32('ISX ');
fseek(f, extended? 0x20 : 0, SEEK_SET);
uint8_t *old_rom = gb->rom;
uint32_t old_size = gb->rom_size;
gb->rom = NULL;
gb->rom_size = 0;
while (true) {
uint8_t record_type = 0;
if (fread(&record_type, sizeof(record_type), 1, f) != 1) break;
switch (record_type) {
case 0x01: { // Binary
uint16_t bank;
uint16_t address;
uint16_t length;
uint8_t byte;
READ(byte);
bank = byte;
if (byte >= 0x80) {
READ(byte);
bank |= byte << 8;
}
READ(address);
address = LE16(address);
address &= 0x3FFF;
READ(length);
length = LE16(length);
size_t needed_size = bank * 0x4000 + address + length;
if (needed_size > 1024 * 1024 * 32) goto error;
if (gb->rom_size < needed_size) {
gb->rom = realloc(gb->rom, needed_size);
memset(gb->rom + gb->rom_size, 0, needed_size - gb->rom_size);
gb->rom_size = needed_size;
}
if (fread(gb->rom + (bank * 0x4000 + address), length, 1, f) != 1) goto error;
break;
}
case 0x11: { // Extended Binary
uint32_t address;
uint32_t length;
READ(address);
address = LE32(address);
READ(length);
length = LE32(length);
size_t needed_size = address + length;
if (needed_size > 1024 * 1024 * 32) goto error;
if (gb->rom_size < needed_size) {
gb->rom = realloc(gb->rom, needed_size);
memset(gb->rom + gb->rom_size, 0, needed_size - gb->rom_size);
gb->rom_size = needed_size;
}
if (fread(gb->rom + address, length, 1, f) != 1) goto error;
break;
}
case 0x04: { // Symbol
uint16_t count;
uint8_t length;
char name[257];
uint8_t flag;
uint16_t bank;
uint16_t address;
uint8_t byte;
READ(count);
count = LE16(count);
while (count--) {
READ(length);
if (fread(name, length, 1, f) != 1) goto error;
name[length] = 0;
READ(flag); // unused
READ(byte);
bank = byte;
if (byte >= 0x80) {
READ(byte);
bank |= byte << 8;
}
READ(address);
address = LE16(address);
GB_debugger_add_symbol(gb, bank, address, name);
}
break;
}
case 0x14: { // Extended Binary
uint16_t count;
uint8_t length;
char name[257];
uint8_t flag;
uint32_t address;
READ(count);
count = LE16(count);
while (count--) {
READ(length);
if (fread(name, length + 1, 1, f) != 1) goto error;
name[length] = 0;
READ(flag); // unused
READ(address);
address = LE32(address);
// TODO: How to convert 32-bit addresses to Bank:Address? Needs to tell RAM and ROM apart
}
break;
}
default:
goto done;
}
}
done:;
#undef READ
if (gb->rom_size == 0) goto error;
size_t needed_size = (gb->rom_size + 0x3FFF) & ~0x3FFF; /* Round to bank */
/* And then round to a power of two */
while (needed_size & (needed_size - 1)) {
/* I promise this works. */
needed_size |= needed_size >> 1;
needed_size++;
}
if (needed_size < 0x8000) {
needed_size = 0x8000;
}
if (gb->rom_size < needed_size) {
gb->rom = realloc(gb->rom, needed_size);
memset(gb->rom + gb->rom_size, 0, needed_size - gb->rom_size);
gb->rom_size = needed_size;
}
GB_configure_cart(gb);
// Fix a common wrong MBC error
if (gb->rom[0x147] == 3) { // MBC1 + RAM + Battery
bool needs_fix = false;
if (gb->rom_size >= 0x21 * 0x4000) {
for (unsigned i = 0x20 * 0x4000; i < 0x21 * 0x4000; i++) {
if (gb->rom[i]) {
needs_fix = true;
break;
}
}
}
if (!needs_fix && gb->rom_size >= 0x41 * 0x4000) {
for (unsigned i = 0x40 * 0x4000; i < 0x41 * 0x4000; i++) {
if (gb->rom[i]) {
needs_fix = true;
break;
}
}
}
if (!needs_fix && gb->rom_size >= 0x61 * 0x4000) {
for (unsigned i = 0x60 * 0x4000; i < 0x61 * 0x4000; i++) {
if (gb->rom[i]) {
needs_fix = true;
break;
}
}
}
if (needs_fix) {
gb->rom[0x147] = 0x10; // MBC3 + RTC + RAM + Battery
GB_configure_cart(gb);
gb->rom[0x147] = 0x3;
GB_log(gb, "ROM claims to use MBC1 but appears to require MBC3 or 5, assuming MBC3.\n");
}
}
if (old_rom) {
free(old_rom);
}
return 0;
error:
GB_log(gb, "Invalid or unsupported ISX file.\n");
if (gb->rom) {
free(gb->rom);
gb->rom = old_rom;
gb->rom_size = old_size;
}
fclose(f);
gb->tried_loading_sgb_border = false;
gb->has_sgb_border = false;
load_default_border(gb);
return -1;
}
void GB_load_rom_from_buffer(GB_gameboy_t *gb, const uint8_t *buffer, size_t size)
{
gb->rom_size = (size + 0x3FFF) & ~0x3FFF;
while (gb->rom_size & (gb->rom_size - 1)) {
gb->rom_size |= gb->rom_size >> 1;
gb->rom_size++;
}
if (gb->rom_size == 0) {
gb->rom_size = 0x8000;
}
if (gb->rom) {
free(gb->rom);
}
gb->rom = malloc(gb->rom_size);
memset(gb->rom, 0xFF, gb->rom_size);
memcpy(gb->rom, buffer, size);
GB_configure_cart(gb);
gb->tried_loading_sgb_border = false;
gb->has_sgb_border = false;
load_default_border(gb);
}
typedef struct {
uint8_t seconds;
uint8_t padding1[3];
uint8_t minutes;
uint8_t padding2[3];
uint8_t hours;
uint8_t padding3[3];
uint8_t days;
uint8_t padding4[3];
uint8_t high;
uint8_t padding5[3];
} vba_rtc_time_t;
typedef struct __attribute__((packed)) {
uint32_t magic;
uint16_t version;
uint8_t mr4;
uint8_t reserved;
uint64_t last_rtc_second;
uint8_t rtc_data[4];
} tpp1_rtc_save_t;
typedef union {
struct __attribute__((packed)) {
GB_rtc_time_t rtc_real;
time_t last_rtc_second; /* Platform specific endianess and size */
} sameboy_legacy;
struct {
/* Used by VBA versions with 32-bit timestamp*/
vba_rtc_time_t rtc_real, rtc_latched;
uint32_t last_rtc_second; /* Always little endian */
} vba32;
struct {
/* Used by BGB and VBA versions with 64-bit timestamp*/
vba_rtc_time_t rtc_real, rtc_latched;
uint64_t last_rtc_second; /* Always little endian */
} vba64;
} rtc_save_t;
static void fill_tpp1_save_data(GB_gameboy_t *gb, tpp1_rtc_save_t *data)
{
data->magic = BE32('TPP1');
data->version = BE16(0x100);
data->mr4 = gb->tpp1_mr4;
data->reserved = 0;
data->last_rtc_second = LE64(time(NULL));
unrolled for (unsigned i = 4; i--;) {
data->rtc_data[i] = gb->rtc_real.data[i ^ 3];
}
}
int GB_save_battery_size(GB_gameboy_t *gb)
{
if (!gb->cartridge_type->has_battery) return 0; // Nothing to save.
if (gb->cartridge_type->mbc_type == GB_TPP1 && !(gb->rom[0x153] & 8)) return 0; // Nothing to save.
if (gb->mbc_ram_size == 0 && !gb->cartridge_type->has_rtc) return 0; /* Claims to have battery, but has no RAM or RTC */
if (gb->cartridge_type->mbc_type == GB_HUC3) {
return gb->mbc_ram_size + sizeof(GB_huc3_rtc_time_t);
}
if (gb->cartridge_type->mbc_type == GB_TPP1) {
return gb->mbc_ram_size + sizeof(tpp1_rtc_save_t);
}
rtc_save_t rtc_save_size;
return gb->mbc_ram_size + (gb->cartridge_type->has_rtc ? sizeof(rtc_save_size.vba64) : 0);
}
int GB_save_battery_to_buffer(GB_gameboy_t *gb, uint8_t *buffer, size_t size)
{
if (!gb->cartridge_type->has_battery) return 0; // Nothing to save.
if (gb->cartridge_type->mbc_type == GB_TPP1 && !(gb->rom[0x153] & 8)) return 0; // Nothing to save.
if (gb->mbc_ram_size == 0 && !gb->cartridge_type->has_rtc) return 0; /* Claims to have battery, but has no RAM or RTC */
if (size < GB_save_battery_size(gb)) return EIO;
memcpy(buffer, gb->mbc_ram, gb->mbc_ram_size);
if (gb->cartridge_type->mbc_type == GB_TPP1) {
buffer += gb->mbc_ram_size;
tpp1_rtc_save_t rtc_save;
fill_tpp1_save_data(gb, &rtc_save);
memcpy(buffer, &rtc_save, sizeof(rtc_save));
}
else if (gb->cartridge_type->mbc_type == GB_HUC3) {
buffer += gb->mbc_ram_size;
GB_huc3_rtc_time_t rtc_save = {
LE64(gb->last_rtc_second),
LE16(gb->huc3.minutes),
LE16(gb->huc3.days),
LE16(gb->huc3.alarm_minutes),
LE16(gb->huc3.alarm_days),
gb->huc3.alarm_enabled,
};
memcpy(buffer, &rtc_save, sizeof(rtc_save));
}
else if (gb->cartridge_type->has_rtc) {
rtc_save_t rtc_save = {{{{0,}},},};
rtc_save.vba64.rtc_real.seconds = gb->rtc_real.seconds;
rtc_save.vba64.rtc_real.minutes = gb->rtc_real.minutes;
rtc_save.vba64.rtc_real.hours = gb->rtc_real.hours;
rtc_save.vba64.rtc_real.days = gb->rtc_real.days;
rtc_save.vba64.rtc_real.high = gb->rtc_real.high;
rtc_save.vba64.rtc_latched.seconds = gb->rtc_latched.seconds;
rtc_save.vba64.rtc_latched.minutes = gb->rtc_latched.minutes;
rtc_save.vba64.rtc_latched.hours = gb->rtc_latched.hours;
rtc_save.vba64.rtc_latched.days = gb->rtc_latched.days;
rtc_save.vba64.rtc_latched.high = gb->rtc_latched.high;
rtc_save.vba64.last_rtc_second = LE64(time(NULL));
memcpy(buffer + gb->mbc_ram_size, &rtc_save.vba64, sizeof(rtc_save.vba64));
}
errno = 0;
return errno;
}
int GB_save_battery(GB_gameboy_t *gb, const char *path)
{
if (!gb->cartridge_type->has_battery) return 0; // Nothing to save.
if (gb->cartridge_type->mbc_type == GB_TPP1 && !(gb->rom[0x153] & 8)) return 0; // Nothing to save.
if (gb->mbc_ram_size == 0 && !gb->cartridge_type->has_rtc) return 0; /* Claims to have battery, but has no RAM or RTC */
FILE *f = fopen(path, "wb");
if (!f) {
GB_log(gb, "Could not open battery save: %s.\n", strerror(errno));
return errno;
}
if (fwrite(gb->mbc_ram, 1, gb->mbc_ram_size, f) != gb->mbc_ram_size) {
fclose(f);
return EIO;
}
if (gb->cartridge_type->mbc_type == GB_TPP1) {
tpp1_rtc_save_t rtc_save;
fill_tpp1_save_data(gb, &rtc_save);
if (fwrite(&rtc_save, sizeof(rtc_save), 1, f) != 1) {
fclose(f);
return EIO;
}
}
else if (gb->cartridge_type->mbc_type == GB_HUC3) {
GB_huc3_rtc_time_t rtc_save = {
LE64(gb->last_rtc_second),
LE16(gb->huc3.minutes),
LE16(gb->huc3.days),
LE16(gb->huc3.alarm_minutes),
LE16(gb->huc3.alarm_days),
gb->huc3.alarm_enabled,
};
if (fwrite(&rtc_save, sizeof(rtc_save), 1, f) != 1) {
fclose(f);
return EIO;
}
}
else if (gb->cartridge_type->has_rtc) {
rtc_save_t rtc_save = {{{{0,}},},};
rtc_save.vba64.rtc_real.seconds = gb->rtc_real.seconds;
rtc_save.vba64.rtc_real.minutes = gb->rtc_real.minutes;
rtc_save.vba64.rtc_real.hours = gb->rtc_real.hours;
rtc_save.vba64.rtc_real.days = gb->rtc_real.days;
rtc_save.vba64.rtc_real.high = gb->rtc_real.high;
rtc_save.vba64.rtc_latched.seconds = gb->rtc_latched.seconds;
rtc_save.vba64.rtc_latched.minutes = gb->rtc_latched.minutes;
rtc_save.vba64.rtc_latched.hours = gb->rtc_latched.hours;
rtc_save.vba64.rtc_latched.days = gb->rtc_latched.days;
rtc_save.vba64.rtc_latched.high = gb->rtc_latched.high;
rtc_save.vba64.last_rtc_second = LE64(time(NULL));
if (fwrite(&rtc_save.vba64, 1, sizeof(rtc_save.vba64), f) != sizeof(rtc_save.vba64)) {
fclose(f);
return EIO;
}
}
errno = 0;
fclose(f);
return errno;
}
static void load_tpp1_save_data(GB_gameboy_t *gb, const tpp1_rtc_save_t *data)
{
gb->last_rtc_second = LE64(data->last_rtc_second);
unrolled for (unsigned i = 4; i--;) {
gb->rtc_real.data[i ^ 3] = data->rtc_data[i];
}
}
void GB_load_battery_from_buffer(GB_gameboy_t *gb, const uint8_t *buffer, size_t size)
{
memcpy(gb->mbc_ram, buffer, MIN(gb->mbc_ram_size, size));
if (size <= gb->mbc_ram_size) {
goto reset_rtc;
}
if (gb->cartridge_type->mbc_type == GB_TPP1) {
tpp1_rtc_save_t rtc_save;
if (size - gb->mbc_ram_size < sizeof(rtc_save)) {
goto reset_rtc;
}
memcpy(&rtc_save, buffer + gb->mbc_ram_size, sizeof(rtc_save));
load_tpp1_save_data(gb, &rtc_save);
if (gb->last_rtc_second > time(NULL)) {
/* We must reset RTC here, or it will not advance. */
goto reset_rtc;
}
return;
}
if (gb->cartridge_type->mbc_type == GB_HUC3) {
GB_huc3_rtc_time_t rtc_save;
if (size - gb->mbc_ram_size < sizeof(rtc_save)) {
goto reset_rtc;
}
memcpy(&rtc_save, buffer + gb->mbc_ram_size, sizeof(rtc_save));
gb->last_rtc_second = LE64(rtc_save.last_rtc_second);
gb->huc3.minutes = LE16(rtc_save.minutes);
gb->huc3.days = LE16(rtc_save.days);
gb->huc3.alarm_minutes = LE16(rtc_save.alarm_minutes);
gb->huc3.alarm_days = LE16(rtc_save.alarm_days);
gb->huc3.alarm_enabled = rtc_save.alarm_enabled;
if (gb->last_rtc_second > time(NULL)) {
/* We must reset RTC here, or it will not advance. */
goto reset_rtc;
}
return;
}
rtc_save_t rtc_save;
memcpy(&rtc_save, buffer + gb->mbc_ram_size, MIN(sizeof(rtc_save), size));
switch (size - gb->mbc_ram_size) {
case sizeof(rtc_save.sameboy_legacy):
memcpy(&gb->rtc_real, &rtc_save.sameboy_legacy.rtc_real, sizeof(gb->rtc_real));
memcpy(&gb->rtc_latched, &rtc_save.sameboy_legacy.rtc_real, sizeof(gb->rtc_real));
gb->last_rtc_second = rtc_save.sameboy_legacy.last_rtc_second;
break;
case sizeof(rtc_save.vba32):
gb->rtc_real.seconds = rtc_save.vba32.rtc_real.seconds;
gb->rtc_real.minutes = rtc_save.vba32.rtc_real.minutes;
gb->rtc_real.hours = rtc_save.vba32.rtc_real.hours;
gb->rtc_real.days = rtc_save.vba32.rtc_real.days;
gb->rtc_real.high = rtc_save.vba32.rtc_real.high;
gb->rtc_latched.seconds = rtc_save.vba32.rtc_latched.seconds;
gb->rtc_latched.minutes = rtc_save.vba32.rtc_latched.minutes;
gb->rtc_latched.hours = rtc_save.vba32.rtc_latched.hours;
gb->rtc_latched.days = rtc_save.vba32.rtc_latched.days;
gb->rtc_latched.high = rtc_save.vba32.rtc_latched.high;
gb->last_rtc_second = LE32(rtc_save.vba32.last_rtc_second);
break;
case sizeof(rtc_save.vba64):
gb->rtc_real.seconds = rtc_save.vba64.rtc_real.seconds;
gb->rtc_real.minutes = rtc_save.vba64.rtc_real.minutes;
gb->rtc_real.hours = rtc_save.vba64.rtc_real.hours;
gb->rtc_real.days = rtc_save.vba64.rtc_real.days;
gb->rtc_real.high = rtc_save.vba64.rtc_real.high;
gb->rtc_latched.seconds = rtc_save.vba64.rtc_latched.seconds;
gb->rtc_latched.minutes = rtc_save.vba64.rtc_latched.minutes;
gb->rtc_latched.hours = rtc_save.vba64.rtc_latched.hours;
gb->rtc_latched.days = rtc_save.vba64.rtc_latched.days;
gb->rtc_latched.high = rtc_save.vba64.rtc_latched.high;
gb->last_rtc_second = LE64(rtc_save.vba64.last_rtc_second);
break;
default:
goto reset_rtc;
}
if (gb->last_rtc_second > time(NULL)) {
/* We must reset RTC here, or it will not advance. */
goto reset_rtc;
}
if (gb->last_rtc_second < 852076800) { /* 1/1/97. There weren't any RTC games that time,
so if the value we read is lower it means it wasn't
really RTC data. */
goto reset_rtc;
}
goto exit;
reset_rtc:
gb->last_rtc_second = time(NULL);
gb->rtc_real.high |= 0x80; /* This gives the game a hint that the clock should be reset. */
if (gb->cartridge_type->mbc_type == GB_HUC3) {
gb->huc3.days = 0xFFFF;
gb->huc3.minutes = 0xFFF;
gb->huc3.alarm_enabled = false;
}
exit:
return;
}
/* Loading will silently stop if the format is incomplete */
void GB_load_battery(GB_gameboy_t *gb, const char *path)
{
FILE *f = fopen(path, "rb");
if (!f) {
return;
}
if (fread(gb->mbc_ram, 1, gb->mbc_ram_size, f) != gb->mbc_ram_size) {
goto reset_rtc;
}
if (gb->cartridge_type->mbc_type == GB_TPP1) {
tpp1_rtc_save_t rtc_save;
if (fread(&rtc_save, sizeof(rtc_save), 1, f) != 1) {
goto reset_rtc;
}
load_tpp1_save_data(gb, &rtc_save);
if (gb->last_rtc_second > time(NULL)) {
/* We must reset RTC here, or it will not advance. */
goto reset_rtc;
}
return;
}
if (gb->cartridge_type->mbc_type == GB_HUC3) {
GB_huc3_rtc_time_t rtc_save;
if (fread(&rtc_save, sizeof(rtc_save), 1, f) != 1) {
goto reset_rtc;
}
gb->last_rtc_second = LE64(rtc_save.last_rtc_second);
gb->huc3.minutes = LE16(rtc_save.minutes);
gb->huc3.days = LE16(rtc_save.days);
gb->huc3.alarm_minutes = LE16(rtc_save.alarm_minutes);
gb->huc3.alarm_days = LE16(rtc_save.alarm_days);
gb->huc3.alarm_enabled = rtc_save.alarm_enabled;
if (gb->last_rtc_second > time(NULL)) {
/* We must reset RTC here, or it will not advance. */
goto reset_rtc;
}
return;
}
rtc_save_t rtc_save;
switch (fread(&rtc_save, 1, sizeof(rtc_save), f)) {
case sizeof(rtc_save.sameboy_legacy):
memcpy(&gb->rtc_real, &rtc_save.sameboy_legacy.rtc_real, sizeof(gb->rtc_real));
memcpy(&gb->rtc_latched, &rtc_save.sameboy_legacy.rtc_real, sizeof(gb->rtc_real));
gb->last_rtc_second = rtc_save.sameboy_legacy.last_rtc_second;
break;
case sizeof(rtc_save.vba32):
gb->rtc_real.seconds = rtc_save.vba32.rtc_real.seconds;
gb->rtc_real.minutes = rtc_save.vba32.rtc_real.minutes;
gb->rtc_real.hours = rtc_save.vba32.rtc_real.hours;
gb->rtc_real.days = rtc_save.vba32.rtc_real.days;
gb->rtc_real.high = rtc_save.vba32.rtc_real.high;
gb->rtc_latched.seconds = rtc_save.vba32.rtc_latched.seconds;
gb->rtc_latched.minutes = rtc_save.vba32.rtc_latched.minutes;
gb->rtc_latched.hours = rtc_save.vba32.rtc_latched.hours;
gb->rtc_latched.days = rtc_save.vba32.rtc_latched.days;
gb->rtc_latched.high = rtc_save.vba32.rtc_latched.high;
gb->last_rtc_second = LE32(rtc_save.vba32.last_rtc_second);
break;
case sizeof(rtc_save.vba64):
gb->rtc_real.seconds = rtc_save.vba64.rtc_real.seconds;
gb->rtc_real.minutes = rtc_save.vba64.rtc_real.minutes;
gb->rtc_real.hours = rtc_save.vba64.rtc_real.hours;
gb->rtc_real.days = rtc_save.vba64.rtc_real.days;
gb->rtc_real.high = rtc_save.vba64.rtc_real.high;
gb->rtc_latched.seconds = rtc_save.vba64.rtc_latched.seconds;
gb->rtc_latched.minutes = rtc_save.vba64.rtc_latched.minutes;
gb->rtc_latched.hours = rtc_save.vba64.rtc_latched.hours;
gb->rtc_latched.days = rtc_save.vba64.rtc_latched.days;
gb->rtc_latched.high = rtc_save.vba64.rtc_latched.high;
gb->last_rtc_second = LE64(rtc_save.vba64.last_rtc_second);
break;
default:
goto reset_rtc;
}
if (gb->last_rtc_second > time(NULL)) {
/* We must reset RTC here, or it will not advance. */
goto reset_rtc;
}
if (gb->last_rtc_second < 852076800) { /* 1/1/97. There weren't any RTC games that time,
so if the value we read is lower it means it wasn't
really RTC data. */
goto reset_rtc;
}
goto exit;
reset_rtc:
gb->last_rtc_second = time(NULL);
gb->rtc_real.high |= 0x80; /* This gives the game a hint that the clock should be reset. */
if (gb->cartridge_type->mbc_type == GB_HUC3) {
gb->huc3.days = 0xFFFF;
gb->huc3.minutes = 0xFFF;
gb->huc3.alarm_enabled = false;
}
exit:
fclose(f);
return;
}
unsigned GB_run(GB_gameboy_t *gb)
{
gb->vblank_just_occured = false;
if (gb->sgb && gb->sgb->intro_animation < 96) {
/* On the SGB, the GB is halted after finishing the boot ROM.
Then, after the boot animation is almost done, it's reset.
Since the SGB HLE does not perform any header validity checks,
we just halt the CPU (with hacky code) until the correct time.
This ensures the Nintendo logo doesn't flash on screen, and
the game does "run in background" while the animation is playing. */
GB_display_run(gb, 228, true);
gb->cycles_since_last_sync += 228;
return 228;
}
GB_debugger_run(gb);
gb->cycles_since_run = 0;
GB_cpu_run(gb);
if (gb->vblank_just_occured) {
GB_debugger_handle_async_commands(gb);
GB_rewind_push(gb);
}
if (!(gb->io_registers[GB_IO_IF] & 0x10) && (gb->io_registers[GB_IO_JOYP] & 0x30) != 0x30) {
gb->joyp_accessed = true;
}
return gb->cycles_since_run;
}
uint64_t GB_run_frame(GB_gameboy_t *gb)
{
/* Configure turbo temporarily, the user wants to handle FPS capping manually. */
bool old_turbo = gb->turbo;
bool old_dont_skip = gb->turbo_dont_skip;
gb->turbo = true;
gb->turbo_dont_skip = true;
gb->cycles_since_last_sync = 0;
while (true) {
GB_run(gb);
if (gb->vblank_just_occured) {
break;
}
}
gb->turbo = old_turbo;
gb->turbo_dont_skip = old_dont_skip;
return gb->cycles_since_last_sync * 1000000000LL / 2 / GB_get_clock_rate(gb); /* / 2 because we use 8MHz units */
}
void GB_set_pixels_output(GB_gameboy_t *gb, uint32_t *output)
{
gb->screen = output;
}
void GB_set_vblank_callback(GB_gameboy_t *gb, GB_vblank_callback_t callback)
{
gb->vblank_callback = callback;
}
void GB_set_log_callback(GB_gameboy_t *gb, GB_log_callback_t callback)
{
gb->log_callback = callback;
}
void GB_set_input_callback(GB_gameboy_t *gb, GB_input_callback_t callback)
{
#ifndef GB_DISABLE_DEBUGGER
if (gb->input_callback == default_input_callback) {
gb->async_input_callback = NULL;
}
gb->input_callback = callback;
#endif
}
void GB_set_async_input_callback(GB_gameboy_t *gb, GB_input_callback_t callback)
{
#ifndef GB_DISABLE_DEBUGGER
gb->async_input_callback = callback;
#endif
}
void GB_set_execution_callback(GB_gameboy_t *gb, GB_execution_callback_t callback)
{
gb->execution_callback = callback;
}
void GB_set_lcd_line_callback(GB_gameboy_t *gb, GB_lcd_line_callback_t callback)
{
gb->lcd_line_callback = callback;
}
const GB_palette_t GB_PALETTE_GREY = {{{0x00, 0x00, 0x00}, {0x55, 0x55, 0x55}, {0xAA, 0xAA, 0xAA}, {0xFF, 0xFF, 0xFF}, {0xFF, 0xFF, 0xFF}}};
const GB_palette_t GB_PALETTE_DMG = {{{0x08, 0x18, 0x10}, {0x39, 0x61, 0x39}, {0x84, 0xA5, 0x63}, {0xC6, 0xDE, 0x8C}, {0xD2, 0xE6, 0xA6}}};
const GB_palette_t GB_PALETTE_MGB = {{{0x07, 0x10, 0x0E}, {0x3A, 0x4C, 0x3A}, {0x81, 0x8D, 0x66}, {0xC2, 0xCE, 0x93}, {0xCF, 0xDA, 0xAC}}};
const GB_palette_t GB_PALETTE_GBL = {{{0x0A, 0x1C, 0x15}, {0x35, 0x78, 0x62}, {0x56, 0xB4, 0x95}, {0x7F, 0xE2, 0xC3}, {0x91, 0xEA, 0xD0}}};
static void update_dmg_palette(GB_gameboy_t *gb)
{
const GB_palette_t *palette = gb->dmg_palette ?: &GB_PALETTE_GREY;
if (gb->rgb_encode_callback && !GB_is_cgb(gb)) {
gb->object_palettes_rgb[4] = gb->object_palettes_rgb[0] = gb->background_palettes_rgb[0] =
gb->rgb_encode_callback(gb, palette->colors[3].r, palette->colors[3].g, palette->colors[3].b);
gb->object_palettes_rgb[5] = gb->object_palettes_rgb[1] = gb->background_palettes_rgb[1] =
gb->rgb_encode_callback(gb, palette->colors[2].r, palette->colors[2].g, palette->colors[2].b);
gb->object_palettes_rgb[6] = gb->object_palettes_rgb[2] = gb->background_palettes_rgb[2] =
gb->rgb_encode_callback(gb, palette->colors[1].r, palette->colors[1].g, palette->colors[1].b);
gb->object_palettes_rgb[7] = gb->object_palettes_rgb[3] = gb->background_palettes_rgb[3] =
gb->rgb_encode_callback(gb, palette->colors[0].r, palette->colors[0].g, palette->colors[0].b);
// LCD off color
gb->background_palettes_rgb[4] =
gb->rgb_encode_callback(gb, palette->colors[4].r, palette->colors[4].g, palette->colors[4].b);
}
}
void GB_set_palette(GB_gameboy_t *gb, const GB_palette_t *palette)
{
gb->dmg_palette = palette;
update_dmg_palette(gb);
}
const GB_palette_t *GB_get_palette(GB_gameboy_t *gb)
{
return gb->dmg_palette;
}
void GB_set_rgb_encode_callback(GB_gameboy_t *gb, GB_rgb_encode_callback_t callback)
{
gb->rgb_encode_callback = callback;
update_dmg_palette(gb);
for (unsigned i = 0; i < 32; i++) {
GB_palette_changed(gb, true, i * 2);
GB_palette_changed(gb, false, i * 2);
}
}
void GB_set_infrared_callback(GB_gameboy_t *gb, GB_infrared_callback_t callback)
{
gb->infrared_callback = callback;
}
void GB_set_infrared_input(GB_gameboy_t *gb, bool state)
{
gb->infrared_input = state;
}
void GB_set_rumble_callback(GB_gameboy_t *gb, GB_rumble_callback_t callback)
{
gb->rumble_callback = callback;
}
void GB_set_serial_transfer_bit_start_callback(GB_gameboy_t *gb, GB_serial_transfer_bit_start_callback_t callback)
{
gb->serial_transfer_bit_start_callback = callback;
}
void GB_set_serial_transfer_bit_end_callback(GB_gameboy_t *gb, GB_serial_transfer_bit_end_callback_t callback)
{
gb->serial_transfer_bit_end_callback = callback;
}
bool GB_serial_get_data_bit(GB_gameboy_t *gb)
{
if (!(gb->io_registers[GB_IO_SC] & 0x80)) {
/* Disabled serial returns 0 bits */
return false;
}
if (gb->io_registers[GB_IO_SC] & 1) {
/* Internal Clock */
GB_log(gb, "Serial read request while using internal clock. \n");
return true;
}
return gb->io_registers[GB_IO_SB] & 0x80;
}
void GB_serial_set_data_bit(GB_gameboy_t *gb, bool data)
{
if (!(gb->io_registers[GB_IO_SC] & 0x80)) {
/* Serial disabled */
return;
}
if (gb->io_registers[GB_IO_SC] & 1) {
/* Internal Clock */
GB_log(gb, "Serial write request while using internal clock. \n");
return;
}
gb->io_registers[GB_IO_SB] <<= 1;
gb->io_registers[GB_IO_SB] |= data;
gb->serial_count++;
if (gb->serial_count == 8) {
gb->io_registers[GB_IO_IF] |= 8;
gb->io_registers[GB_IO_SC] &= ~0x80;
gb->serial_count = 0;
}
}
void GB_disconnect_serial(GB_gameboy_t *gb)
{
gb->serial_transfer_bit_start_callback = NULL;
gb->serial_transfer_bit_end_callback = NULL;
/* Reset any internally-emulated device. */
memset(&gb->printer, 0, sizeof(gb->printer));
memset(&gb->workboy, 0, sizeof(gb->workboy));
}
bool GB_is_inited(GB_gameboy_t *gb)
{
return gb->magic == state_magic();
}
bool GB_is_cgb(const GB_gameboy_t *gb)
{
return gb->model >= GB_MODEL_CGB_0;
}
bool GB_is_cgb_in_cgb_mode(GB_gameboy_t *gb)
{
return gb->cgb_mode;
}
bool GB_is_sgb(GB_gameboy_t *gb)
{
return (gb->model & ~GB_MODEL_PAL_BIT & ~GB_MODEL_NO_SFC_BIT) == GB_MODEL_SGB || (gb->model & ~GB_MODEL_NO_SFC_BIT) == GB_MODEL_SGB2;
}
bool GB_is_hle_sgb(GB_gameboy_t *gb)
{
return (gb->model & ~GB_MODEL_PAL_BIT) == GB_MODEL_SGB || gb->model == GB_MODEL_SGB2;
}
void GB_set_turbo_mode(GB_gameboy_t *gb, bool on, bool no_frame_skip)
{
gb->turbo = on;
gb->turbo_dont_skip = no_frame_skip;
}
void GB_set_rendering_disabled(GB_gameboy_t *gb, bool disabled)
{
gb->disable_rendering = disabled;
}
void *GB_get_user_data(GB_gameboy_t *gb)
{
return gb->user_data;
}
void GB_set_user_data(GB_gameboy_t *gb, void *data)
{
gb->user_data = data;
}
static void reset_ram(GB_gameboy_t *gb)
{
switch (gb->model) {
case GB_MODEL_MGB:
case GB_MODEL_CGB_E:
case GB_MODEL_AGB_A: /* Unverified */
for (unsigned i = 0; i < gb->ram_size; i++) {
gb->ram[i] = GB_random();
}
break;
case GB_MODEL_DMG_B:
case GB_MODEL_SGB_NTSC: /* Unverified*/
case GB_MODEL_SGB_PAL: /* Unverified */
case GB_MODEL_SGB_NTSC_NO_SFC: /* Unverified */
case GB_MODEL_SGB_PAL_NO_SFC: /* Unverified */
for (unsigned i = 0; i < gb->ram_size; i++) {
gb->ram[i] = GB_random();
if (i & 0x100) {
gb->ram[i] &= GB_random();
}
else {
gb->ram[i] |= GB_random();
}
}
break;
case GB_MODEL_SGB2:
case GB_MODEL_SGB2_NO_SFC:
for (unsigned i = 0; i < gb->ram_size; i++) {
gb->ram[i] = 0x55;
gb->ram[i] ^= GB_random() & GB_random() & GB_random();
}
break;
case GB_MODEL_CGB_0:
case GB_MODEL_CGB_A:
case GB_MODEL_CGB_B:
case GB_MODEL_CGB_C:
for (unsigned i = 0; i < gb->ram_size; i++) {
if ((i & 0x808) == 0x800 || (i & 0x808) == 0x008) {
gb->ram[i] = 0;
}
else {
gb->ram[i] = GB_random() | GB_random() | GB_random() | GB_random() | GB_random();
}
}
break;
case GB_MODEL_CGB_D:
for (unsigned i = 0; i < gb->ram_size; i++) {
gb->ram[i] = GB_random();
if (i & 0x800) {
gb->ram[i] &= GB_random();
}
else {
gb->ram[i] |= GB_random();
}
}
break;
}
/* HRAM */
switch (gb->model) {
case GB_MODEL_CGB_0:
case GB_MODEL_CGB_A:
case GB_MODEL_CGB_B:
case GB_MODEL_CGB_C:
case GB_MODEL_CGB_D:
case GB_MODEL_CGB_E:
case GB_MODEL_AGB_A:
for (unsigned i = 0; i < sizeof(gb->hram); i++) {
gb->hram[i] = GB_random();
}
break;
case GB_MODEL_DMG_B:
case GB_MODEL_MGB:
case GB_MODEL_SGB_NTSC: /* Unverified*/
case GB_MODEL_SGB_PAL: /* Unverified */
case GB_MODEL_SGB_NTSC_NO_SFC: /* Unverified */
case GB_MODEL_SGB_PAL_NO_SFC: /* Unverified */
case GB_MODEL_SGB2:
case GB_MODEL_SGB2_NO_SFC:
for (unsigned i = 0; i < sizeof(gb->hram); i++) {
if (i & 1) {
gb->hram[i] = GB_random() | GB_random() | GB_random();
}
else {
gb->hram[i] = GB_random() & GB_random() & GB_random();
}
}
break;
}
/* OAM */
switch (gb->model) {
case GB_MODEL_CGB_0:
case GB_MODEL_CGB_A:
case GB_MODEL_CGB_B:
case GB_MODEL_CGB_C:
case GB_MODEL_CGB_D:
case GB_MODEL_CGB_E:
case GB_MODEL_AGB_A:
/* Zero'd out by boot ROM anyway */
break;
case GB_MODEL_DMG_B:
case GB_MODEL_MGB:
case GB_MODEL_SGB_NTSC: /* Unverified */
case GB_MODEL_SGB_PAL: /* Unverified */
case GB_MODEL_SGB_NTSC_NO_SFC: /* Unverified */
case GB_MODEL_SGB_PAL_NO_SFC: /* Unverified */
case GB_MODEL_SGB2:
case GB_MODEL_SGB2_NO_SFC:
for (unsigned i = 0; i < 8; i++) {
if (i & 2) {
gb->oam[i] = GB_random() & GB_random() & GB_random();
}
else {
gb->oam[i] = GB_random() | GB_random() | GB_random();
}
}
for (unsigned i = 8; i < sizeof(gb->oam); i++) {
gb->oam[i] = gb->oam[i - 8];
}
break;
}
/* Wave RAM */
switch (gb->model) {
case GB_MODEL_CGB_0:
case GB_MODEL_CGB_A:
case GB_MODEL_CGB_B:
case GB_MODEL_CGB_C:
case GB_MODEL_CGB_D:
case GB_MODEL_CGB_E:
case GB_MODEL_AGB_A:
/* Initialized by CGB-A and newer, 0s in CGB-0 */
break;
case GB_MODEL_MGB: {
for (unsigned i = 0; i < GB_IO_WAV_END - GB_IO_WAV_START; i++) {
if (i & 1) {
gb->io_registers[GB_IO_WAV_START + i] = GB_random() & GB_random();
}
else {
gb->io_registers[GB_IO_WAV_START + i] = GB_random() | GB_random();
}
}
break;
}
case GB_MODEL_DMG_B:
case GB_MODEL_SGB_NTSC: /* Unverified*/
case GB_MODEL_SGB_PAL: /* Unverified */
case GB_MODEL_SGB_NTSC_NO_SFC: /* Unverified */
case GB_MODEL_SGB_PAL_NO_SFC: /* Unverified */
case GB_MODEL_SGB2:
case GB_MODEL_SGB2_NO_SFC: {
for (unsigned i = 0; i < GB_IO_WAV_END - GB_IO_WAV_START; i++) {
if (i & 1) {
gb->io_registers[GB_IO_WAV_START + i] = GB_random() & GB_random() & GB_random();
}
else {
gb->io_registers[GB_IO_WAV_START + i] = GB_random() | GB_random() | GB_random();
}
}
break;
}
}
for (unsigned i = 0; i < sizeof(gb->extra_oam); i++) {
gb->extra_oam[i] = GB_random();
}
if (GB_is_cgb(gb)) {
for (unsigned i = 0; i < 64; i++) {
gb->background_palettes_data[i] = GB_random(); /* Doesn't really matter as the boot ROM overrides it anyway*/
gb->object_palettes_data[i] = GB_random();
}
for (unsigned i = 0; i < 32; i++) {
GB_palette_changed(gb, true, i * 2);
GB_palette_changed(gb, false, i * 2);
}
}
}
static void request_boot_rom(GB_gameboy_t *gb)
{
if (gb->boot_rom_load_callback) {
GB_boot_rom_t type = 0;
switch (gb->model) {
case GB_MODEL_DMG_B:
type = GB_BOOT_ROM_DMG;
break;
case GB_MODEL_MGB:
type = GB_BOOT_ROM_MGB;
break;
case GB_MODEL_SGB_NTSC:
case GB_MODEL_SGB_PAL:
case GB_MODEL_SGB_NTSC_NO_SFC:
case GB_MODEL_SGB_PAL_NO_SFC:
type = GB_BOOT_ROM_SGB;
break;
case GB_MODEL_SGB2:
case GB_MODEL_SGB2_NO_SFC:
type = GB_BOOT_ROM_SGB2;
break;
case GB_MODEL_CGB_0:
type = GB_BOOT_ROM_CGB_0;
break;
case GB_MODEL_CGB_A:
case GB_MODEL_CGB_B:
case GB_MODEL_CGB_C:
case GB_MODEL_CGB_D:
case GB_MODEL_CGB_E:
type = GB_BOOT_ROM_CGB;
break;
case GB_MODEL_AGB_A:
type = GB_BOOT_ROM_AGB;
break;
}
gb->boot_rom_load_callback(gb, type);
}
}
void GB_reset(GB_gameboy_t *gb)
{
uint32_t mbc_ram_size = gb->mbc_ram_size;
GB_model_t model = gb->model;
GB_update_clock_rate(gb);
uint8_t rtc_section[GB_SECTION_SIZE(rtc)];
memcpy(rtc_section, GB_GET_SECTION(gb, rtc), sizeof(rtc_section));
memset(gb, 0, (size_t)GB_GET_SECTION((GB_gameboy_t *) 0, unsaved));
memcpy(GB_GET_SECTION(gb, rtc), rtc_section, sizeof(rtc_section));
gb->model = model;
gb->version = GB_STRUCT_VERSION;
GB_reset_mbc(gb);
gb->last_rtc_second = time(NULL);
gb->cgb_ram_bank = 1;
gb->io_registers[GB_IO_JOYP] = 0xCF;
gb->mbc_ram_size = mbc_ram_size;
if (GB_is_cgb(gb)) {
gb->ram_size = 0x1000 * 8;
gb->vram_size = 0x2000 * 2;
memset(gb->vram, 0, gb->vram_size);
gb->cgb_mode = true;
gb->object_priority = GB_OBJECT_PRIORITY_INDEX;
}
else {
gb->ram_size = 0x2000;
gb->vram_size = 0x2000;
memset(gb->vram, 0, gb->vram_size);
gb->object_priority = GB_OBJECT_PRIORITY_X;
update_dmg_palette(gb);
}
reset_ram(gb);
gb->serial_mask = 0x80;
gb->io_registers[GB_IO_SC] = 0x7E;
/* These are not deterministic, but 00 (CGB) and FF (DMG) are the most common initial values by far */
gb->io_registers[GB_IO_DMA] = gb->io_registers[GB_IO_OBP0] = gb->io_registers[GB_IO_OBP1] = GB_is_cgb(gb)? 0x00 : 0xFF;
gb->accessed_oam_row = -1;
gb->dma_current_dest = 0xA1;
if (GB_is_hle_sgb(gb)) {
if (!gb->sgb) {
gb->sgb = malloc(sizeof(*gb->sgb));
}
memset(gb->sgb, 0, sizeof(*gb->sgb));
memset(gb->sgb_intro_jingle_phases, 0, sizeof(gb->sgb_intro_jingle_phases));
gb->sgb_intro_sweep_phase = 0;
gb->sgb_intro_sweep_previous_sample = 0;
gb->sgb->intro_animation = -10;
gb->sgb->player_count = 1;
GB_sgb_load_default_data(gb);
}
else {
if (gb->sgb) {
free(gb->sgb);
gb->sgb = NULL;
}
}
GB_set_internal_div_counter(gb, 8);
if (gb->nontrivial_jump_state) {
free(gb->nontrivial_jump_state);
gb->nontrivial_jump_state = NULL;
}
gb->magic = state_magic();
request_boot_rom(gb);
}
void GB_switch_model_and_reset(GB_gameboy_t *gb, GB_model_t model)
{
gb->model = model;
if (GB_is_cgb(gb)) {
gb->ram = realloc(gb->ram, gb->ram_size = 0x1000 * 8);
gb->vram = realloc(gb->vram, gb->vram_size = 0x2000 * 2);
}
else {
gb->ram = realloc(gb->ram, gb->ram_size = 0x2000);
gb->vram = realloc(gb->vram, gb->vram_size = 0x2000);
}
if (gb->undo_state) {
free(gb->undo_state);
gb->undo_state = NULL;
}
GB_rewind_free(gb);
GB_reset(gb);
load_default_border(gb);
}
void *GB_get_direct_access(GB_gameboy_t *gb, GB_direct_access_t access, size_t *size, uint16_t *bank)
{
/* Set size and bank to dummy pointers if not set */
size_t dummy_size;
uint16_t dummy_bank;
if (!size) {
size = &dummy_size;
}
if (!bank) {
bank = &dummy_bank;
}
switch (access) {
case GB_DIRECT_ACCESS_ROM:
*size = gb->rom_size;
*bank = gb->mbc_rom_bank;
return gb->rom;
case GB_DIRECT_ACCESS_RAM:
*size = gb->ram_size;
*bank = gb->cgb_ram_bank;
return gb->ram;
case GB_DIRECT_ACCESS_CART_RAM:
*size = gb->mbc_ram_size;
*bank = gb->mbc_ram_bank;
return gb->mbc_ram;
case GB_DIRECT_ACCESS_VRAM:
*size = gb->vram_size;
*bank = gb->cgb_vram_bank;
return gb->vram;
case GB_DIRECT_ACCESS_HRAM:
*size = sizeof(gb->hram);
*bank = 0;
return &gb->hram;
case GB_DIRECT_ACCESS_IO:
*size = sizeof(gb->io_registers);
*bank = 0;
return &gb->io_registers;
case GB_DIRECT_ACCESS_BOOTROM:
*size = GB_is_cgb(gb)? sizeof(gb->boot_rom) : 0x100;
*bank = 0;
return &gb->boot_rom;
case GB_DIRECT_ACCESS_OAM:
*size = sizeof(gb->oam);
*bank = 0;
return &gb->oam;
case GB_DIRECT_ACCESS_BGP:
*size = sizeof(gb->background_palettes_data);
*bank = 0;
return &gb->background_palettes_data;
case GB_DIRECT_ACCESS_OBP:
*size = sizeof(gb->object_palettes_data);
*bank = 0;
return &gb->object_palettes_data;
case GB_DIRECT_ACCESS_IE:
*size = sizeof(gb->interrupt_enable);
*bank = 0;
return &gb->interrupt_enable;
default:
*size = 0;
*bank = 0;
return NULL;
}
}
GB_registers_t *GB_get_registers(GB_gameboy_t *gb)
{
return (GB_registers_t *)&gb->registers;
}
void GB_set_clock_multiplier(GB_gameboy_t *gb, double multiplier)
{
gb->clock_multiplier = multiplier;
GB_update_clock_rate(gb);
}
uint32_t GB_get_clock_rate(GB_gameboy_t *gb)
{
return gb->clock_rate;
}
uint32_t GB_get_unmultiplied_clock_rate(GB_gameboy_t *gb)
{
return gb->unmultiplied_clock_rate;
}
void GB_update_clock_rate(GB_gameboy_t *gb)
{
if (gb->model & GB_MODEL_PAL_BIT) {
gb->unmultiplied_clock_rate = SGB_PAL_FREQUENCY;
}
else if ((gb->model & ~GB_MODEL_NO_SFC_BIT) == GB_MODEL_SGB) {
gb->unmultiplied_clock_rate = SGB_NTSC_FREQUENCY;
}
else {
gb->unmultiplied_clock_rate = CPU_FREQUENCY;
}
gb->clock_rate = gb->unmultiplied_clock_rate * gb->clock_multiplier;
}
void GB_set_border_mode(GB_gameboy_t *gb, GB_border_mode_t border_mode)
{
if (gb->border_mode > GB_BORDER_ALWAYS) return;
gb->border_mode = border_mode;
}
unsigned GB_get_screen_width(GB_gameboy_t *gb)
{
switch (gb->border_mode) {
default:
case GB_BORDER_SGB:
return GB_is_hle_sgb(gb)? 256 : 160;
case GB_BORDER_NEVER:
return 160;
case GB_BORDER_ALWAYS:
return 256;
}
}
unsigned GB_get_screen_height(GB_gameboy_t *gb)
{
switch (gb->border_mode) {
default:
case GB_BORDER_SGB:
return GB_is_hle_sgb(gb)? 224 : 144;
case GB_BORDER_NEVER:
return 144;
case GB_BORDER_ALWAYS:
return 224;
}
}
unsigned GB_get_player_count(GB_gameboy_t *gb)
{
return GB_is_hle_sgb(gb)? gb->sgb->player_count : 1;
}
void GB_set_update_input_hint_callback(GB_gameboy_t *gb, GB_update_input_hint_callback_t callback)
{
gb->update_input_hint_callback = callback;
}
double GB_get_usual_frame_rate(GB_gameboy_t *gb)
{
return GB_get_clock_rate(gb) / (double)LCDC_PERIOD;
}
void GB_set_joyp_write_callback(GB_gameboy_t *gb, GB_joyp_write_callback_t callback)
{
gb->joyp_write_callback = callback;
}
void GB_set_icd_pixel_callback(GB_gameboy_t *gb, GB_icd_pixel_callback_t callback)
{
gb->icd_pixel_callback = callback;
}
void GB_set_icd_hreset_callback(GB_gameboy_t *gb, GB_icd_hreset_callback_t callback)
{
gb->icd_hreset_callback = callback;
}
void GB_set_icd_vreset_callback(GB_gameboy_t *gb, GB_icd_vreset_callback_t callback)
{
gb->icd_vreset_callback = callback;
}
void GB_set_boot_rom_load_callback(GB_gameboy_t *gb, GB_boot_rom_load_callback_t callback)
{
gb->boot_rom_load_callback = callback;
request_boot_rom(gb);
}
unsigned GB_time_to_alarm(GB_gameboy_t *gb)
{
if (gb->cartridge_type->mbc_type != GB_HUC3) return 0;
if (!gb->huc3.alarm_enabled) return 0;
if (!(gb->huc3.alarm_days & 0x2000)) return 0;
unsigned current_time = (gb->huc3.days & 0x1FFF) * 24 * 60 * 60 + gb->huc3.minutes * 60 + (time(NULL) % 60);
unsigned alarm_time = (gb->huc3.alarm_days & 0x1FFF) * 24 * 60 * 60 + gb->huc3.alarm_minutes * 60;
if (current_time > alarm_time) return 0;
return alarm_time - current_time;
}
bool GB_has_accelerometer(GB_gameboy_t *gb)
{
return gb->cartridge_type->mbc_type == GB_MBC7;
}
void GB_set_accelerometer_values(GB_gameboy_t *gb, double x, double y)
{
gb->accelerometer_x = x;
gb->accelerometer_y = y;
}
void GB_get_rom_title(GB_gameboy_t *gb, char *title)
{
memset(title, 0, 17);
if (gb->rom_size >= 0x4000) {
for (unsigned i = 0; i < 0x10; i++) {
if (gb->rom[0x134 + i] < 0x20 || gb->rom[0x134 + i] >= 0x80) break;
title[i] = gb->rom[0x134 + i];
}
}
}
uint32_t GB_get_rom_crc32(GB_gameboy_t *gb)
{
static const uint32_t table[] = {
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F,
0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2,
0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9,
0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C,
0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423,
0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106,
0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D,
0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950,
0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7,
0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA,
0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81,
0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84,
0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB,
0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E,
0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55,
0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28,
0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F,
0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242,
0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69,
0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC,
0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693,
0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
};
const uint8_t *byte = gb->rom;
uint32_t size = gb->rom_size;
uint32_t ret = 0xFFFFFFFF;
while (size--) {
ret = table[(ret ^ *byte++) & 0xFF] ^ (ret >> 8);
}
return ~ret;
}
| 32.545869 | 140 | 0.585769 | [
"object",
"model"
] |
65fc896346020ca2de6d5eed34ab0b28b08543cb | 2,590 | h | C | module/server.h | ctring/Detock | a1171a511d9cd1f79cc3a8d54ec17f759d088de4 | [
"MIT"
] | null | null | null | module/server.h | ctring/Detock | a1171a511d9cd1f79cc3a8d54ec17f759d088de4 | [
"MIT"
] | null | null | null | module/server.h | ctring/Detock | a1171a511d9cd1f79cc3a8d54ec17f759d088de4 | [
"MIT"
] | null | null | null | #pragma once
#include <glog/logging.h>
#include <chrono>
#include <set>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <zmq.hpp>
#include "common/configuration.h"
#include "common/proto_utils.h"
#include "common/rate_limiter.h"
#include "common/types.h"
#include "connection/broker.h"
#include "module/base/networked_module.h"
#include "proto/api.pb.h"
#include "storage/lookup_master_index.h"
namespace slog {
/**
* A Server serves external requests from the clients.
*
* INPUT: External TransactionRequest
*
* OUTPUT: For external TransactionRequest, it forwards the txn internally
* to appropriate modules and waits for internal responses before
* responding back to the client with an external TransactionResponse.
*/
class Server : public NetworkedModule {
public:
Server(const std::shared_ptr<Broker>& broker, const MetricsRepositoryManagerPtr& metrics_manager,
std::chrono::milliseconds poll_timeout = kModuleTimeout);
std::string name() const override { return "Server"; }
protected:
void Initialize() final;
/**
* After a transaction is processed by different partitions, each
* involving partition will send a sub-transaction with the processing
* result to the coordinating server. The coordinating server will be
* in charge of merging these sub-transactions and responding back to
* the client.
*/
void OnInternalRequestReceived(EnvelopePtr&& env) final;
void OnInternalResponseReceived(EnvelopePtr&& env) final;
bool OnCustomSocket() final;
private:
void ProcessFinishedSubtxn(EnvelopePtr&& req);
void ProcessStatsRequest(const internal::StatsRequest& stats_request);
void SendTxnToClient(Transaction* txn);
void SendResponseToClient(TxnId txn_id, api::Response&& res);
TxnId NextTxnId();
RateLimiter rate_limiter_;
TxnId txn_id_counter_;
struct PendingResponse {
zmq::message_t identity;
uint32_t stream_id;
explicit PendingResponse(zmq::message_t&& identity, uint32_t stream_id)
: identity(std::move(identity)), stream_id(stream_id) {}
};
std::unordered_map<TxnId, PendingResponse> pending_responses_;
class FinishedTransaction {
public:
FinishedTransaction(size_t involved_partitions);
bool AddSubTxn(EnvelopePtr&& new_req, uint32_t part);
Transaction* ReleaseTxn();
private:
EnvelopePtr req_;
size_t remaining_partitions_;
};
std::unordered_map<TxnId, FinishedTransaction> finished_txns_;
std::unordered_set<MachineId> offline_machines_;
};
} // namespace slog | 28.152174 | 99 | 0.749035 | [
"vector"
] |
65fe3c21402f2ce2c11a0ec3b7feb2e4e3af8d12 | 519 | h | C | LibreSTR/units/BuildingSprite.h | jordsti/LibreSTR | f3ad913d333663211aa55379494aac6c898e079e | [
"MIT"
] | 1 | 2020-07-18T13:18:26.000Z | 2020-07-18T13:18:26.000Z | LibreSTR/units/BuildingSprite.h | jordsti/LibreSTR | f3ad913d333663211aa55379494aac6c898e079e | [
"MIT"
] | null | null | null | LibreSTR/units/BuildingSprite.h | jordsti/LibreSTR | f3ad913d333663211aa55379494aac6c898e079e | [
"MIT"
] | null | null | null | #ifndef BUILDINGSPRITE_H
#define BUILDINGSPRITE_H
#include "SpriteLibrary.h"
#include "UnitSprite.h"
#include "Building.h"
#include <vector>
class BuildingSprite :
public UnitSprite
{
public:
BuildingSprite(Building *m_building, StiGame::SpriteLibrary *m_library);
virtual ~BuildingSprite();
void render(void);
Unit* getUnit(void);
protected:
StiGame::SpriteLibrary *library;
Building *building;
std::map<std::string, StiGame::ClonedSprite> sprites;
};
#endif // BUILDINGSPRITE_H
| 21.625 | 76 | 0.728324 | [
"render",
"vector"
] |
d662f9a0fa8792d0e6914283a88d0e7273f0dea7 | 927 | h | C | src/node_timer.h | blaine/node | 704f394c6671af5b981900fc3666f1b97ef580a9 | [
"MIT"
] | 4 | 2015-04-08T12:21:32.000Z | 2022-01-25T02:51:35.000Z | src/node_timer.h | jdunck/node | d1f69ef35dac810530df8249d523add168e09f03 | [
"MIT"
] | null | null | null | src/node_timer.h | jdunck/node | d1f69ef35dac810530df8249d523add168e09f03 | [
"MIT"
] | 1 | 2019-12-19T16:28:13.000Z | 2019-12-19T16:28:13.000Z | #ifndef node_timer_h
#define node_timer_h
#include <node.h>
#include <node_events.h>
#include <v8.h>
#include <ev.h>
namespace node {
class Timer : EventEmitter {
public:
static void Initialize (v8::Handle<v8::Object> target);
protected:
static v8::Persistent<v8::FunctionTemplate> constructor_template;
Timer () : EventEmitter () { }
~Timer();
static v8::Handle<v8::Value> New (const v8::Arguments& args);
static v8::Handle<v8::Value> Start (const v8::Arguments& args);
static v8::Handle<v8::Value> Stop (const v8::Arguments& args);
static v8::Handle<v8::Value> RepeatGetter (v8::Local<v8::String> property, const v8::AccessorInfo& info);
static void RepeatSetter (v8::Local<v8::String> property, v8::Local<v8::Value> value, const v8::AccessorInfo& info);
private:
static void OnTimeout (EV_P_ ev_timer *watcher, int revents);
ev_timer watcher_;
};
} // namespace node
#endif // node_timer_h
| 27.264706 | 118 | 0.711974 | [
"object"
] |
d666ab84aede123eb3df7f584bdacf49364e2f36 | 2,812 | h | C | usr/libexec/druid/DRSessionController.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 2 | 2021-11-02T09:23:27.000Z | 2022-03-28T08:21:57.000Z | usr/libexec/druid/DRSessionController.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | null | null | null | usr/libexec/druid/DRSessionController.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 1 | 2022-03-28T08:21:59.000Z | 2022-03-28T08:21:59.000Z | //
// Generated by classdumpios 1.0.1 (64 bit) (iOS port by DreamDevLost)(Debug version compiled Sep 26 2020 13:48:20).
//
// Copyright (C) 1997-2019 Steve Nygard.
//
#import <objc/NSObject.h>
#import "DRSessionViewDelegate-Protocol.h"
#import "DRSessionViewModelDelegate-Protocol.h"
@class DRFlockAnimator, DRFlockLayout, DRFlockLayoutOutput, DRPrecisionMode, DRSessionView, DRSessionViewModel, NSMutableArray, NSString;
@protocol DRSessionControllerDelegate, OS_dispatch_source;
@interface DRSessionController : NSObject <DRSessionViewModelDelegate, DRSessionViewDelegate>
{
_Bool _animating; // 8 = 0x8
NSMutableArray *_afterAnimationBlocks; // 16 = 0x10
DRFlockLayout *_flockLayout; // 24 = 0x18
DRFlockAnimator *_flockAnimator; // 32 = 0x20
DRFlockLayoutOutput *_lastFlockLayoutOutput; // 40 = 0x28
NSObject<OS_dispatch_source> *_precisionHysteresisTimer; // 48 = 0x30
DRPrecisionMode *_pendingPrecisionMode; // 56 = 0x38
double _precisionModeLimitY; // 64 = 0x40
_Bool _didStartAnimateOut; // 72 = 0x48
unsigned int _sessionID; // 76 = 0x4c
id <DRSessionControllerDelegate> _delegate; // 80 = 0x50
DRSessionViewModel *_model; // 88 = 0x58
DRSessionView *_view; // 96 = 0x60
}
- (void).cxx_destruct; // IMP=0x0000000100025c9c
@property(readonly, nonatomic) DRSessionView *view; // @synthesize view=_view;
@property(readonly, nonatomic) DRSessionViewModel *model; // @synthesize model=_model;
@property(readonly, nonatomic) unsigned int sessionID; // @synthesize sessionID=_sessionID;
@property(readonly, nonatomic) __weak id <DRSessionControllerDelegate> delegate; // @synthesize delegate=_delegate;
- (struct CGPoint)_transformVelocity:(struct CGPoint)arg1 withTransform:(struct CATransform3D)arg2; // IMP=0x0000000100025b40
- (void)_usePrecisionMode:(id)arg1; // IMP=0x000000010002597c
- (void)_updatePrecisionMode; // IMP=0x0000000100025054
- (void)_requestItemImagesIfNecessary; // IMP=0x0000000100024a60
- (void)sessionViewWillLayoutSubviews:(id)arg1; // IMP=0x00000001000244dc
- (void)viewModelInvalidated:(id)arg1; // IMP=0x000000010002446c
- (id)visibleDroppedItemsWithTransform:(struct CATransform3D)arg1; // IMP=0x0000000100023eb4
- (void)animateOut; // IMP=0x0000000100023b54
- (void)performAfterAnimationsComplete:(CDUnknownBlockType)arg1; // IMP=0x0000000100023ab4
- (void)setOrientation:(long long)arg1 withDuration:(double)arg2 direction:(long long)arg3; // IMP=0x0000000100023aa4
- (void)dealloc; // IMP=0x0000000100023a4c
- (id)initWithSessionID:(unsigned int)arg1 delegate:(id)arg2; // IMP=0x0000000100023908
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| 48.482759 | 137 | 0.776316 | [
"model"
] |
d66e9049a4b41ca32aa2fcf9cf70f58eb0a5c5a3 | 9,312 | c | C | torch-test/mpich-3.4.3/src/mpi/attr/comm_set_attr.c | alchemy315/NoPFS | f3901e963e2301e8a6f1c7aac0511d0cf9a1889d | [
"BSD-3-Clause"
] | null | null | null | torch-test/mpich-3.4.3/src/mpi/attr/comm_set_attr.c | alchemy315/NoPFS | f3901e963e2301e8a6f1c7aac0511d0cf9a1889d | [
"BSD-3-Clause"
] | null | null | null | torch-test/mpich-3.4.3/src/mpi/attr/comm_set_attr.c | alchemy315/NoPFS | f3901e963e2301e8a6f1c7aac0511d0cf9a1889d | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) by Argonne National Laboratory
* See COPYRIGHT in top-level directory
*/
#include "mpiimpl.h"
#include "attr.h"
/* -- Begin Profiling Symbol Block for routine MPI_Comm_set_attr */
#if defined(HAVE_PRAGMA_WEAK)
#pragma weak MPI_Comm_set_attr = PMPI_Comm_set_attr
#elif defined(HAVE_PRAGMA_HP_SEC_DEF)
#pragma _HP_SECONDARY_DEF PMPI_Comm_set_attr MPI_Comm_set_attr
#elif defined(HAVE_PRAGMA_CRI_DUP)
#pragma _CRI duplicate MPI_Comm_set_attr as PMPI_Comm_set_attr
#elif defined(HAVE_WEAK_ATTRIBUTE)
int MPI_Comm_set_attr(MPI_Comm comm, int comm_keyval, void *attribute_val)
__attribute__ ((weak, alias("PMPI_Comm_set_attr")));
#endif
/* -- End Profiling Symbol Block */
/* Define MPICH_MPI_FROM_PMPI if weak symbols are not supported to build
the MPI routines */
#ifndef MPICH_MPI_FROM_PMPI
#undef MPI_Comm_set_attr
#define MPI_Comm_set_attr PMPI_Comm_set_attr
int MPIR_Comm_set_attr_impl(MPIR_Comm * comm_ptr, int comm_keyval, void *attribute_val,
MPIR_Attr_type attrType)
{
int mpi_errno = MPI_SUCCESS;
MPII_Keyval *keyval_ptr = NULL;
MPIR_Attribute *p;
MPIR_ERR_CHKANDJUMP(comm_keyval == MPI_KEYVAL_INVALID, mpi_errno, MPI_ERR_KEYVAL,
"**keyvalinvalid");
/* CHANGE FOR MPI 2.2: Look for attribute. They are ordered by when they
* were added, with the most recent first. This uses
* a simple linear list algorithm because few applications use more than a
* handful of attributes */
MPII_Keyval_get_ptr(comm_keyval, keyval_ptr);
MPIR_Assert(keyval_ptr != NULL);
/* printf("Setting attr val to %x\n", attribute_val); */
p = comm_ptr->attributes;
while (p) {
if (p->keyval->handle == keyval_ptr->handle) {
/* If found, call the delete function before replacing the
* attribute */
mpi_errno = MPIR_Call_attr_delete(comm_ptr->handle, p);
if (mpi_errno) {
goto fn_fail;
}
p->attrType = attrType;
/* FIXME: This code is incorrect in some cases, particularly
* in the case where intptr_t is different from MPI_Aint,
* since in that case, the Fortran 9x interface will provide
* more bytes in the attribute_val than this allows. The
* dual casts are a sign that this is faulty. This will
* need to be fixed in the type/win set_attr routines as
* well. */
p->value = (MPII_Attr_val_t) (intptr_t) attribute_val;
/* printf("Updating attr at %x\n", &p->value); */
/* Does not change the reference count on the keyval */
break;
}
p = p->next;
}
/* CHANGE FOR MPI 2.2: If not found, add at the beginning */
if (!p) {
MPIR_Attribute *new_p = MPID_Attr_alloc();
MPIR_ERR_CHKANDJUMP(!new_p, mpi_errno, MPI_ERR_OTHER, "**nomem");
/* Did not find in list. Add at end */
new_p->keyval = keyval_ptr;
new_p->attrType = attrType;
new_p->pre_sentinal = 0;
/* FIXME: See the comment above on this dual cast. */
new_p->value = (MPII_Attr_val_t) (intptr_t) attribute_val;
new_p->post_sentinal = 0;
new_p->next = comm_ptr->attributes;
MPII_Keyval_add_ref(keyval_ptr);
comm_ptr->attributes = new_p;
/* printf("Creating attr at %x\n", &new_p->value); */
}
/* Here is where we could add a hook for the device to detect attribute
* value changes, using something like
* MPID_Comm_attr_hook(comm_ptr, keyval, attribute_val);
*/
fn_exit:
return mpi_errno;
fn_fail:
goto fn_exit;
}
int MPII_Comm_set_attr(MPI_Comm comm, int comm_keyval, void *attribute_val, MPIR_Attr_type attrType)
{
int mpi_errno = MPI_SUCCESS;
MPIR_Comm *comm_ptr = NULL;
MPIR_FUNC_TERSE_STATE_DECL(MPID_STATE_MPIR_COMM_SET_ATTR);
MPIR_ERRTEST_INITIALIZED_ORDIE();
MPID_THREAD_CS_ENTER(GLOBAL, MPIR_THREAD_GLOBAL_ALLFUNC_MUTEX);
MPIR_FUNC_TERSE_ENTER(MPID_STATE_MPIR_COMM_SET_ATTR);
/* Validate parameters, especially handles needing to be converted */
#ifdef HAVE_ERROR_CHECKING
{
MPID_BEGIN_ERROR_CHECKS;
{
MPIR_ERRTEST_COMM(comm, mpi_errno);
MPIR_ERRTEST_KEYVAL(comm_keyval, MPIR_COMM, "communicator", mpi_errno);
MPIR_ERRTEST_KEYVAL_PERM(comm_keyval, mpi_errno);
}
MPID_END_ERROR_CHECKS;
}
#endif
/* Convert MPI object handles to object pointers */
MPIR_Comm_get_ptr(comm, comm_ptr);
/* Validate parameters and objects (post conversion) */
#ifdef HAVE_ERROR_CHECKING
{
MPID_BEGIN_ERROR_CHECKS;
{
MPII_Keyval *keyval_ptr = NULL;
/* Validate comm_ptr */
MPIR_Comm_valid_ptr(comm_ptr, mpi_errno, TRUE);
/* If comm_ptr is not valid, it will be reset to null */
/* Validate keyval_ptr */
MPII_Keyval_get_ptr(comm_keyval, keyval_ptr);
MPII_Keyval_valid_ptr(keyval_ptr, mpi_errno);
if (mpi_errno)
goto fn_fail;
}
MPID_END_ERROR_CHECKS;
}
#endif /* HAVE_ERROR_CHECKING */
/* ... body of routine ... */
mpi_errno = MPIR_Comm_set_attr_impl(comm_ptr, comm_keyval, attribute_val, attrType);
if (mpi_errno)
goto fn_fail;
/* ... end of body of routine ... */
fn_exit:
MPIR_FUNC_TERSE_EXIT(MPID_STATE_MPIR_COMM_SET_ATTR);
MPID_THREAD_CS_EXIT(GLOBAL, MPIR_THREAD_GLOBAL_ALLFUNC_MUTEX);
return mpi_errno;
fn_fail:
/* --BEGIN ERROR HANDLING-- */
#ifdef HAVE_ERROR_CHECKING
{
mpi_errno =
MPIR_Err_create_code(mpi_errno, MPIR_ERR_RECOVERABLE, __func__, __LINE__, MPI_ERR_OTHER,
"**mpi_comm_set_attr", "**mpi_comm_set_attr %C %d %p", comm,
comm_keyval, attribute_val);
}
#endif
mpi_errno = MPIR_Err_return_comm(comm_ptr, __func__, mpi_errno);
goto fn_exit;
/* --END ERROR HANDLING-- */
}
#endif /* MPICH_MPI_FROM_PMPI */
/*@
MPI_Comm_set_attr - Stores attribute value associated with a key
Input Parameters:
+ comm - communicator to which attribute will be attached (handle)
. comm_keyval - key value, as returned by 'MPI_Comm_create_keyval' (integer)
- attribute_val - attribute value
Notes:
Values of the permanent attributes 'MPI_TAG_UB', 'MPI_HOST', 'MPI_IO',
'MPI_WTIME_IS_GLOBAL', 'MPI_UNIVERSE_SIZE', 'MPI_LASTUSEDCODE', and
'MPI_APPNUM' may not be changed.
The type of the attribute value depends on whether C, C++, or Fortran
is being used.
In C and C++, an attribute value is a pointer ('void *'); in Fortran, it is an
address-sized integer.
If an attribute is already present, the delete function (specified when the
corresponding keyval was created) will be called.
.N ThreadSafe
.N Fortran
.N Errors
.N MPI_SUCCESS
.N MPI_ERR_COMM
.N MPI_ERR_KEYVAL
.N MPI_ERR_PERM_KEY
.seealso MPI_Comm_create_keyval, MPI_Comm_delete_attr
@*/
int MPI_Comm_set_attr(MPI_Comm comm, int comm_keyval, void *attribute_val)
{
int mpi_errno = MPI_SUCCESS;
MPIR_Comm *comm_ptr = NULL;
MPIR_FUNC_TERSE_STATE_DECL(MPID_STATE_MPI_COMM_SET_ATTR);
MPID_THREAD_CS_ENTER(GLOBAL, MPIR_THREAD_GLOBAL_ALLFUNC_MUTEX);
MPIR_FUNC_TERSE_ENTER(MPID_STATE_MPI_COMM_SET_ATTR);
/* Validate parameters, especially handles needing to be converted */
#ifdef HAVE_ERROR_CHECKING
{
MPID_BEGIN_ERROR_CHECKS;
{
MPIR_ERRTEST_COMM(comm, mpi_errno);
MPIR_ERRTEST_KEYVAL(comm_keyval, MPIR_COMM, "communicator", mpi_errno);
MPIR_ERRTEST_KEYVAL_PERM(comm_keyval, mpi_errno);
}
MPID_END_ERROR_CHECKS;
}
#endif
/* Convert MPI object handles to object pointers */
MPIR_Comm_get_ptr(comm, comm_ptr);
/* Validate parameters and objects (post conversion) */
#ifdef HAVE_ERROR_CHECKING
{
MPID_BEGIN_ERROR_CHECKS;
{
MPII_Keyval *keyval_ptr = NULL;
/* Validate comm_ptr */
MPIR_Comm_valid_ptr(comm_ptr, mpi_errno, TRUE);
/* If comm_ptr is not valid, it will be reset to null */
/* Validate keyval_ptr */
MPII_Keyval_get_ptr(comm_keyval, keyval_ptr);
MPII_Keyval_valid_ptr(keyval_ptr, mpi_errno);
if (mpi_errno)
goto fn_fail;
}
MPID_END_ERROR_CHECKS;
}
#endif /* HAVE_ERROR_CHECKING */
/* ... body of routine ... */
mpi_errno = MPIR_Comm_set_attr_impl(comm_ptr, comm_keyval, attribute_val, MPIR_ATTR_PTR);
if (mpi_errno)
goto fn_fail;
/* ... end of body of routine ... */
fn_exit:
MPIR_FUNC_TERSE_EXIT(MPID_STATE_MPI_COMM_SET_ATTR);
MPID_THREAD_CS_EXIT(GLOBAL, MPIR_THREAD_GLOBAL_ALLFUNC_MUTEX);
return mpi_errno;
fn_fail:
/* --BEGIN ERROR HANDLING-- */
#ifdef HAVE_ERROR_CHECKING
{
mpi_errno =
MPIR_Err_create_code(mpi_errno, MPIR_ERR_RECOVERABLE, __func__, __LINE__, MPI_ERR_OTHER,
"**mpi_comm_set_attr", "**mpi_comm_set_attr %C %d %p", comm,
comm_keyval, attribute_val);
}
#endif
goto fn_exit;
/* --END ERROR HANDLING-- */
}
| 33.496403 | 100 | 0.664734 | [
"object"
] |
d66f9adf2e6ac9e48b84728a85912a9b2b077a1d | 4,076 | h | C | romeo/romeo/src/romeo/robot.h | eerimoq/robomower | 9eac800689bd6ee02a8a93e078353873a73c26a5 | [
"MIT"
] | 2 | 2016-02-26T22:13:44.000Z | 2017-09-15T07:35:21.000Z | romeo/romeo/src/romeo/robot.h | eerimoq/robomower | 9eac800689bd6ee02a8a93e078353873a73c26a5 | [
"MIT"
] | null | null | null | romeo/romeo/src/romeo/robot.h | eerimoq/robomower | 9eac800689bd6ee02a8a93e078353873a73c26a5 | [
"MIT"
] | 3 | 2015-12-31T08:46:36.000Z | 2021-09-24T08:12:36.000Z | /**
* @file romeo/robot.h
* @version 0.1
*
* @section License
* Copyright (C) 2015, Erik Moqvist
*
* 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.
*
* This file is part of the Romeo project.
*/
#ifndef __ROMEO_ROBOT_H__
#define __ROMEO_ROBOT_H__
#include "simba.h"
#include "romeo.h"
/* The processing loop period in milliseconds. */
#define PROCESS_PERIOD_MS 30L
#define PROCESS_PERIOD_NS (PROCESS_PERIOD_MS * 1000000L)
/* Robot modes. */
enum robot_mode_t {
ROBOT_MODE_MANUAL = 0,
ROBOT_MODE_AUTOMATIC
};
/* Robot states. */
enum e_robot_state_t {
ROBOT_STATE_IDLE = 0,
ROBOT_STATE_STARTING,
ROBOT_STATE_CUTTING,
ROBOT_STATE_SEARCHING_FOR_BASE_STATION,
ROBOT_STATE_IN_BASE_STATION
};
/* Cutting states. */
enum e_cutting_state_t {
CUTTING_STATE_FORWARD = 0,
CUTTING_STATE_BACKWARDS,
CUTTING_STATE_ROTATING
};
/* Searching for base station states. */
enum e_searching_state_t {
SEARCHING_STATE_SEARCHING_FOR_PERIMETER_WIRE = 0,
SEARCHING_STATE_ALIGNING_WITH_WIRE,
SEARCHING_STATE_FOLLOWING_PERIMETER_WIRE
};
/* Drive backwards a number of ticks. */
#ifndef CUTTING_STATE_BACKWARDS_TICKS
# define CUTTING_STATE_BACKWARDS_TICKS (1500L / PROCESS_PERIOD_MS)
#endif
#ifndef WATCHDOG_TIMEOUT_TICKS
# define WATCHDOG_TIMEOUT_TICKS (1500L / PROCESS_PERIOD_MS)
#endif
/* Rotate a random number of ticks. */
#ifndef CUTTING_STATE_ROTATING_TICKS
# include <math.h>
# define CUTTING_STATE_ROTATING_TICKS \
((500L + (rand() % 512L)) / PROCESS_PERIOD_MS)
#endif
struct robot_t;
typedef int (*state_callback_t)(struct robot_t *);
typedef state_callback_t (*transition_callback_t)(struct robot_t *);
struct robot_state_t {
volatile int current;
volatile int next;
int (*callback)(struct robot_t *);
};
struct cutting_state_t {
int state;
int ticks_left;
};
struct searching_for_base_station_state_t {
int state;
struct controller_pid_t pid_controller;
float control;
struct {
int is_inside;
int count;
} tick;
};
struct robot_t {
volatile int mode;
struct robot_state_t state;
union {
struct cutting_state_t cutting;
struct searching_for_base_station_state_t searching;
} substate;
struct movement_t movement;
struct motor_t left_motor;
struct motor_t right_motor;
struct perimeter_wire_rx_t perimeter;
struct battery_t battery;
struct watchdog_t watchdog;
struct {
int tick_time;
} debug;
volatile struct {
float speed;
float omega;
} manual;
};
/**
* Initialize the robot module.
* @return zero(0) or negative error code
*/
int robot_module_init(void);
/**
* Initialize robot object.
* @param[out] robot_p Robot object to initialize.
* @return zero(0) or negative error code
*/
int robot_init(struct robot_t *robot_p);
/**
* Start of the robot. Do from idle to cutting state.
* @param[in] robot_p Initialized robot object.
* @return zero(0) or negative error code
*/
int robot_start(struct robot_t *robot_p);
/**
* Stop of the robot. Do from idle to cutting state.
* @param[in] robot_p Initialized robot object.
* @return zero(0) or negative error code
*/
int robot_stop(struct robot_t *robot_p);
/**
* Tick the robot.
* @param[in] robot_p Initialized robot object.
* @return zero(0) or negative error code
*/
int robot_tick(struct robot_t *robot_p);
/**
* Kick the robot watchdog.
* @param[in] robot_p Initialized robot object.
* @return zero(0) or negative error code
*/
int robot_watchdog_kick(struct robot_t *robot_p);
#endif
| 24.554217 | 69 | 0.720559 | [
"object"
] |
d6717da2ac77cd60ba5b28d739c10131da097254 | 21,378 | c | C | rt-smart/kernel/bsp/imx6ull/platform/devices/MCIMX6Y2/system_MCIMX6Y2.c | dengchow/rt_smart_imx6ull- | 4d9879e3d543a4e4ddd4b73ce0d30668127f5c5a | [
"Apache-2.0"
] | null | null | null | rt-smart/kernel/bsp/imx6ull/platform/devices/MCIMX6Y2/system_MCIMX6Y2.c | dengchow/rt_smart_imx6ull- | 4d9879e3d543a4e4ddd4b73ce0d30668127f5c5a | [
"Apache-2.0"
] | null | null | null | rt-smart/kernel/bsp/imx6ull/platform/devices/MCIMX6Y2/system_MCIMX6Y2.c | dengchow/rt_smart_imx6ull- | 4d9879e3d543a4e4ddd4b73ce0d30668127f5c5a | [
"Apache-2.0"
] | 2 | 2021-11-10T12:07:35.000Z | 2022-01-17T14:24:56.000Z | /*
** ###################################################################
** Processors: MCIMX6Y2CVM05
** MCIMX6Y2CVM08
** MCIMX6Y2DVM05
** MCIMX6Y2DVM09
**
** Compilers: Keil ARM C/C++ Compiler
** GNU C Compiler
** IAR ANSI C/C++ Compiler for ARM
**
** Reference manual: IMX6ULLRM, Rev. 1, Feb. 2017
** Version: rev. 3.0, 2017-02-28
** Build: b170410
**
** Abstract:
** Provides a system configuration function and a global variable that
** contains the system frequency. It configures the device and initializes
** the oscillator (PLL) that is part of the microcontroller device.
**
** Copyright 2016 Freescale Semiconductor, Inc.
** Copyright 2016-2017 NXP
** Redistribution and use in source and binary forms, with or without modification,
** are permitted provided that the following conditions are met:
**
** o Redistributions of source code must retain the above copyright notice, this list
** of conditions and the following disclaimer.
**
** o 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.
**
** o Neither the name of the copyright holder nor the names of its
** contributors may be used to endorse or promote products derived from this
** software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
** ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
** ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
** http: www.nxp.com
** mail: support@nxp.com
**
** Revisions:
** - rev. 1.0 (2015-12-18)
** Initial version.
** - rev. 2.0 (2016-08-02)
** Rev.B Header GA
** - rev. 3.0 (2017-02-28)
** Rev.1 Header GA
**
** ###################################################################
*/
/*!
* @file MCIMX6Y2
* @version 3.0
* @date 2017-02-28
* @brief Device specific configuration file for MCIMX6Y2 (implementation file)
*
* Provides a system configuration function and a global variable that contains
* the system frequency. It configures the device and initializes the oscillator
* (PLL) that is part of the microcontroller device.
*/
#include <stdint.h>
#include "fsl_device_registers.h"
/* Transaction Drivers Handler Declaration */
extern void CAN1_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void CAN2_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void ECSPI1_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void ECSPI2_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void ECSPI3_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void ECSPI4_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void ENET1_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void ENET1_Driver1588IRQHandler (uint32_t giccIar, void *userParam);
extern void ENET2_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void ENET2_Driver1588IRQHandler (uint32_t giccIar, void *userParam);
extern void I2C1_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void I2C2_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void I2C3_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void I2C4_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void I2S1_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void I2S2_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void I2S3_Tx_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void I2S3_Rx_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void UART1_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void UART2_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void UART3_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void UART4_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void UART5_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void UART6_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void UART7_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void UART8_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void USDHC1_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void USDHC2_DriverIRQHandler (uint32_t giccIar, void *userParam);
extern void SDMA_DriverIRQHandler (uint32_t giccIar, void *userParam);
#if defined(__IAR_SYSTEMS_ICC__)
#pragma weak CAN1_DriverIRQHandler=defaultIrqHandler
#pragma weak CAN2_DriverIRQHandler=defaultIrqHandler
#pragma weak ECSPI1_DriverIRQHandler=defaultIrqHandler
#pragma weak ECSPI2_DriverIRQHandler=defaultIrqHandler
#pragma weak ECSPI3_DriverIRQHandler=defaultIrqHandler
#pragma weak ECSPI4_DriverIRQHandler=defaultIrqHandler
#pragma weak ENET1_DriverIRQHandler=defaultIrqHandler
#pragma weak ENET2_DriverIRQHandler=defaultIrqHandler
#pragma weak ENET1_Driver1588IRQHandler=defaultIrqHandler
#pragma weak ENET2_Driver1588IRQHandler=defaultIrqHandler
#pragma weak I2C1_DriverIRQHandler=defaultIrqHandler
#pragma weak I2C2_DriverIRQHandler=defaultIrqHandler
#pragma weak I2C3_DriverIRQHandler=defaultIrqHandler
#pragma weak I2C4_DriverIRQHandler=defaultIrqHandler
#pragma weak I2S1_DriverIRQHandler=defaultIrqHandler
#pragma weak I2S2_DriverIRQHandler=defaultIrqHandler
#pragma weak I2S3_Tx_DriverIRQHandler=defaultIrqHandler
#pragma weak I2S3_Rx_DriverIRQHandler=defaultIrqHandler
#pragma weak UART1_DriverIRQHandler=defaultIrqHandler
#pragma weak UART2_DriverIRQHandler=defaultIrqHandler
#pragma weak UART3_DriverIRQHandler=defaultIrqHandler
#pragma weak UART4_DriverIRQHandler=defaultIrqHandler
#pragma weak UART5_DriverIRQHandler=defaultIrqHandler
#pragma weak UART6_DriverIRQHandler=defaultIrqHandler
#pragma weak UART7_DriverIRQHandler=defaultIrqHandler
#pragma weak UART8_DriverIRQHandler=defaultIrqHandler
#pragma weak USDHC1_DriverIRQHandler=defaultIrqHandler
#pragma weak USDHC2_DriverIRQHandler=defaultIrqHandler
#pragma weak SDMA_DriverIRQHandler=defaultIrqHandler
#elif defined(__GNUC__)
void CAN1_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void CAN2_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void ECSPI1_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void ECSPI2_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void ECSPI3_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void ECSPI4_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void ENET1_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void ENET2_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void ENET1_Driver1588IRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void ENET2_Driver1588IRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void I2C1_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void I2C2_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void I2C3_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void I2C4_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void I2S1_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void I2S2_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void I2S3_Tx_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void I2S3_Rx_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void UART1_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void UART2_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void UART3_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void UART4_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void UART5_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void UART6_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void UART7_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void UART8_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void USDHC1_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void USDHC2_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
void SDMA_DriverIRQHandler() __attribute__((weak, alias("defaultIrqHandler")));
#else
#error Not supported compiler type
#endif
extern uint32_t __VECTOR_TABLE[];
/* Local irq table and nesting level value */
static sys_irq_handle_t irqTable[NUMBER_OF_INT_VECTORS];
static uint32_t irqNesting;
/* Local IRQ functions */
static void defaultIrqHandler (uint32_t giccIar, void *userParam) {
while(1) {
}
}
/* ----------------------------------------------------------------------------
-- Core clock
---------------------------------------------------------------------------- */
uint32_t SystemCoreClock = DEFAULT_SYSTEM_CLOCK;
/* ----------------------------------------------------------------------------
-- SystemInit()
---------------------------------------------------------------------------- */
void SystemInit (void) {
uint32_t sctlr;
uint32_t actlr;
#if ((__FPU_PRESENT == 1) && (__FPU_USED == 1))
uint32_t cpacr;
uint32_t fpexc;
#endif
L1C_InvalidateInstructionCacheAll();
L1C_InvalidateDataCacheAll();
actlr = __get_ACTLR();
actlr = (actlr | ACTLR_SMP_Msk); /* Change to SMP mode before enable DCache */
__set_ACTLR(actlr);
sctlr = __get_SCTLR();
sctlr = (sctlr & ~(SCTLR_V_Msk | /* Use low vector */
SCTLR_A_Msk | /* Disable alignment fault checking */
SCTLR_M_Msk)) /* Disable MMU */
| (SCTLR_I_Msk | /* Enable ICache */
SCTLR_Z_Msk | /* Enable Prediction */
SCTLR_CP15BEN_Msk | /* Enable CP15 barrier operations */
SCTLR_C_Msk); /* Enable DCache */
__set_SCTLR(sctlr);
/* Set vector base address */
GIC_Init();
__set_VBAR((uint32_t)__VECTOR_TABLE);
#if ((__FPU_PRESENT == 1) && (__FPU_USED == 1))
cpacr = __get_CPACR();
/* Enable NEON and FPU */
cpacr = (cpacr & ~(CPACR_ASEDIS_Msk | CPACR_D32DIS_Msk))
| (3UL << CPACR_cp10_Pos) | (3UL << CPACR_cp11_Pos);
__set_CPACR(cpacr);
fpexc = __get_FPEXC();
fpexc |= 0x40000000UL; /* Enable NEON and FPU */
__set_FPEXC(fpexc);
#endif /* ((__FPU_PRESENT == 1) && (__FPU_USED == 1)) */
}
/* ----------------------------------------------------------------------------
-- SystemCoreClockUpdate()
---------------------------------------------------------------------------- */
void SystemCoreClockUpdate (void) {
/* i.MX6ULL systemCoreClockUpdate */
uint32_t PLL1SWClock;
uint32_t PLL2MainClock;
if (CCM->CCSR & CCM_CCSR_PLL1_SW_CLK_SEL_MASK)
{
if (CCM->CCSR & CCM_CCSR_STEP_SEL_MASK)
{
/* Get SYS PLL clock*/
if (CCM_ANALOG->PLL_SYS & CCM_ANALOG_PLL_SYS_DIV_SELECT_MASK)
{
PLL2MainClock = (24000000UL * 22UL + (uint64_t)(24000000UL) * (uint64_t)(CCM_ANALOG->PLL_SYS_NUM) / (uint64_t)(CCM_ANALOG->PLL_SYS_DENOM));
}
else
{
PLL2MainClock = (24000000UL * 20UL + (uint64_t)(24000000UL) * (uint64_t)(CCM_ANALOG->PLL_SYS_NUM) / (uint64_t)(CCM_ANALOG->PLL_SYS_DENOM));
}
if (CCM->CCSR & CCM_CCSR_SECONDARY_CLK_SEL_MASK)
{
/* PLL2 ---> Secondary_clk ---> Step Clock ---> CPU Clock */
PLL1SWClock = PLL2MainClock;
}
else
{
/* PLL2 PFD2 ---> Secondary_clk ---> Step Clock ---> CPU Clock */
PLL1SWClock = ((uint64_t)PLL2MainClock * 18) / ((CCM_ANALOG->PFD_528 & CCM_ANALOG_PFD_528_PFD2_FRAC_MASK) >> CCM_ANALOG_PFD_528_PFD2_FRAC_SHIFT);
}
}
else
{
/* Osc_clk (24M) ---> Step Clock ---> CPU Clock */
PLL1SWClock = 24000000UL;
}
}
else
{
/* ARM PLL ---> CPU Clock */
PLL1SWClock = 24000000UL;
PLL1SWClock = ( PLL1SWClock * (CCM_ANALOG->PLL_ARM & CCM_ANALOG_PLL_ARM_DIV_SELECT_MASK) >> CCM_ANALOG_PLL_ARM_DIV_SELECT_SHIFT) >> 1UL;
}
SystemCoreClock = PLL1SWClock / (((CCM->CACRR & CCM_CACRR_ARM_PODF_MASK) >> CCM_CACRR_ARM_PODF_SHIFT) + 1UL);
}
/* ----------------------------------------------------------------------------
-- SystemInitIrqTable()
---------------------------------------------------------------------------- */
void SystemInitIrqTable (void) {
uint32_t i;
/* First set all handler to default */
for (i = 0; i < NUMBER_OF_INT_VECTORS; i++) {
SystemInstallIrqHandler((IRQn_Type)i, defaultIrqHandler, NULL);
}
/* Then set transaction drivers handler */
/* FlexCAN transaction drivers handler */
SystemInstallIrqHandler(CAN1_IRQn, CAN1_DriverIRQHandler, NULL);
SystemInstallIrqHandler(CAN2_IRQn, CAN2_DriverIRQHandler, NULL);
/* ECSPI transaction drivers handler */
SystemInstallIrqHandler(eCSPI1_IRQn, ECSPI1_DriverIRQHandler, NULL);
SystemInstallIrqHandler(eCSPI2_IRQn, ECSPI2_DriverIRQHandler, NULL);
SystemInstallIrqHandler(eCSPI3_IRQn, ECSPI3_DriverIRQHandler, NULL);
SystemInstallIrqHandler(eCSPI4_IRQn, ECSPI4_DriverIRQHandler, NULL);
/* ENET transaction drivers handler */
SystemInstallIrqHandler(ENET1_IRQn, ENET1_DriverIRQHandler, NULL);
SystemInstallIrqHandler(ENET1_1588_IRQn, ENET1_Driver1588IRQHandler, NULL);
SystemInstallIrqHandler(ENET2_IRQn, ENET2_DriverIRQHandler, NULL);
SystemInstallIrqHandler(ENET2_1588_IRQn, ENET2_Driver1588IRQHandler, NULL);
/* I2C transaction drivers handler */
SystemInstallIrqHandler(I2C1_IRQn, I2C1_DriverIRQHandler, NULL);
SystemInstallIrqHandler(I2C2_IRQn, I2C2_DriverIRQHandler, NULL);
SystemInstallIrqHandler(I2C3_IRQn, I2C3_DriverIRQHandler, NULL);
SystemInstallIrqHandler(I2C4_IRQn, I2C4_DriverIRQHandler, NULL);
/* I2S transaction drivers handler */
SystemInstallIrqHandler(SAI1_IRQn, I2S1_DriverIRQHandler, NULL);
SystemInstallIrqHandler(SAI2_IRQn, I2S2_DriverIRQHandler, NULL);
SystemInstallIrqHandler(SAI3_TX_IRQn, I2S3_Tx_DriverIRQHandler, NULL);
SystemInstallIrqHandler(SAI3_RX_IRQn, I2S3_Rx_DriverIRQHandler, NULL);
/* UART transaction drivers handler */
SystemInstallIrqHandler(UART1_IRQn, UART1_DriverIRQHandler, NULL);
SystemInstallIrqHandler(UART2_IRQn, UART2_DriverIRQHandler, NULL);
SystemInstallIrqHandler(UART3_IRQn, UART3_DriverIRQHandler, NULL);
SystemInstallIrqHandler(UART4_IRQn, UART4_DriverIRQHandler, NULL);
SystemInstallIrqHandler(UART5_IRQn, UART5_DriverIRQHandler, NULL);
SystemInstallIrqHandler(UART6_IRQn, UART6_DriverIRQHandler, NULL);
SystemInstallIrqHandler(UART7_IRQn, UART7_DriverIRQHandler, NULL);
SystemInstallIrqHandler(UART8_IRQn, UART8_DriverIRQHandler, NULL);
/* USDHC transaction drivers handler */
SystemInstallIrqHandler(USDHC1_IRQn, USDHC1_DriverIRQHandler, NULL);
SystemInstallIrqHandler(USDHC2_IRQn, USDHC2_DriverIRQHandler, NULL);
/* SDMA transaction driver handler */
SystemInstallIrqHandler(SDMA_IRQn, SDMA_DriverIRQHandler, NULL);
}
/* ----------------------------------------------------------------------------
-- SystemInstallIrqHandler()
---------------------------------------------------------------------------- */
void SystemInstallIrqHandler(IRQn_Type irq, system_irq_handler_t handler, void *userParam) {
irqTable[irq].irqHandler = handler;
irqTable[irq].userParam = userParam;
}
/* ----------------------------------------------------------------------------
-- SystemIrqHandler()
---------------------------------------------------------------------------- */
#if defined(__IAR_SYSTEMS_ICC__)
#pragma weak SystemIrqHandler
void SystemIrqHandler(uint32_t giccIar) {
#elif defined(__GNUC__)
__attribute__((weak)) void SystemIrqHandler(uint32_t giccIar) {
#else
#error Not supported compiler type
#endif
uint32_t intNum = giccIar & 0x3FFUL;
/* Spurious interrupt ID or Wrong interrupt number */
if ((intNum == 1023) || (intNum >= NUMBER_OF_INT_VECTORS))
{
return;
}
irqNesting++;
__enable_irq(); /* Support nesting interrupt */
/* Now call the real irq handler for intNum */
irqTable[intNum].irqHandler(giccIar, irqTable[intNum].userParam);
__disable_irq();
irqNesting--;
}
uint32_t SystemGetIRQNestingLevel(void)
{
return irqNesting;
}
/* Leverage GPT1 to provide Systick */
void SystemSetupSystick(uint32_t tickRateHz, void *tickHandler, uint32_t intPriority)
{
uint32_t clockFreq;
uint32_t spllTmp;
/* Install IRQ handler for GPT1 */
SystemInstallIrqHandler(GPT1_IRQn, (system_irq_handler_t)(uint32_t)tickHandler, NULL);
/* Enable Systick all the time */
CCM->CCGR1 |= CCM_CCGR1_CG10_MASK | CCM_CCGR1_CG11_MASK;
GPT1->CR = GPT_CR_SWR_MASK;
/* Wait reset finished. */
while (GPT1->CR == GPT_CR_SWR_MASK)
{
}
/* Use peripheral clock source IPG */
GPT1->CR = GPT_CR_WAITEN_MASK | GPT_CR_STOPEN_MASK | GPT_CR_DOZEEN_MASK |
GPT_CR_DBGEN_MASK | GPT_CR_ENMOD_MASK | GPT_CR_CLKSRC(1UL);
/* Set clock divider to 1 */
GPT1->PR = 0;
/* Get IPG clock*/
/* Periph_clk2_clk ---> Periph_clk */
if (CCM->CBCDR & CCM_CBCDR_PERIPH_CLK_SEL_MASK)
{
switch (CCM->CBCMR & CCM_CBCMR_PERIPH_CLK2_SEL_MASK)
{
/* Pll3_sw_clk ---> Periph_clk2_clk ---> Periph_clk */
case CCM_CBCMR_PERIPH_CLK2_SEL(0U):
clockFreq = (24000000UL * ((CCM_ANALOG->PLL_USB1 & CCM_ANALOG_PLL_USB1_DIV_SELECT_MASK) ? 22U : 20U));
break;
/* Osc_clk ---> Periph_clk2_clk ---> Periph_clk */
case CCM_CBCMR_PERIPH_CLK2_SEL(1U):
clockFreq = 24000000UL;
break;
case CCM_CBCMR_PERIPH_CLK2_SEL(2U):
case CCM_CBCMR_PERIPH_CLK2_SEL(3U):
default:
clockFreq = 0U;
break;
}
clockFreq /= (((CCM->CBCDR & CCM_CBCDR_PERIPH_CLK2_PODF_MASK) >> CCM_CBCDR_PERIPH_CLK2_PODF_SHIFT) + 1U);
}
/* Pll2_main_clk ---> Periph_clk */
else
{
/* Get SYS PLL clock*/
if (CCM_ANALOG->PLL_SYS & CCM_ANALOG_PLL_SYS_DIV_SELECT_MASK)
{
spllTmp = (24000000UL * 22UL + (uint64_t)(24000000UL) * (uint64_t)(CCM_ANALOG->PLL_SYS_NUM) / (uint64_t)(CCM_ANALOG->PLL_SYS_DENOM));
}
else
{
spllTmp = (24000000UL * 20UL + (uint64_t)(24000000UL) * (uint64_t)(CCM_ANALOG->PLL_SYS_NUM) / (uint64_t)(CCM_ANALOG->PLL_SYS_DENOM));
}
switch (CCM->CBCMR & CCM_CBCMR_PRE_PERIPH_CLK_SEL_MASK)
{
/* PLL2 ---> Pll2_main_clk ---> Periph_clk */
case CCM_CBCMR_PRE_PERIPH_CLK_SEL(0U):
clockFreq = spllTmp;
break;
/* PLL2 PFD2 ---> Pll2_main_clk ---> Periph_clk */
case CCM_CBCMR_PRE_PERIPH_CLK_SEL(1U):
clockFreq = ((uint64_t)spllTmp * 18) / ((CCM_ANALOG->PFD_528 & CCM_ANALOG_PFD_528_PFD2_FRAC_MASK) >> CCM_ANALOG_PFD_528_PFD2_FRAC_SHIFT);
break;
/* PLL2 PFD0 ---> Pll2_main_clk ---> Periph_clk */
case CCM_CBCMR_PRE_PERIPH_CLK_SEL(2U):
clockFreq = ((uint64_t)spllTmp * 18) / ((CCM_ANALOG->PFD_528 & CCM_ANALOG_PFD_528_PFD0_FRAC_MASK) >> CCM_ANALOG_PFD_528_PFD0_FRAC_SHIFT);
break;
/* PLL2 PFD2 divided(/2) ---> Pll2_main_clk ---> Periph_clk */
case CCM_CBCMR_PRE_PERIPH_CLK_SEL(3U):
clockFreq = ((((uint64_t)spllTmp * 18) / ((CCM_ANALOG->PFD_528 & CCM_ANALOG_PFD_528_PFD2_FRAC_MASK) >> CCM_ANALOG_PFD_528_PFD2_FRAC_SHIFT)) >> 1U);
break;
default:
clockFreq = 0U;
break;
}
}
clockFreq /= (((CCM->CBCDR & CCM_CBCDR_AHB_PODF_MASK) >> CCM_CBCDR_AHB_PODF_SHIFT) + 1U);
clockFreq /= (((CCM->CBCDR & CCM_CBCDR_IPG_PODF_MASK) >> CCM_CBCDR_IPG_PODF_SHIFT) + 1U);
/* Set timeout value and enable interrupt */
GPT1->OCR[0] = clockFreq / tickRateHz - 1UL;
GPT1->IR = GPT_IR_OF1IE_MASK;
/* Set interrupt priority */
GIC_SetPriority(GPT1_IRQn, intPriority);
/* Enable IRQ */
GIC_EnableIRQ(GPT1_IRQn);
/* Start GPT counter */
GPT1->CR |= GPT_CR_EN_MASK;
}
void SystemClearSystickFlag(void)
{
GPT1->SR = GPT_SR_OF1_MASK;
}
| 43.628571 | 163 | 0.682758 | [
"vector"
] |
d672ce3a92a01ae4c7d70e05d31c983a22dca394 | 1,848 | h | C | src/helics/network/zmq/ZmqComms.h | GMLC-TDC/HELICS-src | 5e37168bca0ea9e16b939e052e257182ca6e24bd | [
"BSD-3-Clause"
] | 31 | 2017-06-29T19:50:25.000Z | 2019-05-17T14:10:14.000Z | src/helics/network/zmq/ZmqComms.h | GMLC-TDC/HELICS-src | 5e37168bca0ea9e16b939e052e257182ca6e24bd | [
"BSD-3-Clause"
] | 511 | 2017-08-18T02:14:00.000Z | 2019-06-18T20:11:02.000Z | src/helics/network/zmq/ZmqComms.h | GMLC-TDC/HELICS-src | 5e37168bca0ea9e16b939e052e257182ca6e24bd | [
"BSD-3-Clause"
] | 11 | 2017-10-27T15:03:37.000Z | 2019-05-03T19:35:14.000Z | /*
Copyright (c) 2017-2022,
Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable
Energy, LLC. See the top-level NOTICE for additional details. All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
*/
#pragma once
#include "../NetworkCommsInterface.hpp"
#include <atomic>
#include <set>
#include <string>
namespace zmq {
class message_t;
class socket_t;
} // namespace zmq
namespace helics {
namespace zeromq {
/** implementation for the communication interface that uses ZMQ messages to communicate*/
class ZmqComms final: public NetworkCommsInterface {
public:
/** default constructor*/
ZmqComms() noexcept;
/** destructor*/
~ZmqComms();
/** load network information into the comms object*/
virtual void loadNetworkInfo(const NetworkBrokerData& netInfo) override;
/** set the port numbers for the local ports*/
private:
virtual int getDefaultBrokerPort() const override;
virtual void queue_rx_function() override; //!< the functional loop for the receive queue
virtual void queue_tx_function() override; //!< the loop for transmitting data
virtual void closeReceiver() override; //!< function to instruct the receiver loop to close
/** process an incoming message
return code for required action 0=NONE, -1 TERMINATE*/
int processIncomingMessage(zmq::message_t& msg);
/** process an incoming message and send and ack in response
return code for required action 0=NONE, -1 TERMINATE*/
int replyToIncomingMessage(zmq::message_t& msg, zmq::socket_t& sock);
int initializeBrokerConnections(zmq::socket_t& controlSocket);
public:
std::string getPushAddress() const;
};
} // namespace zeromq
} // namespace helics
| 34.222222 | 100 | 0.699134 | [
"object"
] |
d67939d8ad4bb0cf8b662988587f65251c6ca797 | 111,180 | c | C | src/slots_table.c | ashtul/RedisGears | eba879519984616536027717d7d02f81007ae985 | [
"Adobe-2006"
] | null | null | null | src/slots_table.c | ashtul/RedisGears | eba879519984616536027717d7d02f81007ae985 | [
"Adobe-2006"
] | null | null | null | src/slots_table.c | ashtul/RedisGears | eba879519984616536027717d7d02f81007ae985 | [
"Adobe-2006"
] | null | null | null | #include "slots_table.h"
const char *slot_table[] = {
"06S", "Qi", "5L5", "4Iu", "4gY", "460", "1Y7", "1LV", "0QG", "ru", "7Ok", "4ji", "4DE", "65n", "2JH", "I8", "F9", "SX", "7nF", "4KD",
"4eh", "6PK", "2ke", "1Ng", "0Sv", "4L", "491", "4hX", "4Ft", "5C4", "2Hy", "09R", "021", "0cX", "4Xv", "6mU", "6Cy", "42R", "0Mt", "nF",
"cv", "1Pe", "5kK", "6NI", "74L", "4UF", "0nh", "MZ", "2TJ", "0ai", "4ZG", "6od", "6AH", "40c", "0OE", "lw", "aG", "0Bu", "5iz", "6Lx",
"5R7", "4Ww", "0lY", "Ok", "5n3", "4ks", "8YE", "7g", "2KR", "1nP", "714", "64t", "69D", "4Ho", "07I", "Ps", "2hN", "1ML", "4fC", "7CA",
"avs", "4iB", "0Rl", "5V", "2Ic", "08H", "4Gn", "66E", "aUo", "b4e", "05x", "RB", "8f", "8VD", "4dr", "5a2", "4zp", "6OS", "bl", "355",
"0or", "1j2", "75V", "bno", "4Yl", "6lO", "Ap", "0bB", "0Ln", "2yM", "6Bc", "43H", "4xA", "6Mb", "22D", "14", "0mC", "Nq", "6cN", "4Vm",
"ban", "aDl", "CA", "14Z", "8GG", "mm", "549", "41y", "53t", "464", "1Y3", "1LR", "06W", "Qm", "5L1", "4Iq", "4DA", "65j", "2JL", "1oN",
"0QC", "6y", "7Oo", "4jm", "4el", "6PO", "9x", "1Nc", "04f", "2EM", "7nB", "bqs", "4Fp", "5C0", "d6F", "09V", "0Sr", "4H", "495", "bRo",
"aio", "42V", "0Mp", "nB", "025", "17u", "4Xr", "6mQ", "74H", "4UB", "0nl", "3Kn", "cr", "1Pa", "5kO", "6NM", "6AL", "40g", "0OA", "ls",
"2TN", "0am", "4ZC", "aEr", "5R3", "4Ws", "18t", "Oo", "aC", "0Bq", "bCl", "afn", "2KV", "1nT", "5Uz", "64p", "5n7", "4kw", "0PY", "7c",
"2hJ", "1MH", "4fG", "6Sd", "7mi", "4Hk", "07M", "Pw", "2Ig", "08L", "4Gj", "66A", "7LD", "4iF", "0Rh", "5R", "8b", "1Oy", "4dv", "5a6",
"7oX", "4JZ", "0qt", "RF", "0ov", "LD", "4A9", "4TX", "4zt", "6OW", "bh", "0AZ", "z9", "oX", "6Bg", "43L", "4Yh", "6lK", "At", "0bF",
"0mG", "Nu", "6cJ", "4Vi", "4xE", "6Mf", "2vH", "10", "8GC", "mi", "5p5", "4uu", "5Kx", "4N8", "CE", "1pV", "0QO", "6u", "7Oc", "4ja",
"4DM", "65f", "3Za", "I0", "0rS", "Qa", "68V", "b7F", "4gQ", "468", "dSo", "285", "274", "4D", "499", "4hP", "b8G", "67W", "0h3", "09Z",
"F1", "SP", "7nN", "4KL", "51I", "6PC", "9t", "1No", "21g", "1Pm", "5kC", "6NA", "74D", "4UN", "X3", "MR", "029", "0cP", "bbM", "79t",
"4c3", "42Z", "8Dd", "nN", "aO", "8Ke", "4yS", "4l2", "76u", "635", "0lQ", "Oc", "BS", "W2", "4ZO", "6ol", "7Qa", "40k", "0OM", "2zn",
"69L", "4Hg", "07A", "2Fj", "2hF", "k6", "4fK", "6Sh", "7Ny", "6K9", "0PU", "7o", "2KZ", "1nX", "4EW", "4P6", "7oT", "4JV", "05p", "RJ",
"8n", "1Ou", "4dz", "6QY", "7LH", "4iJ", "d7", "qV", "2Ik", "1li", "4Gf", "66M", "4Yd", "6lG", "Ax", "0bJ", "z5", "oT", "6Bk", "4wH",
"4zx", "aeI", "bd", "0AV", "0oz", "LH", "4A5", "4TT", "5Kt", "4N4", "CI", "14R", "0NW", "me", "541", "41q", "4xI", "6Mj", "22L", "u4",
"0mK", "Ny", "6cF", "4Ve", "4DI", "65b", "2JD", "I4", "0QK", "6q", "7Og", "4je", "4gU", "4r4", "2iX", "1LZ", "0rW", "Qe", "5L9", "4Iy",
"4Fx", "5C8", "0h7", "1mw", "0Sz", "pH", "7MV", "4hT", "4ed", "6PG", "9p", "1Nk", "F5", "ST", "7nJ", "4KH", "7pH", "4UJ", "X7", "MV",
"cz", "1Pi", "5kG", "6NE", "4c7", "4vV", "0Mx", "nJ", "0v5", "0cT", "4Xz", "6mY", "6bX", "5GZ", "0lU", "Og", "aK", "0By", "4yW", "4l6",
"6AD", "40o", "0OI", "2zj", "BW", "W6", "4ZK", "6oh", "2hB", "k2", "4fO", "6Sl", "69H", "4Hc", "07E", "2Fn", "d5e", "83m", "4ES", "4P2",
"a0F", "bQL", "0PQ", "7k", "8j", "1Oq", "50W", "hbv", "7oP", "4JR", "05t", "RN", "2Io", "08D", "4Gb", "66I", "7LL", "4iN", "d3", "5Z",
"z1", "oP", "6Bo", "43D", "5IA", "6lC", "2Wm", "0bN", "8ff", "LL", "4A1", "4TP", "cPn", "aeM", "0T3", "0AR", "0NS", "ma", "545", "41u",
"5Kp", "4N0", "CM", "14V", "0mO", "2Xl", "6cB", "4Va", "4xM", "6Mn", "22H", "18", "04s", "SI", "7nW", "4KU", "4ey", "6PZ", "9m", "1Nv",
"e4", "pU", "7MK", "4hI", "4Fe", "67N", "2Hh", "09C", "06B", "Qx", "68O", "4Id", "4gH", "6Rk", "2iE", "j5", "0QV", "6l", "5o8", "4jx",
"4DT", "4Q5", "2JY", "82j", "BJ", "0ax", "4ZV", "4O7", "552", "40r", "0OT", "lf", "aV", "t7", "4yJ", "6Li", "6bE", "4Wf", "0lH", "Oz",
"2Vj", "0cI", "4Xg", "6mD", "6Ch", "42C", "0Me", "nW", "cg", "1Pt", "5kZ", "6NX", "7pU", "4UW", "0ny", "MK", "7LQ", "4iS", "267", "5G",
"0i0", "08Y", "b9D", "66T", "7oM", "4JO", "G2", "RS", "8w", "1Ol", "4dc", "7Aa", "atS", "4kb", "0PL", "7v", "2KC", "H3", "4EN", "64e",
"69U", "b6E", "07X", "Pb", "dRl", "296", "4fR", "4s3", "4xP", "4m1", "22U", "8Jf", "0mR", "0x3", "77v", "626", "5Km", "6no", "CP", "V1",
"0NN", "3kL", "7Pb", "41h", "4za", "6OB", "20d", "0AO", "Y0", "LQ", "6an", "4TM", "bcN", "78w", "Aa", "0bS", "8Eg", "oM", "4b0", "43Y",
"51T", "azL", "9i", "1Nr", "04w", "SM", "7nS", "4KQ", "4Fa", "67J", "2Hl", "09G", "e0", "4Y", "7MO", "4hM", "4gL", "6Ro", "2iA", "j1",
"06F", "2Gm", "68K", "5YA", "4DP", "4Q1", "d4f", "82n", "0QR", "6h", "a1E", "bPO", "556", "40v", "0OP", "lb", "BN", "15U", "4ZR", "4O3",
"6bA", "4Wb", "0lL", "2Yo", "aR", "t3", "4yN", "6Lm", "6Cl", "42G", "0Ma", "nS", "2Vn", "0cM", "4Xc", "79i", "74Y", "4US", "8ge", "MO",
"cc", "1Pp", "bAL", "adN", "0i4", "1lt", "5WZ", "66P", "7LU", "4iW", "0Ry", "5C", "8s", "1Oh", "4dg", "6QD", "7oI", "4JK", "G6", "RW",
"2KG", "H7", "4EJ", "64a", "7Nd", "4kf", "0PH", "7r", "1X8", "1MY", "4fV", "4s7", "69Q", "4Hz", "0sT", "Pf", "0mV", "Nd", "5S8", "4Vx",
"4xT", "4m5", "22Q", "0Cz", "0NJ", "mx", "7Pf", "41l", "5Ki", "6nk", "CT", "V5", "Y4", "LU", "6aj", "4TI", "4ze", "6OF", "by", "0AK",
"2l9", "oI", "4b4", "4wU", "4Yy", "6lZ", "Ae", "0bW", "0So", "4U", "7MC", "4hA", "4Fm", "67F", "3XA", "09K", "0ps", "SA", "aTl", "b5f",
"4eq", "6PR", "9e", "8WG", "8XF", "6d", "5o0", "4jp", "707", "65w", "1z2", "1oS", "06J", "Qp", "68G", "4Il", "53i", "6Rc", "2iM", "1LO",
"23G", "07", "4yB", "6La", "6bM", "4Wn", "18i", "Or", "BB", "0ap", "c4D", "aEo", "5q2", "40z", "8FD", "ln", "co", "346", "5kR", "6NP",
"74U", "bol", "0nq", "MC", "2Vb", "0cA", "4Xo", "6mL", "7SA", "42K", "0Mm", "2xN", "7oE", "4JG", "05a", "2DJ", "2jf", "1Od", "4dk", "6QH",
"482", "5yz", "0Ru", "5O", "0i8", "08Q", "4Gw", "5B7", "5M6", "4Hv", "07P", "Pj", "1X4", "1MU", "4fZ", "473", "7Nh", "4kj", "0PD", "sv",
"2KK", "1nI", "4EF", "64m", "5Ke", "6ng", "CX", "V9", "0NF", "mt", "7Pj", "4uh", "4xX", "4m9", "1F6", "0Cv", "0mZ", "Nh", "5S4", "4Vt",
"4Yu", "6lV", "Ai", "16r", "0Lw", "oE", "4b8", "43Q", "4zi", "6OJ", "bu", "0AG", "Y8", "LY", "6af", "4TE", "4Fi", "67B", "2Hd", "09O",
"e8", "4Q", "7MG", "4hE", "4eu", "6PV", "9a", "1Nz", "0pw", "SE", "aTh", "4KY", "4DX", "4Q9", "1z6", "1oW", "0QZ", "rh", "5o4", "4jt",
"4gD", "6Rg", "2iI", "j9", "06N", "Qt", "68C", "4Ih", "6bI", "4Wj", "0lD", "Ov", "aZ", "03", "4yF", "6Le", "5q6", "4tv", "0OX", "lj",
"BF", "0at", "4ZZ", "6oy", "74Q", "5Ez", "0nu", "MG", "ck", "1Px", "5kV", "6NT", "6Cd", "42O", "0Mi", "2xJ", "2Vf", "0cE", "4Xk", "6mH",
"2jb", "8VY", "4do", "6QL", "7oA", "4JC", "05e", "2DN", "d7E", "08U", "4Gs", "5B3", "486", "bSl", "0Rq", "5K", "1X0", "1MQ", "52w", "477",
"5M2", "4Hr", "07T", "Pn", "2KO", "1nM", "4EB", "64i", "7Nl", "4kn", "8YX", "7z", "0NB", "mp", "7Pn", "41d", "5Ka", "6nc", "2UM", "14G",
"19w", "Nl", "5S0", "4Vp", "bBo", "agm", "1F2", "0Cr", "0Ls", "oA", "ahl", "43U", "4Yq", "6lR", "Am", "16v", "0oo", "2ZL", "6ab", "4TA",
"4zm", "6ON", "bq", "0AC", "2VY", "0cz", "4XT", "4M5", "570", "42p", "0MV", "nd", "cT", "v5", "5ki", "6Nk", "74n", "4Ud", "0nJ", "Mx",
"By", "0aK", "4Ze", "6oF", "6Aj", "40A", "y4", "lU", "ae", "0BW", "4yy", "581", "4B4", "4WU", "18R", "OI", "06q", "QK", "7lU", "4IW",
"53R", "6RX", "0I4", "1Lt", "g6", "rW", "7OI", "4jK", "4Dg", "65L", "2Jj", "1oh", "0pH", "Sz", "7nd", "4Kf", "4eJ", "6Pi", "2kG", "h7",
"0ST", "4n", "7Mx", "4hz", "4FV", "4S7", "1x8", "09p", "4zR", "4o3", "bN", "8Hd", "0oP", "Lb", "75t", "604", "4YN", "6lm", "AR", "T3",
"0LL", "2yo", "6BA", "43j", "4xc", "agR", "22f", "0CM", "0ma", "NS", "6cl", "4VO", "baL", "aDN", "Cc", "14x", "8Ge", "mO", "7PQ", "4uS",
"7NS", "4kQ", "245", "7E", "0k2", "1nr", "coo", "64V", "69f", "4HM", "E0", "PQ", "2hl", "1Mn", "4fa", "6SB", "7Lb", "5yA", "0RN", "5t",
"2IA", "J1", "4GL", "66g", "aUM", "b4G", "05Z", "0d3", "8D", "8Vf", "4dP", "459", "574", "42t", "0MR", "0X3", "dln", "17W", "4XP", "4M1",
"74j", "5EA", "0nN", "3KL", "cP", "29", "5km", "6No", "6An", "40E", "y0", "lQ", "2Tl", "0aO", "4Za", "6oB", "4B0", "4WQ", "18V", "OM",
"aa", "0BS", "bCN", "585", "53V", "axN", "0I0", "1Lp", "06u", "QO", "68x", "4IS", "4Dc", "65H", "2Jn", "1ol", "g2", "rS", "7OM", "4jO",
"4eN", "6Pm", "9Z", "h3", "04D", "2Eo", "aTS", "4Kb", "4FR", "4S3", "d6d", "09t", "0SP", "4j", "a3G", "bRM", "0oT", "Lf", "6aY", "4Tz",
"4zV", "4o7", "bJ", "0Ax", "0LH", "oz", "6BE", "43n", "4YJ", "6li", "AV", "T7", "0me", "NW", "6ch", "4VK", "4xg", "6MD", "22b", "0CI",
"0Ny", "mK", "7PU", "4uW", "5KZ", "6nX", "Cg", "1pt", "0k6", "1nv", "4Ey", "64R", "7NW", "4kU", "241", "7A", "2hh", "1Mj", "4fe", "6SF",
"69b", "4HI", "E4", "PU", "2IE", "J5", "4GH", "66c", "7Lf", "4id", "0RJ", "5p", "2jY", "8Vb", "4dT", "4q5", "5O8", "4Jx", "0qV", "Rd",
"21E", "25", "5ka", "6Nc", "74f", "4Ul", "0nB", "Mp", "1f2", "0cr", "bbo", "79V", "578", "42x", "395", "nl", "am", "364", "4yq", "589",
"76W", "bmn", "0ls", "OA", "Bq", "0aC", "4Zm", "6oN", "6Ab", "40I", "0Oo", "2zL", "0Qm", "6W", "7OA", "4jC", "4Do", "65D", "2Jb", "82Q",
"06y", "QC", "68t", "b7d", "4gs", "5b3", "dSM", "8UE", "8ZD", "4f", "5m2", "4hr", "725", "67u", "1x0", "09x", "04H", "Sr", "7nl", "4Kn",
"4eB", "6Pa", "9V", "1NM", "4YF", "6le", "AZ", "0bh", "0LD", "ov", "6BI", "43b", "4zZ", "6Oy", "bF", "0At", "0oX", "Lj", "5Q6", "4Tv",
"5KV", "6nT", "Ck", "14p", "0Nu", "mG", "7PY", "41S", "4xk", "6MH", "22n", "0CE", "0mi", "2XJ", "6cd", "4VG", "69n", "4HE", "E8", "PY",
"2hd", "1Mf", "4fi", "6SJ", "ath", "4kY", "0Pw", "7M", "2Kx", "1nz", "4Eu", "6pV", "5O4", "4Jt", "05R", "Rh", "8L", "1OW", "4dX", "451",
"7Lj", "4ih", "0RF", "qt", "2II", "J9", "4GD", "66o", "74b", "4Uh", "0nF", "Mt", "cX", "21", "5ke", "6Ng", "5s4", "4vt", "0MZ", "nh",
"1f6", "0cv", "4XX", "4M9", "4B8", "4WY", "0lw", "OE", "ai", "1Rz", "4yu", "6LV", "6Af", "40M", "y8", "lY", "Bu", "0aG", "4Zi", "6oJ",
"4Dk", "6qH", "2Jf", "1od", "0Qi", "6S", "7OE", "4jG", "4gw", "5b7", "0I8", "1Lx", "0ru", "QG", "68p", "5Yz", "4FZ", "67q", "1x4", "1mU",
"0SX", "4b", "5m6", "4hv", "4eF", "6Pe", "9R", "1NI", "04L", "Sv", "7nh", "4Kj", "8EX", "or", "6BM", "43f", "4YB", "6la", "2WO", "0bl",
"8fD", "Ln", "5Q2", "4Tr", "cPL", "aeo", "bB", "0Ap", "0Nq", "mC", "ajn", "41W", "5KR", "6nP", "Co", "14t", "0mm", "2XN", "77I", "4VC",
"4xo", "6ML", "22j", "0CA", "3xA", "1Mb", "4fm", "6SN", "69j", "4HA", "07g", "2FL", "d5G", "83O", "4Eq", "64Z", "a0d", "bQn", "0Ps", "7I",
"8H", "1OS", "50u", "455", "5O0", "4Jp", "05V", "Rl", "2IM", "08f", "5Wa", "66k", "7Ln", "4il", "0RB", "5x", "Bh", "0aZ", "4Zt", "6oW",
"4a9", "40P", "0Ov", "lD", "at", "0BF", "4yh", "6LK", "6bg", "4WD", "Z9", "OX", "2VH", "U8", "4XE", "6mf", "6CJ", "42a", "0MG", "nu",
"cE", "1PV", "5kx", "4n8", "5P5", "4Uu", "8gC", "Mi", "04Q", "Sk", "5N7", "4Kw", "51r", "442", "9O", "1NT", "0SE", "pw", "7Mi", "4hk",
"4FG", "67l", "2HJ", "09a", "3", "QZ", "68m", "4IF", "4gj", "6RI", "2ig", "1Le", "0Qt", "6N", "7OX", "4jZ", "4Dv", "5A6", "0j9", "1oy",
"4xr", "6MQ", "22w", "377", "0mp", "NB", "77T", "blm", "5KO", "6nM", "Cr", "14i", "0Nl", "3kn", "ajs", "41J", "4zC", "aer", "20F", "36",
"0oA", "Ls", "6aL", "4To", "bcl", "78U", "AC", "0bq", "386", "oo", "5r3", "4ws", "5l1", "4iq", "9Kf", "5e", "1y3", "1lR", "736", "66v",
"7oo", "4Jm", "05K", "Rq", "8U", "1ON", "4dA", "6Qb", "7NB", "bQs", "0Pn", "7T", "2Ka", "1nc", "4El", "64G", "69w", "b6g", "07z", "1v2",
"dRN", "8TF", "4fp", "5c0", "akm", "40T", "0Or", "1J2", "Bl", "15w", "4Zp", "6oS", "6bc", "5Ga", "0ln", "2YM", "ap", "0BB", "4yl", "6LO",
"6CN", "42e", "0MC", "nq", "2VL", "0co", "4XA", "6mb", "5P1", "4Uq", "8gG", "Mm", "cA", "1PR", "bAn", "adl", "51v", "446", "9K", "1NP",
"04U", "So", "5N3", "4Ks", "4FC", "67h", "2HN", "09e", "0SA", "ps", "7Mm", "4ho", "4gn", "6RM", "2ic", "1La", "7", "2GO", "68i", "4IB",
"4Dr", "5A2", "d4D", "82L", "0Qp", "6J", "a1g", "bPm", "0mt", "NF", "6cy", "4VZ", "4xv", "6MU", "0V9", "0CX", "0Nh", "mZ", "7PD", "41N",
"5KK", "6nI", "Cv", "14m", "0oE", "Lw", "6aH", "4Tk", "4zG", "6Od", "20B", "32", "0LY", "ok", "5r7", "4ww", "5Iz", "6lx", "AG", "0bu",
"1y7", "1lV", "4GY", "4R8", "5l5", "4iu", "1Bz", "5a", "8Q", "i8", "4dE", "6Qf", "7ok", "4Ji", "05O", "Ru", "2Ke", "1ng", "4Eh", "64C",
"7NF", "4kD", "f9", "7P", "2hy", "3m9", "4ft", "5c4", "69s", "4HX", "0sv", "PD", "23e", "0BN", "5iA", "6LC", "6bo", "4WL", "Z1", "OP",
"0t3", "0aR", "c4f", "aEM", "4a1", "40X", "8Ff", "lL", "cM", "8Ig", "5kp", "4n0", "74w", "617", "0nS", "Ma", "3Fa", "U0", "4XM", "6mn",
"6CB", "42i", "0MO", "2xl", "0SM", "4w", "7Ma", "4hc", "4FO", "67d", "2HB", "K2", "04Y", "Sc", "aTN", "b5D", "4eS", "4p2", "9G", "8We",
"256", "6F", "7OP", "4jR", "cnl", "65U", "0j1", "1oq", "D3", "QR", "68e", "4IN", "4gb", "6RA", "2io", "1Lm", "5KG", "6nE", "Cz", "14a",
"x7", "mV", "7PH", "41B", "4xz", "592", "0V5", "0CT", "0mx", "NJ", "4C7", "4VV", "4YW", "4L6", "AK", "0by", "0LU", "og", "563", "43s",
"4zK", "6Oh", "bW", "w6", "0oI", "2Zj", "6aD", "4Tg", "7og", "4Je", "05C", "Ry", "2jD", "i4", "4dI", "6Qj", "5l9", "4iy", "0RW", "5m",
"2IX", "08s", "4GU", "4R4", "7mV", "4HT", "07r", "PH", "0H7", "1Mw", "4fx", "5c8", "7NJ", "4kH", "f5", "sT", "2Ki", "1nk", "4Ed", "64O",
"6bk", "4WH", "Z5", "OT", "ax", "0BJ", "4yd", "6LG", "4a5", "4tT", "0Oz", "lH", "Bd", "0aV", "4Zx", "aEI", "5P9", "4Uy", "0nW", "Me",
"cI", "1PZ", "5kt", "4n4", "6CF", "42m", "0MK", "ny", "2VD", "U4", "4XI", "6mj", "4FK", "6sh", "2HF", "K6", "0SI", "4s", "7Me", "4hg",
"4eW", "4p6", "9C", "1NX", "0pU", "Sg", "7ny", "6k9", "4Dz", "65Q", "0j5", "1ou", "0Qx", "6B", "7OT", "4jV", "4gf", "6RE", "2ik", "1Li",
"D7", "QV", "68a", "4IJ", "x3", "mR", "7PL", "41F", "5KC", "6nA", "2Uo", "14e", "19U", "NN", "4C3", "4VR", "bBM", "596", "0V1", "0CP",
"0LQ", "oc", "567", "43w", "4YS", "4L2", "AO", "16T", "0oM", "2Zn", "75i", "4Tc", "4zO", "6Ol", "bS", "w2", "8Y", "i0", "4dM", "6Qn",
"7oc", "4Ja", "05G", "2Dl", "d7g", "08w", "4GQ", "4R0", "a2D", "bSN", "0RS", "5i", "0H3", "1Ms", "52U", "ayM", "7mR", "4HP", "07v", "PL",
"2Km", "1no", "5UA", "64K", "7NN", "4kL", "f1", "7X", "5nw", "4k7", "fJ", "0Ex", "0kT", "Hf", "6eY", "4Pz", "5Mk", "6hi", "EV", "P7",
"0HH", "kz", "6FE", "47n", "48o", "6ID", "26b", "0GI", "0ie", "JW", "6gh", "4RK", "5OZ", "6jX", "Gg", "0dU", "0Jy", "iK", "4d6", "4qW",
"4z4", "4oU", "1DZ", "3A", "Ye", "0zW", "4Ay", "5D9", "6yj", "4LI", "A4", "TU", "zy", "0YK", "4be", "6WF", "6XG", "4md", "0VJ", "1p",
"2ME", "N5", "4CH", "62c", "5K8", "4Nx", "0uV", "Vd", "xH", "8Rb", "5pu", "4u5", "D", "13W", "5Lq", "4I1", "534", "46t", "0IR", "28y",
"gP", "69", "5om", "6Jo", "6dC", "5AA", "0jN", "3OL", "2Pl", "0eO", "aT1", "6kB", "6En", "44E", "98", "hQ", "ea", "0FS", "49u", "abL",
"4F0", "4SQ", "8ag", "KM", "02u", "UO", "4X2", "4MS", "57V", "a8F", "0M0", "0XQ", "c2", "vS", "7KM", "4nO", "5PB", "61H", "2Nn", "1kl",
"00D", "2Ao", "6zA", "4Ob", "4aN", "6Tm", "yR", "l3", "0WP", "0j", "a7G", "58W", "4BR", "4W3", "ZN", "84l", "0kP", "Hb", "71t", "644",
"5ns", "4k3", "fN", "8Ld", "0HL", "29g", "6FA", "47j", "5Mo", "6hm", "ER", "P3", "0ia", "JS", "6gl", "4RO", "48k", "7Ya", "26f", "0GM",
"8Ce", "iO", "4d2", "4qS", "beL", "hYw", "Gc", "0dQ", "Ya", "0zS", "cko", "60V", "4z0", "4oQ", "205", "3E", "2ll", "0YO", "4ba", "6WB",
"6yn", "4LM", "A0", "TQ", "2MA", "N1", "4CL", "62g", "6XC", "59I", "0VN", "1t", "xL", "8Rf", "54y", "419", "aQM", "b0G", "01Z", "3PP",
"530", "46p", "0IV", "jd", "DH", "0gz", "5Lu", "4I5", "6dG", "4Qd", "0jJ", "Ix", "gT", "r5", "5oi", "6Jk", "6Ej", "44A", "0Kg", "hU",
"Fy", "0eK", "5ND", "6kF", "4F4", "4SU", "1xZ", "KI", "ee", "0FW", "49q", "5x9", "57R", "6VX", "0M4", "0XU", "02q", "UK", "4X6", "4MW",
"5PF", "61L", "2Nj", "1kh", "c6", "vW", "7KI", "4nK", "4aJ", "6Ti", "yV", "l7", "0tH", "Wz", "6zE", "4Of", "4BV", "4W7", "ZJ", "0yx",
"0WT", "0n", "6YY", "4lz", "5Mc", "6ha", "2SO", "0fl", "1Xa", "kr", "6FM", "47f", "bDm", "aao", "fB", "0Ep", "8bD", "Hn", "5U2", "4Pr",
"5OR", "5Z3", "Go", "10t", "0Jq", "iC", "ann", "45W", "48g", "6IL", "ds", "0GA", "0im", "3Lo", "73I", "4RC", "6yb", "4LA", "03g", "2BL",
"zq", "0YC", "4bm", "6WN", "a4d", "bUn", "0Ts", "3I", "Ym", "87O", "4Aq", "5D1", "5K0", "4Np", "01V", "Vl", "2nQ", "1KS", "54u", "415",
"6XO", "4ml", "0VB", "1x", "2MM", "0xn", "5Sa", "62k", "gX", "61", "5oe", "6Jg", "6dK", "4Qh", "0jF", "It", "L", "0gv", "5Ly", "4I9",
"5w4", "4rt", "0IZ", "jh", "ei", "1Vz", "5mT", "5x5", "4F8", "4SY", "0hw", "KE", "Fu", "0eG", "5NH", "6kJ", "6Ef", "44M", "90", "hY",
"0Ui", "2S", "7KE", "4nG", "5PJ", "6uH", "Xw", "1kd", "0vu", "UG", "6xx", "790", "4cw", "5f7", "0M8", "0XY", "0WX", "0b", "5i6", "4lv",
"4BZ", "63q", "ZF", "0yt", "00L", "Wv", "6zI", "4Oj", "4aF", "6Te", "yZ", "0Zh", "0HD", "kv", "6FI", "47b", "5Mg", "6he", "EZ", "0fh",
"0kX", "Hj", "5U6", "4Pv", "7N9", "6Ky", "fF", "0Et", "0Ju", "iG", "6Dx", "45S", "5OV", "5Z7", "Gk", "0dY", "0ii", "3Lk", "6gd", "4RG",
"48c", "6IH", "dw", "0GE", "zu", "0YG", "4bi", "6WJ", "6yf", "4LE", "A8", "TY", "Yi", "1jz", "4Au", "5D5", "4z8", "4oY", "0Tw", "3M",
"xD", "1KW", "54q", "411", "5K4", "4Nt", "01R", "Vh", "2MI", "N9", "4CD", "62o", "6XK", "4mh", "0VF", "ut", "6dO", "4Ql", "0jB", "Ip",
"25E", "65", "5oa", "6Jc", "538", "46x", "9Pg", "jl", "H", "0gr", "bfo", "aCm", "72W", "bin", "0hs", "KA", "em", "324", "49y", "5x1",
"6Eb", "44I", "94", "3nm", "Fq", "0eC", "5NL", "6kN", "5PN", "61D", "Xs", "86Q", "0Um", "2W", "7KA", "4nC", "4cs", "5f3", "39W", "8QE",
"02y", "UC", "aRn", "794", "765", "63u", "ZB", "0yp", "9Ne", "0f", "5i2", "4lr", "4aB", "6Ta", "2oO", "0Zl", "00H", "Wr", "6zM", "4On",
"5lW", "5y6", "dj", "0GX", "0it", "JF", "6gy", "4RZ", "5OK", "6jI", "Gv", "0dD", "83", "iZ", "6De", "45N", "5nf", "6Kd", "24B", "72",
"0kE", "Hw", "6eH", "4Pk", "5Mz", "6hx", "EG", "0fu", "0HY", "kk", "5v7", "4sw", "5h5", "4mu", "1Fz", "1a", "2MT", "0xw", "4CY", "4V8",
"7kk", "4Ni", "01O", "Vu", "xY", "m8", "54l", "6Uf", "6Zg", "4oD", "b9", "3P", "Yt", "0zF", "4Ah", "60C", "4Y9", "4LX", "0wv", "TD",
"zh", "0YZ", "4bt", "5g4", "Fl", "11w", "5NQ", "6kS", "aom", "44T", "0Kr", "1N2", "ep", "0FB", "49d", "6HO", "6fc", "5Ca", "0hn", "3Ml",
"U", "0go", "bfr", "6ib", "6GN", "46e", "0IC", "jq", "gA", "0Ds", "bEn", "hyU", "5T1", "4Qq", "8cG", "Im", "00U", "Wo", "5J3", "4Os",
"55v", "406", "yC", "0Zq", "0WA", "ts", "6YL", "4lo", "4BC", "63h", "2LN", "0ym", "02d", "2CO", "6xa", "4MB", "4cn", "6VM", "2mc", "1Ha",
"0Up", "2J", "a5g", "bTm", "5PS", "5E2", "Xn", "86L", "0ip", "JB", "73T", "bhm", "48z", "5y2", "dn", "337", "87", "3on", "6Da", "45J",
"5OO", "6jM", "Gr", "10i", "0kA", "Hs", "6eL", "4Po", "5nb", "aar", "24F", "76", "8AE", "ko", "5v3", "4ss", "bgl", "aBn", "EC", "0fq",
"2MP", "0xs", "776", "62v", "5h1", "4mq", "9Of", "1e", "2nL", "1KN", "54h", "6Ub", "7ko", "4Nm", "01K", "Vq", "Yp", "0zB", "4Al", "60G",
"6Zc", "bUs", "0Tn", "3T", "zl", "8PF", "4bp", "5g0", "aSm", "787", "03z", "1r2", "4e9", "44P", "0Kv", "hD", "Fh", "0eZ", "5NU", "6kW",
"6fg", "4SD", "0hj", "KX", "et", "0FF", "5mI", "6HK", "6GJ", "46a", "0IG", "ju", "Q", "Q8", "5Ld", "6if", "5T5", "4Qu", "1zz", "Ii",
"gE", "0Dw", "5ox", "4j8", "55r", "402", "yG", "0Zu", "00Q", "Wk", "5J7", "4Ow", "4BG", "63l", "2LJ", "0yi", "0WE", "tw", "6YH", "4lk",
"4cj", "6VI", "2mg", "0XD", "0vh", "UZ", "6xe", "4MF", "5PW", "5E6", "Xj", "1ky", "0Ut", "2N", "7KX", "4nZ", "5OC", "6jA", "2Qo", "0dL",
"1ZA", "iR", "6Dm", "45F", "48v", "acO", "db", "0GP", "94M", "JN", "4G3", "4RR", "5Mr", "4H2", "EO", "12T", "0HQ", "kc", "527", "47w",
"5nn", "6Kl", "fS", "s2", "0kM", "3NO", "71i", "4Pc", "7kc", "4Na", "01G", "3PM", "xQ", "m0", "54d", "6Un", "a6D", "59T", "0VS", "1i",
"197", "85o", "4CQ", "4V0", "4Y1", "4LP", "03v", "TL", "0L3", "0YR", "56U", "a9E", "6Zo", "4oL", "b1", "3X", "2Om", "0zN", "5QA", "60K",
"ex", "0FJ", "49l", "6HG", "6fk", "4SH", "0hf", "KT", "Fd", "0eV", "5NY", "aAI", "4e5", "4pT", "0Kz", "hH", "gI", "1TZ", "5ot", "4j4",
"5T9", "4Qy", "0jW", "Ie", "DU", "Q4", "5Lh", "6ij", "6GF", "46m", "0IK", "jy", "0WI", "0s", "6YD", "4lg", "4BK", "6wh", "ZW", "O6",
"0tU", "Wg", "6zX", "6o9", "4aW", "4t6", "yK", "0Zy", "0Ux", "2B", "7KT", "4nV", "bzI", "61Q", "Xf", "1ku", "02l", "UV", "6xi", "4MJ",
"4cf", "6VE", "2mk", "0XH", "0Jd", "iV", "6Di", "45B", "5OG", "6jE", "Gz", "0dH", "0ix", "JJ", "4G7", "4RV", "48r", "6IY", "df", "0GT",
"0HU", "kg", "523", "47s", "5Mv", "4H6", "EK", "0fy", "0kI", "3NK", "6eD", "4Pg", "5nj", "6Kh", "fW", "s6", "xU", "m4", "5ph", "6Uj",
"7kg", "4Ne", "01C", "Vy", "193", "1hZ", "4CU", "4V4", "5h9", "4my", "0VW", "1m", "zd", "0YV", "4bx", "5g8", "4Y5", "4LT", "03r", "TH",
"Yx", "0zJ", "4Ad", "60O", "6Zk", "4oH", "b5", "wT", "6fo", "4SL", "0hb", "KP", "27e", "0FN", "49h", "6HC", "4e1", "44X", "8Bf", "hL",
"0p3", "0eR", "bdO", "aAM", "70w", "657", "0jS", "Ia", "gM", "8Mg", "5op", "4j0", "6GB", "46i", "0IO", "28d", "Y", "Q0", "5Ll", "6in",
"4BO", "63d", "ZS", "O2", "0WM", "0w", "7Ia", "4lc", "4aS", "4t2", "yO", "8Se", "00Y", "Wc", "aPN", "b1D", "bzM", "61U", "Xb", "1kq",
"216", "2F", "7KP", "4nR", "4cb", "6VA", "2mo", "0XL", "02h", "UR", "6xm", "4MN", "5j7", "4ow", "0TY", "3c", "YG", "0zu", "5Qz", "60p",
"6yH", "4Lk", "03M", "Tw", "2lJ", "0Yi", "4bG", "6Wd", "6Xe", "4mF", "0Vh", "1R", "2Mg", "0xD", "4Cj", "62A", "7kX", "4NZ", "0ut", "VF",
"xj", "1Ky", "5pW", "5e6", "5nU", "6KW", "fh", "0EZ", "0kv", "HD", "4E9", "4PX", "5MI", "6hK", "Et", "0fF", "0Hj", "kX", "6Fg", "47L",
"48M", "6If", "dY", "50", "0iG", "Ju", "6gJ", "4Ri", "5Ox", "4J8", "GE", "0dw", "1Zz", "ii", "5t5", "4qu", "02W", "Um", "5H1", "4Mq",
"57t", "424", "2mP", "0Xs", "0UC", "2y", "7Ko", "4nm", "bzr", "61j", "2NL", "1kN", "00f", "2AM", "6zc", "bus", "4al", "6TO", "yp", "0ZB",
"0Wr", "0H", "a7e", "58u", "4Bp", "5G0", "Zl", "84N", "f", "13u", "5LS", "5Y2", "amo", "46V", "0Ip", "jB", "gr", "1Ta", "5oO", "6JM",
"6da", "4QB", "0jl", "3On", "2PN", "0em", "5Nb", "aAr", "6EL", "44g", "0KA", "hs", "eC", "0Fq", "49W", "abn", "5V3", "4Ss", "8aE", "Ko",
"YC", "0zq", "754", "60t", "5j3", "4os", "9Md", "3g", "2lN", "0Ym", "4bC", "7GA", "6yL", "4Lo", "03I", "Ts", "2Mc", "1ha", "4Cn", "62E",
"6Xa", "4mB", "0Vl", "1V", "xn", "8RD", "5pS", "5e2", "aQo", "b0e", "01x", "VB", "0kr", "1n2", "71V", "bjo", "5nQ", "6KS", "fl", "315",
"0Hn", "29E", "6Fc", "47H", "5MM", "6hO", "Ep", "0fB", "0iC", "Jq", "6gN", "4Rm", "48I", "6Ib", "26D", "54", "8CG", "im", "509", "45y",
"ben", "hYU", "GA", "0ds", "4cY", "420", "2mT", "0Xw", "02S", "Ui", "5H5", "4Mu", "5Pd", "61n", "XY", "M8", "0UG", "vu", "7Kk", "4ni",
"4ah", "6TK", "yt", "0ZF", "B9", "WX", "6zg", "4OD", "4Bt", "5G4", "Zh", "0yZ", "0Wv", "0L", "4y9", "4lX", "6Gy", "46R", "0It", "jF",
"b", "0gX", "5LW", "5Y6", "6de", "4QF", "0jh", "IZ", "gv", "0DD", "5oK", "6JI", "6EH", "44c", "0KE", "hw", "2PJ", "0ei", "5Nf", "6kd",
"5V7", "4Sw", "0hY", "Kk", "eG", "0Fu", "49S", "6Hx", "7ia", "4Lc", "03E", "2Bn", "zS", "o2", "4bO", "6Wl", "a4F", "bUL", "0TQ", "3k",
"YO", "87m", "4AS", "4T2", "7kP", "4NR", "01t", "VN", "xb", "1Kq", "54W", "hfv", "6Xm", "4mN", "1FA", "1Z", "2Mo", "0xL", "4Cb", "62I",
"5MA", "6hC", "2Sm", "0fN", "0Hb", "kP", "6Fo", "47D", "bDO", "aaM", "0P3", "0ER", "8bf", "HL", "4E1", "4PP", "5Op", "4J0", "GM", "10V",
"0JS", "ia", "505", "45u", "48E", "6In", "dQ", "58", "0iO", "3LM", "6gB", "4Ra", "0UK", "2q", "7Kg", "4ne", "5Ph", "61b", "XU", "M4",
"0vW", "Ue", "5H9", "4My", "4cU", "4v4", "2mX", "1HZ", "0Wz", "tH", "4y5", "4lT", "4Bx", "5G8", "Zd", "0yV", "B5", "WT", "6zk", "4OH",
"4ad", "6TG", "yx", "0ZJ", "gz", "0DH", "5oG", "6JE", "6di", "4QJ", "0jd", "IV", "n", "0gT", "680", "6iY", "4g7", "4rV", "0Ix", "jJ",
"eK", "0Fy", "5mv", "4h6", "6fX", "5CZ", "0hU", "Kg", "FW", "S6", "5Nj", "6kh", "6ED", "44o", "0KI", "3nK", "zW", "o6", "4bK", "6Wh",
"6yD", "4Lg", "03A", "2Bj", "YK", "0zy", "4AW", "4T6", "6ZX", "6O9", "0TU", "3o", "xf", "1Ku", "54S", "6UY", "7kT", "4NV", "01p", "VJ",
"2Mk", "0xH", "4Cf", "62M", "6Xi", "4mJ", "0Vd", "uV", "0Hf", "kT", "6Fk", "4sH", "5ME", "6hG", "Ex", "0fJ", "0kz", "HH", "4E5", "4PT",
"5nY", "aaI", "fd", "0EV", "0JW", "ie", "501", "45q", "5Ot", "4J4", "GI", "10R", "0iK", "Jy", "6gF", "4Re", "48A", "6Ij", "dU", "q4",
"5Pl", "61f", "XQ", "M0", "0UO", "2u", "7Kc", "4na", "4cQ", "428", "39u", "8Qg", "0vS", "Ua", "aRL", "b3F", "bxO", "63W", "0l3", "0yR",
"234", "0D", "4y1", "4lP", "55I", "6TC", "2om", "0ZN", "B1", "WP", "6zo", "4OL", "6dm", "4QN", "1zA", "IR", "25g", "0DL", "5oC", "6JA",
"4g3", "46Z", "9PE", "jN", "j", "0gP", "684", "aCO", "72u", "675", "0hQ", "Kc", "eO", "8Oe", "5mr", "4h2", "7Ua", "44k", "0KM", "3nO",
"FS", "S2", "5Nn", "6kl", "4x6", "4mW", "0Vy", "1C", "0m4", "0xU", "5SZ", "62P", "7kI", "4NK", "C6", "VW", "2nj", "1Kh", "54N", "6UD",
"6ZE", "4of", "0TH", "3r", "YV", "L7", "4AJ", "60a", "6yY", "4Lz", "0wT", "Tf", "zJ", "0Yx", "4bV", "4w7", "5lu", "4i5", "dH", "0Gz",
"0iV", "Jd", "5W8", "4Rx", "5Oi", "6jk", "GT", "R5", "0JJ", "ix", "6DG", "45l", "5nD", "6KF", "fy", "0EK", "0kg", "HU", "6ej", "4PI",
"5MX", "5X9", "Ee", "0fW", "1XZ", "kI", "4f4", "4sU", "00w", "WM", "4Z0", "4OQ", "55T", "hgu", "ya", "0ZS", "a0", "0Y", "6Yn", "4lM",
"4Ba", "63J", "2Ll", "0yO", "02F", "2Cm", "6xC", "aG0", "4cL", "6Vo", "2mA", "n1", "0UR", "2h", "a5E", "bTO", "5Pq", "4U1", "XL", "86n",
"FN", "11U", "5Nsextern", "4K3", "516", "44v", "0KP", "hb", "eR", "p3", "49F", "6Hm", "6fA", "4Sb", "0hL", "3MN", "w", "0gM", "5LB", "7ya",
"6Gl", "46G", "0Ia", "jS", "gc", "0DQ", "bEL", "hyw", "4D2", "4QS", "8ce", "IO", "0m0", "0xQ", "byL", "62T", "4x2", "4mS", "227", "1G",
"2nn", "1Kl", "54J", "7Ea", "7kM", "4NO", "C2", "VS", "YR", "L3", "4AN", "60e", "6ZA", "4ob", "0TL", "3v", "zN", "8Pd", "4bR", "4w3",
"aSO", "b2E", "03X", "Tb", "0iR", "3LP", "73v", "666", "48X", "4i1", "dL", "8Nf", "0JN", "3oL", "6DC", "45h", "5Om", "6jo", "GP", "R1",
"0kc", "HQ", "6en", "4PM", "a09", "6KB", "24d", "0EO", "8Ag", "kM", "4f0", "47Y", "697", "aBL", "Ea", "0fS", "4ay", "5d9", "ye", "0ZW",
"00s", "WI", "4Z4", "4OU", "4Be", "63N", "Zy", "0yK", "a4", "tU", "6Yj", "4lI", "4cH", "6Vk", "2mE", "n5", "02B", "Ux", "6xG", "4Md",
"5Pu", "4U5", "XH", "86j", "0UV", "2l", "5k8", "4nx", "512", "44r", "0KT", "hf", "FJ", "0ex", "5Nw", "4K7", "6fE", "4Sf", "0hH", "Kz",
"eV", "p7", "49B", "6Hi", "6Gh", "46C", "0Ie", "jW", "s", "0gI", "5LF", "6iD", "4D6", "4QW", "0jy", "IK", "gg", "0DU", "5oZ", "6JX",
"7kA", "4NC", "01e", "3Po", "xs", "8RY", "54F", "6UL", "a6f", "59v", "0Vq", "1K", "d3E", "85M", "4Cs", "5F3", "5I2", "4Lr", "03T", "Tn",
"zB", "0Yp", "56w", "437", "6ZM", "4on", "1Da", "3z", "2OO", "0zl", "4AB", "60i", "5Oa", "6jc", "2QM", "0dn", "0JB", "ip", "6DO", "45d",
"48T", "acm", "1B2", "0Gr", "94o", "Jl", "5W0", "4Rp", "5MP", "5X1", "Em", "12v", "0Hs", "kA", "all", "47U", "5nL", "6KN", "fq", "0EC",
"0ko", "3Nm", "6eb", "4PA", "a8", "0Q", "6Yf", "4lE", "4Bi", "63B", "Zu", "0yG", "0tw", "WE", "4Z8", "4OY", "4au", "5d5", "yi", "1Jz",
"0UZ", "vh", "5k4", "4nt", "5Py", "4U9", "XD", "1kW", "02N", "Ut", "6xK", "4Mh", "4cD", "6Vg", "2mI", "n9", "eZ", "43", "49N", "6He",
"6fI", "4Sj", "0hD", "Kv", "FF", "0et", "7n9", "6ky", "5u6", "4pv", "0KX", "hj", "gk", "0DY", "5oV", "5z7", "6dx", "5Az", "0ju", "IG",
"Dw", "0gE", "5LJ", "6iH", "6Gd", "46O", "0Ii", "28B", "xw", "1Kd", "54B", "6UH", "7kE", "4NG", "01a", "3Pk", "0m8", "0xY", "4Cw", "5F7",
"6Xx", "59r", "0Vu", "1O", "zF", "0Yt", "4bZ", "433", "5I6", "4Lv", "03P", "Tj", "YZ", "0zh", "4AF", "60m", "6ZI", "4oj", "0TD", "wv",
"0JF", "it", "6DK", "4qh", "5Oe", "6jg", "GX", "R9", "0iZ", "Jh", "5W4", "4Rt", "48P", "4i9", "dD", "0Gv", "0Hw", "kE", "4f8", "47Q",
"5MT", "5X5", "Ei", "12r", "0kk", "HY", "6ef", "4PE", "5nH", "6KJ", "fu", "0EG", "4Bm", "63F", "Zq", "0yC", "0Wo", "0U", "6Yb", "4lA",
"4aq", "5d1", "ym", "8SG", "0ts", "WA", "aPl", "b1f", "747", "61w", "2NQ", "1kS", "9Lg", "2d", "5k0", "4np", "57i", "6Vc", "2mM", "0Xn",
"02J", "Up", "6xO", "4Ml", "6fM", "4Sn", "1xa", "Kr", "27G", "47", "49J", "6Ha", "5u2", "44z", "8BD", "hn", "FB", "0ep", "bdm", "aAo",
"70U", "bkl", "0jq", "IC", "go", "306", "5oR", "5z3", "7WA", "46K", "0Im", "28F", "Ds", "0gA", "5LN", "6iL", "0cY", "020", "6mT", "4Xw",
"42S", "6Cx", "nG", "0Mu", "1Pd", "cw", "6NH", "5kJ", "4UG", "74M", "3Kk", "0ni", "0ah", "BZ", "6oe", "4ZF", "40b", "6AI", "lv", "0OD",
"0Bt", "aF", "6Ly", "4yZ", "4Wv", "5R6", "Oj", "0lX", "Qh", "06R", "4It", "5L4", "461", "4gX", "1LW", "1Y6", "rt", "0QF", "4jh", "7Oj",
"65o", "4DD", "I9", "2JI", "SY", "F8", "4KE", "7nG", "6PJ", "4ei", "1Nf", "2kd", "4M", "0Sw", "4hY", "490", "5C5", "4Fu", "09S", "2Hx",
"6OR", "4zq", "354", "bm", "LA", "0os", "bnn", "75W", "6lN", "4Ym", "0bC", "Aq", "2yL", "0Lo", "43I", "6Bb", "6Mc", "5ha", "15", "22E",
"Np", "0mB", "4Vl", "6cO", "aDm", "bao", "1pS", "1e2", "ml", "8GF", "41x", "548", "4kr", "5n2", "7f", "8YD", "1nQ", "2KS", "64u", "715",
"4Hn", "69E", "Pr", "07H", "1MM", "2hO", "6Sa", "4fB", "4iC", "7LA", "5W", "0Rm", "08I", "2Ib", "66D", "4Go", "b4d", "aUn", "RC", "05y",
"8VE", "8g", "5a3", "4ds", "42W", "ain", "nC", "0Mq", "17t", "024", "6mP", "4Xs", "4UC", "74I", "3Ko", "0nm", "8IY", "cs", "6NL", "5kN",
"40f", "6AM", "lr", "8FX", "0al", "2TO", "6oa", "4ZB", "4Wr", "5R2", "On", "18u", "0Bp", "aB", "afo", "bCm", "465", "53u", "1LS", "1Y2",
"Ql", "06V", "4Ip", "5L0", "65k", "5Ta", "1oO", "2JM", "6x", "0QB", "4jl", "7On", "6PN", "4em", "1Nb", "9y", "2EL", "04g", "4KA", "7nC",
"5C1", "4Fq", "09W", "d6G", "4I", "0Ss", "bRn", "494", "LE", "0ow", "4TY", "4A8", "6OV", "4zu", "1Qz", "bi", "oY", "z8", "43M", "6Bf",
"6lJ", "4Yi", "0bG", "Au", "Nt", "0mF", "4Vh", "6cK", "6Mg", "4xD", "11", "22A", "mh", "0NZ", "4ut", "5p4", "4N9", "5Ky", "1pW", "CD",
"1nU", "2KW", "64q", "4EZ", "4kv", "5n6", "7b", "0PX", "1MI", "2hK", "6Se", "4fF", "4Hj", "69A", "Pv", "07L", "08M", "2If", "6rH", "4Gk",
"4iG", "7LE", "5S", "0Ri", "1Ox", "8c", "5a7", "4dw", "5Zz", "7oY", "RG", "0qu", "1Pl", "21f", "adR", "5kB", "4UO", "74E", "MS", "X2",
"0cQ", "028", "79u", "bbL", "4vS", "4c2", "nO", "8De", "8Kd", "aN", "4l3", "4yR", "634", "76t", "Ob", "0lP", "W3", "BR", "6om", "4ZN",
"40j", "6AA", "2zo", "0OL", "6t", "0QN", "5zA", "7Ob", "65g", "4DL", "I1", "2JA", "0g3", "06Z", "b7G", "68W", "469", "4gP", "284", "dSn",
"4E", "275", "4hQ", "498", "67V", "b8F", "1mr", "0h2", "SQ", "F0", "4KM", "7nO", "6PB", "4ea", "1Nn", "9u", "6lF", "4Ye", "0bK", "Ay",
"oU", "z4", "43A", "6Bj", "6OZ", "4zy", "0AW", "be", "LI", "2O9", "4TU", "4A4", "4N5", "5Ku", "14S", "CH", "md", "0NV", "41p", "540",
"6Mk", "4xH", "u5", "22M", "Nx", "0mJ", "4Vd", "6cG", "4Hf", "69M", "Pz", "0sH", "k7", "2hG", "6Si", "4fJ", "4kz", "7Nx", "7n", "0PT",
"1nY", "dqh", "4P7", "4EV", "4JW", "7oU", "RK", "05q", "1Ot", "8o", "6QX", "50R", "4iK", "7LI", "qW", "d6", "08A", "2Ij", "66L", "4Gg",
"4UK", "74A", "MW", "X6", "1Ph", "21b", "6ND", "5kF", "4vW", "4c6", "nK", "0My", "0cU", "0v4", "6mX", "5HZ", "4Wz", "6bY", "Of", "0lT",
"0Bx", "aJ", "4l7", "4yV", "40n", "6AE", "lz", "0OH", "W7", "BV", "6oi", "4ZJ", "65c", "4DH", "I5", "2JE", "6p", "0QJ", "4jd", "7Of",
"4r5", "4gT", "280", "2iY", "Qd", "0rV", "4Ix", "5L8", "5C9", "4Fy", "1mv", "0h6", "4A", "1CZ", "4hU", "7MW", "6PF", "4ee", "1Nj", "9q",
"SU", "F4", "4KI", "7nK", "oQ", "z0", "43E", "6Bn", "6lB", "4Ya", "0bO", "2Wl", "LM", "8fg", "4TQ", "4A0", "aeL", "cPo", "0AS", "ba",
"3kP", "0NR", "41t", "544", "4N1", "5Kq", "14W", "CL", "2Xm", "0mN", "5FA", "6cC", "6Mo", "4xL", "19", "22I", "k3", "2hC", "6Sm", "4fN",
"4Hb", "69I", "2Fo", "07D", "83l", "d5d", "4P3", "4ER", "bQM", "a0G", "7j", "0PP", "1Op", "8k", "hbw", "50V", "4JS", "7oQ", "RO", "05u",
"08E", "2In", "66H", "4Gc", "4iO", "7LM", "qS", "d2", "0ay", "BK", "4O6", "4ZW", "40s", "553", "lg", "0OU", "t6", "aW", "6Lh", "4yK",
"4Wg", "6bD", "2Yj", "0lI", "0cH", "2Vk", "6mE", "4Xf", "42B", "6Ci", "nV", "0Md", "1Pu", "cf", "6NY", "bAI", "4UV", "7pT", "MJ", "0nx",
"SH", "04r", "4KT", "7nV", "azI", "4ex", "1Nw", "9l", "pT", "e5", "4hH", "7MJ", "67O", "4Fd", "09B", "2Hi", "Qy", "06C", "4Ie", "68N",
"6Rj", "4gI", "j4", "2iD", "6m", "0QW", "4jy", "5o9", "4Q4", "4DU", "1oZ", "2JX", "4m0", "4xQ", "8Jg", "22T", "Na", "0mS", "627", "77w",
"6nn", "5Kl", "V0", "CQ", "3kM", "0NO", "41i", "7Pc", "6OC", "5jA", "0AN", "20e", "LP", "Y1", "4TL", "6ao", "78v", "bcO", "0bR", "0w3",
"oL", "8Ef", "43X", "4b1", "4iR", "7LP", "5F", "266", "08X", "0i1", "66U", "b9E", "4JN", "7oL", "RR", "G3", "1Om", "8v", "6QA", "4db",
"4kc", "7Na", "7w", "0PM", "H2", "2KB", "64d", "4EO", "b6D", "69T", "Pc", "07Y", "297", "dRm", "4s2", "4fS", "40w", "557", "lc", "0OQ",
"15T", "BO", "4O2", "4ZS", "4Wc", "76i", "2Yn", "0lM", "t2", "aS", "6Ll", "4yO", "42F", "6Cm", "nR", "8Dx", "0cL", "2Vo", "6mA", "4Xb",
"4UR", "74X", "MN", "8gd", "1Pq", "cb", "adO", "bAM", "azM", "51U", "1Ns", "9h", "SL", "04v", "4KP", "7nR", "67K", "5VA", "09F", "2Hm",
"4X", "e1", "4hL", "7MN", "6Rn", "4gM", "j0", "3ya", "2Gl", "06G", "4Ia", "68J", "4Q0", "4DQ", "82o", "d4g", "6i", "0QS", "bPN", "a1D",
"Ne", "0mW", "4Vy", "5S9", "4m4", "4xU", "1SZ", "22P", "my", "0NK", "41m", "7Pg", "6nj", "5Kh", "V4", "CU", "LT", "Y5", "4TH", "6ak",
"6OG", "4zd", "0AJ", "bx", "oH", "0Lz", "4wT", "4b5", "78r", "4Yx", "0bV", "Ad", "1lu", "0i5", "66Q", "4Gz", "4iV", "7LT", "5B", "0Rx",
"1Oi", "8r", "6QE", "4df", "4JJ", "7oH", "RV", "G7", "H6", "2KF", "6ph", "4EK", "4kg", "7Ne", "7s", "0PI", "1MX", "1X9", "4s6", "4fW",
"5XZ", "69P", "Pg", "0sU", "06", "23F", "afr", "4yC", "4Wo", "6bL", "Os", "0lA", "0aq", "BC", "aEn", "c4E", "4ts", "5q3", "lo", "8FE",
"347", "cn", "6NQ", "5kS", "bom", "74T", "MB", "0np", "17i", "2Vc", "6mM", "4Xn", "42J", "6Ca", "2xO", "0Ml", "4T", "0Sn", "5xa", "7MB",
"67G", "4Fl", "09J", "2Ha", "1u2", "04z", "b5g", "aTm", "6PS", "4ep", "8WF", "9d", "6e", "8XG", "4jq", "5o1", "65v", "706", "1oR", "1z3",
"Qq", "06K", "4Im", "68F", "6Rb", "4gA", "1LN", "2iL", "6nf", "5Kd", "V8", "CY", "mu", "0NG", "41a", "7Pk", "4m8", "4xY", "0Cw", "1F7",
"Ni", "19r", "4Vu", "5S5", "6lW", "4Yt", "0bZ", "Ah", "oD", "0Lv", "43P", "4b9", "6OK", "4zh", "0AF", "bt", "LX", "Y9", "4TD", "6ag",
"4JF", "7oD", "RZ", "0qh", "1Oe", "2jg", "6QI", "4dj", "4iZ", "483", "5N", "0Rt", "08P", "0i9", "5B6", "4Gv", "4Hw", "5M7", "Pk", "07Q",
"1MT", "1X5", "472", "52r", "4kk", "7Ni", "sw", "0PE", "1nH", "2KJ", "64l", "4EG", "4Wk", "6bH", "Ow", "0lE", "02", "23B", "6Ld", "4yG",
"4tw", "5q7", "lk", "0OY", "0au", "BG", "6ox", "5Jz", "4UZ", "74P", "MF", "0nt", "1Py", "cj", "6NU", "5kW", "42N", "6Ce", "nZ", "0Mh",
"0cD", "2Vg", "6mI", "4Xj", "67C", "4Fh", "09N", "2He", "4P", "e9", "4hD", "7MF", "6PW", "4et", "3n9", "2ky", "SD", "0pv", "4KX", "7nZ",
"4Q8", "4DY", "1oV", "1z7", "6a", "1Az", "4ju", "5o5", "6Rf", "4gE", "j8", "2iH", "Qu", "06O", "4Ii", "68B", "mq", "0NC", "41e", "7Po",
"6nb", "bar", "14F", "2UL", "Nm", "19v", "4Vq", "5S1", "agl", "bBn", "0Cs", "1F3", "1I2", "0Lr", "43T", "ahm", "6lS", "4Yp", "16w", "Al",
"2ZM", "0on", "5Da", "6ac", "6OO", "4zl", "0AB", "bp", "1Oa", "8z", "6QM", "4dn", "4JB", "aUs", "2DO", "05d", "08T", "d7D", "5B2", "4Gr",
"bSm", "487", "5J", "0Rp", "1MP", "1X1", "476", "52v", "4Hs", "5M3", "Po", "07U", "1nL", "2KN", "64h", "4EC", "4ko", "7Nm", "ss", "0PA",
"QJ", "06p", "4IV", "7lT", "6RY", "4gz", "1Lu", "0I5", "rV", "g7", "4jJ", "7OH", "65M", "4Df", "1oi", "2Jk", "2Ej", "04A", "4Kg", "7ne",
"6Ph", "4eK", "h6", "2kF", "4o", "0SU", "5xZ", "7My", "4S6", "4FW", "09q", "1x9", "17R", "2VX", "4M4", "4XU", "42q", "571", "ne", "0MW",
"v4", "cU", "6Nj", "5kh", "4Ue", "74o", "My", "0nK", "0aJ", "Bx", "6oG", "4Zd", "4tH", "6Ak", "lT", "y5", "0BV", "ad", "580", "4yx",
"4WT", "4B5", "OH", "0lz", "4kP", "7NR", "7D", "244", "1ns", "0k3", "64W", "con", "4HL", "69g", "PP", "E1", "1Mo", "2hm", "6SC", "52I",
"4ia", "7Lc", "5u", "0RO", "J0", "3Ya", "66f", "4GM", "b4F", "aUL", "Ra", "0qS", "8Vg", "8E", "458", "4dQ", "4o2", "4zS", "8He", "bO",
"Lc", "0oQ", "605", "75u", "6ll", "4YO", "T2", "AS", "2yn", "0LM", "43k", "7Ra", "6MA", "4xb", "0CL", "22g", "NR", "19I", "4VN", "6cm",
"aDO", "baM", "14y", "Cb", "mN", "8Gd", "41Z", "7PP", "axO", "53W", "1Lq", "0I1", "QN", "06t", "4IR", "68y", "65I", "4Db", "1om", "2Jo",
"6Z", "g3", "4jN", "7OL", "6Pl", "4eO", "h2", "2kB", "2En", "04E", "4Kc", "7na", "4S2", "4FS", "09u", "d6e", "4k", "0SQ", "bRL", "a3F",
"42u", "575", "na", "0MS", "17V", "dlo", "4M0", "4XQ", "4Ua", "74k", "3KM", "0nO", "28", "cQ", "6Nn", "5kl", "40D", "6Ao", "lP", "y1",
"0aN", "2Tm", "6oC", "5JA", "4WP", "4B1", "OL", "18W", "0BR", "0W3", "584", "bCO", "1nw", "0k7", "64S", "4Ex", "4kT", "7NV", "sH", "0Pz",
"1Mk", "2hi", "6SG", "4fd", "4HH", "69c", "PT", "E5", "J4", "2ID", "66b", "4GI", "4ie", "7Lg", "5q", "0RK", "1OZ", "8A", "4q4", "4dU",
"4Jy", "5O9", "Re", "0qW", "Lg", "0oU", "5DZ", "6aX", "4o6", "4zW", "0Ay", "bK", "2yj", "0LI", "43o", "6BD", "6lh", "4YK", "T6", "AW",
"NV", "0md", "4VJ", "6ci", "6ME", "4xf", "0CH", "22c", "mJ", "0Nx", "4uV", "7PT", "6nY", "baI", "1pu", "Cf", "6V", "0Ql", "4jB", "aus",
"65E", "4Dn", "1oa", "2Jc", "QB", "06x", "b7e", "68u", "5b2", "4gr", "8UD", "dSL", "4g", "8ZE", "4hs", "5m3", "67t", "724", "09y", "1x1",
"Ss", "04I", "4Ko", "7nm", "azr", "4eC", "1NL", "9W", "24", "21D", "6Nb", "bAr", "4Um", "74g", "Mq", "0nC", "0cs", "1f3", "79W", "bbn",
"42y", "579", "nm", "394", "365", "al", "588", "4yp", "bmo", "76V", "1i2", "0lr", "0aB", "Bp", "6oO", "4Zl", "40H", "6Ac", "2zM", "0On",
"4HD", "69o", "PX", "E9", "1Mg", "2he", "6SK", "4fh", "4kX", "7NZ", "7L", "0Pv", "3N9", "2Ky", "6pW", "4Et", "4Ju", "5O5", "Ri", "05S",
"1OV", "8M", "450", "4dY", "4ii", "7Lk", "qu", "0RG", "J8", "2IH", "66n", "4GE", "6ld", "4YG", "0bi", "2WJ", "ow", "0LE", "43c", "6BH",
"6Ox", "5jz", "0Au", "bG", "Lk", "0oY", "4Tw", "5Q7", "6nU", "5KW", "14q", "Cj", "mF", "0Nt", "41R", "7PX", "6MI", "4xj", "0CD", "22o",
"NZ", "0mh", "4VF", "6ce", "65A", "4Dj", "1oe", "2Jg", "6R", "0Qh", "4jF", "7OD", "5b6", "4gv", "1Ly", "0I9", "QF", "0rt", "4IZ", "68q",
"67p", "5Vz", "1mT", "1x5", "4c", "0SY", "4hw", "5m7", "6Pd", "4eG", "1NH", "9S", "Sw", "04M", "4Kk", "7ni", "4Ui", "74c", "Mu", "0nG",
"20", "cY", "6Nf", "5kd", "4vu", "5s5", "ni", "390", "0cw", "1f7", "4M8", "4XY", "4WX", "4B9", "OD", "0lv", "0BZ", "ah", "6LW", "4yt",
"40L", "6Ag", "lX", "y9", "0aF", "Bt", "6oK", "4Zh", "1Mc", "2ha", "6SO", "4fl", "5Xa", "69k", "2FM", "07f", "83N", "d5F", "6pS", "4Ep",
"bQo", "a0e", "7H", "0Pr", "1OR", "8I", "454", "50t", "4Jq", "5O1", "Rm", "05W", "08g", "2IL", "66j", "4GA", "4im", "7Lo", "5y", "0RC",
"os", "0LA", "43g", "6BL", "78I", "4YC", "0bm", "2WN", "Lo", "8fE", "4Ts", "5Q3", "aen", "cPM", "0Aq", "bC", "mB", "0Np", "41V", "ajo",
"6nQ", "5KS", "14u", "Cn", "2XO", "0ml", "4VB", "6ca", "6MM", "4xn", "1Sa", "22k", "Sj", "04P", "4Kv", "5N6", "443", "4eZ", "1NU", "9N",
"pv", "0SD", "4hj", "7Mh", "67m", "4FF", "1mI", "2HK", "2GJ", "2", "4IG", "68l", "6RH", "4gk", "1Ld", "2if", "6O", "0Qu", "5zz", "7OY",
"5A7", "4Dw", "1ox", "0j8", "15r", "Bi", "6oV", "4Zu", "40Q", "4a8", "lE", "0Ow", "0BG", "au", "6LJ", "4yi", "4WE", "6bf", "OY", "Z8",
"U9", "2VI", "6mg", "4XD", "4vh", "6CK", "nt", "0MF", "1PW", "cD", "4n9", "5ky", "4Ut", "5P4", "Mh", "0nZ", "4ip", "5l0", "5d", "9Kg",
"08z", "1y2", "66w", "737", "4Jl", "7on", "Rp", "05J", "1OO", "8T", "6Qc", "50i", "4kA", "7NC", "7U", "0Po", "1nb", "dqS", "64F", "4Em",
"b6f", "69v", "PA", "0ss", "8TG", "dRO", "5c1", "4fq", "6MP", "4xs", "376", "22v", "NC", "0mq", "bll", "77U", "6nL", "5KN", "14h", "Cs",
"3ko", "0Nm", "41K", "7PA", "6Oa", "4zB", "37", "20G", "Lr", "8fX", "4Tn", "6aM", "78T", "bcm", "0bp", "AB", "on", "387", "43z", "5r2",
"447", "51w", "1NQ", "9J", "Sn", "04T", "4Kr", "5N2", "67i", "4FB", "09d", "2HO", "4z", "1Ca", "4hn", "7Ml", "6RL", "4go", "8UY", "2ib",
"2GN", "6", "4IC", "68h", "5A3", "4Ds", "82M", "d4E", "6K", "0Qq", "bPl", "a1f", "40U", "akl", "lA", "0Os", "15v", "Bm", "6oR", "4Zq",
"4WA", "6bb", "2YL", "0lo", "0BC", "aq", "6LN", "4ym", "42d", "6CO", "np", "0MB", "0cn", "2VM", "6mc", "5Ha", "4Up", "5P0", "Ml", "8gF",
"1PS", "1E2", "adm", "bAo", "1lW", "1y6", "4R9", "4GX", "4it", "5l4", "qh", "0RZ", "i9", "8P", "6Qg", "4dD", "4Jh", "7oj", "Rt", "05N",
"1nf", "2Kd", "64B", "4Ei", "4kE", "7NG", "7Q", "f8", "1Mz", "2hx", "5c5", "4fu", "4HY", "69r", "PE", "0sw", "NG", "0mu", "5Fz", "6cx",
"6MT", "4xw", "0CY", "0V8", "3kk", "0Ni", "41O", "7PE", "6nH", "5KJ", "14l", "Cw", "Lv", "0oD", "4Tj", "6aI", "6Oe", "4zF", "33", "bZ",
"oj", "0LX", "4wv", "5r6", "6ly", "4YZ", "0bt", "AF", "4v", "0SL", "4hb", "awS", "67e", "4FN", "K3", "2HC", "Sb", "04X", "b5E", "aTO",
"4p3", "4eR", "8Wd", "9F", "6G", "257", "4jS", "7OQ", "65T", "cnm", "1op", "0j0", "QS", "D2", "4IO", "68d", "7Ba", "4gc", "1Ll", "2in",
"0BO", "23d", "6LB", "4ya", "4WM", "6bn", "OQ", "Z0", "0aS", "Ba", "aEL", "c4g", "40Y", "4a0", "lM", "8Fg", "8If", "cL", "4n1", "5kq",
"616", "74v", "3KP", "0nR", "U1", "2VA", "6mo", "4XL", "42h", "6CC", "2xm", "0MN", "4Jd", "7of", "Rx", "05B", "i5", "2jE", "6Qk", "4dH",
"4ix", "5l8", "5l", "0RV", "08r", "2IY", "4R5", "4GT", "4HU", "7mW", "PI", "07s", "1Mv", "0H6", "5c9", "4fy", "4kI", "7NK", "sU", "f4",
"1nj", "2Kh", "64N", "4Ee", "6nD", "5KF", "1ph", "2Uj", "mW", "x6", "41C", "7PI", "593", "5hZ", "0CU", "0V4", "NK", "0my", "4VW", "4C6",
"4L7", "4YV", "0bx", "AJ", "of", "0LT", "43r", "562", "6Oi", "4zJ", "w7", "bV", "Lz", "0oH", "4Tf", "6aE", "67a", "4FJ", "K7", "2HG",
"4r", "0SH", "4hf", "7Md", "4p7", "4eV", "1NY", "9B", "Sf", "0pT", "4Kz", "7nx", "65P", "5TZ", "1ot", "0j4", "6C", "0Qy", "4jW", "7OU",
"6RD", "4gg", "1Lh", "2ij", "QW", "D6", "4IK", "7lI", "4WI", "6bj", "OU", "Z4", "0BK", "ay", "6LF", "4ye", "4tU", "4a4", "lI", "2o9",
"0aW", "Be", "6oZ", "4Zy", "4Ux", "5P8", "Md", "0nV", "8Ib", "cH", "4n5", "5ku", "42l", "6CG", "nx", "0MJ", "U5", "2VE", "6mk", "4XH",
"i1", "8X", "6Qo", "4dL", "5ZA", "7ob", "2Dm", "05F", "08v", "d7f", "4R1", "4GP", "bSO", "a2E", "5h", "0RR", "1Mr", "0H2", "ayL", "52T",
"4HQ", "69z", "PM", "07w", "1nn", "2Kl", "64J", "4Ea", "4kM", "7NO", "7Y", "f0", "mS", "x2", "41G", "7PM", "aDR", "5KB", "14d", "2Un",
"NO", "19T", "4VS", "4C2", "597", "bBL", "0CQ", "0V0", "ob", "0LP", "43v", "566", "4L3", "4YR", "16U", "AN", "2Zo", "0oL", "4Tb", "6aA",
"6Om", "4zN", "w3", "bR", "4oT", "4z5", "wH", "0Tz", "0zV", "Yd", "5D8", "4Ax", "4LH", "6yk", "TT", "A5", "0YJ", "zx", "6WG", "4bd",
"4me", "6XF", "1q", "0VK", "N4", "2MD", "62b", "4CI", "4Ny", "5K9", "Ve", "0uW", "1KZ", "xI", "4u4", "5pt", "4k6", "5nv", "0Ey", "fK",
"Hg", "0kU", "641", "6eX", "6hh", "5Mj", "P6", "EW", "29b", "0HI", "47o", "6FD", "6IE", "48n", "0GH", "dz", "JV", "0id", "4RJ", "6gi",
"6jY", "beI", "0dT", "Gf", "iJ", "0Jx", "4qV", "4d7", "UN", "02t", "4MR", "4X3", "a8G", "57W", "0XP", "0M1", "2Z", "c3", "4nN", "7KL",
"61I", "5PC", "1km", "2No", "2An", "00E", "4Oc", "7ja", "6Tl", "4aO", "l2", "yS", "0k", "0WQ", "58V", "a7F", "4W2", "4BS", "84m", "ZO",
"13V", "E", "4I0", "5Lp", "46u", "535", "ja", "0IS", "68", "gQ", "6Jn", "5ol", "4Qa", "6dB", "3OM", "0jO", "0eN", "2Pm", "6kC", "5NA",
"44D", "6Eo", "hP", "99", "0FR", "0S3", "abM", "49t", "4SP", "4F1", "KL", "8af", "0zR", "0o3", "60W", "ckn", "4oP", "4z1", "3D", "204",
"0YN", "2lm", "6WC", "56I", "4LL", "6yo", "TP", "A1", "N0", "903", "62f", "4CM", "4ma", "6XB", "1u", "0VO", "8Rg", "xM", "418", "54x",
"b0F", "aQL", "Va", "0uS", "Hc", "0kQ", "645", "71u", "4k2", "5nr", "8Le", "fO", "29f", "0HM", "47k", "7Va", "6hl", "5Mn", "P2", "ES",
"JR", "1yA", "4RN", "6gm", "6IA", "48j", "0GL", "26g", "iN", "8Cd", "45Z", "4d3", "hYv", "beM", "0dP", "Gb", "6VY", "4cz", "0XT", "0M5",
"UJ", "02p", "4MV", "4X7", "61M", "5PG", "1ki", "Xz", "vV", "c7", "4nJ", "7KH", "6Th", "4aK", "l6", "yW", "2Aj", "00A", "4Og", "6zD",
"4W6", "4BW", "0yy", "ZK", "0o", "0WU", "58R", "6YX", "46q", "531", "je", "0IW", "13R", "A", "4I4", "5Lt", "4Qe", "6dF", "Iy", "0jK",
"r4", "gU", "6Jj", "5oh", "4pH", "6Ek", "hT", "0Kf", "0eJ", "Fx", "6kG", "5NE", "4ST", "4F5", "KH", "0hz", "0FV", "ed", "5x8", "49p",
"bvs", "6yc", "2BM", "03f", "0YB", "zp", "6WO", "4bl", "bUo", "a4e", "3H", "0Tr", "87N", "Yl", "5D0", "4Ap", "4Nq", "5K1", "Vm", "01W",
"1KR", "xA", "414", "54t", "4mm", "6XN", "1y", "0VC", "0xo", "2ML", "62j", "4CA", "7xA", "5Mb", "0fm", "2SN", "ks", "0HA", "47g", "6FL",
"aan", "bDl", "0Eq", "fC", "Ho", "8bE", "4Ps", "5U3", "5Z2", "5OS", "10u", "Gn", "iB", "0Jp", "45V", "ano", "6IM", "48f", "1Wa", "dr",
"3Ln", "0il", "4RB", "6ga", "2R", "0Uh", "4nF", "7KD", "61A", "5PK", "1ke", "Xv", "UF", "0vt", "4MZ", "6xy", "5f6", "4cv", "0XX", "0M9",
"0c", "0WY", "4lw", "5i7", "63p", "5Rz", "0yu", "ZG", "Ww", "00M", "4Ok", "6zH", "6Td", "4aG", "0Zi", "2oJ", "60", "gY", "6Jf", "5od",
"4Qi", "6dJ", "Iu", "0jG", "0gw", "M", "4I8", "5Lx", "4ru", "5w5", "ji", "1Yz", "0FZ", "eh", "5x4", "5mU", "4SX", "4F9", "KD", "0hv",
"0eF", "Ft", "6kK", "5NI", "44L", "6Eg", "hX", "91", "0YF", "zt", "6WK", "4bh", "4LD", "6yg", "TX", "A9", "0zZ", "Yh", "5D4", "4At",
"4oX", "4z9", "3L", "0Tv", "1KV", "xE", "410", "54p", "4Nu", "5K5", "Vi", "01S", "N8", "2MH", "62n", "4CE", "4mi", "6XJ", "uu", "0VG",
"kw", "0HE", "47c", "6FH", "6hd", "5Mf", "0fi", "2SJ", "Hk", "0kY", "4Pw", "5U7", "6Kx", "5nz", "0Eu", "fG", "iF", "0Jt", "45R", "6Dy",
"5Z6", "5OW", "0dX", "Gj", "JZ", "0ih", "4RF", "6ge", "6II", "48b", "0GD", "dv", "61E", "5PO", "1ka", "Xr", "2V", "0Ul", "4nB", "aqs",
"5f2", "4cr", "8QD", "39V", "UB", "02x", "795", "aRo", "63t", "764", "0yq", "ZC", "0g", "9Nd", "4ls", "5i3", "7DA", "4aC", "0Zm", "2oN",
"Ws", "00I", "4Oo", "6zL", "4Qm", "6dN", "Iq", "0jC", "64", "25D", "6Jb", "bEr", "46y", "539", "jm", "9Pf", "0gs", "I", "aCl", "bfn",
"bio", "72V", "1m2", "0hr", "325", "el", "5x0", "49x", "44H", "6Ec", "3nl", "95", "0eB", "Fp", "6kO", "5NM", "4mt", "5h4", "uh", "0VZ",
"0xv", "2MU", "4V9", "4CX", "4Nh", "7kj", "Vt", "01N", "m9", "xX", "6Ug", "54m", "4oE", "6Zf", "3Q", "b8", "0zG", "Yu", "60B", "4Ai",
"4LY", "4Y8", "TE", "0ww", "1Iz", "zi", "5g5", "4bu", "5y7", "5lV", "0GY", "dk", "JG", "0iu", "5Bz", "6gx", "6jH", "5OJ", "0dE", "Gw",
"3ok", "82", "45O", "6Dd", "6Ke", "5ng", "73", "fZ", "Hv", "0kD", "4Pj", "6eI", "6hy", "7m9", "0ft", "EF", "kj", "0HX", "4sv", "5v6",
"Wn", "00T", "4Or", "5J2", "407", "55w", "0Zp", "yB", "0z", "1Ga", "4ln", "6YM", "63i", "4BB", "0yl", "2LO", "2CN", "02e", "4MC", "7hA",
"6VL", "4co", "0XA", "2mb", "2K", "0Uq", "bTl", "a5f", "5E3", "5PR", "86M", "Xo", "11v", "Fm", "6kR", "5NP", "44U", "aol", "hA", "0Ks",
"0FC", "eq", "6HN", "49e", "4SA", "6fb", "3Mm", "0ho", "0gn", "T", "6ic", "5La", "46d", "6GO", "jp", "0IB", "0Dr", "1A2", "hyT", "bEo",
"4Qp", "5T0", "Il", "8cF", "0xr", "2MQ", "62w", "777", "4mp", "5h0", "1d", "9Og", "1KO", "2nM", "6Uc", "54i", "4Nl", "7kn", "Vp", "01J",
"0zC", "Yq", "60F", "4Am", "4oA", "6Zb", "3U", "0To", "8PG", "zm", "5g1", "4bq", "786", "aSl", "TA", "0ws", "JC", "0iq", "bhl", "73U",
"5y3", "5lR", "336", "do", "3oo", "86", "45K", "7TA", "6jL", "5ON", "0dA", "Gs", "Hr", "8bX", "4Pn", "6eM", "6Ka", "5nc", "77", "24G",
"kn", "8AD", "47z", "5v2", "aBo", "bgm", "0fp", "EB", "403", "4aZ", "0Zt", "yF", "Wj", "00P", "4Ov", "5J6", "63m", "4BF", "0yh", "ZZ",
"tv", "0WD", "4lj", "6YI", "6VH", "4ck", "0XE", "2mf", "2CJ", "02a", "4MG", "6xd", "5E7", "5PV", "1kx", "Xk", "2O", "0Uu", "bTh", "7KY",
"44Q", "4e8", "hE", "0Kw", "11r", "Fi", "6kV", "5NT", "4SE", "6ff", "KY", "0hk", "0FG", "eu", "6HJ", "49a", "4rh", "6GK", "jt", "0IF",
"Q9", "P", "6ig", "5Le", "4Qt", "5T4", "Ih", "0jZ", "0Dv", "gD", "4j9", "5oy", "aD0", "7kb", "3PL", "01F", "m1", "xP", "6Uo", "54e",
"59U", "a6E", "1h", "0VR", "85n", "196", "4V1", "4CP", "4LQ", "4Y0", "TM", "03w", "0YS", "za", "a9D", "56T", "4oM", "6Zn", "3Y", "b0",
"0zO", "2Ol", "60J", "4Aa", "7za", "5OB", "0dM", "2Qn", "iS", "0Ja", "45G", "6Dl", "acN", "48w", "0GQ", "dc", "JO", "94L", "4RS", "4G2",
"4H3", "5Ms", "12U", "EN", "kb", "0HP", "47v", "526", "6Km", "5no", "s3", "fR", "3NN", "0kL", "4Pb", "6eA", "0r", "0WH", "4lf", "6YE",
"63a", "4BJ", "O7", "ZV", "Wf", "0tT", "4Oz", "6zY", "4t7", "4aV", "0Zx", "yJ", "2C", "0Uy", "4nW", "7KU", "61P", "5PZ", "1kt", "Xg",
"UW", "02m", "4MK", "6xh", "6VD", "4cg", "0XI", "2mj", "0FK", "ey", "6HF", "49m", "4SI", "6fj", "KU", "0hg", "0eW", "Fe", "6kZ", "5NX",
"4pU", "4e4", "hI", "2k9", "0Dz", "gH", "4j5", "5ou", "4Qx", "5T8", "Id", "0jV", "Q5", "DT", "6ik", "5Li", "46l", "6GG", "jx", "0IJ",
"m5", "xT", "6Uk", "54a", "4Nd", "7kf", "Vx", "01B", "0xz", "192", "4V5", "4CT", "4mx", "5h8", "1l", "0VV", "0YW", "ze", "5g9", "4by",
"4LU", "4Y4", "TI", "03s", "0zK", "Yy", "60N", "4Ae", "4oI", "6Zj", "wU", "b4", "iW", "0Je", "45C", "6Dh", "6jD", "5OF", "0dI", "2Qj",
"JK", "0iy", "4RW", "4G6", "6IX", "48s", "0GU", "dg", "kf", "0HT", "47r", "522", "4H7", "5Mw", "0fx", "EJ", "Hz", "0kH", "4Pf", "6eE",
"6Ki", "5nk", "s7", "fV", "63e", "4BN", "O3", "ZR", "0v", "0WL", "4lb", "6YA", "4t3", "4aR", "8Sd", "yN", "Wb", "00X", "b1E", "aPO",
"61T", "bzL", "1kp", "Xc", "2G", "217", "4nS", "7KQ", "7Fa", "4cc", "0XM", "2mn", "US", "02i", "4MO", "6xl", "4SM", "6fn", "KQ", "0hc",
"0FO", "27d", "6HB", "49i", "44Y", "4e0", "hM", "8Bg", "0eS", "Fa", "aAL", "bdN", "656", "70v", "3OP", "0jR", "8Mf", "gL", "4j1", "5oq",
"46h", "6GC", "28e", "0IN", "Q1", "X", "6io", "5Lm", "6KV", "5nT", "1Uz", "fi", "HE", "0kw", "4PY", "4E8", "6hJ", "5MH", "0fG", "Eu",
"kY", "0Hk", "47M", "6Ff", "6Ig", "48L", "51", "dX", "Jt", "0iF", "4Rh", "6gK", "4J9", "5Oy", "0dv", "GD", "ih", "0JZ", "4qt", "5t4",
"4ov", "5j6", "3b", "0TX", "0zt", "YF", "60q", "4AZ", "4Lj", "6yI", "Tv", "03L", "0Yh", "zZ", "6We", "4bF", "4mG", "6Xd", "1S", "0Vi",
"0xE", "2Mf", "6vH", "4Ck", "bth", "7kY", "VG", "0uu", "1Kx", "xk", "5e7", "5pV", "13t", "g", "5Y3", "5LR", "46W", "amn", "jC", "0Iq",
"0DA", "gs", "6JL", "5oN", "4QC", "70I", "3Oo", "0jm", "0el", "2PO", "6ka", "5Nc", "44f", "6EM", "hr", "8BX", "0Fp", "eB", "abo", "49V",
"4Sr", "5V2", "Kn", "8aD", "Ul", "02V", "4Mp", "5H0", "425", "57u", "0Xr", "2mQ", "2x", "0UB", "4nl", "7Kn", "61k", "5Pa", "1kO", "2NM",
"2AL", "00g", "4OA", "6zb", "6TN", "4am", "0ZC", "yq", "0I", "0Ws", "58t", "a7d", "5G1", "4Bq", "84O", "Zm", "HA", "0ks", "bjn", "71W",
"6KR", "5nP", "314", "fm", "29D", "0Ho", "47I", "6Fb", "6hN", "5ML", "0fC", "Eq", "Jp", "0iB", "4Rl", "6gO", "6Ic", "48H", "55", "26E",
"il", "8CF", "45x", "508", "hYT", "beo", "0dr", "1a2", "0zp", "YB", "60u", "755", "4or", "5j2", "3f", "9Me", "0Yl", "2lO", "6Wa", "4bB",
"4Ln", "6yM", "Tr", "03H", "0xA", "2Mb", "62D", "4Co", "4mC", "7HA", "1W", "0Vm", "8RE", "xo", "5e3", "54Z", "b0d", "aQn", "VC", "01y",
"46S", "6Gx", "jG", "0Iu", "0gY", "c", "5Y7", "5LV", "4QG", "6dd", "3Ok", "0ji", "0DE", "gw", "6JH", "5oJ", "44b", "6EI", "hv", "0KD",
"0eh", "FZ", "6ke", "5Ng", "4Sv", "5V6", "Kj", "0hX", "0Ft", "eF", "6Hy", "49R", "421", "4cX", "0Xv", "2mU", "Uh", "02R", "4Mt", "5H4",
"61o", "5Pe", "M9", "XX", "vt", "0UF", "4nh", "7Kj", "6TJ", "4ai", "0ZG", "yu", "WY", "B8", "4OE", "6zf", "5G5", "4Bu", "1iz", "Zi",
"0M", "0Ww", "4lY", "4y8", "6hB", "aW1", "0fO", "2Sl", "kQ", "0Hc", "47E", "6Fn", "aaL", "bDN", "0ES", "fa", "HM", "8bg", "4PQ", "4E0",
"4J1", "5Oq", "10W", "GL", "3oP", "0JR", "45t", "504", "6Io", "48D", "59", "dP", "3LL", "0iN", "5BA", "6gC", "4Lb", "6yA", "2Bo", "03D",
"o3", "zR", "6Wm", "4bN", "bUM", "a4G", "3j", "0TP", "87l", "YN", "4T3", "4AR", "4NS", "7kQ", "VO", "01u", "1Kp", "xc", "hfw", "54V",
"4mO", "6Xl", "uS", "0Va", "0xM", "2Mn", "62H", "4Cc", "0DI", "25b", "6JD", "5oF", "4QK", "6dh", "IW", "0je", "0gU", "o", "6iX", "5LZ",
"4rW", "4g6", "jK", "0Iy", "0Fx", "eJ", "4h7", "5mw", "4Sz", "6fY", "Kf", "0hT", "S7", "FV", "6ki", "5Nk", "44n", "6EE", "hz", "0KH",
"2p", "0UJ", "4nd", "7Kf", "61c", "5Pi", "M5", "XT", "Ud", "0vV", "4Mx", "5H8", "4v5", "4cT", "0Xz", "2mY", "0A", "1GZ", "4lU", "4y4",
"5G9", "4By", "0yW", "Ze", "WU", "B4", "4OI", "6zj", "6TF", "4ae", "0ZK", "yy", "kU", "0Hg", "47A", "6Fj", "6hF", "5MD", "0fK", "Ey",
"HI", "2K9", "4PU", "4E4", "6KZ", "5nX", "0EW", "fe", "id", "0JV", "45p", "500", "4J5", "5Ou", "0dz", "GH", "Jx", "0iJ", "4Rd", "6gG",
"6Ik", "5li", "q5", "dT", "o7", "zV", "6Wi", "4bJ", "4Lf", "6yE", "Tz", "0wH", "0zx", "YJ", "4T7", "4AV", "4oz", "6ZY", "3n", "0TT",
"1Kt", "xg", "6UX", "54R", "4NW", "7kU", "VK", "01q", "0xI", "2Mj", "62L", "4Cg", "4mK", "6Xh", "uW", "0Ve", "4QO", "6dl", "IS", "0ja",
"0DM", "25f", "7Za", "5oB", "4rS", "4g2", "jO", "9PD", "0gQ", "k", "aCN", "685", "674", "72t", "Kb", "0hP", "8Od", "eN", "4h3", "49Z",
"44j", "6EA", "3nN", "0KL", "S3", "FR", "6km", "5No", "61g", "5Pm", "M1", "XP", "2t", "0UN", "ad0", "7Kb", "429", "4cP", "8Qf", "39t",
"0c3", "02Z", "b3G", "aRM", "63V", "bxN", "0yS", "Za", "0E", "235", "4lQ", "4y0", "6TB", "4aa", "0ZO", "2ol", "WQ", "B0", "4OM", "6zn",
"4i4", "5lt", "1WZ", "dI", "Je", "0iW", "4Ry", "5W9", "6jj", "5Oh", "R4", "GU", "iy", "0JK", "45m", "6DF", "6KG", "5nE", "0EJ", "fx",
"HT", "0kf", "4PH", "6ek", "5X8", "5MY", "0fV", "Ed", "kH", "0Hz", "4sT", "4f5", "4mV", "4x7", "1B", "0Vx", "0xT", "0m5", "62Q", "4Cz",
"4NJ", "7kH", "VV", "C7", "1Ki", "xz", "6UE", "54O", "4og", "6ZD", "3s", "0TI", "L6", "YW", "6th", "4AK", "6l9", "6yX", "Tg", "0wU",
"0Yy", "zK", "4w6", "4bW", "11T", "FO", "4K2", "5Nr", "44w", "517", "hc", "0KQ", "p2", "eS", "6Hl", "49G", "4Sc", "72i", "3MO", "0hM",
"0gL", "v", "6iA", "5LC", "46F", "6Gm", "jR", "1YA", "0DP", "gb", "hyv", "bEM", "4QR", "4D3", "IN", "8cd", "WL", "00v", "4OP", "4Z1",
"hgt", "55U", "0ZR", "0O3", "0X", "a1", "4lL", "6Yo", "63K", "5RA", "0yN", "2Lm", "2Cl", "02G", "4Ma", "6xB", "6Vn", "4cM", "n0", "39i",
"2i", "0US", "bTN", "a5D", "4U0", "5Pp", "86o", "XM", "Ja", "0iS", "667", "73w", "4i0", "48Y", "8Ng", "dM", "3oM", "0JO", "45i", "6DB",
"6jn", "5Ol", "R0", "GQ", "HP", "0kb", "4PL", "6eo", "6KC", "5nA", "0EN", "24e", "kL", "8Af", "47X", "4f1", "aBM", "696", "0fR", "0s3",
"0xP", "0m1", "62U", "byM", "4mR", "4x3", "1F", "226", "1Km", "2no", "6UA", "54K", "4NN", "7kL", "VR", "C3", "L2", "YS", "60d", "4AO",
"4oc", "7Ja", "3w", "0TM", "8Pe", "zO", "4w2", "4bS", "b2D", "aSN", "Tc", "03Y", "44s", "513", "hg", "0KU", "0ey", "FK", "4K6", "5Nv",
"4Sg", "6fD", "3MK", "0hI", "p6", "eW", "6Hh", "49C", "46B", "6Gi", "jV", "0Id", "0gH", "r", "6iE", "5LG", "4QV", "4D7", "IJ", "0jx",
"0DT", "gf", "6JY", "bEI", "5d8", "4ax", "0ZV", "yd", "WH", "00r", "4OT", "4Z5", "63O", "4Bd", "0yJ", "Zx", "tT", "a5", "4lH", "6Yk",
"6Vj", "4cI", "n4", "2mD", "Uy", "02C", "4Me", "6xF", "4U4", "5Pt", "1kZ", "XI", "2m", "0UW", "4ny", "5k9", "6jb", "ber", "0do", "2QL",
"iq", "0JC", "45e", "6DN", "acl", "48U", "0Gs", "dA", "Jm", "94n", "4Rq", "5W1", "5X0", "5MQ", "12w", "El", "1M2", "0Hr", "47T", "alm",
"6KO", "5nM", "0EB", "fp", "3Nl", "0kn", "bjs", "6ec", "4NB", "aQs", "3Pn", "01d", "1Ka", "xr", "6UM", "54G", "59w", "a6g", "1J", "0Vp",
"85L", "d3D", "5F2", "4Cr", "4Ls", "5I3", "To", "03U", "0Yq", "zC", "436", "56v", "4oo", "6ZL", "ws", "0TA", "0zm", "2ON", "60h", "4AC",
"42", "27B", "6Hd", "49O", "4Sk", "6fH", "Kw", "0hE", "0eu", "FG", "6kx", "5Nz", "4pw", "5u7", "hk", "0KY", "0DX", "gj", "5z6", "5oW",
"4QZ", "6dy", "IF", "0jt", "0gD", "Dv", "6iI", "5LK", "46N", "6Ge", "jZ", "0Ih", "0P", "a9", "4lD", "6Yg", "63C", "4Bh", "0yF", "Zt",
"WD", "0tv", "4OX", "4Z9", "5d4", "4at", "0ZZ", "yh", "2a", "1Ez", "4nu", "5k5", "4U8", "5Px", "1kV", "XE", "Uu", "02O", "4Mi", "6xJ",
"6Vf", "4cE", "n8", "2mH", "iu", "0JG", "45a", "6DJ", "6jf", "5Od", "R8", "GY", "Ji", "1yz", "4Ru", "5W5", "4i8", "48Q", "0Gw", "dE",
"kD", "0Hv", "47P", "4f9", "5X4", "5MU", "0fZ", "Eh", "HX", "0kj", "4PD", "6eg", "6KK", "5nI", "0EF", "ft", "1Ke", "xv", "6UI", "54C",
"4NF", "7kD", "VZ", "0uh", "0xX", "0m9", "5F6", "4Cv", "4mZ", "6Xy", "1N", "0Vt", "0Yu", "zG", "432", "56r", "4Lw", "5I7", "Tk", "03Q",
"0zi", "2OJ", "60l", "4AG", "4ok", "6ZH", "ww", "0TE", "4So", "6fL", "Ks", "0hA", "46", "27F", "7XA", "49K", "4ps", "5u3", "ho", "8BE",
"0eq", "FC", "aAn", "bdl", "bkm", "70T", "IB", "0jp", "307", "gn", "5z2", "5oS", "46J", "6Ga", "28G", "0Il", "13i", "z", "6iM", "5LO",
"63G", "4Bl", "0yB", "Zp", "0T", "0Wn", "58i", "6Yc", "5d0", "4ap", "8SF", "yl", "1q2", "00z", "b1g", "aPm", "61v", "746", "1kR", "XA",
"2e", "9Lf", "4nq", "5k1", "6Vb", "4cA", "0Xo", "2mL", "Uq", "02K", "4Mm", "6xN", "8YG", "7e", "5n1", "4kq", "716", "64v", "2KP", "1nR",
"07K", "Pq", "69F", "4Hm", "4fA", "6Sb", "2hL", "1MN", "0Rn", "5T", "7LB", "5ya", "4Gl", "66G", "2Ia", "08J", "05z", "1t2", "aUm", "b4g",
"4dp", "5a0", "8d", "8VF", "bn", "357", "4zr", "6OQ", "75T", "bnm", "0op", "LB", "Ar", "16i", "4Yn", "6lM", "6Ba", "43J", "0Ll", "2yO",
"22F", "16", "4xC", "agr", "6cL", "4Vo", "0mA", "Ns", "CC", "14X", "bal", "aDn", "5p3", "4us", "8GE", "mo", "5L7", "4Iw", "06Q", "Qk",
"1Y5", "1LT", "53r", "462", "7Oi", "4jk", "0QE", "rw", "2JJ", "1oH", "4DG", "65l", "7nD", "4KF", "0ph", "SZ", "2kg", "1Ne", "4ej", "6PI",
"493", "4hZ", "0St", "4N", "0h9", "09P", "4Fv", "5C6", "4Xt", "6mW", "023", "0cZ", "0Mv", "nD", "4c9", "42P", "5kI", "6NK", "ct", "1Pg",
"X9", "MX", "74N", "4UD", "4ZE", "6of", "BY", "W8", "0OG", "lu", "6AJ", "40a", "4yY", "4l8", "aE", "0Bw", "18r", "Oi", "5R5", "4Wu",
"4EY", "4P8", "2KT", "1nV", "8YC", "7a", "5n5", "4ku", "4fE", "6Sf", "2hH", "k8", "07O", "Pu", "69B", "4Hi", "4Gh", "66C", "2Ie", "08N",
"d9", "5P", "7LF", "4iD", "4dt", "5a4", "2jy", "3o9", "0qv", "RD", "7oZ", "4JX", "6ay", "4TZ", "0ot", "LF", "bj", "0AX", "4zv", "6OU",
"6Be", "43N", "0Lh", "oZ", "Av", "0bD", "4Yj", "6lI", "6cH", "4Vk", "0mE", "Nw", "22B", "12", "4xG", "6Md", "5p7", "4uw", "0NY", "mk",
"CG", "1pT", "5Kz", "6nx", "1Y1", "1LP", "53v", "466", "5L3", "4Is", "06U", "Qo", "2JN", "1oL", "4DC", "65h", "7Om", "4jo", "0QA", "rs",
"9z", "1Na", "4en", "6PM", "aTs", "4KB", "04d", "2EO", "d6D", "09T", "4Fr", "5C2", "497", "bRm", "0Sp", "4J", "0Mr", "1H2", "aim", "42T",
"4Xp", "6mS", "027", "17w", "0nn", "3Kl", "74J", "5Ea", "5kM", "6NO", "cp", "1Pc", "0OC", "lq", "6AN", "40e", "4ZA", "6ob", "2TL", "0ao",
"18v", "Om", "5R1", "4Wq", "bCn", "afl", "aA", "0Bs", "07C", "Py", "69N", "4He", "4fI", "6Sj", "2hD", "k4", "0PW", "7m", "5n9", "4ky",
"4EU", "4P4", "2KX", "1nZ", "05r", "RH", "7oV", "4JT", "4dx", "5a8", "8l", "1Ow", "d5", "qT", "7LJ", "4iH", "4Gd", "66O", "2Ii", "08B",
"Az", "0bH", "4Yf", "6lE", "6Bi", "43B", "z7", "oV", "bf", "0AT", "4zz", "6OY", "4A7", "4TV", "0ox", "LJ", "CK", "14P", "5Kv", "4N6",
"543", "41s", "0NU", "mg", "22N", "u6", "4xK", "6Mh", "6cD", "4Vg", "0mI", "2Xj", "7Oa", "4jc", "0QM", "6w", "2JB", "I2", "4DO", "65d",
"68T", "b7D", "06Y", "Qc", "dSm", "287", "4gS", "4r2", "7MP", "4hR", "276", "4F", "0h1", "09X", "b8E", "67U", "7nL", "4KN", "F3", "SR",
"9v", "1Nm", "4eb", "6PA", "5kA", "6NC", "21e", "1Po", "X1", "MP", "74F", "4UL", "bbO", "79v", "0v3", "0cR", "8Df", "nL", "4c1", "42X",
"4yQ", "4l0", "aM", "8Kg", "0lS", "Oa", "76w", "637", "4ZM", "6on", "BQ", "W0", "0OO", "2zl", "6AB", "40i", "4fM", "6Sn", "3xa", "k0",
"07G", "2Fl", "69J", "4Ha", "4EQ", "4P0", "d5g", "83o", "0PS", "7i", "a0D", "bQN", "50U", "hbt", "8h", "1Os", "05v", "RL", "7oR", "4JP",
"5WA", "66K", "2Im", "08F", "d1", "5X", "7LN", "4iL", "6Bm", "43F", "z3", "oR", "2Wo", "0bL", "4Yb", "6lA", "4A3", "4TR", "8fd", "LN",
"bb", "0AP", "cPl", "aeO", "547", "41w", "0NQ", "mc", "CO", "14T", "5Kr", "4N2", "77i", "4Vc", "0mM", "2Xn", "22J", "u2", "4xO", "6Ml",
"2JF", "I6", "4DK", "6qh", "7Oe", "4jg", "0QI", "6s", "1Y9", "1LX", "4gW", "4r6", "68P", "5YZ", "0rU", "Qg", "0h5", "1mu", "4Fz", "67Q",
"7MT", "4hV", "0Sx", "4B", "9r", "1Ni", "4ef", "6PE", "7nH", "4KJ", "F7", "SV", "X5", "MT", "74B", "4UH", "5kE", "6NG", "cx", "1Pk",
"0Mz", "nH", "4c5", "4vT", "4Xx", "79r", "0v7", "0cV", "0lW", "Oe", "5R9", "4Wy", "4yU", "4l4", "aI", "1RZ", "0OK", "ly", "6AF", "40m",
"4ZI", "6oj", "BU", "W4", "265", "5E", "488", "4iQ", "b9F", "66V", "0i2", "1lr", "G0", "RQ", "7oO", "4JM", "4da", "6QB", "8u", "1On",
"0PN", "7t", "7Nb", "aa0", "4EL", "64g", "2KA", "H1", "07Z", "0f3", "69W", "b6G", "4fP", "479", "dRn", "294", "22W", "8Jd", "4xR", "4m3",
"77t", "624", "0mP", "Nb", "CR", "V3", "5Ko", "6nm", "ajS", "41j", "0NL", "3kN", "20f", "0AM", "4zc", "aeR", "6al", "4TO", "Y2", "LS",
"Ac", "0bQ", "bcL", "78u", "4b2", "4wS", "8Ee", "oO", "7nU", "4KW", "04q", "SK", "9o", "1Nt", "51R", "6PX", "7MI", "4hK", "e6", "pW",
"2Hj", "09A", "4Fg", "67L", "68M", "4If", "0rH", "Qz", "2iG", "j7", "4gJ", "6Ri", "7Ox", "4jz", "0QT", "6n", "1z8", "1oY", "4DV", "4Q7",
"4ZT", "4O5", "BH", "0az", "0OV", "ld", "550", "40p", "4yH", "6Lk", "aT", "t5", "0lJ", "Ox", "6bG", "4Wd", "4Xe", "6mF", "2Vh", "0cK",
"0Mg", "nU", "6Cj", "42A", "5kX", "6NZ", "ce", "1Pv", "2N9", "MI", "7pW", "4UU", "4Gy", "5B9", "0i6", "1lv", "1BZ", "5A", "7LW", "4iU",
"4de", "6QF", "8q", "1Oj", "G4", "RU", "7oK", "4JI", "4EH", "64c", "2KE", "H5", "0PJ", "7p", "7Nf", "4kd", "4fT", "4s5", "2hY", "290",
"0sV", "Pd", "5M8", "4Hx", "6cY", "4Vz", "0mT", "Nf", "1F8", "0Cx", "4xV", "4m7", "7Pd", "41n", "0NH", "mz", "CV", "V7", "5Kk", "6ni",
"6ah", "4TK", "Y6", "LW", "20b", "0AI", "4zg", "6OD", "4b6", "4wW", "0Ly", "oK", "Ag", "0bU", "5IZ", "6lX", "9k", "1Np", "51V", "azN",
"7nQ", "4KS", "04u", "SO", "2Hn", "09E", "4Fc", "67H", "7MM", "4hO", "e2", "pS", "2iC", "j3", "4gN", "6Rm", "68I", "4Ib", "06D", "2Go",
"d4d", "82l", "4DR", "4Q3", "a1G", "bPM", "0QP", "6j", "0OR", "0Z3", "554", "40t", "4ZP", "4O1", "BL", "15W", "0lN", "2Ym", "6bC", "5GA",
"4yL", "6Lo", "aP", "09", "0Mc", "nQ", "6Cn", "42E", "4Xa", "6mB", "2Vl", "0cO", "8gg", "MM", "7pS", "4UQ", "bAN", "adL", "ca", "1Pr",
"G8", "RY", "7oG", "4JE", "4di", "6QJ", "2jd", "1Of", "0Rw", "5M", "480", "4iY", "4Gu", "5B5", "2Ix", "08S", "07R", "Ph", "5M4", "4Ht",
"4fX", "471", "1X6", "1MW", "0PF", "st", "7Nj", "4kh", "4ED", "64o", "2KI", "H9", "CZ", "14A", "5Kg", "6ne", "7Ph", "41b", "0ND", "mv",
"1F4", "0Ct", "4xZ", "6My", "5S6", "4Vv", "0mX", "Nj", "Ak", "0bY", "4Yw", "6lT", "6Bx", "43S", "0Lu", "oG", "bw", "0AE", "4zk", "6OH",
"6ad", "4TG", "0oi", "2ZJ", "7MA", "4hC", "0Sm", "4W", "2Hb", "09I", "4Fo", "67D", "aTn", "b5d", "04y", "SC", "9g", "8WE", "4es", "6PP",
"5o2", "4jr", "8XD", "6f", "1z0", "1oQ", "705", "65u", "68E", "4In", "06H", "Qr", "2iO", "1LM", "4gB", "6Ra", "5ia", "6Lc", "23E", "05",
"0lB", "Op", "6bO", "4Wl", "c4F", "aEm", "1d2", "0ar", "8FF", "ll", "558", "40x", "5kP", "6NR", "cm", "344", "0ns", "MA", "74W", "bon",
"4Xm", "6mN", "3FA", "0cC", "0Mo", "2xL", "6Cb", "42I", "4dm", "6QN", "8y", "1Ob", "05g", "2DL", "7oC", "4JA", "4Gq", "5B1", "d7G", "08W",
"0Rs", "5I", "484", "bSn", "52u", "475", "1X2", "1MS", "07V", "Pl", "5M0", "4Hp", "5Ua", "64k", "2KM", "1nO", "0PB", "7x", "7Nn", "4kl",
"7Pl", "41f", "8GX", "mr", "2UO", "14E", "5Kc", "6na", "5S2", "4Vr", "19u", "Nn", "1F0", "0Cp", "bBm", "ago", "ahn", "43W", "0Lq", "oC",
"Ao", "16t", "4Ys", "6lP", "75I", "4TC", "0om", "2ZN", "bs", "0AA", "4zo", "6OL", "2Hf", "09M", "4Fk", "6sH", "7ME", "4hG", "0Si", "4S",
"9c", "1Nx", "4ew", "6PT", "7nY", "bqh", "0pu", "SG", "1z4", "1oU", "4DZ", "65q", "5o6", "4jv", "0QX", "6b", "2iK", "1LI", "4gF", "6Re",
"68A", "4Ij", "06L", "Qv", "0lF", "Ot", "6bK", "4Wh", "4yD", "6Lg", "aX", "01", "0OZ", "lh", "5q4", "4tt", "4ZX", "4O9", "BD", "0av",
"0nw", "ME", "74S", "4UY", "5kT", "6NV", "ci", "1Pz", "0Mk", "nY", "6Cf", "42M", "4Xi", "6mJ", "2Vd", "0cG", "bL", "8Hf", "4zP", "4o1",
"75v", "606", "0oR", "0z3", "AP", "T1", "4YL", "6lo", "6BC", "43h", "0LN", "2ym", "22d", "0CO", "4xa", "6MB", "6cn", "4VM", "0mc", "NQ",
"Ca", "14z", "baN", "aDL", "7PS", "41Y", "8Gg", "mM", "247", "7G", "7NQ", "4kS", "com", "64T", "0k0", "1np", "E2", "PS", "69d", "4HO",
"4fc", "7Ca", "2hn", "1Ml", "0RL", "5v", "avS", "4ib", "4GN", "66e", "2IC", "J3", "05X", "Rb", "aUO", "b4E", "4dR", "4q3", "8F", "8Vd",
"4XV", "4M7", "1f8", "0cx", "0MT", "nf", "572", "42r", "5kk", "6Ni", "cV", "v7", "0nH", "Mz", "74l", "4Uf", "4Zg", "6oD", "2Tj", "0aI",
"y6", "lW", "6Ah", "40C", "5iZ", "583", "ag", "0BU", "0ly", "OK", "4B6", "4WW", "7lW", "4IU", "06s", "QI", "0I6", "1Lv", "4gy", "5b9",
"7OK", "4jI", "g4", "rU", "2Jh", "1oj", "4De", "65N", "7nf", "4Kd", "04B", "Sx", "2kE", "h5", "4eH", "6Pk", "5m8", "4hx", "0SV", "4l",
"2HY", "09r", "4FT", "4S5", "5Q8", "4Tx", "0oV", "Ld", "bH", "0Az", "4zT", "4o5", "6BG", "43l", "0LJ", "ox", "AT", "T5", "4YH", "6lk",
"6cj", "4VI", "0mg", "NU", "2vh", "0CK", "4xe", "6MF", "7PW", "4uU", "2n9", "mI", "Ce", "1pv", "5KX", "6nZ", "5UZ", "64P", "0k4", "1nt",
"0Py", "7C", "7NU", "4kW", "4fg", "6SD", "2hj", "1Mh", "E6", "PW", "7mI", "4HK", "4GJ", "66a", "2IG", "J7", "0RH", "5r", "7Ld", "4if",
"4dV", "4q7", "8B", "1OY", "0qT", "Rf", "7ox", "4Jz", "0MP", "nb", "576", "42v", "4XR", "4M3", "dll", "17U", "0nL", "3KN", "74h", "4Ub",
"5ko", "6Nm", "cR", "v3", "y2", "lS", "6Al", "40G", "4Zc", "aER", "2Tn", "0aM", "18T", "OO", "4B2", "4WS", "bCL", "587", "ac", "0BQ",
"0I2", "1Lr", "53T", "axL", "68z", "4IQ", "06w", "QM", "2Jl", "1on", "4Da", "65J", "7OO", "4jM", "g0", "6Y", "9X", "h1", "4eL", "6Po",
"7nb", "aA0", "04F", "2Em", "d6f", "09v", "4FP", "4S1", "a3E", "bRO", "0SR", "4h", "AX", "T9", "4YD", "6lg", "6BK", "4wh", "0LF", "ot",
"bD", "0Av", "4zX", "4o9", "5Q4", "4Tt", "0oZ", "Lh", "Ci", "14r", "5KT", "6nV", "ajh", "41Q", "0Nw", "mE", "22l", "0CG", "4xi", "6MJ",
"6cf", "4VE", "0mk", "NY", "07a", "2FJ", "69l", "4HG", "4fk", "6SH", "2hf", "1Md", "0Pu", "7O", "7NY", "bQh", "4Ew", "6pT", "0k8", "1nx",
"05P", "Rj", "5O6", "4Jv", "4dZ", "453", "8N", "1OU", "0RD", "qv", "7Lh", "4ij", "4GF", "66m", "2IK", "1lI", "5kc", "6Na", "21G", "27",
"8gX", "Mr", "74d", "4Un", "bbm", "79T", "1f0", "0cp", "397", "nn", "5s2", "42z", "4ys", "6LP", "ao", "366", "0lq", "OC", "76U", "bml",
"4Zo", "6oL", "Bs", "0aA", "0Om", "2zN", "7QA", "40K", "7OC", "4jA", "0Qo", "6U", "3ZA", "1ob", "4Dm", "65F", "68v", "b7f", "0rs", "QA",
"dSO", "8UG", "4gq", "5b1", "5m0", "4hp", "8ZF", "4d", "1x2", "09z", "727", "67w", "7nn", "4Kl", "04J", "Sp", "9T", "1NO", "51i", "6Pc",
"6BO", "43d", "0LB", "op", "2WM", "0bn", "5Ia", "6lc", "5Q0", "4Tp", "8fF", "Ll", "1D2", "0Ar", "cPN", "aem", "ajl", "41U", "0Ns", "mA",
"Cm", "14v", "5KP", "6nR", "6cb", "4VA", "0mo", "2XL", "22h", "0CC", "4xm", "6MN", "4fo", "6SL", "2hb", "8TY", "07e", "2FN", "69h", "4HC",
"4Es", "64X", "d5E", "83M", "0Pq", "7K", "a0f", "bQl", "50w", "457", "8J", "1OQ", "05T", "Rn", "5O2", "4Jr", "4GB", "66i", "2IO", "08d",
"1Ba", "5z", "7Ll", "4in", "0nD", "Mv", "7ph", "4Uj", "5kg", "6Ne", "cZ", "23", "0MX", "nj", "5s6", "4vv", "4XZ", "6my", "1f4", "0ct",
"0lu", "OG", "6bx", "5Gz", "4yw", "6LT", "ak", "0BY", "0Oi", "2zJ", "6Ad", "40O", "4Zk", "6oH", "Bw", "0aE", "2Jd", "1of", "4Di", "65B",
"7OG", "4jE", "g8", "6Q", "2ix", "1Lz", "4gu", "5b5", "68r", "4IY", "0rw", "QE", "1x6", "1mW", "4FX", "4S9", "5m4", "4ht", "0SZ", "ph",
"9P", "h9", "4eD", "6Pg", "7nj", "4Kh", "04N", "St", "22u", "375", "4xp", "598", "77V", "blo", "0mr", "1h2", "Cp", "14k", "5KM", "6nO",
"7PB", "41H", "0Nn", "3kl", "20D", "34", "4zA", "6Ob", "6aN", "4Tm", "0oC", "Lq", "AA", "0bs", "bcn", "78W", "569", "43y", "384", "om",
"9Kd", "5g", "5l3", "4is", "734", "66t", "1y1", "08y", "05I", "Rs", "7om", "4Jo", "4dC", "7AA", "8W", "1OL", "0Pl", "7V", "ats", "4kB",
"4En", "64E", "2Kc", "1na", "07x", "PB", "69u", "b6e", "4fr", "5c2", "dRL", "8TD", "4Zv", "6oU", "Bj", "0aX", "0Ot", "lF", "6Ay", "40R",
"4yj", "6LI", "av", "0BD", "0lh", "OZ", "6be", "4WF", "4XG", "6md", "2VJ", "0ci", "0ME", "nw", "6CH", "42c", "5kz", "6Nx", "cG", "1PT",
"0nY", "Mk", "5P7", "4Uw", "5N5", "4Ku", "04S", "Si", "9M", "1NV", "4eY", "440", "7Mk", "4hi", "0SG", "pu", "2HH", "K8", "4FE", "67n",
"68o", "4ID", "1", "QX", "2ie", "1Lg", "4gh", "6RK", "7OZ", "4jX", "0Qv", "6L", "2Jy", "3O9", "4Dt", "5A4", "4C9", "4VX", "0mv", "ND",
"22q", "0CZ", "4xt", "6MW", "7PF", "41L", "x9", "mX", "Ct", "14o", "5KI", "6nK", "6aJ", "4Ti", "0oG", "Lu", "bY", "30", "4zE", "6Of",
"5r5", "4wu", "380", "oi", "AE", "0bw", "4YY", "4L8", "5Wz", "66p", "1y5", "1lT", "0RY", "5c", "5l7", "4iw", "4dG", "6Qd", "8S", "1OH",
"05M", "Rw", "7oi", "4Jk", "4Ej", "64A", "2Kg", "1ne", "0Ph", "7R", "7ND", "4kF", "4fv", "5c6", "0H9", "1My", "0st", "PF", "69q", "4HZ",
"0Op", "lB", "ako", "40V", "4Zr", "6oQ", "Bn", "15u", "0ll", "2YO", "6ba", "4WB", "4yn", "6LM", "ar", "1Ra", "0MA", "ns", "6CL", "42g",
"4XC", "79I", "2VN", "0cm", "8gE", "Mo", "5P3", "4Us", "bAl", "adn", "cC", "1PP", "9I", "1NR", "51t", "444", "5N1", "4Kq", "04W", "Sm",
"2HL", "09g", "4FA", "67j", "7Mo", "4hm", "0SC", "4y", "2ia", "1Lc", "4gl", "6RO", "68k", "5Ya", "5", "2GM", "d4F", "82N", "4Dp", "5A0",
"a1e", "bPo", "0Qr", "6H", "Cx", "14c", "5KE", "6nG", "7PJ", "4uH", "x5", "mT", "0V7", "0CV", "4xx", "590", "4C5", "4VT", "0mz", "NH",
"AI", "16R", "4YU", "4L4", "561", "43q", "0LW", "oe", "bU", "w4", "4zI", "6Oj", "6aF", "4Te", "0oK", "Ly", "05A", "2Dj", "7oe", "4Jg",
"4dK", "6Qh", "2jF", "i6", "0RU", "5o", "7Ly", "5yZ", "4GW", "4R6", "1y9", "08q", "07p", "PJ", "7mT", "4HV", "4fz", "6SY", "0H5", "1Mu",
"f7", "sV", "7NH", "4kJ", "4Ef", "64M", "2Kk", "1ni", "4yb", "6LA", "23g", "0BL", "Z3", "OR", "6bm", "4WN", "c4d", "aEO", "Bb", "0aP",
"8Fd", "lN", "4a3", "40Z", "5kr", "4n2", "cO", "8Ie", "0nQ", "Mc", "74u", "615", "4XO", "6ml", "2VB", "U2", "0MM", "2xn", "7Sa", "42k",
"7Mc", "4ha", "0SO", "4u", "3Xa", "K0", "4FM", "67f", "aTL", "b5F", "0pS", "Sa", "9E", "8Wg", "4eQ", "448", "7OR", "4jP", "254", "6D",
"0j3", "1os", "cnn", "65W", "68g", "4IL", "9", "QP", "2im", "1Lo", "53I", "6RC", "7PN", "41D", "x1", "mP", "2Um", "14g", "5KA", "6nC",
"4C1", "4VP", "19W", "NL", "0V3", "0CR", "bBO", "594", "565", "43u", "0LS", "oa", "AM", "16V", "4YQ", "4L0", "6aB", "4Ta", "0oO", "2Zl",
"bQ", "38", "4zM", "6On", "4dO", "6Ql", "2jB", "i2", "05E", "2Dn", "7oa", "4Jc", "4GS", "4R2", "d7e", "08u", "0RQ", "5k", "a2F", "bSL",
"52W", "ayO", "0H1", "1Mq", "07t", "PN", "69y", "4HR", "4Eb", "64I", "2Ko", "1nm", "f3", "7Z", "7NL", "4kN", "Z7", "OV", "6bi", "4WJ",
"4yf", "6LE", "az", "0BH", "0Ox", "lJ", "4a7", "4tV", "4Zz", "6oY", "Bf", "0aT", "0nU", "Mg", "74q", "5EZ", "5kv", "4n6", "cK", "1PX",
"0MI", "2xj", "6CD", "42o", "4XK", "6mh", "2VF", "U6", "2HD", "K4", "4FI", "67b", "7Mg", "4he", "0SK", "4q", "9A", "1NZ", "4eU", "4p4",
"5N9", "4Ky", "0pW", "Se", "0j7", "1ow", "4Dx", "5A8", "7OV", "4jT", "0Qz", "rH", "2ii", "1Lk", "4gd", "6RG", "68c", "4IH", "D5", "QT",
"5Ls", "4I3", "F", "13U", "0IP", "jb", "536", "46v", "5oo", "6Jm", "gR", "r3", "0jL", "3ON", "6dA", "4Qb", "5NB", "aAR", "2Pn", "0eM",
"0Ka", "hS", "6El", "44G", "49w", "abN", "ec", "0FQ", "8ae", "KO", "4F2", "4SS", "4X0", "4MQ", "02w", "UM", "0M2", "0XS", "57T", "a8D",
"7KO", "4nM", "c0", "2Y", "2Nl", "1kn", "aJ1", "61J", "6zC", "aE0", "00F", "2Am", "yP", "l1", "4aL", "6To", "a7E", "58U", "0WR", "0h",
"ZL", "84n", "4BP", "4W1", "fH", "0Ez", "5nu", "4k5", "5U8", "4Px", "0kV", "Hd", "ET", "P5", "5Mi", "6hk", "6FG", "47l", "0HJ", "kx",
"dy", "0GK", "48m", "6IF", "6gj", "4RI", "0ig", "JU", "Ge", "0dW", "5OX", "5Z9", "4d4", "4qU", "1ZZ", "iI", "0Ty", "3C", "4z6", "4oW",
"5QZ", "60P", "Yg", "0zU", "A6", "TW", "6yh", "4LK", "4bg", "6WD", "2lj", "0YI", "0VH", "1r", "6XE", "4mf", "4CJ", "62a", "2MG", "N7",
"0uT", "Vf", "7kx", "4Nz", "5pw", "4u7", "xJ", "1KY", "0IT", "jf", "532", "46r", "5Lw", "4I7", "B", "0gx", "0jH", "Iz", "6dE", "4Qf",
"5ok", "6Ji", "gV", "r7", "0Ke", "hW", "6Eh", "44C", "5NF", "6kD", "2Pj", "0eI", "0hy", "KK", "4F6", "4SW", "49s", "6HX", "eg", "0FU",
"0M6", "0XW", "4cy", "5f9", "4X4", "4MU", "02s", "UI", "Xy", "1kj", "5PD", "61N", "7KK", "4nI", "c4", "vU", "yT", "l5", "4aH", "6Tk",
"6zG", "4Od", "00B", "Wx", "ZH", "0yz", "4BT", "4W5", "5i8", "4lx", "0WV", "0l", "71v", "646", "0kR", "3NP", "fL", "8Lf", "5nq", "4k1",
"6FC", "47h", "0HN", "29e", "EP", "P1", "5Mm", "6ho", "6gn", "4RM", "0ic", "JQ", "26d", "0GO", "48i", "6IB", "4d0", "45Y", "8Cg", "iM",
"Ga", "0dS", "beN", "hYu", "ckm", "60T", "Yc", "0zQ", "207", "3G", "4z2", "4oS", "4bc", "7Ga", "2ln", "0YM", "A2", "TS", "6yl", "4LO",
"4CN", "62e", "2MC", "N3", "0VL", "1v", "6XA", "4mb", "5ps", "4u3", "xN", "8Rd", "01X", "Vb", "aQO", "b0E", "5og", "6Je", "gZ", "63",
"0jD", "Iv", "6dI", "4Qj", "7l9", "6iy", "N", "0gt", "0IX", "jj", "5w6", "4rv", "5mV", "5x7", "ek", "0FY", "0hu", "KG", "6fx", "5Cz",
"5NJ", "6kH", "Fw", "0eE", "92", "3nk", "6Ed", "44O", "7KG", "4nE", "c8", "2Q", "Xu", "1kf", "5PH", "61B", "4X8", "4MY", "0vw", "UE",
"2mx", "1Hz", "4cu", "5f5", "5i4", "4lt", "0WZ", "th", "ZD", "0yv", "4BX", "4W9", "6zK", "4Oh", "00N", "Wt", "yX", "l9", "4aD", "6Tg",
"2SM", "0fn", "5Ma", "6hc", "6FO", "47d", "0HB", "kp", "24Y", "0Er", "bDo", "aam", "5U0", "4Pp", "8bF", "Hl", "Gm", "10v", "5OP", "5Z1",
"anl", "45U", "0Js", "iA", "dq", "0GC", "48e", "6IN", "6gb", "4RA", "0io", "3Lm", "03e", "2BN", "7iA", "4LC", "4bo", "6WL", "zs", "0YA",
"0Tq", "3K", "a4f", "bUl", "4As", "5D3", "Yo", "87M", "01T", "Vn", "5K2", "4Nr", "54w", "417", "xB", "1KQ", "1Fa", "1z", "6XM", "4mn",
"4CB", "62i", "2MO", "0xl", "1za", "Ir", "6dM", "4Qn", "5oc", "6Ja", "25G", "67", "9Pe", "jn", "5w2", "46z", "bfm", "aCo", "J", "0gp",
"0hq", "KC", "72U", "bil", "5mR", "5x3", "eo", "326", "96", "3no", "7UA", "44K", "5NN", "6kL", "Fs", "0eA", "Xq", "1kb", "5PL", "61F",
"7KC", "4nA", "0Uo", "2U", "39U", "8QG", "4cq", "5f1", "aRl", "796", "0vs", "UA", "2LQ", "0yr", "767", "63w", "5i0", "4lp", "9Ng", "0d",
"2oM", "0Zn", "55i", "6Tc", "6zO", "4Ol", "00J", "Wp", "6FK", "4sh", "0HF", "kt", "EX", "P9", "5Me", "6hg", "5U4", "4Pt", "0kZ", "Hh",
"fD", "0Ev", "5ny", "4k9", "4d8", "45Q", "0Jw", "iE", "Gi", "10r", "5OT", "5Z5", "6gf", "4RE", "0ik", "JY", "du", "0GG", "48a", "6IJ",
"4bk", "6WH", "zw", "0YE", "03a", "2BJ", "6yd", "4LG", "4Aw", "5D7", "Yk", "0zY", "0Tu", "3O", "6Zx", "bUh", "54s", "413", "xF", "1KU",
"01P", "Vj", "5K6", "4Nv", "4CF", "62m", "2MK", "0xh", "0VD", "uv", "6XI", "4mj", "5NS", "6kQ", "Fn", "11u", "0Kp", "hB", "aoo", "44V",
"49f", "6HM", "er", "1Va", "0hl", "3Mn", "6fa", "4SB", "5Lb", "7yA", "W", "0gm", "0IA", "js", "6GL", "46g", "bEl", "hyW", "gC", "0Dq",
"8cE", "Io", "5T3", "4Qs", "5J1", "4Oq", "00W", "Wm", "yA", "0Zs", "55t", "404", "6YN", "4lm", "0WC", "0y", "2LL", "0yo", "4BA", "63j",
"6xc", "bws", "02f", "2CM", "2ma", "0XB", "4cl", "6VO", "a5e", "bTo", "0Ur", "2H", "Xl", "86N", "5PQ", "5E0", "dh", "0GZ", "5lU", "5y4",
"4G9", "4RX", "0iv", "JD", "Gt", "0dF", "5OI", "6jK", "6Dg", "45L", "81", "iX", "fY", "70", "5nd", "6Kf", "6eJ", "4Pi", "0kG", "Hu",
"EE", "0fw", "5Mx", "4H8", "5v5", "4su", "1Xz", "ki", "0VY", "1c", "5h7", "4mw", "5Sz", "62p", "2MV", "0xu", "01M", "Vw", "7ki", "4Nk",
"54n", "6Ud", "2nJ", "1KH", "0Th", "3R", "6Ze", "4oF", "4Aj", "60A", "Yv", "0zD", "0wt", "TF", "6yy", "4LZ", "4bv", "5g6", "zj", "0YX",
"0Kt", "hF", "6Ey", "44R", "5NW", "6kU", "Fj", "0eX", "0hh", "KZ", "6fe", "4SF", "49b", "6HI", "ev", "0FD", "0IE", "jw", "6GH", "46c",
"5Lf", "6id", "S", "0gi", "0jY", "Ik", "5T7", "4Qw", "5oz", "6Jx", "gG", "0Du", "yE", "0Zw", "4aY", "400", "5J5", "4Ou", "00S", "Wi",
"ZY", "O8", "4BE", "63n", "6YJ", "4li", "0WG", "tu", "2me", "0XF", "4ch", "6VK", "6xg", "4MD", "02b", "UX", "Xh", "3K9", "5PU", "5E4",
"7KZ", "4nX", "0Uv", "2L", "73V", "bho", "0ir", "1l2", "dl", "335", "48x", "5y0", "6Dc", "45H", "85", "3ol", "Gp", "0dB", "5OM", "6jO",
"6eN", "4Pm", "0kC", "Hq", "24D", "74", "bDr", "6Kb", "529", "47y", "8AG", "km", "EA", "0fs", "bgn", "aBl", "774", "62t", "199", "0xq",
"9Od", "1g", "5h3", "4ms", "54j", "7EA", "2nN", "1KL", "01I", "Vs", "7km", "4No", "4An", "60E", "Yr", "1ja", "0Tl", "3V", "6Za", "4oB",
"4br", "5g2", "zn", "8PD", "03x", "TB", "aSo", "785", "49n", "6HE", "ez", "0FH", "0hd", "KV", "6fi", "4SJ", "bdI", "6kY", "Ff", "0eT",
"0Kx", "hJ", "4e7", "4pV", "5ov", "4j6", "gK", "0Dy", "0jU", "Ig", "6dX", "5AZ", "5Lj", "6ih", "DW", "Q6", "0II", "28b", "6GD", "46o",
"6YF", "4le", "0WK", "0q", "ZU", "O4", "4BI", "63b", "5J9", "4Oy", "0tW", "We", "yI", "1JZ", "4aU", "4t4", "7KV", "4nT", "0Uz", "vH",
"Xd", "1kw", "5PY", "5E8", "6xk", "4MH", "02n", "UT", "2mi", "0XJ", "4cd", "6VG", "2Qm", "0dN", "5OA", "6jC", "6Do", "45D", "89", "iP",
"0R3", "0GR", "48t", "acM", "4G1", "4RP", "94O", "JL", "EM", "12V", "5Mp", "4H0", "525", "47u", "0HS", "ka", "fQ", "78", "5nl", "6Kn",
"6eB", "4Pa", "0kO", "3NM", "01E", "3PO", "7ka", "4Nc", "54f", "6Ul", "xS", "m2", "0VQ", "1k", "a6F", "59V", "4CS", "4V2", "195", "85m",
"03t", "TN", "4Y3", "4LR", "56W", "a9G", "zb", "0YP", "b3", "3Z", "6Zm", "4oN", "4Ab", "60I", "2Oo", "0zL", "1xA", "KR", "6fm", "4SN",
"49j", "6HA", "27g", "0FL", "8Bd", "hN", "4e3", "44Z", "bdM", "aAO", "Fb", "0eP", "0jQ", "Ic", "70u", "655", "5or", "4j2", "gO", "8Me",
"0IM", "28f", "7Wa", "46k", "5Ln", "6il", "DS", "Q2", "ZQ", "O0", "4BM", "63f", "6YB", "4la", "0WO", "0u", "yM", "8Sg", "4aQ", "408",
"aPL", "b1F", "0tS", "Wa", "0n3", "1ks", "bzO", "61W", "7KR", "4nP", "214", "2D", "2mm", "0XN", "57I", "6VC", "6xo", "4ML", "02j", "UP",
"6Dk", "4qH", "0Jf", "iT", "Gx", "0dJ", "5OE", "6jG", "4G5", "4RT", "0iz", "JH", "dd", "0GV", "48p", "5y8", "521", "47q", "0HW", "ke",
"EI", "12R", "5Mt", "4H4", "6eF", "4Pe", "0kK", "Hy", "fU", "s4", "5nh", "6Kj", "54b", "6Uh", "xW", "m6", "01A", "3PK", "7ke", "4Ng",
"4CW", "4V6", "191", "0xy", "0VU", "1o", "6XX", "59R", "4bz", "6WY", "zf", "0YT", "03p", "TJ", "4Y7", "4LV", "4Af", "60M", "Yz", "0zH",
"b7", "wV", "6Zi", "4oJ", "5H3", "4Ms", "02U", "Uo", "2mR", "0Xq", "57v", "426", "7Km", "4no", "0UA", "vs", "2NN", "1kL", "5Pb", "61h",
"6za", "4OB", "00d", "2AO", "yr", "1Ja", "4an", "6TM", "a7g", "58w", "0Wp", "0J", "Zn", "84L", "4Br", "5G2", "5LQ", "5Y0", "d", "13w",
"0Ir", "1L2", "amm", "46T", "5oM", "6JO", "gp", "0DB", "0jn", "3Ol", "6dc", "5Aa", "bdr", "6kb", "2PL", "0eo", "0KC", "hq", "6EN", "44e",
"49U", "abl", "eA", "0Fs", "8aG", "Km", "5V1", "4Sq", "1Dz", "3a", "5j5", "4ou", "4AY", "4T8", "YE", "0zw", "03O", "Tu", "6yJ", "4Li",
"4bE", "6Wf", "zY", "o8", "0Vj", "1P", "6Xg", "4mD", "4Ch", "62C", "2Me", "0xF", "0uv", "VD", "7kZ", "4NX", "5pU", "5e4", "xh", "3k9",
"fj", "0EX", "5nW", "6KU", "6ey", "4PZ", "0kt", "HF", "Ev", "0fD", "5MK", "6hI", "6Fe", "47N", "0Hh", "kZ", "26B", "52", "48O", "6Id",
"6gH", "4Rk", "0iE", "Jw", "GG", "0du", "5Oz", "6jx", "5t7", "4qw", "0JY", "ik", "2mV", "0Xu", "57r", "422", "5H7", "4Mw", "02Q", "Uk",
"2NJ", "1kH", "5Pf", "61l", "7Ki", "4nk", "0UE", "vw", "yv", "0ZD", "4aj", "6TI", "6ze", "4OF", "0th", "WZ", "Zj", "0yX", "4Bv", "5G6",
"6Yy", "4lZ", "0Wt", "0N", "0Iv", "jD", "4g9", "46P", "5LU", "5Y4", "Dh", "0gZ", "0jj", "IX", "6dg", "4QD", "5oI", "6JK", "gt", "0DF",
"0KG", "hu", "6EJ", "44a", "5Nd", "6kf", "FY", "S8", "1xz", "Ki", "5V5", "4Su", "49Q", "4h8", "eE", "0Fw", "756", "60v", "YA", "0zs",
"9Mf", "3e", "5j1", "4oq", "4bA", "6Wb", "2lL", "0Yo", "03K", "Tq", "6yN", "4Lm", "4Cl", "62G", "2Ma", "0xB", "0Vn", "1T", "6Xc", "59i",
"54Y", "5e0", "xl", "8RF", "01z", "1p2", "aQm", "b0g", "71T", "bjm", "0kp", "HB", "fn", "317", "5nS", "6KQ", "6Fa", "47J", "0Hl", "29G",
"Er", "12i", "5MO", "6hM", "6gL", "4Ro", "0iA", "Js", "26F", "56", "48K", "7YA", "5t3", "4qs", "8CE", "io", "GC", "0dq", "bel", "hYW",
"7Ke", "4ng", "0UI", "2s", "XW", "M6", "5Pj", "6uh", "6xX", "6m9", "0vU", "Ug", "2mZ", "0Xy", "4cW", "4v6", "4y7", "4lV", "0Wx", "0B",
"Zf", "0yT", "4Bz", "63Q", "6zi", "4OJ", "B7", "WV", "yz", "0ZH", "4af", "6TE", "5oE", "6JG", "gx", "0DJ", "0jf", "IT", "6dk", "4QH",
"5LY", "5Y8", "l", "0gV", "0Iz", "jH", "4g5", "4rT", "5mt", "4h4", "eI", "1VZ", "0hW", "Ke", "5V9", "4Sy", "5Nh", "6kj", "FU", "S4",
"0KK", "hy", "6EF", "44m", "03G", "2Bl", "6yB", "4La", "4bM", "6Wn", "zQ", "o0", "0TS", "3i", "a4D", "bUN", "4AQ", "4T0", "YM", "87o",
"01v", "VL", "7kR", "4NP", "54U", "hft", "0N3", "1Ks", "0Vb", "1X", "6Xo", "4mL", "5SA", "62K", "2Mm", "0xN", "2So", "0fL", "5MC", "6hA",
"6Fm", "47F", "1XA", "kR", "fb", "0EP", "bDM", "aaO", "4E3", "4PR", "8bd", "HN", "GO", "10T", "5Or", "4J2", "507", "45w", "0JQ", "ic",
"dS", "q2", "48G", "6Il", "73i", "4Rc", "0iM", "3LO", "XS", "M2", "5Pn", "61d", "7Ka", "4nc", "0UM", "2w", "39w", "8Qe", "4cS", "4v2",
"aRN", "b3D", "02Y", "Uc", "Zb", "0yP", "bxM", "63U", "4y3", "4lR", "236", "0F", "2oo", "0ZL", "4ab", "6TA", "6zm", "4ON", "B3", "WR",
"0jb", "IP", "6do", "4QL", "5oA", "6JC", "25e", "0DN", "9PG", "jL", "4g1", "46X", "686", "aCM", "h", "0gR", "0hS", "Ka", "72w", "677",
"49Y", "4h0", "eM", "8Og", "0KO", "3nM", "6EB", "44i", "5Nl", "6kn", "FQ", "S0", "4bI", "6Wj", "zU", "o4", "03C", "Ty", "6yF", "4Le",
"4AU", "4T4", "YI", "1jZ", "0TW", "3m", "5j9", "4oy", "54Q", "5e8", "xd", "1Kw", "01r", "VH", "7kV", "4NT", "4Cd", "62O", "2Mi", "0xJ",
"0Vf", "uT", "6Xk", "4mH", "6Fi", "47B", "0Hd", "kV", "Ez", "0fH", "5MG", "6hE", "4E7", "4PV", "0kx", "HJ", "ff", "0ET", "bDI", "6KY",
"503", "45s", "0JU", "ig", "GK", "0dy", "5Ov", "4J6", "6gD", "4Rg", "0iI", "3LK", "dW", "q6", "48C", "6Ih", "4Z2", "4OS", "00u", "WO",
"yc", "0ZQ", "55V", "hgw", "6Yl", "4lO", "a2", "tS", "2Ln", "0yM", "4Bc", "63H", "6xA", "4Mb", "02D", "2Co", "2mC", "n3", "4cN", "6Vm",
"a5G", "bTM", "0UP", "2j", "XN", "86l", "5Ps", "4U3", "5Nq", "4K1", "FL", "11W", "0KR", "3nP", "514", "44t", "49D", "6Ho", "eP", "49",
"0hN", "3ML", "6fC", "5CA", "aV1", "6iB", "u", "0gO", "0Ic", "jQ", "6Gn", "46E", "bEN", "hyu", "ga", "0DS", "8cg", "IM", "4D0", "4QQ",
"1FZ", "1A", "4x4", "4mU", "4Cy", "5F9", "0m6", "0xW", "C4", "VU", "7kK", "4NI", "54L", "6UF", "xy", "1Kj", "0TJ", "3p", "6ZG", "4od",
"4AH", "60c", "YT", "L5", "0wV", "Td", "5I8", "4Lx", "4bT", "4w5", "zH", "0Yz", "dJ", "0Gx", "5lw", "4i7", "6gY", "4Rz", "0iT", "Jf",
"GV", "R7", "5Ok", "6ji", "6DE", "45n", "0JH", "iz", "24b", "0EI", "5nF", "6KD", "6eh", "4PK", "0ke", "HW", "Eg", "0fU", "5MZ", "6hX",
"4f6", "4sW", "0Hy", "kK", "yg", "0ZU", "55R", "6TX", "4Z6", "4OW", "00q", "WK", "2Lj", "0yI", "4Bg", "63L", "6Yh", "4lK", "a6", "tW",
"2mG", "n7", "4cJ", "6Vi", "6xE", "4Mf", "0vH", "Uz", "XJ", "1kY", "5Pw", "4U7", "7Kx", "4nz", "0UT", "2n", "0KV", "hd", "510", "44p",
"5Nu", "4K5", "FH", "0ez", "0hJ", "Kx", "6fG", "4Sd", "5mi", "6Hk", "eT", "p5", "0Ig", "jU", "6Gj", "46A", "5LD", "6iF", "q", "0gK",
"1zZ", "II", "4D4", "4QU", "5oX", "5z9", "ge", "0DW", "byN", "62V", "0m2", "0xS", "225", "1E", "4x0", "4mQ", "54H", "6UB", "2nl", "1Kn",
"C0", "VQ", "7kO", "4NM", "4AL", "60g", "YP", "L1", "0TN", "3t", "6ZC", "ae0", "4bP", "439", "zL", "8Pf", "03Z", "0b3", "aSM", "b2G",
"73t", "664", "0iP", "Jb", "dN", "8Nd", "48Z", "4i3", "6DA", "45j", "0JL", "3oN", "GR", "R3", "5Oo", "6jm", "6el", "4PO", "0ka", "HS",
"24f", "0EM", "5nB", "aaR", "4f2", "4sS", "8Ae", "kO", "Ec", "0fQ", "695", "aBN", "6Yd", "4lG", "0Wi", "0S", "Zw", "0yE", "4Bk", "6wH",
"6zx", "buh", "0tu", "WG", "yk", "0ZY", "4aw", "5d7", "5k6", "4nv", "0UX", "2b", "XF", "1kU", "741", "61q", "6xI", "4Mj", "02L", "Uv",
"2mK", "0Xh", "4cF", "6Ve", "49L", "6Hg", "eX", "41", "0hF", "Kt", "6fK", "4Sh", "5Ny", "4K9", "FD", "0ev", "0KZ", "hh", "5u4", "4pt",
"5oT", "5z5", "gi", "1Tz", "0jw", "IE", "4D8", "4QY", "5LH", "6iJ", "Du", "0gG", "0Ik", "jY", "6Gf", "46M", "01g", "3Pm", "7kC", "4NA",
"54D", "6UN", "xq", "1Kb", "0Vs", "1I", "a6d", "59t", "4Cq", "5F1", "d3G", "85O", "03V", "Tl", "5I0", "4Lp", "56u", "435", "2lQ", "0Yr",
"0TB", "3x", "6ZO", "4ol", "5Qa", "60k", "2OM", "0zn", "2QO", "0dl", "5Oc", "6ja", "6DM", "45f", "1Za", "ir", "dB", "0Gp", "48V", "aco",
"5W2", "4Rr", "94m", "Jn", "Eo", "12t", "5MR", "5X3", "aln", "47W", "0Hq", "kC", "fs", "0EA", "5nN", "6KL", "71I", "4PC", "0km", "3No",
"Zs", "0yA", "4Bo", "63D", "7IA", "4lC", "0Wm", "0W", "yo", "8SE", "4as", "5d3", "aPn", "b1d", "00y", "WC", "XB", "1kQ", "745", "61u",
"5k2", "4nr", "9Le", "2f", "2mO", "0Xl", "4cB", "6Va", "6xM", "4Mn", "02H", "Ur", "0hB", "Kp", "6fO", "4Sl", "49H", "6Hc", "27E", "45",
"8BF", "hl", "518", "44x", "bdo", "aAm", "2PQ", "0er", "0js", "IA", "70W", "bkn", "5oP", "5z1", "gm", "304", "0Io", "28D", "6Gb", "46I",
"5LL", "6iN", "y", "0gC", "5pH", "6UJ", "xu", "1Kf", "C8", "VY", "7kG", "4NE", "4Cu", "5F5", "2Mx", "1hz", "0Vw", "1M", "4x8", "4mY",
"4bX", "431", "zD", "0Yv", "03R", "Th", "5I4", "4Lt", "4AD", "60o", "YX", "L9", "0TF", "wt", "6ZK", "4oh", "6DI", "45b", "0JD", "iv",
"GZ", "0dh", "5Og", "6je", "5W6", "4Rv", "0iX", "Jj", "dF", "0Gt", "48R", "6Iy", "6Fx", "47S", "0Hu", "kG", "Ek", "0fY", "5MV", "5X7",
"6ed", "4PG", "0ki", "3Nk", "fw", "0EE", "5nJ", "6KH", "356", "bo", "6OP", "4zs", "bnl", "75U", "LC", "0oq", "0bA", "As", "6lL", "4Yo",
"43K", "7RA", "2yN", "0Lm", "17", "22G", "6Ma", "4xB", "4Vn", "6cM", "Nr", "19i", "14Y", "CB", "aDo", "bam", "41z", "5p2", "mn", "8GD",
"7d", "8YF", "4kp", "5n0", "64w", "717", "1nS", "2KQ", "Pp", "07J", "4Hl", "69G", "6Sc", "52i", "1MO", "2hM", "5U", "0Ro", "4iA", "7LC",
"66F", "4Gm", "08K", "3YA", "RA", "0qs", "b4f", "aUl", "5a1", "4dq", "8VG", "8e", "6mV", "4Xu", "17r", "022", "nE", "0Mw", "42Q", "4c8",
"6NJ", "5kH", "1Pf", "cu", "MY", "X8", "4UE", "74O", "6og", "4ZD", "W9", "BX", "lt", "0OF", "4th", "6AK", "4l9", "4yX", "0Bv", "aD",
"Oh", "0lZ", "4Wt", "5R4", "4Iv", "5L6", "Qj", "06P", "1LU", "1Y4", "463", "4gZ", "4jj", "7Oh", "rv", "0QD", "1oI", "2JK", "65m", "4DF",
"4KG", "7nE", "2EJ", "04a", "1Nd", "2kf", "6PH", "4ek", "5xz", "492", "4O", "0Su", "09Q", "0h8", "5C7", "4Fw", "5Dz", "6ax", "LG", "0ou",
"0AY", "bk", "6OT", "4zw", "43O", "6Bd", "2yJ", "0Li", "0bE", "Aw", "6lH", "4Yk", "4Vj", "6cI", "Nv", "0mD", "13", "22C", "6Me", "4xF",
"4uv", "5p6", "mj", "0NX", "1pU", "CF", "6ny", "7k9", "4P9", "4EX", "1nW", "2KU", "sh", "0PZ", "4kt", "5n4", "6Sg", "4fD", "k9", "2hI",
"Pt", "07N", "4Hh", "69C", "66B", "4Gi", "08O", "2Id", "5Q", "d8", "4iE", "7LG", "5a5", "4du", "1Oz", "8a", "RE", "0qw", "4JY", "aUh",
"nA", "0Ms", "42U", "ail", "6mR", "4Xq", "17v", "026", "3Km", "0no", "4UA", "74K", "6NN", "5kL", "1Pb", "cq", "lp", "0OB", "40d", "6AO",
"6oc", "5Ja", "0an", "2TM", "Ol", "18w", "4Wp", "5R0", "afm", "bCo", "0Br", "1G2", "1LQ", "1Y0", "467", "53w", "4Ir", "5L2", "Qn", "06T",
"1oM", "2JO", "65i", "4DB", "4jn", "7Ol", "6z", "1Aa", "8WY", "2kb", "6PL", "4eo", "4KC", "7nA", "2EN", "04e", "09U", "d6E", "5C3", "4Fs",
"bRl", "496", "4K", "0Sq", "0bI", "2Wj", "6lD", "4Yg", "43C", "6Bh", "oW", "z6", "0AU", "bg", "6OX", "5jZ", "4TW", "4A6", "LK", "0oy",
"14Q", "CJ", "4N7", "5Kw", "41r", "542", "mf", "0NT", "u7", "22O", "6Mi", "4xJ", "4Vf", "6cE", "Nz", "0mH", "Px", "07B", "4Hd", "69O",
"6Sk", "4fH", "k5", "2hE", "7l", "0PV", "4kx", "5n8", "4P5", "4ET", "83j", "2KY", "RI", "05s", "4JU", "7oW", "5a9", "4dy", "1Ov", "8m",
"qU", "d4", "4iI", "7LK", "66N", "4Ge", "08C", "2Ih", "6NB", "a59", "1Pn", "21d", "MQ", "X0", "4UM", "74G", "79w", "bbN", "0cS", "0v2",
"nM", "8Dg", "42Y", "4c0", "4l1", "4yP", "8Kf", "aL", "0y3", "0lR", "636", "76v", "6oo", "4ZL", "W1", "BP", "2zm", "0ON", "40h", "6AC",
"4jb", "auS", "6v", "0QL", "I3", "2JC", "65e", "4DN", "b7E", "68U", "Qb", "06X", "286", "dSl", "4r3", "4gR", "4hS", "7MQ", "4G", "277",
"09Y", "0h0", "67T", "b8D", "4KO", "7nM", "SS", "F2", "1Nl", "9w", "azR", "4ec", "43G", "6Bl", "oS", "z2", "0bM", "2Wn", "78i", "4Yc",
"4TS", "4A2", "LO", "8fe", "0AQ", "bc", "aeN", "cPm", "41v", "546", "mb", "0NP", "14U", "CN", "4N3", "5Ks", "4Vb", "6cA", "2Xo", "0mL",
"u3", "22K", "6Mm", "4xN", "6So", "4fL", "k1", "2hA", "2Fm", "07F", "5XA", "69K", "4P1", "4EP", "83n", "d5f", "7h", "0PR", "bQO", "a0E",
"hbu", "50T", "1Or", "8i", "RM", "05w", "4JQ", "7oS", "66J", "4Ga", "08G", "2Il", "5Y", "d0", "4iM", "7LO", "MU", "X4", "4UI", "74C",
"6NF", "5kD", "1Pj", "cy", "nI", "2m9", "4vU", "4c4", "6mZ", "4Xy", "0cW", "0v6", "Od", "0lV", "4Wx", "5R8", "4l5", "4yT", "0Bz", "aH",
"lx", "0OJ", "40l", "6AG", "6ok", "4ZH", "W5", "BT", "I7", "2JG", "65a", "4DJ", "4jf", "7Od", "6r", "0QH", "1LY", "1Y8", "4r7", "4gV",
"4Iz", "68Q", "Qf", "0rT", "1mt", "0h4", "67P", "5VZ", "4hW", "7MU", "4C", "0Sy", "1Nh", "9s", "6PD", "4eg", "4KK", "7nI", "SW", "F6",
"8Je", "22V", "4m2", "4xS", "625", "77u", "Nc", "0mQ", "V2", "CS", "6nl", "5Kn", "41k", "7Pa", "3kO", "0NM", "0AL", "20g", "6OA", "4zb",
"4TN", "6am", "LR", "Y3", "0bP", "Ab", "78t", "bcM", "43Z", "4b3", "oN", "8Ed", "5D", "264", "4iP", "489", "66W", "b9G", "08Z", "0i3",
"RP", "G1", "4JL", "7oN", "6QC", "50I", "1Oo", "8t", "7u", "0PO", "4ka", "7Nc", "64f", "4EM", "H0", "963", "Pa", "0sS", "b6F", "69V",
"478", "4fQ", "295", "dRo", "4O4", "4ZU", "15R", "BI", "le", "0OW", "40q", "551", "6Lj", "4yI", "t4", "aU", "Oy", "0lK", "4We", "6bF",
"6mG", "4Xd", "0cJ", "2Vi", "nT", "0Mf", "4vH", "6Ck", "adI", "5kY", "1Pw", "cd", "MH", "0nz", "4UT", "7pV", "4KV", "7nT", "SJ", "04p",
"1Nu", "9n", "6PY", "4ez", "4hJ", "7MH", "pV", "e7", "1mi", "2Hk", "67M", "4Ff", "4Ig", "68L", "2Gj", "06A", "j6", "2iF", "6Rh", "4gK",
"5zZ", "7Oy", "6o", "0QU", "1oX", "1z9", "4Q6", "4DW", "5FZ", "6cX", "Ng", "0mU", "0Cy", "1F9", "4m6", "4xW", "41o", "7Pe", "3kK", "0NI",
"V6", "CW", "6nh", "5Kj", "4TJ", "6ai", "LV", "Y7", "0AH", "bz", "6OE", "4zf", "4wV", "4b7", "oJ", "0Lx", "0bT", "Af", "6lY", "4Yz",
"5B8", "4Gx", "1lw", "0i7", "qH", "0Rz", "4iT", "7LV", "6QG", "4dd", "1Ok", "8p", "RT", "G5", "4JH", "7oJ", "64b", "4EI", "H4", "2KD",
"7q", "0PK", "4ke", "7Ng", "4s4", "4fU", "1MZ", "2hX", "Pe", "0sW", "4Hy", "5M9", "la", "0OS", "40u", "555", "4O0", "4ZQ", "15V", "BM",
"2Yl", "0lO", "4Wa", "6bB", "6Ln", "4yM", "08", "aQ", "nP", "0Mb", "42D", "6Co", "6mC", "5HA", "0cN", "2Vm", "ML", "8gf", "4UP", "74Z",
"adM", "bAO", "1Ps", "0U3", "1Nq", "9j", "azO", "51W", "4KR", "7nP", "SN", "04t", "09D", "2Ho", "67I", "4Fb", "4hN", "7ML", "4Z", "e3",
"j2", "2iB", "6Rl", "4gO", "4Ic", "68H", "2Gn", "06E", "82m", "d4e", "4Q2", "4DS", "bPL", "a1F", "6k", "0QQ", "1pH", "2UJ", "6nd", "5Kf",
"41c", "7Pi", "mw", "0NE", "0Cu", "1F5", "6Mx", "5hz", "4Vw", "5S7", "Nk", "0mY", "0bX", "Aj", "6lU", "4Yv", "43R", "6By", "oF", "0Lt",
"0AD", "bv", "6OI", "4zj", "4TF", "6ae", "LZ", "0oh", "RX", "G9", "4JD", "7oF", "6QK", "4dh", "1Og", "2je", "5L", "0Rv", "4iX", "481",
"5B4", "4Gt", "08R", "2Iy", "Pi", "07S", "4Hu", "5M5", "470", "4fY", "1MV", "1X7", "su", "0PG", "4ki", "7Nk", "64n", "4EE", "H8", "2KH",
"6Lb", "4yA", "04", "23D", "Oq", "0lC", "4Wm", "6bN", "aEl", "c4G", "0as", "BA", "lm", "8FG", "40y", "559", "6NS", "5kQ", "345", "cl",
"1k2", "0nr", "boo", "74V", "6mO", "4Xl", "0cB", "2Va", "2xM", "0Mn", "42H", "6Cc", "4hB", "aws", "4V", "0Sl", "09H", "2Hc", "67E", "4Fn",
"b5e", "aTo", "SB", "04x", "8WD", "9f", "6PQ", "4er", "4js", "5o3", "6g", "8XE", "1oP", "1z1", "65t", "704", "4Io", "68D", "Qs", "06I",
"1LL", "2iN", "7BA", "4gC", "41g", "7Pm", "ms", "0NA", "14D", "2UN", "aDr", "5Kb", "4Vs", "5S3", "No", "19t", "0Cq", "1F1", "agn", "bBl",
"43V", "aho", "oB", "0Lp", "16u", "An", "6lQ", "4Yr", "4TB", "6aa", "2ZO", "0ol", "1Qa", "br", "6OM", "4zn", "6QO", "4dl", "1Oc", "8x",
"2DM", "05f", "5Za", "7oB", "5B0", "4Gp", "08V", "d7F", "5H", "0Rr", "bSo", "485", "474", "52t", "1MR", "1X3", "Pm", "07W", "4Hq", "5M1",
"64j", "4EA", "1nN", "2KL", "7y", "0PC", "4km", "7No", "Ou", "0lG", "4Wi", "6bJ", "6Lf", "4yE", "00", "aY", "li", "8FC", "4tu", "5q5",
"4O8", "4ZY", "0aw", "BE", "MD", "0nv", "4UX", "74R", "6NW", "5kU", "341", "ch", "nX", "0Mj", "42L", "6Cg", "6mK", "4Xh", "0cF", "2Ve",
"09L", "2Hg", "67A", "4Fj", "4hF", "7MD", "4R", "0Sh", "1Ny", "9b", "6PU", "4ev", "4KZ", "7nX", "SF", "0pt", "1oT", "1z5", "65p", "5Tz",
"4jw", "5o7", "6c", "0QY", "1LH", "2iJ", "6Rd", "4gG", "4Ik", "7li", "Qw", "06M", "7F", "246", "4kR", "7NP", "64U", "col", "1nq", "0k1",
"PR", "E3", "4HN", "69e", "6SA", "4fb", "1Mm", "2ho", "5w", "0RM", "4ic", "7La", "66d", "4GO", "J2", "2IB", "Rc", "05Y", "b4D", "aUN",
"4q2", "4dS", "8Ve", "8G", "8Hg", "bM", "4o0", "4zQ", "607", "75w", "La", "0oS", "T0", "AQ", "6ln", "4YM", "43i", "6BB", "2yl", "0LO",
"0CN", "22e", "6MC", "5hA", "4VL", "6co", "NP", "0mb", "1ps", "0u3", "aDM", "baO", "41X", "7PR", "mL", "8Gf", "4IT", "7lV", "QH", "06r",
"1Lw", "0I7", "5b8", "4gx", "4jH", "7OJ", "rT", "g5", "1ok", "2Ji", "65O", "4Dd", "4Ke", "7ng", "Sy", "04C", "h4", "2kD", "6Pj", "4eI",
"4hy", "5m9", "4m", "0SW", "09s", "2HX", "4S4", "4FU", "4M6", "4XW", "0cy", "1f9", "ng", "0MU", "42s", "573", "6Nh", "5kj", "v6", "cW",
"3KK", "0nI", "4Ug", "74m", "6oE", "4Zf", "0aH", "Bz", "lV", "y7", "40B", "6Ai", "582", "4yz", "0BT", "af", "OJ", "0lx", "4WV", "4B7",
"64Q", "4Ez", "1nu", "0k5", "7B", "0Px", "4kV", "7NT", "6SE", "4ff", "1Mi", "2hk", "PV", "E7", "4HJ", "69a", "6rh", "4GK", "J6", "2IF",
"5s", "0RI", "4ig", "7Le", "4q6", "4dW", "1OX", "8C", "Rg", "0qU", "5ZZ", "7oy", "4Ty", "5Q9", "Le", "0oW", "1QZ", "bI", "4o4", "4zU",
"43m", "6BF", "oy", "0LK", "T4", "AU", "6lj", "4YI", "4VH", "6ck", "NT", "0mf", "0CJ", "22a", "6MG", "4xd", "4uT", "7PV", "mH", "0Nz",
"1pw", "Cd", "aDI", "5KY", "1Ls", "0I3", "axM", "53U", "4IP", "7lR", "QL", "06v", "1oo", "2Jm", "65K", "5TA", "4jL", "7ON", "6X", "g1",
"h0", "9Y", "6Pn", "4eM", "4Ka", "7nc", "2El", "04G", "09w", "d6g", "4S0", "4FQ", "bRN", "a3D", "4i", "0SS", "nc", "0MQ", "42w", "577",
"4M2", "4XS", "17T", "dlm", "3KO", "0nM", "4Uc", "74i", "6Nl", "5kn", "v2", "cS", "lR", "y3", "40F", "6Am", "6oA", "4Zb", "0aL", "2To",
"ON", "18U", "4WR", "4B3", "586", "bCM", "0BP", "ab", "PZ", "0sh", "4HF", "69m", "6SI", "4fj", "1Me", "2hg", "7N", "0Pt", "4kZ", "7NX",
"6pU", "4Ev", "1ny", "0k9", "Rk", "05Q", "4Jw", "5O7", "452", "50r", "1OT", "8O", "qw", "0RE", "4ik", "7Li", "66l", "4GG", "08a", "2IJ",
"T8", "AY", "6lf", "4YE", "43a", "6BJ", "ou", "0LG", "0Aw", "bE", "4o8", "4zY", "4Tu", "5Q5", "Li", "8fC", "14s", "Ch", "6nW", "5KU",
"41P", "7PZ", "mD", "0Nv", "0CF", "22m", "6MK", "4xh", "4VD", "6cg", "NX", "0mj", "5za", "7OB", "6T", "0Qn", "1oc", "2Ja", "65G", "4Dl",
"b7g", "68w", "1w2", "06z", "8UF", "dSN", "5b0", "4gp", "4hq", "5m1", "4e", "8ZG", "1mR", "1x3", "67v", "726", "4Km", "7no", "Sq", "04K",
"1NN", "9U", "6Pb", "4eA", "adr", "5kb", "26", "21F", "Ms", "0nA", "4Uo", "74e", "79U", "bbl", "0cq", "1f1", "no", "396", "4vs", "5s3",
"6LQ", "4yr", "367", "an", "OB", "0lp", "bmm", "76T", "6oM", "4Zn", "15i", "Br", "2zO", "0Ol", "40J", "6Aa", "6SM", "4fn", "1Ma", "2hc",
"2FO", "07d", "4HB", "69i", "64Y", "4Er", "83L", "d5D", "7J", "0Pp", "bQm", "a0g", "456", "50v", "1OP", "8K", "Ro", "05U", "4Js", "5O3",
"66h", "4GC", "08e", "2IN", "qs", "0RA", "4io", "7Lm", "43e", "6BN", "oq", "0LC", "0bo", "2WL", "6lb", "4YA", "4Tq", "5Q1", "Lm", "8fG",
"0As", "bA", "ael", "cPO", "41T", "ajm", "1K2", "0Nr", "14w", "Cl", "6nS", "5KQ", "5Fa", "6cc", "2XM", "0mn", "0CB", "22i", "6MO", "4xl",
"1og", "2Je", "65C", "4Dh", "4jD", "7OF", "6P", "g9", "3l9", "2iy", "5b4", "4gt", "4IX", "68s", "QD", "0rv", "1mV", "1x7", "4S8", "4FY",
"4hu", "5m5", "4a", "1Cz", "h8", "9Q", "6Pf", "4eE", "4Ki", "7nk", "Su", "04O", "Mw", "0nE", "4Uk", "74a", "6Nd", "5kf", "22", "21B",
"nk", "0MY", "4vw", "5s7", "6mx", "5Hz", "0cu", "1f5", "OF", "0lt", "4WZ", "6by", "6LU", "4yv", "0BX", "aj", "lZ", "0Oh", "40N", "6Ae",
"6oI", "4Zj", "0aD", "Bv", "5f", "9Ke", "4ir", "5l2", "66u", "735", "08x", "1y0", "Rr", "05H", "4Jn", "7ol", "6Qa", "4dB", "1OM", "8V",
"7W", "0Pm", "4kC", "7NA", "64D", "4Eo", "83Q", "2Kb", "PC", "07y", "b6d", "69t", "5c3", "4fs", "8TE", "dRM", "374", "22t", "599", "4xq",
"bln", "77W", "NA", "0ms", "14j", "Cq", "6nN", "5KL", "41I", "7PC", "3km", "0No", "35", "20E", "6Oc", "5ja", "4Tl", "6aO", "Lp", "0oB",
"0br", "1g2", "78V", "bco", "43x", "568", "ol", "385", "4Kt", "5N4", "Sh", "04R", "1NW", "9L", "441", "4eX", "4hh", "7Mj", "pt", "0SF",
"K9", "2HI", "67o", "4FD", "4IE", "68n", "QY", "0", "1Lf", "2id", "6RJ", "4gi", "4jY", "auh", "6M", "0Qw", "1oz", "2Jx", "5A5", "4Du",
"6oT", "4Zw", "0aY", "Bk", "lG", "0Ou", "40S", "6Ax", "6LH", "4yk", "0BE", "aw", "2YJ", "0li", "4WG", "6bd", "6me", "4XF", "0ch", "2VK",
"nv", "0MD", "42b", "6CI", "6Ny", "7K9", "1PU", "cF", "Mj", "0nX", "4Uv", "5P6", "66q", "4GZ", "1lU", "1y4", "5b", "0RX", "4iv", "5l6",
"6Qe", "4dF", "1OI", "8R", "Rv", "05L", "4Jj", "7oh", "6pH", "4Ek", "1nd", "2Kf", "7S", "0Pi", "4kG", "7NE", "5c7", "4fw", "1Mx", "0H8",
"PG", "0su", "5Xz", "69p", "4VY", "4C8", "NE", "0mw", "1Sz", "22p", "6MV", "4xu", "41M", "7PG", "mY", "x8", "14n", "Cu", "6nJ", "5KH",
"4Th", "6aK", "Lt", "0oF", "31", "bX", "6Og", "4zD", "4wt", "5r4", "oh", "0LZ", "0bv", "AD", "4L9", "4YX", "1NS", "9H", "445", "51u",
"4Kp", "5N0", "Sl", "04V", "09f", "2HM", "67k", "5Va", "4hl", "7Mn", "4x", "0SB", "1Lb", "3yA", "6RN", "4gm", "4IA", "68j", "2GL", "4",
"82O", "d4G", "5A1", "4Dq", "bPn", "a1d", "6I", "0Qs", "lC", "0Oq", "40W", "akn", "6oP", "4Zs", "15t", "Bo", "2YN", "0lm", "4WC", "76I",
"6LL", "4yo", "0BA", "as", "nr", "8DX", "42f", "6CM", "6ma", "4XB", "0cl", "2VO", "Mn", "8gD", "4Ur", "5P2", "ado", "bAm", "1PQ", "cB",
"Rz", "0qH", "4Jf", "7od", "6Qi", "4dJ", "i7", "2jG", "5n", "0RT", "4iz", "7Lx", "4R7", "4GV", "08p", "1y8", "PK", "07q", "4HW", "7mU",
"6SX", "52R", "1Mt", "0H4", "sW", "f6", "4kK", "7NI", "64L", "4Eg", "1nh", "2Kj", "14b", "Cy", "6nF", "5KD", "41A", "7PK", "mU", "x4",
"0CW", "0V6", "591", "4xy", "4VU", "4C4", "NI", "19R", "0bz", "AH", "4L5", "4YT", "43p", "560", "od", "0LV", "w5", "bT", "6Ok", "4zH",
"4Td", "6aG", "Lx", "0oJ", "5xA", "7Mb", "4t", "0SN", "K1", "2HA", "67g", "4FL", "b5G", "aTM", "0e3", "04Z", "8Wf", "9D", "449", "4eP",
"4jQ", "7OS", "6E", "255", "1or", "0j2", "65V", "cno", "4IM", "68f", "QQ", "8", "1Ln", "2il", "6RB", "4ga", "afR", "4yc", "0BM", "23f",
"OS", "Z2", "4WO", "6bl", "aEN", "c4e", "0aQ", "Bc", "lO", "8Fe", "4tS", "4a2", "4n3", "5ks", "8Id", "cN", "Mb", "0nP", "614", "74t",
"6mm", "4XN", "U3", "2VC", "2xo", "0ML", "42j", "6CA", "6Qm", "4dN", "i3", "8Z", "2Do", "05D", "4Jb", "aUS", "4R3", "4GR", "08t", "d7d",
"5j", "0RP", "bSM", "a2G", "ayN", "52V", "1Mp", "0H0", "PO", "07u", "4HS", "69x", "64H", "4Ec", "1nl", "2Kn", "sS", "f2", "4kO", "7NM",
"41E", "7PO", "mQ", "x0", "14f", "2Ul", "6nB", "aQ1", "4VQ", "4C0", "NM", "19V", "0CS", "0V2", "595", "bBN", "43t", "564", "0Y3", "0LR",
"16W", "AL", "4L1", "4YP", "5DA", "6aC", "2Zm", "0oN", "39", "bP", "6Oo", "4zL", "K5", "2HE", "67c", "4FH", "4hd", "7Mf", "4p", "0SJ",
"8Wb", "2kY", "4p5", "4eT", "4Kx", "5N8", "Sd", "0pV", "1ov", "0j6", "5A9", "4Dy", "4jU", "7OW", "6A", "1AZ", "1Lj", "2ih", "6RF", "4ge",
"4II", "68b", "QU", "D4", "OW", "Z6", "4WK", "6bh", "6LD", "4yg", "0BI", "23b", "lK", "0Oy", "4tW", "4a6", "6oX", "5JZ", "0aU", "Bg",
"Mf", "0nT", "4Uz", "74p", "4n7", "5kw", "1PY", "cJ", "nz", "0MH", "42n", "6CE", "6mi", "4XJ", "U7", "2VG", "4MP", "4X1", "UL", "02v",
"0XR", "0M3", "a8E", "57U", "4nL", "7KN", "2X", "c1", "1ko", "2Nm", "61K", "5PA", "4Oa", "6zB", "2Al", "00G", "l0", "yQ", "6Tn", "4aM",
"58T", "a7D", "0i", "0WS", "84o", "ZM", "4W0", "4BQ", "4I2", "5Lr", "13T", "G", "jc", "0IQ", "46w", "537", "6Jl", "5on", "r2", "gS",
"3OO", "0jM", "4Qc", "70i", "6kA", "5NC", "0eL", "2Po", "hR", "8Bx", "44F", "6Em", "abO", "49v", "0FP", "eb", "KN", "8ad", "4SR", "4F3",
"3B", "0Tx", "4oV", "4z7", "60Q", "4Az", "0zT", "Yf", "TV", "A7", "4LJ", "6yi", "6WE", "4bf", "0YH", "zz", "1s", "0VI", "4mg", "6XD",
"6vh", "4CK", "N6", "2MF", "Vg", "0uU", "6n9", "7ky", "4u6", "5pv", "1KX", "xK", "1UZ", "fI", "4k4", "5nt", "4Py", "5U9", "He", "0kW",
"P4", "EU", "6hj", "5Mh", "47m", "6FF", "ky", "0HK", "0GJ", "dx", "6IG", "48l", "4RH", "6gk", "JT", "0if", "0dV", "Gd", "5Z8", "5OY",
"4qT", "4d5", "iH", "0Jz", "0XV", "0M7", "5f8", "4cx", "4MT", "4X5", "UH", "02r", "1kk", "Xx", "61O", "5PE", "4nH", "7KJ", "vT", "c5",
"l4", "yU", "6Tj", "4aI", "4Oe", "6zF", "Wy", "00C", "1iZ", "ZI", "4W4", "4BU", "4ly", "5i9", "0m", "0WW", "jg", "0IU", "46s", "533",
"4I6", "5Lv", "0gy", "C", "3OK", "0jI", "4Qg", "6dD", "6Jh", "5oj", "r6", "gW", "hV", "0Kd", "44B", "6Ei", "6kE", "5NG", "0eH", "Fz",
"KJ", "0hx", "4SV", "4F7", "6HY", "49r", "0FT", "ef", "60U", "ckl", "0zP", "Yb", "3F", "206", "4oR", "4z3", "6WA", "4bb", "0YL", "2lo",
"TR", "A3", "4LN", "6ym", "62d", "4CO", "N2", "2MB", "1w", "0VM", "4mc", "7Ha", "4u2", "54z", "8Re", "xO", "Vc", "01Y", "b0D", "aQN",
"647", "71w", "Ha", "0kS", "8Lg", "fM", "4k0", "5np", "47i", "6FB", "29d", "0HO", "P0", "EQ", "6hn", "5Ml", "4RL", "6go", "JP", "0ib",
"0GN", "26e", "6IC", "48h", "45X", "4d1", "iL", "8Cf", "0dR", "0q3", "hYt", "beO", "4nD", "7KF", "2P", "c9", "1kg", "Xt", "61C", "5PI",
"4MX", "4X9", "UD", "0vv", "0XZ", "2my", "5f4", "4ct", "4lu", "5i5", "0a", "1Gz", "0yw", "ZE", "4W8", "4BY", "4Oi", "6zJ", "Wu", "00O",
"l8", "yY", "6Tf", "4aE", "6Jd", "5of", "62", "25B", "Iw", "0jE", "4Qk", "6dH", "6ix", "5Lz", "0gu", "O", "jk", "0IY", "4rw", "5w7",
"5x6", "5mW", "0FX", "ej", "KF", "0ht", "4SZ", "6fy", "6kI", "5NK", "0eD", "Fv", "hZ", "93", "44N", "6Ee", "2BO", "03d", "4LB", "6ya",
"6WM", "4bn", "1Ia", "zr", "3J", "0Tp", "bUm", "a4g", "5D2", "4Ar", "87L", "Yn", "Vo", "01U", "4Ns", "5K3", "416", "54v", "1KP", "xC",
"us", "0VA", "4mo", "6XL", "62h", "4CC", "0xm", "2MN", "0fo", "2SL", "6hb", "bgr", "47e", "6FN", "kq", "0HC", "0Es", "fA", "aal", "bDn",
"4Pq", "5U1", "Hm", "8bG", "10w", "Gl", "5Z0", "5OQ", "45T", "anm", "1O2", "0Jr", "0GB", "dp", "6IO", "48d", "5Ba", "6gc", "3Ll", "0in",
"1kc", "Xp", "61G", "5PM", "bTs", "7KB", "2T", "0Un", "8QF", "39T", "5f0", "4cp", "797", "aRm", "1s2", "02z", "0ys", "ZA", "63v", "766",
"4lq", "5i1", "0e", "9Nf", "0Zo", "2oL", "6Tb", "4aA", "4Om", "6zN", "Wq", "00K", "Is", "0jA", "4Qo", "6dL", "7ZA", "5ob", "66", "25F",
"jo", "9Pd", "4rs", "5w3", "aCn", "bfl", "0gq", "K", "KB", "0hp", "bim", "72T", "5x2", "49z", "327", "en", "3nn", "97", "44J", "6Ea",
"6kM", "5NO", "11i", "Fr", "6WI", "4bj", "0YD", "zv", "TZ", "0wh", "4LF", "6ye", "5D6", "4Av", "0zX", "Yj", "3N", "0Tt", "4oZ", "6Zy",
"412", "54r", "1KT", "xG", "Vk", "01Q", "4Nw", "5K7", "62l", "4CG", "0xi", "2MJ", "uw", "0VE", "4mk", "6XH", "47a", "6FJ", "ku", "0HG",
"P8", "EY", "6hf", "5Md", "4Pu", "5U5", "Hi", "8bC", "0Ew", "fE", "4k8", "5nx", "45P", "4d9", "iD", "0Jv", "0dZ", "Gh", "5Z4", "5OU",
"4RD", "6gg", "JX", "0ij", "0GF", "dt", "6IK", "5lI", "4Op", "5J0", "Wl", "00V", "0Zr", "2oQ", "405", "55u", "4ll", "6YO", "0x", "0WB",
"0yn", "2LM", "63k", "5Ra", "4MA", "6xb", "2CL", "02g", "0XC", "39I", "6VN", "4cm", "bTn", "a5d", "2I", "0Us", "86O", "Xm", "5E1", "5PP",
"6kP", "5NR", "11t", "Fo", "hC", "0Kq", "44W", "aon", "6HL", "49g", "0FA", "es", "3Mo", "0hm", "4SC", "72I", "6ia", "5Lc", "0gl", "V",
"jr", "1Ya", "46f", "6GM", "hyV", "bEm", "0Dp", "gB", "In", "8cD", "4Qr", "5T2", "1b", "0VX", "4mv", "5h6", "62q", "4CZ", "0xt", "2MW",
"Vv", "01L", "4Nj", "7kh", "6Ue", "54o", "1KI", "xZ", "3S", "0Ti", "4oG", "6Zd", "6tH", "4Ak", "0zE", "Yw", "TG", "0wu", "780", "6yx",
"5g7", "4bw", "0YY", "zk", "1Wz", "di", "5y5", "5lT", "4RY", "4G8", "JE", "0iw", "0dG", "Gu", "6jJ", "5OH", "45M", "6Df", "iY", "80",
"71", "fX", "6Kg", "5ne", "4Ph", "6eK", "Ht", "0kF", "0fv", "ED", "4H9", "5My", "4st", "5v4", "kh", "0HZ", "0Zv", "yD", "401", "4aX",
"4Ot", "5J4", "Wh", "00R", "O9", "ZX", "63o", "4BD", "4lh", "6YK", "tt", "0WF", "0XG", "2md", "6VJ", "4ci", "4ME", "6xf", "UY", "02c",
"1kz", "Xi", "5E5", "5PT", "4nY", "aqh", "2M", "0Uw", "hG", "0Ku", "44S", "6Ex", "6kT", "5NV", "0eY", "Fk", "3Mk", "0hi", "4SG", "6fd",
"6HH", "49c", "0FE", "ew", "jv", "0ID", "46b", "6GI", "6ie", "5Lg", "0gh", "R", "Ij", "0jX", "4Qv", "5T6", "6Jy", "7O9", "0Dt", "gF",
"62u", "775", "0xp", "198", "1f", "9Oe", "4mr", "5h2", "6Ua", "54k", "1KM", "2nO", "Vr", "01H", "4Nn", "7kl", "60D", "4Ao", "0zA", "Ys",
"3W", "0Tm", "4oC", "7JA", "5g3", "4bs", "8PE", "zo", "TC", "03y", "784", "aSn", "bhn", "73W", "JA", "0is", "334", "dm", "5y1", "48y",
"45I", "6Db", "3om", "84", "0dC", "Gq", "6jN", "5OL", "4Pl", "6eO", "Hp", "0kB", "75", "24E", "6Kc", "5na", "47x", "528", "kl", "8AF",
"0fr", "1c2", "aBm", "bgo", "4ld", "6YG", "0p", "0WJ", "O5", "ZT", "63c", "4BH", "4Ox", "5J8", "Wd", "0tV", "0Zz", "yH", "4t5", "4aT",
"4nU", "7KW", "2A", "1EZ", "1kv", "Xe", "5E9", "5PX", "4MI", "6xj", "UU", "02o", "0XK", "2mh", "6VF", "4ce", "6HD", "49o", "0FI", "27b",
"KW", "0he", "4SK", "6fh", "6kX", "5NZ", "0eU", "Fg", "hK", "0Ky", "4pW", "4e6", "4j7", "5ow", "0Dx", "gJ", "If", "0jT", "4Qz", "6dY",
"6ii", "5Lk", "Q7", "DV", "jz", "0IH", "46n", "6GE", "3PN", "01D", "4Nb", "aQS", "6Um", "54g", "m3", "xR", "1j", "0VP", "59W", "a6G",
"4V3", "4CR", "85l", "194", "TO", "03u", "4LS", "4Y2", "a9F", "56V", "0YQ", "zc", "wS", "b2", "4oO", "6Zl", "60H", "4Ac", "0zM", "2On",
"0dO", "2Ql", "6jB", "aU1", "45E", "6Dn", "iQ", "88", "0GS", "da", "acL", "48u", "4RQ", "4G0", "JM", "94N", "12W", "EL", "4H1", "5Mq",
"47t", "524", "29y", "0HR", "79", "fP", "6Ko", "5nm", "aZ0", "6eC", "3NL", "0kN", "O1", "ZP", "63g", "4BL", "58I", "6YC", "0t", "0WN",
"8Sf", "yL", "409", "4aP", "b1G", "aPM", "0a3", "00Z", "1kr", "Xa", "61V", "bzN", "4nQ", "7KS", "2E", "215", "0XO", "2ml", "6VB", "4ca",
"4MM", "6xn", "UQ", "02k", "KS", "0ha", "4SO", "6fl", "7Xa", "49k", "0FM", "27f", "hO", "8Be", "4pS", "4e2", "aAN", "bdL", "0eQ", "Fc",
"Ib", "0jP", "654", "70t", "4j3", "5os", "8Md", "gN", "28g", "0IL", "46j", "6GA", "6im", "5Lo", "Q3", "Z", "6Ui", "54c", "m7", "xV",
"Vz", "0uH", "4Nf", "7kd", "4V7", "4CV", "0xx", "190", "1n", "0VT", "4mz", "6XY", "6WX", "56R", "0YU", "zg", "TK", "03q", "4LW", "4Y6",
"60L", "4Ag", "0zI", "2Oj", "wW", "b6", "4oK", "6Zh", "45A", "6Dj", "iU", "0Jg", "0dK", "Gy", "6jF", "5OD", "4RU", "4G4", "JI", "1yZ",
"0GW", "de", "5y9", "48q", "47p", "520", "kd", "0HV", "0fz", "EH", "4H5", "5Mu", "4Pd", "6eG", "Hx", "0kJ", "s5", "fT", "6Kk", "5ni",
"5Y1", "5LP", "13v", "e", "jA", "0Is", "46U", "aml", "6JN", "5oL", "0DC", "gq", "3Om", "0jo", "4QA", "6db", "6kc", "5Na", "0en", "2PM",
"hp", "0KB", "44d", "6EO", "abm", "49T", "0Fr", "1C2", "Kl", "8aF", "4Sp", "5V0", "4Mr", "5H2", "Un", "02T", "0Xp", "2mS", "427", "57w",
"4nn", "7Kl", "2z", "1Ea", "1kM", "2NO", "61i", "5Pc", "4OC", "7jA", "2AN", "00e", "0ZA", "ys", "6TL", "4ao", "58v", "a7f", "0K", "0Wq",
"84M", "Zo", "5G3", "4Bs", "0EY", "fk", "6KT", "5nV", "bjh", "6ex", "HG", "0ku", "0fE", "Ew", "6hH", "5MJ", "47O", "6Fd", "29B", "0Hi",
"53", "dZ", "6Ie", "48N", "4Rj", "6gI", "Jv", "0iD", "0dt", "GF", "6jy", "7o9", "4qv", "5t6", "ij", "0JX", "wh", "0TZ", "4ot", "5j4",
"4T9", "4AX", "0zv", "YD", "Tt", "03N", "4Lh", "6yK", "6Wg", "4bD", "o9", "zX", "1Q", "0Vk", "4mE", "6Xf", "62B", "4Ci", "0xG", "2Md",
"VE", "0uw", "4NY", "aQh", "5e5", "5pT", "1Kz", "xi", "jE", "0Iw", "46Q", "4g8", "5Y5", "5LT", "13r", "a", "IY", "0jk", "4QE", "6df",
"6JJ", "5oH", "0DG", "gu", "ht", "0KF", "4ph", "6EK", "6kg", "5Ne", "S9", "FX", "Kh", "0hZ", "4St", "5V4", "4h9", "49P", "0Fv", "eD",
"0Xt", "2mW", "423", "4cZ", "4Mv", "5H6", "Uj", "02P", "1kI", "XZ", "61m", "5Pg", "4nj", "7Kh", "vv", "0UD", "0ZE", "yw", "6TH", "4ak",
"4OG", "6zd", "2AJ", "00a", "0yY", "Zk", "5G7", "4Bw", "58r", "6Yx", "0O", "0Wu", "bjl", "71U", "HC", "0kq", "316", "fo", "6KP", "5nR",
"47K", "7VA", "29F", "0Hm", "0fA", "Es", "6hL", "5MN", "4Rn", "6gM", "Jr", "1ya", "57", "26G", "6Ia", "48J", "45z", "5t2", "in", "8CD",
"0dp", "GB", "hYV", "bem", "60w", "757", "0zr", "2OQ", "3d", "9Mg", "4op", "5j0", "6Wc", "56i", "0Yn", "2lM", "Tp", "03J", "4Ll", "6yO",
"62F", "4Cm", "0xC", "dwS", "1U", "0Vo", "4mA", "6Xb", "5e1", "54X", "8RG", "xm", "VA", "0us", "b0f", "aQl", "6JF", "5oD", "0DK", "gy",
"IU", "0jg", "4QI", "6dj", "5Y9", "5LX", "0gW", "m", "jI", "1YZ", "4rU", "4g4", "4h5", "5mu", "0Fz", "eH", "Kd", "0hV", "4Sx", "5V8",
"6kk", "5Ni", "S5", "FT", "hx", "0KJ", "44l", "6EG", "4nf", "7Kd", "2r", "0UH", "M7", "XV", "61a", "5Pk", "4Mz", "6xY", "Uf", "0vT",
"0Xx", "39r", "4v7", "4cV", "4lW", "4y6", "0C", "0Wy", "0yU", "Zg", "63P", "5RZ", "4OK", "6zh", "WW", "B6", "0ZI", "2oj", "6TD", "4ag",
"0fM", "2Sn", "7xa", "5MB", "47G", "6Fl", "kS", "0Ha", "0EQ", "fc", "aaN", "bDL", "4PS", "4E2", "HO", "8be", "10U", "GN", "4J3", "5Os",
"45v", "506", "ib", "0JP", "q3", "dR", "6Im", "48F", "4Rb", "6gA", "3LN", "0iL", "2Bm", "03F", "aF0", "6yC", "6Wo", "4bL", "o1", "zP",
"3h", "0TR", "bUO", "a4E", "4T1", "4AP", "87n", "YL", "VM", "01w", "4NQ", "7kS", "hfu", "54T", "1Kr", "xa", "1Y", "0Vc", "4mM", "6Xn",
"62J", "4Ca", "0xO", "2Ml", "IQ", "0jc", "4QM", "6dn", "6JB", "a19", "0DO", "25d", "jM", "9PF", "46Y", "4g0", "aCL", "687", "0gS", "i",
"3MP", "0hR", "676", "72v", "4h1", "49X", "8Of", "eL", "3nL", "0KN", "44h", "6EC", "6ko", "5Nm", "S1", "FP", "M3", "XR", "61e", "5Po",
"4nb", "aqS", "2v", "0UL", "8Qd", "39v", "4v3", "4cR", "b3E", "aRO", "Ub", "02X", "0yQ", "Zc", "63T", "bxL", "4lS", "4y2", "0G", "237",
"0ZM", "2on", "7Da", "4ac", "4OO", "6zl", "WS", "B2", "47C", "6Fh", "kW", "0He", "0fI", "2Sj", "6hD", "5MF", "4PW", "4E6", "HK", "0ky",
"0EU", "fg", "6KX", "5nZ", "45r", "502", "if", "0JT", "0dx", "GJ", "4J7", "5Ow", "4Rf", "6gE", "Jz", "0iH", "q7", "dV", "6Ii", "48B",
"6Wk", "4bH", "o5", "zT", "Tx", "03B", "4Ld", "6yG", "4T5", "4AT", "0zz", "YH", "3l", "0TV", "4ox", "5j8", "5e9", "54P", "1Kv", "xe",
"VI", "01s", "4NU", "7kW", "62N", "4Ce", "0xK", "2Mh", "uU", "0Vg", "4mI", "6Xj", "4K0", "5Np", "11V", "FM", "ha", "0KS", "44u", "515",
"6Hn", "49E", "48", "eQ", "3MM", "0hO", "4Sa", "6fB", "6iC", "5LA", "0gN", "t", "jP", "0Ib", "46D", "6Go", "hyt", "bEO", "0DR", "0Q3",
"IL", "8cf", "4QP", "4D1", "4OR", "4Z3", "WN", "00t", "0ZP", "yb", "hgv", "55W", "4lN", "6Ym", "0Z", "a3", "0yL", "2Lo", "63I", "4Bb",
"4Mc", "7ha", "2Cn", "02E", "n2", "2mB", "6Vl", "4cO", "bTL", "a5F", "2k", "0UQ", "86m", "XO", "4U2", "5Pr", "0Gy", "dK", "4i6", "5lv",
"5BZ", "6gX", "Jg", "0iU", "R6", "GW", "6jh", "5Oj", "45o", "6DD", "3oK", "0JI", "0EH", "fz", "6KE", "5nG", "4PJ", "6ei", "HV", "0kd",
"0fT", "Ef", "6hY", "690", "4sV", "4f7", "kJ", "0Hx", "uH", "0Vz", "4mT", "4x5", "5F8", "4Cx", "0xV", "0m7", "VT", "C5", "4NH", "7kJ",
"6UG", "54M", "1Kk", "xx", "3q", "0TK", "4oe", "6ZF", "60b", "4AI", "L4", "YU", "Te", "0wW", "4Ly", "5I9", "4w4", "4bU", "1IZ", "zI",
"he", "0KW", "44q", "511", "4K4", "5Nt", "11R", "FI", "Ky", "0hK", "4Se", "6fF", "6Hj", "49A", "p4", "eU", "jT", "0If", "4rH", "6Gk",
"6iG", "5LE", "0gJ", "p", "IH", "0jz", "4QT", "4D5", "5z8", "5oY", "0DV", "gd", "0ZT", "yf", "6TY", "4az", "4OV", "4Z7", "WJ", "00p",
"0yH", "Zz", "63M", "4Bf", "4lJ", "6Yi", "tV", "a7", "n6", "2mF", "6Vh", "4cK", "4Mg", "6xD", "2Cj", "02A", "1kX", "XK", "4U6", "5Pv",
"6N9", "7Ky", "2o", "0UU", "665", "73u", "Jc", "0iQ", "8Ne", "dO", "4i2", "5lr", "45k", "7Ta", "3oO", "0JM", "R2", "GS", "6jl", "5On",
"4PN", "6em", "HR", "8bx", "0EL", "24g", "6KA", "5nC", "47Z", "4f3", "kN", "8Ad", "0fP", "Eb", "aBO", "694", "62W", "byO", "0xR", "0m3",
"1D", "224", "4mP", "4x1", "6UC", "54I", "1Ko", "2nm", "VP", "C1", "4NL", "7kN", "60f", "4AM", "L0", "YQ", "3u", "0TO", "4oa", "6ZB",
"438", "4bQ", "8Pg", "zM", "Ta", "0wS", "b2F", "aSL", "6Hf", "49M", "40", "eY", "Ku", "0hG", "4Si", "6fJ", "4K8", "5Nx", "0ew", "FE",
"hi", "8BC", "4pu", "5u5", "5z4", "5oU", "0DZ", "gh", "ID", "0jv", "4QX", "4D9", "6iK", "5LI", "0gF", "Dt", "jX", "0Ij", "46L", "6Gg",
"4lF", "6Ye", "0R", "0Wh", "0yD", "Zv", "63A", "4Bj", "4OZ", "6zy", "WF", "0tt", "0ZX", "yj", "5d6", "4av", "4nw", "5k7", "2c", "0UY",
"1kT", "XG", "61p", "5Pz", "4Mk", "6xH", "Uw", "02M", "0Xi", "2mJ", "6Vd", "4cG", "0dm", "2QN", "7zA", "5Ob", "45g", "6DL", "is", "0JA",
"0Gq", "dC", "acn", "48W", "4Rs", "5W3", "Jo", "94l", "12u", "En", "5X2", "5MS", "47V", "alo", "kB", "0Hp", "1Ua", "fr", "6KM", "5nO",
"4PB", "6ea", "3Nn", "0kl", "3Pl", "01f", "bts", "7kB", "6UO", "54E", "1Kc", "xp", "1H", "0Vr", "59u", "a6e", "5F0", "4Cp", "85N", "d3F",
"Tm", "03W", "4Lq", "5I1", "434", "56t", "0Ys", "zA", "3y", "0TC", "4om", "6ZN", "60j", "4AA", "0zo", "2OL", "Kq", "0hC", "4Sm", "6fN",
"6Hb", "49I", "44", "27D", "hm", "8BG", "44y", "519", "aAl", "bdn", "0es", "FA", "1o2", "0jr", "bko", "70V", "5z0", "5oQ", "305", "gl",
"28E", "0In", "46H", "6Gc", "6iO", "5LM", "0gB", "x", "1ia", "Zr", "63E", "4Bn", "4lB", "6Ya", "0V", "0Wl", "8SD", "yn", "5d2", "4ar",
"b1e", "aPo", "WB", "00x", "1kP", "XC", "61t", "744", "4ns", "5k3", "2g", "9Ld", "0Xm", "2mN", "7FA", "4cC", "4Mo", "6xL", "Us", "02I",
"45c", "6DH", "iw", "0JE", "0di", "2QJ", "6jd", "5Of", "4Rw", "5W7", "Jk", "0iY", "0Gu", "dG", "6Ix", "48S", "47R", "6Fy", "kF", "0Ht",
"0fX", "Ej", "5X6", "5MW", "4PF", "6ee", "HZ", "0kh", "0ED", "fv", "6KI", "5nK", "6UK", "54A", "1Kg", "xt", "VX", "C9", "4ND", "7kF",
"5F4", "4Ct", "0xZ", "2My", "1L", "0Vv", "4mX", "4x9", "430", "4bY", "0Yw", "zE", "Ti", "03S", "4Lu", "5I5", "60n", "4AE", "L8", "YY",
"wu", "0TG", "4oi", "1oU", };
| 134.927184 | 139 | 0.410362 | [
"3d"
] |
d67d323ab240cbc181b37ffc063a7f1e91ca8ae2 | 231 | h | C | include/jast/ir/interp-native-functions.h | PrinceDhaliwal/copta | 396404bc7ecc3e28cc2582acd9d1c19857e6b471 | [
"MIT"
] | null | null | null | include/jast/ir/interp-native-functions.h | PrinceDhaliwal/copta | 396404bc7ecc3e28cc2582acd9d1c19857e6b471 | [
"MIT"
] | null | null | null | include/jast/ir/interp-native-functions.h | PrinceDhaliwal/copta | 396404bc7ecc3e28cc2582acd9d1c19857e6b471 | [
"MIT"
] | null | null | null | #ifndef INTERP_NATIVE_FUNCTIONS_H_
#define INTERP_NATIVE_FUNCTIONS_H_
#include "jast/handle.h"
#include <vector>
namespace jast {
namespace internal {
class Object;
Ref<Object> print(std::vector<Ref<Object>> &args);
}
}
#endif
| 14.4375 | 50 | 0.766234 | [
"object",
"vector"
] |
d6823c1ef92bc98035e6d5a64519f55545049743 | 7,197 | h | C | third_party/tonic/dart_wrappable.h | TeXniKK/engine | 6b3d4396320f3280ea5763f7673804643cc8f02a | [
"BSD-3-Clause"
] | 3 | 2019-12-11T02:54:11.000Z | 2021-04-14T06:04:07.000Z | third_party/tonic/dart_wrappable.h | TeXniKK/engine | 6b3d4396320f3280ea5763f7673804643cc8f02a | [
"BSD-3-Clause"
] | null | null | null | third_party/tonic/dart_wrappable.h | TeXniKK/engine | 6b3d4396320f3280ea5763f7673804643cc8f02a | [
"BSD-3-Clause"
] | 1 | 2020-06-23T16:38:59.000Z | 2020-06-23T16:38:59.000Z | // Copyright 2013 The Flutter 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 LIB_TONIC_DART_WRAPPABLE_H_
#define LIB_TONIC_DART_WRAPPABLE_H_
#include "third_party/dart/runtime/include/dart_api.h"
#include "tonic/common/macros.h"
#include "tonic/converter/dart_converter.h"
#include "tonic/dart_state.h"
#include "tonic/dart_wrapper_info.h"
#include "tonic/logging/dart_error.h"
#include <type_traits>
namespace tonic {
// DartWrappable is a base class that you can inherit from in order to be
// exposed to Dart code as an interface.
class DartWrappable {
public:
enum DartNativeFields {
kPeerIndex, // Must be first to work with Dart_GetNativeReceiver.
kWrapperInfoIndex,
kNumberOfNativeFields,
};
DartWrappable() : dart_wrapper_(nullptr) {}
// Subclasses that wish to expose a new interface must override this function
// and provide information about their wrapper. There is no need to call your
// base class's implementation of this function.
// Implement using IMPLEMENT_WRAPPERTYPEINFO macro
virtual const DartWrapperInfo& GetDartWrapperInfo() const = 0;
// Override this to customize the object size reported to the Dart garbage
// collector.
// Implement using IMPLEMENT_WRAPPERTYPEINFO macro
virtual size_t GetAllocationSize();
virtual void RetainDartWrappableReference() const = 0;
virtual void ReleaseDartWrappableReference() const = 0;
Dart_Handle CreateDartWrapper(DartState* dart_state);
void AssociateWithDartWrapper(Dart_NativeArguments args);
void ClearDartWrapper(); // Warning: Might delete this.
Dart_WeakPersistentHandle dart_wrapper() const { return dart_wrapper_; }
protected:
virtual ~DartWrappable();
static Dart_PersistentHandle GetTypeForWrapper(
tonic::DartState* dart_state,
const tonic::DartWrapperInfo& wrapper_info);
private:
static void FinalizeDartWrapper(void* isolate_callback_data,
Dart_WeakPersistentHandle wrapper,
void* peer);
Dart_WeakPersistentHandle dart_wrapper_;
TONIC_DISALLOW_COPY_AND_ASSIGN(DartWrappable);
};
#define DEFINE_WRAPPERTYPEINFO() \
public: \
const tonic::DartWrapperInfo& GetDartWrapperInfo() const override { \
return dart_wrapper_info_; \
} \
static Dart_PersistentHandle GetDartType(tonic::DartState* dart_state) { \
return GetTypeForWrapper(dart_state, dart_wrapper_info_); \
} \
\
private: \
static const tonic::DartWrapperInfo& dart_wrapper_info_
#define IMPLEMENT_WRAPPERTYPEINFO(LibraryName, ClassName) \
static const tonic::DartWrapperInfo \
kDartWrapperInfo_##LibraryName_##ClassName = { \
#LibraryName, \
#ClassName, \
sizeof(ClassName), \
}; \
const tonic::DartWrapperInfo& ClassName::dart_wrapper_info_ = \
kDartWrapperInfo_##LibraryName_##ClassName;
struct DartConverterWrappable {
static DartWrappable* FromDart(Dart_Handle handle);
static DartWrappable* FromArguments(Dart_NativeArguments args,
int index,
Dart_Handle& exception);
};
template <typename T>
struct DartConverter<
T*,
typename std::enable_if<
std::is_convertible<T*, const DartWrappable*>::value>::type> {
static Dart_Handle ToDart(DartWrappable* val) {
if (!val)
return Dart_Null();
if (Dart_WeakPersistentHandle wrapper = val->dart_wrapper())
return Dart_HandleFromWeakPersistent(wrapper);
return val->CreateDartWrapper(DartState::Current());
}
static void SetReturnValue(Dart_NativeArguments args,
DartWrappable* val,
bool auto_scope = true) {
if (!val)
Dart_SetReturnValue(args, Dart_Null());
else if (Dart_WeakPersistentHandle wrapper = val->dart_wrapper())
Dart_SetWeakHandleReturnValue(args, wrapper);
else
Dart_SetReturnValue(args, val->CreateDartWrapper(DartState::Current()));
}
static T* FromDart(Dart_Handle handle) {
// TODO(abarth): We're missing a type check.
return static_cast<T*>(DartConverterWrappable::FromDart(handle));
}
static T* FromArguments(Dart_NativeArguments args,
int index,
Dart_Handle& exception,
bool auto_scope = true) {
// TODO(abarth): We're missing a type check.
return static_cast<T*>(
DartConverterWrappable::FromArguments(args, index, exception));
}
};
////////////////////////////////////////////////////////////////////////////////
// Support for generic smart pointers that have a "get" method that returns a
// pointer to a type that is Dart convertible as well as a constructor that
// adopts a raw pointer to that type.
template <template <typename T> class PTR, typename T>
struct DartConverter<PTR<T>> {
static Dart_Handle ToDart(const PTR<T>& val) {
return DartConverter<T*>::ToDart(val.get());
}
static PTR<T> FromDart(Dart_Handle handle) {
return DartConverter<T*>::FromDart(handle);
}
static PTR<T> FromArguments(Dart_NativeArguments args,
int index,
Dart_Handle& exception,
bool auto_scope = true) {
return PTR<T>(
DartConverter<T*>::FromArguments(args, index, exception, auto_scope));
}
static void SetReturnValue(Dart_NativeArguments args,
const PTR<T>& val,
bool auto_scope = true) {
DartConverter<T*>::SetReturnValue(args, val.get());
}
};
template <template <typename T> class PTR, typename T>
struct DartListFactory<
PTR<T>,
typename std::enable_if<
std::is_convertible<T*, const DartWrappable*>::value>::type> {
static Dart_Handle NewList(intptr_t length) {
Dart_PersistentHandle type = T::GetDartType(DartState::Current());
TONIC_DCHECK(!LogIfError(type));
return Dart_NewListOfType(Dart_HandleFromPersistent(type), length);
}
};
template <typename T>
inline T* GetReceiver(Dart_NativeArguments args) {
intptr_t receiver;
Dart_Handle result = Dart_GetNativeReceiver(args, &receiver);
TONIC_DCHECK(!Dart_IsError(result));
if (!receiver)
Dart_ThrowException(ToDart("Object has been disposed."));
return static_cast<T*>(reinterpret_cast<DartWrappable*>(receiver));
}
} // namespace tonic
#endif // LIB_TONIC_DART_WRAPPABLE_H_
| 37.680628 | 80 | 0.622343 | [
"object"
] |
d68aef3f86075d883781de02cbf56010cb023e40 | 2,124 | h | C | mindspore/ccsrc/backend/kernel_compiler/aicpu/aicpu_util.h | i4oolish/mindspore | dac3be31d0f2c0a3516200f47af30980e566601b | [
"Apache-2.0"
] | 2 | 2020-08-12T16:14:40.000Z | 2020-12-04T03:05:57.000Z | mindspore/ccsrc/backend/kernel_compiler/aicpu/aicpu_util.h | dilingsong/mindspore | 4276050f2494cfbf8682560a1647576f859991e8 | [
"Apache-2.0"
] | null | null | null | mindspore/ccsrc/backend/kernel_compiler/aicpu/aicpu_util.h | dilingsong/mindspore | 4276050f2494cfbf8682560a1647576f859991e8 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2020 Huawei Technologies 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 MINDSPORE_CCSRC_BACKEND_KERNEL_COMPILER_AICPU_AICPU_UTIL_H_
#define MINDSPORE_CCSRC_BACKEND_KERNEL_COMPILER_AICPU_AICPU_UTIL_H_
#include <cstdint>
#include <vector>
#include <map>
#include <string>
#include "backend/kernel_compiler/kernel.h"
namespace mindspore {
namespace kernel {
constexpr auto kInitDataSetQueue = "InitDataSetQueue";
constexpr auto kInitData = "InitData";
constexpr auto kGetNext = "GetNext";
constexpr auto kPrint = "Print";
constexpr auto kPack = "Pack";
constexpr auto kOutputTypes = "output_types";
constexpr auto kOutputShapes = "output_shapes";
constexpr auto kChannelName = "channel_name";
constexpr auto kSharedName = "shared_name";
constexpr auto kShapes = "shapes";
constexpr auto kTypes = "types";
constexpr auto kQueueName = "queue_name";
constexpr auto kSeed = "seed";
constexpr auto kSeed0 = "Seed0";
constexpr auto kSeed1 = "Seed1";
constexpr auto kSeed2 = "seed2";
constexpr auto kTopK = "TopK";
constexpr auto kTopKV2 = "TopKV2";
struct AicpuParamHead {
uint32_t length; // Total length: include cunstom message
uint32_t ioAddrNum; // Input and output address number
uint32_t extInfoLength; // extInfo struct Length
uint64_t extInfoAddr; // extInfo address
} __attribute__((packed));
class AicpuOpUtil {
public:
static int MsTypeToProtoType(TypeId ms_type);
private:
// kernel id
static uint64_t KernelId_;
};
} // namespace kernel
} // namespace mindspore
#endif // MINDSPORE_CCSRC_BACKEND_KERNEL_COMPILER_AICPU_AICPU_UTIL_H_
| 32.676923 | 75 | 0.763653 | [
"vector"
] |
d68bd357e077442633d198180cc325657ddd0ca0 | 55,570 | h | C | cppForSwig/BinaryData.h | RomanValov/ArmoryDB | 625eff9712161676ad83deb03616e6edb48283ca | [
"MIT"
] | null | null | null | cppForSwig/BinaryData.h | RomanValov/ArmoryDB | 625eff9712161676ad83deb03616e6edb48283ca | [
"MIT"
] | null | null | null | cppForSwig/BinaryData.h | RomanValov/ArmoryDB | 625eff9712161676ad83deb03616e6edb48283ca | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
// //
// Copyright (C) 2011-2015, Armory Technologies, Inc. //
// Distributed under the GNU Affero General Public License (AGPL v3) //
// See LICENSE-ATI or http://www.gnu.org/licenses/agpl.html //
// //
////////////////////////////////////////////////////////////////////////////////
#ifndef _BINARYDATA_H_
#define _BINARYDATA_H_
#include <stdio.h>
#if defined(_MSC_VER) || defined(__MINGW32__)
#if _MSC_PLATFORM_TOOLSET < 110
#include <stdint.h>
#endif
#ifndef ssize_t
#ifdef _WIN32
#define ssize_t SSIZE_T
#else
#define ssize_t long
#endif
#endif
#else
#include <stdlib.h>
#include <inttypes.h>
#include <cstring>
#include <stdint.h>
#ifndef PAGESIZE
#include <unistd.h>
#define PAGESIZE sysconf(_SC_PAGESIZE)
#endif
#ifndef PAGEFLOOR
// "Round" a ptr down to the beginning of the memory page containing it
// PAGERANGE gives us a size to lock/map as a multiple of the PAGESIZE
#define PAGEFLOOR(ptr,sz) ((void*)(((size_t)(ptr)) & (~(PAGESIZE-1)) ))
#define PAGERANGE(ptr,sz) ( (((size_t)(ptr)+(sz)-1) | (PAGESIZE-1)) + 1 - PAGEFLOOR(ptr,sz) )
#endif
#endif
#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
#include <atomic>
// We can remove these includes (Crypto++ ) if we remove the GenerateRandom()
#include "log.h"
#define DEFAULT_BUFFER_SIZE 32*1048576
#include "UniversalTimer.h"
#define READHEX BinaryData::CreateFromHex
#define READ_UINT8_LE BinaryData::StrToIntLE<uint8_t>
#define READ_UINT16_LE BinaryData::StrToIntLE<uint16_t>
#define READ_UINT32_LE BinaryData::StrToIntLE<uint32_t>
#define READ_UINT64_LE BinaryData::StrToIntLE<uint64_t>
#define READ_UINT8_BE BinaryData::StrToIntBE<uint8_t>
#define READ_UINT16_BE BinaryData::StrToIntBE<uint16_t>
#define READ_UINT32_BE BinaryData::StrToIntBE<uint32_t>
#define READ_UINT64_BE BinaryData::StrToIntBE<uint64_t>
#define READ_UINT8_HEX_LE(A) (READ_UINT8_LE(READHEX(A)))
#define READ_UINT16_HEX_LE(A) (READ_UINT16_LE(READHEX(A)))
#define READ_UINT32_HEX_LE(A) (READ_UINT32_LE(READHEX(A)))
#define READ_UINT64_HEX_LE(A) (READ_UINT64_LE(READHEX(A)))
#define READ_UINT8_HEX_BE(A) (READ_UINT8_BE(READHEX(A)))
#define READ_UINT16_HEX_BE(A) (READ_UINT16_BE(READHEX(A)))
#define READ_UINT32_HEX_BE(A) (READ_UINT32_BE(READHEX(A)))
#define READ_UINT64_HEX_BE(A) (READ_UINT64_BE(READHEX(A)))
#define WRITE_UINT8_LE BinaryData::IntToStrLE<uint8_t>
#define WRITE_UINT16_LE BinaryData::IntToStrLE<uint16_t>
#define WRITE_UINT32_LE BinaryData::IntToStrLE<uint32_t>
#define WRITE_UINT64_LE BinaryData::IntToStrLE<uint64_t>
#define WRITE_UINT8_BE BinaryData::IntToStrBE<uint8_t>
#define WRITE_UINT16_BE BinaryData::IntToStrBE<uint16_t>
#define WRITE_UINT32_BE BinaryData::IntToStrBE<uint32_t>
#define WRITE_UINT64_BE BinaryData::IntToStrBE<uint64_t>
enum ENDIAN
{
ENDIAN_LITTLE,
ENDIAN_BIG
};
#define LE ENDIAN_LITTLE
#define BE ENDIAN_BIG
class BinaryDataRef;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class BinaryData
{
public:
/////////////////////////////////////////////////////////////////////////////
BinaryData(void) : data_(0) { }
explicit BinaryData(size_t sz) { alloc(sz); }
BinaryData(uint8_t const * inData, size_t sz)
{ copyFrom(inData, sz); }
BinaryData(uint8_t const * dstart, uint8_t const * dend )
{ copyFrom(dstart, dend); }
BinaryData(std::string const & str) { copyFrom(str); }
BinaryData(BinaryData const & bd) { copyFrom(bd); }
BinaryData(BinaryData && copy)
{ data_ = move(copy.data_); }
BinaryData(BinaryDataRef const & bdRef);
size_t getSize(void) const { return data_.size(); }
~BinaryData(void)
{
data_.clear();
}
bool isNull(void) const { return (data_.size()==0);}
bool isZero(void) const;
BinaryData& operator=(const BinaryData &o)
{
data_ = o.data_;
return *this;
}
BinaryData& operator=(BinaryData &&o)
{
swap(data_, o.data_);
return *this;
}
/////////////////////////////////////////////////////////////////////////////
uint8_t const * getPtr(void) const
{
if(getSize()==0)
return NULL;
else
return &(data_[0]);
}
/////////////////////////////////////////////////////////////////////////////
uint8_t* getPtr(void)
{
if(getSize()==0)
return NULL;
else
return &(data_[0]);
}
/////////////////////////////////////////////////////////////////////////////
char const * getCharPtr(void) const
{
if (getSize() == 0)
{
LOGERR << "Tried to get pointer of empty BinaryData";
throw std::runtime_error("Tried to get pointer of empty BinaryData");
}
else
return reinterpret_cast<const char*>(&data_[0]);
}
/////////////////////////////////////////////////////////////////////////////
char* getCharPtr(void)
{
if(getSize()==0)
{
LOGERR << "Tried to get pointer of empty BinaryData";
throw std::runtime_error("Tried to get pointer of empty BinaryData");
}
else
return reinterpret_cast<char*>(&data_[0]);
}
/////////////////////////////////////////////////////////////////////////////
const std::vector<uint8_t>& getDataVector(void) const
{
return data_;
}
BinaryDataRef getRef(void) const;
//uint8_t const * getConstPtr(void) const { return &(data_[0]); }
/////////////////////////////////////////////////////////////////////////////
// We allocate space as necesssary
void copyFrom(uint8_t const * start, uint8_t const * end)
{ copyFrom( start, (end-start)); } // [start, end)
void copyFrom(std::string const & str)
{ copyFrom( (uint8_t*)str.data(), str.size()); }
void copyFrom(BinaryData const & bd)
{ copyFrom( bd.getPtr(), bd.getSize() ); }
void copyFrom(BinaryDataRef const & bdr);
void copyFrom(uint8_t const * inData, size_t sz)
{
if(inData==NULL || sz == 0)
alloc(0);
else
{
alloc(sz);
memcpy( &(data_[0]), inData, sz);
}
}
/////////////////////////////////////////////////////////////////////////////
// UNSAFE -- you don't know if outData holds enough space for this
void copyTo(uint8_t* outData) const { memcpy( outData, &(data_[0]), getSize()); }
void copyTo(uint8_t* outData, size_t sz) const { memcpy( outData, &(data_[0]), (size_t)sz); }
void copyTo(uint8_t* outData, size_t offset, size_t sz) const { memcpy( outData, &(data_[offset]), (size_t)sz); }
void copyTo(BinaryData & bd) const
{
bd.resize(data_.size());
#ifdef _MSC_VER
if(data_.size())
#endif
memcpy( bd.getPtr(), &data_[0], data_.size());
}
void fill(uint8_t ch) { if(getSize()>0) memset(getPtr(), ch, getSize()); }
uint8_t & operator[](ssize_t i) { return (i<0 ? data_[getSize()+i] : data_[i]); }
uint8_t operator[](ssize_t i) const { return (i<0 ? data_[getSize()+i] : data_[i]); }
/////////////////////////////////////////////////////////////////////////////
friend std::ostream& operator<<(std::ostream& os, BinaryData const & bd)
{
os << bd.toHexStr();
return os;
}
/////////////////////////////////////////////////////////////////////////////
BinaryData operator+(BinaryData const & bd2) const
{
BinaryData out(getSize() + bd2.getSize());
memcpy(out.getPtr(), getPtr(), getSize());
memcpy(out.getPtr()+getSize(), bd2.getPtr(), bd2.getSize());
return out;
}
/////////////////////////////////////////////////////////////////////////////
// This is about as efficient as we're going to get...
BinaryData & append(BinaryData const & bd2)
{
if(bd2.getSize()==0)
return (*this);
if(getSize()==0)
copyFrom(bd2.getPtr(), bd2.getSize());
else
data_.insert(data_.end(), bd2.data_.begin(), bd2.data_.end());
return (*this);
}
/////////////////////////////////////////////////////////////////////////////
BinaryData & append(BinaryDataRef const & bd2);
/////////////////////////////////////////////////////////////////////////////
BinaryData & append(uint8_t const * str, size_t sz);
/////////////////////////////////////////////////////////////////////////////
BinaryData & append(uint8_t byte)
{
data_.insert(data_.end(), byte);
return (*this);
}
/////////////////////////////////////////////////////////////////////////////
int32_t find(BinaryDataRef const & matchStr, uint32_t startPos=0);
/////////////////////////////////////////////////////////////////////////////
int32_t find(BinaryData const & matchStr, uint32_t startPos=0);
/////////////////////////////////////////////////////////////////////////////
bool contains(BinaryDataRef const & matchStr, uint32_t startPos=0);
/////////////////////////////////////////////////////////////////////////////
bool contains(BinaryData const & matchStr, uint32_t startPos=0);
/////////////////////////////////////////////////////////////////////////////
bool startsWith(BinaryDataRef const & matchStr) const;
/////////////////////////////////////////////////////////////////////////////
bool startsWith(BinaryData const & matchStr) const;
/////////////////////////////////////////////////////////////////////////////
bool endsWith(BinaryDataRef const & matchStr) const;
/////////////////////////////////////////////////////////////////////////////
bool endsWith(BinaryData const & matchStr) const;
/////////////////////////////////////////////////////////////////////////////
BinaryDataRef getSliceRef(ssize_t start_pos, uint32_t nChar) const;
/////////////////////////////////////////////////////////////////////////////
BinaryData getSliceCopy(ssize_t start_pos, uint32_t nChar) const;
/////////////////////////////////////////////////////////////////////////////
bool operator<(BinaryData const & bd2) const;
/////////////////////////////////////////////////////////////////////////////
bool operator<(BinaryDataRef const & bd2) const;
/////////////////////////////////////////////////////////////////////////////
bool operator==(BinaryData const & bd2) const
{
if(getSize() != bd2.getSize())
return false;
return (memcmp(getPtr(), bd2.getPtr(), getSize()) == 0);
// Why did I do this before?
//for(unsigned int i=0; i<getSize(); i++)
//if( data_[i] != bd2.data_[i] )
//return false;
//return true;
}
/////////////////////////////////////////////////////////////////////////////
bool operator!=(BinaryData const & bd2) const { return (!((*this)==bd2)); }
/////////////////////////////////////////////////////////////////////////////
bool operator==(BinaryDataRef const & bd2) const;
/////////////////////////////////////////////////////////////////////////////
bool operator!=(BinaryDataRef const & bd2) const { return (!((*this)==bd2)); }
/////////////////////////////////////////////////////////////////////////////
bool operator>(BinaryData const & bd2) const;
/////////////////////////////////////////////////////////////////////////////
bool operator>=(BinaryData const & bd2) const
{
return (*this > bd2 || *this == bd2);
}
/////////////////////////////////////////////////////////////////////////////
// These are always memory-safe
void copyTo(std::string & str) {
#ifdef _MSC_VER
if(getSize())
#endif
str.assign( (char const *)(&(data_[0])), getSize());
}
/////////////////////////////////////////////////////////////////////////////
std::string toBinStr(bool bigEndian=false) const
{
if(getSize()==0)
return std::string("");
if(bigEndian)
{
BinaryData out = copySwapEndian();
return std::string((char const *)(out.getPtr()), getSize());
}
else
return std::string((char const *)(getPtr()), getSize());
}
char* toCharPtr(void) const { return (char*)(&(data_[0])); }
unsigned char* toUCharPtr(void) const { return (unsigned char*)(&(data_[0])); }
void resize(size_t sz) { data_.resize(sz); }
void reserve(size_t sz) { data_.reserve(sz); }
/////////////////////////////////////////////////////////////////////////////
// Swap endianness of the bytes in the index range [pos1, pos2)
BinaryData& swapEndian(size_t pos1=0, size_t pos2=0)
{
if(getSize()==0)
return (*this);
if(pos2 <= pos1)
pos2 = getSize();
size_t totalBytes = pos2-pos1;
for(size_t i=0; i<(totalBytes/2); i++)
{
uint8_t d1 = data_[pos1+i];
data_[pos1+i] = data_[pos2-(i+1)];
data_[pos2-(i+1)] = d1;
}
return (*this);
}
/////////////////////////////////////////////////////////////////////////////
// Swap endianness of the bytes in the index range [pos1, pos2)
BinaryData copySwapEndian(size_t pos1=0, size_t pos2=0) const
{
BinaryData bdout(*this);
bdout.swapEndian(pos1, pos2);
return bdout;
}
/////////////////////////////////////////////////////////////////////////////
std::string toHexStr(bool bigEndian=false) const
{
if(getSize()==0)
return std::string("");
static char hexLookupTable[16] = {'0','1','2','3',
'4','5','6','7',
'8','9','a','b',
'c','d','e','f' };
BinaryData bdToHex(*this);
if(bigEndian)
bdToHex.swapEndian();
std::vector<int8_t> outStr(2*getSize());
for( size_t i=0; i<getSize(); i++)
{
uint8_t nextByte = bdToHex.data_[i];
outStr[2*i ] = hexLookupTable[ (nextByte >> 4) & 0x0F ];
outStr[2*i+1] = hexLookupTable[ (nextByte ) & 0x0F ];
}
return std::string((char const *)(&(outStr[0])), 2*getSize());
}
/////////////////////////////////////////////////////////////////////////////
static BinaryData CreateFromHex(std::string const & str)
{
BinaryData out;
out.createFromHex(str);
return out;
}
/////////////////////////////////////////////////////////////////////////////
// This is an architecture-agnostic way to serialize integers to little- or
// big-endian. Bit-shift & mod will always return the lowest significant
// bytes, so we can put them into an array of bytes in the desired order.
template<typename INTTYPE>
static BinaryData IntToStrLE(INTTYPE val)
{
static const uint8_t SZ = sizeof(INTTYPE);
BinaryData out(SZ);
for(uint8_t i=0; i<SZ; i++, val>>=8)
out[i] = val % 256;
return out;
}
/////////////////////////////////////////////////////////////////////////////
template<typename INTTYPE>
inline static BinaryData IntToStrBE(INTTYPE val)
{
static const uint8_t SZ = sizeof(INTTYPE);
BinaryData out(SZ);
for(uint8_t i=0; i<SZ; i++, val>>=8)
out[(SZ-1)-i] = val % 256;
return out;
}
/////////////////////////////////////////////////////////////////////////////
template<typename INTTYPE>
static INTTYPE StrToIntLE(BinaryData binstr)
{
uint8_t const SZ = sizeof(INTTYPE);
if(binstr.getSize() != SZ)
{
LOGERR << "StrToInt: strsz: " << binstr.getSize() << " intsz: " << SZ;
return (INTTYPE)0;
}
/*INTTYPE out = 0;
for(uint8_t i=0; i<SZ; i++)
out |= ((INTTYPE)binstr[i]) << (8*i);*/
auto intPtr = (INTTYPE*)binstr.getPtr();
return *intPtr;
}
/////////////////////////////////////////////////////////////////////////////
template<typename INTTYPE>
static INTTYPE StrToIntBE(BinaryData binstr)
{
uint8_t const SZ = sizeof(INTTYPE);
if(binstr.getSize() != SZ)
{
LOGERR << "StrToInt: strsz: " << binstr.getSize() << " intsz: " << SZ;
return (INTTYPE)0;
}
INTTYPE out = 0;
for(uint8_t i=0; i<SZ; i++)
out |= ((INTTYPE)binstr[i]) << (8*((SZ-1)-i));
return out;
}
/////////////////////////////////////////////////////////////////////////////
template<typename INTTYPE>
static INTTYPE StrToIntLE(uint8_t const * ptr)
{
/*INTTYPE out = 0;
for(uint8_t i=0; i<sizeof(INTTYPE); i++)
out |= ((INTTYPE)ptr[i]) << (8*i);*/
auto intPtr = (INTTYPE*)ptr;
return *intPtr;
}
/////////////////////////////////////////////////////////////////////////////
template<typename INTTYPE>
static INTTYPE StrToIntBE(uint8_t const * ptr)
{
uint8_t const SZ = sizeof(INTTYPE);
INTTYPE out = 0;
for(uint8_t i=0; i<SZ; i++)
out |= ((INTTYPE)ptr[i]) << (8*((SZ-1)-i));
return out;
}
/////////////////////////////////////////////////////////////////////////////
void createFromHex(const std::string& str);
void createFromHex(BinaryDataRef const & bdr);
// For deallocating all the memory that is currently used by this BD
void clear(void) { data_.clear(); }
std::vector<uint8_t> release(void)
{
auto vec = move(data_);
clear();
return vec;
}
/////////////////////////////////////////////////////////////////////////////
const std::vector<uint8_t>& getVector(void) const
{
return data_;
}
public:
static BinaryData EmptyBinData_;
protected:
std::vector<uint8_t> data_;
private:
void alloc(size_t sz)
{
if(sz != getSize())
{
data_.clear();
data_.resize(sz);
}
}
};
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class BinaryDataRef
{
public:
/////////////////////////////////////////////////////////////////////////////
BinaryDataRef(void) : ptr_(NULL), nBytes_(0)
{
// Nothing to put here
}
/////////////////////////////////////////////////////////////////////////////
BinaryDataRef(uint8_t const * inData, size_t sz)
{
setRef(inData, sz);
}
/////////////////////////////////////////////////////////////////////////////
BinaryDataRef(uint8_t const * dstart, uint8_t const * dend )
{
setRef(dstart,dend);
}
/////////////////////////////////////////////////////////////////////////////
BinaryDataRef(BinaryDataRef const & bdr)
{
ptr_ = bdr.ptr_;
nBytes_ = bdr.nBytes_;
}
/////////////////////////////////////////////////////////////////////////////
BinaryDataRef(BinaryData const & bd)
{
if(bd.getSize()!=0)
{
ptr_ = bd.getPtr();
nBytes_ = bd.getSize();
}
else
{
ptr_= NULL;
nBytes_ = 0;
}
}
/////////////////////////////////////////////////////////////////////////////
void reset(void)
{
ptr_ = nullptr;
nBytes_ = 0;
}
/////////////////////////////////////////////////////////////////////////////
uint8_t const * getPtr(void) const { return ptr_; }
size_t getSize(void) const { return nBytes_; }
bool isNull(void) { return (ptr_==NULL);}
/////////////////////////////////////////////////////////////////////////////
void setRef(uint8_t const * inData, size_t sz)
{
ptr_ = inData;
nBytes_ = sz;
}
void setRef(uint8_t const * start, uint8_t const * end)
{ setRef( start, (end-start)); } // [start, end)
void setRef(std::string const & str)
{ setRef( (uint8_t*)str.data(), str.size()); }
void setRef(BinaryData const & bd)
{ setRef( bd.getPtr(), bd.getSize() ); }
/////////////////////////////////////////////////////////////////////////////
// UNSAFE -- you don't know if outData holds enough space for this
void copyTo(uint8_t* outData) const { memcpy( outData, ptr_, (size_t)nBytes_); }
void copyTo(uint8_t* outData, size_t sz) const { memcpy( outData, ptr_, (size_t)sz); }
void copyTo(uint8_t* outData, size_t offset, size_t sz) const
{ memcpy( outData, ptr_+offset, (size_t)sz); }
void copyTo(BinaryData & bd) const
{
bd.resize(nBytes_);
memcpy( bd.getPtr(), ptr_, (size_t)nBytes_);
}
/////////////////////////////////////////////////////////////////////////////
BinaryData copy(void) const
{
BinaryData outData(nBytes_);
copyTo(outData);
return outData;
}
/////////////////////////////////////////////////////////////////////////////
// These are always memory-safe
void copyTo(std::string & str) { str.assign( (char const *)(ptr_), nBytes_); }
/////////////////////////////////////////////////////////////////////////////
friend std::ostream& operator<<(std::ostream& os, BinaryDataRef const & bd)
{
os << bd.toHexStr();
return os;
}
/////////////////////////////////////////////////////////////////////////////
std::string toBinStr(bool bigEndian=false) const
{
if(getSize()==0)
return std::string("");
if(bigEndian)
{
BinaryData out = copy();
return std::string((char const *)(out.swapEndian().getPtr()), nBytes_);
}
else
return std::string((char const *)(ptr_), nBytes_);
}
/////////////////////////////////////////////////////////////////////////////
char* toCharPtr(void) const { return (char*)(ptr_); }
unsigned char* toUCharPtr(void) const { return (unsigned char*)(ptr_); }
/////////////////////////////////////////////////////////////////////////////
uint8_t const & operator[](ssize_t i) const { return (i<0 ? ptr_[nBytes_+i] : ptr_[i]); }
bool isValid(void) const { return ptr_ != NULL; }
/////////////////////////////////////////////////////////////////////////////
int32_t find(BinaryDataRef const & matchStr, uint32_t startPos=0)
{
int32_t finalAnswer = -1;
if(matchStr.getSize()==0)
return startPos;
for(int32_t i=startPos; i<=(int32_t)nBytes_-(int32_t)matchStr.nBytes_; i++)
{
if(matchStr.ptr_[0] != ptr_[i])
continue;
for(uint32_t j=0; j<matchStr.nBytes_; j++)
{
if(matchStr.ptr_[j] != ptr_[i+j])
break;
// If we are at this instruction and is the last index, it's a match
if(j==matchStr.nBytes_-1)
finalAnswer = i;
}
if(finalAnswer != -1)
break;
}
return finalAnswer;
}
/////////////////////////////////////////////////////////////////////////////
int32_t find(BinaryData const & matchStr, uint32_t startPos=0)
{
BinaryDataRef bdr(matchStr);
return find(bdr, startPos);
}
/////////////////////////////////////////////////////////////////////////////
bool contains(BinaryDataRef const & matchStr, uint32_t startPos=0)
{
return (find(matchStr, startPos) != -1);
}
/////////////////////////////////////////////////////////////////////////////
bool contains(BinaryData const & matchStr, uint32_t startPos=0)
{
BinaryDataRef bdr(matchStr);
return (find(bdr, startPos) != -1);
}
/////////////////////////////////////////////////////////////////////////////
bool startsWith(BinaryDataRef const & matchStr) const
{
if(matchStr.getSize() > nBytes_)
return false;
for(uint32_t i=0; i<matchStr.getSize(); i++)
if(matchStr[i] != (*this)[i])
return false;
return true;
}
/////////////////////////////////////////////////////////////////////////////
bool startsWith(BinaryData const & matchStr) const
{
if(matchStr.getSize() > nBytes_)
return false;
for(uint32_t i=0; i<matchStr.getSize(); i++)
if(matchStr[i] != (*this)[i])
return false;
return true;
}
/////////////////////////////////////////////////////////////////////////////
bool endsWith(BinaryDataRef const & matchStr) const
{
size_t sz = matchStr.getSize();
if(sz > nBytes_)
return false;
for(size_t i=0; i<sz; i++)
if(matchStr[sz-(i+1)] != (*this)[nBytes_-(i+1)])
return false;
return true;
}
/////////////////////////////////////////////////////////////////////////////
bool endsWith(BinaryData const & matchStr) const
{
size_t sz = matchStr.getSize();
if(sz > nBytes_)
return false;
for(size_t i=0; i<sz; i++)
if(matchStr[sz-(i+1)] != (*this)[nBytes_-(i+1)])
return false;
return true;
}
/////////////////////////////////////////////////////////////////////////////
BinaryDataRef getSliceRef(ssize_t start_pos, size_t nChar) const
{
if(start_pos < 0)
start_pos = nBytes_ + start_pos;
if(start_pos + nChar > nBytes_)
{
std::cerr << "getSliceRef: Invalid BinaryData access" << std::endl;
return BinaryDataRef();
}
return BinaryDataRef( getPtr()+start_pos, nChar);
}
/////////////////////////////////////////////////////////////////////////////
BinaryData getSliceCopy(ssize_t start_pos, size_t nChar) const
{
if(start_pos < 0)
start_pos = nBytes_ + start_pos;
if(start_pos + nChar > nBytes_)
{
std::cerr << "getSliceCopy: Invalid BinaryData access" << std::endl;
return BinaryDataRef();
}
return BinaryData( getPtr()+start_pos, nChar);
}
/////////////////////////////////////////////////////////////////////////////
bool isSameRefAs(BinaryDataRef const & bdRef2)
{
return (ptr_ == bdRef2.ptr_ && nBytes_ == bdRef2.nBytes_);
}
/////////////////////////////////////////////////////////////////////////////
bool operator<(BinaryDataRef const & bd2) const;
/////////////////////////////////////////////////////////////////////////////
bool operator==(BinaryDataRef const & bd2) const
{
if(nBytes_ != bd2.nBytes_)
return false;
else if(ptr_ == bd2.ptr_)
return true;
return (memcmp(getPtr(), bd2.getPtr(), getSize()) == 0);
//for(unsigned int i=0; i<nBytes_; i++)
//if( ptr_[i] != bd2.ptr_[i] )
//return false;
//return true;
}
/////////////////////////////////////////////////////////////////////////////
bool operator==(BinaryData const & bd2) const
{
if(nBytes_ != bd2.getSize())
return false;
else if(ptr_ == bd2.getPtr())
return true;
return (memcmp(getPtr(), bd2.getPtr(), getSize()) == 0);
//for(unsigned int i=0; i<nBytes_; i++)
//if( ptr_[i] != bd2[i])
//return false;
//return true;
}
/////////////////////////////////////////////////////////////////////////////
bool operator!=(BinaryDataRef const & bd2) const { return !((*this)==bd2); }
bool operator!=(BinaryData const & bd2) const { return !((*this)==bd2); }
/////////////////////////////////////////////////////////////////////////////
bool operator>(BinaryDataRef const & bd2) const;
/////////////////////////////////////////////////////////////////////////////
std::string toHexStr(bool bigEndian=false) const
{
if(getSize() == 0)
return std::string("");
static char hexLookupTable[16] = {'0','1','2','3',
'4','5','6','7',
'8','9','a','b',
'c','d','e','f' };
BinaryData bdToHex(*this);
if(bigEndian)
bdToHex.swapEndian();
std::vector<int8_t> outStr(2*nBytes_);
for(size_t i=0; i<nBytes_; i++)
{
uint8_t nextByte = *(bdToHex.getPtr()+i);
outStr[2*i ] = hexLookupTable[ (nextByte >> 4) & 0x0F ];
outStr[2*i+1] = hexLookupTable[ (nextByte ) & 0x0F ];
}
return std::string((char const *)(&(outStr[0])), 2*nBytes_);
}
private:
uint8_t const * ptr_;
size_t nBytes_;
private:
};
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class BinaryReader
{
public:
/////////////////////////////////////////////////////////////////////////////
BinaryReader(int sz=0) :
bdStr_(sz),
pos_(0)
{
// Nothing needed here
}
/////////////////////////////////////////////////////////////////////////////
BinaryReader(BinaryData const & toRead)
{
setNewData(toRead);
}
/////////////////////////////////////////////////////////////////////////////
BinaryReader(uint8_t* ptr, uint32_t nBytes)
{
setNewData(ptr, nBytes);
}
/////////////////////////////////////////////////////////////////////////////
void setNewData(BinaryData const & toRead)
{
bdStr_ = toRead;
pos_ = 0;
}
/////////////////////////////////////////////////////////////////////////////
void setNewData(uint8_t* ptr, uint32_t nBytes)
{
bdStr_ = BinaryData(ptr, nBytes);
pos_ = 0;
}
/////////////////////////////////////////////////////////////////////////////
void advance(uint32_t nBytes);
/////////////////////////////////////////////////////////////////////////////
void rewind(size_t nBytes);
/////////////////////////////////////////////////////////////////////////////
void resize(size_t nBytes);
/////////////////////////////////////////////////////////////////////////////
uint64_t get_var_int(uint8_t* nRead=NULL);
/////////////////////////////////////////////////////////////////////////////
uint8_t get_uint8_t(ENDIAN e=LE)
{
uint8_t outVal = bdStr_[pos_];
pos_ += 1;
return outVal;
}
/////////////////////////////////////////////////////////////////////////////
uint16_t get_uint16_t(ENDIAN e=LE)
{
uint16_t outVal = (e==LE ? READ_UINT16_LE(bdStr_.getPtr() + pos_) :
READ_UINT16_BE(bdStr_.getPtr() + pos_));
pos_ += 2;
return outVal;
}
/////////////////////////////////////////////////////////////////////////////
uint32_t get_uint32_t(ENDIAN e=LE)
{
uint32_t outVal = (e==LE ? READ_UINT32_LE(bdStr_.getPtr() + pos_) :
READ_UINT32_BE(bdStr_.getPtr() + pos_));
pos_ += 4;
return outVal;
}
/////////////////////////////////////////////////////////////////////////////
uint32_t get_int32_t(ENDIAN e = LE)
{
uint32_t outVal = (e == LE ?
BinaryData::StrToIntLE<int32_t>(bdStr_.getPtr() + pos_) :
BinaryData::StrToIntBE<int32_t>(bdStr_.getPtr() + pos_));
pos_ += 4;
return outVal;
}
/////////////////////////////////////////////////////////////////////////////
uint64_t get_uint64_t(ENDIAN e=LE)
{
uint64_t outVal = (e==LE ? READ_UINT64_LE(bdStr_.getPtr() + pos_) :
READ_UINT64_BE(bdStr_.getPtr() + pos_));
pos_ += 8;
return outVal;
}
/////////////////////////////////////////////////////////////////////////////
void get_BinaryData(BinaryData & bdTarget, uint32_t nBytes)
{
bdTarget.copyFrom( bdStr_.getPtr() + pos_, nBytes);
pos_ += nBytes;
}
/////////////////////////////////////////////////////////////////////////////
void get_BinaryData(uint8_t* targPtr, uint32_t nBytes)
{
bdStr_.copyTo(targPtr, pos_, nBytes);
pos_ += nBytes;
}
/////////////////////////////////////////////////////////////////////////////
// Take the remaining buffer and shift it to the front
// then return a pointer to where the old data ends
//
//
// Before: pos
// |
// V
// [ a b c d e f g h i j k l m n o p q r s t]
//
// After: pos return*
// | |
// V V
// [ m n o p q r s t - - - - - - - - - - - -]
//
//
std::pair<uint8_t*, size_t> rotateRemaining(void)
{
size_t nRemain = getSizeRemaining();
//if(pos_ > nRemain+1)
//memcpy(bdStr_.getPtr(), bdStr_.getPtr() + pos_, nRemain);
//else
memmove(bdStr_.getPtr(), bdStr_.getPtr() + pos_, nRemain);
pos_ = 0;
return std::make_pair(bdStr_.getPtr() + nRemain, getSize() - nRemain);
}
/////////////////////////////////////////////////////////////////////////////
void resetPosition(void) { pos_ = 0; }
size_t getPosition(void) const { return pos_; }
size_t getSize(void) const { return bdStr_.getSize(); }
size_t getSizeRemaining(void) const { return getSize() - pos_; }
bool isEndOfStream(void) const { return pos_ >= getSize(); }
uint8_t* exposeDataPtr(void) { return bdStr_.getPtr(); }
uint8_t const * getCurrPtr(void) { return bdStr_.getPtr() + pos_; }
private:
BinaryData bdStr_;
size_t pos_;
};
class SecureBinaryData;
class BinaryRefReader
{
public:
/////////////////////////////////////////////////////////////////////////////
BinaryRefReader(size_t sz=0) :
bdRef_(),
totalSize_(sz)
{
pos_.store(0, std::memory_order_relaxed);
}
BinaryRefReader& operator=(const BinaryRefReader& brr)
{
if(&brr == this)
return *this;
bdRef_ = brr.bdRef_;
totalSize_ = brr.totalSize_;
pos_.store(brr.pos_.load(std::memory_order_relaxed), std::memory_order_relaxed);
return *this;
}
BinaryRefReader(const BinaryRefReader& brr)
{
bdRef_ = brr.bdRef_;
totalSize_ = brr.totalSize_;
pos_.store(brr.pos_.load(std::memory_order_relaxed), std::memory_order_relaxed);
}
/////////////////////////////////////////////////////////////////////////////
BinaryRefReader(BinaryData const & toRead) { setNewData(toRead); }
BinaryRefReader(BinaryDataRef const & toRead) { setNewData(toRead); }
// Default to INF size -- leave it to the user to guarantee that he's
// not reading past the end of rawPtr
BinaryRefReader(uint8_t const * rawPtr, size_t nBytes=UINT32_MAX)
{
setNewData(rawPtr, nBytes);
}
void setNewData(BinaryData const & toRead)
{
setNewData(toRead.getPtr(), toRead.getSize());
}
void setNewData(BinaryDataRef const & toRead)
{
setNewData(toRead.getPtr(), toRead.getSize());
}
void setNewData(uint8_t const * ptr, size_t nBytes=UINT32_MAX)
{
bdRef_ = BinaryDataRef(ptr, nBytes);
totalSize_ = nBytes;
pos_.store(0, std::memory_order_relaxed);
}
/////////////////////////////////////////////////////////////////////////////
void advance(size_t nBytes);
/////////////////////////////////////////////////////////////////////////////
void rewind(uint32_t nBytes)
{
size_t start = pos_.load(std::memory_order_relaxed);
pos_.fetch_sub(nBytes, std::memory_order_relaxed);
if(pos_.load(std::memory_order_relaxed) > start)
pos_.store(0, std::memory_order_relaxed);
}
/////////////////////////////////////////////////////////////////////////////
uint64_t get_var_int(uint8_t* nRead=NULL);
/////////////////////////////////////////////////////////////////////////////
uint8_t get_uint8_t(ENDIAN e=LE)
{
if (getSizeRemaining() < 1)
{
LOGERR << "buffer overflow";
throw std::runtime_error("buffer overflow");
}
uint8_t outVal = bdRef_[pos_];
pos_.fetch_add(1, std::memory_order_relaxed);
return outVal;
}
/////////////////////////////////////////////////////////////////////////////
uint16_t get_uint16_t(ENDIAN e=LE)
{
if (getSizeRemaining() < 2)
{
LOGERR << "buffer overflow";
throw std::runtime_error("buffer overflow");
}
uint16_t outVal = (e==LE ? READ_UINT16_LE(bdRef_.getPtr() + pos_) :
READ_UINT16_BE(bdRef_.getPtr() + pos_) );
pos_.fetch_add(2, std::memory_order_relaxed);
return outVal;
}
/////////////////////////////////////////////////////////////////////////////
uint32_t get_uint32_t(ENDIAN e=LE)
{
if (getSizeRemaining() < 4)
{
LOGERR << "buffer overflow";
throw std::runtime_error("buffer overflow");
}
uint32_t outVal = (e==LE ? READ_UINT32_LE(bdRef_.getPtr() + pos_) :
READ_UINT32_BE(bdRef_.getPtr() + pos_) );
pos_.fetch_add(4, std::memory_order_relaxed);
return outVal;
}
/////////////////////////////////////////////////////////////////////////////
int32_t get_int32_t(ENDIAN e = LE)
{
if (getSizeRemaining() < 4)
{
LOGERR << "buffer overflow";
throw std::runtime_error("buffer overflow");
}
int32_t outVal = (e == LE ?
BinaryData::StrToIntLE<int32_t>(bdRef_.getPtr() + pos_) :
BinaryData::StrToIntBE<int32_t>(bdRef_.getPtr() + pos_));
pos_.fetch_add(4, std::memory_order_relaxed);
return outVal;
}
/////////////////////////////////////////////////////////////////////////////
uint64_t get_uint64_t(ENDIAN e=LE)
{
if (getSizeRemaining() < 8)
{
LOGERR << "buffer overflow";
throw std::runtime_error("buffer overflow");
}
uint64_t outVal = (e==LE ? READ_UINT64_LE(bdRef_.getPtr() + pos_) :
READ_UINT64_BE(bdRef_.getPtr() + pos_) );
pos_.fetch_add(8, std::memory_order_relaxed);
return outVal;
}
/////////////////////////////////////////////////////////////////////////////
double get_double()
{
if (getSizeRemaining() < 8)
{
LOGERR << "buffer overflow";
throw std::runtime_error("buffer overflow");
}
auto doublePtr = (double*)(bdRef_.getPtr() + pos_);
pos_.fetch_add(8, std::memory_order_relaxed);
return *doublePtr;
}
/////////////////////////////////////////////////////////////////////////////
BinaryDataRef get_BinaryDataRef(uint32_t nBytes)
{
if (getSizeRemaining() < nBytes)
{
LOGERR << "buffer overflow";
throw std::runtime_error("buffer overflow");
}
BinaryDataRef bdrefout(bdRef_.getPtr() + pos_, nBytes);
pos_.fetch_add(nBytes, std::memory_order_relaxed);
return bdrefout;
}
/////////////////////////////////////////////////////////////////////////////
BinaryRefReader fork(void) const
{
return BinaryRefReader(
bdRef_.getPtr() + pos_.load(std::memory_order_relaxed), getSizeRemaining());
}
/////////////////////////////////////////////////////////////////////////////
void get_BinaryData(BinaryData & bdTarget, uint32_t nBytes)
{
if (getSizeRemaining() < nBytes)
{
LOGERR << "buffer overflow";
throw std::runtime_error("buffer overflow");
}
bdTarget.copyFrom( bdRef_.getPtr() + pos_, nBytes);
pos_.fetch_add(nBytes, std::memory_order_relaxed);
}
/////////////////////////////////////////////////////////////////////////////
BinaryData get_BinaryData(uint32_t nBytes)
{
if (getSizeRemaining() < nBytes)
{
LOGERR << "buffer overflow!";
LOGERR << "grabbing " << nBytes <<
" out of " << getSizeRemaining() << " bytes";
throw std::runtime_error("buffer overflow");
}
BinaryData out;
get_BinaryData(out, nBytes);
return out;
}
/////////////////////////////////////////////////////////////////////////////
SecureBinaryData get_SecureBinaryData(uint32_t nBytes);
/////////////////////////////////////////////////////////////////////////////
void get_BinaryData(uint8_t* targPtr, uint32_t nBytes)
{
if (getSizeRemaining() < nBytes)
{
LOGERR << "buffer overflow";
throw std::runtime_error("buffer overflow");
}
bdRef_.copyTo(targPtr, pos_, nBytes);
pos_.fetch_add(nBytes, std::memory_order_relaxed);
}
/////////////////////////////////////////////////////////////////////////////
void resetPosition(void) { pos_ = 0; }
size_t getPosition(void) const { return pos_; }
size_t getSize(void) const { return totalSize_; }
size_t getSizeRemaining(void) const { return totalSize_ - pos_.load(std::memory_order_relaxed); }
bool isEndOfStream(void) const { return pos_.load(std::memory_order_relaxed) >= totalSize_; }
uint8_t const * exposeDataPtr(void) { return bdRef_.getPtr(); }
uint8_t const * getCurrPtr(void) { return bdRef_.getPtr() + pos_.load(std::memory_order_relaxed); }
/////////////////////////////////////////////////////////////////////////////
BinaryDataRef getRawRef(void) { return bdRef_; }
private:
BinaryDataRef bdRef_;
size_t totalSize_;
/*
On at least AMD Ryzen CPUs, gcc O1/2 compilation has demonstrated that reset
and advance operations can result in out of order execution on pos leading to
unexpected offset position, when pos_ is a simple size_t.
Upgrading pos_ to either volatile or atomic<size_t> enforces the sequential
execution of operations on pos_, fixing the issue.
Since the only desirable additional feature is sequentiality, relaxed atomic
operations were prefered to volatile, as they are generally cheaper at least
on Windows (where volatiles come with acq_rel semantics by default).
*/
std::atomic<size_t> pos_;
};
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// This is only intended to be used for the four datatypes:
// uint8_t, uint16_t, uint32_t, uint64_t
// Simplicity is what makes this so useful
template<typename DTYPE>
class BitPacker
{
public:
BitPacker(void) : intVal_(0), bitsUsed_(0) {}
void putBits(DTYPE val, uint32_t bitWidth)
{
uint8_t const SZ = sizeof(DTYPE);
if(bitsUsed_ + bitWidth > SZ*8)
LOGERR << "Tried to put bits beyond end of bit field";
if(bitsUsed_==0 && bitWidth==SZ*8)
{
bitsUsed_ = SZ*8;
intVal_ = val;
return;
}
uint32_t shiftAmt = SZ*8 - (bitsUsed_ + bitWidth);
DTYPE mask = (DTYPE)((1ULL<<bitWidth) - 1);
intVal_ |= (val & mask) << shiftAmt;
bitsUsed_ += bitWidth;
}
void putBit(bool val)
{
DTYPE bit = (val ? 1 : 0);
putBits(bit, 1);
}
uint32_t getBitsUsed(void) {return bitsUsed_;}
BinaryData getBinaryData(void)
{ return BinaryData::IntToStrBE<DTYPE>(intVal_); }
// Disabling this to avoid inadvertantly using it to write out
// data in the wrong endianness. (instead, always use getBinaryData
// or writeToStream
//DTYPE getValue(void) { return intVal_; }
void reset(void) { intVal_ = 0; bitsUsed_ = 0; }
private:
DTYPE intVal_;
uint32_t bitsUsed_;
};
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// This is only intended to be used for the four datatypes:
// uint8_t, uint16_t, uint32_t, uint64_t
// Simplicity is what makes this so useful
template<typename DTYPE>
class BitUnpacker
{
public:
BitUnpacker(void) {bitsRead_=0xffffffff;}
BitUnpacker(DTYPE valToRead) {setValue(valToRead);}
BitUnpacker(BinaryRefReader & brr)
{
BinaryData bytes = brr.get_BinaryData(sizeof(DTYPE));
setValue( BinaryData::StrToIntBE<DTYPE>(bytes) );
}
void setValue(DTYPE val) { intVal_ = val; bitsRead_ = 0; }
DTYPE getBits(uint32_t bitWidth)
{
uint8_t const SZ = sizeof(DTYPE);
if(bitsRead_==0 && bitWidth==SZ*8)
{
bitsRead_ = bitWidth;
return intVal_;
}
uint32_t shiftAmt = SZ*8 - (bitsRead_ + bitWidth);
DTYPE mask = (DTYPE)((1ULL<<bitWidth) - 1);
bitsRead_ += bitWidth;
return ((intVal_ >> shiftAmt) & mask);
}
bool getBit(void)
{
return (getBits(1) > 0);
}
void reset(void) { intVal_ = 0; bitsRead_ = 0; }
private:
DTYPE intVal_;
uint32_t bitsRead_;
};
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class BinaryWriter
{
public:
/////////////////////////////////////////////////////////////////////////////
// Using the argument to pre-allocate a certain amount of capacity. Not
// required, but will improve performance if you can take a reasonable guess
// about the final size of the output data
BinaryWriter(size_t reserveSize=0) :
theString_(0)
{
if(reserveSize != 0)
theString_.reserve(reserveSize);
}
/////////////////////////////////////////////////////////////////////////////
void reserve(size_t sz) { theString_.reserve(sz); }
/////////////////////////////////////////////////////////////////////////////
// These write data properly regardless of the architecture
void put_uint8_t (const uint8_t& val, ENDIAN e=LE) { theString_.append( val ); }
/////
void put_uint16_t(const uint16_t& val, ENDIAN e=LE)
{
if (e == LE)
{
auto valPtr = (uint8_t*)&val;
theString_.append(valPtr, 2);
}
else
{
auto&& out = WRITE_UINT16_BE(val);
theString_.append(out.getPtr(), 2);
}
}
/////
void put_uint32_t(const uint32_t& val, ENDIAN e=LE)
{
if (e == LE)
{
auto valPtr = (uint8_t*)&val;
theString_.append(valPtr, 4);
}
else
{
auto&& out = WRITE_UINT32_BE(val);
theString_.append(out.getPtr(), 4);
}
}
/////
void put_int32_t(const int32_t& val, ENDIAN e = LE)
{
if (e == LE)
{
auto valPtr = (uint8_t*)&val;
theString_.append(valPtr, 4);
}
else
{
auto&& out = BinaryData::IntToStrBE<int32_t>(val);
theString_.append(out.getPtr(), 4);
}
}
/////
void put_uint64_t(const uint64_t& val, ENDIAN e=LE)
{
if (e == LE)
{
auto valPtr = (uint8_t*)&val;
theString_.append(valPtr, 8);
}
else
{
auto&& out = WRITE_UINT64_BE(val);
theString_.append(out.getPtr(), 8);
}
}
////
void put_double(const double& val)
{
auto valPtr = (uint8_t*)&val;
theString_.append(valPtr, 8);
}
/////////////////////////////////////////////////////////////////////////////
uint8_t put_var_int(const uint64_t& val)
{
if(val < 0xfd)
{
put_uint8_t((uint8_t)val);
return 1;
}
else if(val <= UINT16_MAX)
{
put_uint8_t(0xfd);
put_uint16_t((uint16_t)val);
return 3;
}
else if(val <= UINT32_MAX)
{
put_uint8_t(0xfe);
put_uint32_t((uint32_t)val);
return 5;
}
else
{
put_uint8_t(0xff);
put_uint64_t(val);
return 9;
}
}
/////////////////////////////////////////////////////////////////////////////
void put_BinaryData(BinaryData const & str, size_t offset=0, uint32_t sz=0)
{
if(offset==0)
{
if(sz==0)
theString_.append(str);
else
theString_.append(str.getPtr(), sz);
}
else
{
if(sz==0)
theString_.append(str.getPtr() + offset, str.getSize() - offset);
else
theString_.append(str.getPtr() + offset, sz);
}
}
/////////////////////////////////////////////////////////////////////////////
void put_BinaryDataRef(BinaryDataRef const & str)
{
theString_.append(str);
}
/////////////////////////////////////////////////////////////////////////////
void put_BinaryData(uint8_t const * targPtr, uint32_t nBytes)
{
theString_.append(targPtr, nBytes);
}
/////////////////////////////////////////////////////////////////////////////
template<typename T>
void put_BitPacker(BitPacker<T> & bp) { put_BinaryData(bp.getBinaryData()); }
/////////////////////////////////////////////////////////////////////////////
BinaryData const & getData(void)
{
return theString_;
}
/////////////////////////////////////////////////////////////////////////////
size_t getSize(void)
{
return theString_.getSize();
}
/////////////////////////////////////////////////////////////////////////////
BinaryDataRef getDataRef(void) const
{
return theString_.getRef();
}
/////////////////////////////////////////////////////////////////////////////
std::string toString(void)
{
return theString_.toBinStr();
}
/////////////////////////////////////////////////////////////////////////////
std::string toHex(void)
{
return theString_.toHexStr();
}
/////////////////////////////////////////////////////////////////////////////
void reset(void)
{
theString_.resize(0);
}
private:
BinaryData theString_;
};
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
class BinaryStreamBuffer
{
public:
/////////////////////////////////////////////////////////////////////////////
BinaryStreamBuffer(std::string filename="", uint32_t bufSize=DEFAULT_BUFFER_SIZE) :
binReader_(bufSize),
streamPtr_(NULL),
weOwnTheStream_(false),
bufferSize_(bufSize),
fileBytesRemaining_(0)
{
if( filename.size() > 0 )
{
streamPtr_ = new std::ifstream;
weOwnTheStream_ = true;
std::ifstream* ifstreamPtr = static_cast<std::ifstream*>(streamPtr_);
ifstreamPtr->open(OS_TranslatePath(filename.c_str()), std::ios::in | std::ios::binary);
if( !ifstreamPtr->is_open() )
{
std::cerr << "Could not open file for reading! File: " << filename.c_str() << std::endl;
std::cerr << "Aborting!" << std::endl;
throw std::runtime_error("failed to open file");
}
ifstreamPtr->seekg(0, std::ios::end);
totalStreamSize_ = (uint32_t)ifstreamPtr->tellg();
fileBytesRemaining_ = totalStreamSize_;
ifstreamPtr->seekg(0, std::ios::beg);
}
}
/////////////////////////////////////////////////////////////////////////////
void attachAsStreamBuffer(std::istream & is,
uint32_t streamSize,
uint32_t bufSz=DEFAULT_BUFFER_SIZE)
{
if(streamPtr_ != NULL && weOwnTheStream_)
{
static_cast<std::ifstream*>(streamPtr_)->close();
delete streamPtr_;
}
streamPtr_ = &is;
fileBytesRemaining_ = streamSize;
totalStreamSize_ = streamSize;
bufferSize_ = bufSz;
binReader_.resize(bufferSize_);
}
/////////////////////////////////////////////////////////////////////////////
// Refills the buffer from the stream, returns true if there is more data
// left in the stream
bool streamPull(void)
{
SCOPED_TIMER("StreamPull");
size_t prevBufSizeRemain = binReader_.getSizeRemaining();
if(fileBytesRemaining_ == 0)
return false;
if( binReader_.getPosition() <= 0)
{
// No data to shuffle, just pull from the stream buffer
if(fileBytesRemaining_ > binReader_.getSize())
{
// Enough left in the stream to fill the entire buffer
streamPtr_->read((char*)(binReader_.exposeDataPtr()), binReader_.getSize());
fileBytesRemaining_ -= binReader_.getSize();
}
else
{
// The buffer is bigger than the remaining stream size
streamPtr_->read((char*)(binReader_.exposeDataPtr()), fileBytesRemaining_);
binReader_.resize(fileBytesRemaining_);
fileBytesRemaining_ = 0;
}
}
else
{
// The buffer needs to be refilled but has leftover data at the end
std::pair<uint8_t*, size_t> leftover = binReader_.rotateRemaining();
uint8_t* putNewDataPtr = leftover.first;
size_t numBytes = leftover.second;
if(fileBytesRemaining_ > numBytes)
{
// Enough data left in the stream to fill the entire buffer
streamPtr_->read((char*)putNewDataPtr, numBytes);
fileBytesRemaining_ -= numBytes;
}
else
{
// The buffer is bigger than the remaining stream size
streamPtr_->read((char*)putNewDataPtr, fileBytesRemaining_);
binReader_.resize(fileBytesRemaining_+ prevBufSizeRemain);
fileBytesRemaining_ = 0;
}
}
return true;
}
/////////////////////////////////////////////////////////////////////////////
BinaryReader& reader(void)
{
return binReader_;
}
/////////////////////////////////////////////////////////////////////////////
size_t getFileByteLocation(void)
{
return totalStreamSize_ - (fileBytesRemaining_ + binReader_.getSizeRemaining());
}
size_t getBufferSizeRemaining(void) { return binReader_.getSizeRemaining(); }
size_t getFileSizeRemaining(void) { return fileBytesRemaining_; }
size_t getBufferSize(void) { return binReader_.getSize(); }
private:
BinaryReader binReader_;
std::istream* streamPtr_;
bool weOwnTheStream_;
size_t bufferSize_;
size_t totalStreamSize_;
size_t fileBytesRemaining_;
};
struct BinaryDataHash
{
size_t operator()(const BinaryData &x) const
{
// use the first size_t bytes of HashString in our hashtable
// hash256 should have good even distribution
const char *y = x.toCharPtr();
return *reinterpret_cast<const size_t*>(y);
}
};
#endif
| 31.271806 | 116 | 0.45413 | [
"vector"
] |
d6934e8a7dae69d66301390fe6f015f57260c367 | 34,543 | h | C | source/blender/blenkernel/BKE_mesh.h | Zorobay/blender | 9bc7e400ac544fa84b20457718c6090bd61008aa | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2021-06-01T17:04:34.000Z | 2021-06-01T17:04:34.000Z | source/blender/blenkernel/BKE_mesh.h | Zorobay/blender | 9bc7e400ac544fa84b20457718c6090bd61008aa | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | source/blender/blenkernel/BKE_mesh.h | Zorobay/blender | 9bc7e400ac544fa84b20457718c6090bd61008aa | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2022-03-14T19:02:22.000Z | 2022-03-14T19:02:22.000Z | /*
* 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.
*
* The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
* All rights reserved.
*/
#ifndef __BKE_MESH_H__
#define __BKE_MESH_H__
/** \file
* \ingroup bke
*/
/* defines BLI_INLINE */
#include "BLI_compiler_compat.h"
struct BLI_Stack;
struct BMEditMesh;
struct BMesh;
struct BMeshCreateParams;
struct BMeshFromMeshParams;
struct BMeshToMeshParams;
struct BoundBox;
struct CustomData;
struct CustomData_MeshMasks;
struct Depsgraph;
struct EdgeHash;
struct ID;
struct KeyBlock;
struct LinkNode;
struct ListBase;
struct MDeformVert;
struct MDisps;
struct MEdge;
struct MFace;
struct MLoop;
struct MLoopTri;
struct MLoopUV;
struct MPoly;
struct MVert;
struct Main;
struct MemArena;
struct Mesh;
struct ModifierData;
struct Object;
struct Scene;
#ifdef __cplusplus
extern "C" {
#endif
/* setting zero so we can catch bugs in OpenMP/BMesh */
#ifdef DEBUG
# define BKE_MESH_OMP_LIMIT 0
#else
# define BKE_MESH_OMP_LIMIT 10000
#endif
/* *** mesh.c *** */
struct BMesh *BKE_mesh_to_bmesh_ex(const struct Mesh *me,
const struct BMeshCreateParams *create_params,
const struct BMeshFromMeshParams *convert_params);
struct BMesh *BKE_mesh_to_bmesh(struct Mesh *me,
struct Object *ob,
const bool add_key_index,
const struct BMeshCreateParams *params);
struct Mesh *BKE_mesh_from_bmesh_nomain(struct BMesh *bm,
const struct BMeshToMeshParams *params,
const struct Mesh *me_settings);
struct Mesh *BKE_mesh_from_bmesh_for_eval_nomain(struct BMesh *bm,
const struct CustomData_MeshMasks *cd_mask_extra,
const struct Mesh *me_settings);
struct Mesh *BKE_mesh_from_editmesh_with_coords_thin_wrap(
struct BMEditMesh *em,
const struct CustomData_MeshMasks *data_mask,
float (*vertexCos)[3],
const struct Mesh *me_settings);
int poly_find_loop_from_vert(const struct MPoly *poly, const struct MLoop *loopstart, uint vert);
int poly_get_adj_loops_from_vert(const struct MPoly *poly,
const struct MLoop *mloop,
unsigned int vert,
unsigned int r_adj[2]);
int BKE_mesh_edge_other_vert(const struct MEdge *e, int v);
void BKE_mesh_looptri_get_real_edges(const struct Mesh *mesh,
const struct MLoopTri *looptri,
int r_edges[3]);
void BKE_mesh_free(struct Mesh *me);
void BKE_mesh_init(struct Mesh *me);
void BKE_mesh_clear_geometry(struct Mesh *me);
struct Mesh *BKE_mesh_add(struct Main *bmain, const char *name);
void BKE_mesh_copy_data(struct Main *bmain,
struct Mesh *me_dst,
const struct Mesh *me_src,
const int flag);
struct Mesh *BKE_mesh_copy(struct Main *bmain, const struct Mesh *me);
void BKE_mesh_copy_settings(struct Mesh *me_dst, const struct Mesh *me_src);
void BKE_mesh_update_customdata_pointers(struct Mesh *me, const bool do_ensure_tess_cd);
void BKE_mesh_ensure_skin_customdata(struct Mesh *me);
struct Mesh *BKE_mesh_new_nomain(
int verts_len, int edges_len, int tessface_len, int loops_len, int polys_len);
struct Mesh *BKE_mesh_new_nomain_from_template(const struct Mesh *me_src,
int verts_len,
int edges_len,
int tessface_len,
int loops_len,
int polys_len);
struct Mesh *BKE_mesh_new_nomain_from_template_ex(const struct Mesh *me_src,
int verts_len,
int edges_len,
int tessface_len,
int loops_len,
int polys_len,
CustomData_MeshMasks mask);
void BKE_mesh_eval_delete(struct Mesh *me_eval);
/* Performs copy for use during evaluation,
* optional referencing original arrays to reduce memory. */
struct Mesh *BKE_mesh_copy_for_eval(struct Mesh *source, bool reference);
/* These functions construct a new Mesh,
* contrary to BKE_mesh_from_nurbs which modifies ob itself. */
struct Mesh *BKE_mesh_new_nomain_from_curve(struct Object *ob);
struct Mesh *BKE_mesh_new_nomain_from_curve_displist(struct Object *ob, struct ListBase *dispbase);
bool BKE_mesh_ensure_facemap_customdata(struct Mesh *me);
bool BKE_mesh_clear_facemap_customdata(struct Mesh *me);
void BKE_mesh_make_local(struct Main *bmain, struct Mesh *me, const bool lib_local);
float (*BKE_mesh_orco_verts_get(struct Object *ob))[3];
void BKE_mesh_orco_verts_transform(struct Mesh *me, float (*orco)[3], int totvert, int invert);
int test_index_face(struct MFace *mface, struct CustomData *mfdata, int mfindex, int nr);
struct Mesh *BKE_mesh_from_object(struct Object *ob);
void BKE_mesh_assign_object(struct Main *bmain, struct Object *ob, struct Mesh *me);
void BKE_mesh_from_metaball(struct ListBase *lb, struct Mesh *me);
int BKE_mesh_nurbs_to_mdata(struct Object *ob,
struct MVert **r_allvert,
int *r_totvert,
struct MEdge **r_alledge,
int *r_totedge,
struct MLoop **r_allloop,
struct MPoly **r_allpoly,
int *r_totloop,
int *r_totpoly);
int BKE_mesh_nurbs_displist_to_mdata(struct Object *ob,
const struct ListBase *dispbase,
struct MVert **r_allvert,
int *r_totvert,
struct MEdge **r_alledge,
int *r_totedge,
struct MLoop **r_allloop,
struct MPoly **r_allpoly,
struct MLoopUV **r_alluv,
int *r_totloop,
int *r_totpoly);
void BKE_mesh_from_nurbs_displist(struct Main *bmain,
struct Object *ob,
struct ListBase *dispbase,
const char *obdata_name,
bool temporary);
void BKE_mesh_from_nurbs(struct Main *bmain, struct Object *ob);
void BKE_mesh_to_curve_nurblist(const struct Mesh *me,
struct ListBase *nurblist,
const int edge_users_test);
void BKE_mesh_to_curve(struct Main *bmain,
struct Depsgraph *depsgraph,
struct Scene *scene,
struct Object *ob);
void BKE_mesh_material_index_remove(struct Mesh *me, short index);
bool BKE_mesh_material_index_used(struct Mesh *me, short index);
void BKE_mesh_material_index_clear(struct Mesh *me);
void BKE_mesh_material_remap(struct Mesh *me, const unsigned int *remap, unsigned int remap_len);
void BKE_mesh_smooth_flag_set(struct Mesh *me, const bool use_smooth);
const char *BKE_mesh_cmp(struct Mesh *me1, struct Mesh *me2, float thresh);
struct BoundBox *BKE_mesh_boundbox_get(struct Object *ob);
void BKE_mesh_texspace_calc(struct Mesh *me);
void BKE_mesh_texspace_ensure(struct Mesh *me);
void BKE_mesh_texspace_get(struct Mesh *me, float r_loc[3], float r_size[3]);
void BKE_mesh_texspace_get_reference(struct Mesh *me,
short **r_texflag,
float **r_loc,
float **r_size);
void BKE_mesh_texspace_copy_from_object(struct Mesh *me, struct Object *ob);
void BKE_mesh_split_faces(struct Mesh *mesh, bool free_loop_normals);
/* Create new mesh from the given object at its current state.
* The owner of this mesh is unknown, it is up to the caller to decide.
*
* If preserve_all_data_layers is truth then the modifier stack is re-evaluated to ensure it
* preserves all possible custom data layers.
*
* NOTE: Dependency graph argument is required when preserve_all_data_layers is truth, and is
* ignored otherwise. */
struct Mesh *BKE_mesh_new_from_object(struct Depsgraph *depsgraph,
struct Object *object,
bool preserve_all_data_layers);
/* This is a version of BKE_mesh_new_from_object() which stores mesh in the given main database.
* However, that function enforces object type to be a geometry one, and ensures a mesh is always
* generated, be it empty. */
struct Mesh *BKE_mesh_new_from_object_to_bmain(struct Main *bmain,
struct Depsgraph *depsgraph,
struct Object *object,
bool preserve_all_data_layers);
struct Mesh *BKE_mesh_create_derived_for_modifier(struct Depsgraph *depsgraph,
struct Scene *scene,
struct Object *ob_eval,
struct ModifierData *md_eval,
int build_shapekey_layers);
/* Copies a nomain-Mesh into an existing Mesh. */
void BKE_mesh_nomain_to_mesh(struct Mesh *mesh_src,
struct Mesh *mesh_dst,
struct Object *ob,
const struct CustomData_MeshMasks *mask,
bool take_ownership);
void BKE_mesh_nomain_to_meshkey(struct Mesh *mesh_src, struct Mesh *mesh_dst, struct KeyBlock *kb);
/* vertex level transformations & checks (no derived mesh) */
bool BKE_mesh_minmax(const struct Mesh *me, float r_min[3], float r_max[3]);
void BKE_mesh_transform(struct Mesh *me, float mat[4][4], bool do_keys);
void BKE_mesh_translate(struct Mesh *me, const float offset[3], const bool do_keys);
void BKE_mesh_ensure_navmesh(struct Mesh *me);
void BKE_mesh_tessface_calc(struct Mesh *mesh);
void BKE_mesh_tessface_ensure(struct Mesh *mesh);
void BKE_mesh_tessface_clear(struct Mesh *mesh);
void BKE_mesh_do_versions_cd_flag_init(struct Mesh *mesh);
void BKE_mesh_mselect_clear(struct Mesh *me);
void BKE_mesh_mselect_validate(struct Mesh *me);
int BKE_mesh_mselect_find(struct Mesh *me, int index, int type);
int BKE_mesh_mselect_active_get(struct Mesh *me, int type);
void BKE_mesh_mselect_active_set(struct Mesh *me, int index, int type);
void BKE_mesh_count_selected_items(const struct Mesh *mesh, int r_count[3]);
float (*BKE_mesh_vert_coords_alloc(const struct Mesh *mesh, int *r_vert_len))[3];
void BKE_mesh_vert_coords_get(const struct Mesh *mesh, float (*vert_coords)[3]);
void BKE_mesh_vert_coords_apply_with_mat4(struct Mesh *mesh,
const float (*vert_coords)[3],
const float mat[4][4]);
void BKE_mesh_vert_coords_apply(struct Mesh *mesh, const float (*vert_coords)[3]);
void BKE_mesh_vert_normals_apply(struct Mesh *mesh, const short (*vertNormals)[3]);
/* *** mesh_evaluate.c *** */
void BKE_mesh_calc_normals_mapping_simple(struct Mesh *me);
void BKE_mesh_calc_normals_mapping(struct MVert *mverts,
int numVerts,
const struct MLoop *mloop,
const struct MPoly *mpolys,
int numLoops,
int numPolys,
float (*r_polyNors)[3],
const struct MFace *mfaces,
int numFaces,
const int *origIndexFace,
float (*r_faceNors)[3]);
void BKE_mesh_calc_normals_mapping_ex(struct MVert *mverts,
int numVerts,
const struct MLoop *mloop,
const struct MPoly *mpolys,
int numLoops,
int numPolys,
float (*r_polyNors)[3],
const struct MFace *mfaces,
int numFaces,
const int *origIndexFace,
float (*r_faceNors)[3],
const bool only_face_normals);
void BKE_mesh_calc_normals_poly(struct MVert *mverts,
float (*r_vertnors)[3],
int numVerts,
const struct MLoop *mloop,
const struct MPoly *mpolys,
int numLoops,
int numPolys,
float (*r_polyNors)[3],
const bool only_face_normals);
void BKE_mesh_calc_normals(struct Mesh *me);
void BKE_mesh_ensure_normals(struct Mesh *me);
void BKE_mesh_ensure_normals_for_display(struct Mesh *mesh);
void BKE_mesh_calc_normals_looptri(struct MVert *mverts,
int numVerts,
const struct MLoop *mloop,
const struct MLoopTri *looptri,
int looptri_num,
float (*r_tri_nors)[3]);
void BKE_mesh_loop_manifold_fan_around_vert_next(const struct MLoop *mloops,
const struct MPoly *mpolys,
const int *loop_to_poly,
const int *e2lfan_curr,
const uint mv_pivot_index,
const struct MLoop **r_mlfan_curr,
int *r_mlfan_curr_index,
int *r_mlfan_vert_index,
int *r_mpfan_curr_index);
void BKE_edges_sharp_from_angle_set(const struct MVert *mverts,
const int numVerts,
struct MEdge *medges,
const int numEdges,
struct MLoop *mloops,
const int numLoops,
struct MPoly *mpolys,
const float (*polynors)[3],
const int numPolys,
const float split_angle);
/**
* References a contiguous loop-fan with normal offset vars.
*/
typedef struct MLoopNorSpace {
/** Automatically computed loop normal. */
float vec_lnor[3];
/** Reference vector, orthogonal to vec_lnor. */
float vec_ref[3];
/** Third vector, orthogonal to vec_lnor and vec_ref. */
float vec_ortho[3];
/** Reference angle, around vec_ortho, in ]0, pi] range (0.0 marks that space as invalid). */
float ref_alpha;
/** Reference angle, around vec_lnor, in ]0, 2pi] range (0.0 marks that space as invalid). */
float ref_beta;
/** All loops using this lnor space (i.e. smooth fan of loops),
* as (depending on owning MLoopNorSpaceArrary.data_type):
* - Indices (uint_in_ptr), or
* - BMLoop pointers. */
struct LinkNode *loops;
char flags;
/** To be used for extended processing related to loop normal spaces (aka smooth fans). */
void *user_data;
} MLoopNorSpace;
/**
* MLoopNorSpace.flags
*/
enum {
MLNOR_SPACE_IS_SINGLE = 1 << 0,
};
/**
* Collection of #MLoopNorSpace basic storage & pre-allocation.
*/
typedef struct MLoopNorSpaceArray {
MLoopNorSpace **lspacearr; /* MLoop aligned array */
struct LinkNode
*loops_pool; /* Allocated once, avoids to call BLI_linklist_prepend_arena() for each loop! */
char data_type; /* Whether we store loop indices, or pointers to BMLoop. */
int num_spaces; /* Number of clnors spaces defined in this array. */
struct MemArena *mem;
} MLoopNorSpaceArray;
/**
* MLoopNorSpaceArray.data_type
*/
enum {
MLNOR_SPACEARR_LOOP_INDEX = 0,
MLNOR_SPACEARR_BMLOOP_PTR = 1,
};
/* Low-level custom normals functions. */
void BKE_lnor_spacearr_init(MLoopNorSpaceArray *lnors_spacearr,
const int numLoops,
const char data_type);
void BKE_lnor_spacearr_clear(MLoopNorSpaceArray *lnors_spacearr);
void BKE_lnor_spacearr_free(MLoopNorSpaceArray *lnors_spacearr);
MLoopNorSpace *BKE_lnor_space_create(MLoopNorSpaceArray *lnors_spacearr);
void BKE_lnor_space_define(MLoopNorSpace *lnor_space,
const float lnor[3],
float vec_ref[3],
float vec_other[3],
struct BLI_Stack *edge_vectors);
void BKE_lnor_space_add_loop(MLoopNorSpaceArray *lnors_spacearr,
MLoopNorSpace *lnor_space,
const int ml_index,
void *bm_loop,
const bool is_single);
void BKE_lnor_space_custom_data_to_normal(MLoopNorSpace *lnor_space,
const short clnor_data[2],
float r_custom_lnor[3]);
void BKE_lnor_space_custom_normal_to_data(MLoopNorSpace *lnor_space,
const float custom_lnor[3],
short r_clnor_data[2]);
/* Medium-level custom normals functions. */
void BKE_mesh_normals_loop_split(const struct MVert *mverts,
const int numVerts,
struct MEdge *medges,
const int numEdges,
struct MLoop *mloops,
float (*r_loopnors)[3],
const int numLoops,
struct MPoly *mpolys,
const float (*polynors)[3],
const int numPolys,
const bool use_split_normals,
const float split_angle,
MLoopNorSpaceArray *r_lnors_spacearr,
short (*clnors_data)[2],
int *r_loop_to_poly);
void BKE_mesh_normals_loop_custom_set(const struct MVert *mverts,
const int numVerts,
struct MEdge *medges,
const int numEdges,
struct MLoop *mloops,
float (*r_custom_loopnors)[3],
const int numLoops,
struct MPoly *mpolys,
const float (*polynors)[3],
const int numPolys,
short (*r_clnors_data)[2]);
void BKE_mesh_normals_loop_custom_from_vertices_set(const struct MVert *mverts,
float (*r_custom_vertnors)[3],
const int numVerts,
struct MEdge *medges,
const int numEdges,
struct MLoop *mloops,
const int numLoops,
struct MPoly *mpolys,
const float (*polynors)[3],
const int numPolys,
short (*r_clnors_data)[2]);
void BKE_mesh_normals_loop_to_vertex(const int numVerts,
const struct MLoop *mloops,
const int numLoops,
const float (*clnors)[3],
float (*r_vert_clnors)[3]);
/* High-level custom normals functions. */
bool BKE_mesh_has_custom_loop_normals(struct Mesh *me);
void BKE_mesh_calc_normals_split(struct Mesh *mesh);
void BKE_mesh_calc_normals_split_ex(struct Mesh *mesh,
struct MLoopNorSpaceArray *r_lnors_spacearr);
void BKE_mesh_set_custom_normals(struct Mesh *mesh, float (*r_custom_loopnors)[3]);
void BKE_mesh_set_custom_normals_from_vertices(struct Mesh *mesh, float (*r_custom_vertnors)[3]);
void BKE_mesh_calc_poly_normal(const struct MPoly *mpoly,
const struct MLoop *loopstart,
const struct MVert *mvarray,
float r_no[3]);
void BKE_mesh_calc_poly_normal_coords(const struct MPoly *mpoly,
const struct MLoop *loopstart,
const float (*vertex_coords)[3],
float r_no[3]);
void BKE_mesh_calc_poly_center(const struct MPoly *mpoly,
const struct MLoop *loopstart,
const struct MVert *mvarray,
float r_cent[3]);
float BKE_mesh_calc_poly_area(const struct MPoly *mpoly,
const struct MLoop *loopstart,
const struct MVert *mvarray);
float BKE_mesh_calc_area(const struct Mesh *me);
float BKE_mesh_calc_poly_uv_area(const struct MPoly *mpoly, const struct MLoopUV *uv_array);
void BKE_mesh_calc_poly_angles(const struct MPoly *mpoly,
const struct MLoop *loopstart,
const struct MVert *mvarray,
float angles[]);
void BKE_mesh_poly_edgehash_insert(struct EdgeHash *ehash,
const struct MPoly *mp,
const struct MLoop *mloop);
void BKE_mesh_poly_edgebitmap_insert(unsigned int *edge_bitmap,
const struct MPoly *mp,
const struct MLoop *mloop);
bool BKE_mesh_center_median(const struct Mesh *me, float r_cent[3]);
bool BKE_mesh_center_bounds(const struct Mesh *me, float r_cent[3]);
bool BKE_mesh_center_of_surface(const struct Mesh *me, float r_cent[3]);
bool BKE_mesh_center_of_volume(const struct Mesh *me, float r_cent[3]);
void BKE_mesh_calc_volume(const struct MVert *mverts,
const int mverts_num,
const struct MLoopTri *mlooptri,
const int looptri_num,
const struct MLoop *mloop,
float *r_volume,
float r_center[3]);
/* tessface */
void BKE_mesh_loops_to_mface_corners(struct CustomData *fdata,
struct CustomData *ldata,
struct CustomData *pdata,
unsigned int lindex[4],
int findex,
const int polyindex,
const int mf_len,
const int numTex,
const int numCol,
const bool hasPCol,
const bool hasOrigSpace,
const bool hasLNor);
void BKE_mesh_loops_to_tessdata(struct CustomData *fdata,
struct CustomData *ldata,
struct MFace *mface,
int *polyindices,
unsigned int (*loopindices)[4],
const int num_faces);
void BKE_mesh_tangent_loops_to_tessdata(struct CustomData *fdata,
struct CustomData *ldata,
struct MFace *mface,
int *polyindices,
unsigned int (*loopindices)[4],
const int num_faces,
const char *layer_name);
int BKE_mesh_tessface_calc_ex(struct CustomData *fdata,
struct CustomData *ldata,
struct CustomData *pdata,
struct MVert *mvert,
int totface,
int totloop,
int totpoly,
const bool do_face_nor_copy);
void BKE_mesh_recalc_looptri(const struct MLoop *mloop,
const struct MPoly *mpoly,
const struct MVert *mvert,
int totloop,
int totpoly,
struct MLoopTri *mlooptri);
void BKE_mesh_convert_mfaces_to_mpolys(struct Mesh *mesh);
void BKE_mesh_do_versions_convert_mfaces_to_mpolys(struct Mesh *mesh);
void BKE_mesh_convert_mfaces_to_mpolys_ex(struct ID *id,
struct CustomData *fdata,
struct CustomData *ldata,
struct CustomData *pdata,
int totedge_i,
int totface_i,
int totloop_i,
int totpoly_i,
struct MEdge *medge,
struct MFace *mface,
int *r_totloop,
int *r_totpoly,
struct MLoop **r_mloop,
struct MPoly **r_mpoly);
void BKE_mesh_mdisp_flip(struct MDisps *md, const bool use_loop_mdisp_flip);
void BKE_mesh_polygon_flip_ex(struct MPoly *mpoly,
struct MLoop *mloop,
struct CustomData *ldata,
float (*lnors)[3],
struct MDisps *mdisp,
const bool use_loop_mdisp_flip);
void BKE_mesh_polygon_flip(struct MPoly *mpoly, struct MLoop *mloop, struct CustomData *ldata);
void BKE_mesh_polygons_flip(struct MPoly *mpoly,
struct MLoop *mloop,
struct CustomData *ldata,
int totpoly);
/* merge verts */
/* Enum for merge_mode of CDDM_merge_verts.
* Refer to mesh.c for details. */
enum {
MESH_MERGE_VERTS_DUMP_IF_MAPPED,
MESH_MERGE_VERTS_DUMP_IF_EQUAL,
};
struct Mesh *BKE_mesh_merge_verts(struct Mesh *mesh,
const int *vtargetmap,
const int tot_vtargetmap,
const int merge_mode);
/* flush flags */
void BKE_mesh_flush_hidden_from_verts_ex(const struct MVert *mvert,
const struct MLoop *mloop,
struct MEdge *medge,
const int totedge,
struct MPoly *mpoly,
const int totpoly);
void BKE_mesh_flush_hidden_from_verts(struct Mesh *me);
void BKE_mesh_flush_hidden_from_polys_ex(struct MVert *mvert,
const struct MLoop *mloop,
struct MEdge *medge,
const int totedge,
const struct MPoly *mpoly,
const int totpoly);
void BKE_mesh_flush_hidden_from_polys(struct Mesh *me);
void BKE_mesh_flush_select_from_polys_ex(struct MVert *mvert,
const int totvert,
const struct MLoop *mloop,
struct MEdge *medge,
const int totedge,
const struct MPoly *mpoly,
const int totpoly);
void BKE_mesh_flush_select_from_polys(struct Mesh *me);
void BKE_mesh_flush_select_from_verts_ex(const struct MVert *mvert,
const int totvert,
const struct MLoop *mloop,
struct MEdge *medge,
const int totedge,
struct MPoly *mpoly,
const int totpoly);
void BKE_mesh_flush_select_from_verts(struct Mesh *me);
/* spatial evaluation */
void BKE_mesh_calc_relative_deform(const struct MPoly *mpoly,
const int totpoly,
const struct MLoop *mloop,
const int totvert,
const float (*vert_cos_src)[3],
const float (*vert_cos_dst)[3],
const float (*vert_cos_org)[3],
float (*vert_cos_new)[3]);
/* *** mesh_validate.c *** */
bool BKE_mesh_validate(struct Mesh *me, const bool do_verbose, const bool cddata_check_mask);
bool BKE_mesh_is_valid(struct Mesh *me);
bool BKE_mesh_validate_material_indices(struct Mesh *me);
bool BKE_mesh_validate_arrays(struct Mesh *me,
struct MVert *mverts,
unsigned int totvert,
struct MEdge *medges,
unsigned int totedge,
struct MFace *mfaces,
unsigned int totface,
struct MLoop *mloops,
unsigned int totloop,
struct MPoly *mpolys,
unsigned int totpoly,
struct MDeformVert *dverts, /* assume totvert length */
const bool do_verbose,
const bool do_fixes,
bool *r_change);
bool BKE_mesh_validate_all_customdata(struct CustomData *vdata,
const uint totvert,
struct CustomData *edata,
const uint totedge,
struct CustomData *ldata,
const uint totloop,
struct CustomData *pdata,
const uint totpoly,
const bool check_meshmask,
const bool do_verbose,
const bool do_fixes,
bool *r_change);
void BKE_mesh_strip_loose_faces(struct Mesh *me);
void BKE_mesh_strip_loose_polysloops(struct Mesh *me);
void BKE_mesh_strip_loose_edges(struct Mesh *me);
void BKE_mesh_calc_edges_legacy(struct Mesh *me, const bool use_old);
void BKE_mesh_calc_edges_loose(struct Mesh *mesh);
void BKE_mesh_calc_edges(struct Mesh *mesh, bool update, const bool select);
void BKE_mesh_calc_edges_tessface(struct Mesh *mesh);
/* **** Depsgraph evaluation **** */
void BKE_mesh_eval_geometry(struct Depsgraph *depsgraph, struct Mesh *mesh);
/* Draw Cache */
enum {
BKE_MESH_BATCH_DIRTY_ALL = 0,
BKE_MESH_BATCH_DIRTY_SELECT,
BKE_MESH_BATCH_DIRTY_SELECT_PAINT,
BKE_MESH_BATCH_DIRTY_SHADING,
BKE_MESH_BATCH_DIRTY_UVEDIT_ALL,
BKE_MESH_BATCH_DIRTY_UVEDIT_SELECT,
};
void BKE_mesh_batch_cache_dirty_tag(struct Mesh *me, int mode);
void BKE_mesh_batch_cache_free(struct Mesh *me);
extern void (*BKE_mesh_batch_cache_dirty_tag_cb)(struct Mesh *me, int mode);
extern void (*BKE_mesh_batch_cache_free_cb)(struct Mesh *me);
/* Inlines */
/* Instead of -1 that function uses ORIGINDEX_NONE as defined in BKE_customdata.h,
* but I don't want to force every user of BKE_mesh.h to also include that file.
* ~~ Sybren */
BLI_INLINE int BKE_mesh_origindex_mface_mpoly(const int *index_mf_to_mpoly,
const int *index_mp_to_orig,
const int i)
{
const int j = index_mf_to_mpoly[i];
return (j != -1) ? (index_mp_to_orig ? index_mp_to_orig[j] : j) : -1;
}
#ifdef __cplusplus
}
#endif
#endif /* __BKE_MESH_H__ */
| 48.043115 | 99 | 0.528761 | [
"mesh",
"geometry",
"object",
"vector"
] |
d69692724ad78144c8ab4f6fd94c023a989cc97e | 4,599 | h | C | include/irrklang/sound.h | mamontov-cpp/saddy | f20a0030e18af9e0714fe56c19407fbeacc529a7 | [
"BSD-2-Clause"
] | 58 | 2015-08-09T14:56:35.000Z | 2022-01-15T22:06:58.000Z | include/irrklang/sound.h | mamontov-cpp/saddy-graphics-engine-2d | e25a6637fcc49cb26614bf03b70e5d03a3a436c7 | [
"BSD-2-Clause"
] | 245 | 2015-08-08T08:44:22.000Z | 2022-01-04T09:18:08.000Z | include/irrklang/sound.h | mamontov-cpp/saddy | f20a0030e18af9e0714fe56c19407fbeacc529a7 | [
"BSD-2-Clause"
] | 23 | 2015-12-06T03:57:49.000Z | 2020-10-12T14:15:50.000Z | /*! \file sound.h
Describes a sound as resource
*/
#pragma once
#include "engine.h"
// ReSharper disable once CppUnusedIncludeDirective
#include <resource/resource.h>
#include <renderer.h>
#include <3rdparty/picojson/valuetotype.h>
#include <util/pointercallback.h>
namespace sad
{
namespace irrklang
{
/*! Defines a wrapper for sound from irrKlang to make it loadable
from resource files
*/
class Sound: public sad::resource::Resource, public ::irrklang::ISoundStopEventReceiver
{
SAD_OBJECT
public:
/*! A callback, which is called, when sound is stopped
*/
typedef sad::util::PointerCallback<sad::irrklang::Sound> StopCallback;
/*! Constructs default, invalid source
*/
Sound();
/*! Returns source for data
\return wrapped source
*/
::irrklang::ISoundSource* s() const;
/*! Loads a texture from specified file, using specified renderer for building mip maps.
\param[in] file a file, via which a resource should be loaded
\param[in] r a renderer, which resource should be linked to (nullptr if global renderer)
\param[in] options an options for loading a resource
\return whether loading was successfull
*/
virtual bool load(
const sad::resource::ResourceFile & file,
sad::Renderer * r,
const picojson::value& options
) override;
/*! Sets default volume for a sound
\param[in] volume a default volume
*/
void setDefaultVolume(double volume);
/*! Plays sound with specified volume
\param[in] volume a volume
\param[in] looped whether sound is looped
\return sound object
*/
::irrklang::ISound* play2D(double volume, bool looped = true);
/*! Returns true, whether sound is playing
\return whether sound is playing
*/
bool isPlaying() const;
/*! Adds callback, which will be called, when sound is stopped
\param[in] cb callback
*/
void addCallback(StopCallback* cb);
/*! Adds callback, which will be called, when sound is stopped
\param[in] cb callback
*/
inline void addCallback(void (*cb)())
{
addCallback(new sad::util::FreeZeroArgCallback<sad::irrklang::Sound>(cb));
}
/*! Adds callback, which will be called, when sound is stopped
\param[in] cb callback
*/
inline void addCallback(void (*cb)(sad::irrklang::Sound*))
{
addCallback(new sad::util::FreeOneArgCallback<sad::irrklang::Sound>(cb));
}
/*! Adds callback, which will be called, when sound is stopped
\param[in] o object
\param[in] cb callback
*/
template<
typename _Object,
typename _CalledObject
>
inline void addCallback(_Object* o, void (_CalledObject::*cb)())
{
addCallback(new sad::util::MethodZeroArgCallback<sad::irrklang::Sound, _Object, _CalledObject>(o, cb));
}
/*! Adds callback, which will be called, when sound is stopped
\param[in] o object
\param[in] cb callback
*/
template<
typename _Object,
typename _CalledObject
>
inline void addCallback(_Object* o, void (_CalledObject::*cb)(sad::irrklang::Sound*))
{
addCallback(new sad::util::MethodOneArgCallback<sad::irrklang::Sound, _Object, _CalledObject>(o, cb));
}
/*! Adds callback, which will be called, when sound is stopped
\param[in] o object
\param[in] cb callback
*/
template<
typename _Object,
typename _CalledObject
>
inline void addCallback(_Object* o, void (_CalledObject::*cb)() const)
{
addCallback(new sad::util::ConstMethodZeroArgCallback<sad::irrklang::Sound, _Object, _CalledObject>(o, cb));
}
/*! Adds callback, which will be called, when sound is stopped
\param[in] o object
\param[in] cb callback
*/
template<
typename _Object,
typename _CalledObject
>
inline void addCallback(_Object* o, void (_CalledObject::*cb)(sad::irrklang::Sound*) const)
{
addCallback(new sad::util::ConstMethodOneArgCallback<sad::irrklang::Sound, _Object, _CalledObject>(o, cb));
}
protected:
/*! Called, when sound is stopped
*/
void OnSoundStopped(
::irrklang::ISound * sound,
::irrklang::E_STOP_EVENT_CAUSE reason,
void * userData
) override;
/*! A sound source, wrapped in resource
*/
::irrklang::ISoundSource* m_source;
/*! A callbacks on stopping sound
*/
sad::PtrVector<StopCallback> m_stop_callbacks;
};
}
}
| 30.865772 | 116 | 0.642096 | [
"object"
] |
d69eded3ed3d964e2af71b03302534645a617e93 | 2,939 | h | C | timeout_manager_impl.h | anqin/trident | 1291596db0532b07865920b46165722a6c6244f4 | [
"BSD-3-Clause"
] | 6 | 2015-03-03T14:22:29.000Z | 2021-07-20T13:20:28.000Z | timeout_manager_impl.h | anqin/trident | 1291596db0532b07865920b46165722a6c6244f4 | [
"BSD-3-Clause"
] | null | null | null | timeout_manager_impl.h | anqin/trident | 1291596db0532b07865920b46165722a6c6244f4 | [
"BSD-3-Clause"
] | 5 | 2015-03-03T14:30:18.000Z | 2018-04-12T06:01:39.000Z | // Copyright (c) 2014 The Trident 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 _TRIDENT_TIMEOUT_MANAGER_IMPL_H_
#define _TRIDENT_TIMEOUT_MANAGER_IMPL_H_
#include <vector>
#include <trident/common_internal.h>
#include <trident/timeout_manager.h>
#include <trident/thread_group_impl.h>
#include <trident/timer_worker.h>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/indexed_by.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/member.hpp>
namespace trident {
// Defined in this file.
class TimeoutManagerImpl;
typedef trident::shared_ptr<TimeoutManagerImpl> TimeoutManagerImplPtr;
class TimeoutManagerImpl : public trident::enable_shared_from_this<TimeoutManagerImpl>
{
public:
// Thread number for timer and callbacks.
const static int kThreadCount = 1;
// Timeout granularity of timer in milli-seconds.
const static int64 kTimerGranularity = 10;
typedef TimeoutManager::Id Id;
typedef TimeoutManager::Type Type;
typedef TimeoutManager::Callback Callback;
TimeoutManagerImpl();
~TimeoutManagerImpl();
bool is_running();
void start();
void stop();
void clear();
Id add(int64 interval, Callback* callback);
Id add_repeating(int64 interval, Callback* callback);
bool erase(Id id);
private:
// Given interval in milli-seconds, calculate expiration ticks.
inline int64 calc_expiration(int64 interval)
{
return _last_ticks + time_duration_milliseconds(interval).ticks() + _rectify_ticks;
}
void timer_run(const PTime& now);
private:
struct Event {
Id id;
int64 expiration;
int64 repeat_interval;
Callback* callback;
Event(Id i, int64 e, int64 r, Callback* c)
: id(i), expiration(e), repeat_interval(r), callback(c) {}
};
typedef boost::multi_index_container<
Event,
boost::multi_index::indexed_by<
boost::multi_index::ordered_unique<boost::multi_index::member<
Event, Id, &Event::id
> >,
boost::multi_index::ordered_non_unique<boost::multi_index::member<
Event, int64, &Event::expiration
> >
>
> Set;
enum {
BY_ID=0,
BY_EXPIRATION=1
};
typedef Set::nth_index<BY_ID>::type IdIndex;
typedef Set::nth_index<BY_EXPIRATION>::type ExpirationIndex;
typedef std::vector<Event> EventVec;
volatile bool _is_running;
MutexLock _start_stop_lock;
PTime _epoch_time;
volatile int64 _last_ticks;
int64 _rectify_ticks;
ThreadGroupImplPtr _thread_group;
TimerWorkerPtr _timer_worker;
Set _timeouts;
Id _next_id;
MutexLock _timeouts_lock;
};
} // namespace trident
#endif // _TRIDENT_TIMEOUT_MANAGER_IMPL_H_
/* vim: set ts=4 sw=4 sts=4 tw=100 */
| 25.119658 | 91 | 0.694114 | [
"vector"
] |
d6a2c95b511388120be5b4bf398fae466d25d4e0 | 2,440 | h | C | mods/scene/include/scene/node.h | tpearson1/Eris | f64b681966f9cbd4a4cd448f4d3028efdab19bd9 | [
"MIT"
] | null | null | null | mods/scene/include/scene/node.h | tpearson1/Eris | f64b681966f9cbd4a4cd448f4d3028efdab19bd9 | [
"MIT"
] | null | null | null | mods/scene/include/scene/node.h | tpearson1/Eris | f64b681966f9cbd4a4cd448f4d3028efdab19bd9 | [
"MIT"
] | null | null | null | /*
-------------------------------------------------------------------------------
This file is part of Eris Engine
-------------------------------------------------------------------------------
Copyright (c) 2017 Thomas Pearson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-------------------------------------------------------------------------------
*/
#ifndef _SCENE__NODE_H
#define _SCENE__NODE_H
#include <scene/transform.h>
#include <scene/transformationtree.h>
class NNode;
template <>
struct JSONImpl<NNode> {
static void Read(NNode &out, const JSON::Value &value,
const JSON::ReadData &data);
static void Write(const NNode &value, JSON::Writer &writer);
};
class NNode : public TransformationTree<NNode> {
protected:
static void RecursiveDestroy(NNode *n);
virtual void OnDestroy() {}
public:
Vec3 GlobalLocation() const;
Quat GlobalRotation() const;
Vec3 GlobalScale() const;
/*
* This function is equivalent to:
* return Transform(
* GlobalLocation(),
* GlobalRotation(),
* GlobalScale()
* );
*/
Transform GlobalTransform() const;
virtual ~NNode() {}
void Destroy() { RecursiveDestroy(this); }
Transform transform;
friend void JSONImpl<NNode>::Write(const NNode &value, JSON::Writer &writer);
friend void JSONImpl<NNode>::Read(NNode &out, const JSON::Value &value,
const JSON::ReadData &data);
};
#endif // _SCENE__NODE_H
| 31.688312 | 79 | 0.660656 | [
"transform"
] |
d6a42776f2d266bfa085413bbae9404193e2002a | 27,335 | h | C | c-efi/c-efi-system.h | jarlostensen/josx64 | a5da0ad5db3306f21e77b57bb2e3ecb76aa04036 | [
"Unlicense"
] | 12 | 2020-07-22T14:41:24.000Z | 2022-01-06T11:37:54.000Z | c-efi/c-efi-system.h | jarlostensen/josx64 | a5da0ad5db3306f21e77b57bb2e3ecb76aa04036 | [
"Unlicense"
] | 8 | 2021-01-15T16:23:30.000Z | 2021-01-26T17:46:01.000Z | c-efi/c-efi-system.h | jarlostensen/josx64 | a5da0ad5db3306f21e77b57bb2e3ecb76aa04036 | [
"Unlicense"
] | null | null | null | #pragma once
/**
* UEFI System Integration
*
* This header defines the structures and types of the surrounding system of an
* UEFI application. It contains the definitions of the system table, the
* runtime and boot services, as well as common types.
*
* We do not document the behavior of each of these types and functions. They
* follow the UEFI specification, which does a well-enough job of documenting
* each. This file just provides you the C definitions of each symbol and some
* limited hints on some pecularities.
*/
#ifdef __cplusplus
extern "C" {
#endif
#include <c-efi-base.h>
/*
* Time Management
*
* UEFI time management is modeled around the CEfiTime structure, which
* represents any arbitrary timestamp. The runtime and boot services provide
* helper functions to query and set the system time.
*/
#define C_EFI_TIME_ADJUST_DAYLIGHT C_EFI_U8_C(0x01)
#define C_EFI_TIME_IN_DAYLIGHT C_EFI_U8_C(0x02)
#define C_EFI_UNSPECIFIED_TIMEZONE C_EFI_I16_C(0x07ff)
typedef struct CEfiTime {
CEfiU16 year;
CEfiU8 month;
CEfiU8 day;
CEfiU8 hour;
CEfiU8 minute;
CEfiU8 second;
CEfiU8 pad1;
CEfiU32 nanosecond;
CEfiI16 timezone;
CEfiU8 daylight;
CEfiU8 pad2;
} CEfiTime;
typedef struct CEfiTimeCapabilities {
CEfiU32 resolution;
CEfiU32 accuracy;
CEfiBool sets_to_zero;
} CEfiTimeCapabilities;
/*
* UEFI Variables
*
* UEFI systems provide a way to store global variables. These can be
* persistent or volatile. The variable store must be provided by the platform,
* but persistent storage might not be available.
*/
#define C_EFI_VARIABLE_NON_VOLATILE C_EFI_U32_C(0x00000001)
#define C_EFI_VARIABLE_BOOTSERVICE_ACCESS C_EFI_U32_C(0x00000002)
#define C_EFI_VARIABLE_RUNTIME_ACCESS C_EFI_U32_C(0x00000004)
#define C_EFI_VARIABLE_HARDWARE_ERROR_RECORD C_EFI_U32_C(0x00000008)
#define C_EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS C_EFI_U32_C(0x00000010)
#define C_EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS C_EFI_U32_C(0x00000020)
#define C_EFI_VARIABLE_APPEND_WRITE C_EFI_U32_C(0x00000040)
#define C_EFI_VARIABLE_ENHANCED_AUTHENTICATED_ACCESS C_EFI_U32_C(0x00000080)
#define C_EFI_VARIABLE_AUTHENTICATION_3_CERT_ID_SHA256 C_EFI_U32_C(1)
typedef struct CEfiVariableAuthentication3CertId {
CEfiU8 type;
CEfiU32 id_size;
CEfiU8 id[];
} CEfiVariableAuthentication3CertId;
typedef struct CEfiVariableAuthentication {
CEfiU64 monotonic_count;
CEfiU8 auth_info[]; /* WIN_CERTIFICATE_UEFI_ID from PE/COFF */
} CEfiVariableAuthentication;
typedef struct CEfiVariableAuthentication2 {
CEfiTime timestamp;
CEfiU8 auth_info[]; /* WIN_CERTIFICATE_UEFI_ID from PE/COFF */
} CEfiVariableAuthentication2;
#define C_EFI_VARIABLE_AUTHENTICATION_3_TIMESTAMP_TYPE C_EFI_U32_C(1)
#define C_EFI_VARIABLE_AUTHENTICATION_3_NONCE_TYPE C_EFI_U32_C(2)
typedef struct CEfiVariableAuthentication3 {
CEfiU8 version;
CEfiU8 type;
CEfiU32 metadata_size;
CEfiU32 flags;
} CEfiVariableAuthentication3;
typedef struct CEfiVariableAuthentication3Nonce {
CEfiU32 nonce_size;
CEfiU8 nonce[];
} CEfiVariableAuthentication3Nonce;
#define C_EFI_HARDWARE_ERROR_VARIABLE_GUID C_EFI_GUID(0x414E6BDD, 0xE47B, 0x47cc, 0xB2, 0x44, 0xBB, 0x61, 0x02, 0x0C, 0xF5, 0x16)
/*
* Virtual Mappings
*
* UEFI runs in an 1-to-1 mapping from virtual to physical addresses. But once
* you exit boot services, you can apply any address mapping you want, as long
* as you inform UEFI about it (or, alternatively, stop using the UEFI runtime
* services).
*/
#define C_EFI_OPTIONAL_POINTER C_EFI_U32_C(0x00000001)
/*
* System Reset
*
* UEFI provides access to firmware functions to reset the system. This
* includes a wide variety of different possible resets.
*/
typedef enum CEfiResetType {
C_EFI_RESET_COLD,
C_EFI_RESET_WARM,
C_EFI_RESET_SHUTDOWN,
C_EFI_RESET_PLATFORM_SPECIFIC,
_C_EFI_RESET_N,
} CEfiResetType;
/*
* Update Capsules
*
* The process of firmware updates is generalized in UEFI. There are small
* blobs called capsules that you can push into the firmware to be run either
* immediately or on next reboot.
*/
typedef struct CEfiCapsuleBlockDescriptor {
CEfiU64 length;
union {
CEfiPhysicalAddress data_block;
CEfiPhysicalAddress continuation_pointer;
};
} CEfiCapsuleBlockDescriptor;
#define C_EFI_CAPSULE_FLAGS_PERSIST_ACROSS_RESET C_EFI_U32(0x00010000)
#define C_EFI_CAPSULE_FLAGS_POPULATE_SYSTEM_TABLE C_EFI_U32(0x00020000)
#define C_EFI_CAPSULE_FLAGS_INITIATE_RESET C_EFI_U32(0x00040000)
typedef struct CEfiCapsuleHeader {
CEfiGuid capsule_guid;
CEfiU32 header_size;
CEfiU32 flags;
CEfiU32 capsule_image_size;
} CEfiCapsuleHeader;
#define C_EFI_OS_INDICATIONS_BOOT_TO_FW_UI C_EFI_U64_C(0x0000000000000001)
#define C_EFI_OS_INDICATIONS_TIMESTAMP_REVOCATION C_EFI_U64_C(0x0000000000000002)
#define C_EFI_OS_INDICATIONS_FILE_CAPSULE_DELIVERY_SUPPORTED C_EFI_U64_C(0x0000000000000004)
#define C_EFI_OS_INDICATIONS_FMP_CAPSULE_SUPPORTED C_EFI_U64_C(0x0000000000000008)
#define C_EFI_OS_INDICATIONS_CAPSULE_RESULT_VAR_SUPPORTED C_EFI_U64_C(0x0000000000000010)
#define C_EFI_OS_INDICATIONS_START_OS_RECOVERY C_EFI_U64_C(0x0000000000000020)
#define C_EFI_OS_INDICATIONS_START_PLATFORM_RECOVERY C_EFI_U64_C(0x0000000000000040)
#define C_EFI_CAPSULE_REPORT_GUID C_EFI_GUID(0x39b68c46, 0xf7fb, 0x441b, 0xb6, 0xec, 0x16, 0xb0, 0xf6, 0x98, 0x21, 0xf3)
typedef struct CEfiCapsuleResultVariableHeader {
CEfiU32 variable_total_size;
CEfiU32 reserved;
CEfiGuid capsule_guid;
CEfiTime capsule_processed;
CEfiStatus capsule_status;
} CEfiCapsuleResultVariableHeader;
typedef struct CEfiCapsuleResultVariableFMP {
CEfiU16 version;
CEfiU8 payload_index;
CEfiU8 update_image_index;
CEfiGuid update_image_type_id;
CEfiChar16 capsule_file_name_and_target[];
} CEfiCapsuleResultVariableFMP;
/*
* Tasks
*
* UEFI uses a simplified task model, and only ever runs on a single CPU.
* Usually, there is only one single task running on the system, which is the
* current execution. No interrupts are supported, other than timer interrupts.
* That is, all device management must be reliant on polling.
*
* You can, however, register callbacks to be run by the UEFI core. That is,
* either when execution is returned to the UEFI core, or when a timer
* interrupt fires, the scheduler will run the highest priority task next,
* interrupting the current task. You can use simple task-priority-levels (TPL)
* to adjust the priority of your callbacks and current task.
*/
#define C_EFI_EVT_TIMER C_EFI_U32_C(0x80000000)
#define C_EFI_EVT_RUNTIME C_EFI_U32_C(0x40000000)
#define C_EFI_EVT_NOTIFY_WAIT C_EFI_U32_C(0x00000100)
#define C_EFI_EVT_NOTIFY_SIGNAL C_EFI_U32_C(0x00000200)
#define C_EFI_EVT_SIGNAL_EXIT_BOOT_SERVICES C_EFI_U32_C(0x00000201)
#define C_EFI_EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE C_EFI_U32_C(0x60000202)
typedef void (CEFICALL *CEfiEventNotify) (CEfiEvent event, void *context);
#define C_EFI_EVENT_GROUP_EXIT_BOOT_SERVICES C_EFI_GUID(0x27abf055, 0xb1b8, 0x4c26, 0x80, 0x48, 0x74, 0x8f, 0x37, 0xba, 0xa2, 0xdf)
#define C_EFI_EVENT_GROUP_VIRTUAL_ADDRESS_CHANGE C_EFI_GUID(0x13fa7698, 0xc831, 0x49c7, 0x87, 0xea, 0x8f, 0x43, 0xfc, 0xc2, 0x51, 0x96)
#define C_EFI_EVENT_GROUP_MEMORY_MAP_CHANGE C_EFI_GUID(0x78bee926, 0x692f, 0x48fd, 0x9e, 0xdb, 0x1, 0x42, 0x2e, 0xf0, 0xd7, 0xab)
#define C_EFI_EVENT_GROUP_READY_TO_BOOT C_EFI_GUID(0x7ce88fb3, 0x4bd7, 0x4679, 0x87, 0xa8, 0xa8, 0xd8, 0xde, 0xe5, 0x0d, 0x2b)
#define C_EFI_EVENT_GROUP_RESET_SYSTEM C_EFI_GUID(0x62da6a56, 0x13fb, 0x485a, 0xa8, 0xda, 0xa3, 0xdd, 0x79, 0x12, 0xcb, 0x6b)
typedef enum CEfiTimerDelay {
C_EFI_TIMER_CANCEL,
C_EFI_TIMER_PERIODIC,
C_EFI_TIMER_RELATIVE,
} CEfiTimerDelay;
#define C_EFI_TPL_APPLICATION 4
#define C_EFI_TPL_CALLBACK 8
#define C_EFI_TPL_NOTIFY 16
#define C_EFI_TPL_HIGH_LEVEL 31
/*
* Memory management
*
* The UEFI boot services provide you pool-allocation helpers to reserve
* memory. The region for each allocation can be selected by the caller,
* allowing to reserve memory that even survives beyond boot services. However,
* dynamic allocations can only performed via boot services, so no dynamic
* modifications can be done once you exit boot services.
*/
typedef enum CEfiAllocateType {
C_EFI_ALLOCATE_ANY_PAGES,
C_EFI_ALLOCATE_MAX_ADDRESS,
C_EFI_ALLOCATE_ADDRESS,
_C_EFI_ALLOCATE_TYPE_N,
} CEfiAllocateType;
typedef enum CEfiMemoryType {
C_EFI_RESERVED_MEMORY_TYPE,
C_EFI_LOADER_CODE,
C_EFI_LOADER_DATA,
C_EFI_BOOT_SERVICES_CODE,
C_EFI_BOOT_SERVICES_DATA,
C_EFI_RUNTIME_SERVICES_CODE,
C_EFI_RUNTIME_SERVICES_DATA,
C_EFI_CONVENTIONAL_MEMORY,
C_EFI_UNUSABLE_MEMORY,
C_EFI_ACPI_RECLAIM_MEMORY,
C_EFI_ACPI_MEMORY_NVS,
C_EFI_MEMORY_MAPPED_IO,
C_EFI_MEMORY_MAPPED_IO_PORT_SPACE,
C_EFI_PAL_CODE,
C_EFI_PERSISTENT_MEMORY,
_C_EFI_MEMORY_TYPE_N,
} CEfiMemoryType;
#define C_EFI_MEMORY_UC C_EFI_U64_C(0x0000000000000001)
#define C_EFI_MEMORY_WC C_EFI_U64_C(0x0000000000000002)
#define C_EFI_MEMORY_WT C_EFI_U64_C(0x0000000000000004)
#define C_EFI_MEMORY_WB C_EFI_U64_C(0x0000000000000008)
#define C_EFI_MEMORY_UCE C_EFI_U64_C(0x0000000000000010)
#define C_EFI_MEMORY_WP C_EFI_U64_C(0x0000000000001000)
#define C_EFI_MEMORY_RP C_EFI_U64_C(0x0000000000002000)
#define C_EFI_MEMORY_XP C_EFI_U64_C(0x0000000000004000)
#define C_EFI_MEMORY_NV C_EFI_U64_C(0x0000000000008000)
#define C_EFI_MEMORY_MORE_RELIABLE C_EFI_U64_C(0x0000000000010000)
#define C_EFI_MEMORY_RO C_EFI_U64_C(0x0000000000020000)
#define C_EFI_MEMORY_RUNTIME C_EFI_U64_C(0x8000000000000000)
#define C_EFI_MEMORY_DESCRIPTOR_VERSION C_EFI_U32_C(0x00000001)
typedef struct CEfiMemoryDescriptor {
CEfiU32 type;
CEfiPhysicalAddress physical_start;
CEfiVirtualAddress virtual_start;
CEfiU64 number_of_pages;
CEfiU64 attribute;
} CEfiMemoryDescriptor;
/*
* Protocol Management
*
* The UEFI driver model provides ways to have bus-drivers, device-drivers, and
* applications as separate, independent entities. They use protocols to
* communicate, and handles to refer to common state. Drivers and devices can
* be registered dynamically at runtime, and can support hotplugging.
*/
typedef enum CEfiInterfaceType {
C_EFI_NATIVE_INTERFACE,
} CEfiInterfaceType;
typedef enum CEfiLocateSearchType {
C_EFI_ALL_HANDLES,
C_EFI_BY_REGISTER_NOTIFY,
C_EFI_BY_PROTOCOL,
} CEfiLocateSearchType;
#define C_EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL C_EFI_U32_C(0x00000001)
#define C_EFI_OPEN_PROTOCOL_GET_PROTOCOL C_EFI_U32_C(0x00000002)
#define C_EFI_OPEN_PROTOCOL_TEST_PROTOCOL C_EFI_U32_C(0x00000004)
#define C_EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER C_EFI_U32_C(0x00000008)
#define C_EFI_OPEN_PROTOCOL_BY_DRIVER C_EFI_U32_C(0x00000010)
#define C_EFI_OPEN_PROTOCOL_EXCLUSIVE C_EFI_U32_C(0x00000020)
typedef struct CEfiOpenProtocolInformationEntry {
CEfiHandle agent_handle;
CEfiHandle controller_handle;
CEfiU32 attributes;
CEfiU32 open_count;
} CEfiOpenProtocolInformationEntry;
/*
* Configuration Tables
*
* The system table contains an array of auxiliary tables, indexed by their
* GUID, called configuration tables. Each table uses the generic
* CEfiConfigurationTable structure as header.
*/
typedef struct CEfiConfigurationTable {
CEfiGuid vendor_guid;
void *vendor_table;
} CEfiConfigurationTable;
#define C_EFI_PROPERTIES_TABLE_GUID C_EFI_GUID(0x880aaca3, 0x4adc, 0x4a04, 0x90, 0x79, 0xb7, 0x47, 0x34, 0x8, 0x25, 0xe5)
#define C_EFI_PROPERTIES_TABLE_VERSION C_EFI_U32_C(0x00010000)
#define C_EFI_PROPERTIES_RUNTIME_MEMORY_PROTECTION_NON_EXECUTABLE_PE_DATA C_EFI_U64_C(0x1)
typedef struct CEfiPropertiesTable {
CEfiU32 version;
CEfiU32 length;
CEfiU64 memory_protection_attribute;
} CEfiPropertiesTable;
#define C_EFI_MEMORY_ATTRIBUTES_TABLE_GUID C_EFI_GUID(0xdcfa911d, 0x26eb, 0x469f, 0xa2, 0x20, 0x38, 0xb7, 0xdc, 0x46, 0x12, 0x20)
#define C_EFI_MEMORY_ATTRIBUTES_TABLE_VERSION C_EFI_U32_C(0x00000001)
typedef struct CEfiMemoryAttributesTable {
CEfiU32 version;
CEfiU32 number_of_entries;
CEfiU32 descriptor_size;
CEfiU32 reserved;
CEfiMemoryDescriptor entry[];
} CEfiMemoryAttributesTable;
//*******************************************************
// Task Priority Levels
//*******************************************************
#define C_EFI_TPL_APPLICATION 4
#define C_EFI_TPL_CALLBACK 8
#define C_EFI_TPL_NOTIFY 16
#define C_EFI_TPL_HIGH_LEVEL 31
/*
* Global Tables
*
* UEFI uses no global state, so all access to UEFI internal state is done
* through vtables you get passed to your entry-point. The global entry is the
* system-table, which encorporates several sub-tables, including the runtime
* and boot service tables, and configuration tables (including vendor
* extensions).
*/
#define C_EFI_2_70_SYSTEM_TABLE_REVISION ((2 << 16) | (70))
#define C_EFI_2_60_SYSTEM_TABLE_REVISION ((2 << 16) | (60))
#define C_EFI_2_50_SYSTEM_TABLE_REVISION ((2 << 16) | (50))
#define C_EFI_2_40_SYSTEM_TABLE_REVISION ((2 << 16) | (40))
#define C_EFI_2_31_SYSTEM_TABLE_REVISION ((2 << 16) | (31))
#define C_EFI_2_30_SYSTEM_TABLE_REVISION ((2 << 16) | (30))
#define C_EFI_2_20_SYSTEM_TABLE_REVISION ((2 << 16) | (20))
#define C_EFI_2_10_SYSTEM_TABLE_REVISION ((2 << 16) | (10))
#define C_EFI_2_00_SYSTEM_TABLE_REVISION ((2 << 16) | ( 0))
#define C_EFI_1_10_SYSTEM_TABLE_REVISION ((1 << 16) | (10))
#define C_EFI_1_02_SYSTEM_TABLE_REVISION ((1 << 16) | ( 2))
#define C_EFI_SPECIFICATION_VERSION C_EFI_SYSTEM_TABLE_REVISION
#define C_EFI_SYSTEM_TABLE_REVISION C_EFI_2_70_SYSTEM_TABLE_REVISION
#define C_EFI_RUNTIME_SERVICES_REVISION C_EFI_SPECIFICATION_VERSION
#define C_EFI_BOOT_SERVICES_REVISION C_EFI_SPECIFICATION_VERSION
typedef struct CEfiTableHeader {
CEfiU64 signature;
CEfiU32 revision;
CEfiU32 header_size;
CEfiU32 crc32;
CEfiU32 reserved;
} CEfiTableHeader;
#define C_EFI_RUNTIME_TABLE_SIGNATURE C_EFI_U64_C(0x56524553544e5552) /* "RUNTSERV" */
typedef struct CEfiRuntimeServices {
CEfiTableHeader hdr;
CEfiStatus (CEFICALL *get_time) (
CEfiTime *time,
CEfiTimeCapabilities *capabilities
);
CEfiStatus (CEFICALL *set_time) (
CEfiTime *time
);
CEfiStatus (CEFICALL *get_wakeup_time) (
CEfiBool *enabled,
CEfiBool *pending,
CEfiTime *time
);
CEfiStatus (CEFICALL *set_wakeup_time) (
CEfiBool enable,
CEfiTime *time
);
CEfiStatus (CEFICALL *set_virtual_address_map) (
CEfiUSize memory_map_size,
CEfiUSize descriptor_size,
CEfiU32 descriptor_version,
CEfiMemoryDescriptor *virtual_map
);
CEfiStatus (CEFICALL *convert_pointer) (
CEfiUSize debug_disposition,
void **address
);
CEfiStatus (CEFICALL *get_variable) (
CEfiChar16 *variable_name,
CEfiGuid *vendor_guid,
CEfiU32 *attributes,
CEfiUSize *data_size,
void *data
);
CEfiStatus (CEFICALL *get_next_variable_name) (
CEfiUSize *variable_name_size,
CEfiChar16 *variable_name,
CEfiGuid *vendor_guid
);
CEfiStatus (CEFICALL *set_variable) (
CEfiChar16 *variable_name,
CEfiGuid *vendor_guid,
CEfiU32 attributes,
CEfiUSize data_size,
void *data
);
CEfiStatus (CEFICALL *get_next_high_mono_count) (
CEfiU32 *high_count
);
void (CEFICALL *reset_system) (
CEfiResetType reset_type,
CEfiStatus reset_status,
CEfiUSize data_size,
void *reset_data
);
CEfiStatus (CEFICALL *update_capsule) (
CEfiCapsuleHeader **capsule_header_array,
CEfiUSize capsule_count,
CEfiPhysicalAddress scatter_gather_list
);
CEfiStatus (CEFICALL *query_capsule_capabilities) (
CEfiCapsuleHeader **capsule_header_array,
CEfiUSize capsule_count,
CEfiU64 *maximum_capsule_size,
CEfiResetType *reset_type
);
CEfiStatus (CEFICALL *query_variable_info) (
CEfiU32 attributes,
CEfiU64 *maximum_variable_storage_size,
CEfiU64 *remaining_variable_storage_size,
CEfiU64 *maximum_variable_size
);
} CEfiRuntimeServices;
#define C_EFI_BOOT_SERVICES_SIGNATURE C_EFI_U64_C(0x56524553544f4f42) /* "BOOTSERV" */
typedef struct CEfiBootServices {
CEfiTableHeader hdr;
CEfiTpl (CEFICALL *raise_tpl) (
CEfiTpl new_tpl
);
void (CEFICALL *restore_tpl) (
CEfiTpl old_tpl
);
CEfiStatus (CEFICALL *allocate_pages) (
CEfiAllocateType type,
CEfiMemoryType memory_type,
CEfiUSize pages,
CEfiPhysicalAddress *memory
);
CEfiStatus (CEFICALL *free_pages) (
CEfiPhysicalAddress memory,
CEfiUSize pages
);
CEfiStatus (CEFICALL *get_memory_map) (
CEfiUSize *memory_map_size,
CEfiMemoryDescriptor *memory_map,
CEfiUSize *map_key,
CEfiUSize *descriptor_size,
CEfiU32 *descriptor_version
);
CEfiStatus (CEFICALL *allocate_pool) (
CEfiMemoryType pool_type,
CEfiUSize size,
void **buffer
);
CEfiStatus (CEFICALL *free_pool) (
void *buffer
);
CEfiStatus (CEFICALL *create_event) (
CEfiU32 type,
CEfiTpl notify_tpl,
CEfiEventNotify notify_function,
void *notify_context,
CEfiEvent *event
);
CEfiStatus (CEFICALL *set_timer) (
CEfiEvent event,
CEfiTimerDelay type,
CEfiU64 trigger_time
);
CEfiStatus (CEFICALL *wait_for_event) (
CEfiUSize number_of_events,
CEfiEvent *event,
CEfiUSize *index
);
CEfiStatus (CEFICALL *signal_event) (
CEfiEvent event
);
CEfiStatus (CEFICALL *close_event) (
CEfiEvent event
);
CEfiStatus (CEFICALL *check_event) (
CEfiEvent event
);
CEfiStatus (CEFICALL *install_protocol_interface) (
CEfiHandle *handle,
CEfiGuid *protocol,
CEfiInterfaceType interface_type,
void *interface
);
CEfiStatus (CEFICALL *reinstall_protocol_interface) (
CEfiHandle handle,
CEfiGuid *protocol,
void *old_interface,
void *new_interface
);
CEfiStatus (CEFICALL *uninstall_protocol_interface) (
CEfiHandle handle,
CEfiGuid *protocol,
void *interface
);
CEfiStatus (CEFICALL *handle_protocol) (
CEfiHandle handle,
CEfiGuid *protocol,
void **interface
);
void *reserved;
CEfiStatus (CEFICALL *register_protocol_notify) (
CEfiGuid *protocol,
CEfiEvent event,
void **registration
);
CEfiStatus (CEFICALL *locate_handle) (
CEfiLocateSearchType search_type,
CEfiGuid *protocol,
void *search_key,
CEfiUSize *buffer_size,
CEfiHandle *buffer
);
CEfiStatus (CEFICALL *locate_device_path) (
CEfiGuid *protocol,
CEfiDevicePathProtocol **device_path,
CEfiHandle *device
);
CEfiStatus (CEFICALL *install_configuration_table) (
CEfiGuid *guid,
void *table
);
CEfiStatus (CEFICALL *load_image) (
CEfiBool boot_policy,
CEfiHandle parent_image_handle,
CEfiDevicePathProtocol *device_path,
void *source_buffer,
CEfiUSize source_size,
CEfiHandle *image_handle
);
CEfiStatus (CEFICALL *start_image) (
CEfiHandle image_handle,
CEfiUSize *exit_data_size,
CEfiChar16 **exit_data
);
CEfiStatus (CEFICALL *exit) (
CEfiHandle image_handle,
CEfiStatus exit_status,
CEfiUSize exit_data_size,
CEfiChar16 *exit_data
);
CEfiStatus (CEFICALL *unload_image) (
CEfiHandle image_handle
);
CEfiStatus (CEFICALL *exit_boot_services) (
CEfiHandle image_handle,
CEfiUSize map_key
);
CEfiStatus (CEFICALL *get_next_monotonic_count) (
CEfiU64 *count
);
CEfiStatus (CEFICALL *stall) (
CEfiUSize microseconds
);
CEfiStatus (CEFICALL *set_watchdog_timer) (
CEfiUSize timeout,
CEfiU64 watchdog_code,
CEfiUSize data_size,
CEfiChar16 *watchdog_data
);
/* 1.1+ */
CEfiStatus (CEFICALL *connect_controller) (
CEfiHandle controller_handle,
CEfiHandle *driver_image_handle,
CEfiDevicePathProtocol *remaining_device_path,
CEfiBool recursive
);
CEfiStatus (CEFICALL *disconnect_controller) (
CEfiHandle controller_handle,
CEfiHandle driver_image_handle,
CEfiHandle child_handle
);
CEfiStatus (CEFICALL *open_protocol) (
CEfiHandle handle,
CEfiGuid *protocol,
void **interface,
CEfiHandle agent_handle,
CEfiHandle controller_handle,
CEfiU32 attributes
);
CEfiStatus (CEFICALL *close_protocol) (
CEfiHandle handle,
CEfiGuid *protocol,
CEfiHandle agent_handle,
CEfiHandle controller_handle
);
CEfiStatus (CEFICALL *open_protocol_information) (
CEfiHandle handle,
CEfiGuid *protocol,
CEfiOpenProtocolInformationEntry **entry_buffer,
CEfiUSize *entry_count
);
CEfiStatus (CEFICALL *protocols_per_handle) (
CEfiHandle handle,
CEfiGuid ***protocol_buffer,
CEfiUSize *protocol_buffer_count
);
CEfiStatus (CEFICALL *locate_handle_buffer) (
CEfiLocateSearchType search_type,
CEfiGuid *protocol,
void *search_key,
CEfiUSize *no_handles,
CEfiHandle **buffer
);
CEfiStatus (CEFICALL *locate_protocol) (
CEfiGuid *protocol,
void *registration,
void **interface
);
CEfiStatus (CEFICALL *install_multiple_protocol_interfaces) (
CEfiHandle *handle,
...
);
CEfiStatus (CEFICALL *uninstall_multiple_protocol_interfaces) (
CEfiHandle handle,
...
);
CEfiStatus (CEFICALL *calculate_crc32) (
void *data,
CEfiUSize data_size,
CEfiU32 *crc32
);
void (CEFICALL *copy_mem) (
void *destination,
void *source,
CEfiUSize length
);
void (CEFICALL *set_mem) (
void *buffer,
CEfiUSize size,
CEfiU8 value
);
/* 2.0+ */
CEfiStatus (CEFICALL *create_event_ex) (
CEfiU32 type,
CEfiTpl notify_tpl,
CEfiEventNotify notify_function,
void *notify_context,
CEfiGuid *event_group,
CEfiEvent *event
);
} CEfiBootServices;
#define C_EFI_SYSTEM_TABLE_SIGNATURE C_EFI_U64_C(0x5453595320494249) /* "IBI SYST" */
typedef struct CEfiSystemTable {
CEfiTableHeader hdr;
CEfiChar16 *firmware_vendor;
CEfiU32 firmware_revision;
CEfiHandle console_in_handle;
CEfiSimpleTextInputProtocol *con_in;
CEfiHandle console_out_handle;
CEfiSimpleTextOutputProtocol *con_out;
CEfiHandle standard_error_handle;
CEfiSimpleTextOutputProtocol *std_err;
CEfiRuntimeServices *runtime_services;
CEfiBootServices *boot_services;
CEfiUSize number_of_table_entries;
CEfiConfigurationTable *configuration_table;
} CEfiSystemTable;
#ifdef __cplusplus
}
#endif
| 36.642091 | 143 | 0.630327 | [
"model"
] |
d6a46c96f01412fe2ca92e6ea4b0a163f5c11dd7 | 687 | h | C | stage0/src/kernel/for_each_fn.h | semorrison/lean4 | 6bd37361dce078123572b93c25005f9c34072622 | [
"Apache-2.0"
] | null | null | null | stage0/src/kernel/for_each_fn.h | semorrison/lean4 | 6bd37361dce078123572b93c25005f9c34072622 | [
"Apache-2.0"
] | null | null | null | stage0/src/kernel/for_each_fn.h | semorrison/lean4 | 6bd37361dce078123572b93c25005f9c34072622 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#pragma once
#include <memory>
#include <utility>
#include <functional>
#include <lean/buffer.h>
#include "kernel/expr.h"
#include "kernel/expr_sets.h"
namespace lean {
/** \brief Expression visitor.
The argument \c f must be a lambda (function object) containing the method
<code>
bool operator()(expr const & e, unsigned offset)
</code>
The \c offset is the number of binders under which \c e occurs.
*/
void for_each(expr const & e, std::function<bool(expr const &, unsigned)> && f); // NOLINT
}
| 24.535714 | 90 | 0.708879 | [
"object"
] |
d6a8f54046a0418d3ad3f91171dc62243b290d8b | 8,124 | h | C | modules/newbase/newbase/NFmiTime.h | fmidev/smartmet-workstation-vtk | ee1b42f63a9bc54dd5217e5c1a1fa8e672870a99 | [
"MIT"
] | null | null | null | modules/newbase/newbase/NFmiTime.h | fmidev/smartmet-workstation-vtk | ee1b42f63a9bc54dd5217e5c1a1fa8e672870a99 | [
"MIT"
] | null | null | null | modules/newbase/newbase/NFmiTime.h | fmidev/smartmet-workstation-vtk | ee1b42f63a9bc54dd5217e5c1a1fa8e672870a99 | [
"MIT"
] | null | null | null | // ======================================================================
/*!
* \file NFmiTime.h
* \brief Interface of class NFmiTime
*/
// ======================================================================
#pragma once
#include "NFmiStaticTime.h"
#include <boost/date_time/local_time/local_date_time.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#define DICT_WEEKDAY_MONDAY "WeekdayMonday"
#define DICT_WEEKDAY_TUESDAY "WeekdayTuesday"
#define DICT_WEEKDAY_WEDNESDAY "WeekdayWednesday"
#define DICT_WEEKDAY_THURSDAY "WeekdayThursday"
#define DICT_WEEKDAY_FRIDAY "WeekdayFriday"
#define DICT_WEEKDAY_SATURDAY "WeekdaySaturday"
#define DICT_WEEKDAY_SUNDAY "WeekdaySunday"
#define DICT_MONTH_JANUARY "MonthJanuary"
#define DICT_MONTH_FEBRUARY "MonthFebruary"
#define DICT_MONTH_MARCH "MonthMarch"
#define DICT_MONTH_APRIL "MonthApril"
#define DICT_MONTH_MAY "MonthMay"
#define DICT_MONTH_JUNE "MonthJune"
#define DICT_MONTH_JULY "MonthJuly"
#define DICT_MONTH_AUGUST "MonthAugust"
#define DICT_MONTH_SEPTEMPER "MonthSeptember"
#define DICT_MONTH_OCTOBER "MonthOctober"
#define DICT_MONTH_NOVEMBER "MonthNovember"
#define DICT_MONTH_DECEMBER "MonthDecember"
class NFmiLocation;
//! Undocumented
class _FMI_DLL NFmiTime : public NFmiStaticTime
{
public:
NFmiTime(void);
NFmiTime(const NFmiTime &aTime);
NFmiTime(long datePart, long timePart);
NFmiTime(short year, short month, short day);
NFmiTime(short year, short month, short day, short hour, short minute = 0, short sec = 0);
NFmiTime(const boost::posix_time::ptime &thePosixTime);
NFmiTime(const boost::local_time::local_date_time &theLocalTime);
NFmiTime &operator=(const NFmiTime &theTime);
static void Init(const FmiLanguage theLanguage);
// HUOM! tämä voi olla hämäävä, koska time_t on integer,
// (pitäisikö thehdä SetTime-metodi konstruktorin sijaan?)
explicit NFmiTime(std::time_t theTime);
// Use always even numbers between 0->12
// 0 = Real length of the night (not implemented yet)
bool IsNight(const NFmiLocation &theLocation, unsigned short theResolution = 12);
// Use always even numbers between 0->12
// 0 = Real length of the day (not implemented yet)
bool IsDay(const NFmiLocation &theLocation, unsigned short theResolution = 12);
void ChangeBySeconds(long seconds);
void ChangeByMinutes(long minutes);
void ChangeByHours(long hours);
void ChangeByDays(long days);
long DifferenceInMinutes(const NFmiTime &anotherTime) const;
long DifferenceInHours(const NFmiTime &anotherTime) const;
long DifferenceInDays(const NFmiTime &anotherTime) const;
short GetZoneDifferenceHour(void) const;
short GetWeekday(void) const; // mon=1, tue=2,..., sat=6, sun=7
const NFmiString Weekday(const FmiLanguage theLanguage = kFinnish) const;
const NFmiString MonthName(const FmiLanguage theLanguage = kFinnish) const;
using NFmiStaticTime::ToStr;
virtual const NFmiString ToStr(const NFmiString theTimeFormat,
const FmiLanguage theLanguage = kFinnish) const;
void PrintWeekday(void) const;
short GetJulianDay(void) const;
virtual const NFmiTime UTCTime(float theLongitude = kFloatMissing) const;
virtual const NFmiTime UTCTime(const NFmiLocation &theLocation) const;
virtual const NFmiTime LocalTime(float theLongitude = kFloatMissing) const;
virtual const NFmiTime LocalTime(const NFmiLocation &theLocation) const;
virtual void SetLocalPlace(float theLongitude);
static short DaysInYear(short aYear);
static short DaysInMonth(short aMonth, short aYear);
long GetCompareValue(void) const;
protected:
void DecodeCompareValue(long aCompareValue);
void SetZoneDifferenceHour(void);
short CalcZoneDifferenceHour(float theLongitude) const;
const NFmiString RelativeDay(FmiLanguage theLanguage,
NFmiString theFormat,
int &thePlusInd) const;
static std::string GetDictionaryString(const char *theMagicWord);
private:
short itsZoneDifferenceHour;
}; // class NFmiTime
//! Undocumented, should be removed
typedef NFmiTime *PTFmiTime;
//! Undocumented, should be removed
typedef NFmiTime TFmiTime;
// ----------------------------------------------------------------------
/*!
* Void constructor
*/
// ----------------------------------------------------------------------
inline NFmiTime::NFmiTime(void) : NFmiStaticTime(), itsZoneDifferenceHour()
{
SetZoneDifferenceHour();
}
// ----------------------------------------------------------------------
/*!
* Copy constructor
*
* \param aTime The object being copied
*/
// ----------------------------------------------------------------------
inline NFmiTime::NFmiTime(const NFmiTime &aTime)
: NFmiStaticTime(aTime), itsZoneDifferenceHour(aTime.itsZoneDifferenceHour)
{
}
// ----------------------------------------------------------------------
/*!
* Constructor
*
* \param year Undocumented
* \param month Undocumented
* \param day Undocumented
*/
// ----------------------------------------------------------------------
inline NFmiTime::NFmiTime(short year, short month, short day)
: NFmiStaticTime(year, month, day), itsZoneDifferenceHour()
{
SetZoneDifferenceHour();
}
// ----------------------------------------------------------------------
/*!
* Constructor
*
* \param year Undocumented
* \param month Undocumented
* \param day Undocumented
* \param hour Undocumented
* \param minute Undocumented
* \param sec Undocumented
*/
// ----------------------------------------------------------------------
inline NFmiTime::NFmiTime(short year, short month, short day, short hour, short minute, short sec)
: NFmiStaticTime(year, month, day, hour, minute, sec), itsZoneDifferenceHour()
{
SetZoneDifferenceHour();
}
// ----------------------------------------------------------------------
/*!
* \param minutes Undocumented
*/
// ----------------------------------------------------------------------
inline void NFmiTime::ChangeByMinutes(long minutes)
{
if (minutes) DecodeCompareValue(GetCompareValue() + minutes);
}
// ----------------------------------------------------------------------
/*!
* \param hours Undocumented
*/
// ----------------------------------------------------------------------
inline void NFmiTime::ChangeByHours(long hours)
{
if (hours) DecodeCompareValue(GetCompareValue() + 60L * hours);
}
// ----------------------------------------------------------------------
/*!
* \param days Undocumented
*/
// ----------------------------------------------------------------------
inline void NFmiTime::ChangeByDays(long days)
{
if (days) DecodeCompareValue(GetCompareValue() + 60L * 24L * days);
}
// ----------------------------------------------------------------------
/*!
* \param anotherTime Undocumented
* \return Undocumented
*/
// ----------------------------------------------------------------------
inline long NFmiTime::DifferenceInMinutes(const NFmiTime &anotherTime) const
{
return (GetCompareValue() - anotherTime.GetCompareValue());
}
// ----------------------------------------------------------------------
/*!
* \param anotherTime Undocumented
* \return Undocumented
*/
// ----------------------------------------------------------------------
inline long NFmiTime::DifferenceInHours(const NFmiTime &anotherTime) const
{
return (DifferenceInMinutes(anotherTime) / 60L);
}
// ----------------------------------------------------------------------
/*!
* \param anotherTime Undocumented
* \return Undocumented
*/
// ----------------------------------------------------------------------
inline long NFmiTime::DifferenceInDays(const NFmiTime &anotherTime) const
{
return (DifferenceInMinutes(anotherTime) / 60L / 24L);
}
// ----------------------------------------------------------------------
/*!
* \return Undocumented
*/
// ----------------------------------------------------------------------
inline short NFmiTime::GetZoneDifferenceHour(void) const { return itsZoneDifferenceHour; }
// ======================================================================
| 30.889734 | 98 | 0.582226 | [
"object"
] |
d6a9cfbb99801e0a5a263db0d96f695673d6c7fd | 8,741 | h | C | android/android_9/frameworks/av/media/libmedia/include/media/BufferProviders.h | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | null | null | null | android/android_9/frameworks/av/media/libmedia/include/media/BufferProviders.h | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | null | null | null | android/android_9/frameworks/av/media/libmedia/include/media/BufferProviders.h | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_BUFFER_PROVIDERS_H
#define ANDROID_BUFFER_PROVIDERS_H
#include <stdint.h>
#include <sys/types.h>
#include <media/AudioBufferProvider.h>
#include <media/AudioResamplerPublic.h>
#include <system/audio.h>
#include <system/audio_effect.h>
#include <utils/StrongPointer.h>
// external forward declaration from external/sonic/sonic.h
struct sonicStreamStruct;
typedef struct sonicStreamStruct *sonicStream;
namespace android {
class EffectBufferHalInterface;
class EffectHalInterface;
class EffectsFactoryHalInterface;
// ----------------------------------------------------------------------------
class PassthruBufferProvider : public AudioBufferProvider {
public:
PassthruBufferProvider() : mTrackBufferProvider(NULL) { }
virtual ~PassthruBufferProvider() { }
// call this to release the buffer to the upstream provider.
// treat it as an audio discontinuity for future samples.
virtual void reset() { }
// set the upstream buffer provider. Consider calling "reset" before this function.
virtual void setBufferProvider(AudioBufferProvider *p) {
mTrackBufferProvider = p;
}
protected:
AudioBufferProvider *mTrackBufferProvider;
};
// Base AudioBufferProvider class used for DownMixerBufferProvider, RemixBufferProvider,
// and ReformatBufferProvider.
// It handles a private buffer for use in converting format or channel masks from the
// input data to a form acceptable by the mixer.
// TODO: Make a ResamplerBufferProvider when integers are entirely removed from the
// processing pipeline.
class CopyBufferProvider : public PassthruBufferProvider {
public:
// Use a private buffer of bufferFrameCount frames (each frame is outputFrameSize bytes).
// If bufferFrameCount is 0, no private buffer is created and in-place modification of
// the upstream buffer provider's buffers is performed by copyFrames().
CopyBufferProvider(size_t inputFrameSize, size_t outputFrameSize,
size_t bufferFrameCount);
virtual ~CopyBufferProvider();
// Overrides AudioBufferProvider methods
virtual status_t getNextBuffer(Buffer *buffer);
virtual void releaseBuffer(Buffer *buffer);
// Overrides PassthruBufferProvider
virtual void reset();
// this function should be supplied by the derived class. It converts
// #frames in the *src pointer to the *dst pointer. It is public because
// some providers will allow this to work on arbitrary buffers outside
// of the internal buffers.
virtual void copyFrames(void *dst, const void *src, size_t frames) = 0;
protected:
const size_t mInputFrameSize;
const size_t mOutputFrameSize;
private:
AudioBufferProvider::Buffer mBuffer;
const size_t mLocalBufferFrameCount;
void *mLocalBufferData;
size_t mConsumed;
};
// DownmixerBufferProvider derives from CopyBufferProvider to provide
// position dependent downmixing by an Audio Effect.
class DownmixerBufferProvider : public CopyBufferProvider {
public:
DownmixerBufferProvider(audio_channel_mask_t inputChannelMask,
audio_channel_mask_t outputChannelMask, audio_format_t format,
uint32_t sampleRate, int32_t sessionId, size_t bufferFrameCount);
virtual ~DownmixerBufferProvider();
//Overrides
virtual void copyFrames(void *dst, const void *src, size_t frames);
bool isValid() const { return mDownmixInterface.get() != NULL; }
static status_t init();
static bool isMultichannelCapable() { return sIsMultichannelCapable; }
protected:
sp<EffectsFactoryHalInterface> mEffectsFactory;
sp<EffectHalInterface> mDownmixInterface;
size_t mInFrameSize;
size_t mOutFrameSize;
sp<EffectBufferHalInterface> mInBuffer;
sp<EffectBufferHalInterface> mOutBuffer;
effect_config_t mDownmixConfig;
// effect descriptor for the downmixer used by the mixer
static effect_descriptor_t sDwnmFxDesc;
// indicates whether a downmix effect has been found and is usable by this mixer
static bool sIsMultichannelCapable;
// FIXME: should we allow effects outside of the framework?
// We need to here. A special ioId that must be <= -2 so it does not map to a session.
static const int32_t SESSION_ID_INVALID_AND_IGNORED = -2;
};
// RemixBufferProvider derives from CopyBufferProvider to perform an
// upmix or downmix to the proper channel count and mask.
class RemixBufferProvider : public CopyBufferProvider {
public:
RemixBufferProvider(audio_channel_mask_t inputChannelMask,
audio_channel_mask_t outputChannelMask, audio_format_t format,
size_t bufferFrameCount);
//Overrides
virtual void copyFrames(void *dst, const void *src, size_t frames);
protected:
const audio_format_t mFormat;
const size_t mSampleSize;
const size_t mInputChannels;
const size_t mOutputChannels;
int8_t mIdxAry[sizeof(uint32_t) * 8]; // 32 bits => channel indices
};
// ReformatBufferProvider derives from CopyBufferProvider to convert the input data
// to an acceptable mixer input format type.
class ReformatBufferProvider : public CopyBufferProvider {
public:
ReformatBufferProvider(int32_t channelCount,
audio_format_t inputFormat, audio_format_t outputFormat,
size_t bufferFrameCount);
virtual void copyFrames(void *dst, const void *src, size_t frames);
protected:
const uint32_t mChannelCount;
const audio_format_t mInputFormat;
const audio_format_t mOutputFormat;
};
// ClampFloatBufferProvider derives from CopyBufferProvider to clamp floats inside -3db
class ClampFloatBufferProvider : public CopyBufferProvider {
public:
ClampFloatBufferProvider(int32_t channelCount,
size_t bufferFrameCount);
virtual void copyFrames(void *dst, const void *src, size_t frames);
protected:
const uint32_t mChannelCount;
};
// TimestretchBufferProvider derives from PassthruBufferProvider for time stretching
class TimestretchBufferProvider : public PassthruBufferProvider {
public:
TimestretchBufferProvider(int32_t channelCount,
audio_format_t format, uint32_t sampleRate,
const AudioPlaybackRate &playbackRate);
virtual ~TimestretchBufferProvider();
// Overrides AudioBufferProvider methods
virtual status_t getNextBuffer(Buffer* buffer);
virtual void releaseBuffer(Buffer* buffer);
// Overrides PassthruBufferProvider
virtual void reset();
virtual status_t setPlaybackRate(const AudioPlaybackRate &playbackRate);
// processes frames
// dstBuffer is where to place the data
// dstFrames [in/out] is the desired frames (return with actual placed in buffer)
// srcBuffer is the source data
// srcFrames [in/out] is the available source frames (return with consumed)
virtual void processFrames(void *dstBuffer, size_t *dstFrames,
const void *srcBuffer, size_t *srcFrames);
protected:
const uint32_t mChannelCount;
const audio_format_t mFormat;
const uint32_t mSampleRate; // const for now (TODO change this)
const size_t mFrameSize;
AudioPlaybackRate mPlaybackRate;
private:
AudioBufferProvider::Buffer mBuffer; // for upstream request
size_t mLocalBufferFrameCount; // size of local buffer
void *mLocalBufferData; // internally allocated buffer for data returned
// to caller
size_t mRemaining; // remaining data in local buffer
sonicStream mSonicStream; // handle to sonic timestretch object
//FIXME: this dependency should be abstracted out
bool mFallbackFailErrorShown; // log fallback error only once
bool mAudioPlaybackRateValid; // flag for current parameters validity
};
// ----------------------------------------------------------------------------
} // namespace android
#endif // ANDROID_BUFFER_PROVIDERS_H
| 39.197309 | 98 | 0.717538 | [
"object"
] |
d6aaf65192e90f14301c76870f8c8a1ec7238b8d | 45,374 | c | C | release/src-rt/linux/linux-2.6/net/wireless/wext.c | ghsecuritylab/tomato_egg | 50473a46347f4631eb4878a0f47955cc64c87293 | [
"FSFAP"
] | 278 | 2015-11-03T03:01:20.000Z | 2022-01-20T18:21:05.000Z | release/src-rt/linux/linux-2.6/net/wireless/wext.c | ghsecuritylab/tomato_egg | 50473a46347f4631eb4878a0f47955cc64c87293 | [
"FSFAP"
] | 374 | 2015-11-03T12:37:22.000Z | 2021-12-17T14:18:08.000Z | release/src-rt/linux/linux-2.6/net/wireless/wext.c | ghsecuritylab/tomato_egg | 50473a46347f4631eb4878a0f47955cc64c87293 | [
"FSFAP"
] | 96 | 2015-11-22T07:47:26.000Z | 2022-01-20T19:52:19.000Z | /*
* This file implement the Wireless Extensions APIs.
*
* Authors : Jean Tourrilhes - HPL - <jt@hpl.hp.com>
* Copyright (c) 1997-2007 Jean Tourrilhes, All Rights Reserved.
*
* (As all part of the Linux kernel, this file is GPL)
*/
/************************** DOCUMENTATION **************************/
/*
* API definition :
* --------------
* See <linux/wireless.h> for details of the APIs and the rest.
*
* History :
* -------
*
* v1 - 5.12.01 - Jean II
* o Created this file.
*
* v2 - 13.12.01 - Jean II
* o Move /proc/net/wireless stuff from net/core/dev.c to here
* o Make Wireless Extension IOCTLs go through here
* o Added iw_handler handling ;-)
* o Added standard ioctl description
* o Initial dumb commit strategy based on orinoco.c
*
* v3 - 19.12.01 - Jean II
* o Make sure we don't go out of standard_ioctl[] in ioctl_standard_call
* o Add event dispatcher function
* o Add event description
* o Propagate events as rtnetlink IFLA_WIRELESS option
* o Generate event on selected SET requests
*
* v4 - 18.04.02 - Jean II
* o Fix stupid off by one in iw_ioctl_description : IW_ESSID_MAX_SIZE + 1
*
* v5 - 21.06.02 - Jean II
* o Add IW_PRIV_TYPE_ADDR in priv_type_size (+cleanup)
* o Reshuffle IW_HEADER_TYPE_XXX to map IW_PRIV_TYPE_XXX changes
* o Add IWEVCUSTOM for driver specific event/scanning token
* o Turn on WE_STRICT_WRITE by default + kernel warning
* o Fix WE_STRICT_WRITE in ioctl_export_private() (32 => iw_num)
* o Fix off-by-one in test (extra_size <= IFNAMSIZ)
*
* v6 - 9.01.03 - Jean II
* o Add common spy support : iw_handler_set_spy(), wireless_spy_update()
* o Add enhanced spy support : iw_handler_set_thrspy() and event.
* o Add WIRELESS_EXT version display in /proc/net/wireless
*
* v6 - 18.06.04 - Jean II
* o Change get_spydata() method for added safety
* o Remove spy #ifdef, they are always on -> cleaner code
* o Allow any size GET request if user specifies length > max
* and if request has IW_DESCR_FLAG_NOMAX flag or is SIOCGIWPRIV
* o Start migrating get_wireless_stats to struct iw_handler_def
* o Add wmb() in iw_handler_set_spy() for non-coherent archs/cpus
* Based on patch from Pavel Roskin <proski@gnu.org> :
* o Fix kernel data leak to user space in private handler handling
*
* v7 - 18.3.05 - Jean II
* o Remove (struct iw_point *)->pointer from events and streams
* o Remove spy_offset from struct iw_handler_def
* o Start deprecating dev->get_wireless_stats, output a warning
* o If IW_QUAL_DBM is set, show dBm values in /proc/net/wireless
* o Don't loose INVALID/DBM flags when clearing UPDATED flags (iwstats)
*
* v8 - 17.02.06 - Jean II
* o RtNetlink requests support (SET/GET)
*
* v8b - 03.08.06 - Herbert Xu
* o Fix Wireless Event locking issues.
*
* v9 - 14.3.06 - Jean II
* o Change length in ESSID and NICK to strlen() instead of strlen()+1
* o Make standard_ioctl_num and standard_event_num unsigned
* o Remove (struct net_device *)->get_wireless_stats()
*
* v10 - 16.3.07 - Jean II
* o Prevent leaking of kernel space in stream on 64 bits.
*/
/***************************** INCLUDES *****************************/
#include <linux/module.h>
#include <linux/types.h> /* off_t */
#include <linux/netdevice.h> /* struct ifreq, dev_get_by_name() */
#include <linux/proc_fs.h>
#include <linux/rtnetlink.h> /* rtnetlink stuff */
#include <linux/seq_file.h>
#include <linux/init.h> /* for __init */
#include <linux/if_arp.h> /* ARPHRD_ETHER */
#include <linux/etherdevice.h> /* compare_ether_addr */
#include <linux/interrupt.h>
#include <linux/wireless.h> /* Pretty obvious */
#include <net/iw_handler.h> /* New driver API */
#include <net/netlink.h>
#include <net/wext.h>
#include <asm/uaccess.h> /* copy_to_user() */
/************************* GLOBAL VARIABLES *************************/
/*
* You should not use global variables, because of re-entrancy.
* On our case, it's only const, so it's OK...
*/
/*
* Meta-data about all the standard Wireless Extension request we
* know about.
*/
static const struct iw_ioctl_description standard_ioctl[] = {
[SIOCSIWCOMMIT - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_NULL,
},
[SIOCGIWNAME - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_CHAR,
.flags = IW_DESCR_FLAG_DUMP,
},
[SIOCSIWNWID - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_PARAM,
.flags = IW_DESCR_FLAG_EVENT,
},
[SIOCGIWNWID - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_PARAM,
.flags = IW_DESCR_FLAG_DUMP,
},
[SIOCSIWFREQ - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_FREQ,
.flags = IW_DESCR_FLAG_EVENT,
},
[SIOCGIWFREQ - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_FREQ,
.flags = IW_DESCR_FLAG_DUMP,
},
[SIOCSIWMODE - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_UINT,
.flags = IW_DESCR_FLAG_EVENT,
},
[SIOCGIWMODE - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_UINT,
.flags = IW_DESCR_FLAG_DUMP,
},
[SIOCSIWSENS - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_PARAM,
},
[SIOCGIWSENS - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_PARAM,
},
[SIOCSIWRANGE - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_NULL,
},
[SIOCGIWRANGE - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = 1,
.max_tokens = sizeof(struct iw_range),
.flags = IW_DESCR_FLAG_DUMP,
},
[SIOCSIWPRIV - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_NULL,
},
[SIOCGIWPRIV - SIOCIWFIRST] = { /* (handled directly by us) */
.header_type = IW_HEADER_TYPE_POINT,
.token_size = sizeof(struct iw_priv_args),
.max_tokens = 16,
.flags = IW_DESCR_FLAG_NOMAX,
},
[SIOCSIWSTATS - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_NULL,
},
[SIOCGIWSTATS - SIOCIWFIRST] = { /* (handled directly by us) */
.header_type = IW_HEADER_TYPE_POINT,
.token_size = 1,
.max_tokens = sizeof(struct iw_statistics),
.flags = IW_DESCR_FLAG_DUMP,
},
[SIOCSIWSPY - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = sizeof(struct sockaddr),
.max_tokens = IW_MAX_SPY,
},
[SIOCGIWSPY - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = sizeof(struct sockaddr) +
sizeof(struct iw_quality),
.max_tokens = IW_MAX_SPY,
},
[SIOCSIWTHRSPY - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = sizeof(struct iw_thrspy),
.min_tokens = 1,
.max_tokens = 1,
},
[SIOCGIWTHRSPY - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = sizeof(struct iw_thrspy),
.min_tokens = 1,
.max_tokens = 1,
},
[SIOCSIWAP - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_ADDR,
},
[SIOCGIWAP - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_ADDR,
.flags = IW_DESCR_FLAG_DUMP,
},
[SIOCSIWMLME - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = 1,
.min_tokens = sizeof(struct iw_mlme),
.max_tokens = sizeof(struct iw_mlme),
},
[SIOCGIWAPLIST - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = sizeof(struct sockaddr) +
sizeof(struct iw_quality),
.max_tokens = IW_MAX_AP,
.flags = IW_DESCR_FLAG_NOMAX,
},
[SIOCSIWSCAN - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = 1,
.min_tokens = 0,
.max_tokens = sizeof(struct iw_scan_req),
},
[SIOCGIWSCAN - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = 1,
.max_tokens = IW_SCAN_MAX_DATA,
.flags = IW_DESCR_FLAG_NOMAX,
},
[SIOCSIWESSID - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = 1,
.max_tokens = IW_ESSID_MAX_SIZE,
.flags = IW_DESCR_FLAG_EVENT,
},
[SIOCGIWESSID - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = 1,
.max_tokens = IW_ESSID_MAX_SIZE,
.flags = IW_DESCR_FLAG_DUMP,
},
[SIOCSIWNICKN - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = 1,
.max_tokens = IW_ESSID_MAX_SIZE,
},
[SIOCGIWNICKN - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = 1,
.max_tokens = IW_ESSID_MAX_SIZE,
},
[SIOCSIWRATE - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_PARAM,
},
[SIOCGIWRATE - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_PARAM,
},
[SIOCSIWRTS - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_PARAM,
},
[SIOCGIWRTS - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_PARAM,
},
[SIOCSIWFRAG - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_PARAM,
},
[SIOCGIWFRAG - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_PARAM,
},
[SIOCSIWTXPOW - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_PARAM,
},
[SIOCGIWTXPOW - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_PARAM,
},
[SIOCSIWRETRY - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_PARAM,
},
[SIOCGIWRETRY - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_PARAM,
},
[SIOCSIWENCODE - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = 1,
.max_tokens = IW_ENCODING_TOKEN_MAX,
.flags = IW_DESCR_FLAG_EVENT | IW_DESCR_FLAG_RESTRICT,
},
[SIOCGIWENCODE - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = 1,
.max_tokens = IW_ENCODING_TOKEN_MAX,
.flags = IW_DESCR_FLAG_DUMP | IW_DESCR_FLAG_RESTRICT,
},
[SIOCSIWPOWER - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_PARAM,
},
[SIOCGIWPOWER - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_PARAM,
},
[SIOCSIWGENIE - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = 1,
.max_tokens = IW_GENERIC_IE_MAX,
},
[SIOCGIWGENIE - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = 1,
.max_tokens = IW_GENERIC_IE_MAX,
},
[SIOCSIWAUTH - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_PARAM,
},
[SIOCGIWAUTH - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_PARAM,
},
[SIOCSIWENCODEEXT - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = 1,
.min_tokens = sizeof(struct iw_encode_ext),
.max_tokens = sizeof(struct iw_encode_ext) +
IW_ENCODING_TOKEN_MAX,
},
[SIOCGIWENCODEEXT - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = 1,
.min_tokens = sizeof(struct iw_encode_ext),
.max_tokens = sizeof(struct iw_encode_ext) +
IW_ENCODING_TOKEN_MAX,
},
[SIOCSIWPMKSA - SIOCIWFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = 1,
.min_tokens = sizeof(struct iw_pmksa),
.max_tokens = sizeof(struct iw_pmksa),
},
};
static const unsigned standard_ioctl_num = ARRAY_SIZE(standard_ioctl);
/*
* Meta-data about all the additional standard Wireless Extension events
* we know about.
*/
static const struct iw_ioctl_description standard_event[] = {
[IWEVTXDROP - IWEVFIRST] = {
.header_type = IW_HEADER_TYPE_ADDR,
},
[IWEVQUAL - IWEVFIRST] = {
.header_type = IW_HEADER_TYPE_QUAL,
},
[IWEVCUSTOM - IWEVFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = 1,
.max_tokens = IW_CUSTOM_MAX,
},
[IWEVREGISTERED - IWEVFIRST] = {
.header_type = IW_HEADER_TYPE_ADDR,
},
[IWEVEXPIRED - IWEVFIRST] = {
.header_type = IW_HEADER_TYPE_ADDR,
},
[IWEVGENIE - IWEVFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = 1,
.max_tokens = IW_GENERIC_IE_MAX,
},
[IWEVMICHAELMICFAILURE - IWEVFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = 1,
.max_tokens = sizeof(struct iw_michaelmicfailure),
},
[IWEVASSOCREQIE - IWEVFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = 1,
.max_tokens = IW_GENERIC_IE_MAX,
},
[IWEVASSOCRESPIE - IWEVFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = 1,
.max_tokens = IW_GENERIC_IE_MAX,
},
[IWEVPMKIDCAND - IWEVFIRST] = {
.header_type = IW_HEADER_TYPE_POINT,
.token_size = 1,
.max_tokens = sizeof(struct iw_pmkid_cand),
},
};
static const unsigned standard_event_num = ARRAY_SIZE(standard_event);
/* Size (in bytes) of the various private data types */
static const char iw_priv_type_size[] = {
0, /* IW_PRIV_TYPE_NONE */
1, /* IW_PRIV_TYPE_BYTE */
1, /* IW_PRIV_TYPE_CHAR */
0, /* Not defined */
sizeof(__u32), /* IW_PRIV_TYPE_INT */
sizeof(struct iw_freq), /* IW_PRIV_TYPE_FLOAT */
sizeof(struct sockaddr), /* IW_PRIV_TYPE_ADDR */
0, /* Not defined */
};
/* Size (in bytes) of various events */
static const int event_type_size[] = {
IW_EV_LCP_LEN, /* IW_HEADER_TYPE_NULL */
0,
IW_EV_CHAR_LEN, /* IW_HEADER_TYPE_CHAR */
0,
IW_EV_UINT_LEN, /* IW_HEADER_TYPE_UINT */
IW_EV_FREQ_LEN, /* IW_HEADER_TYPE_FREQ */
IW_EV_ADDR_LEN, /* IW_HEADER_TYPE_ADDR */
0,
IW_EV_POINT_LEN, /* Without variable payload */
IW_EV_PARAM_LEN, /* IW_HEADER_TYPE_PARAM */
IW_EV_QUAL_LEN, /* IW_HEADER_TYPE_QUAL */
};
/* Size (in bytes) of various events, as packed */
static const int event_type_pk_size[] = {
IW_EV_LCP_PK_LEN, /* IW_HEADER_TYPE_NULL */
0,
IW_EV_CHAR_PK_LEN, /* IW_HEADER_TYPE_CHAR */
0,
IW_EV_UINT_PK_LEN, /* IW_HEADER_TYPE_UINT */
IW_EV_FREQ_PK_LEN, /* IW_HEADER_TYPE_FREQ */
IW_EV_ADDR_PK_LEN, /* IW_HEADER_TYPE_ADDR */
0,
IW_EV_POINT_PK_LEN, /* Without variable payload */
IW_EV_PARAM_PK_LEN, /* IW_HEADER_TYPE_PARAM */
IW_EV_QUAL_PK_LEN, /* IW_HEADER_TYPE_QUAL */
};
/************************ COMMON SUBROUTINES ************************/
/*
* Stuff that may be used in various place or doesn't fit in one
* of the section below.
*/
/* ---------------------------------------------------------------- */
/*
* Return the driver handler associated with a specific Wireless Extension.
*/
static iw_handler get_handler(struct net_device *dev, unsigned int cmd)
{
/* Don't "optimise" the following variable, it will crash */
unsigned int index; /* *MUST* be unsigned */
/* Check if we have some wireless handlers defined */
if (dev->wireless_handlers == NULL)
return NULL;
/* Try as a standard command */
index = cmd - SIOCIWFIRST;
if (index < dev->wireless_handlers->num_standard)
return dev->wireless_handlers->standard[index];
/* Try as a private command */
index = cmd - SIOCIWFIRSTPRIV;
if (index < dev->wireless_handlers->num_private)
return dev->wireless_handlers->private[index];
/* Not found */
return NULL;
}
/* ---------------------------------------------------------------- */
/*
* Get statistics out of the driver
*/
static struct iw_statistics *get_wireless_stats(struct net_device *dev)
{
/* New location */
if ((dev->wireless_handlers != NULL) &&
(dev->wireless_handlers->get_wireless_stats != NULL))
return dev->wireless_handlers->get_wireless_stats(dev);
/* Not found */
return NULL;
}
/* ---------------------------------------------------------------- */
/*
* Call the commit handler in the driver
* (if exist and if conditions are right)
*
* Note : our current commit strategy is currently pretty dumb,
* but we will be able to improve on that...
* The goal is to try to agreagate as many changes as possible
* before doing the commit. Drivers that will define a commit handler
* are usually those that need a reset after changing parameters, so
* we want to minimise the number of reset.
* A cool idea is to use a timer : at each "set" command, we re-set the
* timer, when the timer eventually fires, we call the driver.
* Hopefully, more on that later.
*
* Also, I'm waiting to see how many people will complain about the
* netif_running(dev) test. I'm open on that one...
* Hopefully, the driver will remember to do a commit in "open()" ;-)
*/
static int call_commit_handler(struct net_device *dev)
{
if ((netif_running(dev)) &&
(dev->wireless_handlers->standard[0] != NULL))
/* Call the commit handler on the driver */
return dev->wireless_handlers->standard[0](dev, NULL,
NULL, NULL);
else
return 0; /* Command completed successfully */
}
/* ---------------------------------------------------------------- */
/*
* Calculate size of private arguments
*/
static inline int get_priv_size(__u16 args)
{
int num = args & IW_PRIV_SIZE_MASK;
int type = (args & IW_PRIV_TYPE_MASK) >> 12;
return num * iw_priv_type_size[type];
}
/* ---------------------------------------------------------------- */
/*
* Re-calculate the size of private arguments
*/
static inline int adjust_priv_size(__u16 args,
union iwreq_data * wrqu)
{
int num = wrqu->data.length;
int max = args & IW_PRIV_SIZE_MASK;
int type = (args & IW_PRIV_TYPE_MASK) >> 12;
/* Make sure the driver doesn't goof up */
if (max < num)
num = max;
return num * iw_priv_type_size[type];
}
/* ---------------------------------------------------------------- */
/*
* Standard Wireless Handler : get wireless stats
* Allow programatic access to /proc/net/wireless even if /proc
* doesn't exist... Also more efficient...
*/
static int iw_handler_get_iwstats(struct net_device * dev,
struct iw_request_info * info,
union iwreq_data * wrqu,
char * extra)
{
/* Get stats from the driver */
struct iw_statistics *stats;
stats = get_wireless_stats(dev);
if (stats) {
/* Copy statistics to extra */
memcpy(extra, stats, sizeof(struct iw_statistics));
wrqu->data.length = sizeof(struct iw_statistics);
/* Check if we need to clear the updated flag */
if (wrqu->data.flags != 0)
stats->qual.updated &= ~IW_QUAL_ALL_UPDATED;
return 0;
} else
return -EOPNOTSUPP;
}
/* ---------------------------------------------------------------- */
/*
* Standard Wireless Handler : get iwpriv definitions
* Export the driver private handler definition
* They will be picked up by tools like iwpriv...
*/
static int iw_handler_get_private(struct net_device * dev,
struct iw_request_info * info,
union iwreq_data * wrqu,
char * extra)
{
/* Check if the driver has something to export */
if ((dev->wireless_handlers->num_private_args == 0) ||
(dev->wireless_handlers->private_args == NULL))
return -EOPNOTSUPP;
/* Check if there is enough buffer up there */
if (wrqu->data.length < dev->wireless_handlers->num_private_args) {
/* User space can't know in advance how large the buffer
* needs to be. Give it a hint, so that we can support
* any size buffer we want somewhat efficiently... */
wrqu->data.length = dev->wireless_handlers->num_private_args;
return -E2BIG;
}
/* Set the number of available ioctls. */
wrqu->data.length = dev->wireless_handlers->num_private_args;
/* Copy structure to the user buffer. */
memcpy(extra, dev->wireless_handlers->private_args,
sizeof(struct iw_priv_args) * wrqu->data.length);
return 0;
}
/******************** /proc/net/wireless SUPPORT ********************/
/*
* The /proc/net/wireless file is a human readable user-space interface
* exporting various wireless specific statistics from the wireless devices.
* This is the most popular part of the Wireless Extensions ;-)
*
* This interface is a pure clone of /proc/net/dev (in net/core/dev.c).
* The content of the file is basically the content of "struct iw_statistics".
*/
#ifdef CONFIG_PROC_FS
/* ---------------------------------------------------------------- */
/*
* Print one entry (line) of /proc/net/wireless
*/
static void wireless_seq_printf_stats(struct seq_file *seq,
struct net_device *dev)
{
/* Get stats from the driver */
struct iw_statistics *stats = get_wireless_stats(dev);
if (stats) {
seq_printf(seq, "%6s: %04x %3d%c %3d%c %3d%c %6d %6d %6d "
"%6d %6d %6d\n",
dev->name, stats->status, stats->qual.qual,
stats->qual.updated & IW_QUAL_QUAL_UPDATED
? '.' : ' ',
((__s32) stats->qual.level) -
((stats->qual.updated & IW_QUAL_DBM) ? 0x100 : 0),
stats->qual.updated & IW_QUAL_LEVEL_UPDATED
? '.' : ' ',
((__s32) stats->qual.noise) -
((stats->qual.updated & IW_QUAL_DBM) ? 0x100 : 0),
stats->qual.updated & IW_QUAL_NOISE_UPDATED
? '.' : ' ',
stats->discard.nwid, stats->discard.code,
stats->discard.fragment, stats->discard.retries,
stats->discard.misc, stats->miss.beacon);
stats->qual.updated &= ~IW_QUAL_ALL_UPDATED;
}
}
/* ---------------------------------------------------------------- */
/*
* Print info for /proc/net/wireless (print all entries)
*/
static int wireless_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_printf(seq, "Inter-| sta-| Quality | Discarded "
"packets | Missed | WE\n"
" face | tus | link level noise | nwid "
"crypt frag retry misc | beacon | %d\n",
WIRELESS_EXT);
else
wireless_seq_printf_stats(seq, v);
return 0;
}
static const struct seq_operations wireless_seq_ops = {
.start = dev_seq_start,
.next = dev_seq_next,
.stop = dev_seq_stop,
.show = wireless_seq_show,
};
static int wireless_seq_open(struct inode *inode, struct file *file)
{
return seq_open(file, &wireless_seq_ops);
}
static const struct file_operations wireless_seq_fops = {
.owner = THIS_MODULE,
.open = wireless_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
int __init wext_proc_init(void)
{
/* Create /proc/net/wireless entry */
if (!proc_net_fops_create("wireless", S_IRUGO, &wireless_seq_fops))
return -ENOMEM;
return 0;
}
#endif /* CONFIG_PROC_FS */
/************************** IOCTL SUPPORT **************************/
/*
* The original user space API to configure all those Wireless Extensions
* is through IOCTLs.
* In there, we check if we need to call the new driver API (iw_handler)
* or just call the driver ioctl handler.
*/
/* ---------------------------------------------------------------- */
/*
* Wrapper to call a standard Wireless Extension handler.
* We do various checks and also take care of moving data between
* user space and kernel space.
*/
static int ioctl_standard_call(struct net_device * dev,
struct ifreq * ifr,
unsigned int cmd,
iw_handler handler)
{
struct iwreq * iwr = (struct iwreq *) ifr;
const struct iw_ioctl_description * descr;
struct iw_request_info info;
int ret = -EINVAL;
/* Get the description of the IOCTL */
if ((cmd - SIOCIWFIRST) >= standard_ioctl_num)
return -EOPNOTSUPP;
descr = &(standard_ioctl[cmd - SIOCIWFIRST]);
/* Prepare the call */
info.cmd = cmd;
info.flags = 0;
/* Check if we have a pointer to user space data or not */
if (descr->header_type != IW_HEADER_TYPE_POINT) {
/* No extra arguments. Trivial to handle */
ret = handler(dev, &info, &(iwr->u), NULL);
/* Generate an event to notify listeners of the change */
if ((descr->flags & IW_DESCR_FLAG_EVENT) &&
((ret == 0) || (ret == -EIWCOMMIT)))
wireless_send_event(dev, cmd, &(iwr->u), NULL);
} else {
char * extra;
int extra_size;
int user_length = 0;
int err;
int essid_compat = 0;
/* Calculate space needed by arguments. Always allocate
* for max space. Easier, and won't last long... */
extra_size = descr->max_tokens * descr->token_size;
/* Check need for ESSID compatibility for WE < 21 */
switch (cmd) {
case SIOCSIWESSID:
case SIOCGIWESSID:
case SIOCSIWNICKN:
case SIOCGIWNICKN:
if (iwr->u.data.length == descr->max_tokens + 1)
essid_compat = 1;
else if (IW_IS_SET(cmd) && (iwr->u.data.length != 0)) {
char essid[IW_ESSID_MAX_SIZE + 1];
err = copy_from_user(essid, iwr->u.data.pointer,
iwr->u.data.length *
descr->token_size);
if (err)
return -EFAULT;
if (essid[iwr->u.data.length - 1] == '\0')
essid_compat = 1;
}
break;
default:
break;
}
iwr->u.data.length -= essid_compat;
/* Check what user space is giving us */
if (IW_IS_SET(cmd)) {
/* Check NULL pointer */
if ((iwr->u.data.pointer == NULL) &&
(iwr->u.data.length != 0))
return -EFAULT;
/* Check if number of token fits within bounds */
if (iwr->u.data.length > descr->max_tokens)
return -E2BIG;
if (iwr->u.data.length < descr->min_tokens)
return -EINVAL;
} else {
/* Check NULL pointer */
if (iwr->u.data.pointer == NULL)
return -EFAULT;
/* Save user space buffer size for checking */
user_length = iwr->u.data.length;
/* Don't check if user_length > max to allow forward
* compatibility. The test user_length < min is
* implied by the test at the end. */
/* Support for very large requests */
if ((descr->flags & IW_DESCR_FLAG_NOMAX) &&
(user_length > descr->max_tokens)) {
/* Allow userspace to GET more than max so
* we can support any size GET requests.
* There is still a limit : -ENOMEM. */
extra_size = user_length * descr->token_size;
/* Note : user_length is originally a __u16,
* and token_size is controlled by us,
* so extra_size won't get negative and
* won't overflow... */
}
}
/* Create the kernel buffer */
/* kzalloc ensures NULL-termination for essid_compat */
extra = kzalloc(extra_size, GFP_KERNEL);
if (extra == NULL)
return -ENOMEM;
/* If it is a SET, get all the extra data in here */
if (IW_IS_SET(cmd) && (iwr->u.data.length != 0)) {
err = copy_from_user(extra, iwr->u.data.pointer,
iwr->u.data.length *
descr->token_size);
if (err) {
kfree(extra);
return -EFAULT;
}
}
/* Call the handler */
ret = handler(dev, &info, &(iwr->u), extra);
iwr->u.data.length += essid_compat;
/* If we have something to return to the user */
if (!ret && IW_IS_GET(cmd)) {
/* Check if there is enough buffer up there */
if (user_length < iwr->u.data.length) {
kfree(extra);
return -E2BIG;
}
err = copy_to_user(iwr->u.data.pointer, extra,
iwr->u.data.length *
descr->token_size);
if (err)
ret = -EFAULT;
}
/* Generate an event to notify listeners of the change */
if ((descr->flags & IW_DESCR_FLAG_EVENT) &&
((ret == 0) || (ret == -EIWCOMMIT))) {
if (descr->flags & IW_DESCR_FLAG_RESTRICT)
/* If the event is restricted, don't
* export the payload */
wireless_send_event(dev, cmd, &(iwr->u), NULL);
else
wireless_send_event(dev, cmd, &(iwr->u),
extra);
}
/* Cleanup - I told you it wasn't that long ;-) */
kfree(extra);
}
/* Call commit handler if needed and defined */
if (ret == -EIWCOMMIT)
ret = call_commit_handler(dev);
/* Here, we will generate the appropriate event if needed */
return ret;
}
/* ---------------------------------------------------------------- */
/*
* Wrapper to call a private Wireless Extension handler.
* We do various checks and also take care of moving data between
* user space and kernel space.
* It's not as nice and slimline as the standard wrapper. The cause
* is struct iw_priv_args, which was not really designed for the
* job we are going here.
*
* IMPORTANT : This function prevent to set and get data on the same
* IOCTL and enforce the SET/GET convention. Not doing it would be
* far too hairy...
* If you need to set and get data at the same time, please don't use
* a iw_handler but process it in your ioctl handler (i.e. use the
* old driver API).
*/
static int ioctl_private_call(struct net_device *dev, struct ifreq *ifr,
unsigned int cmd, iw_handler handler)
{
struct iwreq * iwr = (struct iwreq *) ifr;
const struct iw_priv_args * descr = NULL;
struct iw_request_info info;
int extra_size = 0;
int i;
int ret = -EINVAL;
/* Get the description of the IOCTL */
for (i = 0; i < dev->wireless_handlers->num_private_args; i++)
if (cmd == dev->wireless_handlers->private_args[i].cmd) {
descr = &(dev->wireless_handlers->private_args[i]);
break;
}
/* Compute the size of the set/get arguments */
if (descr != NULL) {
if (IW_IS_SET(cmd)) {
int offset = 0; /* For sub-ioctls */
/* Check for sub-ioctl handler */
if (descr->name[0] == '\0')
/* Reserve one int for sub-ioctl index */
offset = sizeof(__u32);
/* Size of set arguments */
extra_size = get_priv_size(descr->set_args);
/* Does it fits in iwr ? */
if ((descr->set_args & IW_PRIV_SIZE_FIXED) &&
((extra_size + offset) <= IFNAMSIZ))
extra_size = 0;
} else {
/* Size of get arguments */
extra_size = get_priv_size(descr->get_args);
/* Does it fits in iwr ? */
if ((descr->get_args & IW_PRIV_SIZE_FIXED) &&
(extra_size <= IFNAMSIZ))
extra_size = 0;
}
}
/* Prepare the call */
info.cmd = cmd;
info.flags = 0;
/* Check if we have a pointer to user space data or not. */
if (extra_size == 0) {
/* No extra arguments. Trivial to handle */
ret = handler(dev, &info, &(iwr->u), (char *) &(iwr->u));
} else {
char * extra;
int err;
/* Check what user space is giving us */
if (IW_IS_SET(cmd)) {
/* Check NULL pointer */
if ((iwr->u.data.pointer == NULL) &&
(iwr->u.data.length != 0))
return -EFAULT;
/* Does it fits within bounds ? */
if (iwr->u.data.length > (descr->set_args &
IW_PRIV_SIZE_MASK))
return -E2BIG;
} else if (iwr->u.data.pointer == NULL)
return -EFAULT;
/* Always allocate for max space. Easier, and won't last
* long... */
extra = kmalloc(extra_size, GFP_KERNEL);
if (extra == NULL)
return -ENOMEM;
/* If it is a SET, get all the extra data in here */
if (IW_IS_SET(cmd) && (iwr->u.data.length != 0)) {
err = copy_from_user(extra, iwr->u.data.pointer,
extra_size);
if (err) {
kfree(extra);
return -EFAULT;
}
}
/* Call the handler */
ret = handler(dev, &info, &(iwr->u), extra);
/* If we have something to return to the user */
if (!ret && IW_IS_GET(cmd)) {
/* Adjust for the actual length if it's variable,
* avoid leaking kernel bits outside. */
if (!(descr->get_args & IW_PRIV_SIZE_FIXED)) {
extra_size = adjust_priv_size(descr->get_args,
&(iwr->u));
}
err = copy_to_user(iwr->u.data.pointer, extra,
extra_size);
if (err)
ret = -EFAULT;
}
/* Cleanup - I told you it wasn't that long ;-) */
kfree(extra);
}
/* Call commit handler if needed and defined */
if (ret == -EIWCOMMIT)
ret = call_commit_handler(dev);
return ret;
}
/* ---------------------------------------------------------------- */
/*
* Main IOCTl dispatcher.
* Check the type of IOCTL and call the appropriate wrapper...
*/
static int wireless_process_ioctl(struct ifreq *ifr, unsigned int cmd)
{
struct net_device *dev;
iw_handler handler;
/* Permissions are already checked in dev_ioctl() before calling us.
* The copy_to/from_user() of ifr is also dealt with in there */
/* Make sure the device exist */
if ((dev = __dev_get_by_name(ifr->ifr_name)) == NULL)
return -ENODEV;
/* A bunch of special cases, then the generic case...
* Note that 'cmd' is already filtered in dev_ioctl() with
* (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST) */
if (cmd == SIOCGIWSTATS)
return ioctl_standard_call(dev, ifr, cmd,
&iw_handler_get_iwstats);
if (cmd == SIOCGIWPRIV && dev->wireless_handlers)
return ioctl_standard_call(dev, ifr, cmd,
&iw_handler_get_private);
/* Basic check */
if (!netif_device_present(dev))
return -ENODEV;
/* New driver API : try to find the handler */
handler = get_handler(dev, cmd);
if (handler) {
/* Standard and private are not the same */
if (cmd < SIOCIWFIRSTPRIV)
return ioctl_standard_call(dev, ifr, cmd, handler);
else
return ioctl_private_call(dev, ifr, cmd, handler);
}
/* Old driver API : call driver ioctl handler */
if (dev->do_ioctl)
return dev->do_ioctl(dev, ifr, cmd);
return -EOPNOTSUPP;
}
/* entry point from dev ioctl */
int wext_handle_ioctl(struct ifreq *ifr, unsigned int cmd,
void __user *arg)
{
int ret;
/* If command is `set a parameter', or
* `get the encoding parameters', check if
* the user has the right to do it */
if ((IW_IS_SET(cmd) || cmd == SIOCGIWENCODE || cmd == SIOCGIWENCODEEXT)
&& !capable(CAP_NET_ADMIN))
return -EPERM;
dev_load(ifr->ifr_name);
rtnl_lock();
ret = wireless_process_ioctl(ifr, cmd);
rtnl_unlock();
if (IW_IS_GET(cmd) && copy_to_user(arg, ifr, sizeof(struct ifreq)))
return -EFAULT;
return ret;
}
/************************* EVENT PROCESSING *************************/
/*
* Process events generated by the wireless layer or the driver.
* Most often, the event will be propagated through rtnetlink
*/
/* ---------------------------------------------------------------- */
/*
* Locking...
* ----------
*
* Thanks to Herbert Xu <herbert@gondor.apana.org.au> for fixing
* the locking issue in here and implementing this code !
*
* The issue : wireless_send_event() is often called in interrupt context,
* while the Netlink layer can never be called in interrupt context.
* The fully formed RtNetlink events are queued, and then a tasklet is run
* to feed those to Netlink.
* The skb_queue is interrupt safe, and its lock is not held while calling
* Netlink, so there is no possibility of dealock.
* Jean II
*/
static struct sk_buff_head wireless_nlevent_queue;
static int __init wireless_nlevent_init(void)
{
skb_queue_head_init(&wireless_nlevent_queue);
return 0;
}
subsys_initcall(wireless_nlevent_init);
static void wireless_nlevent_process(unsigned long data)
{
struct sk_buff *skb;
while ((skb = skb_dequeue(&wireless_nlevent_queue)))
rtnl_notify(skb, 0, RTNLGRP_LINK, NULL, GFP_ATOMIC);
}
static DECLARE_TASKLET(wireless_nlevent_tasklet, wireless_nlevent_process, 0);
/* ---------------------------------------------------------------- */
/*
* Fill a rtnetlink message with our event data.
* Note that we propage only the specified event and don't dump the
* current wireless config. Dumping the wireless config is far too
* expensive (for each parameter, the driver need to query the hardware).
*/
static int rtnetlink_fill_iwinfo(struct sk_buff *skb, struct net_device *dev,
int type, char *event, int event_len)
{
struct ifinfomsg *r;
struct nlmsghdr *nlh;
unsigned char *b = skb_tail_pointer(skb);
nlh = NLMSG_PUT(skb, 0, 0, type, sizeof(*r));
r = NLMSG_DATA(nlh);
r->ifi_family = AF_UNSPEC;
r->__ifi_pad = 0;
r->ifi_type = dev->type;
r->ifi_index = dev->ifindex;
r->ifi_flags = dev_get_flags(dev);
r->ifi_change = 0; /* Wireless changes don't affect those flags */
/* Add the wireless events in the netlink packet */
RTA_PUT(skb, IFLA_WIRELESS, event_len, event);
nlh->nlmsg_len = skb_tail_pointer(skb) - b;
return skb->len;
nlmsg_failure:
rtattr_failure:
nlmsg_trim(skb, b);
return -1;
}
/* ---------------------------------------------------------------- */
/*
* Create and broadcast and send it on the standard rtnetlink socket
* This is a pure clone rtmsg_ifinfo() in net/core/rtnetlink.c
* Andrzej Krzysztofowicz mandated that I used a IFLA_XXX field
* within a RTM_NEWLINK event.
*/
static void rtmsg_iwinfo(struct net_device *dev, char *event, int event_len)
{
struct sk_buff *skb;
int size = NLMSG_GOODSIZE;
skb = alloc_skb(size, GFP_ATOMIC);
if (!skb)
return;
if (rtnetlink_fill_iwinfo(skb, dev, RTM_NEWLINK,
event, event_len) < 0) {
kfree_skb(skb);
return;
}
NETLINK_CB(skb).dst_group = RTNLGRP_LINK;
skb_queue_tail(&wireless_nlevent_queue, skb);
tasklet_schedule(&wireless_nlevent_tasklet);
}
/* ---------------------------------------------------------------- */
/*
* Main event dispatcher. Called from other parts and drivers.
* Send the event on the appropriate channels.
* May be called from interrupt context.
*/
void wireless_send_event(struct net_device * dev,
unsigned int cmd,
union iwreq_data * wrqu,
char * extra)
{
const struct iw_ioctl_description * descr = NULL;
int extra_len = 0;
struct iw_event *event; /* Mallocated whole event */
int event_len; /* Its size */
int hdr_len; /* Size of the event header */
int wrqu_off = 0; /* Offset in wrqu */
/* Don't "optimise" the following variable, it will crash */
unsigned cmd_index; /* *MUST* be unsigned */
/* Get the description of the Event */
if (cmd <= SIOCIWLAST) {
cmd_index = cmd - SIOCIWFIRST;
if (cmd_index < standard_ioctl_num)
descr = &(standard_ioctl[cmd_index]);
} else {
cmd_index = cmd - IWEVFIRST;
if (cmd_index < standard_event_num)
descr = &(standard_event[cmd_index]);
}
/* Don't accept unknown events */
if (descr == NULL) {
/* Note : we don't return an error to the driver, because
* the driver would not know what to do about it. It can't
* return an error to the user, because the event is not
* initiated by a user request.
* The best the driver could do is to log an error message.
* We will do it ourselves instead...
*/
printk(KERN_ERR "%s (WE) : Invalid/Unknown Wireless Event (0x%04X)\n",
dev->name, cmd);
return;
}
/* Check extra parameters and set extra_len */
if (descr->header_type == IW_HEADER_TYPE_POINT) {
/* Check if number of token fits within bounds */
if (wrqu->data.length > descr->max_tokens) {
printk(KERN_ERR "%s (WE) : Wireless Event too big (%d)\n", dev->name, wrqu->data.length);
return;
}
if (wrqu->data.length < descr->min_tokens) {
printk(KERN_ERR "%s (WE) : Wireless Event too small (%d)\n", dev->name, wrqu->data.length);
return;
}
/* Calculate extra_len - extra is NULL for restricted events */
if (extra != NULL)
extra_len = wrqu->data.length * descr->token_size;
/* Always at an offset in wrqu */
wrqu_off = IW_EV_POINT_OFF;
}
/* Total length of the event */
hdr_len = event_type_size[descr->header_type];
event_len = hdr_len + extra_len;
/* Create temporary buffer to hold the event */
event = kmalloc(event_len, GFP_ATOMIC);
if (event == NULL)
return;
/* Fill event */
event->len = event_len;
event->cmd = cmd;
memcpy(&event->u, ((char *) wrqu) + wrqu_off, hdr_len - IW_EV_LCP_LEN);
if (extra)
memcpy(((char *) event) + hdr_len, extra, extra_len);
/* Send via the RtNetlink event channel */
rtmsg_iwinfo(dev, (char *) event, event_len);
/* Cleanup */
kfree(event);
return; /* Always success, I guess ;-) */
}
EXPORT_SYMBOL(wireless_send_event);
/********************** ENHANCED IWSPY SUPPORT **********************/
/*
* In the old days, the driver was handling spy support all by itself.
* Now, the driver can delegate this task to Wireless Extensions.
* It needs to use those standard spy iw_handler in struct iw_handler_def,
* push data to us via wireless_spy_update() and include struct iw_spy_data
* in its private part (and export it in net_device->wireless_data->spy_data).
* One of the main advantage of centralising spy support here is that
* it becomes much easier to improve and extend it without having to touch
* the drivers. One example is the addition of the Spy-Threshold events.
*/
/* ---------------------------------------------------------------- */
/*
* Return the pointer to the spy data in the driver.
* Because this is called on the Rx path via wireless_spy_update(),
* we want it to be efficient...
*/
static inline struct iw_spy_data *get_spydata(struct net_device *dev)
{
/* This is the new way */
if (dev->wireless_data)
return dev->wireless_data->spy_data;
return NULL;
}
/*------------------------------------------------------------------*/
/*
* Standard Wireless Handler : set Spy List
*/
int iw_handler_set_spy(struct net_device * dev,
struct iw_request_info * info,
union iwreq_data * wrqu,
char * extra)
{
struct iw_spy_data * spydata = get_spydata(dev);
struct sockaddr * address = (struct sockaddr *) extra;
/* Make sure driver is not buggy or using the old API */
if (!spydata)
return -EOPNOTSUPP;
/* Disable spy collection while we copy the addresses.
* While we copy addresses, any call to wireless_spy_update()
* will NOP. This is OK, as anyway the addresses are changing. */
spydata->spy_number = 0;
/* We want to operate without locking, because wireless_spy_update()
* most likely will happen in the interrupt handler, and therefore
* have its own locking constraints and needs performance.
* The rtnl_lock() make sure we don't race with the other iw_handlers.
* This make sure wireless_spy_update() "see" that the spy list
* is temporarily disabled. */
smp_wmb();
/* Are there are addresses to copy? */
if (wrqu->data.length > 0) {
int i;
/* Copy addresses */
for (i = 0; i < wrqu->data.length; i++)
memcpy(spydata->spy_address[i], address[i].sa_data,
ETH_ALEN);
/* Reset stats */
memset(spydata->spy_stat, 0,
sizeof(struct iw_quality) * IW_MAX_SPY);
}
/* Make sure above is updated before re-enabling */
smp_wmb();
/* Enable addresses */
spydata->spy_number = wrqu->data.length;
return 0;
}
EXPORT_SYMBOL(iw_handler_set_spy);
/*------------------------------------------------------------------*/
/*
* Standard Wireless Handler : get Spy List
*/
int iw_handler_get_spy(struct net_device * dev,
struct iw_request_info * info,
union iwreq_data * wrqu,
char * extra)
{
struct iw_spy_data * spydata = get_spydata(dev);
struct sockaddr * address = (struct sockaddr *) extra;
int i;
/* Make sure driver is not buggy or using the old API */
if (!spydata)
return -EOPNOTSUPP;
wrqu->data.length = spydata->spy_number;
/* Copy addresses. */
for (i = 0; i < spydata->spy_number; i++) {
memcpy(address[i].sa_data, spydata->spy_address[i], ETH_ALEN);
address[i].sa_family = AF_UNIX;
}
/* Copy stats to the user buffer (just after). */
if (spydata->spy_number > 0)
memcpy(extra + (sizeof(struct sockaddr) *spydata->spy_number),
spydata->spy_stat,
sizeof(struct iw_quality) * spydata->spy_number);
/* Reset updated flags. */
for (i = 0; i < spydata->spy_number; i++)
spydata->spy_stat[i].updated &= ~IW_QUAL_ALL_UPDATED;
return 0;
}
EXPORT_SYMBOL(iw_handler_get_spy);
/*------------------------------------------------------------------*/
/*
* Standard Wireless Handler : set spy threshold
*/
int iw_handler_set_thrspy(struct net_device * dev,
struct iw_request_info *info,
union iwreq_data * wrqu,
char * extra)
{
struct iw_spy_data * spydata = get_spydata(dev);
struct iw_thrspy * threshold = (struct iw_thrspy *) extra;
/* Make sure driver is not buggy or using the old API */
if (!spydata)
return -EOPNOTSUPP;
/* Just do it */
memcpy(&(spydata->spy_thr_low), &(threshold->low),
2 * sizeof(struct iw_quality));
/* Clear flag */
memset(spydata->spy_thr_under, '\0', sizeof(spydata->spy_thr_under));
return 0;
}
EXPORT_SYMBOL(iw_handler_set_thrspy);
/*------------------------------------------------------------------*/
/*
* Standard Wireless Handler : get spy threshold
*/
int iw_handler_get_thrspy(struct net_device * dev,
struct iw_request_info *info,
union iwreq_data * wrqu,
char * extra)
{
struct iw_spy_data * spydata = get_spydata(dev);
struct iw_thrspy * threshold = (struct iw_thrspy *) extra;
/* Make sure driver is not buggy or using the old API */
if (!spydata)
return -EOPNOTSUPP;
/* Just do it */
memcpy(&(threshold->low), &(spydata->spy_thr_low),
2 * sizeof(struct iw_quality));
return 0;
}
EXPORT_SYMBOL(iw_handler_get_thrspy);
/*------------------------------------------------------------------*/
/*
* Prepare and send a Spy Threshold event
*/
static void iw_send_thrspy_event(struct net_device * dev,
struct iw_spy_data * spydata,
unsigned char * address,
struct iw_quality * wstats)
{
union iwreq_data wrqu;
struct iw_thrspy threshold;
/* Init */
wrqu.data.length = 1;
wrqu.data.flags = 0;
/* Copy address */
memcpy(threshold.addr.sa_data, address, ETH_ALEN);
threshold.addr.sa_family = ARPHRD_ETHER;
/* Copy stats */
memcpy(&(threshold.qual), wstats, sizeof(struct iw_quality));
/* Copy also thresholds */
memcpy(&(threshold.low), &(spydata->spy_thr_low),
2 * sizeof(struct iw_quality));
/* Send event to user space */
wireless_send_event(dev, SIOCGIWTHRSPY, &wrqu, (char *) &threshold);
}
/* ---------------------------------------------------------------- */
/*
* Call for the driver to update the spy data.
* For now, the spy data is a simple array. As the size of the array is
* small, this is good enough. If we wanted to support larger number of
* spy addresses, we should use something more efficient...
*/
void wireless_spy_update(struct net_device * dev,
unsigned char * address,
struct iw_quality * wstats)
{
struct iw_spy_data * spydata = get_spydata(dev);
int i;
int match = -1;
/* Make sure driver is not buggy or using the old API */
if (!spydata)
return;
/* Update all records that match */
for (i = 0; i < spydata->spy_number; i++)
if (!compare_ether_addr(address, spydata->spy_address[i])) {
memcpy(&(spydata->spy_stat[i]), wstats,
sizeof(struct iw_quality));
match = i;
}
/* Generate an event if we cross the spy threshold.
* To avoid event storms, we have a simple hysteresis : we generate
* event only when we go under the low threshold or above the
* high threshold. */
if (match >= 0) {
if (spydata->spy_thr_under[match]) {
if (wstats->level > spydata->spy_thr_high.level) {
spydata->spy_thr_under[match] = 0;
iw_send_thrspy_event(dev, spydata,
address, wstats);
}
} else {
if (wstats->level < spydata->spy_thr_low.level) {
spydata->spy_thr_under[match] = 1;
iw_send_thrspy_event(dev, spydata,
address, wstats);
}
}
}
}
EXPORT_SYMBOL(wireless_spy_update);
| 30.049007 | 94 | 0.65251 | [
"3d"
] |
d6acfe9d944148653414888076e241ffe899e79d | 26,296 | h | C | BrotGen-Pert-AVX/Compute.h | Panjaksli/BrotGen | 83e62c982f0b209b2efae2b7d9019d3999c06a07 | [
"MIT"
] | 4 | 2021-06-08T06:51:00.000Z | 2021-06-14T17:00:56.000Z | BrotGen-Pert-AVX/Compute.h | Panjaksli/BrotGen | 83e62c982f0b209b2efae2b7d9019d3999c06a07 | [
"MIT"
] | null | null | null | BrotGen-Pert-AVX/Compute.h | Panjaksli/BrotGen | 83e62c982f0b209b2efae2b7d9019d3999c06a07 | [
"MIT"
] | null | null | null | #ifndef COMPUTE_H_INCLUDED
#define COMPUTE_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#include <SDL2/SDL.h>
#include <math.h>
#include <omp.h>
#include <time.h>
#include <immintrin.h>
#include "Grad.h"
__float128 dx[10000],dy[10000],x0,y01;
float Ax,Ay,Bx,By,Cx,Cy;
float A,B,C,Ai,Bi,Ci;
float dxl[10000],dyl[10000];
int apnum;
char setpoint=1;
inline static void Screenshot(__float128 m,__float128 ph,__float128 pv,int iter, int res,__float128 mcx,__float128 mcy)
{
char file[30];
int height=HEIGHT*res, width=WIDTH*res;
unsigned char *pixels = malloc(height*4*width),tcb,tcg,tcr;
__float128 prex=(width*(-0.5)+1.0*m*ph*res),prey=(height*(-0.5)-1.0*m*pv*res);
__m256 zx,zy,cx,cy,x,y,four,mask,sum;
__m256 xy,tx,tx1;
__m256 k,iterace,one;
int off,i,j,off1,l,off2,off3;
iterace=_mm256_set1_ps(iter);
one=_mm256_set1_ps(1.0);
four= _mm256_set1_ps(4.0);
__float128 invert=1.0/(360*m*res);
#pragma omp parallel for simd collapse (2) schedule(dynamic,100) shared(pixels,dx,dy,x0,y01,Ax,Ay,Bx,By,Cx,Cy) private(off,i,j,k,zx,zy,x,y,cy,cx,sum,mask,xy,tx,tx1,tcb,tcg,tcr)
for(i=4; i<height-4; i+=4)
{
for(j=4; j<width-4; j+=4)
{
off=4*(width*i+j);
off1=4*(width*(i+1)+j);
off2=4*(width*(i+2)+j);
off3=4*(width*(i+3)+j);
x=cx=_mm256_setr_ps(((j+prex)*invert-x0),((j+prex+1)*invert-x0),((j+prex+2)*invert-x0),((j+prex+3)*invert-x0),((j+prex)*invert-x0),((j+prex+1)*invert-x0),((j+prex+2)*invert-x0),((j+prex+3)*invert-x0));
y=cy=_mm256_setr_ps(((i+prey)*invert-y01),((i+prey+1)*invert-y01),((i+prey)*invert-y01),((i+prey+1)*invert-y01),((i+prey+2)*invert-y01),((i+prey+3)*invert-y01),((i+prey+2)*invert-y01),((i+prey+3)*invert-y01));
k=_mm256_setzero_ps();
l=0;
if(m>1e15&&apnum)
{
zx=_mm256_mul_ps(x,x);
zy=_mm256_mul_ps(y,y);
sum=_mm256_sub_ps(zx,zy);
xy=x*y;
tx=Ax*x-Ay*y+Bx*(sum)-2.0f*By*xy+Cx*x*(zx-3.0f*zy)+Cy*y*(zy-3.0f*zx);
y=Ax*y+Ay*x+2.0f*Bx*xy+By*(sum)+Cx*y*(3.0f*zx-zy)+Cy*x*(zx-3.0f*zy);
x=tx;
l=apnum;
k+=(float)apnum;
}
do
{
tx=_mm256_set1_ps(dxl[l]);
tx1=_mm256_set1_ps(dyl[l]);
zx=_mm256_mul_ps(x,x);
zy=_mm256_mul_ps(y,y);
sum=_mm256_add_ps(zy,zx);
xy=2.0f*(y*(x+tx)+x*tx1);
x=2.0f*(tx*x-tx1*y)+zx-zy+cx;
y=_mm256_add_ps(xy,cy);
mask= _mm256_cmp_ps(sum,four,_CMP_LT_OQ);
k=_mm256_add_ps(k,_mm256_and_ps(one,mask));
}
while(++l<iter&&_mm256_movemask_ps(mask));
k=_mm256_div_ps(k,iterace);k*=8000.0f;
tcb=pixels[off] = colb(k[0]);
tcg=pixels[off+1] = colg(k[0]);
tcr=pixels[off+2] = colr(k[0]);
pixels[off1+4] = colb(k[1]);
pixels[off1+5] = colg(k[1]);
pixels[off1+6] = colr(k[1]);
pixels[off+8] = colb(k[2]);
pixels[off+9] = colg(k[2]);
pixels[off+10] = colr(k[2]);
pixels[off1+12] = colb(k[3]);
pixels[off1+13] = colg(k[3]);
pixels[off1+14] = colr(k[3]);
pixels[off2] = colb(k[4]);
pixels[off2+1] = colg(k[4]);
pixels[off2+2] = colr(k[4]);
pixels[off3+4] = colb(k[5]);
pixels[off3+5] = colg(k[5]);
pixels[off3+6] = colr(k[5]);
pixels[off2+8] = colb(k[6]);
pixels[off2+9] = colg(k[6]);
pixels[off2+10] = colr(k[6]);
pixels[off3+12] = colb(k[7]);
pixels[off3+13] = colg(k[7]);
pixels[off3+14] = colr(k[7]);
if(tcb==pixels[off1+4]&&tcb==pixels[off+8]&&tcb==pixels[off1+12]&&tcb==pixels[off2]&&tcb==pixels[off3+4]&&tcb==pixels[off2+8]&&tcb==pixels[off3+12]&&
tcg==pixels[off1+5]&&tcg==pixels[off+9]&&tcg==pixels[off1+13]&&tcg==pixels[off2+1]&&tcg==pixels[off3+5]&&tcg==pixels[off2+9]&&tcg==pixels[off3+13]&&
tcr==pixels[off1+6]&&tcr==pixels[off+10]&&tcr==pixels[off1+14]&&tcr==pixels[off2+2]&&tcr==pixels[off3+6]&&tcr==pixels[off2+10]&&tcr==pixels[off3+14]){
pixels[off+4]=pixels[off+12]=pixels[off1]=pixels[off1+8]=pixels[off2+4]=pixels[off2+12]= pixels[off3]=pixels[off3+8]=tcb;
pixels[off+5]=pixels[off+13]=pixels[off1+1]=pixels[off1+9]=pixels[off2+5]=pixels[off2+13]= pixels[off3+1]=pixels[off3+9]=tcg;
pixels[off+6]=pixels[off+14]=pixels[off1+2]=pixels[off1+10]=pixels[off2+6]=pixels[off2+14]= pixels[off3+2]=pixels[off3+10]=tcr;
}
else{
x=cx;
y=cy=_mm256_setr_ps(((i+prey+1)*invert-y01),((i+prey)*invert-y01),((i+prey+1)*invert-y01),((i+prey)*invert-y01),((i+prey+3)*invert-y01),((i+prey+2)*invert-y01),((i+prey+3)*invert-y01),((i+prey+2)*invert-y01));
k=_mm256_setzero_ps();
l=0;
if(m>1e15&&apnum)
{
zx=_mm256_mul_ps(x,x);
zy=_mm256_mul_ps(y,y);
sum=_mm256_sub_ps(zx,zy);
xy=x*y;
tx=Ax*x-Ay*y+Bx*(sum)-2.0f*By*xy+Cx*x*(zx-3.0f*zy)+Cy*y*(zy-3.0f*zx);
y=Ax*y+Ay*x+2.0f*Bx*xy+By*(sum)+Cx*y*(3.0f*zx-zy)+Cy*x*(zx-3.0f*zy);
x=tx;
l=apnum;
k+=(float)apnum;
}
do
{
tx=_mm256_set1_ps(dxl[l]);
tx1=_mm256_set1_ps(dyl[l]);
zx=_mm256_mul_ps(x,x);
zy=_mm256_mul_ps(y,y);
sum=_mm256_add_ps(zy,zx);
xy=2.0f*(y*(x+tx)+x*tx1);
x=2.0f*(tx*x-tx1*y)+zx-zy+cx;
y=_mm256_add_ps(xy,cy);
mask= _mm256_cmp_ps(sum,four,_CMP_LT_OQ);
k=_mm256_add_ps(k,_mm256_and_ps(one,mask));
}
while(++l<iter&&_mm256_movemask_ps(mask));
k=_mm256_div_ps(k,iterace);k*=8000.0f;
pixels[off1] = colb(k[0]);
pixels[off1+1] = colg(k[0]);
pixels[off1+2] = colr(k[0]);
pixels[off+4] = colb(k[1]);
pixels[off+5] = colg(k[1]);
pixels[off+6] = colr(k[1]);
pixels[off1+8] = colb(k[2]);
pixels[off1+9] = colg(k[2]);
pixels[off1+10] = colr(k[2]);
pixels[off+12] = colb(k[3]);
pixels[off+13] = colg(k[3]);
pixels[off+14] = colr(k[3]);
pixels[off3] = colb(k[4]);
pixels[off3+1] = colg(k[4]);
pixels[off3+2] = colr(k[4]);
pixels[off2+4] = colb(k[5]);
pixels[off2+5] = colg(k[5]);
pixels[off2+6] = colr(k[5]);
pixels[off3+8] = colb(k[6]);
pixels[off3+9] = colg(k[6]);
pixels[off3+10] = colr(k[6]);
pixels[off2+12] = colb(k[7]);
pixels[off2+13] = colg(k[7]);
pixels[off2+14] = colr(k[7]);
}
}
}
SDL_Surface *surf = SDL_CreateRGBSurfaceFrom(pixels, width, height, 8*4, width*4, 0, 0, 0, 0);
sprintf_s(file,30,"images/%d.bmp",time(NULL));
SDL_SaveBMP(surf,file);
SDL_FreeSurface(surf);
free(pixels);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
inline static void Render(unsigned char *pixels,__float128 m,__float128 ph,__float128 pv,int iter,__float128 mcx,
__float128 mcy,char index,char index2,char index3)
{
__float128 prex=(m*ph-HWIDTH),prey=(-HHEIGHT-m*pv);
__float128 px,py;
__m256 zx,zy,cx,cy,x,y,four,mask,sum;
__m256 xy,tx,tx1;
__m256 k,iterace,one;
iterace=_mm256_set1_ps(iter);
one=_mm256_set1_ps(1.0f);
four= _mm256_set1_ps(4.0f);
__float128 invert=(1.0/(360.0*m));
int off,i,j,off1,l,f,off2,off3;
unsigned char tcb,tcr,tcg;
if(setpoint)
{
dx[0]=x0=mcx;
dy[0]=y01=mcy;
for(f=0; f<9999; f++)
{
px=dx[f]*dx[f];
py=dy[f]*dy[f];
dy[f+1]=2.0*dx[f]*dy[f]+y01;
dx[f+1]=px-py+x0;
}
#pragma omp parallel for simd
for(i=0; i<9999; i++)
{
dxl[i]=dx[i];
dyl[i]=dy[i];
}
Ax=1.0f;
Ay=Bx=By=Cx=Cy=0.0f;
apnum=0;
for(f=0; f<iter; f++)
{
C=2.0f*(dxl[f]*Cx-dyl[f]*Cy+Ax*Bx-Ay*By);
Ci=2.0f*(dyl[f]*Cx+dxl[f]*Cy+Ay*Bx+Ax*By);
B=2.0f*(dxl[f]*Bx-dyl[f]*By)+Ax*Ax-Ay*Ay;
Bi=2.0f*(dyl[f]*Bx+dxl[f]*By+Ax*Ay);
A=2.0f*(dxl[f]*Ax-dyl[f]*Ay)+1.0f;
Ai=2.0f*(dyl[f]*Ax+dxl[f]*Ay);
if(A>2e200||Ai>2e200||B>2e200||Bi>2e200||C>2e200||Ci>2e200)break;
if(A<-2e200||Ai<-2e200||B<-2e200||Bi<-2e200||C<-2e200||Ci<-2e200)break;
Cx=C;
Cy=Ci;
Bx=B;
By=Bi;
Ax=A;
Ay=Ai;
}
apnum=f;
printf("A %e %e B %e %e C %e %e Skipped: %d/%d\n",Ax,Ay,Bx,By,Cx,Cy,apnum,iter);
setpoint=0;
}
#pragma omp parallel for simd collapse (2) schedule(dynamic,100) shared(pixels,dx,dy,x0,y01,Ax,Ay,Bx,By,Cx,Cy) private(off,i,j,k,zx,zy,x,y,cy,cx,sum,mask,xy,tx,tx1,tcb,tcg,tcr)
for(i=4*index*index2+4; i<HEIGHT-4; i+=4*(1+index2))
{
for(j=(index*index2+index3)*4; j<WIDTH-4; j+=4+index2*4)
{
if(j<4)continue;
off = 4*WIDTH*i+(j<<2);
off1 = 4*WIDTH*(i+1)+(j<<2);
off2 = 4*WIDTH*(i+2)+(j<<2);
off3 = 4*WIDTH*(i+3)+(j<<2);
x=cx=_mm256_setr_ps(((j+prex)*invert-x0),((j+prex+1)*invert-x0),((j+prex+2)*invert-x0),((j+prex+3)*invert-x0),((j+prex)*invert-x0),((j+prex+1)*invert-x0),((j+prex+2)*invert-x0),((j+prex+3)*invert-x0));
y=cy=_mm256_setr_ps(((i+prey)*invert-y01),((i+prey+1)*invert-y01),((i+prey)*invert-y01),((i+prey+1)*invert-y01),((i+prey+2)*invert-y01),((i+prey+3)*invert-y01),((i+prey+2)*invert-y01),((i+prey+3)*invert-y01));
k=_mm256_setzero_ps();
l=0;
if(m>1e15&&apnum)
{
zx=_mm256_mul_ps(x,x);
zy=_mm256_mul_ps(y,y);
sum=_mm256_sub_ps(zx,zy);
xy=x*y;
tx=Ax*x-Ay*y+Bx*(sum)-2.0f*By*xy+Cx*x*(zx-3.0f*zy)+Cy*y*(zy-3.0f*zx);
y=Ax*y+Ay*x+2.0f*Bx*xy+By*(sum)+Cx*y*(3.0f*zx-zy)+Cy*x*(zx-3.0f*zy);
x=tx;
l=apnum;
k+=(float)apnum;
}
do
{
tx=_mm256_set1_ps(dxl[l]);
tx1=_mm256_set1_ps(dyl[l]);
zx=_mm256_mul_ps(x,x);
zy=_mm256_mul_ps(y,y);
sum=_mm256_add_ps(zy,zx);
xy=2.0f*(y*(x+tx)+x*tx1);
x=2.0f*(tx*x-tx1*y)+zx-zy+cx;
y=_mm256_add_ps(xy,cy);
mask= _mm256_cmp_ps(sum,four,_CMP_LT_OQ);
k=_mm256_add_ps(k,_mm256_and_ps(one,mask));
}
while(++l<iter&&_mm256_movemask_ps(mask));
k=_mm256_div_ps(k,iterace);k*=8000.0f;
tcb=pixels[off] = colb(k[0]);
tcg=pixels[off+1] = colg(k[0]);
tcr=pixels[off+2] = colr(k[0]);
pixels[off1+4] = colb(k[1]);
pixels[off1+5] = colg(k[1]);
pixels[off1+6] = colr(k[1]);
pixels[off+8] = colb(k[2]);
pixels[off+9] = colg(k[2]);
pixels[off+10] = colr(k[2]);
pixels[off1+12] = colb(k[3]);
pixels[off1+13] = colg(k[3]);
pixels[off1+14] = colr(k[3]);
pixels[off2] = colb(k[4]);
pixels[off2+1] = colg(k[4]);
pixels[off2+2] = colr(k[4]);
pixels[off3+4] = colb(k[5]);
pixels[off3+5] = colg(k[5]);
pixels[off3+6] = colr(k[5]);
pixels[off2+8] = colb(k[6]);
pixels[off2+9] = colg(k[6]);
pixels[off2+10] = colr(k[6]);
pixels[off3+12] = colb(k[7]);
pixels[off3+13] = colg(k[7]);
pixels[off3+14] = colr(k[7]);
if(tcb==pixels[off1+4]&&tcb==pixels[off+8]&&tcb==pixels[off1+12]&&tcb==pixels[off2]&&tcb==pixels[off3+4]&&tcb==pixels[off2+8]&&tcb==pixels[off3+12]&&
tcg==pixels[off1+5]&&tcg==pixels[off+9]&&tcg==pixels[off1+13]&&tcg==pixels[off2+1]&&tcg==pixels[off3+5]&&tcg==pixels[off2+9]&&tcg==pixels[off3+13]&&
tcr==pixels[off1+6]&&tcr==pixels[off+10]&&tcr==pixels[off1+14]&&tcr==pixels[off2+2]&&tcr==pixels[off3+6]&&tcr==pixels[off2+10]&&tcr==pixels[off3+14]){
pixels[off+4]=pixels[off+12]=pixels[off1]=pixels[off1+8]=pixels[off2+4]=pixels[off2+12]= pixels[off3]=pixels[off3+8]=tcb;
pixels[off+5]=pixels[off+13]=pixels[off1+1]=pixels[off1+9]=pixels[off2+5]=pixels[off2+13]= pixels[off3+1]=pixels[off3+9]=tcg;
pixels[off+6]=pixels[off+14]=pixels[off1+2]=pixels[off1+10]=pixels[off2+6]=pixels[off2+14]= pixels[off3+2]=pixels[off3+10]=tcr;
}
else{
x=cx;
y=cy=_mm256_setr_ps(((i+prey+1)*invert-y01),((i+prey)*invert-y01),((i+prey+1)*invert-y01),((i+prey)*invert-y01),((i+prey+3)*invert-y01),((i+prey+2)*invert-y01),((i+prey+3)*invert-y01),((i+prey+2)*invert-y01));
k=_mm256_setzero_ps();
l=0;
if(m>1e15&&apnum)
{
zx=_mm256_mul_ps(x,x);
zy=_mm256_mul_ps(y,y);
sum=_mm256_sub_ps(zx,zy);
xy=x*y;
tx=Ax*x-Ay*y+Bx*(sum)-2.0f*By*xy+Cx*x*(zx-3.0f*zy)+Cy*y*(zy-3.0f*zx);
y=Ax*y+Ay*x+2.0f*Bx*xy+By*(sum)+Cx*y*(3.0f*zx-zy)+Cy*x*(zx-3.0f*zy);
x=tx;
l=apnum;
k+=(float)apnum;
}
do
{
tx=_mm256_set1_ps(dxl[l]);
tx1=_mm256_set1_ps(dyl[l]);
zx=_mm256_mul_ps(x,x);
zy=_mm256_mul_ps(y,y);
sum=_mm256_add_ps(zy,zx);
xy=2.0f*(y*(x+tx)+x*tx1);
x=2.0f*(tx*x-tx1*y)+zx-zy+cx;
y=_mm256_add_ps(xy,cy);
mask= _mm256_cmp_ps(sum,four,_CMP_LT_OQ);
k=_mm256_add_ps(k,_mm256_and_ps(one,mask));
}
while(++l<iter&&_mm256_movemask_ps(mask));
k=_mm256_div_ps(k,iterace);k*=8000.0f;
pixels[off1] = colb(k[0]);
pixels[off1+1] = colg(k[0]);
pixels[off1+2] = colr(k[0]);
pixels[off+4] = colb(k[1]);
pixels[off+5] = colg(k[1]);
pixels[off+6] = colr(k[1]);
pixels[off1+8] = colb(k[2]);
pixels[off1+9] = colg(k[2]);
pixels[off1+10] = colr(k[2]);
pixels[off+12] = colb(k[3]);
pixels[off+13] = colg(k[3]);
pixels[off+14] = colr(k[3]);
pixels[off3] = colb(k[4]);
pixels[off3+1] = colg(k[4]);
pixels[off3+2] = colr(k[4]);
pixels[off2+4] = colb(k[5]);
pixels[off2+5] = colg(k[5]);
pixels[off2+6] = colr(k[5]);
pixels[off3+8] = colb(k[6]);
pixels[off3+9] = colg(k[6]);
pixels[off3+10] = colr(k[6]);
pixels[off2+12] = colb(k[7]);
pixels[off2+13] = colg(k[7]);
pixels[off2+14] = colr(k[7]);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
inline static void RenderCol(unsigned char *pixels,__float128 m,__float128 ph,__float128 pv,int iter,__float128 mcx,
__float128 mcy,char index,char index2,char index3)
{
__float128 prex=(m*ph-HWIDTH),prey=(-HHEIGHT-m*pv);
__float128 px,py;
__m256 zx,zy,cx,cy,x,y,four,mask,sum;
__m256 xy,tx,tx1;
__m256 k,iterace,one;
iterace=_mm256_set1_ps(iter);
one=_mm256_set1_ps(1.0f);
four= _mm256_set1_ps(4.0f);
__float128 invert=(1.0/(360.0*m));
int off,i,j,off1,l,f,off2,off3;
unsigned char tcb,tcr,tcg;
if(setpoint)
{
dx[0]=x0=mcx;
dy[0]=y01=mcy;
for(f=0; f<9999; f++)
{
px=dx[f]*dx[f];
py=dy[f]*dy[f];
dy[f+1]=2.0*dx[f]*dy[f]+y01;
dx[f+1]=px-py+x0;
}
#pragma omp parallel for simd
for(i=0; i<9999; i++)
{
dxl[i]=dx[i];
dyl[i]=dy[i];
}
Ax=1.0f;
Ay=Bx=By=Cx=Cy=0.0f;
apnum=0;
for(f=0; f<iter; f++)
{
C=2.0f*(dxl[f]*Cx-dyl[f]*Cy+Ax*Bx-Ay*By);
Ci=2.0f*(dyl[f]*Cx+dxl[f]*Cy+Ay*Bx+Ax*By);
B=2.0f*(dxl[f]*Bx-dyl[f]*By)+Ax*Ax-Ay*Ay;
Bi=2.0f*(dyl[f]*Bx+dxl[f]*By+Ax*Ay);
A=2.0f*(dxl[f]*Ax-dyl[f]*Ay)+1.0f;
Ai=2.0f*(dyl[f]*Ax+dxl[f]*Ay);
if(A>2e200||Ai>2e200||B>2e200||Bi>2e200||C>2e200||Ci>2e200)break;
if(A<-2e200||Ai<-2e200||B<-2e200||Bi<-2e200||C<-2e200||Ci<-2e200)break;
Cx=C;
Cy=Ci;
Bx=B;
By=Bi;
Ax=A;
Ay=Ai;
}
apnum=f;
printf("A %e %e B %e %e C %e %e Skipped: %d/%d\n",Ax,Ay,Bx,By,Cx,Cy,apnum,iter);
setpoint=0;
}
#pragma omp parallel for simd collapse (2) schedule(dynamic,100) shared(pixels,dx,dy,x0,y01,Ax,Ay,Bx,By,Cx,Cy) private(off,i,j,k,zx,zy,x,y,cy,cx,sum,mask,xy,tx,tx1,tcb,tcg,tcr)
for(i=4*index*index2+4; i<HEIGHT-4; i+=4*(1+index2))
{
for(j=(index*index2+index3)*4+2*WIDTH/5-4; j<WIDTH-4; j+=4+index2*4)
{
if(j<2*WIDTH/5)continue;
off = 4*WIDTH*i+(j<<2);
off1 = 4*WIDTH*(i+1)+(j<<2);
off2 = 4*WIDTH*(i+2)+(j<<2);
off3 = 4*WIDTH*(i+3)+(j<<2);
x=cx=_mm256_setr_ps(((j+prex)*invert-x0),((j+prex+1)*invert-x0),((j+prex+2)*invert-x0),((j+prex+3)*invert-x0),((j+prex)*invert-x0),((j+prex+1)*invert-x0),((j+prex+2)*invert-x0),((j+prex+3)*invert-x0));
y=cy=_mm256_setr_ps(((i+prey)*invert-y01),((i+prey+1)*invert-y01),((i+prey)*invert-y01),((i+prey+1)*invert-y01),((i+prey+2)*invert-y01),((i+prey+3)*invert-y01),((i+prey+2)*invert-y01),((i+prey+3)*invert-y01));
k=_mm256_setzero_ps();
l=0;
if(m>1e15&&apnum)
{
zx=_mm256_mul_ps(x,x);
zy=_mm256_mul_ps(y,y);
sum=_mm256_sub_ps(zx,zy);
xy=x*y;
tx=Ax*x-Ay*y+Bx*(sum)-2.0f*By*xy+Cx*x*(zx-3.0f*zy)+Cy*y*(zy-3.0f*zx);
y=Ax*y+Ay*x+2.0f*Bx*xy+By*(sum)+Cx*y*(3.0f*zx-zy)+Cy*x*(zx-3.0f*zy);
x=tx;
l=apnum;
k+=(float)apnum;
}
do
{
tx=_mm256_set1_ps(dxl[l]);
tx1=_mm256_set1_ps(dyl[l]);
zx=_mm256_mul_ps(x,x);
zy=_mm256_mul_ps(y,y);
sum=_mm256_add_ps(zy,zx);
xy=2.0f*(y*(x+tx)+x*tx1);
x=2.0f*(tx*x-tx1*y)+zx-zy+cx;
y=_mm256_add_ps(xy,cy);
mask= _mm256_cmp_ps(sum,four,_CMP_LT_OQ);
k=_mm256_add_ps(k,_mm256_and_ps(one,mask));
}
while(++l<iter&&_mm256_movemask_ps(mask));
k=_mm256_div_ps(k,iterace);k*=8000.0f;
tcb=pixels[off] = colb(k[0]);
tcg=pixels[off+1] = colg(k[0]);
tcr=pixels[off+2] = colr(k[0]);
pixels[off1+4] = colb(k[1]);
pixels[off1+5] = colg(k[1]);
pixels[off1+6] = colr(k[1]);
pixels[off+8] = colb(k[2]);
pixels[off+9] = colg(k[2]);
pixels[off+10] = colr(k[2]);
pixels[off1+12] = colb(k[3]);
pixels[off1+13] = colg(k[3]);
pixels[off1+14] = colr(k[3]);
pixels[off2] = colb(k[4]);
pixels[off2+1] = colg(k[4]);
pixels[off2+2] = colr(k[4]);
pixels[off3+4] = colb(k[5]);
pixels[off3+5] = colg(k[5]);
pixels[off3+6] = colr(k[5]);
pixels[off2+8] = colb(k[6]);
pixels[off2+9] = colg(k[6]);
pixels[off2+10] = colr(k[6]);
pixels[off3+12] = colb(k[7]);
pixels[off3+13] = colg(k[7]);
pixels[off3+14] = colr(k[7]);
if(tcb==pixels[off1+4]&&tcb==pixels[off+8]&&tcb==pixels[off1+12]&&tcb==pixels[off2]&&tcb==pixels[off3+4]&&tcb==pixels[off2+8]&&tcb==pixels[off3+12]&&
tcg==pixels[off1+5]&&tcg==pixels[off+9]&&tcg==pixels[off1+13]&&tcg==pixels[off2+1]&&tcg==pixels[off3+5]&&tcg==pixels[off2+9]&&tcg==pixels[off3+13]&&
tcr==pixels[off1+6]&&tcr==pixels[off+10]&&tcr==pixels[off1+14]&&tcr==pixels[off2+2]&&tcr==pixels[off3+6]&&tcr==pixels[off2+10]&&tcr==pixels[off3+14]){
pixels[off+4]=pixels[off+12]=pixels[off1]=pixels[off1+8]=pixels[off2+4]=pixels[off2+12]= pixels[off3]=pixels[off3+8]=tcb;
pixels[off+5]=pixels[off+13]=pixels[off1+1]=pixels[off1+9]=pixels[off2+5]=pixels[off2+13]= pixels[off3+1]=pixels[off3+9]=tcg;
pixels[off+6]=pixels[off+14]=pixels[off1+2]=pixels[off1+10]=pixels[off2+6]=pixels[off2+14]= pixels[off3+2]=pixels[off3+10]=tcr;
}
else{
x=cx;
y=cy=_mm256_setr_ps(((i+prey+1)*invert-y01),((i+prey)*invert-y01),((i+prey+1)*invert-y01),((i+prey)*invert-y01),((i+prey+3)*invert-y01),((i+prey+2)*invert-y01),((i+prey+3)*invert-y01),((i+prey+2)*invert-y01));
k=_mm256_setzero_ps();
l=0;
if(m>1e15&&apnum)
{
zx=_mm256_mul_ps(x,x);
zy=_mm256_mul_ps(y,y);
sum=_mm256_sub_ps(zx,zy);
xy=x*y;
tx=Ax*x-Ay*y+Bx*(sum)-2.0f*By*xy+Cx*x*(zx-3.0f*zy)+Cy*y*(zy-3.0f*zx);
y=Ax*y+Ay*x+2.0f*Bx*xy+By*(sum)+Cx*y*(3.0f*zx-zy)+Cy*x*(zx-3.0f*zy);
x=tx;
l=apnum;
k+=(float)apnum;
}
do
{
tx=_mm256_set1_ps(dxl[l]);
tx1=_mm256_set1_ps(dyl[l]);
zx=_mm256_mul_ps(x,x);
zy=_mm256_mul_ps(y,y);
sum=_mm256_add_ps(zy,zx);
xy=2.0f*(y*(x+tx)+x*tx1);
x=2.0f*(tx*x-tx1*y)+zx-zy+cx;
y=_mm256_add_ps(xy,cy);
mask= _mm256_cmp_ps(sum,four,_CMP_LT_OQ);
k=_mm256_add_ps(k,_mm256_and_ps(one,mask));
}
while(++l<iter&&_mm256_movemask_ps(mask));
k=_mm256_div_ps(k,iterace);k*=8000.0f;
pixels[off1] = colb(k[0]);
pixels[off1+1] = colg(k[0]);
pixels[off1+2] = colr(k[0]);
pixels[off+4] = colb(k[1]);
pixels[off+5] = colg(k[1]);
pixels[off+6] = colr(k[1]);
pixels[off1+8] = colb(k[2]);
pixels[off1+9] = colg(k[2]);
pixels[off1+10] = colr(k[2]);
pixels[off+12] = colb(k[3]);
pixels[off+13] = colg(k[3]);
pixels[off+14] = colr(k[3]);
pixels[off3] = colb(k[4]);
pixels[off3+1] = colg(k[4]);
pixels[off3+2] = colr(k[4]);
pixels[off2+4] = colb(k[5]);
pixels[off2+5] = colg(k[5]);
pixels[off2+6] = colr(k[5]);
pixels[off3+8] = colb(k[6]);
pixels[off3+9] = colg(k[6]);
pixels[off3+10] = colr(k[6]);
pixels[off2+12] = colb(k[7]);
pixels[off2+13] = colg(k[7]);
pixels[off2+14] = colr(k[7]);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
#endif // COMPUTE_H_INCLUDED
| 47.551537 | 222 | 0.436188 | [
"render"
] |
d6af18897779eb6266a343f06fb6e3cc87650798 | 1,202 | h | C | GTE/Graphics/TransformController.h | lakinwecker/GeometricTools | cff3e3fcb52d714afe0b6789839c460437c10b27 | [
"BSL-1.0"
] | null | null | null | GTE/Graphics/TransformController.h | lakinwecker/GeometricTools | cff3e3fcb52d714afe0b6789839c460437c10b27 | [
"BSL-1.0"
] | 1 | 2022-03-18T00:34:13.000Z | 2022-03-18T00:34:13.000Z | GTE/Graphics/TransformController.h | lakinwecker/GeometricTools | cff3e3fcb52d714afe0b6789839c460437c10b27 | [
"BSL-1.0"
] | 1 | 2022-03-17T21:54:55.000Z | 2022-03-17T21:54:55.000Z | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2022
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
// https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// Version: 6.0.2022.01.06
#pragma once
#include <Graphics/Controller.h>
#include <Mathematics/Transform.h>
namespace gte
{
class TransformController : public Controller
{
public:
TransformController(Transform<float> const& localTransform);
// Member access.
inline void SetTransform(Transform<float> const& localTransform)
{
mLocalTransform = localTransform;
}
inline Transform<float> const& GetTransform() const
{
return mLocalTransform;
}
// The animation update. The application time is in milliseconds.
// The update simply copies mLocalTransform to the Spatial mObject's
// LocalTransform. In this sense, TransformController represents a
// transform that is constant for all time.
virtual bool Update(double applicationTime) override;
protected:
Transform<float> mLocalTransform;
};
}
| 29.317073 | 76 | 0.678869 | [
"transform"
] |
d6b065ce6911dc8924718b86d4f74e005d4a5d9e | 6,343 | h | C | xinu/cross_compiler/arm-none-eabi/include/cs3.h | rrjha/dosp | 21f3624abfec815434007f76504488896a091f6d | [
"BSD-3-Clause"
] | 2 | 2022-02-04T15:49:22.000Z | 2022-02-05T13:38:43.000Z | xinu/cross_compiler/arm-none-eabi/include/cs3.h | rrjha/dosp | 21f3624abfec815434007f76504488896a091f6d | [
"BSD-3-Clause"
] | 1 | 2017-06-14T23:36:20.000Z | 2017-06-14T23:36:29.000Z | xinu/cross_compiler/arm-none-eabi/include/cs3.h | rrjha/dosp | 21f3624abfec815434007f76504488896a091f6d | [
"BSD-3-Clause"
] | null | null | null | /* This file is part of the CodeSourcery Common Startup Code Sequence (CS3).
Copyright (c) 2007 - 2011 CodeSourcery, Inc.
* Version:Sourcery CodeBench Lite 2013.11-24
* BugURL:https://sourcery.mentor.com/GNUToolchain/
THIS FILE CONTAINS PROPRIETARY, CONFIDENTIAL, AND TRADE SECRET
INFORMATION OF CODESOURCERY AND/OR ITS LICENSORS.
You may not use, modify or distribute this file without the express
written permission of CodeSourcery or its authorized
distributor. Please consult your license agreement for the
applicable terms and conditions. */
#ifndef CSL_CS3_H
#define CSL_CS3_H
#include <stddef.h>
#if __cplusplus
extern "C" {
#endif
/* The __cs3_regions array is used by CS3's startup code to initialize
the contents of memory regions during the C initialization phase.
For each region descriptor __cs3_regions[i], __cs3_regions[i].init_size
bytes beginning at __cs3_regions[i].data are initialized by copying from
__cs3_regions[i].init. (E.g., the data field is the VMA and the init
field is the LMA.) Then the following __cs3_regions[i].zero_size bytes
are zero-initialized.
__cs3_regions is normally defined in the linker script. */
typedef unsigned char __cs3_byte_align8 __attribute ((aligned (8)));
struct __cs3_region
{
unsigned long flags; /* Flags for this region. None defined yet. */
__cs3_byte_align8 *init; /* Initial contents of this region. */
__cs3_byte_align8 *data; /* Start address of region. */
size_t init_size; /* Size of initial data. */
size_t zero_size; /* Additional size to be zeroed. */
};
extern const struct __cs3_region __cs3_regions[];
/* The number of elements in __cs3_regions. This is weak, so the
compiler does not presume it is non-zero. */
extern const char __cs3_region_num __attribute__((weak));
#define __cs3_region_num ((size_t)&__cs3_region_num)
/* __cs3_start_c is the entry point to the C initialization phase.
CS3's library provides a default implementation, but it is possible
for user code to override it by defining this function. */
extern void __cs3_start_c (void) __attribute ((noreturn));
/* Space for the heap is designated by the array __cs3_heap_start.
__cs3_heap_limit points at the end of the heap.
CS3 provides default definitions for __cs3_heap_start and
__cs3_heap_end in the linker scripts (typically placed after the
.data and .bss sections in RAM), and a default definition for
__cs3_heap_limit pointing to __cs3_heap_end in the CS3 library.
As a special case, in some profiles &__cs3_heap_end may be zero to
indicate that the end of the heap must be determined some other way,
such as by a supervisory operation on a simulator, or simply by
treating the stack pointer as the limit.
User programs may override these default definitions either by using
a custom linker script, or by defining __cs3_heap_start and
__cs3_heap_limit appropriately from C. */
extern unsigned char __cs3_heap_start[] __attribute ((aligned (8)));
extern unsigned char __cs3_heap_end[] __attribute ((aligned (8)));
extern void *__cs3_heap_limit;
/* The default initial stack pointer. This is normally defined by the
linker script except in profiles where the stack pointer is
initialized externally, e.g. by a simulator or boot monitor.
Refer to the documentation for the Assembly Initialization Phase and Heap
and Stack Placement. */
extern unsigned char __cs3_stack[] __attribute ((aligned (16)));
/* The macro CS3_STACK can be used for creating a custom stack. Refer to the
documentation for Heap and Stack Placement. */
#define CS3_STACK(size) \
CS3_STACK_SYMBOL(__cs3_stack_block, (size), 16)
/* Create a custom stack with name SYMBOL, aligned to ALIGNMENT bytes, sized by
SIZE bytes, but possibly shortened such that the initial stack pointer
(symbol __cs3_stack) that points to the block's last extent is aligned to
ALIGNMENT bytes, too. */
#define CS3_STACK_SYMBOL(symbol, size, alignment) \
static char __attribute__ ((aligned (alignment))) \
symbol[(size - ((size) % (alignment)))]; \
asm (".global __cs3_stack"); \
asm ("__cs3_stack = " #symbol " + (" #size ") - (" #alignment ")" \
" - ((" #size ") % (" #alignment "))")
/* Regions. Some may not be present on particular boards or profiles. */
/* We use weak on objects that might be at address zero.
The compiler is at liberty to presume that no non-weak
object resides at address zero (because that's
indistinguishable from the NULL pointer on the systems
we care about). */
/* itcm region */
extern unsigned char __cs3_region_start_itcm[] __attribute__((weak,aligned(8)));
extern unsigned char __cs3_region_size_itcm[] __attribute__((aligned(8)));
extern const unsigned char __cs3_region_init_itcm[] __attribute__((weak,aligned(8)));
extern const char __cs3_region_init_size_itcm __attribute__((weak,aligned(8)));
#define __cs3_region_init_size_itcm ((size_t)&__cs3_region_init_size_itcm)
extern const char __cs3_region_zero_size_itcm __attribute__((weak,aligned(8)));
#define __cs3_region_zero_size_itcm ((size_t)&__cs3_region_zero_size_itcm)
/* ram region */
extern unsigned char __cs3_region_start_ram[] __attribute__((weak,aligned(8)));
extern unsigned char __cs3_region_size_ram[] __attribute__((aligned(8)));
extern const unsigned char __cs3_region_init_ram[] __attribute__((weak,aligned(8)));
extern const char __cs3_region_init_size_ram __attribute__((weak,aligned(8)));
#define __cs3_region_init_size_ram ((size_t)&__cs3_region_init_size_ram)
extern const char __cs3_region_zero_size_ram __attribute__((weak,aligned(8)));
#define __cs3_region_zero_size_ram ((size_t)&__cs3_region_zero_size_ram)
/* rom region */
extern unsigned char __cs3_region_start_rom[] __attribute__((weak,aligned(8)));
extern unsigned char __cs3_region_size_rom[] __attribute__((aligned(8)));
extern const unsigned char __cs3_region_init_rom[] __attribute__((weak,aligned(8)));
extern const char __cs3_region_init_size_rom __attribute__((weak,aligned(8)));
#define __cs3_region_init_size_rom ((size_t)&__cs3_region_init_size_rom)
extern const char __cs3_region_zero_size_rom __attribute__((weak,aligned(8)));
#define __cs3_region_zero_size_rom ((size_t)&__cs3_region_zero_size_rom)
#if __cplusplus
}
#endif
#endif /* CSL_CS3_H */
| 44.985816 | 85 | 0.764149 | [
"object"
] |
d6b2515aa1b6d86a9583f5d8eea74e50d0e476dd | 13,851 | c | C | Library/src/HTFilter.c | bldcm/Libwww | ba230049bbf6246f9c055ddf9c1526fe98ae9a4f | [
"W3C-19980720"
] | null | null | null | Library/src/HTFilter.c | bldcm/Libwww | ba230049bbf6246f9c055ddf9c1526fe98ae9a4f | [
"W3C-19980720"
] | null | null | null | Library/src/HTFilter.c | bldcm/Libwww | ba230049bbf6246f9c055ddf9c1526fe98ae9a4f | [
"W3C-19980720"
] | null | null | null | /*
** BEFORE AND AFTER FILTERS
**
** (c) COPYRIGHT MIT 1995.
** Please first read the full copyright statement in the file COPYRIGH.
** @(#) $Id: HTFilter.c,v 2.38 1999/03/31 00:53:31 frystyk Exp $
**
** This module implrments a set of default filters that can be registerd
** as BEFORE and AFTER filters to the Net manager
** Authors
** HFN Henrik Frystyk, frystyk@w.org
** History
** Jul 4, 96 Written
*/
/* Library include files */
#include "WWWLib.h"
#include "WWWCache.h"
#include "WWWHTTP.h"
#include "HTLog.h"
#include "HTAccess.h"
#include "HTProxy.h"
#include "HTRules.h"
#include "HTFilter.h" /* Implemented here */
/* ------------------------------------------------------------------------- */
/*
** Proxy and Gateway BEFORE filter
** -------------------------------
** Checks for registerd proxy servers or gateways and sees whether this
** request should be redirected to a proxy or a gateway. Proxies have
** higher priority than gateways so we look for them first!
** For HTTP/1.0 and HTTP/1.1 we may only send a full URL (including the
** host portion) to proxy servers. Therefore, we tell the Library whether
** to use the full URL or the traditional HTTP one without the host part.
*/
PUBLIC int HTProxyFilter (HTRequest * request, void * param, int mode)
{
HTParentAnchor * anchor = HTRequest_anchor(request);
char * addr = HTAnchor_physical(anchor);
char * physical = NULL;
if ((physical = HTProxy_find(addr))) {
HTRequest_setFullURI(request, YES); /* For now */
HTRequest_setProxy(request, physical);
HT_FREE(physical);
#if 0
/* Don't paste the URLs together anymore */
StrAllocCat(physical, addr);
HTAnchor_setPhysical(anchor, physical);
#endif
} else if ((physical = HTGateway_find(addr))) {
/*
** A gateway URL is crated by chopping off any leading "/" to make the
** host into part of path
*/
char * path =
HTParse(addr, "", PARSE_HOST + PARSE_PATH + PARSE_PUNCTUATION);
char * gatewayed = HTParse((*path=='/') ? path+1 : path, physical, PARSE_ALL);
HTAnchor_setPhysical(anchor, gatewayed);
HT_FREE(path);
HT_FREE(gatewayed);
HTRequest_setFullURI(request, NO);
HTRequest_deleteProxy(request);
} else {
HTRequest_setFullURI(request, NO); /* For now */
HTRequest_deleteProxy(request);
}
return HT_OK;
}
/*
** Rule Translation BEFORE Filter
** ------------------------------
** If we have a set of rules loaded (see the Rule manager) then check
** before each request whether how that should be translated. The trick
** is that a parent anchor has a "address" which is the part from the URL
** we used when we created the anchor. However, it also have a "physical
** address" which is the place we are actually going to look for the
** resource. Hence this filter translates the physical address
** (if any translations are found)
*/
PUBLIC int HTRuleFilter (HTRequest * request, void * param, int mode)
{
HTList * list = HTRule_global();
HTParentAnchor * anchor = HTRequest_anchor(request);
char * addr = HTAnchor_physical(anchor);
char * physical = HTRule_translate(list, addr, NO);
if (!physical) {
HTRequest_addError(request, ERR_FATAL, NO, HTERR_FORBIDDEN,
NULL, 0, "HTRuleFilter");
return HT_ERROR;
}
HTAnchor_setPhysical(anchor, physical);
HT_FREE(physical);
return HT_OK;
}
/*
** Check the Memory Cache (History list) BEFORE filter
** ---------------------------------------------------
** Check if document is already loaded. The user can define whether
** the history list should follow normal expiration or work as a
** traditional history list where expired documents are not updated.
** We don't check for anything but existence proof of a document
** associated with the anchor as the definition is left to the application
*/
PUBLIC int HTMemoryCacheFilter (HTRequest * request, void * param, int mode)
{
HTReload validation = HTRequest_reloadMode(request);
HTParentAnchor * anchor = HTRequest_anchor(request);
void * document = HTAnchor_document(anchor);
/*
** We only check the memory cache if it's a GET method
*/
if (HTRequest_method(request) != METHOD_GET) {
HTTRACE(CACHE_TRACE, "Mem Cache... We only check GET methods\n");
return HT_OK;
}
/*
** If we are asked to flush the persistent cache then there is no reason
** to do anything here - we're flushing it anyway. Also if no document
** then just exit from this filter.
*/
if (!document || validation > HT_CACHE_FLUSH_MEM) {
HTTRACE(CACHE_TRACE, "Mem Cache... No fresh document...\n");
return HT_OK;
}
/*
** If we have a document object associated with this anchor then we also
** have the object in the history list. Depending on what the user asked,
** we can add a cache validator
*/
if (document && validation != HT_CACHE_FLUSH_MEM) {
HTTRACE(CACHE_TRACE, "Mem Cache... Document already in memory\n");
return HT_LOADED;
}
return HT_OK;
}
/*
** Error and Information AFTER filter
** ----------------------------------
** It checks the status code from a request and generates an
** error/information message if required.
*/
PUBLIC int HTInfoFilter (HTRequest * request, HTResponse * response,
void * param, int status)
{
HTParentAnchor * anchor = HTRequest_anchor(request);
char * uri = HTAnchor_address((HTAnchor*) anchor);
switch (status) {
case HT_RETRY: {
HTAlertCallback *cbf = HTAlert_find(HT_A_MESSAGE);
if (cbf) (*cbf)(request, HT_A_MESSAGE, HT_MSG_NULL, NULL,
HTRequest_error(request), NULL);
HTTRACE(PROT_TRACE, "Load End.... NOT AVAILABLE, RETRY AT %ld\n" _
HTResponse_retryTime(response));
}
break;
case HT_NO_DATA:
{
/*
** The document was empty
*/
HTAlertCallback *cbf = HTAlert_find(HT_A_MESSAGE);
if (cbf) (*cbf)(request, HT_A_MESSAGE, HT_MSG_NULL, NULL,
HTRequest_error(request), NULL);
HTTRACE(PROT_TRACE, "Load End.... EMPTY: No content `%s\'\n" _
uri ? uri : "<UNKNOWN>");
break;
}
case HT_LOADED:
HTTRACE(PROT_TRACE, "Load End.... OK: `%s\'\n" _ uri);
break;
default:
{
/*
** See if we have a function registered for outputting errors.
** If so then call it and present the message to the user
*/
HTAlertCallback *cbf = HTAlert_find(HT_A_MESSAGE);
if (cbf) (*cbf)(request, HT_A_MESSAGE, HT_MSG_NULL, NULL,
HTRequest_error(request), NULL);
HTTRACE(PROT_TRACE, "Load End.... Request ended with code %d\n" _ status);
break;
}
}
HT_FREE(uri);
return HT_OK;
}
/*
** Redirection AFTER filter
** ------------------------
** The redirection handler only handles redirections
** on the GET or HEAD method (or any other safe method)
*/
PUBLIC int HTRedirectFilter (HTRequest * request, HTResponse * response,
void * param, int status)
{
HTMethod method = HTRequest_method(request);
HTAnchor * new_anchor = HTResponse_redirection(response);
/* Check for destination */
if (!new_anchor) {
HTTRACE(PROT_TRACE, "Redirection. No destination\n");
return HT_OK;
}
/*
** Only do automatic redirect on GET and HEAD. Ask for all
** other methods.
*/
if (!HTMethod_isSafe(method)) {
/*
** If we got a 303 See Other then change the method to GET.
** Otherwise ask the user whether we should continue.
*/
if (status == HT_SEE_OTHER) {
HTTRACE(PROT_TRACE, "Redirection. Changing method from %s to GET\n" _
HTMethod_name(method));
HTRequest_setMethod(request, METHOD_GET);
} else {
HTAlertCallback * prompt = HTAlert_find(HT_A_CONFIRM);
if (prompt) {
if ((*prompt)(request, HT_A_CONFIRM, HT_MSG_REDIRECTION,
NULL, NULL, NULL) != YES)
return HT_OK;
}
}
}
/* Register the redirection as a link relationship */
{
HTLinkType ltype = status==HT_PERM_REDIRECT ? HT_LR_PERM_REDIRECT :
(status==HT_TEMP_REDIRECT || status==HT_FOUND) ? HT_LR_TEMP_REDIRECT :
status==HT_SEE_OTHER ? HT_LR_SEE_OTHER : NULL;
if (ltype) {
HTLink_add((HTAnchor *) HTRequest_anchor(request), new_anchor,
ltype, method);
}
}
/* Delete any auth credendials as they get regenerated */
HTRequest_deleteCredentialsAll(request);
/*
** Start new request with the redirect anchor found in the headers.
** Note that we reuse the same request object which means that we must
** keep this around until the redirected request has terminated. It also
** allows us in an easy way to keep track of the number of redirections
** so that we can detect endless loops.
*/
if (HTRequest_doRetry(request)) {
HTLoadAnchor(new_anchor, request);
} else {
HTRequest_addError(request, ERR_FATAL, NO, HTERR_MAX_REDIRECT,
NULL, 0, "HTRedirectFilter");
return HT_OK; /* Wanna fall through */
}
/*
** By returning HT_ERROR we make sure that this is the last handler to be
** called. We do this as we don't want any other filter to delete the
** request object now when we have just started a new one ourselves
*/
return HT_ERROR;
}
/*
** Retry through Proxy AFTER Filter
** --------------------------------
** This filter handles a 305 Use Proxy response and retries the request
** through the proxy
*/
PUBLIC int HTUseProxyFilter (HTRequest * request, HTResponse * response,
void * param, int status)
{
HTAlertCallback * cbf = HTAlert_find(HT_A_CONFIRM);
HTAnchor * proxy_anchor = HTResponse_redirection(response);
if (!proxy_anchor) {
HTTRACE(PROT_TRACE, "Use Proxy... No proxy location\n");
return HT_OK;
}
/*
** Add the proxy to the list. Assume HTTP access method only!
** Because evil servers may rediret the client to an untrusted
** proxy, we can only accept redirects for this particular
** server. Also, we do not know whether this is for HTTP or all
** other requests as well
*/
if ((cbf && (*cbf)(request, HT_A_CONFIRM, HT_MSG_PROXY, NULL,NULL,NULL))) {
char * addr = HTAnchor_address(proxy_anchor);
HTProxy_add("http", addr);
HT_FREE(addr);
/*
** Start new request through the proxy if we haven't reached the max
** number of redirections for this request
*/
if (HTRequest_doRetry(request)) {
HTLoadAnchor(proxy_anchor, request);
} else {
HTRequest_addError(request, ERR_FATAL, NO, HTERR_MAX_REDIRECT,
NULL, 0, "HTRedirectFilter");
}
/*
** By returning HT_ERROR we make sure that this is the last handler to be
** called. We do this as we don't want any other filter to delete the
** request object now when we have just started a new one ourselves
*/
return HT_ERROR;
} else {
HTRequest_addError(request, ERR_FATAL, NO, HTERR_NO_AUTO_PROXY,
NULL, 0, "HTUseProxyFilter");
return HT_OK;
}
}
/*
** Client side authentication BEFORE filter
** ----------------------------------------
** The filter generates the credentials required to access a document
** Getting the credentials may involve asking the user
*/
PUBLIC int HTCredentialsFilter (HTRequest * request, void * param, int mode)
{
/*
** Ask the authentication module to call the right credentials generator
** that understands this scheme
*/
if (HTAA_beforeFilter(request, param, mode) == HT_OK) {
HTTRACE(PROT_TRACE, "Credentials. verified\n");
return HT_OK;
} else {
HTRequest_addError(request, ERR_FATAL, NO, HTERR_UNAUTHORIZED,
NULL, 0, "HTCredentialsFilter");
return HT_ERROR;
}
}
/*
** Client side authentication AFTER filter
** ---------------------------------------
** The client side authentication filter uses the
** user dialog messages registered in the HTAlert module.
** By default these are the ones used by the line mode browser but you can
** just register something else.
*/
PUBLIC int HTAuthFilter (HTRequest * request, HTResponse * response,
void * param, int status)
{
/*
** Ask the authentication module to call the right challenge parser
** that understands this scheme
*/
if (HTAA_afterFilter(request, response, param, status) == HT_OK) {
/*
** Start request with new credentials. As with the redirection filter
** we reuse the same request object which means that we must
** keep this around until the redirected request has terminated
*/
HTLoad(request, NO);
/*
** We return HT_ERROR to make sure that this is the last handler to be
** called. We do this as we don't want any other filter to delete the
** request object now when we have just started a new one ourselves
*/
return HT_ERROR;
}
return HT_OK;
}
/*
** Client side authentication info AFTER filter
** ---------------------------------------
*/
PUBLIC int HTAuthInfoFilter (HTRequest * request, HTResponse * response,
void * param, int status)
{
/*
** Ask the authentication module to call the right authentication info
** parser
*/
if (! HTResponse_challenge (response))
return HT_OK;
else if (HTAA_updateFilter(request, response, param, status) == HT_OK)
return HT_OK;
else
return HT_ERROR;
}
/*
** Request Logging AFTER filter
** ----------------------------
** Default Logging filter using the log manager provided by HTLog.c
*/
PUBLIC int HTLogFilter (HTRequest * request, HTResponse * response,
void * param, int status)
{
if (request) {
HTLog * log = (HTLog *) param;
if (log) HTLog_addCLF(log, request, status);
return HT_OK;
}
return HT_ERROR;
}
/*
** Request Referer AFTER filter
** ----------------------------
** Default Referer Log filter using the log manager provided by HTLog.c
*/
PUBLIC int HTRefererFilter (HTRequest * request, HTResponse * response,
void * param, int status)
{
if (request) {
HTLog * log = (HTLog *) param;
if (log) HTLog_addReferer(log, request, status);
return HT_OK;
}
return HT_ERROR;
}
| 31.695652 | 79 | 0.666378 | [
"object"
] |
d6b7066b85a32461486f39668e60a22632c2178f | 16,231 | h | C | libraries/disp/viewers/hpisettingsview.h | RDoerfel/mne-cpp | 3e622c7c30524606b7d0a9ee35379cef8430283f | [
"BSD-3-Clause"
] | null | null | null | libraries/disp/viewers/hpisettingsview.h | RDoerfel/mne-cpp | 3e622c7c30524606b7d0a9ee35379cef8430283f | [
"BSD-3-Clause"
] | null | null | null | libraries/disp/viewers/hpisettingsview.h | RDoerfel/mne-cpp | 3e622c7c30524606b7d0a9ee35379cef8430283f | [
"BSD-3-Clause"
] | null | null | null | //=============================================================================================================
/**
* @file hpisettingsview.h
* @author Lorenz Esch <lesch@mgh.harvard.edu>
* Ruben Dörfel <ruben.doerfel@tu-ilmenau.de>
* @since 0.1.0
* @date March, 2020
*
* @section LICENSE
*
* Copyright (C) 2020, Lorenz Esch. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of MNE-CPP authors nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief HpiSettingsView class declaration.
*
*/
#ifndef HPISETTINGSVIEW_H
#define HPISETTINGSVIEW_H
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "../disp_global.h"
#include "abstractview.h"
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QJsonDocument>
//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================
//=============================================================================================================
// FORWARD DECLARATIONS
//=============================================================================================================
namespace Ui {
class HpiSettingsViewWidget;
}
namespace FIFFLIB {
class FiffDigPoint;
class FiffDigPointSet;
}
//=============================================================================================================
// DEFINE NAMESPACE DISPLIB
//=============================================================================================================
namespace DISPLIB
{
//=============================================================================================================
/**
* The HpiSettingsView class provides a QWidget for the HPI controls.
*
* @brief The HpiSettingsView class provides a QWidget for the HPI controls.
*/
class DISPSHARED_EXPORT HpiSettingsView : public AbstractView
{
Q_OBJECT
public:
//=========================================================================================================
/**
* Constructs a HpiSettingsView object.
*
* @param[in] pFiffInfo The FiffInfo.
* @param[in] parent The parent widget.
*/
HpiSettingsView(const QString& sSettingsPath = "",
QWidget *parent = 0,
Qt::WindowFlags f = Qt::Widget);
~HpiSettingsView();
//=========================================================================================================
/**
* Updates the error related labels.
*
* @param[in] vError the new error values.
* @param[in] dMeanErrorDist the mean error value.
*/
void setErrorLabels(const QVector<double>& vError,
double dMeanErrorDist);
//=========================================================================================================
/**
* Updates the movement refered to last reference head position.
*
* @param[in] dMovement the movement refered to last fit.
* @param[in] dRotation the rotation refered to last fit.
*/
void setMovementResults(double dMovement,
double dRotation);
//=========================================================================================================
/**
* Get the SSP checked status.
*
* @return The current SSP checked status.
*/
bool getSspStatusChanged();
//=========================================================================================================
/**
* Get the Comp checked status.
*
* @return The current Comp checked status.
*/
bool getCompStatusChanged();
//=========================================================================================================
/**
* Get the allowed mean error distance.
*
* @return The current allowed mean error distance.
*/
double getAllowedMeanErrorDistChanged();
//=========================================================================================================
/**
* Get the allowed head movement.
*
* @return The current allowed head movement.
*/
double getAllowedMovementChanged();
//=========================================================================================================
/**
* Get the allowed head rotation.
*
* @return The current allowed head rotation.
*/
double getAllowedRotationChanged();
//=========================================================================================================
/**
* Get number of fits per second to do when performing continuous hpi
*
* @return Number of fits per second
*/
int getFittingWindowSize();
//=========================================================================================================
/**
* Display digitizer metadata bsed on input pointList
*
* @param[in] pointList list of digitizer points
*/
void newDigitizerList(QList<FIFFLIB::FiffDigPoint> pointList);
//=========================================================================================================
/**
* Load coil presets from json file at the provided path
*
* @param[in] sFilePath PAth to json file with coil preset data
*/
void loadCoilPresets(const QString& sFilePath);
//=========================================================================================================
/**
* Saves all important settings of this view via QSettings.
*/
void saveSettings();
//=========================================================================================================
/**
* Loads and inits all important settings of this view via QSettings.
*/
void loadSettings();
//=========================================================================================================
/**
* Clears the view
*/
void clearView();
protected:
//=========================================================================================================
/**
* Update the views GUI based on the set GuiMode (Clinical=0, Research=1).
*
* @param[in] mode The new mode (Clinical=0, Research=1).
*/
void updateGuiMode(GuiMode mode);
//=========================================================================================================
/**
* Update the views GUI based on the set ProcessingMode (RealTime=0, Offline=1).
*
* @param[in] mode The new mode (RealTime=0, Offline=1).
*/
void updateProcessingMode(ProcessingMode mode);
//=========================================================================================================
/**
* Load digitzers from a file.
*/
void onLoadDigitizers();
//=========================================================================================================
/**
* Called whenever a cell in the frequenc table widget is changed.
*
* @param[in] row the row of the changed cell.
* @param[in] col the column of the changed cell.
*/
void onFrequencyCellChanged(int row,
int col);
//=========================================================================================================
/**
* Add coil to frequency table widget.
*/
void onAddCoil();
//=========================================================================================================
/**
* Remove coil to frequency table widget.
*/
void onRemoveCoil();
//=========================================================================================================
/**
* Read Polhemus data from fif file.
*/
QList<FIFFLIB::FiffDigPoint> readDigitizersFromFile(const QString& fileName);
//=========================================================================================================
/**
* Sets up coil presets for the number of coils specified by the input argument.
*
* @param[in] iNumCoils number of hpi coils.
*/
void setupCoilPresets(int iNumCoils);
//=========================================================================================================
/**
* Populates preset dropdown gui with names and coil freqs in the input array.
*
* @param[in] presetData json array containing the coil preset name and freqs.
*/
void populatePresetGUI(const QJsonArray& presetData);
//=========================================================================================================
/**
* Adds coil freq and coil error entries based on m_vCoilFreqs. Does not clear existing entires.
*/
void populateCoilGUI();
//=========================================================================================================
/**
* Selects and loads coil preset at index specified by input argument.
*
* @param[in] iCoilPresetIndex selected coil preset.
*/
void selectCoilPreset(int iCoilPresetIndex);
//=========================================================================================================
/**
* Adds coil frequency to gui table based on input argument.
*
* @param[in] iCoilFreq
*/
void addCoilFreqToGUI(int iCoilFreq);
//=========================================================================================================
/**
* @brief addCoilErrorToGUI
*/
void addCoilErrorToGUI();
//=========================================================================================================
/**
* Clears GUI display tables for coil error and coil freqs and empties all rows
*/
void clearCoilGUI();
//=========================================================================================================
/**
* UpdateGUI information with data from input digitizer set.
*
* @param[in] digSet Digigtizer set from which data metadata will be displayed.
*/
void updateDigitizerInfoGUI(const FIFFLIB::FiffDigPointSet& digSet);
Ui::HpiSettingsViewWidget* m_pUi; /**< The HPI dialog. */
QVector<int> m_vCoilFreqs; /**< Vector contains the HPI coil frequencies. */
QString m_sSettingsPath; /**< The settings path to store the GUI settings to. */
QJsonDocument m_CoilPresets; /**< Loaded coil frequency presets */
signals:
//=========================================================================================================
/**
* Emit this signal whenever the coil frequencies changed.
*
* @param[in] vCoilFreqs The new coil frequencies.
*/
void coilFrequenciesChanged(const QVector<int>& vCoilFreqs);
//=========================================================================================================
/**
* Emit this signal whenever new digitzers were loaded.
*
* @param[in] lDigitzers The new digitzers.
* @param[in] sFilePath The file path to the new digitzers.
*/
void digitizersChanged(const QList<FIFFLIB::FiffDigPoint>& lDigitzers,
const QString& sFilePath);
//=========================================================================================================
/**
* Emit this signal whenever the frequency ordering is supposed to be triggered.
*/
void doFreqOrder();
//=========================================================================================================
/**
* Emit this signal whenever a single HPI fit is supposed to be triggered.
*/
void doSingleHpiFit();
//=========================================================================================================
/**
* Emit this signal whenever SSP checkbox changed.
*
* @param[in] bChecked Whether the SSP check box is checked.
*/
void sspStatusChanged(bool bChecked);
//=========================================================================================================
/**
* Emit this signal whenever compensator checkbox changed.
*
* @param[in] bChecked Whether the compensator check box is checked.
*/
void compStatusChanged(bool bChecked);
//=========================================================================================================
/**
* Emit this signal whenever continous HPI checkbox changed.
*
* @param[in] bChecked Whether the continous HPI check box is checked.
*/
void contHpiStatusChanged(bool bChecked);
//=========================================================================================================
/**
* Emit this signal when 'fits per second' control gets updated.
*
* @param[in] iFitsPerSecond How many fits per second we should do.
*/
void fittingWindowSizeChanged(int iFitsPerSecond);
//=========================================================================================================
/**
* Emit this signal whenever the allowed error changed.
*
* @param[in] dAllowedMeanErrorDist Allowed mean error in mm.
*/
void allowedMeanErrorDistChanged(double dAllowedMeanErrorDist);
//=========================================================================================================
/**
* Emit this signal whenever the allowed head movement threshold changed.
*
* @param[in] dAllowedMeanErrorDist Allowed movement threshold.
*/
void allowedMovementChanged(double dAllowedMovement);
//=========================================================================================================
/**
* Emit this signal whenever the allowed head rotation threshold changed.
*
* @param[in] dAllowedMeanErrorDist Allowed rotation in degree.
*/
void allowedRotationChanged(double dAllowedRotation);
};
} //NAMESPACE
#endif // HPISETTINGSVIEW_H
| 39.491484 | 127 | 0.409402 | [
"object",
"vector"
] |
c5ed74d8b9b3984472e5978a0c98de4943c90561 | 44,881 | h | C | include/tcc/tcc.h | lhpustc/tcc_on_nautilus | 75a61711736c56fa744f83aca9a5c790f1986906 | [
"MIT"
] | null | null | null | include/tcc/tcc.h | lhpustc/tcc_on_nautilus | 75a61711736c56fa744f83aca9a5c790f1986906 | [
"MIT"
] | null | null | null | include/tcc/tcc.h | lhpustc/tcc_on_nautilus | 75a61711736c56fa744f83aca9a5c790f1986906 | [
"MIT"
] | null | null | null | /*
* TCC - Tiny C Compiler
*
* Copyright (c) 2001-2004 Fabrice Bellard
*
* 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 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef _TCC_H
#define _TCC_H
#define _GNU_SOURCE
#include "config.h"
#ifdef CONFIG_TCCBOOT
#include "tccboot.h"
#define CONFIG_TCC_STATIC
#else
#include "tccglue.h"
// #include <stdlib.h>
// #include <stdio.h>
// #include <stdarg.h>
// #include <string.h>
// #include <errno.h>
// #include <math.h>
// #include <signal.h>
// #include <fcntl.h>
// #include <setjmp.h>
// #include <time.h>
//
// #ifndef _WIN32
// # include <unistd.h>
// # include <sys/time.h>
// # include <sys/ucontext.h>
// # include <sys/mman.h>
// # ifndef CONFIG_TCC_STATIC
// # include <dlfcn.h>
// # endif
// #else
// # include <windows.h>
// # include <sys/timeb.h>
// # include <io.h> /* open, close etc. */
// # include <direct.h> /* getcwd */
// # ifdef __GNUC__
// # include <stdint.h>
// # else
// typedef UINT_PTR uintptr_t;
// # endif
// # define inline __inline
// # define inp next_inp
// # ifdef LIBTCC_AS_DLL
// # define LIBTCCAPI __declspec(dllexport)
// # define PUB_FUNC LIBTCCAPI
// # endif
// #endif
#endif /* !CONFIG_TCCBOOT */
#ifndef O_BINARY
# define O_BINARY 0
#endif
#include "elf.h"
#ifdef TCC_TARGET_X86_64
# define ELFCLASSW ELFCLASS64
# define ElfW(type) Elf##64##_##type
# define ELFW(type) ELF##64##_##type
# define ElfW_Rel ElfW(Rela)
# define SHT_RELX SHT_RELA
# define REL_SECTION_FMT ".rela%s"
/* XXX: DLL with PLT would only work with x86-64 for now */
# define TCC_OUTPUT_DLL_WITH_PLT
#else
# define ELFCLASSW ELFCLASS32
# define ElfW(type) Elf##32##_##type
# define ELFW(type) ELF##32##_##type
# define ElfW_Rel ElfW(Rel)
# define SHT_RELX SHT_REL
# define REL_SECTION_FMT ".rel%s"
#endif
/* target address type */
#define addr_t ElfW(Addr)
#include "stab.h"
#include "libtcc.h"
/* parser debug */
//#define PARSE_DEBUG
/* preprocessor debug */
//#define PP_DEBUG
/* include file debug */
//#define INC_DEBUG
/* memory leak debug */
//#define MEM_DEBUG
/* assembler debug */
//#define ASM_DEBUG
/* target selection */
//#define TCC_TARGET_I386 /* i386 code generator */
//#define TCC_TARGET_ARM /* ARMv4 code generator */
//#define TCC_TARGET_C67 /* TMS320C67xx code generator */
//#define TCC_TARGET_X86_64 /* x86-64 code generator */
/* default target is I386 */
#if !defined(TCC_TARGET_I386) && !defined(TCC_TARGET_ARM) && \
!defined(TCC_TARGET_C67) && !defined(TCC_TARGET_X86_64)
#define TCC_TARGET_I386
#endif
#if !defined(TCC_UCLIBC) && !defined(TCC_TARGET_ARM) && \
!defined(TCC_TARGET_C67) && !defined(TCC_TARGET_X86_64)
#define CONFIG_TCC_BCHECK /* enable bound checking code */
#endif
/* define it to include assembler support */
#if !defined(TCC_TARGET_ARM) && !defined(TCC_TARGET_C67)
#define CONFIG_TCC_ASM
#endif
/* object format selection */
#if defined(TCC_TARGET_C67)
#define TCC_TARGET_COFF
#endif
/* only native compiler supports -run */
#if defined _WIN32 == defined TCC_TARGET_PE
# if (defined __i386__ || defined _X86_) && defined TCC_TARGET_I386
# define TCC_IS_NATIVE
# elif (defined __x86_64__ || defined _AMD64_) && defined TCC_TARGET_X86_64
# define TCC_IS_NATIVE
# elif defined __arm__ && defined TCC_TARGET_ARM
# define TCC_IS_NATIVE
# endif
#endif
#if defined TCC_IS_NATIVE && !defined CONFIG_TCCBOOT
# define CONFIG_TCC_BACKTRACE
#endif
/* ------------ path configuration ------------ */
#ifndef CONFIG_SYSROOT
# define CONFIG_SYSROOT ""
#endif
#ifndef CONFIG_TCCDIR
# define CONFIG_TCCDIR "."
#endif
#ifndef CONFIG_LDDIR
# define CONFIG_LDDIR "lib"
#endif
/* path to find crt1.o, crti.o and crtn.o */
#ifndef CONFIG_TCC_CRTPREFIX
# define CONFIG_TCC_CRTPREFIX CONFIG_SYSROOT "/usr/" CONFIG_LDDIR
#endif
/* Below: {B} is substituted by CONFIG_TCCDIR (rsp. -B option) */
/* system include paths */
#ifndef CONFIG_TCC_SYSINCLUDEPATHS
# ifdef TCC_TARGET_PE
# define CONFIG_TCC_SYSINCLUDEPATHS "{B}/include;{B}/include/winapi"
# elif defined CONFIG_MULTIARCHDIR
# define CONFIG_TCC_SYSINCLUDEPATHS \
CONFIG_SYSROOT "/usr/local/include" \
":" CONFIG_SYSROOT "/usr/local/include/" CONFIG_MULTIARCHDIR \
":" CONFIG_SYSROOT "/usr/include" \
":" CONFIG_SYSROOT "/usr/include/" CONFIG_MULTIARCHDIR \
":" "{B}/include"
# else
# define CONFIG_TCC_SYSINCLUDEPATHS \
CONFIG_SYSROOT "/usr/local/include" \
":" CONFIG_SYSROOT "/usr/include" \
":" "{B}/include"
# endif
#endif
/* library search paths */
#ifndef CONFIG_TCC_LIBPATHS
# ifdef TCC_TARGET_PE
# define CONFIG_TCC_LIBPATHS "{B}/lib"
# else
# define CONFIG_TCC_LIBPATHS \
CONFIG_SYSROOT "/usr/" CONFIG_LDDIR \
":" CONFIG_SYSROOT "/" CONFIG_LDDIR \
":" CONFIG_SYSROOT "/usr/local/" CONFIG_LDDIR
# endif
#endif
/* name of ELF interpreter */
#ifndef CONFIG_TCC_ELFINTERP
# if defined __FreeBSD__
# define CONFIG_TCC_ELFINTERP "/libexec/ld-elf.so.1"
# elif defined __FreeBSD_kernel__
# define CONFIG_TCC_ELFINTERP "/lib/ld.so.1"
# elif defined TCC_ARM_HARDFLOAT
# define CONFIG_TCC_ELFINTERP "/lib/ld-linux-armhf.so.3"
# elif defined TCC_ARM_EABI
# define CONFIG_TCC_ELFINTERP "/lib/ld-linux.so.3"
# elif defined(TCC_TARGET_X86_64)
# define CONFIG_TCC_ELFINTERP "/lib64/ld-linux-x86-64.so.2"
# elif defined(TCC_UCLIBC)
# define CONFIG_TCC_ELFINTERP "/lib/ld-uClibc.so.0"
# elif defined(TCC_TARGET_PE)
# define CONFIG_TCC_ELFINTERP "-"
# else
# define CONFIG_TCC_ELFINTERP "/lib/ld-linux.so.2"
# endif
#endif
/* library to use with CONFIG_USE_LIBGCC instead of libtcc1.a */
#define TCC_LIBGCC CONFIG_SYSROOT "/" CONFIG_LDDIR "/libgcc_s.so.1"
/* -------------------------------------------- */
/* include the target specific definitions */
#define TARGET_DEFS_ONLY
#ifdef TCC_TARGET_I386
# include "i386-gen.c"
#endif
#ifdef TCC_TARGET_X86_64
# include "x86_64-gen.c"
#endif
#ifdef TCC_TARGET_ARM
# include "arm-gen.c"
#endif
#ifdef TCC_TARGET_C67
# include "coff.h"
# include "c67-gen.c"
#endif
#undef TARGET_DEFS_ONLY
/* -------------------------------------------- */
#define INCLUDE_STACK_SIZE 32
#define IFDEF_STACK_SIZE 64
#define VSTACK_SIZE 256
#define STRING_MAX_SIZE 1024
#define PACK_STACK_SIZE 8
#define TOK_HASH_SIZE 8192 /* must be a power of two */
#define TOK_ALLOC_INCR 512 /* must be a power of two */
#define TOK_MAX_SIZE 4 /* token max size in int unit when stored in string */
/* token symbol management */
typedef struct TokenSym {
struct TokenSym *hash_next;
struct Sym *sym_define; /* direct pointer to define */
struct Sym *sym_label; /* direct pointer to label */
struct Sym *sym_struct; /* direct pointer to structure */
struct Sym *sym_identifier; /* direct pointer to identifier */
int tok; /* token number */
int len;
char str[1];
} TokenSym;
#ifdef TCC_TARGET_PE
typedef unsigned short nwchar_t;
#else
typedef int nwchar_t;
#endif
typedef struct CString {
int size; /* size in bytes */
void *data; /* either 'char *' or 'nwchar_t *' */
int size_allocated;
void *data_allocated; /* if non NULL, data has been malloced */
} CString;
/* type definition */
typedef struct CType {
int t;
struct Sym *ref;
} CType;
/* constant value */
typedef union CValue {
long double ld;
double d;
float f;
int i;
unsigned int ui;
unsigned int ul; /* address (should be unsigned long on 64 bit cpu) */
long long ll;
unsigned long long ull;
struct CString *cstr;
void *ptr;
int tab[LDOUBLE_SIZE/4];
} CValue;
/* value on stack */
typedef struct SValue {
CType type; /* type */
unsigned short r; /* register + flags */
unsigned short r2; /* second register, used for 'long long'
type. If not used, set to VT_CONST */
CValue c; /* constant, if VT_CONST */
struct Sym *sym; /* symbol, if (VT_SYM | VT_CONST) */
} SValue;
/* symbol management */
typedef struct Sym {
int v; /* symbol token */
char *asm_label; /* associated asm label */
long r; /* associated register */
union {
long c; /* associated number */
int *d; /* define token stream */
};
CType type; /* associated type */
union {
struct Sym *next; /* next related symbol */
long jnext; /* next jump label */
};
struct Sym *prev; /* prev symbol in stack */
struct Sym *prev_tok; /* previous symbol for this token */
} Sym;
/* section definition */
/* XXX: use directly ELF structure for parameters ? */
/* special flag to indicate that the section should not be linked to
the other ones */
#define SHF_PRIVATE 0x80000000
/* special flag, too */
#define SECTION_ABS ((void *)1)
typedef struct Section {
unsigned long data_offset; /* current data offset */
unsigned char *data; /* section data */
unsigned long data_allocated; /* used for realloc() handling */
int sh_name; /* elf section name (only used during output) */
int sh_num; /* elf section number */
int sh_type; /* elf section type */
int sh_flags; /* elf section flags */
int sh_info; /* elf section info */
int sh_addralign; /* elf section alignment */
int sh_entsize; /* elf entry size */
unsigned long sh_size; /* section size (only used during output) */
addr_t sh_addr; /* address at which the section is relocated */
unsigned long sh_offset; /* file offset */
int nb_hashed_syms; /* used to resize the hash table */
struct Section *link; /* link to another section */
struct Section *reloc; /* corresponding section for relocation, if any */
struct Section *hash; /* hash table for symbols */
struct Section *next;
char name[1]; /* section name */
} Section;
typedef struct DLLReference {
int level;
void *handle;
char name[1];
} DLLReference;
/* GNUC attribute definition */
typedef struct AttributeDef {
unsigned
func_call : 3, /* calling convention (0..5), see below */
aligned : 5, /* alignement (0..16) */
packed : 1,
func_export : 1,
func_import : 1,
func_args : 5,
mode : 4,
weak : 1,
fill : 11;
struct Section *section;
int alias_target; /* token */
} AttributeDef;
/* gr: wrappers for casting sym->r for other purposes */
#define FUNC_CALL(r) (((AttributeDef*)&(r))->func_call)
#define FUNC_EXPORT(r) (((AttributeDef*)&(r))->func_export)
#define FUNC_IMPORT(r) (((AttributeDef*)&(r))->func_import)
#define FUNC_ARGS(r) (((AttributeDef*)&(r))->func_args)
#define FUNC_ALIGN(r) (((AttributeDef*)&(r))->aligned)
#define FUNC_PACKED(r) (((AttributeDef*)&(r))->packed)
#define ATTR_MODE(r) (((AttributeDef*)&(r))->mode)
#define INT_ATTR(ad) (*(int*)(ad))
/* -------------------------------------------------- */
#define SYM_STRUCT 0x40000000 /* struct/union/enum symbol space */
#define SYM_FIELD 0x20000000 /* struct/union field symbol space */
#define SYM_FIRST_ANOM 0x10000000 /* first anonymous sym */
/* stored in 'Sym.c' field */
#define FUNC_NEW 1 /* ansi function prototype */
#define FUNC_OLD 2 /* old function prototype */
#define FUNC_ELLIPSIS 3 /* ansi function prototype with ... */
/* stored in 'Sym.r' field */
#define FUNC_CDECL 0 /* standard c call */
#define FUNC_STDCALL 1 /* pascal c call */
#define FUNC_FASTCALL1 2 /* first param in %eax */
#define FUNC_FASTCALL2 3 /* first parameters in %eax, %edx */
#define FUNC_FASTCALL3 4 /* first parameter in %eax, %edx, %ecx */
#define FUNC_FASTCALLW 5 /* first parameter in %ecx, %edx */
/* field 'Sym.t' for macros */
#define MACRO_OBJ 0 /* object like macro */
#define MACRO_FUNC 1 /* function like macro */
/* field 'Sym.r' for C labels */
#define LABEL_DEFINED 0 /* label is defined */
#define LABEL_FORWARD 1 /* label is forward defined */
#define LABEL_DECLARED 2 /* label is declared but never used */
/* type_decl() types */
#define TYPE_ABSTRACT 1 /* type without variable */
#define TYPE_DIRECT 2 /* type with variable */
#define IO_BUF_SIZE 8192
typedef struct BufferedFile {
uint8_t *buf_ptr;
uint8_t *buf_end;
int fd;
struct BufferedFile *prev;
int line_num; /* current line number - here to simplify code */
int ifndef_macro; /* #ifndef macro / #endif search */
int ifndef_macro_saved; /* saved ifndef_macro */
int *ifdef_stack_ptr; /* ifdef_stack value at the start of the file */
char filename[1024]; /* filename */
unsigned char buffer[IO_BUF_SIZE + 1]; /* extra size for CH_EOB char */
} BufferedFile;
#define CH_EOB '\\' /* end of buffer or '\0' char in file */
#define CH_EOF (-1) /* end of file */
/* parsing state (used to save parser state to reparse part of the
source several times) */
typedef struct ParseState {
const int *macro_ptr;
int line_num;
int tok;
CValue tokc;
} ParseState;
/* used to record tokens */
typedef struct TokenString {
int *str;
int len;
int allocated_len;
int last_line_num;
} TokenString;
/* inline functions */
typedef struct InlineFunc {
int *token_str;
Sym *sym;
char filename[1];
} InlineFunc;
/* include file cache, used to find files faster and also to eliminate
inclusion if the include file is protected by #ifndef ... #endif */
typedef struct CachedInclude {
int ifndef_macro;
int hash_next; /* -1 if none */
char filename[1]; /* path specified in #include */
} CachedInclude;
#define CACHED_INCLUDES_HASH_SIZE 512
#ifdef CONFIG_TCC_ASM
typedef struct ExprValue {
uint32_t v;
Sym *sym;
} ExprValue;
#define MAX_ASM_OPERANDS 30
typedef struct ASMOperand {
int id; /* GCC 3 optionnal identifier (0 if number only supported */
char *constraint;
char asm_str[16]; /* computed asm string for operand */
SValue *vt; /* C value of the expression */
int ref_index; /* if >= 0, gives reference to a output constraint */
int input_index; /* if >= 0, gives reference to an input constraint */
int priority; /* priority, used to assign registers */
int reg; /* if >= 0, register number used for this operand */
int is_llong; /* true if double register value */
int is_memory; /* true if memory operand */
int is_rw; /* for '+' modifier */
} ASMOperand;
#endif
struct sym_attr {
unsigned long got_offset;
#ifdef TCC_TARGET_ARM
unsigned char plt_thumb_stub:1;
#endif
};
struct TCCState {
int verbose; /* if true, display some information during compilation */
int nostdinc; /* if true, no standard headers are added */
int nostdlib; /* if true, no standard libraries are added */
int nocommon; /* if true, do not use common symbols for .bss data */
int static_link; /* if true, static linking is performed */
int rdynamic; /* if true, all symbols are exported */
int symbolic; /* if true, resolve symbols in the current module first */
int alacarte_link; /* if true, only link in referenced objects from archive */
char *tcc_lib_path; /* CONFIG_TCCDIR or -B option */
char *soname; /* as specified on the command line (-soname) */
char *rpath; /* as specified on the command line (-Wl,-rpath=) */
/* output type, see TCC_OUTPUT_XXX */
int output_type;
/* output format, see TCC_OUTPUT_FORMAT_xxx */
int output_format;
/* C language options */
int char_is_unsigned;
int leading_underscore;
/* warning switches */
int warn_write_strings;
int warn_unsupported;
int warn_error;
int warn_none;
int warn_implicit_function_declaration;
/* compile with debug symbol (and use them if error during execution) */
int do_debug;
#ifdef CONFIG_TCC_BCHECK
/* compile with built-in memory and bounds checker */
int do_bounds_check;
#endif
addr_t text_addr; /* address of text section */
int has_text_addr;
unsigned long section_align; /* section alignment */
char *init_symbol; /* symbols to call at load-time (not used currently) */
char *fini_symbol; /* symbols to call at unload-time (not used currently) */
#ifdef TCC_TARGET_I386
int seg_size; /* 32. Can be 16 with i386 assembler (.code16) */
#endif
/* array of all loaded dlls (including those referenced by loaded dlls) */
DLLReference **loaded_dlls;
int nb_loaded_dlls;
/* include paths */
char **include_paths;
int nb_include_paths;
char **sysinclude_paths;
int nb_sysinclude_paths;
/* library paths */
char **library_paths;
int nb_library_paths;
/* crt?.o object path */
char **crt_paths;
int nb_crt_paths;
/* error handling */
void *error_opaque;
void (*error_func)(void *opaque, const char *msg);
int error_set_jmp_enabled;
jmp_buf error_jmp_buf;
int nb_errors;
/* output file for preprocessing (-E) */
FILE *ppfp;
/* for -MD/-MF: collected dependencies for this compilation */
char **target_deps;
int nb_target_deps;
/* compilation */
BufferedFile *include_stack[INCLUDE_STACK_SIZE];
BufferedFile **include_stack_ptr;
int ifdef_stack[IFDEF_STACK_SIZE];
int *ifdef_stack_ptr;
/* included files enclosed with #ifndef MACRO */
int cached_includes_hash[CACHED_INCLUDES_HASH_SIZE];
CachedInclude **cached_includes;
int nb_cached_includes;
/* #pragma pack stack */
int pack_stack[PACK_STACK_SIZE];
int *pack_stack_ptr;
/* inline functions are stored as token lists and compiled last
only if referenced */
struct InlineFunc **inline_fns;
int nb_inline_fns;
/* sections */
Section **sections;
int nb_sections; /* number of sections, including first dummy section */
Section **priv_sections;
int nb_priv_sections; /* number of private sections */
/* got & plt handling */
Section *got;
Section *plt;
struct sym_attr *sym_attrs;
int nb_sym_attrs;
/* give the correspondance from symtab indexes to dynsym indexes */
int *symtab_to_dynsym;
/* temporary dynamic symbol sections (for dll loading) */
Section *dynsymtab_section;
/* exported dynamic symbol section */
Section *dynsym;
/* copy of the gobal symtab_section variable */
Section *symtab;
/* tiny assembler state */
Sym *asm_labels;
#ifdef TCC_TARGET_PE
/* PE info */
int pe_subsystem;
unsigned pe_file_align;
unsigned pe_stack_size;
# ifdef TCC_TARGET_X86_64
Section *uw_pdata;
int uw_sym;
unsigned uw_offs;
# endif
#endif
#ifdef TCC_IS_NATIVE
/* for tcc_relocate */
void *runtime_mem;
# ifdef HAVE_SELINUX
void *write_mem;
unsigned long mem_size;
# endif
# if !defined TCC_TARGET_PE && (defined TCC_TARGET_X86_64 || defined TCC_TARGET_ARM)
/* write PLT and GOT here */
char *runtime_plt_and_got;
unsigned runtime_plt_and_got_offset;
# define TCC_HAS_RUNTIME_PLTGOT
# endif
#endif
/* used by main and tcc_parse_args only */
char **files; /* files seen on command line */
int nb_files; /* number thereof */
int nb_libraries; /* number of libs thereof */
char *outfile; /* output filename */
char *option_m; /* only -m32/-m64 handled */
int print_search_dirs; /* option */
int option_r; /* option -r */
int do_bench; /* option -bench */
int gen_deps; /* option -MD */
char *deps_outfile; /* option -MF */
};
/* The current value can be: */
#define VT_VALMASK 0x003f /* mask for value location, register or: */
#define VT_CONST 0x0030 /* constant in vc (must be first non register value) */
#define VT_LLOCAL 0x0031 /* lvalue, offset on stack */
#define VT_LOCAL 0x0032 /* offset on stack */
#define VT_CMP 0x0033 /* the value is stored in processor flags (in vc) */
#define VT_JMP 0x0034 /* value is the consequence of jmp true (even) */
#define VT_JMPI 0x0035 /* value is the consequence of jmp false (odd) */
#define VT_REF 0x0040 /* value is pointer to structure rather than address */
#define VT_LVAL 0x0100 /* var is an lvalue */
#define VT_SYM 0x0200 /* a symbol value is added */
#define VT_MUSTCAST 0x0400 /* value must be casted to be correct (used for
char/short stored in integer registers) */
#define VT_MUSTBOUND 0x0800 /* bound checking must be done before
dereferencing value */
#define VT_BOUNDED 0x8000 /* value is bounded. The address of the
bounding function call point is in vc */
#define VT_LVAL_BYTE 0x1000 /* lvalue is a byte */
#define VT_LVAL_SHORT 0x2000 /* lvalue is a short */
#define VT_LVAL_UNSIGNED 0x4000 /* lvalue is unsigned */
#define VT_LVAL_TYPE (VT_LVAL_BYTE | VT_LVAL_SHORT | VT_LVAL_UNSIGNED)
/* types */
#define VT_BTYPE 0x000f /* mask for basic type */
#define VT_INT 0 /* integer type */
#define VT_BYTE 1 /* signed byte type */
#define VT_SHORT 2 /* short type */
#define VT_VOID 3 /* void type */
#define VT_PTR 4 /* pointer */
#define VT_ENUM 5 /* enum definition */
#define VT_FUNC 6 /* function type */
#define VT_STRUCT 7 /* struct/union definition */
#define VT_FLOAT 8 /* IEEE float */
#define VT_DOUBLE 9 /* IEEE double */
#define VT_LDOUBLE 10 /* IEEE long double */
#define VT_BOOL 11 /* ISOC99 boolean type */
#define VT_LLONG 12 /* 64 bit integer */
#define VT_LONG 13 /* long integer (NEVER USED as type, only
during parsing) */
#define VT_UNSIGNED 0x0010 /* unsigned type */
#define VT_ARRAY 0x0020 /* array type (also has VT_PTR) */
#define VT_BITFIELD 0x0040 /* bitfield modifier */
#define VT_CONSTANT 0x0800 /* const modifier */
#define VT_VOLATILE 0x1000 /* volatile modifier */
#define VT_SIGNED 0x2000 /* signed type */
#define VT_VLA 0x00020000 /* VLA type (also has VT_PTR and VT_ARRAY) */
/* storage */
#define VT_EXTERN 0x00000080 /* extern definition */
#define VT_STATIC 0x00000100 /* static variable */
#define VT_TYPEDEF 0x00000200 /* typedef definition */
#define VT_INLINE 0x00000400 /* inline definition */
#define VT_IMPORT 0x00004000 /* win32: extern data imported from dll */
#define VT_EXPORT 0x00008000 /* win32: data exported from dll */
#define VT_WEAK 0x00010000 /* weak symbol */
#define VT_STRUCT_SHIFT 18 /* shift for bitfield shift values (max: 32 - 2*6) */
/* type mask (except storage) */
#define VT_STORAGE (VT_EXTERN | VT_STATIC | VT_TYPEDEF | VT_INLINE | VT_IMPORT | VT_EXPORT | VT_WEAK)
#define VT_TYPE (~(VT_STORAGE))
/* token values */
/* warning: the following compare tokens depend on i386 asm code */
#define TOK_ULT 0x92
#define TOK_UGE 0x93
#define TOK_EQ 0x94
#define TOK_NE 0x95
#define TOK_ULE 0x96
#define TOK_UGT 0x97
#define TOK_Nset 0x98
#define TOK_Nclear 0x99
#define TOK_LT 0x9c
#define TOK_GE 0x9d
#define TOK_LE 0x9e
#define TOK_GT 0x9f
#define TOK_LAND 0xa0
#define TOK_LOR 0xa1
#define TOK_DEC 0xa2
#define TOK_MID 0xa3 /* inc/dec, to void constant */
#define TOK_INC 0xa4
#define TOK_UDIV 0xb0 /* unsigned division */
#define TOK_UMOD 0xb1 /* unsigned modulo */
#define TOK_PDIV 0xb2 /* fast division with undefined rounding for pointers */
#define TOK_CINT 0xb3 /* number in tokc */
#define TOK_CCHAR 0xb4 /* char constant in tokc */
#define TOK_STR 0xb5 /* pointer to string in tokc */
#define TOK_TWOSHARPS 0xb6 /* ## preprocessing token */
#define TOK_LCHAR 0xb7
#define TOK_LSTR 0xb8
#define TOK_CFLOAT 0xb9 /* float constant */
#define TOK_LINENUM 0xba /* line number info */
#define TOK_CDOUBLE 0xc0 /* double constant */
#define TOK_CLDOUBLE 0xc1 /* long double constant */
#define TOK_UMULL 0xc2 /* unsigned 32x32 -> 64 mul */
#define TOK_ADDC1 0xc3 /* add with carry generation */
#define TOK_ADDC2 0xc4 /* add with carry use */
#define TOK_SUBC1 0xc5 /* add with carry generation */
#define TOK_SUBC2 0xc6 /* add with carry use */
#define TOK_CUINT 0xc8 /* unsigned int constant */
#define TOK_CLLONG 0xc9 /* long long constant */
#define TOK_CULLONG 0xca /* unsigned long long constant */
#define TOK_ARROW 0xcb
#define TOK_DOTS 0xcc /* three dots */
#define TOK_SHR 0xcd /* unsigned shift right */
#define TOK_PPNUM 0xce /* preprocessor number */
#define TOK_NOSUBST 0xcf /* means following token has already been pp'd */
#define TOK_SHL 0x01 /* shift left */
#define TOK_SAR 0x02 /* signed shift right */
/* assignement operators : normal operator or 0x80 */
#define TOK_A_MOD 0xa5
#define TOK_A_AND 0xa6
#define TOK_A_MUL 0xaa
#define TOK_A_ADD 0xab
#define TOK_A_SUB 0xad
#define TOK_A_DIV 0xaf
#define TOK_A_XOR 0xde
#define TOK_A_OR 0xfc
#define TOK_A_SHL 0x81
#define TOK_A_SAR 0x82
#ifndef offsetof
#define offsetof(type, field) ((size_t) &((type *)0)->field)
#endif
#ifndef countof
#define countof(tab) (sizeof(tab) / sizeof((tab)[0]))
#endif
#define TOK_EOF (-1) /* end of file */
#define TOK_LINEFEED 10 /* line feed */
/* all identificators and strings have token above that */
#define TOK_IDENT 256
#define DEF_ASM(x) DEF(TOK_ASM_ ## x, #x)
#define TOK_ASM_int TOK_INT
#define TOK_ASM_weak TOK_WEAK1
#if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
/* only used for i386 asm opcodes definitions */
#define DEF_BWL(x) \
DEF(TOK_ASM_ ## x ## b, #x "b") \
DEF(TOK_ASM_ ## x ## w, #x "w") \
DEF(TOK_ASM_ ## x ## l, #x "l") \
DEF(TOK_ASM_ ## x, #x)
#define DEF_WL(x) \
DEF(TOK_ASM_ ## x ## w, #x "w") \
DEF(TOK_ASM_ ## x ## l, #x "l") \
DEF(TOK_ASM_ ## x, #x)
#ifdef TCC_TARGET_X86_64
# define DEF_BWLQ(x) \
DEF(TOK_ASM_ ## x ## b, #x "b") \
DEF(TOK_ASM_ ## x ## w, #x "w") \
DEF(TOK_ASM_ ## x ## l, #x "l") \
DEF(TOK_ASM_ ## x ## q, #x "q") \
DEF(TOK_ASM_ ## x, #x)
# define DEF_WLQ(x) \
DEF(TOK_ASM_ ## x ## w, #x "w") \
DEF(TOK_ASM_ ## x ## l, #x "l") \
DEF(TOK_ASM_ ## x ## q, #x "q") \
DEF(TOK_ASM_ ## x, #x)
# define DEF_BWLX DEF_BWLQ
# define DEF_WLX DEF_WLQ
/* number of sizes + 1 */
# define NBWLX 5
#else
# define DEF_BWLX DEF_BWL
# define DEF_WLX DEF_WL
/* number of sizes + 1 */
# define NBWLX 4
#endif
#define DEF_FP1(x) \
DEF(TOK_ASM_ ## f ## x ## s, "f" #x "s") \
DEF(TOK_ASM_ ## fi ## x ## l, "fi" #x "l") \
DEF(TOK_ASM_ ## f ## x ## l, "f" #x "l") \
DEF(TOK_ASM_ ## fi ## x ## s, "fi" #x "s")
#define DEF_FP(x) \
DEF(TOK_ASM_ ## f ## x, "f" #x ) \
DEF(TOK_ASM_ ## f ## x ## p, "f" #x "p") \
DEF_FP1(x)
#define DEF_ASMTEST(x) \
DEF_ASM(x ## o) \
DEF_ASM(x ## no) \
DEF_ASM(x ## b) \
DEF_ASM(x ## c) \
DEF_ASM(x ## nae) \
DEF_ASM(x ## nb) \
DEF_ASM(x ## nc) \
DEF_ASM(x ## ae) \
DEF_ASM(x ## e) \
DEF_ASM(x ## z) \
DEF_ASM(x ## ne) \
DEF_ASM(x ## nz) \
DEF_ASM(x ## be) \
DEF_ASM(x ## na) \
DEF_ASM(x ## nbe) \
DEF_ASM(x ## a) \
DEF_ASM(x ## s) \
DEF_ASM(x ## ns) \
DEF_ASM(x ## p) \
DEF_ASM(x ## pe) \
DEF_ASM(x ## np) \
DEF_ASM(x ## po) \
DEF_ASM(x ## l) \
DEF_ASM(x ## nge) \
DEF_ASM(x ## nl) \
DEF_ASM(x ## ge) \
DEF_ASM(x ## le) \
DEF_ASM(x ## ng) \
DEF_ASM(x ## nle) \
DEF_ASM(x ## g)
#endif // defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
enum tcc_token {
TOK_LAST = TOK_IDENT - 1,
#define DEF(id, str) id,
#include "tcctok.h"
#undef DEF
};
#define TOK_UIDENT TOK_DEFINE
#ifdef _WIN32
#define snprintf _snprintf
#define vsnprintf _vsnprintf
#ifndef __GNUC__
#define strtold (long double)strtod
#define strtof (float)strtod
#define strtoll _strtoi64
#define strtoull _strtoui64
#endif
#else
/* XXX: need to define this to use them in non ISOC99 context */
extern float strtof (const char *__nptr, char **__endptr);
extern long double strtold (const char *__nptr, char **__endptr);
#endif
#ifdef _WIN32
#define IS_DIRSEP(c) (c == '/' || c == '\\')
#define IS_ABSPATH(p) (IS_DIRSEP(p[0]) || (p[0] && p[1] == ':' && IS_DIRSEP(p[2])))
#define PATHCMP stricmp
#else
#define IS_DIRSEP(c) (c == '/')
#define IS_ABSPATH(p) IS_DIRSEP(p[0])
#define PATHCMP strcmp
#endif
#ifdef TCC_TARGET_PE
#define PATHSEP ';'
#else
#define PATHSEP ':'
#endif
/* space exlcuding newline */
static inline int is_space(int ch)
{
return ch == ' ' || ch == '\t' || ch == '\v' || ch == '\f' || ch == '\r';
}
static inline int isid(int c)
{
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_';
}
static inline int isnum(int c)
{
return c >= '0' && c <= '9';
}
static inline int isoct(int c)
{
return c >= '0' && c <= '7';
}
static inline int toup(int c)
{
return (c >= 'a' && c <= 'z') ? c - 'a' + 'A' : c;
}
#ifndef PUB_FUNC
# define PUB_FUNC
#endif
#ifdef ONE_SOURCE
#define ST_INLN static inline
#define ST_FUNC static
#define ST_DATA static
#else
#define ST_INLN
#define ST_FUNC
#define ST_DATA extern
#endif
/* ------------ libtcc.c ------------ */
/* use GNU C extensions */
ST_DATA int gnu_ext;
/* use Tiny C extensions */
ST_DATA int tcc_ext;
/* XXX: get rid of this ASAP */
ST_DATA struct TCCState *tcc_state;
#ifdef MEM_DEBUG
ST_DATA int mem_cur_size;
ST_DATA int mem_max_size;
#endif
#define AFF_PRINT_ERROR 0x0001 /* print error if file not found */
#define AFF_REFERENCED_DLL 0x0002 /* load a referenced dll from another dll */
#define AFF_PREPROCESS 0x0004 /* preprocess file */
/* public functions currently used by the tcc main function */
PUB_FUNC char *pstrcpy(char *buf, int buf_size, const char *s);
PUB_FUNC char *pstrcat(char *buf, int buf_size, const char *s);
PUB_FUNC char *pstrncpy(char *out, const char *in, size_t num);
PUB_FUNC char *tcc_basename(const char *name);
PUB_FUNC char *tcc_fileextension (const char *name);
PUB_FUNC void tcc_free(void *ptr);
PUB_FUNC void *tcc_malloc(unsigned long size);
PUB_FUNC void *tcc_mallocz(unsigned long size);
PUB_FUNC void *tcc_realloc(void *ptr, unsigned long size);
PUB_FUNC char *tcc_strdup(const char *str);
// #define free(p) use_tcc_free(p)
// #define malloc(s) use_tcc_malloc(s)
// #define realloc(p, s) use_tcc_realloc(p, s)
#undef strdup
#define strdup(s) use_tcc_strdup(s)
PUB_FUNC void tcc_memstats(void);
PUB_FUNC void tcc_error_noabort(const char *fmt, ...);
PUB_FUNC void tcc_error(const char *fmt, ...);
PUB_FUNC void tcc_warning(const char *fmt, ...);
/* other utilities */
ST_FUNC void dynarray_add(void ***ptab, int *nb_ptr, void *data);
ST_FUNC void dynarray_reset(void *pp, int *n);
ST_FUNC void cstr_ccat(CString *cstr, int ch);
ST_FUNC void cstr_cat(CString *cstr, const char *str);
ST_FUNC void cstr_wccat(CString *cstr, int ch);
ST_FUNC void cstr_new(CString *cstr);
ST_FUNC void cstr_free(CString *cstr);
ST_FUNC void cstr_reset(CString *cstr);
ST_FUNC Section *new_section(TCCState *s1, const char *name, int sh_type, int sh_flags);
ST_FUNC void section_realloc(Section *sec, unsigned long new_size);
ST_FUNC void *section_ptr_add(Section *sec, unsigned long size);
ST_FUNC void section_reserve(Section *sec, unsigned long size);
ST_FUNC Section *find_section(TCCState *s1, const char *name);
ST_FUNC void put_extern_sym2(Sym *sym, Section *section, addr_t value, unsigned long size, int can_add_underscore);
ST_FUNC void put_extern_sym(Sym *sym, Section *section, addr_t value, unsigned long size);
ST_FUNC void greloc(Section *s, Sym *sym, unsigned long offset, int type);
ST_INLN void sym_free(Sym *sym);
ST_FUNC Sym *sym_push2(Sym **ps, int v, int t, long c);
ST_FUNC Sym *sym_find2(Sym *s, int v);
ST_FUNC Sym *sym_push(int v, CType *type, int r, int c);
ST_FUNC void sym_pop(Sym **ptop, Sym *b);
ST_INLN Sym *struct_find(int v);
ST_INLN Sym *sym_find(int v);
ST_FUNC Sym *global_identifier_push(int v, int t, int c);
ST_FUNC void tcc_open_bf(TCCState *s1, const char *filename, int initlen);
ST_FUNC int tcc_open(TCCState *s1, const char *filename);
ST_FUNC void tcc_close(void);
ST_FUNC int tcc_add_file_internal(TCCState *s1, const char *filename, int flags);
ST_FUNC int tcc_add_crt(TCCState *s, const char *filename);
ST_FUNC int tcc_add_dll(TCCState *s, const char *filename, int flags);
PUB_FUNC void tcc_print_stats(TCCState *s, int64_t total_time);
PUB_FUNC int tcc_parse_args(TCCState *s, int argc, char **argv);
/* ------------ tccpp.c ------------ */
ST_DATA struct BufferedFile *file;
ST_DATA int ch, tok;
ST_DATA CValue tokc;
ST_DATA const int *macro_ptr;
ST_DATA int parse_flags;
ST_DATA int tok_flags;
ST_DATA CString tokcstr; /* current parsed string, if any */
/* display benchmark infos */
ST_DATA int total_lines;
ST_DATA int total_bytes;
ST_DATA int tok_ident;
ST_DATA TokenSym **table_ident;
#define TOK_FLAG_BOL 0x0001 /* beginning of line before */
#define TOK_FLAG_BOF 0x0002 /* beginning of file before */
#define TOK_FLAG_ENDIF 0x0004 /* a endif was found matching starting #ifdef */
#define TOK_FLAG_EOF 0x0008 /* end of file */
#define PARSE_FLAG_PREPROCESS 0x0001 /* activate preprocessing */
#define PARSE_FLAG_TOK_NUM 0x0002 /* return numbers instead of TOK_PPNUM */
#define PARSE_FLAG_LINEFEED 0x0004 /* line feed is returned as a
token. line feed is also
returned at eof */
#define PARSE_FLAG_ASM_COMMENTS 0x0008 /* '#' can be used for line comment */
#define PARSE_FLAG_SPACES 0x0010 /* next() returns space tokens (for -E) */
ST_FUNC TokenSym *tok_alloc(const char *str, int len);
ST_FUNC char *get_tok_str(int v, CValue *cv);
ST_FUNC void save_parse_state(ParseState *s);
ST_FUNC void restore_parse_state(ParseState *s);
ST_INLN void tok_str_new(TokenString *s);
ST_FUNC void tok_str_free(int *str);
ST_FUNC void tok_str_add(TokenString *s, int t);
ST_FUNC void tok_str_add_tok(TokenString *s);
ST_INLN void define_push(int v, int macro_type, int *str, Sym *first_arg);
ST_FUNC void define_undef(Sym *s);
ST_INLN Sym *define_find(int v);
ST_FUNC void free_defines(Sym *b);
ST_FUNC Sym *label_find(int v);
ST_FUNC Sym *label_push(Sym **ptop, int v, int flags);
ST_FUNC void label_pop(Sym **ptop, Sym *slast);
ST_FUNC void parse_define(void);
ST_FUNC void preprocess(int is_bof);
ST_FUNC void next_nomacro(void);
ST_FUNC void next(void);
ST_INLN void unget_tok(int last_tok);
ST_FUNC void preprocess_init(TCCState *s1);
ST_FUNC void preprocess_new(void);
ST_FUNC int tcc_preprocess(TCCState *s1);
ST_FUNC void skip(int c);
ST_FUNC void expect(const char *msg);
/* ------------ tccgen.c ------------ */
ST_DATA Section *text_section, *data_section, *bss_section; /* predefined sections */
ST_DATA Section *cur_text_section; /* current section where function code is generated */
#ifdef CONFIG_TCC_ASM
ST_DATA Section *last_text_section; /* to handle .previous asm directive */
#endif
#ifdef CONFIG_TCC_BCHECK
/* bound check related sections */
ST_DATA Section *bounds_section; /* contains global data bound description */
ST_DATA Section *lbounds_section; /* contains local data bound description */
#endif
/* symbol sections */
ST_DATA Section *symtab_section, *strtab_section;
/* debug sections */
ST_DATA Section *stab_section, *stabstr_section;
#define SYM_POOL_NB (8192 / sizeof(Sym))
ST_DATA Sym *sym_free_first;
ST_DATA void **sym_pools;
ST_DATA int nb_sym_pools;
ST_DATA Sym *global_stack;
ST_DATA Sym *local_stack;
ST_DATA Sym *local_label_stack;
ST_DATA Sym *global_label_stack;
ST_DATA Sym *define_stack;
ST_DATA CType char_pointer_type, func_old_type, int_type, size_type;
ST_DATA SValue __vstack[1+/*to make bcheck happy*/ VSTACK_SIZE], *vtop;
#define vstack (__vstack + 1)
ST_DATA int rsym, anon_sym, ind, loc;
ST_DATA int const_wanted; /* true if constant wanted */
ST_DATA int nocode_wanted; /* true if no code generation wanted for an expression */
ST_DATA int global_expr; /* true if compound literals must be allocated globally (used during initializers parsing */
ST_DATA CType func_vt; /* current function return type (used by return instruction) */
ST_DATA int func_vc;
ST_DATA int last_line_num, last_ind, func_ind; /* debug last line number and pc */
ST_DATA char *funcname;
ST_INLN int is_float(int t);
ST_FUNC int ieee_finite(double d);
ST_FUNC void test_lvalue(void);
ST_FUNC void swap(int *p, int *q);
ST_FUNC void vpushi(int v);
ST_FUNC Sym *external_global_sym(int v, CType *type, int r);
ST_FUNC void vset(CType *type, int r, int v);
ST_FUNC void vswap(void);
ST_FUNC void vpush_global_sym(CType *type, int v);
ST_FUNC void vrote(SValue *e, int n);
ST_FUNC void vrott(int n);
ST_FUNC void vrotb(int n);
#ifdef TCC_TARGET_ARM
ST_FUNC int get_reg_ex(int rc, int rc2);
ST_FUNC void lexpand_nr(void);
#endif
ST_FUNC void vpushv(SValue *v);
ST_FUNC void save_reg(int r);
ST_FUNC int get_reg(int rc);
ST_FUNC void save_regs(int n);
ST_FUNC int gv(int rc);
ST_FUNC void gv2(int rc1, int rc2);
ST_FUNC void vpop(void);
ST_FUNC void gen_op(int op);
ST_FUNC int type_size(CType *type, int *a);
ST_FUNC void mk_pointer(CType *type);
ST_FUNC void vstore(void);
ST_FUNC void inc(int post, int c);
ST_FUNC void parse_asm_str(CString *astr);
ST_FUNC int lvalue_type(int t);
ST_FUNC void indir(void);
ST_FUNC void unary(void);
ST_FUNC void expr_prod(void);
ST_FUNC void expr_sum(void);
ST_FUNC void gexpr(void);
ST_FUNC int expr_const(void);
ST_FUNC void gen_inline_functions(void);
ST_FUNC void decl(int l);
#if defined CONFIG_TCC_BCHECK || defined TCC_TARGET_C67
ST_FUNC Sym *get_sym_ref(CType *type, Section *sec, unsigned long offset, unsigned long size);
#endif
/* ------------ tccelf.c ------------ */
#define TCC_OUTPUT_FORMAT_ELF 0 /* default output format: ELF */
#define TCC_OUTPUT_FORMAT_BINARY 1 /* binary image output */
#define TCC_OUTPUT_FORMAT_COFF 2 /* COFF */
#define ARMAG "!<arch>\012" /* For COFF and a.out archives */
typedef struct {
unsigned int n_strx; /* index into string table of name */
unsigned char n_type; /* type of symbol */
unsigned char n_other; /* misc info (usually empty) */
unsigned short n_desc; /* description field */
unsigned int n_value; /* value of symbol */
} Stab_Sym;
ST_FUNC Section *new_symtab(TCCState *s1, const char *symtab_name, int sh_type, int sh_flags, const char *strtab_name, const char *hash_name, int hash_sh_flags);
ST_FUNC int put_elf_str(Section *s, const char *sym);
ST_FUNC int put_elf_sym(Section *s, addr_t value, unsigned long size, int info, int other, int shndx, const char *name);
ST_FUNC int add_elf_sym(Section *s, addr_t value, unsigned long size, int info, int other, int sh_num, const char *name);
ST_FUNC int find_elf_sym(Section *s, const char *name);
ST_FUNC void put_elf_reloc(Section *symtab, Section *s, unsigned long offset, int type, int symbol);
ST_FUNC void put_stabs(const char *str, int type, int other, int desc, unsigned long value);
ST_FUNC void put_stabs_r(const char *str, int type, int other, int desc, unsigned long value, Section *sec, int sym_index);
ST_FUNC void put_stabn(int type, int other, int desc, int value);
ST_FUNC void put_stabd(int type, int other, int desc);
ST_FUNC void relocate_common_syms(void);
ST_FUNC void relocate_syms(TCCState *s1, int do_resolve);
ST_FUNC void relocate_section(TCCState *s1, Section *s);
ST_FUNC void tcc_add_linker_symbols(TCCState *s1);
ST_FUNC int tcc_load_object_file(TCCState *s1, int fd, unsigned long file_offset);
ST_FUNC int tcc_load_archive(TCCState *s1, int fd);
ST_FUNC void tcc_add_bcheck(TCCState *s1);
ST_FUNC void build_got_entries(TCCState *s1);
ST_FUNC void tcc_add_runtime(TCCState *s1);
ST_FUNC addr_t get_elf_sym_addr(TCCState *s, const char *name, int err);
#ifdef TCC_IS_NATIVE
ST_FUNC void *tcc_get_symbol_err(TCCState *s, const char *name);
#endif
#ifndef TCC_TARGET_PE
ST_FUNC int tcc_load_dll(TCCState *s1, int fd, const char *filename, int level);
ST_FUNC int tcc_load_ldscript(TCCState *s1);
ST_FUNC uint8_t *parse_comment(uint8_t *p);
ST_FUNC void minp(void);
ST_INLN void inp(void);
ST_FUNC int handle_eob(void);
#endif
/* ------------ xxx-gen.c ------------ */
#ifdef TCC_TARGET_X86_64
ST_DATA const int reg_classes[NB_REGS+7];
#else
ST_DATA const int reg_classes[NB_REGS];
#endif
ST_FUNC void gsym_addr(int t, int a);
ST_FUNC void gsym(int t);
ST_FUNC void load(int r, SValue *sv);
ST_FUNC void store(int r, SValue *v);
ST_FUNC void gfunc_call(int nb_args);
ST_FUNC void gfunc_prolog(CType *func_type);
ST_FUNC void gfunc_epilog(void);
ST_FUNC int gjmp(int t);
ST_FUNC void gjmp_addr(int a);
ST_FUNC int gtst(int inv, int t);
ST_FUNC void gen_opi(int op);
ST_FUNC void gen_opf(int op);
ST_FUNC void gen_cvt_ftoi(int t);
ST_FUNC void gen_cvt_ftof(int t);
ST_FUNC void ggoto(void);
#ifndef TCC_TARGET_C67
ST_FUNC void o(unsigned int c);
#endif
#ifndef TCC_TARGET_ARM
ST_FUNC void gen_cvt_itof(int t);
#endif
/* ------------ i386-gen.c ------------ */
#if defined TCC_TARGET_I386 || defined TCC_TARGET_X86_64
ST_FUNC void g(int c);
ST_FUNC int oad(int c, int s);
ST_FUNC void gen_le16(int c);
ST_FUNC void gen_le32(int c);
ST_FUNC void gen_addr32(int r, Sym *sym, int c);
ST_FUNC void gen_addrpc32(int r, Sym *sym, int c);
#endif
#ifdef CONFIG_TCC_BCHECK
ST_FUNC void gen_bounded_ptr_add(void);
ST_FUNC void gen_bounded_ptr_deref(void);
#endif
/* ------------ x86_64-gen.c ------------ */
#ifdef TCC_TARGET_X86_64
ST_FUNC void gen_addr64(int r, Sym *sym, int64_t c);
ST_FUNC void gen_opl(int op);
#endif
/* ------------ arm-gen.c ------------ */
#ifdef TCC_TARGET_ARM
ST_FUNC void arm_init_types(void);
ST_FUNC uint32_t encbranch(int pos, int addr, int fail);
ST_FUNC void gen_cvt_itof1(int t);
#endif
/* ------------ c67-gen.c ------------ */
#ifdef TCC_TARGET_C67
#endif
/* ------------ tcccoff.c ------------ */
#ifdef TCC_TARGET_COFF
ST_FUNC int tcc_output_coff(TCCState *s1, FILE *f);
ST_FUNC int tcc_load_coff(TCCState * s1, int fd);
#endif
/* ------------ tccasm.c ------------ */
ST_FUNC void asm_instr(void);
ST_FUNC void asm_global_instr(void);
#ifdef CONFIG_TCC_ASM
ST_FUNC int find_constraint(ASMOperand *operands, int nb_operands, const char *name, const char **pp);
ST_FUNC void asm_expr(TCCState *s1, ExprValue *pe);
ST_FUNC int asm_int_expr(TCCState *s1);
ST_FUNC int tcc_assemble(TCCState *s1, int do_preprocess);
/* ------------ i386-asm.c ------------ */
ST_FUNC void gen_expr32(ExprValue *pe);
ST_FUNC void asm_opcode(TCCState *s1, int opcode);
ST_FUNC void asm_compute_constraints(ASMOperand *operands, int nb_operands, int nb_outputs, const uint8_t *clobber_regs, int *pout_reg);
ST_FUNC void subst_asm_operand(CString *add_str, SValue *sv, int modifier);
ST_FUNC void asm_gen_code(ASMOperand *operands, int nb_operands, int nb_outputs, int is_output, uint8_t *clobber_regs, int out_reg);
ST_FUNC void asm_clobber(uint8_t *clobber_regs, const char *str);
#endif
/* ------------ tccpe.c -------------- */
#ifdef TCC_TARGET_PE
ST_FUNC int pe_load_file(struct TCCState *s1, const char *filename, int fd);
ST_FUNC int pe_output_file(TCCState * s1, const char *filename);
ST_FUNC int pe_putimport(TCCState *s1, int dllindex, const char *name, addr_t value);
ST_FUNC SValue *pe_getimport(SValue *sv, SValue *v2);
#ifdef TCC_TARGET_X86_64
ST_FUNC void pe_add_unwind_data(unsigned start, unsigned end, unsigned stack);
#endif
#endif
/* ------------ tccrun.c ----------------- */
#ifdef TCC_IS_NATIVE
#ifdef CONFIG_TCC_STATIC
#define RTLD_LAZY 0x001
#define RTLD_NOW 0x002
#define RTLD_GLOBAL 0x100
#define RTLD_DEFAULT NULL
/* dummy function for profiling */
ST_FUNC void *dlopen(const char *filename, int flag);
ST_FUNC void dlclose(void *p);
ST_FUNC const char *dlerror(void);
ST_FUNC void *resolve_sym(TCCState *s1, const char *symbol);
#elif !defined _WIN32
ST_FUNC void *resolve_sym(TCCState *s1, const char *symbol);
#endif
#ifdef CONFIG_TCC_BACKTRACE
ST_DATA int rt_num_callers;
ST_DATA const char **rt_bound_error_msg;
ST_DATA void *rt_prog_main;
ST_FUNC void tcc_set_num_callers(int n);
#endif
#endif
/********************************************************/
#undef ST_DATA
#ifdef ONE_SOURCE
#define ST_DATA static
#else
#define ST_DATA
#endif
/********************************************************/
#endif /* _TCC_H */
| 32.498914 | 161 | 0.685368 | [
"object"
] |
c5ee78dffcd5574048d3dfa0b6f677bddef2d79c | 10,108 | h | C | third_party/WebKit/Source/core/dom/NodeListsNodeData.h | wenfeifei/miniblink49 | 2ed562ff70130485148d94b0e5f4c343da0c2ba4 | [
"Apache-2.0"
] | 5,964 | 2016-09-27T03:46:29.000Z | 2022-03-31T16:25:27.000Z | third_party/WebKit/Source/core/dom/NodeListsNodeData.h | w4454962/miniblink49 | b294b6eacb3333659bf7b94d670d96edeeba14c0 | [
"Apache-2.0"
] | 459 | 2016-09-29T00:51:38.000Z | 2022-03-07T14:37:46.000Z | third_party/WebKit/Source/core/dom/NodeListsNodeData.h | w4454962/miniblink49 | b294b6eacb3333659bf7b94d670d96edeeba14c0 | [
"Apache-2.0"
] | 1,006 | 2016-09-27T05:17:27.000Z | 2022-03-30T02:46:51.000Z | /*
* Copyright (C) 2008, 2010 Apple Inc. All rights reserved.
* Copyright (C) 2008 David Smith <catfish.man@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#ifndef NodeListsNodeData_h
#define NodeListsNodeData_h
#include "core/dom/ChildNodeList.h"
#include "core/dom/EmptyNodeList.h"
#include "core/dom/QualifiedName.h"
#include "core/dom/TagCollection.h"
#include "core/html/CollectionType.h"
#include "platform/heap/Handle.h"
#include "wtf/text/AtomicString.h"
#include "wtf/text/StringHash.h"
namespace blink {
class NodeListsNodeData final : public NoBaseWillBeGarbageCollectedFinalized<NodeListsNodeData> {
WTF_MAKE_NONCOPYABLE(NodeListsNodeData);
WTF_MAKE_FAST_ALLOCATED_WILL_BE_REMOVED(NodeListsNodeData);
public:
ChildNodeList* childNodeList(ContainerNode& node)
{
ASSERT_UNUSED(node, !m_childNodeList || node == m_childNodeList->virtualOwnerNode());
return toChildNodeList(m_childNodeList);
}
PassRefPtrWillBeRawPtr<ChildNodeList> ensureChildNodeList(ContainerNode& node)
{
if (m_childNodeList)
return toChildNodeList(m_childNodeList);
RefPtrWillBeRawPtr<ChildNodeList> list = ChildNodeList::create(node);
m_childNodeList = list.get();
return list.release();
}
PassRefPtrWillBeRawPtr<EmptyNodeList> ensureEmptyChildNodeList(Node& node)
{
if (m_childNodeList)
return toEmptyNodeList(m_childNodeList);
RefPtrWillBeRawPtr<EmptyNodeList> list = EmptyNodeList::create(node);
m_childNodeList = list.get();
return list.release();
}
#if !ENABLE(OILPAN)
void removeChildNodeList(ChildNodeList* list)
{
ASSERT(m_childNodeList == list);
if (deleteThisAndUpdateNodeRareDataIfAboutToRemoveLastList(list->ownerNode()))
return;
m_childNodeList = nullptr;
}
void removeEmptyChildNodeList(EmptyNodeList* list)
{
ASSERT(m_childNodeList == list);
if (deleteThisAndUpdateNodeRareDataIfAboutToRemoveLastList(list->ownerNode()))
return;
m_childNodeList = nullptr;
}
#endif
struct NodeListAtomicCacheMapEntryHash {
static unsigned hash(const std::pair<unsigned char, StringImpl*>& entry)
{
return DefaultHash<StringImpl*>::Hash::hash(entry.second) + entry.first;
}
static bool equal(const std::pair<unsigned char, StringImpl*>& a, const std::pair<unsigned char, StringImpl*>& b) { return a == b; }
static const bool safeToCompareToEmptyOrDeleted = DefaultHash<StringImpl*>::Hash::safeToCompareToEmptyOrDeleted;
};
// Oilpan: keep a weak reference to the collection objects.
// Explicit object unregistration in a non-Oilpan setting
// on object destruction is replaced by the garbage collector
// clearing out their weak reference.
typedef WillBeHeapHashMap<std::pair<unsigned char, StringImpl*>, RawPtrWillBeWeakMember<LiveNodeListBase>, NodeListAtomicCacheMapEntryHash> NodeListAtomicNameCacheMap;
typedef WillBeHeapHashMap<QualifiedName, RawPtrWillBeWeakMember<TagCollection>> TagCollectionCacheNS;
template<typename T>
PassRefPtrWillBeRawPtr<T> addCache(ContainerNode& node, CollectionType collectionType, const AtomicString& name)
{
NodeListAtomicNameCacheMap::AddResult result = m_atomicNameCaches.add(namedNodeListKey(collectionType, name), nullptr);
if (!result.isNewEntry) {
#if ENABLE(OILPAN)
return static_cast<T*>(result.storedValue->value.get());
#else
return static_cast<T*>(result.storedValue->value);
#endif
}
RefPtrWillBeRawPtr<T> list = T::create(node, collectionType, name);
result.storedValue->value = list.get();
return list.release();
}
template<typename T>
PassRefPtrWillBeRawPtr<T> addCache(ContainerNode& node, CollectionType collectionType)
{
NodeListAtomicNameCacheMap::AddResult result = m_atomicNameCaches.add(namedNodeListKey(collectionType, starAtom), nullptr);
if (!result.isNewEntry) {
#if ENABLE(OILPAN)
return static_cast<T*>(result.storedValue->value.get());
#else
return static_cast<T*>(result.storedValue->value);
#endif
}
RefPtrWillBeRawPtr<T> list = T::create(node, collectionType);
result.storedValue->value = list.get();
return list.release();
}
template<typename T>
T* cached(CollectionType collectionType)
{
return static_cast<T*>(m_atomicNameCaches.get(namedNodeListKey(collectionType, starAtom)));
}
PassRefPtrWillBeRawPtr<TagCollection> addCache(ContainerNode& node, const AtomicString& namespaceURI, const AtomicString& localName)
{
QualifiedName name(nullAtom, localName, namespaceURI);
TagCollectionCacheNS::AddResult result = m_tagCollectionCacheNS.add(name, nullptr);
if (!result.isNewEntry)
return result.storedValue->value;
RefPtrWillBeRawPtr<TagCollection> list = TagCollection::create(node, namespaceURI, localName);
result.storedValue->value = list.get();
return list.release();
}
#if !ENABLE(OILPAN)
void removeCache(LiveNodeListBase* list, CollectionType collectionType, const AtomicString& name = starAtom)
{
ASSERT(list == m_atomicNameCaches.get(namedNodeListKey(collectionType, name)));
if (deleteThisAndUpdateNodeRareDataIfAboutToRemoveLastList(list->ownerNode()))
return;
m_atomicNameCaches.remove(namedNodeListKey(collectionType, name));
}
void removeCache(LiveNodeListBase* list, const AtomicString& namespaceURI, const AtomicString& localName)
{
QualifiedName name(nullAtom, localName, namespaceURI);
ASSERT(list == m_tagCollectionCacheNS.get(name));
if (deleteThisAndUpdateNodeRareDataIfAboutToRemoveLastList(list->ownerNode()))
return;
m_tagCollectionCacheNS.remove(name);
}
#endif
static PassOwnPtrWillBeRawPtr<NodeListsNodeData> create()
{
return adoptPtrWillBeNoop(new NodeListsNodeData);
}
void invalidateCaches(const QualifiedName* attrName = 0);
bool isEmpty() const
{
return !m_childNodeList && m_atomicNameCaches.isEmpty() && m_tagCollectionCacheNS.isEmpty();
}
void adoptTreeScope()
{
invalidateCaches();
}
void adoptDocument(Document& oldDocument, Document& newDocument)
{
ASSERT(oldDocument != newDocument);
NodeListAtomicNameCacheMap::const_iterator atomicNameCacheEnd = m_atomicNameCaches.end();
for (NodeListAtomicNameCacheMap::const_iterator it = m_atomicNameCaches.begin(); it != atomicNameCacheEnd; ++it) {
LiveNodeListBase* list = it->value;
list->didMoveToDocument(oldDocument, newDocument);
}
TagCollectionCacheNS::const_iterator tagEnd = m_tagCollectionCacheNS.end();
for (TagCollectionCacheNS::const_iterator it = m_tagCollectionCacheNS.begin(); it != tagEnd; ++it) {
LiveNodeListBase* list = it->value;
ASSERT(!list->isRootedAtDocument());
list->didMoveToDocument(oldDocument, newDocument);
}
}
DECLARE_TRACE();
private:
NodeListsNodeData()
: m_childNodeList(nullptr)
{ }
std::pair<unsigned char, StringImpl*> namedNodeListKey(CollectionType type, const AtomicString& name)
{
// Holding the raw StringImpl is safe because |name| is retained by the NodeList and the NodeList
// is reponsible for removing itself from the cache on deletion.
return std::pair<unsigned char, StringImpl*>(type, name.impl());
}
#if !ENABLE(OILPAN)
bool deleteThisAndUpdateNodeRareDataIfAboutToRemoveLastList(Node&);
#endif
// Can be a ChildNodeList or an EmptyNodeList.
RawPtrWillBeWeakMember<NodeList> m_childNodeList;
NodeListAtomicNameCacheMap m_atomicNameCaches;
TagCollectionCacheNS m_tagCollectionCacheNS;
};
#if !ENABLE(OILPAN)
inline bool NodeListsNodeData::deleteThisAndUpdateNodeRareDataIfAboutToRemoveLastList(Node& ownerNode)
{
ASSERT(ownerNode.nodeLists() == this);
if ((m_childNodeList ? 1 : 0) + m_atomicNameCaches.size() + m_tagCollectionCacheNS.size() != 1)
return false;
ownerNode.clearNodeLists();
return true;
}
#endif
template <typename Collection>
inline PassRefPtrWillBeRawPtr<Collection> ContainerNode::ensureCachedCollection(CollectionType type)
{
return ensureNodeLists().addCache<Collection>(*this, type);
}
template <typename Collection>
inline PassRefPtrWillBeRawPtr<Collection> ContainerNode::ensureCachedCollection(CollectionType type, const AtomicString& name)
{
return ensureNodeLists().addCache<Collection>(*this, type, name);
}
template <typename Collection>
inline PassRefPtrWillBeRawPtr<Collection> ContainerNode::ensureCachedCollection(CollectionType type, const AtomicString& namespaceURI, const AtomicString& localName)
{
ASSERT_UNUSED(type, type == TagCollectionType);
return ensureNodeLists().addCache(*this, namespaceURI, localName);
}
template <typename Collection>
inline Collection* ContainerNode::cachedCollection(CollectionType type)
{
NodeListsNodeData* nodeLists = this->nodeLists();
return nodeLists ? nodeLists->cached<Collection>(type) : 0;
}
} // namespace blink
#endif // NodeListsNodeData_h
| 37.716418 | 171 | 0.720123 | [
"object"
] |
c5fdcb46e2212f2a09fa0364c6cb1ff7abfc8920 | 10,838 | h | C | Samples/Common/include/SdkSample.h | Frankincense/ogre | 927d459a7e9d5a9990b4c565ec4ab492f6124566 | [
"MIT"
] | null | null | null | Samples/Common/include/SdkSample.h | Frankincense/ogre | 927d459a7e9d5a9990b4c565ec4ab492f6124566 | [
"MIT"
] | null | null | null | Samples/Common/include/SdkSample.h | Frankincense/ogre | 927d459a7e9d5a9990b4c565ec4ab492f6124566 | [
"MIT"
] | null | null | null | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#ifndef __SdkSample_H__
#define __SdkSample_H__
#include "Sample.h"
#include "OgreTrays.h"
#include "OgreCameraMan.h"
#include "OgreAdvancedRenderControls.h"
#include "Ogre.h"
namespace OgreBites
{
/*=============================================================================
// Base SDK sample class. Includes default player camera and SDK trays.
=============================================================================*/
class SdkSample : public Sample, public TrayListener
{
public:
SdkSample()
{
// so we don't have to worry about checking if these keys exist later
mInfo["Title"] = "Untitled";
mInfo["Description"] = "";
mInfo["Category"] = "Unsorted";
mInfo["Thumbnail"] = "";
mInfo["Help"] = "";
mTrayMgr = 0;
mCameraMan = 0;
mCamera = 0;
mCameraNode = 0;
mViewport = 0;
mControls = 0;
mCursorWasVisible = false;
mDragLook = false;
}
/*-----------------------------------------------------------------------------
| Manually update the cursor position after being unpaused.
-----------------------------------------------------------------------------*/
virtual void unpaused()
{
mTrayMgr->refreshCursor();
}
/*-----------------------------------------------------------------------------
| Automatically saves position and orientation for free-look cameras.
-----------------------------------------------------------------------------*/
virtual void saveState(Ogre::NameValuePairList& state)
{
if (mCameraMan->getStyle() == CS_FREELOOK)
{
state["CameraPosition"] = Ogre::StringConverter::toString(mCameraNode->getPosition());
state["CameraOrientation"] = Ogre::StringConverter::toString(mCameraNode->getOrientation());
}
}
/*-----------------------------------------------------------------------------
| Automatically restores position and orientation for free-look cameras.
-----------------------------------------------------------------------------*/
virtual void restoreState(Ogre::NameValuePairList& state)
{
if (state.find("CameraPosition") != state.end() && state.find("CameraOrientation") != state.end())
{
mCameraMan->setStyle(CS_FREELOOK);
mCameraNode->setPosition(Ogre::StringConverter::parseVector3(state["CameraPosition"]));
mCameraNode->setOrientation(Ogre::StringConverter::parseQuaternion(state["CameraOrientation"]));
}
}
virtual bool frameRenderingQueued(const Ogre::FrameEvent& evt)
{
mTrayMgr->frameRendered(evt);
mControls->frameRendered(evt);
if (!mTrayMgr->isDialogVisible())
{
mCameraMan->frameRendered(evt); // if dialog isn't up, then update the camera
}
return true;
}
virtual bool keyPressed(const KeyboardEvent& evt)
{
int key = evt.keysym.sym;
if (key == 'h' || key == SDLK_F1) // toggle visibility of help dialog
{
if (!mTrayMgr->isDialogVisible() && mInfo["Help"] != "") mTrayMgr->showOkDialog("Help", mInfo["Help"]);
else mTrayMgr->closeDialog();
}
if (mTrayMgr->isDialogVisible()) return true; // don't process any more keys if dialog is up
mControls->keyPressed(evt);
mCameraMan->keyPressed(evt);
return true;
}
virtual bool keyReleased(const KeyboardEvent& evt)
{
mCameraMan->keyReleased(evt);
return true;
}
/* IMPORTANT: When overriding these following handlers, remember to allow the tray manager
to filter out any interface-related mouse events before processing them in your scene.
If the tray manager handler returns true, the event was meant for the trays, not you. */
virtual bool mouseMoved(const MouseMotionEvent& evt)
{
if (mTrayMgr->mouseMoved(evt)) return true;
mCameraMan->mouseMoved(evt);
return true;
}
// convert and redirect
virtual bool touchMoved(const TouchFingerEvent& evt) {
MouseMotionEvent e;
e.xrel = evt.dx * mWindow->getWidth();
e.yrel = evt.dy * mWindow->getHeight();
return mouseMoved(e);
}
virtual bool mousePressed(const MouseButtonEvent& evt)
{
if (mTrayMgr->mousePressed(evt)) return true;
if (mDragLook && evt.button == BUTTON_LEFT)
{
mCameraMan->setStyle(CS_FREELOOK);
mTrayMgr->hideCursor();
}
mCameraMan->mousePressed(evt);
return true;
}
// convert and redirect
virtual bool touchPressed(const TouchFingerEvent& evt) {
MouseButtonEvent e;
e.button = BUTTON_LEFT;
return mousePressed(e);
}
virtual bool mouseReleased(const MouseButtonEvent& evt)
{
if (mTrayMgr->mouseReleased(evt)) return true;
if (mDragLook && evt.button == BUTTON_LEFT)
{
mCameraMan->setStyle(CS_MANUAL);
mTrayMgr->showCursor();
}
mCameraMan->mouseReleased(evt);
return true;
}
// convert and redirect
virtual bool touchReleased(const TouchFingerEvent& evt) {
MouseButtonEvent e;
e.button = BUTTON_LEFT;
return mouseReleased(e);
}
virtual bool mouseWheelRolled(const MouseWheelEvent& evt) {
mCameraMan->mouseWheelRolled(evt);
return true;
}
/*-----------------------------------------------------------------------------
| Extended to setup a default tray interface and camera controller.
-----------------------------------------------------------------------------*/
virtual void _setup(Ogre::RenderWindow* window, Ogre::FileSystemLayer* fsLayer, Ogre::OverlaySystem* overlaySys)
{
// assign mRoot here in case Root was initialised after the Sample's constructor ran.
mRoot = Ogre::Root::getSingletonPtr();
mWindow = window;
mFSLayer = fsLayer;
mOverlaySystem = overlaySys;
locateResources();
createSceneManager();
setupView();
mTrayMgr = new TrayManager("SampleControls", window, this); // create a tray interface
loadResources();
mResourcesLoaded = true;
// show stats and logo and hide the cursor
mTrayMgr->showFrameStats(TL_BOTTOMLEFT);
mTrayMgr->showLogo(TL_BOTTOMRIGHT);
mTrayMgr->hideCursor();
mControls = new AdvancedRenderControls(mTrayMgr, mCamera);
setupContent();
mContentSetup = true;
mDone = false;
}
virtual void _shutdown()
{
Sample::_shutdown();
delete mControls;
delete mTrayMgr;
delete mCameraMan;
// restore settings we may have changed, so as not to affect other samples
Ogre::MaterialManager::getSingleton().setDefaultTextureFiltering(Ogre::TFO_BILINEAR);
Ogre::MaterialManager::getSingleton().setDefaultAnisotropy(1);
}
protected:
virtual void setupView()
{
// setup default viewport layout and camera
mCamera = mSceneMgr->createCamera("MainCamera");
mCameraNode = mSceneMgr->getRootSceneNode()->createChildSceneNode();
mCameraNode->attachObject(mCamera);
mCameraNode->setFixedYawAxis(true);
mViewport = mWindow->addViewport(mCamera);
mCamera->setAspectRatio((Ogre::Real)mViewport->getActualWidth() / (Ogre::Real)mViewport->getActualHeight());
mCamera->setAutoAspectRatio(true);
mCamera->setNearClipDistance(5);
mCameraMan = new CameraMan(mCameraNode); // create a default camera controller
}
virtual void setDragLook(bool enabled)
{
if (enabled)
{
mCameraMan->setStyle(CS_MANUAL);
mTrayMgr->showCursor();
mDragLook = true;
}
else
{
mCameraMan->setStyle(CS_FREELOOK);
mTrayMgr->hideCursor();
mDragLook = false;
}
}
Ogre::Viewport* mViewport; // main viewport
Ogre::Camera* mCamera; // main camera
Ogre::SceneNode* mCameraNode; // camera node
TrayManager* mTrayMgr; // tray interface manager
CameraMan* mCameraMan; // basic camera controller
AdvancedRenderControls* mControls; // sample details panel
bool mCursorWasVisible; // was cursor visible before dialog appeared
bool mDragLook; // click and drag to free-look
};
}
#endif
| 37.372414 | 120 | 0.536169 | [
"object"
] |
68026f4f28211ad4cecdfe641a0dfb05cdf8538d | 3,459 | h | C | Core/DianYing/Include/Dy/Core/Resource/Information/FInformationFrameBuffer.h | liliilli/DianYing | 6e19f67e5d932e346a0ce63a648bed1a04ef618e | [
"MIT"
] | 4 | 2019-03-17T19:46:54.000Z | 2019-12-09T20:11:01.000Z | Core/DianYing/Include/Dy/Core/Resource/Information/FInformationFrameBuffer.h | liliilli/DianYing | 6e19f67e5d932e346a0ce63a648bed1a04ef618e | [
"MIT"
] | null | null | null | Core/DianYing/Include/Dy/Core/Resource/Information/FInformationFrameBuffer.h | liliilli/DianYing | 6e19f67e5d932e346a0ce63a648bed1a04ef618e | [
"MIT"
] | null | null | null | #ifndef GUARD_DY_CORE_RESOURCE_INFORMATION_FInformationFrameBuffer_H
#define GUARD_DY_CORE_RESOURCE_INFORMATION_FInformationFrameBuffer_H
///
/// MIT License
/// Copyright (c) 2018-2019 Jongmin Yun
///
/// 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 <Dy/Helper/Type/DVector2.h>
#include <Dy/Management/Type/AttachmentInformation.h>
#include <Dy/Core/Resource/Type/TInformationBinder.h>
//!
//! Forward declaration
//!
namespace dy
{
struct PDyGlFrameBufferInstanceMetaInfo;
class FInformationAttachment;
} /// ::dy namespace
//!
//! Implementation
//!
namespace dy
{
/// @class FInformationFrameBuffer
/// @brief FrameBuffer information resource.
class FInformationFrameBuffer final
{
public:
MDY_ONLY_MOVEABLE_PROPERTIES_DEFAULT(FInformationFrameBuffer);
/// @brief Construct framebuffer information.
FInformationFrameBuffer(_MIN_ const PDyGlFrameBufferInstanceMetaInfo& metaInfo);
~FInformationFrameBuffer() = default;
/// @brief Get framebuffer specifier name.
MDY_NODISCARD const std::string& GetSpecifierName() const noexcept { return this->mSpecifierName; }
/// @brief Get frame buffer size.
MDY_NODISCARD const DIVec2& GetFrameBufferSize() const noexcept { return this->mFrameBufferSize; }
/// @brief Get attachment info list.
MDY_NODISCARD const auto& GetAttachmentInformationBinderList() const noexcept { return this->mAttachmentInfoList; }
/// @brief Get attachment binding mode list.
MDY_NODISCARD const TBlendingEquationList& GetAttachmentBlendings() const noexcept;
/// @brief Check populated frame buffer is using default depth buffer.
MDY_NODISCARD bool IsUsingDepthBuffer() const noexcept { return this->mIsUsingDepthBuffer; }
/// @brief Get depth information binder instance as reference which is immutable.
MDY_NODISCARD const auto& GetDepthBufferBinder() const noexcept { return this->mDepthAttachment; }
/// @brief Check populated frame buffer is using pixel shader.
MDY_NODISCARD bool IsUsingPixelShader() const noexcept { return this->mIsNotUsingPixelShader == false; }
/// @brief Check framebuffer will be created as ping-pong framebuffer.
MDY_NODISCARD bool IsPingPong() const noexcept;
private:
using TAttachmentInformation = std::pair<
PDyGlAttachmentBinderInformation, std::unique_ptr<TDyInformationBinderAttachment>
>;
using TAttachmentInfoBinderList = std::vector<TAttachmentInformation>;
std::string mSpecifierName;
TAttachmentInfoBinderList mAttachmentInfoList = {};
TBlendingEquationList mAttachmentBlendings = {};
DIVec2 mFrameBufferSize = {};
TAttachmentInformation mDepthAttachment = {};
bool mIsUsingDepthBuffer = false;
bool mIsNotUsingPixelShader = false;
/// @brief When enabled, attachment will be created as ping-pong (two-attachment) attachment.
bool mIsPingpong = false;
};
} /// ::dy namespace
#endif /// GUARD_DY_CORE_RESOURCE_INFORMATION_FInformationFrameBuffer_H
| 37.193548 | 117 | 0.75571 | [
"vector"
] |
6802cea2400af870e97e575905b27224c0586e5d | 22,527 | h | C | t1m1/include/eigen/Eigen/src/Core/DenseCoeffsBase.h | dailysoap/CSMM.104x | 4515b30ab5f60827a9011b23ef155a3063584a9d | [
"MIT"
] | 7 | 2017-04-01T17:18:35.000Z | 2022-01-12T05:23:23.000Z | t1m1/include/eigen/Eigen/src/Core/DenseCoeffsBase.h | dailysoap/CSMM.104x | 4515b30ab5f60827a9011b23ef155a3063584a9d | [
"MIT"
] | 6 | 2020-05-24T13:36:50.000Z | 2022-02-15T06:44:20.000Z | t1m1/include/eigen/Eigen/src/Core/DenseCoeffsBase.h | dailysoap/CSMM.104x | 4515b30ab5f60827a9011b23ef155a3063584a9d | [
"MIT"
] | 2 | 2018-09-20T01:07:39.000Z | 2019-02-22T14:55:38.000Z | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2010 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, 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.
//
// Eigen 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 or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#ifndef EIGEN_DENSECOEFFSBASE_H
#define EIGEN_DENSECOEFFSBASE_H
template<typename Derived, bool EnableDirectAccessAPI>
class DenseCoeffsBase : public EigenBase<Derived>
{
public:
typedef typename ei_traits<Derived>::StorageKind StorageKind;
typedef typename ei_traits<Derived>::Index Index;
typedef typename ei_traits<Derived>::Scalar Scalar;
typedef typename ei_packet_traits<Scalar>::type PacketScalar;
typedef typename ei_meta_if<ei_has_direct_access<Derived>::ret,
const Scalar&,
typename ei_meta_if<ei_is_arithmetic<Scalar>::ret, Scalar, const Scalar>::ret
>::ret CoeffReturnType;
typedef typename ei_makeconst_return_type<typename ei_packet_traits<Scalar>::type>::type PacketReturnType;
typedef EigenBase<Derived> Base;
using Base::rows;
using Base::cols;
using Base::size;
using Base::derived;
EIGEN_STRONG_INLINE Index rowIndexByOuterInner(Index outer, Index inner) const
{
return int(Derived::RowsAtCompileTime) == 1 ? 0
: int(Derived::ColsAtCompileTime) == 1 ? inner
: int(Derived::Flags)&RowMajorBit ? outer
: inner;
}
EIGEN_STRONG_INLINE Index colIndexByOuterInner(Index outer, Index inner) const
{
return int(Derived::ColsAtCompileTime) == 1 ? 0
: int(Derived::RowsAtCompileTime) == 1 ? inner
: int(Derived::Flags)&RowMajorBit ? inner
: outer;
}
/** Short version: don't use this function, use
* \link operator()(Index,Index) const \endlink instead.
*
* Long version: this function is similar to
* \link operator()(Index,Index) const \endlink, but without the assertion.
* Use this for limiting the performance cost of debugging code when doing
* repeated coefficient access. Only use this when it is guaranteed that the
* parameters \a row and \a col are in range.
*
* If EIGEN_INTERNAL_DEBUGGING is defined, an assertion will be made, making this
* function equivalent to \link operator()(Index,Index) const \endlink.
*
* \sa operator()(Index,Index) const, coeffRef(Index,Index), coeff(Index) const
*/
EIGEN_STRONG_INLINE CoeffReturnType coeff(Index row, Index col) const
{
ei_internal_assert(row >= 0 && row < rows()
&& col >= 0 && col < cols());
return derived().coeff(row, col);
}
EIGEN_STRONG_INLINE CoeffReturnType coeffByOuterInner(Index outer, Index inner) const
{
return coeff(rowIndexByOuterInner(outer, inner),
colIndexByOuterInner(outer, inner));
}
/** \returns the coefficient at given the given row and column.
*
* \sa operator()(Index,Index), operator[](Index)
*/
EIGEN_STRONG_INLINE CoeffReturnType operator()(Index row, Index col) const
{
ei_assert(row >= 0 && row < rows()
&& col >= 0 && col < cols());
return derived().coeff(row, col);
}
/** Short version: don't use this function, use
* \link operator[](Index) const \endlink instead.
*
* Long version: this function is similar to
* \link operator[](Index) const \endlink, but without the assertion.
* Use this for limiting the performance cost of debugging code when doing
* repeated coefficient access. Only use this when it is guaranteed that the
* parameter \a index is in range.
*
* If EIGEN_INTERNAL_DEBUGGING is defined, an assertion will be made, making this
* function equivalent to \link operator[](Index) const \endlink.
*
* \sa operator[](Index) const, coeffRef(Index), coeff(Index,Index) const
*/
EIGEN_STRONG_INLINE CoeffReturnType
coeff(Index index) const
{
ei_internal_assert(index >= 0 && index < size());
return derived().coeff(index);
}
/** \returns the coefficient at given index.
*
* This method is allowed only for vector expressions, and for matrix expressions having the LinearAccessBit.
*
* \sa operator[](Index), operator()(Index,Index) const, x() const, y() const,
* z() const, w() const
*/
EIGEN_STRONG_INLINE CoeffReturnType
operator[](Index index) const
{
EIGEN_STATIC_ASSERT(Derived::IsVectorAtCompileTime,
THE_BRACKET_OPERATOR_IS_ONLY_FOR_VECTORS__USE_THE_PARENTHESIS_OPERATOR_INSTEAD)
ei_assert(index >= 0 && index < size());
return derived().coeff(index);
}
/** \returns the coefficient at given index.
*
* This is synonymous to operator[](Index) const.
*
* This method is allowed only for vector expressions, and for matrix expressions having the LinearAccessBit.
*
* \sa operator[](Index), operator()(Index,Index) const, x() const, y() const,
* z() const, w() const
*/
EIGEN_STRONG_INLINE CoeffReturnType
operator()(Index index) const
{
ei_assert(index >= 0 && index < size());
return derived().coeff(index);
}
/** equivalent to operator[](0). */
EIGEN_STRONG_INLINE CoeffReturnType
x() const { return (*this)[0]; }
/** equivalent to operator[](1). */
EIGEN_STRONG_INLINE CoeffReturnType
y() const { return (*this)[1]; }
/** equivalent to operator[](2). */
EIGEN_STRONG_INLINE CoeffReturnType
z() const { return (*this)[2]; }
/** equivalent to operator[](3). */
EIGEN_STRONG_INLINE CoeffReturnType
w() const { return (*this)[3]; }
/** \returns the packet of coefficients starting at the given row and column. It is your responsibility
* to ensure that a packet really starts there. This method is only available on expressions having the
* PacketAccessBit.
*
* The \a LoadMode parameter may have the value \a Aligned or \a Unaligned. Its effect is to select
* the appropriate vectorization instruction. Aligned access is faster, but is only possible for packets
* starting at an address which is a multiple of the packet size.
*/
template<int LoadMode>
EIGEN_STRONG_INLINE PacketReturnType packet(Index row, Index col) const
{
ei_internal_assert(row >= 0 && row < rows()
&& col >= 0 && col < cols());
return derived().template packet<LoadMode>(row,col);
}
template<int LoadMode>
EIGEN_STRONG_INLINE PacketReturnType packetByOuterInner(Index outer, Index inner) const
{
return packet<LoadMode>(rowIndexByOuterInner(outer, inner),
colIndexByOuterInner(outer, inner));
}
/** \returns the packet of coefficients starting at the given index. It is your responsibility
* to ensure that a packet really starts there. This method is only available on expressions having the
* PacketAccessBit and the LinearAccessBit.
*
* The \a LoadMode parameter may have the value \a Aligned or \a Unaligned. Its effect is to select
* the appropriate vectorization instruction. Aligned access is faster, but is only possible for packets
* starting at an address which is a multiple of the packet size.
*/
template<int LoadMode>
EIGEN_STRONG_INLINE PacketReturnType packet(Index index) const
{
ei_internal_assert(index >= 0 && index < size());
return derived().template packet<LoadMode>(index);
}
protected:
// explanation: DenseBase is doing "using ..." on the methods from DenseCoeffsBase.
// But some methods are only available in the EnableDirectAccessAPI case.
// So we add dummy methods here with these names, so that "using... " doesn't fail.
// It's not private so that the child class DenseBase can access them, and it's not public
// either since it's an implementation detail, so has to be protected.
void coeffRef();
void coeffRefByOuterInner();
void writePacket();
void writePacketByOuterInner();
void copyCoeff();
void copyCoeffByOuterInner();
void copyPacket();
void copyPacketByOuterInner();
void stride();
void innerStride();
void outerStride();
void rowStride();
void colStride();
};
template<typename Derived>
class DenseCoeffsBase<Derived, true> : public DenseCoeffsBase<Derived, false>
{
public:
typedef DenseCoeffsBase<Derived, false> Base;
typedef typename ei_traits<Derived>::StorageKind StorageKind;
typedef typename ei_traits<Derived>::Index Index;
typedef typename ei_traits<Derived>::Scalar Scalar;
typedef typename ei_packet_traits<Scalar>::type PacketScalar;
typedef typename NumTraits<Scalar>::Real RealScalar;
using Base::coeff;
using Base::rows;
using Base::cols;
using Base::size;
using Base::derived;
using Base::rowIndexByOuterInner;
using Base::colIndexByOuterInner;
using Base::operator[];
using Base::operator();
using Base::x;
using Base::y;
using Base::z;
using Base::w;
/** Short version: don't use this function, use
* \link operator()(Index,Index) \endlink instead.
*
* Long version: this function is similar to
* \link operator()(Index,Index) \endlink, but without the assertion.
* Use this for limiting the performance cost of debugging code when doing
* repeated coefficient access. Only use this when it is guaranteed that the
* parameters \a row and \a col are in range.
*
* If EIGEN_INTERNAL_DEBUGGING is defined, an assertion will be made, making this
* function equivalent to \link operator()(Index,Index) \endlink.
*
* \sa operator()(Index,Index), coeff(Index, Index) const, coeffRef(Index)
*/
EIGEN_STRONG_INLINE Scalar& coeffRef(Index row, Index col)
{
ei_internal_assert(row >= 0 && row < rows()
&& col >= 0 && col < cols());
return derived().coeffRef(row, col);
}
EIGEN_STRONG_INLINE Scalar&
coeffRefByOuterInner(Index outer, Index inner)
{
return coeffRef(rowIndexByOuterInner(outer, inner),
colIndexByOuterInner(outer, inner));
}
/** \returns a reference to the coefficient at given the given row and column.
*
* \sa operator[](Index)
*/
EIGEN_STRONG_INLINE Scalar&
operator()(Index row, Index col)
{
ei_assert(row >= 0 && row < rows()
&& col >= 0 && col < cols());
return derived().coeffRef(row, col);
}
/** Short version: don't use this function, use
* \link operator[](Index) \endlink instead.
*
* Long version: this function is similar to
* \link operator[](Index) \endlink, but without the assertion.
* Use this for limiting the performance cost of debugging code when doing
* repeated coefficient access. Only use this when it is guaranteed that the
* parameters \a row and \a col are in range.
*
* If EIGEN_INTERNAL_DEBUGGING is defined, an assertion will be made, making this
* function equivalent to \link operator[](Index) \endlink.
*
* \sa operator[](Index), coeff(Index) const, coeffRef(Index,Index)
*/
EIGEN_STRONG_INLINE Scalar&
coeffRef(Index index)
{
ei_internal_assert(index >= 0 && index < size());
return derived().coeffRef(index);
}
/** \returns a reference to the coefficient at given index.
*
* This method is allowed only for vector expressions, and for matrix expressions having the LinearAccessBit.
*
* \sa operator[](Index) const, operator()(Index,Index), x(), y(), z(), w()
*/
EIGEN_STRONG_INLINE Scalar&
operator[](Index index)
{
EIGEN_STATIC_ASSERT(Derived::IsVectorAtCompileTime,
THE_BRACKET_OPERATOR_IS_ONLY_FOR_VECTORS__USE_THE_PARENTHESIS_OPERATOR_INSTEAD)
ei_assert(index >= 0 && index < size());
return derived().coeffRef(index);
}
/** \returns a reference to the coefficient at given index.
*
* This is synonymous to operator[](Index).
*
* This method is allowed only for vector expressions, and for matrix expressions having the LinearAccessBit.
*
* \sa operator[](Index) const, operator()(Index,Index), x(), y(), z(), w()
*/
EIGEN_STRONG_INLINE Scalar&
operator()(Index index)
{
ei_assert(index >= 0 && index < size());
return derived().coeffRef(index);
}
/** equivalent to operator[](0). */
EIGEN_STRONG_INLINE Scalar&
x() { return (*this)[0]; }
/** equivalent to operator[](1). */
EIGEN_STRONG_INLINE Scalar&
y() { return (*this)[1]; }
/** equivalent to operator[](2). */
EIGEN_STRONG_INLINE Scalar&
z() { return (*this)[2]; }
/** equivalent to operator[](3). */
EIGEN_STRONG_INLINE Scalar&
w() { return (*this)[3]; }
/** Stores the given packet of coefficients, at the given row and column of this expression. It is your responsibility
* to ensure that a packet really starts there. This method is only available on expressions having the
* PacketAccessBit.
*
* The \a LoadMode parameter may have the value \a Aligned or \a Unaligned. Its effect is to select
* the appropriate vectorization instruction. Aligned access is faster, but is only possible for packets
* starting at an address which is a multiple of the packet size.
*/
template<int StoreMode>
EIGEN_STRONG_INLINE void writePacket
(Index row, Index col, const typename ei_packet_traits<Scalar>::type& x)
{
ei_internal_assert(row >= 0 && row < rows()
&& col >= 0 && col < cols());
derived().template writePacket<StoreMode>(row,col,x);
}
template<int StoreMode>
EIGEN_STRONG_INLINE void writePacketByOuterInner
(Index outer, Index inner, const typename ei_packet_traits<Scalar>::type& x)
{
writePacket<StoreMode>(rowIndexByOuterInner(outer, inner),
colIndexByOuterInner(outer, inner),
x);
}
/** Stores the given packet of coefficients, at the given index in this expression. It is your responsibility
* to ensure that a packet really starts there. This method is only available on expressions having the
* PacketAccessBit and the LinearAccessBit.
*
* The \a LoadMode parameter may have the value \a Aligned or \a Unaligned. Its effect is to select
* the appropriate vectorization instruction. Aligned access is faster, but is only possible for packets
* starting at an address which is a multiple of the packet size.
*/
template<int StoreMode>
EIGEN_STRONG_INLINE void writePacket
(Index index, const typename ei_packet_traits<Scalar>::type& x)
{
ei_internal_assert(index >= 0 && index < size());
derived().template writePacket<StoreMode>(index,x);
}
#ifndef EIGEN_PARSED_BY_DOXYGEN
/** \internal Copies the coefficient at position (row,col) of other into *this.
*
* This method is overridden in SwapWrapper, allowing swap() assignments to share 99% of their code
* with usual assignments.
*
* Outside of this internal usage, this method has probably no usefulness. It is hidden in the public API dox.
*/
template<typename OtherDerived>
EIGEN_STRONG_INLINE void copyCoeff(Index row, Index col, const DenseBase<OtherDerived>& other)
{
ei_internal_assert(row >= 0 && row < rows()
&& col >= 0 && col < cols());
derived().coeffRef(row, col) = other.derived().coeff(row, col);
}
/** \internal Copies the coefficient at the given index of other into *this.
*
* This method is overridden in SwapWrapper, allowing swap() assignments to share 99% of their code
* with usual assignments.
*
* Outside of this internal usage, this method has probably no usefulness. It is hidden in the public API dox.
*/
template<typename OtherDerived>
EIGEN_STRONG_INLINE void copyCoeff(Index index, const DenseBase<OtherDerived>& other)
{
ei_internal_assert(index >= 0 && index < size());
derived().coeffRef(index) = other.derived().coeff(index);
}
template<typename OtherDerived>
EIGEN_STRONG_INLINE void copyCoeffByOuterInner(Index outer, Index inner, const DenseBase<OtherDerived>& other)
{
const Index row = rowIndexByOuterInner(outer,inner);
const Index col = colIndexByOuterInner(outer,inner);
// derived() is important here: copyCoeff() may be reimplemented in Derived!
derived().copyCoeff(row, col, other);
}
/** \internal Copies the packet at position (row,col) of other into *this.
*
* This method is overridden in SwapWrapper, allowing swap() assignments to share 99% of their code
* with usual assignments.
*
* Outside of this internal usage, this method has probably no usefulness. It is hidden in the public API dox.
*/
template<typename OtherDerived, int StoreMode, int LoadMode>
EIGEN_STRONG_INLINE void copyPacket(Index row, Index col, const DenseBase<OtherDerived>& other)
{
ei_internal_assert(row >= 0 && row < rows()
&& col >= 0 && col < cols());
derived().template writePacket<StoreMode>(row, col,
other.derived().template packet<LoadMode>(row, col));
}
/** \internal Copies the packet at the given index of other into *this.
*
* This method is overridden in SwapWrapper, allowing swap() assignments to share 99% of their code
* with usual assignments.
*
* Outside of this internal usage, this method has probably no usefulness. It is hidden in the public API dox.
*/
template<typename OtherDerived, int StoreMode, int LoadMode>
EIGEN_STRONG_INLINE void copyPacket(Index index, const DenseBase<OtherDerived>& other)
{
ei_internal_assert(index >= 0 && index < size());
derived().template writePacket<StoreMode>(index,
other.derived().template packet<LoadMode>(index));
}
template<typename OtherDerived, int StoreMode, int LoadMode>
EIGEN_STRONG_INLINE void copyPacketByOuterInner(Index outer, Index inner, const DenseBase<OtherDerived>& other)
{
const Index row = rowIndexByOuterInner(outer,inner);
const Index col = colIndexByOuterInner(outer,inner);
// derived() is important here: copyCoeff() may be reimplemented in Derived!
derived().template copyPacket< OtherDerived, StoreMode, LoadMode>(row, col, other);
}
#endif
/** \returns the pointer increment between two consecutive elements within a slice in the inner direction.
*
* \sa outerStride(), rowStride(), colStride()
*/
inline Index innerStride() const
{
return derived().innerStride();
}
/** \returns the pointer increment between two consecutive inner slices (for example, between two consecutive columns
* in a column-major matrix).
*
* \sa innerStride(), rowStride(), colStride()
*/
inline Index outerStride() const
{
return derived().outerStride();
}
inline Index stride() const
{
return Derived::IsVectorAtCompileTime ? innerStride() : outerStride();
}
/** \returns the pointer increment between two consecutive rows.
*
* \sa innerStride(), outerStride(), colStride()
*/
inline Index rowStride() const
{
return Derived::IsRowMajor ? outerStride() : innerStride();
}
/** \returns the pointer increment between two consecutive columns.
*
* \sa innerStride(), outerStride(), rowStride()
*/
inline Index colStride() const
{
return Derived::IsRowMajor ? innerStride() : outerStride();
}
};
template<typename Derived, bool JustReturnZero>
struct ei_first_aligned_impl
{
inline static typename Derived::Index run(const Derived&)
{ return 0; }
};
template<typename Derived>
struct ei_first_aligned_impl<Derived, false>
{
inline static typename Derived::Index run(const Derived& m)
{
return ei_first_aligned(&m.const_cast_derived().coeffRef(0,0), m.size());
}
};
/** \internal \returns the index of the first element of the array that is well aligned for vectorization.
*
* There is also the variant ei_first_aligned(const Scalar*, Integer) defined in Memory.h. See it for more
* documentation.
*/
template<typename Derived>
inline static typename Derived::Index ei_first_aligned(const Derived& m)
{
return ei_first_aligned_impl
<Derived, (Derived::Flags & AlignedBit) || !(Derived::Flags & DirectAccessBit)>
::run(m);
}
template<typename Derived, bool HasDirectAccess = ei_has_direct_access<Derived>::ret>
struct ei_inner_stride_at_compile_time
{
enum { ret = ei_traits<Derived>::InnerStrideAtCompileTime };
};
template<typename Derived>
struct ei_inner_stride_at_compile_time<Derived, false>
{
enum { ret = 0 };
};
template<typename Derived, bool HasDirectAccess = ei_has_direct_access<Derived>::ret>
struct ei_outer_stride_at_compile_time
{
enum { ret = ei_traits<Derived>::OuterStrideAtCompileTime };
};
template<typename Derived>
struct ei_outer_stride_at_compile_time<Derived, false>
{
enum { ret = 0 };
};
#endif // EIGEN_DENSECOEFFSBASE_H
| 36.808824 | 122 | 0.665734 | [
"vector"
] |
68092d15e12b5ffaaa1f974cf625a073ffe6797a | 37,854 | c | C | kernel/linux-5.4/tools/vm/slabinfo.c | josehu07/SplitFS | d7442fa67a17de7057664f91defbfdbf10dd7f4a | [
"Apache-2.0"
] | 27 | 2021-10-04T18:56:52.000Z | 2022-03-28T08:23:06.000Z | src/linux/tools/vm/slabinfo.c | lukedsmalley/oo-kernel-hacking | 57161ae3e8a780a72b475b3c27fec8deef83b8e1 | [
"MIT"
] | 1 | 2022-01-12T04:05:36.000Z | 2022-01-16T15:48:42.000Z | src/linux/tools/vm/slabinfo.c | lukedsmalley/oo-kernel-hacking | 57161ae3e8a780a72b475b3c27fec8deef83b8e1 | [
"MIT"
] | 6 | 2021-11-02T10:56:19.000Z | 2022-03-06T11:58:20.000Z | // SPDX-License-Identifier: GPL-2.0
/*
* Slabinfo: Tool to get reports about slabs
*
* (C) 2007 sgi, Christoph Lameter
* (C) 2011 Linux Foundation, Christoph Lameter
*
* Compile with:
*
* gcc -o slabinfo slabinfo.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>
#include <strings.h>
#include <string.h>
#include <unistd.h>
#include <stdarg.h>
#include <getopt.h>
#include <regex.h>
#include <errno.h>
#define MAX_SLABS 500
#define MAX_ALIASES 500
#define MAX_NODES 1024
struct slabinfo {
char *name;
int alias;
int refs;
int aliases, align, cache_dma, cpu_slabs, destroy_by_rcu;
unsigned int hwcache_align, object_size, objs_per_slab;
unsigned int sanity_checks, slab_size, store_user, trace;
int order, poison, reclaim_account, red_zone;
unsigned long partial, objects, slabs, objects_partial, objects_total;
unsigned long alloc_fastpath, alloc_slowpath;
unsigned long free_fastpath, free_slowpath;
unsigned long free_frozen, free_add_partial, free_remove_partial;
unsigned long alloc_from_partial, alloc_slab, free_slab, alloc_refill;
unsigned long cpuslab_flush, deactivate_full, deactivate_empty;
unsigned long deactivate_to_head, deactivate_to_tail;
unsigned long deactivate_remote_frees, order_fallback;
unsigned long cmpxchg_double_cpu_fail, cmpxchg_double_fail;
unsigned long alloc_node_mismatch, deactivate_bypass;
unsigned long cpu_partial_alloc, cpu_partial_free;
int numa[MAX_NODES];
int numa_partial[MAX_NODES];
} slabinfo[MAX_SLABS];
struct aliasinfo {
char *name;
char *ref;
struct slabinfo *slab;
} aliasinfo[MAX_ALIASES];
int slabs;
int actual_slabs;
int aliases;
int alias_targets;
int highest_node;
char buffer[4096];
int show_empty;
int show_report;
int show_alias;
int show_slab;
int skip_zero = 1;
int show_numa;
int show_track;
int show_first_alias;
int validate;
int shrink;
int show_inverted;
int show_single_ref;
int show_totals;
int sort_size;
int sort_active;
int set_debug;
int show_ops;
int sort_partial;
int show_activity;
int output_lines = -1;
int sort_loss;
int extended_totals;
int show_bytes;
int unreclaim_only;
/* Debug options */
int sanity;
int redzone;
int poison;
int tracking;
int tracing;
int page_size;
regex_t pattern;
static void fatal(const char *x, ...)
{
va_list ap;
va_start(ap, x);
vfprintf(stderr, x, ap);
va_end(ap);
exit(EXIT_FAILURE);
}
static void usage(void)
{
printf("slabinfo 4/15/2011. (c) 2007 sgi/(c) 2011 Linux Foundation.\n\n"
"slabinfo [-aABDefhilLnoPrsStTUvXz1] [N=K] [-dafzput] [slab-regexp]\n"
"-a|--aliases Show aliases\n"
"-A|--activity Most active slabs first\n"
"-B|--Bytes Show size in bytes\n"
"-D|--display-active Switch line format to activity\n"
"-e|--empty Show empty slabs\n"
"-f|--first-alias Show first alias\n"
"-h|--help Show usage information\n"
"-i|--inverted Inverted list\n"
"-l|--slabs Show slabs\n"
"-L|--Loss Sort by loss\n"
"-n|--numa Show NUMA information\n"
"-N|--lines=K Show the first K slabs\n"
"-o|--ops Show kmem_cache_ops\n"
"-P|--partial Sort by number of partial slabs\n"
"-r|--report Detailed report on single slabs\n"
"-s|--shrink Shrink slabs\n"
"-S|--Size Sort by size\n"
"-t|--tracking Show alloc/free information\n"
"-T|--Totals Show summary information\n"
"-U|--Unreclaim Show unreclaimable slabs only\n"
"-v|--validate Validate slabs\n"
"-X|--Xtotals Show extended summary information\n"
"-z|--zero Include empty slabs\n"
"-1|--1ref Single reference\n"
"\n"
"-d | --debug Switch off all debug options\n"
"-da | --debug=a Switch on all debug options (--debug=FZPU)\n"
"\n"
"-d[afzput] | --debug=[afzput]\n"
" f | F Sanity Checks (SLAB_CONSISTENCY_CHECKS)\n"
" z | Z Redzoning\n"
" p | P Poisoning\n"
" u | U Tracking\n"
" t | T Tracing\n"
"\nSorting options (--Loss, --Size, --Partial) are mutually exclusive\n"
);
}
static unsigned long read_obj(const char *name)
{
FILE *f = fopen(name, "r");
if (!f)
buffer[0] = 0;
else {
if (!fgets(buffer, sizeof(buffer), f))
buffer[0] = 0;
fclose(f);
if (buffer[strlen(buffer)] == '\n')
buffer[strlen(buffer)] = 0;
}
return strlen(buffer);
}
/*
* Get the contents of an attribute
*/
static unsigned long get_obj(const char *name)
{
if (!read_obj(name))
return 0;
return atol(buffer);
}
static unsigned long get_obj_and_str(const char *name, char **x)
{
unsigned long result = 0;
char *p;
*x = NULL;
if (!read_obj(name)) {
x = NULL;
return 0;
}
result = strtoul(buffer, &p, 10);
while (*p == ' ')
p++;
if (*p)
*x = strdup(p);
return result;
}
static void set_obj(struct slabinfo *s, const char *name, int n)
{
char x[100];
FILE *f;
snprintf(x, 100, "%s/%s", s->name, name);
f = fopen(x, "w");
if (!f)
fatal("Cannot write to %s\n", x);
fprintf(f, "%d\n", n);
fclose(f);
}
static unsigned long read_slab_obj(struct slabinfo *s, const char *name)
{
char x[100];
FILE *f;
size_t l;
snprintf(x, 100, "%s/%s", s->name, name);
f = fopen(x, "r");
if (!f) {
buffer[0] = 0;
l = 0;
} else {
l = fread(buffer, 1, sizeof(buffer), f);
buffer[l] = 0;
fclose(f);
}
return l;
}
/*
* Put a size string together
*/
static int store_size(char *buffer, unsigned long value)
{
unsigned long divisor = 1;
char trailer = 0;
int n;
if (!show_bytes) {
if (value > 1000000000UL) {
divisor = 100000000UL;
trailer = 'G';
} else if (value > 1000000UL) {
divisor = 100000UL;
trailer = 'M';
} else if (value > 1000UL) {
divisor = 100;
trailer = 'K';
}
}
value /= divisor;
n = sprintf(buffer, "%ld",value);
if (trailer) {
buffer[n] = trailer;
n++;
buffer[n] = 0;
}
if (divisor != 1) {
memmove(buffer + n - 2, buffer + n - 3, 4);
buffer[n-2] = '.';
n++;
}
return n;
}
static void decode_numa_list(int *numa, char *t)
{
int node;
int nr;
memset(numa, 0, MAX_NODES * sizeof(int));
if (!t)
return;
while (*t == 'N') {
t++;
node = strtoul(t, &t, 10);
if (*t == '=') {
t++;
nr = strtoul(t, &t, 10);
numa[node] = nr;
if (node > highest_node)
highest_node = node;
}
while (*t == ' ')
t++;
}
}
static void slab_validate(struct slabinfo *s)
{
if (strcmp(s->name, "*") == 0)
return;
set_obj(s, "validate", 1);
}
static void slab_shrink(struct slabinfo *s)
{
if (strcmp(s->name, "*") == 0)
return;
set_obj(s, "shrink", 1);
}
int line = 0;
static void first_line(void)
{
if (show_activity)
printf("Name Objects Alloc Free"
" %%Fast Fallb O CmpX UL\n");
else
printf("Name Objects Objsize %s "
"Slabs/Part/Cpu O/S O %%Fr %%Ef Flg\n",
sort_loss ? " Loss" : "Space");
}
/*
* Find the shortest alias of a slab
*/
static struct aliasinfo *find_one_alias(struct slabinfo *find)
{
struct aliasinfo *a;
struct aliasinfo *best = NULL;
for(a = aliasinfo;a < aliasinfo + aliases; a++) {
if (a->slab == find &&
(!best || strlen(best->name) < strlen(a->name))) {
best = a;
if (strncmp(a->name,"kmall", 5) == 0)
return best;
}
}
return best;
}
static unsigned long slab_size(struct slabinfo *s)
{
return s->slabs * (page_size << s->order);
}
static unsigned long slab_activity(struct slabinfo *s)
{
return s->alloc_fastpath + s->free_fastpath +
s->alloc_slowpath + s->free_slowpath;
}
static unsigned long slab_waste(struct slabinfo *s)
{
return slab_size(s) - s->objects * s->object_size;
}
static void slab_numa(struct slabinfo *s, int mode)
{
int node;
if (strcmp(s->name, "*") == 0)
return;
if (!highest_node) {
printf("\n%s: No NUMA information available.\n", s->name);
return;
}
if (skip_zero && !s->slabs)
return;
if (!line) {
printf("\n%-21s:", mode ? "NUMA nodes" : "Slab");
for(node = 0; node <= highest_node; node++)
printf(" %4d", node);
printf("\n----------------------");
for(node = 0; node <= highest_node; node++)
printf("-----");
printf("\n");
}
printf("%-21s ", mode ? "All slabs" : s->name);
for(node = 0; node <= highest_node; node++) {
char b[20];
store_size(b, s->numa[node]);
printf(" %4s", b);
}
printf("\n");
if (mode) {
printf("%-21s ", "Partial slabs");
for(node = 0; node <= highest_node; node++) {
char b[20];
store_size(b, s->numa_partial[node]);
printf(" %4s", b);
}
printf("\n");
}
line++;
}
static void show_tracking(struct slabinfo *s)
{
printf("\n%s: Kernel object allocation\n", s->name);
printf("-----------------------------------------------------------------------\n");
if (read_slab_obj(s, "alloc_calls"))
printf("%s", buffer);
else
printf("No Data\n");
printf("\n%s: Kernel object freeing\n", s->name);
printf("------------------------------------------------------------------------\n");
if (read_slab_obj(s, "free_calls"))
printf("%s", buffer);
else
printf("No Data\n");
}
static void ops(struct slabinfo *s)
{
if (strcmp(s->name, "*") == 0)
return;
if (read_slab_obj(s, "ops")) {
printf("\n%s: kmem_cache operations\n", s->name);
printf("--------------------------------------------\n");
printf("%s", buffer);
} else
printf("\n%s has no kmem_cache operations\n", s->name);
}
static const char *onoff(int x)
{
if (x)
return "On ";
return "Off";
}
static void slab_stats(struct slabinfo *s)
{
unsigned long total_alloc;
unsigned long total_free;
unsigned long total;
if (!s->alloc_slab)
return;
total_alloc = s->alloc_fastpath + s->alloc_slowpath;
total_free = s->free_fastpath + s->free_slowpath;
if (!total_alloc)
return;
printf("\n");
printf("Slab Perf Counter Alloc Free %%Al %%Fr\n");
printf("--------------------------------------------------\n");
printf("Fastpath %8lu %8lu %3lu %3lu\n",
s->alloc_fastpath, s->free_fastpath,
s->alloc_fastpath * 100 / total_alloc,
total_free ? s->free_fastpath * 100 / total_free : 0);
printf("Slowpath %8lu %8lu %3lu %3lu\n",
total_alloc - s->alloc_fastpath, s->free_slowpath,
(total_alloc - s->alloc_fastpath) * 100 / total_alloc,
total_free ? s->free_slowpath * 100 / total_free : 0);
printf("Page Alloc %8lu %8lu %3lu %3lu\n",
s->alloc_slab, s->free_slab,
s->alloc_slab * 100 / total_alloc,
total_free ? s->free_slab * 100 / total_free : 0);
printf("Add partial %8lu %8lu %3lu %3lu\n",
s->deactivate_to_head + s->deactivate_to_tail,
s->free_add_partial,
(s->deactivate_to_head + s->deactivate_to_tail) * 100 / total_alloc,
total_free ? s->free_add_partial * 100 / total_free : 0);
printf("Remove partial %8lu %8lu %3lu %3lu\n",
s->alloc_from_partial, s->free_remove_partial,
s->alloc_from_partial * 100 / total_alloc,
total_free ? s->free_remove_partial * 100 / total_free : 0);
printf("Cpu partial list %8lu %8lu %3lu %3lu\n",
s->cpu_partial_alloc, s->cpu_partial_free,
s->cpu_partial_alloc * 100 / total_alloc,
total_free ? s->cpu_partial_free * 100 / total_free : 0);
printf("RemoteObj/SlabFrozen %8lu %8lu %3lu %3lu\n",
s->deactivate_remote_frees, s->free_frozen,
s->deactivate_remote_frees * 100 / total_alloc,
total_free ? s->free_frozen * 100 / total_free : 0);
printf("Total %8lu %8lu\n\n", total_alloc, total_free);
if (s->cpuslab_flush)
printf("Flushes %8lu\n", s->cpuslab_flush);
total = s->deactivate_full + s->deactivate_empty +
s->deactivate_to_head + s->deactivate_to_tail + s->deactivate_bypass;
if (total) {
printf("\nSlab Deactivation Occurrences %%\n");
printf("-------------------------------------------------\n");
printf("Slab full %7lu %3lu%%\n",
s->deactivate_full, (s->deactivate_full * 100) / total);
printf("Slab empty %7lu %3lu%%\n",
s->deactivate_empty, (s->deactivate_empty * 100) / total);
printf("Moved to head of partial list %7lu %3lu%%\n",
s->deactivate_to_head, (s->deactivate_to_head * 100) / total);
printf("Moved to tail of partial list %7lu %3lu%%\n",
s->deactivate_to_tail, (s->deactivate_to_tail * 100) / total);
printf("Deactivation bypass %7lu %3lu%%\n",
s->deactivate_bypass, (s->deactivate_bypass * 100) / total);
printf("Refilled from foreign frees %7lu %3lu%%\n",
s->alloc_refill, (s->alloc_refill * 100) / total);
printf("Node mismatch %7lu %3lu%%\n",
s->alloc_node_mismatch, (s->alloc_node_mismatch * 100) / total);
}
if (s->cmpxchg_double_fail || s->cmpxchg_double_cpu_fail) {
printf("\nCmpxchg_double Looping\n------------------------\n");
printf("Locked Cmpxchg Double redos %lu\nUnlocked Cmpxchg Double redos %lu\n",
s->cmpxchg_double_fail, s->cmpxchg_double_cpu_fail);
}
}
static void report(struct slabinfo *s)
{
if (strcmp(s->name, "*") == 0)
return;
printf("\nSlabcache: %-15s Aliases: %2d Order : %2d Objects: %lu\n",
s->name, s->aliases, s->order, s->objects);
if (s->hwcache_align)
printf("** Hardware cacheline aligned\n");
if (s->cache_dma)
printf("** Memory is allocated in a special DMA zone\n");
if (s->destroy_by_rcu)
printf("** Slabs are destroyed via RCU\n");
if (s->reclaim_account)
printf("** Reclaim accounting active\n");
printf("\nSizes (bytes) Slabs Debug Memory\n");
printf("------------------------------------------------------------------------\n");
printf("Object : %7d Total : %7ld Sanity Checks : %s Total: %7ld\n",
s->object_size, s->slabs, onoff(s->sanity_checks),
s->slabs * (page_size << s->order));
printf("SlabObj: %7d Full : %7ld Redzoning : %s Used : %7ld\n",
s->slab_size, s->slabs - s->partial - s->cpu_slabs,
onoff(s->red_zone), s->objects * s->object_size);
printf("SlabSiz: %7d Partial: %7ld Poisoning : %s Loss : %7ld\n",
page_size << s->order, s->partial, onoff(s->poison),
s->slabs * (page_size << s->order) - s->objects * s->object_size);
printf("Loss : %7d CpuSlab: %7d Tracking : %s Lalig: %7ld\n",
s->slab_size - s->object_size, s->cpu_slabs, onoff(s->store_user),
(s->slab_size - s->object_size) * s->objects);
printf("Align : %7d Objects: %7d Tracing : %s Lpadd: %7ld\n",
s->align, s->objs_per_slab, onoff(s->trace),
((page_size << s->order) - s->objs_per_slab * s->slab_size) *
s->slabs);
ops(s);
show_tracking(s);
slab_numa(s, 1);
slab_stats(s);
}
static void slabcache(struct slabinfo *s)
{
char size_str[20];
char dist_str[40];
char flags[20];
char *p = flags;
if (strcmp(s->name, "*") == 0)
return;
if (unreclaim_only && s->reclaim_account)
return;
if (actual_slabs == 1) {
report(s);
return;
}
if (skip_zero && !show_empty && !s->slabs)
return;
if (show_empty && s->slabs)
return;
if (sort_loss == 0)
store_size(size_str, slab_size(s));
else
store_size(size_str, slab_waste(s));
snprintf(dist_str, 40, "%lu/%lu/%d", s->slabs - s->cpu_slabs,
s->partial, s->cpu_slabs);
if (!line++)
first_line();
if (s->aliases)
*p++ = '*';
if (s->cache_dma)
*p++ = 'd';
if (s->hwcache_align)
*p++ = 'A';
if (s->poison)
*p++ = 'P';
if (s->reclaim_account)
*p++ = 'a';
if (s->red_zone)
*p++ = 'Z';
if (s->sanity_checks)
*p++ = 'F';
if (s->store_user)
*p++ = 'U';
if (s->trace)
*p++ = 'T';
*p = 0;
if (show_activity) {
unsigned long total_alloc;
unsigned long total_free;
total_alloc = s->alloc_fastpath + s->alloc_slowpath;
total_free = s->free_fastpath + s->free_slowpath;
printf("%-21s %8ld %10ld %10ld %3ld %3ld %5ld %1d %4ld %4ld\n",
s->name, s->objects,
total_alloc, total_free,
total_alloc ? (s->alloc_fastpath * 100 / total_alloc) : 0,
total_free ? (s->free_fastpath * 100 / total_free) : 0,
s->order_fallback, s->order, s->cmpxchg_double_fail,
s->cmpxchg_double_cpu_fail);
} else {
printf("%-21s %8ld %7d %15s %14s %4d %1d %3ld %3ld %s\n",
s->name, s->objects, s->object_size, size_str, dist_str,
s->objs_per_slab, s->order,
s->slabs ? (s->partial * 100) / s->slabs : 100,
s->slabs ? (s->objects * s->object_size * 100) /
(s->slabs * (page_size << s->order)) : 100,
flags);
}
}
/*
* Analyze debug options. Return false if something is amiss.
*/
static int debug_opt_scan(char *opt)
{
if (!opt || !opt[0] || strcmp(opt, "-") == 0)
return 1;
if (strcasecmp(opt, "a") == 0) {
sanity = 1;
poison = 1;
redzone = 1;
tracking = 1;
return 1;
}
for ( ; *opt; opt++)
switch (*opt) {
case 'F' : case 'f':
if (sanity)
return 0;
sanity = 1;
break;
case 'P' : case 'p':
if (poison)
return 0;
poison = 1;
break;
case 'Z' : case 'z':
if (redzone)
return 0;
redzone = 1;
break;
case 'U' : case 'u':
if (tracking)
return 0;
tracking = 1;
break;
case 'T' : case 't':
if (tracing)
return 0;
tracing = 1;
break;
default:
return 0;
}
return 1;
}
static int slab_empty(struct slabinfo *s)
{
if (s->objects > 0)
return 0;
/*
* We may still have slabs even if there are no objects. Shrinking will
* remove them.
*/
if (s->slabs != 0)
set_obj(s, "shrink", 1);
return 1;
}
static void slab_debug(struct slabinfo *s)
{
if (strcmp(s->name, "*") == 0)
return;
if (sanity && !s->sanity_checks) {
set_obj(s, "sanity", 1);
}
if (!sanity && s->sanity_checks) {
if (slab_empty(s))
set_obj(s, "sanity", 0);
else
fprintf(stderr, "%s not empty cannot disable sanity checks\n", s->name);
}
if (redzone && !s->red_zone) {
if (slab_empty(s))
set_obj(s, "red_zone", 1);
else
fprintf(stderr, "%s not empty cannot enable redzoning\n", s->name);
}
if (!redzone && s->red_zone) {
if (slab_empty(s))
set_obj(s, "red_zone", 0);
else
fprintf(stderr, "%s not empty cannot disable redzoning\n", s->name);
}
if (poison && !s->poison) {
if (slab_empty(s))
set_obj(s, "poison", 1);
else
fprintf(stderr, "%s not empty cannot enable poisoning\n", s->name);
}
if (!poison && s->poison) {
if (slab_empty(s))
set_obj(s, "poison", 0);
else
fprintf(stderr, "%s not empty cannot disable poisoning\n", s->name);
}
if (tracking && !s->store_user) {
if (slab_empty(s))
set_obj(s, "store_user", 1);
else
fprintf(stderr, "%s not empty cannot enable tracking\n", s->name);
}
if (!tracking && s->store_user) {
if (slab_empty(s))
set_obj(s, "store_user", 0);
else
fprintf(stderr, "%s not empty cannot disable tracking\n", s->name);
}
if (tracing && !s->trace) {
if (slabs == 1)
set_obj(s, "trace", 1);
else
fprintf(stderr, "%s can only enable trace for one slab at a time\n", s->name);
}
if (!tracing && s->trace)
set_obj(s, "trace", 1);
}
static void totals(void)
{
struct slabinfo *s;
int used_slabs = 0;
char b1[20], b2[20], b3[20], b4[20];
unsigned long long max = 1ULL << 63;
/* Object size */
unsigned long long min_objsize = max, max_objsize = 0, avg_objsize;
/* Number of partial slabs in a slabcache */
unsigned long long min_partial = max, max_partial = 0,
avg_partial, total_partial = 0;
/* Number of slabs in a slab cache */
unsigned long long min_slabs = max, max_slabs = 0,
avg_slabs, total_slabs = 0;
/* Size of the whole slab */
unsigned long long min_size = max, max_size = 0,
avg_size, total_size = 0;
/* Bytes used for object storage in a slab */
unsigned long long min_used = max, max_used = 0,
avg_used, total_used = 0;
/* Waste: Bytes used for alignment and padding */
unsigned long long min_waste = max, max_waste = 0,
avg_waste, total_waste = 0;
/* Number of objects in a slab */
unsigned long long min_objects = max, max_objects = 0,
avg_objects, total_objects = 0;
/* Waste per object */
unsigned long long min_objwaste = max,
max_objwaste = 0, avg_objwaste,
total_objwaste = 0;
/* Memory per object */
unsigned long long min_memobj = max,
max_memobj = 0, avg_memobj,
total_objsize = 0;
/* Percentage of partial slabs per slab */
unsigned long min_ppart = 100, max_ppart = 0,
avg_ppart, total_ppart = 0;
/* Number of objects in partial slabs */
unsigned long min_partobj = max, max_partobj = 0,
avg_partobj, total_partobj = 0;
/* Percentage of partial objects of all objects in a slab */
unsigned long min_ppartobj = 100, max_ppartobj = 0,
avg_ppartobj, total_ppartobj = 0;
for (s = slabinfo; s < slabinfo + slabs; s++) {
unsigned long long size;
unsigned long used;
unsigned long long wasted;
unsigned long long objwaste;
unsigned long percentage_partial_slabs;
unsigned long percentage_partial_objs;
if (!s->slabs || !s->objects)
continue;
used_slabs++;
size = slab_size(s);
used = s->objects * s->object_size;
wasted = size - used;
objwaste = s->slab_size - s->object_size;
percentage_partial_slabs = s->partial * 100 / s->slabs;
if (percentage_partial_slabs > 100)
percentage_partial_slabs = 100;
percentage_partial_objs = s->objects_partial * 100
/ s->objects;
if (percentage_partial_objs > 100)
percentage_partial_objs = 100;
if (s->object_size < min_objsize)
min_objsize = s->object_size;
if (s->partial < min_partial)
min_partial = s->partial;
if (s->slabs < min_slabs)
min_slabs = s->slabs;
if (size < min_size)
min_size = size;
if (wasted < min_waste)
min_waste = wasted;
if (objwaste < min_objwaste)
min_objwaste = objwaste;
if (s->objects < min_objects)
min_objects = s->objects;
if (used < min_used)
min_used = used;
if (s->objects_partial < min_partobj)
min_partobj = s->objects_partial;
if (percentage_partial_slabs < min_ppart)
min_ppart = percentage_partial_slabs;
if (percentage_partial_objs < min_ppartobj)
min_ppartobj = percentage_partial_objs;
if (s->slab_size < min_memobj)
min_memobj = s->slab_size;
if (s->object_size > max_objsize)
max_objsize = s->object_size;
if (s->partial > max_partial)
max_partial = s->partial;
if (s->slabs > max_slabs)
max_slabs = s->slabs;
if (size > max_size)
max_size = size;
if (wasted > max_waste)
max_waste = wasted;
if (objwaste > max_objwaste)
max_objwaste = objwaste;
if (s->objects > max_objects)
max_objects = s->objects;
if (used > max_used)
max_used = used;
if (s->objects_partial > max_partobj)
max_partobj = s->objects_partial;
if (percentage_partial_slabs > max_ppart)
max_ppart = percentage_partial_slabs;
if (percentage_partial_objs > max_ppartobj)
max_ppartobj = percentage_partial_objs;
if (s->slab_size > max_memobj)
max_memobj = s->slab_size;
total_partial += s->partial;
total_slabs += s->slabs;
total_size += size;
total_waste += wasted;
total_objects += s->objects;
total_used += used;
total_partobj += s->objects_partial;
total_ppart += percentage_partial_slabs;
total_ppartobj += percentage_partial_objs;
total_objwaste += s->objects * objwaste;
total_objsize += s->objects * s->slab_size;
}
if (!total_objects) {
printf("No objects\n");
return;
}
if (!used_slabs) {
printf("No slabs\n");
return;
}
/* Per slab averages */
avg_partial = total_partial / used_slabs;
avg_slabs = total_slabs / used_slabs;
avg_size = total_size / used_slabs;
avg_waste = total_waste / used_slabs;
avg_objects = total_objects / used_slabs;
avg_used = total_used / used_slabs;
avg_partobj = total_partobj / used_slabs;
avg_ppart = total_ppart / used_slabs;
avg_ppartobj = total_ppartobj / used_slabs;
/* Per object object sizes */
avg_objsize = total_used / total_objects;
avg_objwaste = total_objwaste / total_objects;
avg_partobj = total_partobj * 100 / total_objects;
avg_memobj = total_objsize / total_objects;
printf("Slabcache Totals\n");
printf("----------------\n");
printf("Slabcaches : %15d Aliases : %11d->%-3d Active: %3d\n",
slabs, aliases, alias_targets, used_slabs);
store_size(b1, total_size);store_size(b2, total_waste);
store_size(b3, total_waste * 100 / total_used);
printf("Memory used: %15s # Loss : %15s MRatio:%6s%%\n", b1, b2, b3);
store_size(b1, total_objects);store_size(b2, total_partobj);
store_size(b3, total_partobj * 100 / total_objects);
printf("# Objects : %15s # PartObj: %15s ORatio:%6s%%\n", b1, b2, b3);
printf("\n");
printf("Per Cache Average "
"Min Max Total\n");
printf("---------------------------------------"
"-------------------------------------\n");
store_size(b1, avg_objects);store_size(b2, min_objects);
store_size(b3, max_objects);store_size(b4, total_objects);
printf("#Objects %15s %15s %15s %15s\n",
b1, b2, b3, b4);
store_size(b1, avg_slabs);store_size(b2, min_slabs);
store_size(b3, max_slabs);store_size(b4, total_slabs);
printf("#Slabs %15s %15s %15s %15s\n",
b1, b2, b3, b4);
store_size(b1, avg_partial);store_size(b2, min_partial);
store_size(b3, max_partial);store_size(b4, total_partial);
printf("#PartSlab %15s %15s %15s %15s\n",
b1, b2, b3, b4);
store_size(b1, avg_ppart);store_size(b2, min_ppart);
store_size(b3, max_ppart);
store_size(b4, total_partial * 100 / total_slabs);
printf("%%PartSlab%15s%% %15s%% %15s%% %15s%%\n",
b1, b2, b3, b4);
store_size(b1, avg_partobj);store_size(b2, min_partobj);
store_size(b3, max_partobj);
store_size(b4, total_partobj);
printf("PartObjs %15s %15s %15s %15s\n",
b1, b2, b3, b4);
store_size(b1, avg_ppartobj);store_size(b2, min_ppartobj);
store_size(b3, max_ppartobj);
store_size(b4, total_partobj * 100 / total_objects);
printf("%% PartObj%15s%% %15s%% %15s%% %15s%%\n",
b1, b2, b3, b4);
store_size(b1, avg_size);store_size(b2, min_size);
store_size(b3, max_size);store_size(b4, total_size);
printf("Memory %15s %15s %15s %15s\n",
b1, b2, b3, b4);
store_size(b1, avg_used);store_size(b2, min_used);
store_size(b3, max_used);store_size(b4, total_used);
printf("Used %15s %15s %15s %15s\n",
b1, b2, b3, b4);
store_size(b1, avg_waste);store_size(b2, min_waste);
store_size(b3, max_waste);store_size(b4, total_waste);
printf("Loss %15s %15s %15s %15s\n",
b1, b2, b3, b4);
printf("\n");
printf("Per Object Average "
"Min Max\n");
printf("---------------------------------------"
"--------------------\n");
store_size(b1, avg_memobj);store_size(b2, min_memobj);
store_size(b3, max_memobj);
printf("Memory %15s %15s %15s\n",
b1, b2, b3);
store_size(b1, avg_objsize);store_size(b2, min_objsize);
store_size(b3, max_objsize);
printf("User %15s %15s %15s\n",
b1, b2, b3);
store_size(b1, avg_objwaste);store_size(b2, min_objwaste);
store_size(b3, max_objwaste);
printf("Loss %15s %15s %15s\n",
b1, b2, b3);
}
static void sort_slabs(void)
{
struct slabinfo *s1,*s2;
for (s1 = slabinfo; s1 < slabinfo + slabs; s1++) {
for (s2 = s1 + 1; s2 < slabinfo + slabs; s2++) {
int result;
if (sort_size)
result = slab_size(s1) < slab_size(s2);
else if (sort_active)
result = slab_activity(s1) < slab_activity(s2);
else if (sort_loss)
result = slab_waste(s1) < slab_waste(s2);
else if (sort_partial)
result = s1->partial < s2->partial;
else
result = strcasecmp(s1->name, s2->name);
if (show_inverted)
result = -result;
if (result > 0) {
struct slabinfo t;
memcpy(&t, s1, sizeof(struct slabinfo));
memcpy(s1, s2, sizeof(struct slabinfo));
memcpy(s2, &t, sizeof(struct slabinfo));
}
}
}
}
static void sort_aliases(void)
{
struct aliasinfo *a1,*a2;
for (a1 = aliasinfo; a1 < aliasinfo + aliases; a1++) {
for (a2 = a1 + 1; a2 < aliasinfo + aliases; a2++) {
char *n1, *n2;
n1 = a1->name;
n2 = a2->name;
if (show_alias && !show_inverted) {
n1 = a1->ref;
n2 = a2->ref;
}
if (strcasecmp(n1, n2) > 0) {
struct aliasinfo t;
memcpy(&t, a1, sizeof(struct aliasinfo));
memcpy(a1, a2, sizeof(struct aliasinfo));
memcpy(a2, &t, sizeof(struct aliasinfo));
}
}
}
}
static void link_slabs(void)
{
struct aliasinfo *a;
struct slabinfo *s;
for (a = aliasinfo; a < aliasinfo + aliases; a++) {
for (s = slabinfo; s < slabinfo + slabs; s++)
if (strcmp(a->ref, s->name) == 0) {
a->slab = s;
s->refs++;
break;
}
if (s == slabinfo + slabs)
fatal("Unresolved alias %s\n", a->ref);
}
}
static void alias(void)
{
struct aliasinfo *a;
char *active = NULL;
sort_aliases();
link_slabs();
for(a = aliasinfo; a < aliasinfo + aliases; a++) {
if (!show_single_ref && a->slab->refs == 1)
continue;
if (!show_inverted) {
if (active) {
if (strcmp(a->slab->name, active) == 0) {
printf(" %s", a->name);
continue;
}
}
printf("\n%-12s <- %s", a->slab->name, a->name);
active = a->slab->name;
}
else
printf("%-15s -> %s\n", a->name, a->slab->name);
}
if (active)
printf("\n");
}
static void rename_slabs(void)
{
struct slabinfo *s;
struct aliasinfo *a;
for (s = slabinfo; s < slabinfo + slabs; s++) {
if (*s->name != ':')
continue;
if (s->refs > 1 && !show_first_alias)
continue;
a = find_one_alias(s);
if (a)
s->name = a->name;
else {
s->name = "*";
actual_slabs--;
}
}
}
static int slab_mismatch(char *slab)
{
return regexec(&pattern, slab, 0, NULL, 0);
}
static void read_slab_dir(void)
{
DIR *dir;
struct dirent *de;
struct slabinfo *slab = slabinfo;
struct aliasinfo *alias = aliasinfo;
char *p;
char *t;
int count;
if (chdir("/sys/kernel/slab") && chdir("/sys/slab"))
fatal("SYSFS support for SLUB not active\n");
dir = opendir(".");
while ((de = readdir(dir))) {
if (de->d_name[0] == '.' ||
(de->d_name[0] != ':' && slab_mismatch(de->d_name)))
continue;
switch (de->d_type) {
case DT_LNK:
alias->name = strdup(de->d_name);
count = readlink(de->d_name, buffer, sizeof(buffer)-1);
if (count < 0)
fatal("Cannot read symlink %s\n", de->d_name);
buffer[count] = 0;
p = buffer + count;
while (p > buffer && p[-1] != '/')
p--;
alias->ref = strdup(p);
alias++;
break;
case DT_DIR:
if (chdir(de->d_name))
fatal("Unable to access slab %s\n", slab->name);
slab->name = strdup(de->d_name);
slab->alias = 0;
slab->refs = 0;
slab->aliases = get_obj("aliases");
slab->align = get_obj("align");
slab->cache_dma = get_obj("cache_dma");
slab->cpu_slabs = get_obj("cpu_slabs");
slab->destroy_by_rcu = get_obj("destroy_by_rcu");
slab->hwcache_align = get_obj("hwcache_align");
slab->object_size = get_obj("object_size");
slab->objects = get_obj("objects");
slab->objects_partial = get_obj("objects_partial");
slab->objects_total = get_obj("objects_total");
slab->objs_per_slab = get_obj("objs_per_slab");
slab->order = get_obj("order");
slab->partial = get_obj("partial");
slab->partial = get_obj_and_str("partial", &t);
decode_numa_list(slab->numa_partial, t);
free(t);
slab->poison = get_obj("poison");
slab->reclaim_account = get_obj("reclaim_account");
slab->red_zone = get_obj("red_zone");
slab->sanity_checks = get_obj("sanity_checks");
slab->slab_size = get_obj("slab_size");
slab->slabs = get_obj_and_str("slabs", &t);
decode_numa_list(slab->numa, t);
free(t);
slab->store_user = get_obj("store_user");
slab->trace = get_obj("trace");
slab->alloc_fastpath = get_obj("alloc_fastpath");
slab->alloc_slowpath = get_obj("alloc_slowpath");
slab->free_fastpath = get_obj("free_fastpath");
slab->free_slowpath = get_obj("free_slowpath");
slab->free_frozen= get_obj("free_frozen");
slab->free_add_partial = get_obj("free_add_partial");
slab->free_remove_partial = get_obj("free_remove_partial");
slab->alloc_from_partial = get_obj("alloc_from_partial");
slab->alloc_slab = get_obj("alloc_slab");
slab->alloc_refill = get_obj("alloc_refill");
slab->free_slab = get_obj("free_slab");
slab->cpuslab_flush = get_obj("cpuslab_flush");
slab->deactivate_full = get_obj("deactivate_full");
slab->deactivate_empty = get_obj("deactivate_empty");
slab->deactivate_to_head = get_obj("deactivate_to_head");
slab->deactivate_to_tail = get_obj("deactivate_to_tail");
slab->deactivate_remote_frees = get_obj("deactivate_remote_frees");
slab->order_fallback = get_obj("order_fallback");
slab->cmpxchg_double_cpu_fail = get_obj("cmpxchg_double_cpu_fail");
slab->cmpxchg_double_fail = get_obj("cmpxchg_double_fail");
slab->cpu_partial_alloc = get_obj("cpu_partial_alloc");
slab->cpu_partial_free = get_obj("cpu_partial_free");
slab->alloc_node_mismatch = get_obj("alloc_node_mismatch");
slab->deactivate_bypass = get_obj("deactivate_bypass");
chdir("..");
if (slab->name[0] == ':')
alias_targets++;
slab++;
break;
default :
fatal("Unknown file type %lx\n", de->d_type);
}
}
closedir(dir);
slabs = slab - slabinfo;
actual_slabs = slabs;
aliases = alias - aliasinfo;
if (slabs > MAX_SLABS)
fatal("Too many slabs\n");
if (aliases > MAX_ALIASES)
fatal("Too many aliases\n");
}
static void output_slabs(void)
{
struct slabinfo *slab;
int lines = output_lines;
for (slab = slabinfo; (slab < slabinfo + slabs) &&
lines != 0; slab++) {
if (slab->alias)
continue;
if (lines != -1)
lines--;
if (show_numa)
slab_numa(slab, 0);
else if (show_track)
show_tracking(slab);
else if (validate)
slab_validate(slab);
else if (shrink)
slab_shrink(slab);
else if (set_debug)
slab_debug(slab);
else if (show_ops)
ops(slab);
else if (show_slab)
slabcache(slab);
else if (show_report)
report(slab);
}
}
static void _xtotals(char *heading, char *underline,
int loss, int size, int partial)
{
printf("%s%s", heading, underline);
line = 0;
sort_loss = loss;
sort_size = size;
sort_partial = partial;
sort_slabs();
output_slabs();
}
static void xtotals(void)
{
char *heading, *underline;
totals();
link_slabs();
rename_slabs();
heading = "\nSlabs sorted by size\n";
underline = "--------------------\n";
_xtotals(heading, underline, 0, 1, 0);
heading = "\nSlabs sorted by loss\n";
underline = "--------------------\n";
_xtotals(heading, underline, 1, 0, 0);
heading = "\nSlabs sorted by number of partial slabs\n";
underline = "---------------------------------------\n";
_xtotals(heading, underline, 0, 0, 1);
printf("\n");
}
struct option opts[] = {
{ "aliases", no_argument, NULL, 'a' },
{ "activity", no_argument, NULL, 'A' },
{ "Bytes", no_argument, NULL, 'B'},
{ "debug", optional_argument, NULL, 'd' },
{ "display-activity", no_argument, NULL, 'D' },
{ "empty", no_argument, NULL, 'e' },
{ "first-alias", no_argument, NULL, 'f' },
{ "help", no_argument, NULL, 'h' },
{ "inverted", no_argument, NULL, 'i'},
{ "slabs", no_argument, NULL, 'l' },
{ "Loss", no_argument, NULL, 'L'},
{ "numa", no_argument, NULL, 'n' },
{ "lines", required_argument, NULL, 'N'},
{ "ops", no_argument, NULL, 'o' },
{ "partial", no_argument, NULL, 'p'},
{ "report", no_argument, NULL, 'r' },
{ "shrink", no_argument, NULL, 's' },
{ "Size", no_argument, NULL, 'S'},
{ "tracking", no_argument, NULL, 't'},
{ "Totals", no_argument, NULL, 'T'},
{ "Unreclaim", no_argument, NULL, 'U'},
{ "validate", no_argument, NULL, 'v' },
{ "Xtotals", no_argument, NULL, 'X'},
{ "zero", no_argument, NULL, 'z' },
{ "1ref", no_argument, NULL, '1'},
{ NULL, 0, NULL, 0 }
};
int main(int argc, char *argv[])
{
int c;
int err;
char *pattern_source;
page_size = getpagesize();
while ((c = getopt_long(argc, argv, "aABd::DefhilLnN:oPrsStTUvXz1",
opts, NULL)) != -1)
switch (c) {
case 'a':
show_alias = 1;
break;
case 'A':
sort_active = 1;
break;
case 'B':
show_bytes = 1;
break;
case 'd':
set_debug = 1;
if (!debug_opt_scan(optarg))
fatal("Invalid debug option '%s'\n", optarg);
break;
case 'D':
show_activity = 1;
break;
case 'e':
show_empty = 1;
break;
case 'f':
show_first_alias = 1;
break;
case 'h':
usage();
return 0;
case 'i':
show_inverted = 1;
break;
case 'l':
show_slab = 1;
break;
case 'L':
sort_loss = 1;
break;
case 'n':
show_numa = 1;
break;
case 'N':
if (optarg) {
output_lines = atoi(optarg);
if (output_lines < 1)
output_lines = 1;
}
break;
case 'o':
show_ops = 1;
break;
case 'r':
show_report = 1;
break;
case 'P':
sort_partial = 1;
break;
case 's':
shrink = 1;
break;
case 'S':
sort_size = 1;
break;
case 't':
show_track = 1;
break;
case 'T':
show_totals = 1;
break;
case 'U':
unreclaim_only = 1;
break;
case 'v':
validate = 1;
break;
case 'X':
if (output_lines == -1)
output_lines = 1;
extended_totals = 1;
show_bytes = 1;
break;
case 'z':
skip_zero = 0;
break;
case '1':
show_single_ref = 1;
break;
default:
fatal("%s: Invalid option '%c'\n", argv[0], optopt);
}
if (!show_slab && !show_alias && !show_track && !show_report
&& !validate && !shrink && !set_debug && !show_ops)
show_slab = 1;
if (argc > optind)
pattern_source = argv[optind];
else
pattern_source = ".*";
err = regcomp(&pattern, pattern_source, REG_ICASE|REG_NOSUB);
if (err)
fatal("%s: Invalid pattern '%s' code %d\n",
argv[0], pattern_source, err);
read_slab_dir();
if (show_alias) {
alias();
} else if (extended_totals) {
xtotals();
} else if (show_totals) {
totals();
} else {
link_slabs();
rename_slabs();
sort_slabs();
output_slabs();
}
return 0;
}
| 25.085487 | 86 | 0.618931 | [
"object",
"3d"
] |
680ab3619786b6daac86b5d034a209c62493773f | 20,496 | h | C | be/src/rpc/serialization.h | cyongli/palo | 29e46668e64be71624533c7abf6a26a5cd710be0 | [
"Apache-2.0"
] | null | null | null | be/src/rpc/serialization.h | cyongli/palo | 29e46668e64be71624533c7abf6a26a5cd710be0 | [
"Apache-2.0"
] | null | null | null | be/src/rpc/serialization.h | cyongli/palo | 29e46668e64be71624533c7abf6a26a5cd710be0 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2007-2016 Hypertable, Inc.
//
// This file is part of Hypertable.
//
// Hypertable 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 any later version.
//
// Hypertable 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 BDG_PALO_BE_SRC_RPC_SERIALIZATION_H
#define BDG_PALO_BE_SRC_RPC_SERIALIZATION_H
#include "inet_addr.h"
#include "serialization_c.h"
namespace palo { namespace serialization {
/**
* Encodes a byte into the given buffer. Assumes there is
* enough space available. Increments buffer pointer.
*
* @param bufp Address of the destination buffer
* @param val The byte
*/
inline void encode_i8(uint8_t **bufp, uint8_t val) {
HT_ENCODE_I8(*bufp, val);
}
/**
* Decode a 8-bit integer (a byte/character)
*
* @param bufp The pointer to the source buffer
* @param remainp The pointer to the remaining size variable
* @return The decoded value
*/
inline uint8_t decode_i8(const uint8_t **bufp, size_t *remainp) {
HT_DECODE_NEED(*remainp, 1);
return *(*bufp)++;
}
/**
* Decodes a single byte from the given buffer. Increments buffer pointer
* and decrements remainp on success.
*
* @param bufp Pointer to the source buffer pointer
* @param remainp Pointer to the number of bytes remaining in buffer
* @return The byte value
*/
inline uint8_t decode_byte(const uint8_t **bufp, size_t *remainp) {
return decode_i8(bufp, remainp);
}
/**
* Encodes a boolean into the given buffer. Assumes there is
* enough space available. Increments buffer pointer.
*
* @param bufp Address of the destination buffer
* @param bval The boolean value
*/
inline void encode_bool(uint8_t **bufp, bool bval) {
HT_ENCODE_BOOL(*bufp, bval);
}
/**
* Decodes a boolean value from the given buffer. Increments buffer pointer
* and decrements remainp on success.
*
* @param bufp Pointer to the source buffer pointer
* @param remainp Pointer to number of bytes remaining in buffer
* @return The boolean value
*/
inline bool decode_bool(const uint8_t **bufp, size_t *remainp) {
return decode_i8(bufp, remainp) != 0;
}
/**
* Encode a 16-bit integer in little-endian order
*
* @param bufp Pointer to the destination buffer
* @param val The value to encode
*/
inline void encode_i16(uint8_t **bufp, uint16_t val) {
HT_ENCODE_I16(*bufp, val);
}
/**
* Decode a 16-bit integer in little-endian order
*
* @param bufp Pointer to the source buffer pointer
* @param remainp Pointer to the remaining size variable
* @return The decoded value
*/
inline uint16_t decode_i16(const uint8_t **bufp, size_t *remainp) {
uint16_t val;
HT_DECODE_I16(*bufp, *remainp, val);
return val;
}
/**
* Encode a 32-bit integer in little-endian order
*
* @param bufp Pointer to the destination buffer pointer
* @param val The value to encode
*/
inline void encode_i32(uint8_t **bufp, uint32_t val) {
HT_ENCODE_I32(*bufp, val);
}
/**
* Decode a 32-bit integer in little-endian order
*
* @param bufp Pointer to the source buffer pointer
* @param remainp Pointer to the remaining size variable
* @return The decoded value
*/
inline uint32_t decode_i32(const uint8_t **bufp, size_t *remainp) {
uint32_t val;
HT_DECODE_I32(*bufp, *remainp, val);
return val;
}
/**
* Encode a 64-bit integer in little-endian order
*
* @param bufp Pointer to the destination buffer pointer
* @param val The value to encode
*/
inline void encode_i64(uint8_t **bufp, uint64_t val) {
HT_ENCODE_I64(*bufp, val);
}
/**
* Decode a 64-bit integer in little-endian order
*
* @param bufp Pointer to the source buffer pointer
* @param remainp Pointer to the remaining size variable
* @return The decoded value
*/
inline uint64_t decode_i64(const uint8_t **bufp, size_t *remainp) {
uint64_t val;
HT_DECODE_I64(*bufp, *remainp, val);
return val;
}
/**
* Length of a variable length encoded 32-bit integer (up to 5 bytes)
*
* @param val The 32-bit integer to encode
* @return The number of bytes required for serializing this number
*/
inline int encoded_length_vi32(uint32_t val) {
return HT_ENCODED_LEN_VI32(val);
}
/**
* Length of a variable length encoded 64-bit integer (up to 9 bytes)
*
* @param val The 64-bit integer to encode
* @return The number of bytes required for serializing this number
*/
inline int encoded_length_vi64(uint64_t val) {
return HT_ENCODED_LEN_VI64(val);
}
/**
* Encode a integer (up to 32-bit) in variable length encoding
*
* @param bufp Pointer to the destination buffer pointer
* @param val The value to encode
*/
inline void encode_vi32(uint8_t **bufp, uint32_t val) {
HT_ENCODE_VI32(*bufp, val, return);
}
/**
* Encode a integer (up to 64-bit) in variable length encoding
*
* @param bufp The pointer to the destination buffer pointer
* @param val The value to encode
*/
inline void encode_vi64(uint8_t **bufp, uint64_t val) {
HT_ENCODE_VI64(*bufp, val, return);
}
/**
* Decode a variable length encoded integer up to 32-bit
*
* @param bufp Pointer to the source buffer pointer
* @param remainp Pointer to the remaining size variable
* @return The decoded value
*/
inline uint32_t decode_vi32(const uint8_t **bufp, size_t *remainp) {
uint32_t n;
HT_DECODE_VI32(*bufp, *remainp, n, return n);
}
/**
* Decode a variable length encoded integer up to 64-bit
*
* @param bufp Pointer to the source buffer pointer
* @param remainp Pointer to the remaining size variable
* @return The decoded value
*/
inline uint64_t decode_vi64(const uint8_t **bufp, size_t *remainp) {
uint64_t n;
HT_DECODE_VI64(*bufp, *remainp, n, return n);
}
/**
* Decode a variable length encoded integer up to 32-bit
*
* @param bufp Pointer to the source buffer pointer
* @return The decoded value
*/
inline uint32_t decode_vi32(const uint8_t **bufp) {
size_t remain = 6;
return decode_vi32(bufp, &remain);
}
/**
* Decode a variable length encoded integer up to 64-bit
*
* @param bufp Pointer to the source buffer pointer
* @return The decoded value
*/
inline uint64_t decode_vi64(const uint8_t **bufp) {
size_t remain = 12;
return decode_vi64(bufp, &remain);
}
/**
* Computes the encoded length of a 32-bit length byte array (i32, bytes)
*
* @param len Length of the byte array to be encoded
* @return The encoded length of a byte array of length len
*/
inline size_t encoded_length_bytes32(int32_t len) {
return len + 4;
}
/**
* Encodes a variable sized byte array into the given buffer. Encoded as a
* 4 byte length followed by the data. Assumes there is enough space
* available. Increments buffer pointer.
*
* @param bufp Address of the destination buffer
* @param data Pointer to array of bytes
* @param len The length of the byte array
*/
inline void encode_bytes32(uint8_t **bufp, const void *data, int32_t len) {
HT_ENCODE_BYTES32(*bufp, data, len);
}
/**
* Decodes a variable sized byte array from the given buffer. Byte array i
* encoded as a 4 byte length followed by the data. Increments buffer
* pointer and decrements remainp on success.
*
* @param bufp Address of buffer containing encoded byte array
* @param remainp Address of variable containing number of bytes remaining
* @param lenp Address of length of decoded byte array
*/
inline uint8_t *decode_bytes32(const uint8_t **bufp, size_t *remainp,
uint32_t *lenp) {
uint8_t *out;
HT_DECODE_BYTES32(*bufp, *remainp, out, *lenp);
return out;
}
/**
* Computes the encoded length of a string16 encoding
*
* @param str Pointer to the c-style string
* @return The encoded length of str
*/
inline size_t encoded_length_str16(const char *str) {
return 2 + ((str == 0) ? 0 : strlen(str)) + 1;
}
/**
* Computes the encoded length of a std::string.
*
* @param str Reference to string object
* @return The encoded length of str
*/
inline size_t encoded_length_str16(const std::string &str) {
return 2 + str.length() + 1;
}
/**
* Encodes a string buffer into the given buffer.
* Encoded as a 2 byte length followed by the string data, followed
* by a '\\0' termination byte. The length value does not include
* the '\\0'. Assumes there is enough space available. Increments
* buffer pointer.
*
* @param bufp Address of the destination buffer
* @param str The c-style string to encode
* @param len Length of the string
*/
inline void encode_str16(uint8_t **bufp, const void *str, uint16_t len) {
HT_ENCODE_STR16(*bufp, str, len);
}
/**
* Encodes a c-style null-terminated string into the given buffer.
* Encoded as a 2 byte length followed by the string data, followed
* by a '\\0' termination byte. The length value does not include
* the '\\0'. Assumes there is enough space available. Increments
* buffer pointer.
*
* @param bufp Pointer to pointer of destination buffer
* @param str The c-style string to encode
*/
inline void encode_str16(uint8_t **bufp, const char *str) {
uint16_t len = (str == 0) ? 0 : strlen(str);
encode_str16(bufp, str, len);
}
/**
* Encodes a string into the given buffer. Encoded as a
* 2 byte length followed by the string data, followed by a '\\0'
* termination byte. The length value does not include the '\\0'.
* Assumes there is enough space available. Increments buffer
* pointer.
*
* @param bufp Pointer to pointer of the destinatin buffer
* @param str The std::string to encode
*/
template <class StringT>
inline void encode_str16(uint8_t **bufp, const StringT &str) {
encode_str16(bufp, str.c_str(), str.length());
}
/**
* Decodes a c-style string from the given buffer. The encoding of the
* string is a 2 byte length followed by the string, followed by a '\\0'
* termination byte. The length does not include the '\\0' terminator.
* The decoded string pointer points back into the encoding buffer.
* Increments buffer pointer and decrements remainp on success.
*
* @param bufp Pointer to pointer of buffer containing encoded string
* @param remainp Address of variable of number of bytes remaining in buffer
* @return Pointer to a c-style string
*/
inline const char *decode_str16(const uint8_t **bufp, size_t *remainp) {
const char *str;
uint16_t len;
HT_DECODE_STR16(*bufp, *remainp, str, len);
return str;
}
/**
* Decodes a c-style string from the given buffer. The encoding of the
* string is a 2 byte length followed by the string, followed by a '\\0'
* termination byte. The length does not include the '\\0' terminator.
* The decoded string pointer points back into the encoding buffer.
* Increments buffer pointer and decrements remainp on success.
*
* @param bufp Pointer to pointer of buffer containing encoded string
* @param remainp Address of variable of number of bytes remaining in buffer
* @param lenp Address of varaible to hold the len of the string
* @return Pointer to a c-style string
*/
inline char *decode_str16(const uint8_t **bufp, size_t *remainp,
uint16_t *lenp) {
char *str;
HT_DECODE_STR16(*bufp, *remainp, str, *lenp);
return str;
}
/**
* Decodes a str16 from the given buffer to a std::string. The encoding of the
* string is a 2 byte length followed by the string, followed by a '\\0'
* termination byte. The length does not include the '\\0' terminator.
* Increments buffer pointer and decrements remainp on success.
*
* @param bufp Pointer to pointer of buffer containing encoded string
* @param remainp Address of variable of number of bytes remaining in buffer
* @return True on success, false if buffer has insufficient room
*/
template <class StringT>
inline StringT decode_str16(const uint8_t **bufp, size_t *remainp) {
char *str;
uint16_t len;
HT_DECODE_STR16(*bufp, *remainp, str, len);
return StringT(str, len); // RVO hopeful
}
/**
* Computes the encoded length of vstr (vint64, data, null)
*
* @param len The string length
* @return The encoded length of str
*/
inline size_t encoded_length_vstr(size_t len) {
return encoded_length_vi64(len) + len + 1;
}
/**
* Computes the encoded length of vstr. Assumes that the string length
* can be encoded in 32-bit integer
*
* @param s Pointer to the the c-style string
* @return The encoded length of s
*/
inline size_t encoded_length_vstr(const char *s) {
return encoded_length_vstr(s ? strlen(s) : 0);
}
/**
* Computes the encoded length of vstr. Assumes that the string length
* can be encoded in 32-bit integer
*
* @param s The string to encode
* @return The encoded length of s
*/
inline size_t encoded_length_vstr(const std::string &s) {
return encoded_length_vstr(s.length());
}
/**
* Encode a buffer as variable length string (vint64, data, null)
*
* @param bufp Pointer to pointer of destination buffer
* @param buf Pointer to the start of the input buffer
* @param len Length of the input buffer
*/
inline void encode_vstr(uint8_t **bufp, const void *buf, size_t len) {
HT_ENCODE_VSTR(*bufp, buf, len);
}
/**
* Encode a c-style string as vstr
*
* @param bufp Pointer to pointer of destination buffer
* @param s Pointer to the start of the string
*/
inline void encode_vstr(uint8_t **bufp, const char *s) {
encode_vstr(bufp, s, s ? strlen(s) : 0);
}
/**
* Encode a std::string as vstr
*
* @param bufp Pointer to pointer of destination buffer
* @param s The string to encode
*/
template <class StringT>
inline void encode_vstr(uint8_t **bufp, const StringT &s) {
encode_vstr(bufp, s.data(), s.length());
}
/**
* Decode a vstr (vint64, data, null).
* Note: decoding a vstr longer than 4GiB on a 32-bit platform
* is obviously futile (throws bad vstr exception)
*
* @param bufp Pointer to pointer of the source buffer
* @param remainp Pointer to the remaining size variable
* @return Pointer to the decoded string data
*/
inline char *decode_vstr(const uint8_t **bufp, size_t *remainp) {
char *buf;
size_t len;
HT_DECODE_VSTR(*bufp, *remainp, buf, len);
(void)len; // avoid warnings because len is assigned but never used
return buf;
}
/**
* Decode a vstr (vint64, data, null)
*
* @param bufp Pointer to pointer of the source buffer
* @param remainp Pointer to the remaining size variable
* @return The decoded string
*/
template <class StringT>
inline std::string decode_vstr(const uint8_t **bufp, size_t *remainp) {
char *buf;
size_t len;
HT_DECODE_VSTR(*bufp, *remainp, buf, len);
return StringT(buf, len); // RVO
}
/**
* Decode a vstr (vint64, data, null)
*
* @param bufp Pointer to pointer of the source buffer
* @param remainp Pointer to the remaining size variable
* @param lenp Pointer to the string length
* @return Pointer to the decoded string
*/
inline char *decode_vstr(const uint8_t **bufp, size_t *remainp,
uint32_t *lenp) {
char *buf;
HT_DECODE_VSTR(*bufp, *remainp, buf, *lenp);
return buf;
}
/**
* Encode an InetAddr structure
*
* @param bufp Pointer to pointer of the destination buffer
* @param addr Reference to the InetAddr object to encode
*/
inline void encode_inet_addr(uint8_t **bufp, const InetAddr &addr) {
HT_ENCODE_I16(*bufp, addr.sin_family);
HT_ENCODE_I32(*bufp, addr.sin_addr.s_addr);
HT_ENCODE_I16(*bufp, addr.sin_port);
}
/**
* Decode an InetAddr structure
*
* @param bufp Pointer to pointer of the source buffer
* @param remainp Pointer to remaining size variable
* @return The decoded InetAddr object
*/
inline InetAddr decode_inet_addr(const uint8_t **bufp, size_t *remainp) {
InetAddr addr;
HT_DECODE_I16(*bufp, *remainp, addr.sin_family);
HT_DECODE_I32(*bufp, *remainp, addr.sin_addr.s_addr);
HT_DECODE_I16(*bufp, *remainp, addr.sin_port);
return addr;
}
/**
* Encodes a double with 18 decimal digits of precision as 64-bit
* left-of-decimal, followed by 64-bit right-of-decimal, both in
* little-endian order
*
* @param bufp Pointer to the destination buffer
* @param val The double to encode
*/
inline void encode_double(uint8_t **bufp, double val) {
int64_t lod = (int64_t)val;
int64_t rod = (int64_t)((val - (double)lod) * (double)1000000000000000000.00);
HT_ENCODE_I64(*bufp, lod);
HT_ENCODE_I64(*bufp, rod);
}
/**
* Decodes a double as 64-bit left-of-decimal, followed by
* 64-bit right-of-decimal, both in little-endian order
*
* @param bufp Pointer to pointer of the source buffer
* @param remainp Pointer to remaining size variable
* @return The decoded value
*/
inline double decode_double(const uint8_t **bufp, size_t *remainp) {
int64_t lod;
int64_t rod;
HT_DECODE_I64(*bufp, *remainp, lod);
HT_DECODE_I64(*bufp, *remainp, rod);
return (double)lod + ((double)rod / (double)1000000000000000000.00);
}
/**
* Length of an encoded double (16 bytes)
*
* @return The number of bytes required to encode a double
*/
inline int encoded_length_double() {
return 16;
}
/**
* Compare doubles that may have been serialized and unserialized.
* The serialization process loses precision, so this function is
* necessary to compare pre-serialized with post-serialized values
*
* @param a First value to compare
* @param b Second value to compare
* @return True of values are logically equal, false otherwise
*/
inline bool equal(double a, double b) {
int64_t lod_a = (int64_t)a;
int64_t rod_a = (int64_t)((a - (double)lod_a) * (double)1000000000000000000.00);
double aprime = (double)lod_a + ((double)rod_a / (double)1000000000000000000.00);
int64_t lod_b = (int64_t)b;
int64_t rod_b = (int64_t)((b - (double)lod_b) * (double)1000000000000000000.00);
double bprime = (double)lod_b + ((double)rod_b / (double)1000000000000000000.00);
return aprime == bprime;
}
} // namespace palo::serialization
} // namespace palo
#endif //BDG_PALO_BE_SRC_RPC_SERIALIZATION_H
| 34.16 | 89 | 0.637295 | [
"object"
] |
680eb09da19e3679bcd5f6fa884cb98c51e579b0 | 6,212 | h | C | src/base/allocator/partition_allocator/object_bitmap.h | jsylin/naiveproxy | 4ad4827d3ed3e5fd72eded69c14a90028880fc20 | [
"BSD-3-Clause"
] | null | null | null | src/base/allocator/partition_allocator/object_bitmap.h | jsylin/naiveproxy | 4ad4827d3ed3e5fd72eded69c14a90028880fc20 | [
"BSD-3-Clause"
] | null | null | null | src/base/allocator/partition_allocator/object_bitmap.h | jsylin/naiveproxy | 4ad4827d3ed3e5fd72eded69c14a90028880fc20 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 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 BASE_ALLOCATOR_PARTITION_ALLOCATOR_OBJECT_BITMAP_H_
#define BASE_ALLOCATOR_PARTITION_ALLOCATOR_OBJECT_BITMAP_H_
#include <climits>
#include <cstddef>
#include <cstdint>
#include <algorithm>
#include <array>
#include <atomic>
#include <tuple>
#include "base/allocator/partition_allocator/partition_alloc_check.h"
#include "base/bits.h"
namespace base {
namespace internal {
// Bitmap which tracks beginning of allocated objects. The bitmap can be safely
// accessed from multiple threads, but this doesn't imply visibility on the data
// (i.e. no ordering guaranties, since relaxed atomics are used underneath). The
// bitmap itself must be created inside a page, size and alignment of which are
// specified as template arguments |PageSize| and |PageAlignment|.
// |ObjectAlignment| specifies the minimal alignment of objects that are
// allocated inside a page (serves as the granularity in the bitmap).
template <size_t PageSize, size_t PageAlignment, size_t ObjectAlignment>
class ObjectBitmap final {
static constexpr size_t kBitsPerCell = sizeof(uint8_t) * CHAR_BIT;
static constexpr size_t kBitmapSize =
(PageSize + ((kBitsPerCell * ObjectAlignment) - 1)) /
(kBitsPerCell * ObjectAlignment);
static constexpr size_t kPageOffsetMask = PageAlignment - 1;
static constexpr size_t kPageBaseMask = ~kPageOffsetMask;
public:
static constexpr size_t kPageSize = PageSize;
static constexpr size_t kPageAlignment = PageAlignment;
static constexpr size_t kObjectAlignment = ObjectAlignment;
static constexpr size_t kMaxEntries = kBitmapSize * kBitsPerCell;
static constexpr uintptr_t kSentinel = 0u;
inline ObjectBitmap();
inline void SetBit(uintptr_t address);
inline void ClearBit(uintptr_t address);
inline bool CheckBit(uintptr_t address) const;
// Iterates all objects recorded in the bitmap.
//
// The callback is of type
// void(Address)
// and is passed the object address as parameter.
template <typename Callback>
inline void Iterate(Callback) const;
inline void Clear();
private:
std::atomic<uint8_t>& AsAtomicCell(size_t cell_index) {
return reinterpret_cast<std::atomic<uint8_t>&>(bitmap_[cell_index]);
}
const std::atomic<uint8_t>& AsAtomicCell(size_t cell_index) const {
return reinterpret_cast<const std::atomic<uint8_t>&>(bitmap_[cell_index]);
}
inline uint8_t LoadCell(size_t cell_index) const;
inline std::pair<size_t, size_t> ObjectIndexAndBit(uintptr_t) const;
std::array<uint8_t, kBitmapSize> bitmap_;
};
template <size_t PageSize, size_t PageAlignment, size_t ObjectAlignment>
constexpr size_t
ObjectBitmap<PageSize, PageAlignment, ObjectAlignment>::kSentinel;
// The constructor can be omitted, but the Chromium's clang plugin wrongly
// warns that the type is not trivially constructible.
template <size_t PageSize, size_t PageAlignment, size_t ObjectAlignment>
inline ObjectBitmap<PageSize, PageAlignment, ObjectAlignment>::ObjectBitmap() =
default;
template <size_t PageSize, size_t PageAlignment, size_t ObjectAlignment>
void ObjectBitmap<PageSize, PageAlignment, ObjectAlignment>::SetBit(
uintptr_t address) {
size_t cell_index, object_bit;
std::tie(cell_index, object_bit) = ObjectIndexAndBit(address);
auto& cell = AsAtomicCell(cell_index);
cell.fetch_or(1 << object_bit, std::memory_order_relaxed);
}
template <size_t PageSize, size_t PageAlignment, size_t ObjectAlignment>
void ObjectBitmap<PageSize, PageAlignment, ObjectAlignment>::ClearBit(
uintptr_t address) {
size_t cell_index, object_bit;
std::tie(cell_index, object_bit) = ObjectIndexAndBit(address);
auto& cell = AsAtomicCell(cell_index);
cell.fetch_and(~(1 << object_bit), std::memory_order_relaxed);
}
template <size_t PageSize, size_t PageAlignment, size_t ObjectAlignment>
bool ObjectBitmap<PageSize, PageAlignment, ObjectAlignment>::CheckBit(
uintptr_t address) const {
size_t cell_index, object_bit;
std::tie(cell_index, object_bit) = ObjectIndexAndBit(address);
return LoadCell(cell_index) & (1 << object_bit);
}
template <size_t PageSize, size_t PageAlignment, size_t ObjectAlignment>
uint8_t ObjectBitmap<PageSize, PageAlignment, ObjectAlignment>::LoadCell(
size_t cell_index) const {
return AsAtomicCell(cell_index).load(std::memory_order_relaxed);
}
template <size_t PageSize, size_t PageAlignment, size_t ObjectAlignment>
std::pair<size_t, size_t>
ObjectBitmap<PageSize, PageAlignment, ObjectAlignment>::ObjectIndexAndBit(
uintptr_t address) const {
const uintptr_t offset_in_page = address & kPageOffsetMask;
const size_t object_number = offset_in_page / kObjectAlignment;
const size_t cell_index = object_number / kBitsPerCell;
PA_DCHECK(kBitmapSize > cell_index);
const size_t bit = object_number % kBitsPerCell;
return {cell_index, bit};
}
template <size_t PageSize, size_t PageAlignment, size_t ObjectAlignment>
template <typename Callback>
inline void ObjectBitmap<PageSize, PageAlignment, ObjectAlignment>::Iterate(
Callback callback) const {
// The bitmap (|this|) is allocated inside the page with |kPageAlignment|.
const uintptr_t base = reinterpret_cast<uintptr_t>(this) & kPageBaseMask;
for (size_t cell_index = 0; cell_index < kBitmapSize; ++cell_index) {
uint8_t value = LoadCell(cell_index);
while (value) {
const int trailing_zeroes = base::bits::CountTrailingZeroBits(value);
const size_t object_number =
(cell_index * kBitsPerCell) + trailing_zeroes;
const uintptr_t object_address =
base + (kObjectAlignment * object_number);
callback(object_address);
// Clear current object bit in temporary value to advance iteration.
value &= ~(1 << trailing_zeroes);
}
}
}
template <size_t PageSize, size_t PageAlignment, size_t ObjectAlignment>
void ObjectBitmap<PageSize, PageAlignment, ObjectAlignment>::Clear() {
std::fill(bitmap_.begin(), bitmap_.end(), '\0');
}
} // namespace internal
} // namespace base
#endif // BASE_ALLOCATOR_PARTITION_ALLOCATOR_OBJECT_BITMAP_H_
| 38.825 | 80 | 0.76803 | [
"object"
] |
68136170d876fdede1bd21c8fa86386bace4441c | 4,997 | h | C | Sources/Internal/Render/Highlevel/LandscapeSubdivision.h | stinvi/dava.engine | 2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e | [
"BSD-3-Clause"
] | 26 | 2018-09-03T08:48:22.000Z | 2022-02-14T05:14:50.000Z | Sources/Internal/Render/Highlevel/LandscapeSubdivision.h | ANHELL-blitz/dava.engine | ed83624326f000866e29166c7f4cccfed1bb41d4 | [
"BSD-3-Clause"
] | null | null | null | Sources/Internal/Render/Highlevel/LandscapeSubdivision.h | ANHELL-blitz/dava.engine | ed83624326f000866e29166c7f4cccfed1bb41d4 | [
"BSD-3-Clause"
] | 45 | 2018-05-11T06:47:17.000Z | 2022-02-03T11:30:55.000Z | #pragma once
#include <Base/Any.h>
#include "Base/BaseTypes.h"
#include "Reflection/Reflection.h"
#include "Base/IntrospectionBase.h"
#include "MemoryManager/MemoryProfiler.h"
namespace DAVA
{
class Frustum;
class Heightmap;
class Camera;
class LandscapeSubdivision : public InspBase
{
DAVA_ENABLE_CLASS_ALLOCATION_TRACKING(ALLOC_POOL_LANDSCAPE)
public:
LandscapeSubdivision();
~LandscapeSubdivision();
struct SubdivisionPatchInfo
{
enum
{
CLIPPED = 1,
SUBDIVIDED = 2,
TERMINATED = 3,
};
uint32 lastUpdateID = 0;
float32 subdivMorph = 0.f;
uint8 subdivisionState = CLIPPED;
uint8 startClipPlane = 0;
};
struct SubdivisionLevelInfo
{
uint32 offset;
uint32 size;
};
struct SubdivisionMetrics : public InspBase
{
float32 normalFov = 70.f;
float32 zoomFov = 6.5f;
float32 normalMaxHeightError = 0.014f;
float32 normalMaxPatchRadiusError = 0.45f;
float32 normalMaxAbsoluteHeightError = 3.f;
float32 zoomMaxHeightError = 0.03f;
float32 zoomMaxPatchRadiusError = 0.9f;
float32 zoomMaxAbsoluteHeightError = 3.f;
bool operator==(const SubdivisionMetrics& other) const;
DAVA_VIRTUAL_REFLECTION(SubdivisionMetrics, InspBase);
};
void BuildSubdivision(Heightmap* heightmap, const AABBox3& bbox, uint32 patchSizeQuads, uint32 minSubdivideLevel, bool calculateMorph);
void PrepareSubdivision(Camera* camera, const Matrix4* worldTransform);
void ReleaseInternalData();
const SubdivisionLevelInfo& GetLevelInfo(uint32 level) const;
const SubdivisionPatchInfo& GetPatchInfo(uint32 level, uint32 x, uint32 y) const;
const SubdivisionPatchInfo* GetTerminatedPatchInfo(uint32 level, uint32 x, uint32 y, uint32& patchLevel) const;
SubdivisionMetrics& GetMetrics();
uint32 GetLevelCount() const;
uint32 GetPatchCount() const;
uint32 GetTerminatedPatchesCount() const;
void UpdatePatchInfo(const Rect2i& heighmapRect);
void SetForceMaxSubdivision(bool forceSubdivide);
private:
struct PatchQuadInfo
{
AABBox3 bbox;
Vector3 positionOfMaxError;
float32 maxError;
float32 radius;
};
void UpdatePatchInfo(uint32 level, uint32 x, uint32 y, PatchQuadInfo* parentPatch, const Rect2i& updateRect);
void SubdividePatch(uint32 level, uint32 x, uint32 y, uint8 clippingFlags, float32 heightError0, float32 radiusError0);
const PatchQuadInfo& GetPatchQuadInfo(uint32 level, uint32 x, uint32 y) const;
Vector<SubdivisionLevelInfo> subdivLevelInfoArray;
Vector<PatchQuadInfo> patchQuadArray;
Vector<SubdivisionPatchInfo> subdivPatchArray;
uint32 terminatedPatchesCount = 0;
uint32 minSubdivLevel = 0;
uint32 subdivLevelCount = 0;
uint32 subdivPatchCount = 0;
uint32 patchSizeQuads = 8;
uint32 updateID = 0;
SubdivisionMetrics metrics;
float32 maxHeightError = 0.f;
float32 maxPatchRadiusError = 0.f;
float32 maxAbsoluteHeightError = 0.f;
Vector3 cameraPos;
float32 tanFovY = 0.f;
Frustum* frustum = nullptr;
Heightmap* heightmap = nullptr;
AABBox3 bbox;
bool calculateMorph = true;
bool forceMaxSubdiv = false;
friend class LandscapeSystem;
DAVA_VIRTUAL_REFLECTION(LandscapeSubdivision, InspBase);
};
inline const LandscapeSubdivision::SubdivisionLevelInfo& LandscapeSubdivision::GetLevelInfo(uint32 level) const
{
DVASSERT(level < subdivLevelInfoArray.size());
return subdivLevelInfoArray[level];
}
inline const LandscapeSubdivision::SubdivisionPatchInfo& LandscapeSubdivision::GetPatchInfo(uint32 level, uint32 x, uint32 y) const
{
const SubdivisionLevelInfo& levelInfo = GetLevelInfo(level);
DVASSERT(x < levelInfo.size && y < levelInfo.size);
return subdivPatchArray[levelInfo.offset + (y << level) + x];
}
inline const LandscapeSubdivision::PatchQuadInfo& LandscapeSubdivision::GetPatchQuadInfo(uint32 level, uint32 x, uint32 y) const
{
const SubdivisionLevelInfo& levelInfo = GetLevelInfo(level);
DVASSERT(x < levelInfo.size && y < levelInfo.size);
return patchQuadArray[levelInfo.offset + (y << level) + x];
}
inline void LandscapeSubdivision::SetForceMaxSubdivision(bool forceSubdivide)
{
forceMaxSubdiv = forceSubdivide;
}
inline uint32 LandscapeSubdivision::GetLevelCount() const
{
return subdivLevelCount;
}
inline uint32 LandscapeSubdivision::GetPatchCount() const
{
return subdivPatchCount;
}
inline uint32 LandscapeSubdivision::GetTerminatedPatchesCount() const
{
return terminatedPatchesCount;
}
inline LandscapeSubdivision::SubdivisionMetrics& LandscapeSubdivision::GetMetrics()
{
return metrics;
}
template <>
bool AnyCompare<LandscapeSubdivision::SubdivisionMetrics>::IsEqual(const DAVA::Any& v1, const DAVA::Any& v2);
extern template struct AnyCompare<LandscapeSubdivision::SubdivisionMetrics>;
}
| 28.718391 | 139 | 0.730238 | [
"vector"
] |
681984c2985d165c1ec3372f16c05667b69c867e | 1,245 | h | C | clientplugin/HttpReceiver/unit_test/BpeSimulator/Source/IAsyncVirtualClient.h | shrewdlin/BPE | cf29647479b1b8ed53afadaf70557387f4c07e16 | [
"BSD-3-Clause"
] | 1 | 2016-07-12T06:00:37.000Z | 2016-07-12T06:00:37.000Z | clientplugin/HttpReceiver/unit_test/BpeSimulator/Source/IAsyncVirtualClient.h | shrewdlin/BPE | cf29647479b1b8ed53afadaf70557387f4c07e16 | [
"BSD-3-Clause"
] | null | null | null | clientplugin/HttpReceiver/unit_test/BpeSimulator/Source/IAsyncVirtualClient.h | shrewdlin/BPE | cf29647479b1b8ed53afadaf70557387f4c07e16 | [
"BSD-3-Clause"
] | 2 | 2016-09-06T07:59:09.000Z | 2020-12-12T03:25:24.000Z | #ifndef _I_ASYNC_VIRTUAL_CLIENT_H_
#define _I_ASYNC_VIRTUAL_CLIENT_H_
#include <string>
#include <vector>
#include "ILog.h"
using std::string;
using std::vector;
#ifndef IN
#define IN
#endif
#ifndef OUT
#define OUT
#endif
class IAsyncVirtualClient;
typedef void(*GVirtualClientService)(IAsyncVirtualClient* pPlugIn, void*, const void *, int);
typedef void(*Response2BPE)(void*, const void *, int);
typedef void(*ExceptionWarn)(const string &);
typedef void(*AsyncLog)(int nModel, XLOG_LEVEL level, int nInterval, const string &strMsg,
int nCode, const string& strAddr, int serviceId, int msgId);
class IAsyncVirtualClient
{
public:
virtual int Initialize(GVirtualClientService fnResponse, Response2BPE fnResponse2BPE, ExceptionWarn funcExceptionWarn, AsyncLog funcAsyncLog) = 0;
virtual int RequestService(IN void* pOwner, IN const void *pBuffer, IN int len) = 0;
virtual int ResponseService(IN const void *handle, IN const void *pBuffer, IN int len) = 0;
virtual void GetSelfCheckState(unsigned int &dwAliveNum, unsigned int &dwAllNum) = 0;
virtual void GetServiceId(vector<unsigned int> &vecServiceIds) = 0;
virtual const string OnGetPluginInfo()const = 0;
virtual ~IAsyncVirtualClient(){}
};
#endif
| 29.642857 | 150 | 0.760643 | [
"vector"
] |
682390a914a8a38fc9b601f3fbe11d794c32cd0c | 270 | h | C | IOSDeviceLib/FileHelper.h | platov/ios-device-lib | be975005da24bfc44b99f0152692820a56b57a73 | [
"Apache-2.0"
] | null | null | null | IOSDeviceLib/FileHelper.h | platov/ios-device-lib | be975005da24bfc44b99f0152692820a56b57a73 | [
"Apache-2.0"
] | null | null | null | IOSDeviceLib/FileHelper.h | platov/ios-device-lib | be975005da24bfc44b99f0152692820a56b57a73 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <vector>
#include <string>
struct FileInfo {
long size;
std::vector<char> contents;
};
bool exists(std::string& path);
FileInfo get_file_info(std::string& path, bool get_contents);
std::string base64_encode(const char *path, unsigned int len);
| 20.769231 | 62 | 0.744444 | [
"vector"
] |
6827c29ecb80a1245cb913871972071bef7d8fae | 6,443 | c | C | CM_GDP_CU/src/ExtraModels/MyDriveLine_20220305_2353.c | CU-2021AM-GDP-T1/rollstiffnesscontrol-enhancehandling-matlabsimulink | 64162ebb0e0dc51f23e545f886bbcfce1e9e5ab6 | [
"MIT"
] | null | null | null | CM_GDP_CU/src/ExtraModels/MyDriveLine_20220305_2353.c | CU-2021AM-GDP-T1/rollstiffnesscontrol-enhancehandling-matlabsimulink | 64162ebb0e0dc51f23e545f886bbcfce1e9e5ab6 | [
"MIT"
] | null | null | null | CM_GDP_CU/src/ExtraModels/MyDriveLine_20220305_2353.c | CU-2021AM-GDP-T1/rollstiffnesscontrol-enhancehandling-matlabsimulink | 64162ebb0e0dc51f23e545f886bbcfce1e9e5ab6 | [
"MIT"
] | null | null | null | /* $Id$ (c) IPG */
/*
******************************************************************************
** CarMaker - Version 9.0.1
** Vehicle Dynamics Simulation Toolkit
**
** Copyright (C) IPG Automotive GmbH
** Bannwaldallee 60 Phone +49.721.98520.0
** 76185 Karlsruhe Fax +49.721.98520.99
** Germany WWW www.ipg-automotive.com
******************************************************************************
**
** Simple driveline Model
**
** Add the declaration of the register function to one of your header files,
** for example to User.h and call it in User_Register()
**
** DriveLine_Register_MyModel ();
**
******************************************************************************
*/
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "CarMaker.h"
#include "Car/Vehicle_Car.h"
#include "MyModels.h"
#define NWHEEL 4
static const char ThisModelClass[] = "PowerTrain.DL";
static const char ThisModelKind[] = "MyModel";
static const int ThisVersionId = 1;
struct tMyModel {
int nWheels;
double Irot[NWHEEL];
double rota[NWHEEL];
double x[NWHEEL];
};
static void
MyModel_DeclQuants (void *MP)
{
}
/* Model output parameters in the configuration struct CfgIF, which are required
by CarMaker, are read in before the MyModel_New() function.
- The parametrization of these parameters is supported by the GUI.
- These output parameters can be used internally by the model in same way like
the input parameters
*/
static void *
MyModel_New (struct tInfos *Inf, struct tPTDriveLineCfgIF *CfgIF, const char *KindKey)
{
struct tMyModel *mp = NULL;
char MsgPre[64];
const char *ModelKind;
int iS, VersionId = 0;
if ((ModelKind = SimCore_GetKindInfo(Inf, ModelClass_PTDriveLine, KindKey,
0, ThisVersionId, &VersionId)) == NULL)
return NULL;
mp = (struct tMyModel*)calloc(1,sizeof(*mp));
sprintf (MsgPre, "%s %s", ThisModelClass, ThisModelKind);
/* get CfgIF parameters */
if (DriveLine_GetCfgOutIF (Inf, CfgIF, ModelKind) != 0)
goto ErrorReturn;
/* CfgIF -> Model */
mp->nWheels = CfgIF->nWheels;
if (mp->nWheels != NWHEEL) {
LogErrF(EC_Init, "%s: model supports only a four wheel vehicle", MsgPre);
goto ErrorReturn;
}
for (iS=0; iS < mp->nWheels; iS++) {
mp->Irot[iS] = CfgIF->Wheel_Iyy[iS];
}
/* CfgIF output: verification if the parametrization corresponds to the model */
if (CfgIF->iDiff_mean <= 0) {
LogErrF (EC_Init, "%s: mean driveline ratio must be positive and non zero", MsgPre);
goto ErrorReturn;
}
if (CfgIF->DriveSourcePos[0] != Diff_Front ||
CfgIF->DriveSourcePos[1] != NoPosition ||
CfgIF->DriveSourcePos[2] != NoPosition ||
CfgIF->DriveSourcePos[3] != NoPosition) {
LogErrF (EC_Init, "%s: model supports only one drive source at front differential", MsgPre);
goto ErrorReturn;
}
return mp;
ErrorReturn:
free (mp);
return NULL;
}
static int
MyModel_Calc (void *MP, struct tPTDriveLineIF *IF, double dt)
{
struct tMyModel *mp = (struct tMyModel *)MP;
const tPTDriveLineCfgIF *CfgIF = IF->CfgIF;
double Trq_Ext2W[NWHEEL];
double Trq;
int iS, WithBrake=0;
for (iS=0; iS < 2; iS++) {
Trq = IF->DriveIn[0].Trq_in;
IF->WheelOut[iS].Trq_Drive = Trq*0.5*CfgIF->iDiff_mean;
}
for (iS=2; iS < NWHEEL; iS++) {
IF->WheelOut[iS].Trq_Drive = 0;
}
IF->DriveOut[0].rotv_in = (IF->WheelOut[0].rotv + IF->WheelOut[1].rotv)*0.5*CfgIF->iDiff_mean;
for (iS=0; iS<NWHEEL; iS++)
IF->WheelOut[iS].Trq_Supp2WC = -IF->WheelOut[iS].Trq_Drive;
/** Update Trq **/
for (iS=0; iS < NWHEEL; iS++) {
if (IF->WheelIn[iS].Trq_Brake > 0.0)
WithBrake = 1;
}
if (WithBrake) {
for (iS=0; iS < NWHEEL; iS++) {
#ifdef __cplusplus
struct tPTDriveLineIF::tPTDriveLineIF_WheelIn *wIn = &IF->WheelIn[iS];
struct tPTDriveLineIF::tPTDriveLineIF_WheelOut *wOut = &IF->WheelOut[iS];
#else
struct tPTDriveLineIF_WheelIn *wIn = &IF->WheelIn[iS];
struct tPTDriveLineIF_WheelOut *wOut = &IF->WheelOut[iS];
#endif
double xabs, x, TrqP;
/* dynamic friction */
/* P element */
TrqP = M_MIN(100.0, 1000.0 * wOut->rotv);
x = wIn->Trq_T2W + wOut->Trq_Drive + TrqP;
xabs = fabs(x);
wOut->Trq_B2W = M_MIN(xabs, wIn->Trq_Brake);
/* against moving momentum */
wOut->Trq_B2W = -M_SGN(x) * wOut->Trq_B2W;
}
} else {
for (iS=0; iS < NWHEEL; iS++)
IF->WheelOut[iS].Trq_B2W = 0.0;
}
if (SimCore.State == SCState_EndIdleGet || SimCore.State == SCState_EndIdleSet) {
for (iS=0; iS < NWHEEL; iS++)
IF->WheelOut[iS].Trq_B2W = 0.0;
}
for (iS=0; iS < NWHEEL; iS++) {
#ifdef __cplusplus
struct tPTDriveLineIF::tPTDriveLineIF_WheelIn *wIn = &IF->WheelIn[iS];
struct tPTDriveLineIF::tPTDriveLineIF_WheelOut *wOut = &IF->WheelOut[iS];
#else
struct tPTDriveLineIF_WheelIn *wIn = &IF->WheelIn[iS];
struct tPTDriveLineIF_WheelOut *wOut = &IF->WheelOut[iS];
#endif
Trq_Ext2W[iS] = wOut->Trq_B2W + wIn->Trq_T2W + wIn->Trq_WhlBearing;
}
/* Wheel accelerations */
for (iS=0; iS<NWHEEL; iS++) {
mp->rota[iS] = (IF->WheelOut[iS].Trq_Drive + Trq_Ext2W[iS]) / (mp->Irot[iS] + IF->DriveIn[0].Inert_in*0.5);
}
/* Integration */
if (SimCore.State != SCState_Simulate && SimCore.State != SCState_EndIdleGet) {
for (iS=0; iS<NWHEEL; iS++)
mp->rota[iS] = 0.0;
}
if (SimCore.State == SCState_EndIdleSet) {
for (iS=0; iS<NWHEEL; iS++)
IF->WheelOut[iS].rotv = 0.0;
} else {
for (iS=0; iS<NWHEEL; iS++) {
IF->WheelOut[iS].rotv += mp->rota[iS] * dt;
IF->WheelOut[iS].rot += IF->WheelOut[iS].rotv * dt;
}
}
return 0;
}
static void
MyModel_Delete (void *MP)
{
struct tMyModel *mp = (struct tMyModel *)MP;
free (mp);
}
int
DriveLine_Register_MyModel (void)
{
tModelClassDescr m;
memset(&m, 0, sizeof(m));
m.PTDriveLine.VersionId = ThisVersionId;
m.PTDriveLine.New = MyModel_New;
m.PTDriveLine.Calc = MyModel_Calc;
m.PTDriveLine.Delete = MyModel_Delete;
m.PTDriveLine.DeclQuants = MyModel_DeclQuants;
/* Should only be used if the model doesn't read params from extra files */
m.PTDriveLine.ParamsChanged = ParamsChanged_IgnoreCheck;
return Model_Register(ModelClass_PTDriveLine, ThisModelKind, &m);
}
| 28.135371 | 108 | 0.616328 | [
"model"
] |
682b309f07f277a85f99a24a6527d4750436961c | 1,626 | h | C | ARK2D/src/ARK2D/Tests/TransitionTest.h | ashleygwinnell/ark2d | bbfbee742ace9c52841dad4fab74d0d120ffe662 | [
"Unlicense"
] | 6 | 2015-08-25T19:16:20.000Z | 2021-04-19T16:47:58.000Z | ARK2D/src/ARK2D/Tests/TransitionTest.h | ashleygwinnell/ark2d | bbfbee742ace9c52841dad4fab74d0d120ffe662 | [
"Unlicense"
] | 1 | 2015-09-17T14:03:12.000Z | 2015-09-17T14:03:12.000Z | ARK2D/src/ARK2D/Tests/TransitionTest.h | ashleygwinnell/ark2d | bbfbee742ace9c52841dad4fab74d0d120ffe662 | [
"Unlicense"
] | 1 | 2018-10-02T19:59:47.000Z | 2018-10-02T19:59:47.000Z | /*
* TransitionTest.h
*
* Created on: Mar 23, 2012
* Author: ashleygwinnell
*/
#ifndef TRANSITIONTEST_H_
#define TRANSITIONTEST_H_
#include "../Namespaces.h"
#include "../Common/DLL.h"
#include "../State/GameState.h"
#include "../State/StateBasedGame.h"
#include "../Util/Containers/Vector.h"
namespace ARK {
namespace Tests {
class ARK2D_API TransitionTestGameState : public GameState {
public:
int index;
string name;
TransitionTestGameState(int index, string name);
void enter(GameContainer* container, StateBasedGame* game, GameState* from);
void leave(GameContainer* container, StateBasedGame* game, GameState* to);
unsigned int id();
void init(GameContainer* container, StateBasedGame* game);
void update(GameContainer* container, StateBasedGame* game, GameTimer* timer);
void render(GameContainer* container, StateBasedGame* game, Renderer* g);
virtual ~TransitionTestGameState();
};
class ARK2D_API TransitionTest : public StateBasedGame {
public:
unsigned int transitionIndex;
ARK::Util::Containers::Vector<ARK::State::Transition::Transition*> leaveTransitions;
ARK::Util::Containers::Vector<ARK::State::Transition::Transition*> entryTransitions;
TransitionTest();
virtual void initStates(GameContainer* container);
virtual void update(GameContainer* container, GameTimer* timer);
virtual void render(GameContainer* container, Renderer* g);
virtual void resize(GameContainer* container, int width, int height);
static int start();
virtual ~TransitionTest();
};
}
}
#endif /* TRANSITIONTEST_H_ */
| 27.559322 | 88 | 0.722632 | [
"render",
"vector"
] |
68310f1542a36aedb505ab919afad4e7cdab1f5b | 14,949 | h | C | features/filesystem/littlefs/littlefs/lfs.h | korjaa/mbed-os | 18634009c5f841a4df53c56ec053668c344ce24f | [
"Apache-2.0",
"BSD-3-Clause"
] | 6 | 2018-02-04T11:01:59.000Z | 2021-09-09T01:26:21.000Z | features/filesystem/littlefs/littlefs/lfs.h | korjaa/mbed-os | 18634009c5f841a4df53c56ec053668c344ce24f | [
"Apache-2.0",
"BSD-3-Clause"
] | 8 | 2018-01-15T10:23:03.000Z | 2019-04-05T15:09:14.000Z | features/filesystem/littlefs/littlefs/lfs.h | korjaa/mbed-os | 18634009c5f841a4df53c56ec053668c344ce24f | [
"Apache-2.0",
"BSD-3-Clause"
] | 4 | 2019-03-06T14:34:37.000Z | 2020-12-29T07:03:57.000Z | /*
* The little filesystem
*
* Copyright (c) 2017 ARM Limited
*
* 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 LFS_H
#define LFS_H
#include <stdint.h>
#include <stdbool.h>
/// Version info ///
// Software library version
// Major (top-nibble), incremented on backwards incompatible changes
// Minor (bottom-nibble), incremented on feature additions
#define LFS_VERSION 0x00010003
#define LFS_VERSION_MAJOR (0xffff & (LFS_VERSION >> 16))
#define LFS_VERSION_MINOR (0xffff & (LFS_VERSION >> 0))
// Version of On-disk data structures
// Major (top-nibble), incremented on backwards incompatible changes
// Minor (bottom-nibble), incremented on feature additions
#define LFS_DISK_VERSION 0x00010001
#define LFS_DISK_VERSION_MAJOR (0xffff & (LFS_DISK_VERSION >> 16))
#define LFS_DISK_VERSION_MINOR (0xffff & (LFS_DISK_VERSION >> 0))
/// Definitions ///
// Type definitions
typedef uint32_t lfs_size_t;
typedef uint32_t lfs_off_t;
typedef int32_t lfs_ssize_t;
typedef int32_t lfs_soff_t;
typedef uint32_t lfs_block_t;
// Max name size in bytes
#ifndef LFS_NAME_MAX
#define LFS_NAME_MAX 255
#endif
// Possible error codes, these are negative to allow
// valid positive return values
enum lfs_error {
LFS_ERR_OK = 0, // No error
LFS_ERR_IO = -5, // Error during device operation
LFS_ERR_CORRUPT = -52, // Corrupted
LFS_ERR_NOENT = -2, // No directory entry
LFS_ERR_EXIST = -17, // Entry already exists
LFS_ERR_NOTDIR = -20, // Entry is not a dir
LFS_ERR_ISDIR = -21, // Entry is a dir
LFS_ERR_NOTEMPTY = -39, // Dir is not empty
LFS_ERR_BADF = -9, // Bad file number
LFS_ERR_INVAL = -22, // Invalid parameter
LFS_ERR_NOSPC = -28, // No space left on device
LFS_ERR_NOMEM = -12, // No more memory available
};
// File types
enum lfs_type {
LFS_TYPE_REG = 0x11,
LFS_TYPE_DIR = 0x22,
LFS_TYPE_SUPERBLOCK = 0x2e,
};
// File open flags
enum lfs_open_flags {
// open flags
LFS_O_RDONLY = 1, // Open a file as read only
LFS_O_WRONLY = 2, // Open a file as write only
LFS_O_RDWR = 3, // Open a file as read and write
LFS_O_CREAT = 0x0100, // Create a file if it does not exist
LFS_O_EXCL = 0x0200, // Fail if a file already exists
LFS_O_TRUNC = 0x0400, // Truncate the existing file to zero size
LFS_O_APPEND = 0x0800, // Move to end of file on every write
// internally used flags
LFS_F_DIRTY = 0x10000, // File does not match storage
LFS_F_WRITING = 0x20000, // File has been written since last flush
LFS_F_READING = 0x40000, // File has been read since last flush
LFS_F_ERRED = 0x80000, // An error occurred during write
};
// File seek flags
enum lfs_whence_flags {
LFS_SEEK_SET = 0, // Seek relative to an absolute position
LFS_SEEK_CUR = 1, // Seek relative to the current file position
LFS_SEEK_END = 2, // Seek relative to the end of the file
};
// Configuration provided during initialization of the littlefs
struct lfs_config {
// Opaque user provided context that can be used to pass
// information to the block device operations
void *context;
// Read a region in a block. Negative error codes are propogated
// to the user.
int (*read)(const struct lfs_config *c, lfs_block_t block,
lfs_off_t off, void *buffer, lfs_size_t size);
// Program a region in a block. The block must have previously
// been erased. Negative error codes are propogated to the user.
// May return LFS_ERR_CORRUPT if the block should be considered bad.
int (*prog)(const struct lfs_config *c, lfs_block_t block,
lfs_off_t off, const void *buffer, lfs_size_t size);
// Erase a block. A block must be erased before being programmed.
// The state of an erased block is undefined. Negative error codes
// are propogated to the user.
// May return LFS_ERR_CORRUPT if the block should be considered bad.
int (*erase)(const struct lfs_config *c, lfs_block_t block);
// Sync the state of the underlying block device. Negative error codes
// are propogated to the user.
int (*sync)(const struct lfs_config *c);
// Minimum size of a block read. This determines the size of read buffers.
// This may be larger than the physical read size to improve performance
// by caching more of the block device.
lfs_size_t read_size;
// Minimum size of a block program. This determines the size of program
// buffers. This may be larger than the physical program size to improve
// performance by caching more of the block device.
// Must be a multiple of the read size.
lfs_size_t prog_size;
// Size of an erasable block. This does not impact ram consumption and
// may be larger than the physical erase size. However, this should be
// kept small as each file currently takes up an entire block.
// Must be a multiple of the program size.
lfs_size_t block_size;
// Number of erasable blocks on the device.
lfs_size_t block_count;
// Number of blocks to lookahead during block allocation. A larger
// lookahead reduces the number of passes required to allocate a block.
// The lookahead buffer requires only 1 bit per block so it can be quite
// large with little ram impact. Should be a multiple of 32.
lfs_size_t lookahead;
// Optional, statically allocated read buffer. Must be read sized.
void *read_buffer;
// Optional, statically allocated program buffer. Must be program sized.
void *prog_buffer;
// Optional, statically allocated lookahead buffer. Must be 1 bit per
// lookahead block.
void *lookahead_buffer;
// Optional, statically allocated buffer for files. Must be program sized.
// If enabled, only one file may be opened at a time.
void *file_buffer;
};
// File info structure
struct lfs_info {
// Type of the file, either LFS_TYPE_REG or LFS_TYPE_DIR
uint8_t type;
// Size of the file, only valid for REG files
lfs_size_t size;
// Name of the file stored as a null-terminated string
char name[LFS_NAME_MAX+1];
};
/// littlefs data structures ///
typedef struct lfs_entry {
lfs_off_t off;
struct lfs_disk_entry {
uint8_t type;
uint8_t elen;
uint8_t alen;
uint8_t nlen;
union {
struct {
lfs_block_t head;
lfs_size_t size;
} file;
lfs_block_t dir[2];
} u;
} d;
} lfs_entry_t;
typedef struct lfs_cache {
lfs_block_t block;
lfs_off_t off;
uint8_t *buffer;
} lfs_cache_t;
typedef struct lfs_file {
struct lfs_file *next;
lfs_block_t pair[2];
lfs_off_t poff;
lfs_block_t head;
lfs_size_t size;
uint32_t flags;
lfs_off_t pos;
lfs_block_t block;
lfs_off_t off;
lfs_cache_t cache;
} lfs_file_t;
typedef struct lfs_dir {
struct lfs_dir *next;
lfs_block_t pair[2];
lfs_off_t off;
lfs_block_t head[2];
lfs_off_t pos;
struct lfs_disk_dir {
uint32_t rev;
lfs_size_t size;
lfs_block_t tail[2];
} d;
} lfs_dir_t;
typedef struct lfs_superblock {
lfs_off_t off;
struct lfs_disk_superblock {
uint8_t type;
uint8_t elen;
uint8_t alen;
uint8_t nlen;
lfs_block_t root[2];
uint32_t block_size;
uint32_t block_count;
uint32_t version;
char magic[8];
} d;
} lfs_superblock_t;
typedef struct lfs_free {
lfs_block_t off;
lfs_block_t size;
lfs_block_t index;
lfs_block_t ack;
uint32_t *buffer;
} lfs_free_t;
// The littlefs type
typedef struct lfs {
const struct lfs_config *cfg;
lfs_block_t root[2];
lfs_file_t *files;
lfs_dir_t *dirs;
lfs_cache_t rcache;
lfs_cache_t pcache;
lfs_free_t free;
bool deorphaned;
} lfs_t;
/// Filesystem functions ///
// Format a block device with the littlefs
//
// Requires a littlefs object and config struct. This clobbers the littlefs
// object, and does not leave the filesystem mounted.
//
// Returns a negative error code on failure.
int lfs_format(lfs_t *lfs, const struct lfs_config *config);
// Mounts a littlefs
//
// Requires a littlefs object and config struct. Multiple filesystems
// may be mounted simultaneously with multiple littlefs objects. Both
// lfs and config must be allocated while mounted.
//
// Returns a negative error code on failure.
int lfs_mount(lfs_t *lfs, const struct lfs_config *config);
// Unmounts a littlefs
//
// Does nothing besides releasing any allocated resources.
// Returns a negative error code on failure.
int lfs_unmount(lfs_t *lfs);
/// General operations ///
// Removes a file or directory
//
// If removing a directory, the directory must be empty.
// Returns a negative error code on failure.
int lfs_remove(lfs_t *lfs, const char *path);
// Rename or move a file or directory
//
// If the destination exists, it must match the source in type.
// If the destination is a directory, the directory must be empty.
//
// Note: If power loss occurs, it is possible that the file or directory
// will exist in both the oldpath and newpath simultaneously after the
// next mount.
//
// Returns a negative error code on failure.
int lfs_rename(lfs_t *lfs, const char *oldpath, const char *newpath);
// Find info about a file or directory
//
// Fills out the info structure, based on the specified file or directory.
// Returns a negative error code on failure.
int lfs_stat(lfs_t *lfs, const char *path, struct lfs_info *info);
/// File operations ///
// Open a file
//
// The mode that the file is opened in is determined
// by the flags, which are values from the enum lfs_open_flags
// that are bitwise-ored together.
//
// Returns a negative error code on failure.
int lfs_file_open(lfs_t *lfs, lfs_file_t *file,
const char *path, int flags);
// Close a file
//
// Any pending writes are written out to storage as though
// sync had been called and releases any allocated resources.
//
// Returns a negative error code on failure.
int lfs_file_close(lfs_t *lfs, lfs_file_t *file);
// Synchronize a file on storage
//
// Any pending writes are written out to storage.
// Returns a negative error code on failure.
int lfs_file_sync(lfs_t *lfs, lfs_file_t *file);
// Read data from file
//
// Takes a buffer and size indicating where to store the read data.
// Returns the number of bytes read, or a negative error code on failure.
lfs_ssize_t lfs_file_read(lfs_t *lfs, lfs_file_t *file,
void *buffer, lfs_size_t size);
// Write data to file
//
// Takes a buffer and size indicating the data to write. The file will not
// actually be updated on the storage until either sync or close is called.
//
// Returns the number of bytes written, or a negative error code on failure.
lfs_ssize_t lfs_file_write(lfs_t *lfs, lfs_file_t *file,
const void *buffer, lfs_size_t size);
// Change the position of the file
//
// The change in position is determined by the offset and whence flag.
// Returns the old position of the file, or a negative error code on failure.
lfs_soff_t lfs_file_seek(lfs_t *lfs, lfs_file_t *file,
lfs_soff_t off, int whence);
// Truncates the size of the file to the specified size
//
// Returns a negative error code on failure.
int lfs_file_truncate(lfs_t *lfs, lfs_file_t *file, lfs_off_t size);
// Return the position of the file
//
// Equivalent to lfs_file_seek(lfs, file, 0, LFS_SEEK_CUR)
// Returns the position of the file, or a negative error code on failure.
lfs_soff_t lfs_file_tell(lfs_t *lfs, lfs_file_t *file);
// Change the position of the file to the beginning of the file
//
// Equivalent to lfs_file_seek(lfs, file, 0, LFS_SEEK_CUR)
// Returns a negative error code on failure.
int lfs_file_rewind(lfs_t *lfs, lfs_file_t *file);
// Return the size of the file
//
// Similar to lfs_file_seek(lfs, file, 0, LFS_SEEK_END)
// Returns the size of the file, or a negative error code on failure.
lfs_soff_t lfs_file_size(lfs_t *lfs, lfs_file_t *file);
/// Directory operations ///
// Create a directory
//
// Returns a negative error code on failure.
int lfs_mkdir(lfs_t *lfs, const char *path);
// Open a directory
//
// Once open a directory can be used with read to iterate over files.
// Returns a negative error code on failure.
int lfs_dir_open(lfs_t *lfs, lfs_dir_t *dir, const char *path);
// Close a directory
//
// Releases any allocated resources.
// Returns a negative error code on failure.
int lfs_dir_close(lfs_t *lfs, lfs_dir_t *dir);
// Read an entry in the directory
//
// Fills out the info structure, based on the specified file or directory.
// Returns a negative error code on failure.
int lfs_dir_read(lfs_t *lfs, lfs_dir_t *dir, struct lfs_info *info);
// Change the position of the directory
//
// The new off must be a value previous returned from tell and specifies
// an absolute offset in the directory seek.
//
// Returns a negative error code on failure.
int lfs_dir_seek(lfs_t *lfs, lfs_dir_t *dir, lfs_off_t off);
// Return the position of the directory
//
// The returned offset is only meant to be consumed by seek and may not make
// sense, but does indicate the current position in the directory iteration.
//
// Returns the position of the directory, or a negative error code on failure.
lfs_soff_t lfs_dir_tell(lfs_t *lfs, lfs_dir_t *dir);
// Change the position of the directory to the beginning of the directory
//
// Returns a negative error code on failure.
int lfs_dir_rewind(lfs_t *lfs, lfs_dir_t *dir);
/// Miscellaneous littlefs specific operations ///
// Traverse through all blocks in use by the filesystem
//
// The provided callback will be called with each block address that is
// currently in use by the filesystem. This can be used to determine which
// blocks are in use or how much of the storage is available.
//
// Returns a negative error code on failure.
int lfs_traverse(lfs_t *lfs, int (*cb)(void*, lfs_block_t), void *data);
// Prunes any recoverable errors that may have occurred in the filesystem
//
// Not needed to be called by user unless an operation is interrupted
// but the filesystem is still mounted. This is already called on first
// allocation.
//
// Returns a negative error code on failure.
int lfs_deorphan(lfs_t *lfs);
#endif
| 31.208768 | 78 | 0.70774 | [
"object"
] |
6831eeef37a88014983e9c037675c172ceced7ff | 7,001 | h | C | aws-cpp-sdk-iot/include/aws/iot/model/GetCardinalityRequest.h | grujicbr/aws-sdk-cpp | bdd43c178042f09c6739645e3f6cd17822a7c35c | [
"Apache-2.0"
] | 1 | 2020-07-16T19:02:58.000Z | 2020-07-16T19:02:58.000Z | aws-cpp-sdk-iot/include/aws/iot/model/GetCardinalityRequest.h | novaquark/aws-sdk-cpp | a0969508545bec9ae2864c9e1e2bb9aff109f90c | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-iot/include/aws/iot/model/GetCardinalityRequest.h | novaquark/aws-sdk-cpp | a0969508545bec9ae2864c9e1e2bb9aff109f90c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/iot/IoT_EXPORTS.h>
#include <aws/iot/IoTRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace IoT
{
namespace Model
{
/**
*/
class AWS_IOT_API GetCardinalityRequest : public IoTRequest
{
public:
GetCardinalityRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "GetCardinality"; }
Aws::String SerializePayload() const override;
/**
* <p>The name of the index to search.</p>
*/
inline const Aws::String& GetIndexName() const{ return m_indexName; }
/**
* <p>The name of the index to search.</p>
*/
inline bool IndexNameHasBeenSet() const { return m_indexNameHasBeenSet; }
/**
* <p>The name of the index to search.</p>
*/
inline void SetIndexName(const Aws::String& value) { m_indexNameHasBeenSet = true; m_indexName = value; }
/**
* <p>The name of the index to search.</p>
*/
inline void SetIndexName(Aws::String&& value) { m_indexNameHasBeenSet = true; m_indexName = std::move(value); }
/**
* <p>The name of the index to search.</p>
*/
inline void SetIndexName(const char* value) { m_indexNameHasBeenSet = true; m_indexName.assign(value); }
/**
* <p>The name of the index to search.</p>
*/
inline GetCardinalityRequest& WithIndexName(const Aws::String& value) { SetIndexName(value); return *this;}
/**
* <p>The name of the index to search.</p>
*/
inline GetCardinalityRequest& WithIndexName(Aws::String&& value) { SetIndexName(std::move(value)); return *this;}
/**
* <p>The name of the index to search.</p>
*/
inline GetCardinalityRequest& WithIndexName(const char* value) { SetIndexName(value); return *this;}
/**
* <p>The search query.</p>
*/
inline const Aws::String& GetQueryString() const{ return m_queryString; }
/**
* <p>The search query.</p>
*/
inline bool QueryStringHasBeenSet() const { return m_queryStringHasBeenSet; }
/**
* <p>The search query.</p>
*/
inline void SetQueryString(const Aws::String& value) { m_queryStringHasBeenSet = true; m_queryString = value; }
/**
* <p>The search query.</p>
*/
inline void SetQueryString(Aws::String&& value) { m_queryStringHasBeenSet = true; m_queryString = std::move(value); }
/**
* <p>The search query.</p>
*/
inline void SetQueryString(const char* value) { m_queryStringHasBeenSet = true; m_queryString.assign(value); }
/**
* <p>The search query.</p>
*/
inline GetCardinalityRequest& WithQueryString(const Aws::String& value) { SetQueryString(value); return *this;}
/**
* <p>The search query.</p>
*/
inline GetCardinalityRequest& WithQueryString(Aws::String&& value) { SetQueryString(std::move(value)); return *this;}
/**
* <p>The search query.</p>
*/
inline GetCardinalityRequest& WithQueryString(const char* value) { SetQueryString(value); return *this;}
/**
* <p>The field to aggregate.</p>
*/
inline const Aws::String& GetAggregationField() const{ return m_aggregationField; }
/**
* <p>The field to aggregate.</p>
*/
inline bool AggregationFieldHasBeenSet() const { return m_aggregationFieldHasBeenSet; }
/**
* <p>The field to aggregate.</p>
*/
inline void SetAggregationField(const Aws::String& value) { m_aggregationFieldHasBeenSet = true; m_aggregationField = value; }
/**
* <p>The field to aggregate.</p>
*/
inline void SetAggregationField(Aws::String&& value) { m_aggregationFieldHasBeenSet = true; m_aggregationField = std::move(value); }
/**
* <p>The field to aggregate.</p>
*/
inline void SetAggregationField(const char* value) { m_aggregationFieldHasBeenSet = true; m_aggregationField.assign(value); }
/**
* <p>The field to aggregate.</p>
*/
inline GetCardinalityRequest& WithAggregationField(const Aws::String& value) { SetAggregationField(value); return *this;}
/**
* <p>The field to aggregate.</p>
*/
inline GetCardinalityRequest& WithAggregationField(Aws::String&& value) { SetAggregationField(std::move(value)); return *this;}
/**
* <p>The field to aggregate.</p>
*/
inline GetCardinalityRequest& WithAggregationField(const char* value) { SetAggregationField(value); return *this;}
/**
* <p>The query version.</p>
*/
inline const Aws::String& GetQueryVersion() const{ return m_queryVersion; }
/**
* <p>The query version.</p>
*/
inline bool QueryVersionHasBeenSet() const { return m_queryVersionHasBeenSet; }
/**
* <p>The query version.</p>
*/
inline void SetQueryVersion(const Aws::String& value) { m_queryVersionHasBeenSet = true; m_queryVersion = value; }
/**
* <p>The query version.</p>
*/
inline void SetQueryVersion(Aws::String&& value) { m_queryVersionHasBeenSet = true; m_queryVersion = std::move(value); }
/**
* <p>The query version.</p>
*/
inline void SetQueryVersion(const char* value) { m_queryVersionHasBeenSet = true; m_queryVersion.assign(value); }
/**
* <p>The query version.</p>
*/
inline GetCardinalityRequest& WithQueryVersion(const Aws::String& value) { SetQueryVersion(value); return *this;}
/**
* <p>The query version.</p>
*/
inline GetCardinalityRequest& WithQueryVersion(Aws::String&& value) { SetQueryVersion(std::move(value)); return *this;}
/**
* <p>The query version.</p>
*/
inline GetCardinalityRequest& WithQueryVersion(const char* value) { SetQueryVersion(value); return *this;}
private:
Aws::String m_indexName;
bool m_indexNameHasBeenSet;
Aws::String m_queryString;
bool m_queryStringHasBeenSet;
Aws::String m_aggregationField;
bool m_aggregationFieldHasBeenSet;
Aws::String m_queryVersion;
bool m_queryVersionHasBeenSet;
};
} // namespace Model
} // namespace IoT
} // namespace Aws
| 30.977876 | 136 | 0.661191 | [
"model"
] |
6833ab3e607df2ef553e0b847355bb5cae345f50 | 8,936 | h | C | lib/abc/src/misc/mem/mem2.h | Ace-Ma/LSOracle | 6e940906303ef6c2c6b96352f44206567fdd50d3 | [
"MIT"
] | 9 | 2017-06-12T17:58:42.000Z | 2021-02-04T00:02:29.000Z | reproduction-artifact/ssatABC/src/misc/mem/mem2.h | nianzelee/PhD-Dissertation | 061e22dd55b4e58b3de3b0e58bb1cbe11435decd | [
"Apache-2.0"
] | 1 | 2020-12-15T05:59:37.000Z | 2020-12-15T05:59:37.000Z | reproduction-artifact/ssatABC/src/misc/mem/mem2.h | nianzelee/PhD-Dissertation | 061e22dd55b4e58b3de3b0e58bb1cbe11435decd | [
"Apache-2.0"
] | 3 | 2018-04-23T22:52:53.000Z | 2020-12-15T16:36:19.000Z | /**CFile****************************************************************
FileName [mem2.h]
SystemName [ABC: Logic synthesis and verification system.]
PackageName [Memory management.]
Synopsis [External declarations.]
Author [Alan Mishchenko]
Affiliation [UC Berkeley]
Date [Ver. 1.0. Started - June 20, 2005.]
Revision [$Id: mem2.h,v 1.00 2005/06/20 00:00:00 alanmi Exp $]
***********************************************************************/
#ifndef ABC__aig__mem__mem2_h
#define ABC__aig__mem__mem2_h
#include "misc/vec/vec.h"
ABC_NAMESPACE_HEADER_START
////////////////////////////////////////////////////////////////////////
/// DECLARATIONS ///
////////////////////////////////////////////////////////////////////////
typedef struct Mmr_Flex_t_ Mmr_Flex_t;
typedef struct Mmr_Fixed_t_ Mmr_Fixed_t;
typedef struct Mmr_Step_t_ Mmr_Step_t;
struct Mmr_Flex_t_
{
int nPageBase; // log2 page size in words
int PageMask; // page mask
int nEntries; // entries allocated
int nEntriesMax; // max number of enries used
int iNext; // next word to be used
Vec_Ptr_t vPages; // memory pages
};
struct Mmr_Fixed_t_
{
int nPageBase; // log2 page size in words
int PageMask; // page mask
int nEntryWords; // entry size in words
int nEntries; // entries allocated
int nEntriesMax; // max number of enries used
Vec_Ptr_t vPages; // memory pages
Vec_Int_t vFrees; // free entries
};
struct Mmr_Step_t_
{
int nBits; // the number of bits
int uMask; // the number of managers minus 1
int nEntries; // the number of entries
int nEntriesMax; // the max number of entries
int nEntriesAll; // the total number of entries
Mmr_Fixed_t pMems[0]; // memory managers: 2^0 words, 2^1 words, etc
};
////////////////////////////////////////////////////////////////////////
/// FUNCTION DEFINITIONS ///
////////////////////////////////////////////////////////////////////////
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
static inline Mmr_Flex_t * Mmr_FlexStart( int nPageBase )
{
Mmr_Flex_t * p;
p = ABC_CALLOC( Mmr_Flex_t, 1 );
p->nPageBase = nPageBase;
p->PageMask = (1 << nPageBase) - 1;
p->iNext = (1 << nPageBase);
return p;
}
static inline void Mmr_FlexStop( Mmr_Flex_t * p )
{
word * pPage;
int i;
if ( 0 && Vec_PtrSize(&p->vPages) )
printf( "Using %3d pages of %6d words each with %6d entries (max = %6d). Total memory = %5.2f MB.\n",
Vec_PtrSize(&p->vPages), p->nPageBase ? 1 << p->nPageBase : 0, p->nEntries, p->nEntriesMax,
1.0 * Vec_PtrSize(&p->vPages) * (1 << p->nPageBase) * 8 / (1 << 20) );
Vec_PtrForEachEntry( word *, &p->vPages, pPage, i )
ABC_FREE( pPage );
ABC_FREE( p->vPages.pArray );
ABC_FREE( p );
}
static inline word * Mmr_FlexEntry( Mmr_Flex_t * p, int h )
{
assert( h > 0 && h < p->iNext );
return (word *)Vec_PtrEntry(&p->vPages, (h >> p->nPageBase)) + (h & p->PageMask);
}
static inline int Mmr_FlexFetch( Mmr_Flex_t * p, int nWords )
{
int hEntry;
assert( nWords > 0 && nWords < p->PageMask );
if ( p->iNext + nWords >= p->PageMask )
{
Vec_PtrPush( &p->vPages, ABC_FALLOC( word, p->PageMask + 1 ) );
p->iNext = 1;
}
hEntry = ((Vec_PtrSize(&p->vPages) - 1) << p->nPageBase) | p->iNext;
p->iNext += nWords;
p->nEntries++;
p->nEntriesMax = Abc_MaxInt( p->nEntriesMax, p->nEntries );
return hEntry;
}
static inline void Mmr_FlexRelease( Mmr_Flex_t * p, int h )
{
assert( h > 0 && h < p->iNext );
if ( (h >> p->nPageBase) && Vec_PtrEntry(&p->vPages, (h >> p->nPageBase) - 1) )
{
word * pPage = (word *)Vec_PtrEntry(&p->vPages, (h >> p->nPageBase) - 1);
Vec_PtrWriteEntry( &p->vPages, (h >> p->nPageBase) - 1, NULL );
ABC_FREE( pPage );
}
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
static inline void Mmr_FixedCreate( Mmr_Fixed_t * p, int nPageBase, int nEntryWords )
{
assert( nEntryWords > 0 && nEntryWords < (1 << nPageBase) );
p->nPageBase = nPageBase;
p->PageMask = (1 << nPageBase) - 1;
p->nEntryWords = nEntryWords;
}
static inline Mmr_Fixed_t * Mmr_FixedStart( int nPageBase, int nEntryWords )
{
Mmr_Fixed_t * p = ABC_CALLOC( Mmr_Fixed_t, 1 );
Mmr_FixedCreate( p, nPageBase, nEntryWords );
return p;
}
static inline void Mmr_FixedStop( Mmr_Fixed_t * p, int fFreeLast )
{
word * pPage;
int i;
if ( 0 && Vec_PtrSize(&p->vPages) )
printf( "Using %3d pages of %6d words each with %6d entries (max = %6d) of size %d. Total memory = %5.2f MB.\n",
Vec_PtrSize(&p->vPages), p->nPageBase ? 1 << p->nPageBase : 0, p->nEntries, p->nEntriesMax, p->nEntryWords,
1.0 * Vec_PtrSize(&p->vPages) * (1 << p->nPageBase) * 8 / (1 << 20) );
Vec_PtrForEachEntry( word *, &p->vPages, pPage, i )
ABC_FREE( pPage );
ABC_FREE( p->vPages.pArray );
ABC_FREE( p->vFrees.pArray );
if ( fFreeLast )
ABC_FREE( p );
}
static inline word * Mmr_FixedEntry( Mmr_Fixed_t * p, int h )
{
assert( h > 0 && h < (Vec_PtrSize(&p->vPages) << p->nPageBase) );
return (word *)Vec_PtrEntry(&p->vPages, (h >> p->nPageBase)) + (h & p->PageMask);
}
static inline int Mmr_FixedFetch( Mmr_Fixed_t * p )
{
if ( Vec_IntSize(&p->vFrees) == 0 )
{
int i, hEntry = Vec_PtrSize(&p->vPages) << p->nPageBase;
Vec_PtrPush( &p->vPages, ABC_FALLOC( word, p->PageMask + 1 ) );
for ( i = 1; i + p->nEntryWords <= p->PageMask; i += p->nEntryWords )
Vec_IntPush( &p->vFrees, hEntry | i );
Vec_IntReverseOrder( &p->vFrees );
}
p->nEntries++;
p->nEntriesMax = Abc_MaxInt( p->nEntriesMax, p->nEntries );
return Vec_IntPop( &p->vFrees );
}
static inline void Mmr_FixedRecycle( Mmr_Fixed_t * p, int h )
{
p->nEntries--;
memset( Mmr_FixedEntry(p, h), 0xFF, sizeof(word) * p->nEntryWords );
Vec_IntPush( &p->vFrees, h );
}
static inline int Mmr_FixedMemory( Mmr_Fixed_t * p )
{
return Vec_PtrSize(&p->vPages) * (p->PageMask + 1);
}
/**Function*************************************************************
Synopsis []
Description []
SideEffects []
SeeAlso []
***********************************************************************/
static inline Mmr_Step_t * Mmr_StepStart( int nPageBase, int nWordBase )
{
char * pMemory = ABC_CALLOC( char, sizeof(Mmr_Step_t) + sizeof(Mmr_Fixed_t) * (1 << nWordBase) );
Mmr_Step_t * p = (Mmr_Step_t *)pMemory;
int i;
p->nBits = nWordBase;
p->uMask = (1 << nWordBase) - 1;
for ( i = 1; i <= p->uMask; i++ )
Mmr_FixedCreate( p->pMems + i, nPageBase, i );
return p;
}
static inline void Mmr_StepStop( Mmr_Step_t * p )
{
int i;
for ( i = 0; i <= p->uMask; i++ )
Mmr_FixedStop( p->pMems + i, 0 );
ABC_FREE( p );
}
static inline word * Mmr_StepEntry( Mmr_Step_t * p, int h )
{
assert( (h & p->uMask) > 0 );
return Mmr_FixedEntry( p->pMems + (h & p->uMask), (h >> p->nBits) );
}
static inline int Mmr_StepFetch( Mmr_Step_t * p, int nWords )
{
assert( nWords > 0 && nWords <= p->uMask );
p->nEntries++;
p->nEntriesAll++;
p->nEntriesMax = Abc_MaxInt( p->nEntriesMax, p->nEntries );
return (Mmr_FixedFetch(p->pMems + nWords) << p->nBits) | nWords;
}
static inline void Mmr_StepRecycle( Mmr_Step_t * p, int h )
{
p->nEntries--;
Mmr_FixedRecycle( p->pMems + (h & p->uMask), (h >> p->nBits) );
}
static inline int Mmr_StepMemory( Mmr_Step_t * p )
{
int i, Mem = 0;
for ( i = 1; i <= p->uMask; i++ )
Mem += Mmr_FixedMemory( p->pMems + i );
return Mem;
}
ABC_NAMESPACE_HEADER_END
#endif
////////////////////////////////////////////////////////////////////////
/// END OF FILE ///
////////////////////////////////////////////////////////////////////////
| 32.852941 | 122 | 0.493957 | [
"3d"
] |
683937ed78e79036aa91b5be74d035901ca9919b | 68,368 | c | C | src/sim65/6502.c | xTibor/cc65 | 4799c47cc89913d7a17ad36ffd6dd4a0ded7f0d6 | [
"Zlib"
] | 1 | 2019-07-17T21:23:24.000Z | 2019-07-17T21:23:24.000Z | src/sim65/6502.c | xTibor/cc65 | 4799c47cc89913d7a17ad36ffd6dd4a0ded7f0d6 | [
"Zlib"
] | null | null | null | src/sim65/6502.c | xTibor/cc65 | 4799c47cc89913d7a17ad36ffd6dd4a0ded7f0d6 | [
"Zlib"
] | null | null | null | /*****************************************************************************/
/* */
/* 6502.c */
/* */
/* CPU core for the 6502 */
/* */
/* */
/* */
/* (C) 2003-2012, Ullrich von Bassewitz */
/* Roemerstrasse 52 */
/* D-70794 Filderstadt */
/* EMail: uz@cc65.org */
/* */
/* Mar-2017, Christian Krueger, added support for 65SC02 */
/* */
/* This software is provided 'as-is', without any expressed or implied */
/* warranty. In no event will the authors be held liable for any damages */
/* arising from the use of this software. */
/* */
/* Permission is granted to anyone to use this software for any purpose, */
/* including commercial applications, and to alter it and redistribute it */
/* freely, subject to the following restrictions: */
/* */
/* 1. The origin of this software must not be misrepresented; you must not */
/* claim that you wrote the original software. If you use this software */
/* in a product, an acknowledgment in the product documentation would be */
/* appreciated but is not required. */
/* 2. Altered source versions must be plainly marked as such, and must not */
/* be misrepresented as being the original software. */
/* 3. This notice may not be removed or altered from any source */
/* distribution. */
/* */
/*****************************************************************************/
/* Known bugs and limitations of the 65C02 simulation:
* support currently only on the level of 65SC02:
BBRx, BBSx, RMBx, SMBx, WAI, and STP are unsupported
* BCD flag handling equals 6502 (unchecked if bug is simulated or wrong for
6502)
*/
#include "memory.h"
#include "error.h"
#include "6502.h"
#include "paravirt.h"
/*****************************************************************************/
/* Data */
/*****************************************************************************/
/* Current CPU */
CPUType CPU;
/* Type of an opcode handler function */
typedef void (*OPFunc) (void);
/* The CPU registers */
static CPURegs Regs;
/* Cycles for the current insn */
static unsigned Cycles;
/* Total number of CPU cycles exec'd */
static unsigned long TotalCycles;
/* NMI request active */
static unsigned HaveNMIRequest;
/* IRQ request active */
static unsigned HaveIRQRequest;
/* flag to print cycles at program termination */
int PrintCycles;
/*****************************************************************************/
/* Helper functions and macros */
/*****************************************************************************/
/* Return the flags as boolean values (0/1) */
#define GET_CF() ((Regs.SR & CF) != 0)
#define GET_ZF() ((Regs.SR & ZF) != 0)
#define GET_IF() ((Regs.SR & IF) != 0)
#define GET_DF() ((Regs.SR & DF) != 0)
#define GET_OF() ((Regs.SR & OF) != 0)
#define GET_SF() ((Regs.SR & SF) != 0)
/* Set the flags. The parameter is a boolean flag that says if the flag should be
** set or reset.
*/
#define SET_CF(f) do { if (f) { Regs.SR |= CF; } else { Regs.SR &= ~CF; } } while (0)
#define SET_ZF(f) do { if (f) { Regs.SR |= ZF; } else { Regs.SR &= ~ZF; } } while (0)
#define SET_IF(f) do { if (f) { Regs.SR |= IF; } else { Regs.SR &= ~IF; } } while (0)
#define SET_DF(f) do { if (f) { Regs.SR |= DF; } else { Regs.SR &= ~DF; } } while (0)
#define SET_OF(f) do { if (f) { Regs.SR |= OF; } else { Regs.SR &= ~OF; } } while (0)
#define SET_SF(f) do { if (f) { Regs.SR |= SF; } else { Regs.SR &= ~SF; } } while (0)
/* Special test and set macros. The meaning of the parameter depends on the
** actual flag that should be set or reset.
*/
#define TEST_ZF(v) SET_ZF (((v) & 0xFF) == 0)
#define TEST_SF(v) SET_SF (((v) & 0x80) != 0)
#define TEST_CF(v) SET_CF (((v) & 0xFF00) != 0)
/* Program counter halves */
#define PCL (Regs.PC & 0xFF)
#define PCH ((Regs.PC >> 8) & 0xFF)
/* Stack operations */
#define PUSH(Val) MemWriteByte (0x0100 | (Regs.SP-- & 0xFF), Val)
#define POP() MemReadByte (0x0100 | (++Regs.SP & 0xFF))
/* Test for page cross */
#define PAGE_CROSS(addr,offs) ((((addr) & 0xFF) + offs) >= 0x100)
/* #imm */
#define AC_OP_IMM(op) \
Cycles = 2; \
Regs.AC = Regs.AC op MemReadByte (Regs.PC+1); \
TEST_ZF (Regs.AC); \
TEST_SF (Regs.AC); \
Regs.PC += 2
/* zp */
#define AC_OP_ZP(op) \
Cycles = 3; \
Regs.AC = Regs.AC op MemReadByte (MemReadByte (Regs.PC+1)); \
TEST_ZF (Regs.AC); \
TEST_SF (Regs.AC); \
Regs.PC += 2
/* zp,x */
#define AC_OP_ZPX(op) \
unsigned char ZPAddr; \
Cycles = 4; \
ZPAddr = MemReadByte (Regs.PC+1) + Regs.XR; \
Regs.AC = Regs.AC op MemReadByte (ZPAddr); \
TEST_ZF (Regs.AC); \
TEST_SF (Regs.AC); \
Regs.PC += 2
/* zp,y */
#define AC_OP_ZPY(op) \
unsigned char ZPAddr; \
Cycles = 4; \
ZPAddr = MemReadByte (Regs.PC+1) + Regs.YR; \
Regs.AC = Regs.AC op MemReadByte (ZPAddr); \
TEST_ZF (Regs.AC); \
TEST_SF (Regs.AC); \
Regs.PC += 2
/* abs */
#define AC_OP_ABS(op) \
unsigned Addr; \
Cycles = 4; \
Addr = MemReadWord (Regs.PC+1); \
Regs.AC = Regs.AC op MemReadByte (Addr); \
TEST_ZF (Regs.AC); \
TEST_SF (Regs.AC); \
Regs.PC += 3
/* abs,x */
#define AC_OP_ABSX(op) \
unsigned Addr; \
Cycles = 4; \
Addr = MemReadWord (Regs.PC+1); \
if (PAGE_CROSS (Addr, Regs.XR)) { \
++Cycles; \
} \
Regs.AC = Regs.AC op MemReadByte (Addr + Regs.XR); \
TEST_ZF (Regs.AC); \
TEST_SF (Regs.AC); \
Regs.PC += 3
/* abs,y */
#define AC_OP_ABSY(op) \
unsigned Addr; \
Cycles = 4; \
Addr = MemReadWord (Regs.PC+1); \
if (PAGE_CROSS (Addr, Regs.YR)) { \
++Cycles; \
} \
Regs.AC = Regs.AC op MemReadByte (Addr + Regs.YR); \
TEST_ZF (Regs.AC); \
TEST_SF (Regs.AC); \
Regs.PC += 3
/* (zp,x) */
#define AC_OP_ZPXIND(op) \
unsigned char ZPAddr; \
unsigned Addr; \
Cycles = 6; \
ZPAddr = MemReadByte (Regs.PC+1) + Regs.XR; \
Addr = MemReadZPWord (ZPAddr); \
Regs.AC = Regs.AC op MemReadByte (Addr); \
TEST_ZF (Regs.AC); \
TEST_SF (Regs.AC); \
Regs.PC += 2
/* (zp),y */
#define AC_OP_ZPINDY(op) \
unsigned char ZPAddr; \
unsigned Addr; \
Cycles = 5; \
ZPAddr = MemReadByte (Regs.PC+1); \
Addr = MemReadZPWord (ZPAddr); \
if (PAGE_CROSS (Addr, Regs.YR)) { \
++Cycles; \
} \
Addr += Regs.YR; \
Regs.AC = Regs.AC op MemReadByte (Addr); \
TEST_ZF (Regs.AC); \
TEST_SF (Regs.AC); \
Regs.PC += 2
/* (zp) */
#define AC_OP_ZPIND(op) \
unsigned char ZPAddr; \
unsigned Addr; \
Cycles = 5; \
ZPAddr = MemReadByte (Regs.PC+1); \
Addr = MemReadZPWord (ZPAddr); \
Regs.AC = Regs.AC op MemReadByte (Addr); \
TEST_ZF (Regs.AC); \
TEST_SF (Regs.AC); \
Regs.PC += 2
/* ADC */
#define ADC(v) \
do { \
unsigned old = Regs.AC; \
unsigned rhs = (v & 0xFF); \
if (GET_DF ()) { \
unsigned lo; \
int res; \
lo = (old & 0x0F) + (rhs & 0x0F) + GET_CF (); \
if (lo >= 0x0A) { \
lo = ((lo + 0x06) & 0x0F) + 0x10; \
} \
Regs.AC = (old & 0xF0) + (rhs & 0xF0) + lo; \
res = (signed char)(old & 0xF0) + \
(signed char)(rhs & 0xF0) + \
(signed char)lo; \
TEST_ZF (old + rhs + GET_CF ()); \
TEST_SF (Regs.AC); \
if (Regs.AC >= 0xA0) { \
Regs.AC += 0x60; \
} \
TEST_CF (Regs.AC); \
SET_OF ((res < -128) || (res > 127)); \
if (CPU != CPU_6502) { \
++Cycles; \
} \
} else { \
Regs.AC += rhs + GET_CF (); \
TEST_ZF (Regs.AC); \
TEST_SF (Regs.AC); \
TEST_CF (Regs.AC); \
SET_OF (!((old ^ rhs) & 0x80) && \
((old ^ Regs.AC) & 0x80)); \
Regs.AC &= 0xFF; \
} \
} while (0)
/* branches */
#define BRANCH(cond) \
Cycles = 2; \
if (cond) { \
signed char Offs; \
unsigned char OldPCH; \
++Cycles; \
Offs = (signed char) MemReadByte (Regs.PC+1); \
OldPCH = PCH; \
Regs.PC += 2 + (int) Offs; \
if (PCH != OldPCH) { \
++Cycles; \
} \
} else { \
Regs.PC += 2; \
}
/* compares */
#define CMP(v1, v2) \
do { \
unsigned Result = v1 - v2; \
TEST_ZF (Result & 0xFF); \
TEST_SF (Result); \
SET_CF (Result <= 0xFF); \
} while (0)
/* ROL */
#define ROL(Val) \
Val <<= 1; \
if (GET_CF ()) { \
Val |= 0x01; \
} \
TEST_ZF (Val); \
TEST_SF (Val); \
TEST_CF (Val)
/* ROR */
#define ROR(Val) \
if (GET_CF ()) { \
Val |= 0x100; \
} \
SET_CF (Val & 0x01); \
Val >>= 1; \
TEST_ZF (Val); \
TEST_SF (Val)
/* SBC */
#define SBC(v) \
do { \
unsigned old = Regs.AC; \
unsigned rhs = (v & 0xFF); \
if (GET_DF ()) { \
unsigned lo; \
int res; \
lo = (old & 0x0F) - (rhs & 0x0F) + GET_CF () - 1; \
if (lo & 0x80) { \
lo = ((lo - 0x06) & 0x0F) - 0x10; \
} \
Regs.AC = (old & 0xF0) - (rhs & 0xF0) + lo; \
if (Regs.AC & 0x80) { \
Regs.AC -= 0x60; \
} \
res = Regs.AC - rhs + (!GET_CF ()); \
TEST_ZF (res); \
TEST_SF (res); \
SET_CF (res <= 0xFF); \
SET_OF (((old^rhs) & (old^res) & 0x80)); \
if (CPU != CPU_6502) { \
++Cycles; \
} \
} else { \
Regs.AC -= rhs + (!GET_CF ()); \
TEST_ZF (Regs.AC); \
TEST_SF (Regs.AC); \
SET_CF (Regs.AC <= 0xFF); \
SET_OF (((old^rhs) & (old^Regs.AC) & 0x80)); \
Regs.AC &= 0xFF; \
} \
} while (0)
/*****************************************************************************/
/* Opcode handling functions */
/*****************************************************************************/
static void OPC_Illegal (void)
{
Error ("Illegal opcode $%02X at address $%04X",
MemReadByte (Regs.PC), Regs.PC);
}
static void OPC_6502_00 (void)
/* Opcode $00: BRK */
{
Cycles = 7;
Regs.PC += 2;
PUSH (PCH);
PUSH (PCL);
PUSH (Regs.SR);
SET_IF (1);
if (CPU != CPU_6502)
{
SET_DF (0);
}
Regs.PC = MemReadWord (0xFFFE);
}
static void OPC_6502_01 (void)
/* Opcode $01: ORA (ind,x) */
{
AC_OP_ZPXIND (|);
}
static void OPC_65SC02_04 (void)
/* Opcode $04: TSB zp */
{
unsigned char ZPAddr;
unsigned char Val;
Cycles = 5;
ZPAddr = MemReadByte (Regs.PC+1);
Val = MemReadByte (ZPAddr);
SET_ZF ((Val & Regs.AC) == 0);
MemWriteByte (ZPAddr, (unsigned char)(Val | Regs.AC));
Regs.PC += 2;
}
static void OPC_6502_05 (void)
/* Opcode $05: ORA zp */
{
AC_OP_ZP (|);
}
static void OPC_6502_06 (void)
/* Opcode $06: ASL zp */
{
unsigned char ZPAddr;
unsigned Val;
Cycles = 5;
ZPAddr = MemReadByte (Regs.PC+1);
Val = MemReadByte (ZPAddr) << 1;
MemWriteByte (ZPAddr, (unsigned char) Val);
TEST_ZF (Val & 0xFF);
TEST_SF (Val);
SET_CF (Val & 0x100);
Regs.PC += 2;
}
static void OPC_6502_08 (void)
/* Opcode $08: PHP */
{
Cycles = 3;
PUSH (Regs.SR);
Regs.PC += 1;
}
static void OPC_6502_09 (void)
/* Opcode $09: ORA #imm */
{
AC_OP_IMM (|);
}
static void OPC_6502_0A (void)
/* Opcode $0A: ASL a */
{
Cycles = 2;
Regs.AC <<= 1;
TEST_ZF (Regs.AC & 0xFF);
TEST_SF (Regs.AC);
SET_CF (Regs.AC & 0x100);
Regs.AC &= 0xFF;
Regs.PC += 1;
}
static void OPC_65SC02_0C (void)
/* Opcode $0C: TSB abs */
{
unsigned Addr;
unsigned char Val;
Cycles = 6;
Addr = MemReadWord (Regs.PC+1);
Val = MemReadByte (Addr);
SET_ZF ((Val & Regs.AC) == 0);
MemWriteByte (Addr, (unsigned char) (Val | Regs.AC));
Regs.PC += 3;
}
static void OPC_6502_0D (void)
/* Opcode $0D: ORA abs */
{
AC_OP_ABS (|);
}
static void OPC_6502_0E (void)
/* Opcode $0E: ALS abs */
{
unsigned Addr;
unsigned Val;
Cycles = 6;
Addr = MemReadWord (Regs.PC+1);
Val = MemReadByte (Addr) << 1;
MemWriteByte (Addr, (unsigned char) Val);
TEST_ZF (Val & 0xFF);
TEST_SF (Val);
SET_CF (Val & 0x100);
Regs.PC += 3;
}
static void OPC_6502_10 (void)
/* Opcode $10: BPL */
{
BRANCH (!GET_SF ());
}
static void OPC_6502_11 (void)
/* Opcode $11: ORA (zp),y */
{
AC_OP_ZPINDY (|);
}
static void OPC_65SC02_12 (void)
/* Opcode $12: ORA (zp) */
{
AC_OP_ZPIND (|);
}
static void OPC_65SC02_14 (void)
/* Opcode $14: TRB zp */
{
unsigned char ZPAddr;
unsigned char Val;
Cycles = 5;
ZPAddr = MemReadByte (Regs.PC+1);
Val = MemReadByte (ZPAddr);
SET_ZF ((Val & Regs.AC) == 0);
MemWriteByte (ZPAddr, (unsigned char)(Val & ~Regs.AC));
Regs.PC += 2;
}
static void OPC_6502_15 (void)
/* Opcode $15: ORA zp,x */
{
AC_OP_ZPX (|);
}
static void OPC_6502_16 (void)
/* Opcode $16: ASL zp,x */
{
unsigned char ZPAddr;
unsigned Val;
Cycles = 6;
ZPAddr = MemReadByte (Regs.PC+1) + Regs.XR;
Val = MemReadByte (ZPAddr) << 1;
MemWriteByte (ZPAddr, (unsigned char) Val);
TEST_ZF (Val & 0xFF);
TEST_SF (Val);
SET_CF (Val & 0x100);
Regs.PC += 2;
}
static void OPC_6502_18 (void)
/* Opcode $18: CLC */
{
Cycles = 2;
SET_CF (0);
Regs.PC += 1;
}
static void OPC_6502_19 (void)
/* Opcode $19: ORA abs,y */
{
AC_OP_ABSY (|);
}
static void OPC_65SC02_1A (void)
/* Opcode $1A: INC a */
{
Cycles = 2;
Regs.AC = (Regs.AC + 1) & 0xFF;
TEST_ZF (Regs.AC);
TEST_SF (Regs.AC);
Regs.PC += 1;
}
static void OPC_65SC02_1C (void)
/* Opcode $1C: TRB abs */
{
unsigned Addr;
unsigned char Val;
Cycles = 6;
Addr = MemReadWord (Regs.PC+1);
Val = MemReadByte (Addr);
SET_ZF ((Val & Regs.AC) == 0);
MemWriteByte (Addr, (unsigned char) (Val & ~Regs.AC));
Regs.PC += 3;
}
static void OPC_6502_1D (void)
/* Opcode $1D: ORA abs,x */
{
AC_OP_ABSX (|);
}
static void OPC_6502_1E (void)
/* Opcode $1E: ASL abs,x */
{
unsigned Addr;
unsigned Val;
Cycles = 7;
Addr = MemReadWord (Regs.PC+1) + Regs.XR;
if (CPU != CPU_6502 && !PAGE_CROSS (Addr, Regs.XR))
--Cycles;
Val = MemReadByte (Addr) << 1;
MemWriteByte (Addr, (unsigned char) Val);
TEST_ZF (Val & 0xFF);
TEST_SF (Val);
SET_CF (Val & 0x100);
Regs.PC += 3;
}
static void OPC_6502_20 (void)
/* Opcode $20: JSR */
{
unsigned Addr;
Cycles = 6;
Addr = MemReadWord (Regs.PC+1);
Regs.PC += 2;
PUSH (PCH);
PUSH (PCL);
Regs.PC = Addr;
ParaVirtHooks (&Regs);
}
static void OPC_6502_21 (void)
/* Opcode $21: AND (zp,x) */
{
AC_OP_ZPXIND (&);
}
static void OPC_6502_24 (void)
/* Opcode $24: BIT zp */
{
unsigned char ZPAddr;
unsigned char Val;
Cycles = 3;
ZPAddr = MemReadByte (Regs.PC+1);
Val = MemReadByte (ZPAddr);
SET_SF (Val & 0x80);
SET_OF (Val & 0x40);
SET_ZF ((Val & Regs.AC) == 0);
Regs.PC += 2;
}
static void OPC_6502_25 (void)
/* Opcode $25: AND zp */
{
AC_OP_ZP (&);
}
static void OPC_6502_26 (void)
/* Opcode $26: ROL zp */
{
unsigned char ZPAddr;
unsigned Val;
Cycles = 5;
ZPAddr = MemReadByte (Regs.PC+1);
Val = MemReadByte (ZPAddr);
ROL (Val);
MemWriteByte (ZPAddr, Val);
Regs.PC += 2;
}
static void OPC_6502_28 (void)
/* Opcode $28: PLP */
{
Cycles = 4;
/* Bits 5 and 4 aren't used, and always are 1! */
Regs.SR = (POP () | 0x30);
Regs.PC += 1;
}
static void OPC_6502_29 (void)
/* Opcode $29: AND #imm */
{
AC_OP_IMM (&);
}
static void OPC_6502_2A (void)
/* Opcode $2A: ROL a */
{
Cycles = 2;
ROL (Regs.AC);
Regs.AC &= 0xFF;
Regs.PC += 1;
}
static void OPC_6502_2C (void)
/* Opcode $2C: BIT abs */
{
unsigned Addr;
unsigned char Val;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
Val = MemReadByte (Addr);
SET_SF (Val & 0x80);
SET_OF (Val & 0x40);
SET_ZF ((Val & Regs.AC) == 0);
Regs.PC += 3;
}
static void OPC_6502_2D (void)
/* Opcode $2D: AND abs */
{
AC_OP_ABS (&);
}
static void OPC_6502_2E (void)
/* Opcode $2E: ROL abs */
{
unsigned Addr;
unsigned Val;
Cycles = 6;
Addr = MemReadWord (Regs.PC+1);
Val = MemReadByte (Addr);
ROL (Val);
MemWriteByte (Addr, Val);
Regs.PC += 3;
}
static void OPC_6502_30 (void)
/* Opcode $30: BMI */
{
BRANCH (GET_SF ());
}
static void OPC_6502_31 (void)
/* Opcode $31: AND (zp),y */
{
AC_OP_ZPINDY (&);
}
static void OPC_65SC02_32 (void)
/* Opcode $32: AND (zp) */
{
AC_OP_ZPIND (&);
}
static void OPC_65SC02_34 (void)
/* Opcode $34: BIT zp,x */
{
unsigned char ZPAddr;
unsigned char Val;
Cycles = 4;
ZPAddr = MemReadByte (Regs.PC+1) + Regs.XR;
Val = MemReadByte (ZPAddr);
SET_SF (Val & 0x80);
SET_OF (Val & 0x40);
SET_ZF ((Val & Regs.AC) == 0);
Regs.PC += 2;
}
static void OPC_6502_35 (void)
/* Opcode $35: AND zp,x */
{
AC_OP_ZPX (&);
}
static void OPC_6502_36 (void)
/* Opcode $36: ROL zp,x */
{
unsigned char ZPAddr;
unsigned Val;
Cycles = 6;
ZPAddr = MemReadByte (Regs.PC+1) + Regs.XR;
Val = MemReadByte (ZPAddr);
ROL (Val);
MemWriteByte (ZPAddr, Val);
Regs.PC += 2;
}
static void OPC_6502_38 (void)
/* Opcode $38: SEC */
{
Cycles = 2;
SET_CF (1);
Regs.PC += 1;
}
static void OPC_6502_39 (void)
/* Opcode $39: AND abs,y */
{
AC_OP_ABSY (&);
}
static void OPC_65SC02_3A (void)
/* Opcode $3A: DEC a */
{
Cycles = 2;
Regs.AC = (Regs.AC - 1) & 0xFF;
TEST_ZF (Regs.AC);
TEST_SF (Regs.AC);
Regs.PC += 1;
}
static void OPC_65SC02_3C (void)
/* Opcode $3C: BIT abs,x */
{
unsigned Addr;
unsigned char Val;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
if (PAGE_CROSS (Addr, Regs.XR))
++Cycles;
Val = MemReadByte (Addr + Regs.XR);
SET_SF (Val & 0x80);
SET_OF (Val & 0x40);
SET_ZF ((Val & Regs.AC) == 0);
Regs.PC += 3;
}
static void OPC_6502_3D (void)
/* Opcode $3D: AND abs,x */
{
AC_OP_ABSX (&);
}
static void OPC_6502_3E (void)
/* Opcode $3E: ROL abs,x */
{
unsigned Addr;
unsigned Val;
Cycles = 7;
Addr = MemReadWord (Regs.PC+1) + Regs.XR;
if (CPU != CPU_6502 && !PAGE_CROSS (Addr, Regs.XR))
--Cycles;
Val = MemReadByte (Addr);
ROL (Val);
MemWriteByte (Addr, Val);
Regs.PC += 2;
}
static void OPC_6502_40 (void)
/* Opcode $40: RTI */
{
Cycles = 6;
/* Bits 5 and 4 aren't used, and always are 1! */
Regs.SR = POP () | 0x30;
Regs.PC = POP (); /* PCL */
Regs.PC |= (POP () << 8); /* PCH */
}
static void OPC_6502_41 (void)
/* Opcode $41: EOR (zp,x) */
{
AC_OP_ZPXIND (^);
}
static void OPC_65C02_44 (void)
/* Opcode $44: 'zp' 3 cycle NOP */
{
Cycles = 3;
Regs.PC += 2;
}
static void OPC_6502_45 (void)
/* Opcode $45: EOR zp */
{
AC_OP_ZP (^);
}
static void OPC_6502_46 (void)
/* Opcode $46: LSR zp */
{
unsigned char ZPAddr;
unsigned char Val;
Cycles = 5;
ZPAddr = MemReadByte (Regs.PC+1);
Val = MemReadByte (ZPAddr);
SET_CF (Val & 0x01);
Val >>= 1;
MemWriteByte (ZPAddr, Val);
TEST_ZF (Val);
TEST_SF (Val);
Regs.PC += 2;
}
static void OPC_6502_48 (void)
/* Opcode $48: PHA */
{
Cycles = 3;
PUSH (Regs.AC);
Regs.PC += 1;
}
static void OPC_6502_49 (void)
/* Opcode $49: EOR #imm */
{
AC_OP_IMM (^);
}
static void OPC_6502_4A (void)
/* Opcode $4A: LSR a */
{
Cycles = 2;
SET_CF (Regs.AC & 0x01);
Regs.AC >>= 1;
TEST_ZF (Regs.AC);
TEST_SF (Regs.AC);
Regs.PC += 1;
}
static void OPC_6502_4C (void)
/* Opcode $4C: JMP abs */
{
Cycles = 3;
Regs.PC = MemReadWord (Regs.PC+1);
ParaVirtHooks (&Regs);
}
static void OPC_6502_4D (void)
/* Opcode $4D: EOR abs */
{
AC_OP_ABS (^);
}
static void OPC_6502_4E (void)
/* Opcode $4E: LSR abs */
{
unsigned Addr;
unsigned char Val;
Cycles = 6;
Addr = MemReadWord (Regs.PC+1);
Val = MemReadByte (Addr);
SET_CF (Val & 0x01);
Val >>= 1;
MemWriteByte (Addr, Val);
TEST_ZF (Val);
TEST_SF (Val);
Regs.PC += 3;
}
static void OPC_6502_50 (void)
/* Opcode $50: BVC */
{
BRANCH (!GET_OF ());
}
static void OPC_6502_51 (void)
/* Opcode $51: EOR (zp),y */
{
AC_OP_ZPINDY (^);
}
static void OPC_65SC02_52 (void)
/* Opcode $52: EOR (zp) */
{
AC_OP_ZPIND (^);
}
static void OPC_6502_55 (void)
/* Opcode $55: EOR zp,x */
{
AC_OP_ZPX (^);
}
static void OPC_6502_56 (void)
/* Opcode $56: LSR zp,x */
{
unsigned char ZPAddr;
unsigned char Val;
Cycles = 6;
ZPAddr = MemReadByte (Regs.PC+1) + Regs.XR;
Val = MemReadByte (ZPAddr);
SET_CF (Val & 0x01);
Val >>= 1;
MemWriteByte (ZPAddr, Val);
TEST_ZF (Val);
TEST_SF (Val);
Regs.PC += 2;
}
static void OPC_6502_58 (void)
/* Opcode $58: CLI */
{
Cycles = 2;
SET_IF (0);
Regs.PC += 1;
}
static void OPC_6502_59 (void)
/* Opcode $59: EOR abs,y */
{
AC_OP_ABSY (^);
}
static void OPC_65SC02_5A (void)
/* Opcode $5A: PHY */
{
Cycles = 3;
PUSH (Regs.YR);
Regs.PC += 1;
}
static void OPC_65C02_5C (void)
/* Opcode $5C: 'Absolute' 8 cycle NOP */
{
Cycles = 8;
Regs.PC += 3;
}
static void OPC_6502_5D (void)
/* Opcode $5D: EOR abs,x */
{
AC_OP_ABSX (^);
}
static void OPC_6502_5E (void)
/* Opcode $5E: LSR abs,x */
{
unsigned Addr;
unsigned char Val;
Cycles = 7;
Addr = MemReadWord (Regs.PC+1) + Regs.XR;
if (CPU != CPU_6502 && !PAGE_CROSS (Addr, Regs.XR))
--Cycles;
Val = MemReadByte (Addr);
SET_CF (Val & 0x01);
Val >>= 1;
MemWriteByte (Addr, Val);
TEST_ZF (Val);
TEST_SF (Val);
Regs.PC += 3;
}
static void OPC_6502_60 (void)
/* Opcode $60: RTS */
{
Cycles = 6;
Regs.PC = POP (); /* PCL */
Regs.PC |= (POP () << 8); /* PCH */
Regs.PC += 1;
}
static void OPC_6502_61 (void)
/* Opcode $61: ADC (zp,x) */
{
unsigned char ZPAddr;
unsigned Addr;
Cycles = 6;
ZPAddr = MemReadByte (Regs.PC+1) + Regs.XR;
Addr = MemReadZPWord (ZPAddr);
ADC (MemReadByte (Addr));
Regs.PC += 2;
}
static void OPC_65SC02_64 (void)
/* Opcode $64: STZ zp */
{
unsigned char ZPAddr;
Cycles = 3;
ZPAddr = MemReadByte (Regs.PC+1);
MemWriteByte (ZPAddr, 0);
Regs.PC += 2;
}
static void OPC_6502_65 (void)
/* Opcode $65: ADC zp */
{
unsigned char ZPAddr;
Cycles = 3;
ZPAddr = MemReadByte (Regs.PC+1);
ADC (MemReadByte (ZPAddr));
Regs.PC += 2;
}
static void OPC_6502_66 (void)
/* Opcode $66: ROR zp */
{
unsigned char ZPAddr;
unsigned Val;
Cycles = 5;
ZPAddr = MemReadByte (Regs.PC+1);
Val = MemReadByte (ZPAddr);
ROR (Val);
MemWriteByte (ZPAddr, Val);
Regs.PC += 2;
}
static void OPC_6502_68 (void)
/* Opcode $68: PLA */
{
Cycles = 4;
Regs.AC = POP ();
TEST_ZF (Regs.AC);
TEST_SF (Regs.AC);
Regs.PC += 1;
}
static void OPC_6502_69 (void)
/* Opcode $69: ADC #imm */
{
Cycles = 2;
ADC (MemReadByte (Regs.PC+1));
Regs.PC += 2;
}
static void OPC_6502_6A (void)
/* Opcode $6A: ROR a */
{
Cycles = 2;
ROR (Regs.AC);
Regs.PC += 1;
}
static void OPC_6502_6C (void)
/* Opcode $6C: JMP (ind) */
{
unsigned PC, Lo, Hi;
PC = Regs.PC;
Lo = MemReadWord (PC+1);
if (CPU == CPU_6502)
{
/* Emulate the 6502 bug */
Cycles = 5;
Regs.PC = MemReadByte (Lo);
Hi = (Lo & 0xFF00) | ((Lo + 1) & 0xFF);
Regs.PC |= (MemReadByte (Hi) << 8);
/* Output a warning if the bug is triggered */
if (Hi != Lo + 1)
{
Warning ("6502 indirect jump bug triggered at $%04X, ind addr = $%04X",
PC, Lo);
}
}
else
{
Cycles = 6;
Regs.PC = MemReadWord(Lo);
}
ParaVirtHooks (&Regs);
}
static void OPC_65C02_6C (void)
/* Opcode $6C: JMP (ind) */
{
/* 6502 bug fixed here */
Cycles = 5;
Regs.PC = MemReadWord (MemReadWord (Regs.PC+1));
ParaVirtHooks (&Regs);
}
static void OPC_6502_6D (void)
/* Opcode $6D: ADC abs */
{
unsigned Addr;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
ADC (MemReadByte (Addr));
Regs.PC += 3;
}
static void OPC_6502_6E (void)
/* Opcode $6E: ROR abs */
{
unsigned Addr;
unsigned Val;
Cycles = 6;
Addr = MemReadWord (Regs.PC+1);
Val = MemReadByte (Addr);
ROR (Val);
MemWriteByte (Addr, Val);
Regs.PC += 3;
}
static void OPC_6502_70 (void)
/* Opcode $70: BVS */
{
BRANCH (GET_OF ());
}
static void OPC_6502_71 (void)
/* Opcode $71: ADC (zp),y */
{
unsigned char ZPAddr;
unsigned Addr;
Cycles = 5;
ZPAddr = MemReadByte (Regs.PC+1);
Addr = MemReadZPWord (ZPAddr);
if (PAGE_CROSS (Addr, Regs.YR)) {
++Cycles;
}
ADC (MemReadByte (Addr + Regs.YR));
Regs.PC += 2;
}
static void OPC_65SC02_72 (void)
/* Opcode $72: ADC (zp) */
{
unsigned char ZPAddr;
unsigned Addr;
Cycles = 5;
ZPAddr = MemReadByte (Regs.PC+1);
Addr = MemReadZPWord (ZPAddr);
ADC (MemReadByte (Addr));
Regs.PC += 2;
}
static void OPC_65SC02_74 (void)
/* Opcode $74: STZ zp,x */
{
unsigned char ZPAddr;
Cycles = 4;
ZPAddr = MemReadByte (Regs.PC+1) + Regs.XR;
MemWriteByte (ZPAddr, 0);
Regs.PC += 2;
}
static void OPC_6502_75 (void)
/* Opcode $75: ADC zp,x */
{
unsigned char ZPAddr;
Cycles = 4;
ZPAddr = MemReadByte (Regs.PC+1) + Regs.XR;
ADC (MemReadByte (ZPAddr));
Regs.PC += 2;
}
static void OPC_6502_76 (void)
/* Opcode $76: ROR zp,x */
{
unsigned char ZPAddr;
unsigned Val;
Cycles = 6;
ZPAddr = MemReadByte (Regs.PC+1) + Regs.XR;
Val = MemReadByte (ZPAddr);
ROR (Val);
MemWriteByte (ZPAddr, Val);
Regs.PC += 2;
}
static void OPC_6502_78 (void)
/* Opcode $78: SEI */
{
Cycles = 2;
SET_IF (1);
Regs.PC += 1;
}
static void OPC_6502_79 (void)
/* Opcode $79: ADC abs,y */
{
unsigned Addr;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
if (PAGE_CROSS (Addr, Regs.YR)) {
++Cycles;
}
ADC (MemReadByte (Addr + Regs.YR));
Regs.PC += 3;
}
static void OPC_65SC02_7A (void)
/* Opcode $7A: PLY */
{
Cycles = 4;
Regs.YR = POP ();
TEST_ZF (Regs.YR);
TEST_SF (Regs.YR);
Regs.PC += 1;
}
static void OPC_65SC02_7C (void)
/* Opcode $7C: JMP (ind,X) */
{
unsigned PC, Adr;
Cycles = 6;
PC = Regs.PC;
Adr = MemReadWord (PC+1);
Regs.PC = MemReadWord(Adr+Regs.XR);
ParaVirtHooks (&Regs);
}
static void OPC_6502_7D (void)
/* Opcode $7D: ADC abs,x */
{
unsigned Addr;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
if (PAGE_CROSS (Addr, Regs.XR)) {
++Cycles;
}
ADC (MemReadByte (Addr + Regs.XR));
Regs.PC += 3;
}
static void OPC_6502_7E (void)
/* Opcode $7E: ROR abs,x */
{
unsigned Addr;
unsigned Val;
Cycles = 7;
Addr = MemReadWord (Regs.PC+1) + Regs.XR;
if (CPU != CPU_6502 && !PAGE_CROSS (Addr, Regs.XR))
--Cycles;
Val = MemReadByte (Addr);
ROR (Val);
MemWriteByte (Addr, Val);
Regs.PC += 3;
}
static void OPC_65SC02_80 (void)
/* Opcode $80: BRA */
{
BRANCH (1);
}
static void OPC_6502_81 (void)
/* Opcode $81: STA (zp,x) */
{
unsigned char ZPAddr;
unsigned Addr;
Cycles = 6;
ZPAddr = MemReadByte (Regs.PC+1) + Regs.XR;
Addr = MemReadZPWord (ZPAddr);
MemWriteByte (Addr, Regs.AC);
Regs.PC += 2;
}
static void OPC_6502_84 (void)
/* Opcode $84: STY zp */
{
unsigned char ZPAddr;
Cycles = 3;
ZPAddr = MemReadByte (Regs.PC+1);
MemWriteByte (ZPAddr, Regs.YR);
Regs.PC += 2;
}
static void OPC_6502_85 (void)
/* Opcode $85: STA zp */
{
unsigned char ZPAddr;
Cycles = 3;
ZPAddr = MemReadByte (Regs.PC+1);
MemWriteByte (ZPAddr, Regs.AC);
Regs.PC += 2;
}
static void OPC_6502_86 (void)
/* Opcode $86: STX zp */
{
unsigned char ZPAddr;
Cycles = 3;
ZPAddr = MemReadByte (Regs.PC+1);
MemWriteByte (ZPAddr, Regs.XR);
Regs.PC += 2;
}
static void OPC_6502_88 (void)
/* Opcode $88: DEY */
{
Cycles = 2;
Regs.YR = (Regs.YR - 1) & 0xFF;
TEST_ZF (Regs.YR);
TEST_SF (Regs.YR);
Regs.PC += 1;
}
static void OPC_65SC02_89 (void)
/* Opcode $89: BIT #imm */
{
unsigned char Val;
Cycles = 2;
Val = MemReadByte (Regs.PC+1);
SET_SF (Val & 0x80);
SET_OF (Val & 0x40);
SET_ZF ((Val & Regs.AC) == 0);
Regs.PC += 2;
}
static void OPC_6502_8A (void)
/* Opcode $8A: TXA */
{
Cycles = 2;
Regs.AC = Regs.XR;
TEST_ZF (Regs.AC);
TEST_SF (Regs.AC);
Regs.PC += 1;
}
static void OPC_6502_8C (void)
/* Opcode $8C: STY abs */
{
unsigned Addr;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
MemWriteByte (Addr, Regs.YR);
Regs.PC += 3;
}
static void OPC_6502_8D (void)
/* Opcode $8D: STA abs */
{
unsigned Addr;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
MemWriteByte (Addr, Regs.AC);
Regs.PC += 3;
}
static void OPC_6502_8E (void)
/* Opcode $8E: STX abs */
{
unsigned Addr;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
MemWriteByte (Addr, Regs.XR);
Regs.PC += 3;
}
static void OPC_6502_90 (void)
/* Opcode $90: BCC */
{
BRANCH (!GET_CF ());
}
static void OPC_6502_91 (void)
/* Opcode $91: sta (zp),y */
{
unsigned char ZPAddr;
unsigned Addr;
Cycles = 6;
ZPAddr = MemReadByte (Regs.PC+1);
Addr = MemReadZPWord (ZPAddr) + Regs.YR;
MemWriteByte (Addr, Regs.AC);
Regs.PC += 2;
}
static void OPC_65SC02_92 (void)
/* Opcode $92: sta (zp) */
{
unsigned char ZPAddr;
unsigned Addr;
Cycles = 5;
ZPAddr = MemReadByte (Regs.PC+1);
Addr = MemReadZPWord (ZPAddr);
MemWriteByte (Addr, Regs.AC);
Regs.PC += 2;
}
static void OPC_6502_94 (void)
/* Opcode $94: STY zp,x */
{
unsigned char ZPAddr;
Cycles = 4;
ZPAddr = MemReadByte (Regs.PC+1) + Regs.XR;
MemWriteByte (ZPAddr, Regs.YR);
Regs.PC += 2;
}
static void OPC_6502_95 (void)
/* Opcode $95: STA zp,x */
{
unsigned char ZPAddr;
Cycles = 4;
ZPAddr = MemReadByte (Regs.PC+1) + Regs.XR;
MemWriteByte (ZPAddr, Regs.AC);
Regs.PC += 2;
}
static void OPC_6502_96 (void)
/* Opcode $96: stx zp,y */
{
unsigned char ZPAddr;
Cycles = 4;
ZPAddr = MemReadByte (Regs.PC+1) + Regs.YR;
MemWriteByte (ZPAddr, Regs.XR);
Regs.PC += 2;
}
static void OPC_6502_98 (void)
/* Opcode $98: TYA */
{
Cycles = 2;
Regs.AC = Regs.YR;
TEST_ZF (Regs.AC);
TEST_SF (Regs.AC);
Regs.PC += 1;
}
static void OPC_6502_99 (void)
/* Opcode $99: STA abs,y */
{
unsigned Addr;
Cycles = 5;
Addr = MemReadWord (Regs.PC+1) + Regs.YR;
MemWriteByte (Addr, Regs.AC);
Regs.PC += 3;
}
static void OPC_6502_9A (void)
/* Opcode $9A: TXS */
{
Cycles = 2;
Regs.SP = Regs.XR;
Regs.PC += 1;
}
static void OPC_65SC02_9C (void)
/* Opcode $9C: STZ abs */
{
unsigned Addr;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
MemWriteByte (Addr, 0);
Regs.PC += 3;
}
static void OPC_6502_9D (void)
/* Opcode $9D: STA abs,x */
{
unsigned Addr;
Cycles = 5;
Addr = MemReadWord (Regs.PC+1) + Regs.XR;
MemWriteByte (Addr, Regs.AC);
Regs.PC += 3;
}
static void OPC_65SC02_9E (void)
/* Opcode $9E: STZ abs,x */
{
unsigned Addr;
Cycles = 5;
Addr = MemReadWord (Regs.PC+1) + Regs.XR;
MemWriteByte (Addr, 0);
Regs.PC += 3;
}
static void OPC_6502_A0 (void)
/* Opcode $A0: LDY #imm */
{
Cycles = 2;
Regs.YR = MemReadByte (Regs.PC+1);
TEST_ZF (Regs.YR);
TEST_SF (Regs.YR);
Regs.PC += 2;
}
static void OPC_6502_A1 (void)
/* Opcode $A1: LDA (zp,x) */
{
unsigned char ZPAddr;
unsigned Addr;
Cycles = 6;
ZPAddr = MemReadByte (Regs.PC+1) + Regs.XR;
Addr = MemReadZPWord (ZPAddr);
Regs.AC = MemReadByte (Addr);
TEST_ZF (Regs.AC);
TEST_SF (Regs.AC);
Regs.PC += 2;
}
static void OPC_6502_A2 (void)
/* Opcode $A2: LDX #imm */
{
Cycles = 2;
Regs.XR = MemReadByte (Regs.PC+1);
TEST_ZF (Regs.XR);
TEST_SF (Regs.XR);
Regs.PC += 2;
}
static void OPC_6502_A4 (void)
/* Opcode $A4: LDY zp */
{
unsigned char ZPAddr;
Cycles = 3;
ZPAddr = MemReadByte (Regs.PC+1);
Regs.YR = MemReadByte (ZPAddr);
TEST_ZF (Regs.YR);
TEST_SF (Regs.YR);
Regs.PC += 2;
}
static void OPC_6502_A5 (void)
/* Opcode $A5: LDA zp */
{
unsigned char ZPAddr;
Cycles = 3;
ZPAddr = MemReadByte (Regs.PC+1);
Regs.AC = MemReadByte (ZPAddr);
TEST_ZF (Regs.AC);
TEST_SF (Regs.AC);
Regs.PC += 2;
}
static void OPC_6502_A6 (void)
/* Opcode $A6: LDX zp */
{
unsigned char ZPAddr;
Cycles = 3;
ZPAddr = MemReadByte (Regs.PC+1);
Regs.XR = MemReadByte (ZPAddr);
TEST_ZF (Regs.XR);
TEST_SF (Regs.XR);
Regs.PC += 2;
}
static void OPC_6502_A8 (void)
/* Opcode $A8: TAY */
{
Cycles = 2;
Regs.YR = Regs.AC;
TEST_ZF (Regs.YR);
TEST_SF (Regs.YR);
Regs.PC += 1;
}
static void OPC_6502_A9 (void)
/* Opcode $A9: LDA #imm */
{
Cycles = 2;
Regs.AC = MemReadByte (Regs.PC+1);
TEST_ZF (Regs.AC);
TEST_SF (Regs.AC);
Regs.PC += 2;
}
static void OPC_6502_AA (void)
/* Opcode $AA: TAX */
{
Cycles = 2;
Regs.XR = Regs.AC;
TEST_ZF (Regs.XR);
TEST_SF (Regs.XR);
Regs.PC += 1;
}
static void OPC_6502_AC (void)
/* Opcode $Regs.AC: LDY abs */
{
unsigned Addr;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
Regs.YR = MemReadByte (Addr);
TEST_ZF (Regs.YR);
TEST_SF (Regs.YR);
Regs.PC += 3;
}
static void OPC_6502_AD (void)
/* Opcode $AD: LDA abs */
{
unsigned Addr;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
Regs.AC = MemReadByte (Addr);
TEST_ZF (Regs.AC);
TEST_SF (Regs.AC);
Regs.PC += 3;
}
static void OPC_6502_AE (void)
/* Opcode $AE: LDX abs */
{
unsigned Addr;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
Regs.XR = MemReadByte (Addr);
TEST_ZF (Regs.XR);
TEST_SF (Regs.XR);
Regs.PC += 3;
}
static void OPC_6502_B0 (void)
/* Opcode $B0: BCS */
{
BRANCH (GET_CF ());
}
static void OPC_6502_B1 (void)
/* Opcode $B1: LDA (zp),y */
{
unsigned char ZPAddr;
unsigned Addr;
Cycles = 5;
ZPAddr = MemReadByte (Regs.PC+1);
Addr = MemReadZPWord (ZPAddr);
if (PAGE_CROSS (Addr, Regs.YR)) {
++Cycles;
}
Regs.AC = MemReadByte (Addr + Regs.YR);
TEST_ZF (Regs.AC);
TEST_SF (Regs.AC);
Regs.PC += 2;
}
static void OPC_65SC02_B2 (void)
/* Opcode $B2: LDA (zp) */
{
unsigned char ZPAddr;
unsigned Addr;
Cycles = 5;
ZPAddr = MemReadByte (Regs.PC+1);
Addr = MemReadZPWord (ZPAddr);
Regs.AC = MemReadByte (Addr);
TEST_ZF (Regs.AC);
TEST_SF (Regs.AC);
Regs.PC += 2;
}
static void OPC_6502_B4 (void)
/* Opcode $B4: LDY zp,x */
{
unsigned char ZPAddr;
Cycles = 4;
ZPAddr = MemReadByte (Regs.PC+1) + Regs.XR;
Regs.YR = MemReadByte (ZPAddr);
TEST_ZF (Regs.YR);
TEST_SF (Regs.YR);
Regs.PC += 2;
}
static void OPC_6502_B5 (void)
/* Opcode $B5: LDA zp,x */
{
unsigned char ZPAddr;
Cycles = 4;
ZPAddr = MemReadByte (Regs.PC+1) + Regs.XR;
Regs.AC = MemReadByte (ZPAddr);
TEST_ZF (Regs.AC);
TEST_SF (Regs.AC);
Regs.PC += 2;
}
static void OPC_6502_B6 (void)
/* Opcode $B6: LDX zp,y */
{
unsigned char ZPAddr;
Cycles = 4;
ZPAddr = MemReadByte (Regs.PC+1) + Regs.YR;
Regs.XR = MemReadByte (ZPAddr);
TEST_ZF (Regs.XR);
TEST_SF (Regs.XR);
Regs.PC += 2;
}
static void OPC_6502_B8 (void)
/* Opcode $B8: CLV */
{
Cycles = 2;
SET_OF (0);
Regs.PC += 1;
}
static void OPC_6502_B9 (void)
/* Opcode $B9: LDA abs,y */
{
unsigned Addr;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
if (PAGE_CROSS (Addr, Regs.YR)) {
++Cycles;
}
Regs.AC = MemReadByte (Addr + Regs.YR);
TEST_ZF (Regs.AC);
TEST_SF (Regs.AC);
Regs.PC += 3;
}
static void OPC_6502_BA (void)
/* Opcode $BA: TSX */
{
Cycles = 2;
Regs.XR = Regs.SP & 0xFF;
TEST_ZF (Regs.XR);
TEST_SF (Regs.XR);
Regs.PC += 1;
}
static void OPC_6502_BC (void)
/* Opcode $BC: LDY abs,x */
{
unsigned Addr;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
if (PAGE_CROSS (Addr, Regs.XR)) {
++Cycles;
}
Regs.YR = MemReadByte (Addr + Regs.XR);
TEST_ZF (Regs.YR);
TEST_SF (Regs.YR);
Regs.PC += 3;
}
static void OPC_6502_BD (void)
/* Opcode $BD: LDA abs,x */
{
unsigned Addr;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
if (PAGE_CROSS (Addr, Regs.XR)) {
++Cycles;
}
Regs.AC = MemReadByte (Addr + Regs.XR);
TEST_ZF (Regs.AC);
TEST_SF (Regs.AC);
Regs.PC += 3;
}
static void OPC_6502_BE (void)
/* Opcode $BE: LDX abs,y */
{
unsigned Addr;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
if (PAGE_CROSS (Addr, Regs.YR)) {
++Cycles;
}
Regs.XR = MemReadByte (Addr + Regs.YR);
TEST_ZF (Regs.XR);
TEST_SF (Regs.XR);
Regs.PC += 3;
}
static void OPC_6502_C0 (void)
/* Opcode $C0: CPY #imm */
{
Cycles = 2;
CMP (Regs.YR, MemReadByte (Regs.PC+1));
Regs.PC += 2;
}
static void OPC_6502_C1 (void)
/* Opcode $C1: CMP (zp,x) */
{
unsigned char ZPAddr;
unsigned Addr;
Cycles = 6;
ZPAddr = MemReadByte (Regs.PC+1) + Regs.XR;
Addr = MemReadZPWord (ZPAddr);
CMP (Regs.AC, MemReadByte (Addr));
Regs.PC += 2;
}
static void OPC_6502_C4 (void)
/* Opcode $C4: CPY zp */
{
unsigned char ZPAddr;
Cycles = 3;
ZPAddr = MemReadByte (Regs.PC+1);
CMP (Regs.YR, MemReadByte (ZPAddr));
Regs.PC += 2;
}
static void OPC_6502_C5 (void)
/* Opcode $C5: CMP zp */
{
unsigned char ZPAddr;
Cycles = 3;
ZPAddr = MemReadByte (Regs.PC+1);
CMP (Regs.AC, MemReadByte (ZPAddr));
Regs.PC += 2;
}
static void OPC_6502_C6 (void)
/* Opcode $C6: DEC zp */
{
unsigned char ZPAddr;
unsigned char Val;
Cycles = 5;
ZPAddr = MemReadByte (Regs.PC+1);
Val = MemReadByte (ZPAddr) - 1;
MemWriteByte (ZPAddr, Val);
TEST_ZF (Val);
TEST_SF (Val);
Regs.PC += 2;
}
static void OPC_6502_C8 (void)
/* Opcode $C8: INY */
{
Cycles = 2;
Regs.YR = (Regs.YR + 1) & 0xFF;
TEST_ZF (Regs.YR);
TEST_SF (Regs.YR);
Regs.PC += 1;
}
static void OPC_6502_C9 (void)
/* Opcode $C9: CMP #imm */
{
Cycles = 2;
CMP (Regs.AC, MemReadByte (Regs.PC+1));
Regs.PC += 2;
}
static void OPC_6502_CA (void)
/* Opcode $CA: DEX */
{
Cycles = 2;
Regs.XR = (Regs.XR - 1) & 0xFF;
TEST_ZF (Regs.XR);
TEST_SF (Regs.XR);
Regs.PC += 1;
}
static void OPC_6502_CC (void)
/* Opcode $CC: CPY abs */
{
unsigned Addr;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
CMP (Regs.YR, MemReadByte (Addr));
Regs.PC += 3;
}
static void OPC_6502_CD (void)
/* Opcode $CD: CMP abs */
{
unsigned Addr;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
CMP (Regs.AC, MemReadByte (Addr));
Regs.PC += 3;
}
static void OPC_6502_CE (void)
/* Opcode $CE: DEC abs */
{
unsigned Addr;
unsigned char Val;
Cycles = 6;
Addr = MemReadWord (Regs.PC+1);
Val = MemReadByte (Addr) - 1;
MemWriteByte (Addr, Val);
TEST_ZF (Val);
TEST_SF (Val);
Regs.PC += 3;
}
static void OPC_6502_D0 (void)
/* Opcode $D0: BNE */
{
BRANCH (!GET_ZF ());
}
static void OPC_6502_D1 (void)
/* Opcode $D1: CMP (zp),y */
{
unsigned ZPAddr;
unsigned Addr;
Cycles = 5;
ZPAddr = MemReadByte (Regs.PC+1);
Addr = MemReadWord (ZPAddr);
if (PAGE_CROSS (Addr, Regs.YR)) {
++Cycles;
}
CMP (Regs.AC, MemReadByte (Addr + Regs.YR));
Regs.PC += 2;
}
static void OPC_65SC02_D2 (void)
/* Opcode $D2: CMP (zp) */
{
unsigned ZPAddr;
unsigned Addr;
Cycles = 5;
ZPAddr = MemReadByte (Regs.PC+1);
Addr = MemReadWord (ZPAddr);
CMP (Regs.AC, MemReadByte (Addr));
Regs.PC += 2;
}
static void OPC_6502_D5 (void)
/* Opcode $D5: CMP zp,x */
{
unsigned char ZPAddr;
Cycles = 4;
ZPAddr = MemReadByte (Regs.PC+1) + Regs.XR;
CMP (Regs.AC, MemReadByte (ZPAddr));
Regs.PC += 2;
}
static void OPC_6502_D6 (void)
/* Opcode $D6: DEC zp,x */
{
unsigned char ZPAddr;
unsigned char Val;
Cycles = 6;
ZPAddr = MemReadByte (Regs.PC+1) + Regs.XR;
Val = MemReadByte (ZPAddr) - 1;
MemWriteByte (ZPAddr, Val);
TEST_ZF (Val);
TEST_SF (Val);
Regs.PC += 2;
}
static void OPC_6502_D8 (void)
/* Opcode $D8: CLD */
{
Cycles = 2;
SET_DF (0);
Regs.PC += 1;
}
static void OPC_6502_D9 (void)
/* Opcode $D9: CMP abs,y */
{
unsigned Addr;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
if (PAGE_CROSS (Addr, Regs.YR)) {
++Cycles;
}
CMP (Regs.AC, MemReadByte (Addr + Regs.YR));
Regs.PC += 3;
}
static void OPC_65SC02_DA (void)
/* Opcode $DA: PHX */
{
Cycles = 3;
PUSH (Regs.XR);
Regs.PC += 1;
}
static void OPC_6502_DD (void)
/* Opcode $DD: CMP abs,x */
{
unsigned Addr;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
if (PAGE_CROSS (Addr, Regs.XR)) {
++Cycles;
}
CMP (Regs.AC, MemReadByte (Addr + Regs.XR));
Regs.PC += 3;
}
static void OPC_6502_DE (void)
/* Opcode $DE: DEC abs,x */
{
unsigned Addr;
unsigned char Val;
Cycles = 7;
Addr = MemReadWord (Regs.PC+1) + Regs.XR;
if (CPU != CPU_6502 && !PAGE_CROSS (Addr, Regs.XR))
--Cycles;
Val = MemReadByte (Addr) - 1;
MemWriteByte (Addr, Val);
TEST_ZF (Val);
TEST_SF (Val);
Regs.PC += 3;
}
static void OPC_6502_E0 (void)
/* Opcode $E0: CPX #imm */
{
Cycles = 2;
CMP (Regs.XR, MemReadByte (Regs.PC+1));
Regs.PC += 2;
}
static void OPC_6502_E1 (void)
/* Opcode $E1: SBC (zp,x) */
{
unsigned char ZPAddr;
unsigned Addr;
Cycles = 6;
ZPAddr = MemReadByte (Regs.PC+1) + Regs.XR;
Addr = MemReadZPWord (ZPAddr);
SBC (MemReadByte (Addr));
Regs.PC += 2;
}
static void OPC_6502_E4 (void)
/* Opcode $E4: CPX zp */
{
unsigned char ZPAddr;
Cycles = 3;
ZPAddr = MemReadByte (Regs.PC+1);
CMP (Regs.XR, MemReadByte (ZPAddr));
Regs.PC += 2;
}
static void OPC_6502_E5 (void)
/* Opcode $E5: SBC zp */
{
unsigned char ZPAddr;
Cycles = 3;
ZPAddr = MemReadByte (Regs.PC+1);
SBC (MemReadByte (ZPAddr));
Regs.PC += 2;
}
static void OPC_6502_E6 (void)
/* Opcode $E6: INC zp */
{
unsigned char ZPAddr;
unsigned char Val;
Cycles = 5;
ZPAddr = MemReadByte (Regs.PC+1);
Val = MemReadByte (ZPAddr) + 1;
MemWriteByte (ZPAddr, Val);
TEST_ZF (Val);
TEST_SF (Val);
Regs.PC += 2;
}
static void OPC_6502_E8 (void)
/* Opcode $E8: INX */
{
Cycles = 2;
Regs.XR = (Regs.XR + 1) & 0xFF;
TEST_ZF (Regs.XR);
TEST_SF (Regs.XR);
Regs.PC += 1;
}
static void OPC_6502_E9 (void)
/* Opcode $E9: SBC #imm */
{
Cycles = 2;
SBC (MemReadByte (Regs.PC+1));
Regs.PC += 2;
}
static void OPC_6502_EA (void)
/* Opcode $EA: NOP */
{
/* This one is easy... */
Cycles = 2;
Regs.PC += 1;
}
static void OPC_65C02_NOP11(void)
/* Opcode 'Illegal' 1 cycle NOP */
{
Cycles = 1;
Regs.PC += 1;
}
static void OPC_65C02_NOP22 (void)
/* Opcode 'Illegal' 2 byte 2 cycle NOP */
{
Cycles = 2;
Regs.PC += 2;
}
static void OPC_65C02_NOP24 (void)
/* Opcode 'Illegal' 2 byte 4 cycle NOP */
{
Cycles = 4;
Regs.PC += 2;
}
static void OPC_65C02_NOP34 (void)
/* Opcode 'Illegal' 3 byte 4 cycle NOP */
{
Cycles = 4;
Regs.PC += 3;
}
static void OPC_6502_EC (void)
/* Opcode $EC: CPX abs */
{
unsigned Addr;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
CMP (Regs.XR, MemReadByte (Addr));
Regs.PC += 3;
}
static void OPC_6502_ED (void)
/* Opcode $ED: SBC abs */
{
unsigned Addr;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
SBC (MemReadByte (Addr));
Regs.PC += 3;
}
static void OPC_6502_EE (void)
/* Opcode $EE: INC abs */
{
unsigned Addr;
unsigned char Val;
Cycles = 6;
Addr = MemReadWord (Regs.PC+1);
Val = MemReadByte (Addr) + 1;
MemWriteByte (Addr, Val);
TEST_ZF (Val);
TEST_SF (Val);
Regs.PC += 3;
}
static void OPC_6502_F0 (void)
/* Opcode $F0: BEQ */
{
BRANCH (GET_ZF ());
}
static void OPC_6502_F1 (void)
/* Opcode $F1: SBC (zp),y */
{
unsigned char ZPAddr;
unsigned Addr;
Cycles = 5;
ZPAddr = MemReadByte (Regs.PC+1);
Addr = MemReadZPWord (ZPAddr);
if (PAGE_CROSS (Addr, Regs.YR)) {
++Cycles;
}
SBC (MemReadByte (Addr + Regs.YR));
Regs.PC += 2;
}
static void OPC_65SC02_F2 (void)
/* Opcode $F2: SBC (zp) */
{
unsigned char ZPAddr;
unsigned Addr;
Cycles = 5;
ZPAddr = MemReadByte (Regs.PC+1);
Addr = MemReadZPWord (ZPAddr);
SBC (MemReadByte (Addr));
Regs.PC += 2;
}
static void OPC_6502_F5 (void)
/* Opcode $F5: SBC zp,x */
{
unsigned char ZPAddr;
Cycles = 4;
ZPAddr = MemReadByte (Regs.PC+1) + Regs.XR;
SBC (MemReadByte (ZPAddr));
Regs.PC += 2;
}
static void OPC_6502_F6 (void)
/* Opcode $F6: INC zp,x */
{
unsigned char ZPAddr;
unsigned char Val;
Cycles = 6;
ZPAddr = MemReadByte (Regs.PC+1) + Regs.XR;
Val = MemReadByte (ZPAddr) + 1;
MemWriteByte (ZPAddr, Val);
TEST_ZF (Val);
TEST_SF (Val);
Regs.PC += 2;
}
static void OPC_6502_F8 (void)
/* Opcode $F8: SED */
{
Cycles = 2;
SET_DF (1);
Regs.PC += 1;
}
static void OPC_6502_F9 (void)
/* Opcode $F9: SBC abs,y */
{
unsigned Addr;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
if (PAGE_CROSS (Addr, Regs.YR)) {
++Cycles;
}
SBC (MemReadByte (Addr + Regs.YR));
Regs.PC += 3;
}
static void OPC_65SC02_FA (void)
/* Opcode $7A: PLX */
{
Cycles = 4;
Regs.XR = POP ();
TEST_ZF (Regs.XR);
TEST_SF (Regs.XR);
Regs.PC += 1;
}
static void OPC_6502_FD (void)
/* Opcode $FD: SBC abs,x */
{
unsigned Addr;
Cycles = 4;
Addr = MemReadWord (Regs.PC+1);
if (PAGE_CROSS (Addr, Regs.XR)) {
++Cycles;
}
SBC (MemReadByte (Addr + Regs.XR));
Regs.PC += 3;
}
static void OPC_6502_FE (void)
/* Opcode $FE: INC abs,x */
{
unsigned Addr;
unsigned char Val;
Cycles = 7;
Addr = MemReadWord (Regs.PC+1) + Regs.XR;
if (CPU != CPU_6502 && !PAGE_CROSS (Addr, Regs.XR))
--Cycles;
Val = MemReadByte (Addr) + 1;
MemWriteByte (Addr, Val);
TEST_ZF (Val);
TEST_SF (Val);
Regs.PC += 3;
}
/*****************************************************************************/
/* Opcode handler tables */
/*****************************************************************************/
/* Opcode handler table for the 6502 */
static const OPFunc OP6502Table[256] = {
OPC_6502_00,
OPC_6502_01,
OPC_Illegal,
OPC_Illegal,
OPC_Illegal,
OPC_6502_05,
OPC_6502_06,
OPC_Illegal,
OPC_6502_08,
OPC_6502_09,
OPC_6502_0A,
OPC_Illegal,
OPC_Illegal,
OPC_6502_0D,
OPC_6502_0E,
OPC_Illegal,
OPC_6502_10,
OPC_6502_11,
OPC_Illegal,
OPC_Illegal,
OPC_Illegal,
OPC_6502_15,
OPC_6502_16,
OPC_Illegal,
OPC_6502_18,
OPC_6502_19,
OPC_Illegal,
OPC_Illegal,
OPC_Illegal,
OPC_6502_1D,
OPC_6502_1E,
OPC_Illegal,
OPC_6502_20,
OPC_6502_21,
OPC_Illegal,
OPC_Illegal,
OPC_6502_24,
OPC_6502_25,
OPC_6502_26,
OPC_Illegal,
OPC_6502_28,
OPC_6502_29,
OPC_6502_2A,
OPC_Illegal,
OPC_6502_2C,
OPC_6502_2D,
OPC_6502_2E,
OPC_Illegal,
OPC_6502_30,
OPC_6502_31,
OPC_Illegal,
OPC_Illegal,
OPC_Illegal,
OPC_6502_35,
OPC_6502_36,
OPC_Illegal,
OPC_6502_38,
OPC_6502_39,
OPC_Illegal,
OPC_Illegal,
OPC_Illegal,
OPC_6502_3D,
OPC_6502_3E,
OPC_Illegal,
OPC_6502_40,
OPC_6502_41,
OPC_Illegal,
OPC_Illegal,
OPC_Illegal,
OPC_6502_45,
OPC_6502_46,
OPC_Illegal,
OPC_6502_48,
OPC_6502_49,
OPC_6502_4A,
OPC_Illegal,
OPC_6502_4C,
OPC_6502_4D,
OPC_6502_4E,
OPC_Illegal,
OPC_6502_50,
OPC_6502_51,
OPC_Illegal,
OPC_Illegal,
OPC_Illegal,
OPC_6502_55,
OPC_6502_56,
OPC_Illegal,
OPC_6502_58,
OPC_6502_59,
OPC_Illegal,
OPC_Illegal,
OPC_Illegal,
OPC_6502_5D,
OPC_6502_5E,
OPC_Illegal,
OPC_6502_60,
OPC_6502_61,
OPC_Illegal,
OPC_Illegal,
OPC_Illegal,
OPC_6502_65,
OPC_6502_66,
OPC_Illegal,
OPC_6502_68,
OPC_6502_69,
OPC_6502_6A,
OPC_Illegal,
OPC_6502_6C,
OPC_6502_6D,
OPC_6502_6E,
OPC_Illegal,
OPC_6502_70,
OPC_6502_71,
OPC_Illegal,
OPC_Illegal,
OPC_Illegal,
OPC_6502_75,
OPC_6502_76,
OPC_Illegal,
OPC_6502_78,
OPC_6502_79,
OPC_Illegal,
OPC_Illegal,
OPC_Illegal,
OPC_6502_7D,
OPC_6502_7E,
OPC_Illegal,
OPC_Illegal,
OPC_6502_81,
OPC_Illegal,
OPC_Illegal,
OPC_6502_84,
OPC_6502_85,
OPC_6502_86,
OPC_Illegal,
OPC_6502_88,
OPC_Illegal,
OPC_6502_8A,
OPC_Illegal,
OPC_6502_8C,
OPC_6502_8D,
OPC_6502_8E,
OPC_Illegal,
OPC_6502_90,
OPC_6502_91,
OPC_Illegal,
OPC_Illegal,
OPC_6502_94,
OPC_6502_95,
OPC_6502_96,
OPC_Illegal,
OPC_6502_98,
OPC_6502_99,
OPC_6502_9A,
OPC_Illegal,
OPC_Illegal,
OPC_6502_9D,
OPC_Illegal,
OPC_Illegal,
OPC_6502_A0,
OPC_6502_A1,
OPC_6502_A2,
OPC_Illegal,
OPC_6502_A4,
OPC_6502_A5,
OPC_6502_A6,
OPC_Illegal,
OPC_6502_A8,
OPC_6502_A9,
OPC_6502_AA,
OPC_Illegal,
OPC_6502_AC,
OPC_6502_AD,
OPC_6502_AE,
OPC_Illegal,
OPC_6502_B0,
OPC_6502_B1,
OPC_Illegal,
OPC_Illegal,
OPC_6502_B4,
OPC_6502_B5,
OPC_6502_B6,
OPC_Illegal,
OPC_6502_B8,
OPC_6502_B9,
OPC_6502_BA,
OPC_Illegal,
OPC_6502_BC,
OPC_6502_BD,
OPC_6502_BE,
OPC_Illegal,
OPC_6502_C0,
OPC_6502_C1,
OPC_Illegal,
OPC_Illegal,
OPC_6502_C4,
OPC_6502_C5,
OPC_6502_C6,
OPC_Illegal,
OPC_6502_C8,
OPC_6502_C9,
OPC_6502_CA,
OPC_Illegal,
OPC_6502_CC,
OPC_6502_CD,
OPC_6502_CE,
OPC_Illegal,
OPC_6502_D0,
OPC_6502_D1,
OPC_Illegal,
OPC_Illegal,
OPC_Illegal,
OPC_6502_D5,
OPC_6502_D6,
OPC_Illegal,
OPC_6502_D8,
OPC_6502_D9,
OPC_Illegal,
OPC_Illegal,
OPC_Illegal,
OPC_6502_DD,
OPC_6502_DE,
OPC_Illegal,
OPC_6502_E0,
OPC_6502_E1,
OPC_Illegal,
OPC_Illegal,
OPC_6502_E4,
OPC_6502_E5,
OPC_6502_E6,
OPC_Illegal,
OPC_6502_E8,
OPC_6502_E9,
OPC_6502_EA,
OPC_Illegal,
OPC_6502_EC,
OPC_6502_ED,
OPC_6502_EE,
OPC_Illegal,
OPC_6502_F0,
OPC_6502_F1,
OPC_Illegal,
OPC_Illegal,
OPC_Illegal,
OPC_6502_F5,
OPC_6502_F6,
OPC_Illegal,
OPC_6502_F8,
OPC_6502_F9,
OPC_Illegal,
OPC_Illegal,
OPC_Illegal,
OPC_6502_FD,
OPC_6502_FE,
OPC_Illegal,
};
/* Opcode handler table for the 65C02 */
static const OPFunc OP65C02Table[256] = {
OPC_6502_00,
OPC_6502_01,
OPC_65C02_NOP22, // $02
OPC_65C02_NOP11, // $03
OPC_65SC02_04,
OPC_6502_05,
OPC_6502_06,
OPC_Illegal, // $07: RMB0 currently unsupported
OPC_6502_08,
OPC_6502_09,
OPC_6502_0A,
OPC_65C02_NOP11, // $0B
OPC_65SC02_0C,
OPC_6502_0D,
OPC_6502_0E,
OPC_Illegal, // $0F: BBR0 currently unsupported
OPC_6502_10,
OPC_6502_11,
OPC_65SC02_12,
OPC_65C02_NOP11, // $13
OPC_65SC02_14,
OPC_6502_15,
OPC_6502_16,
OPC_Illegal, // $17: RMB1 currently unsupported
OPC_6502_18,
OPC_6502_19,
OPC_65SC02_1A,
OPC_65C02_NOP11, // $1B
OPC_65SC02_1C,
OPC_6502_1D,
OPC_6502_1E,
OPC_Illegal, // $1F: BBR1 currently unsupported
OPC_6502_20,
OPC_6502_21,
OPC_65C02_NOP22, // $22
OPC_65C02_NOP11, // $23
OPC_6502_24,
OPC_6502_25,
OPC_6502_26,
OPC_Illegal, // $27: RMB2 currently unsupported
OPC_6502_28,
OPC_6502_29,
OPC_6502_2A,
OPC_65C02_NOP11, // $2B
OPC_6502_2C,
OPC_6502_2D,
OPC_6502_2E,
OPC_Illegal, // $2F: BBR2 currently unsupported
OPC_6502_30,
OPC_6502_31,
OPC_65SC02_32,
OPC_65C02_NOP11, // $33
OPC_65SC02_34,
OPC_6502_35,
OPC_6502_36,
OPC_Illegal, // $37: RMB3 currently unsupported
OPC_6502_38,
OPC_6502_39,
OPC_65SC02_3A,
OPC_65C02_NOP11, // $3B
OPC_65SC02_3C,
OPC_6502_3D,
OPC_6502_3E,
OPC_Illegal, // $3F: BBR3 currently unsupported
OPC_6502_40,
OPC_6502_41,
OPC_65C02_NOP22, // $42
OPC_65C02_NOP11, // $43
OPC_65C02_44, // $44
OPC_6502_45,
OPC_6502_46,
OPC_Illegal, // $47: RMB4 currently unsupported
OPC_6502_48,
OPC_6502_49,
OPC_6502_4A,
OPC_65C02_NOP11, // $4B
OPC_6502_4C,
OPC_6502_4D,
OPC_6502_4E,
OPC_Illegal, // $4F: BBR4 currently unsupported
OPC_6502_50,
OPC_6502_51,
OPC_65SC02_52,
OPC_65C02_NOP11, // $53
OPC_65C02_NOP24, // $54
OPC_6502_55,
OPC_6502_56,
OPC_Illegal, // $57: RMB5 currently unsupported
OPC_6502_58,
OPC_6502_59,
OPC_65SC02_5A,
OPC_65C02_NOP11, // $5B
OPC_65C02_5C,
OPC_6502_5D,
OPC_6502_5E,
OPC_Illegal, // $5F: BBR5 currently unsupported
OPC_6502_60,
OPC_6502_61,
OPC_65C02_NOP22, // $62
OPC_65C02_NOP11, // $63
OPC_65SC02_64,
OPC_6502_65,
OPC_6502_66,
OPC_Illegal, // $67: RMB6 currently unsupported
OPC_6502_68,
OPC_6502_69,
OPC_6502_6A,
OPC_65C02_NOP11, // $6B
OPC_65C02_6C,
OPC_6502_6D,
OPC_6502_6E,
OPC_Illegal, // $6F: BBR6 currently unsupported
OPC_6502_70,
OPC_6502_71,
OPC_65SC02_72,
OPC_65C02_NOP11, // $73
OPC_65SC02_74,
OPC_6502_75,
OPC_6502_76,
OPC_Illegal, // $77: RMB7 currently unsupported
OPC_6502_78,
OPC_6502_79,
OPC_65SC02_7A,
OPC_65C02_NOP11, // $7B
OPC_65SC02_7C,
OPC_6502_7D,
OPC_6502_7E,
OPC_Illegal, // $7F: BBR7 currently unsupported
OPC_65SC02_80,
OPC_6502_81,
OPC_65C02_NOP22, // $82
OPC_65C02_NOP11, // $83
OPC_6502_84,
OPC_6502_85,
OPC_6502_86,
OPC_Illegal, // $87: SMB0 currently unsupported
OPC_6502_88,
OPC_65SC02_89,
OPC_6502_8A,
OPC_65C02_NOP11, // $8B
OPC_6502_8C,
OPC_6502_8D,
OPC_6502_8E,
OPC_Illegal, // $8F: BBS0 currently unsupported
OPC_6502_90,
OPC_6502_91,
OPC_65SC02_92,
OPC_65C02_NOP11, // $93
OPC_6502_94,
OPC_6502_95,
OPC_6502_96,
OPC_Illegal, // $97: SMB1 currently unsupported
OPC_6502_98,
OPC_6502_99,
OPC_6502_9A,
OPC_65C02_NOP11, // $9B
OPC_65SC02_9C,
OPC_6502_9D,
OPC_65SC02_9E,
OPC_Illegal, // $9F: BBS1 currently unsupported
OPC_6502_A0,
OPC_6502_A1,
OPC_6502_A2,
OPC_65C02_NOP11, // $A3
OPC_6502_A4,
OPC_6502_A5,
OPC_6502_A6,
OPC_Illegal, // $A7: SMB2 currently unsupported
OPC_6502_A8,
OPC_6502_A9,
OPC_6502_AA,
OPC_65C02_NOP11, // $AB
OPC_6502_AC,
OPC_6502_AD,
OPC_6502_AE,
OPC_Illegal, // $AF: BBS2 currently unsupported
OPC_6502_B0,
OPC_6502_B1,
OPC_65SC02_B2,
OPC_65C02_NOP11, // $B3
OPC_6502_B4,
OPC_6502_B5,
OPC_6502_B6,
OPC_Illegal, // $B7: SMB3 currently unsupported
OPC_6502_B8,
OPC_6502_B9,
OPC_6502_BA,
OPC_65C02_NOP11, // $BB
OPC_6502_BC,
OPC_6502_BD,
OPC_6502_BE,
OPC_Illegal, // $BF: BBS3 currently unsupported
OPC_6502_C0,
OPC_6502_C1,
OPC_65C02_NOP22, // $C2
OPC_65C02_NOP11, // $C3
OPC_6502_C4,
OPC_6502_C5,
OPC_6502_C6,
OPC_Illegal, // $C7: SMB4 currently unsupported
OPC_6502_C8,
OPC_6502_C9,
OPC_6502_CA,
OPC_Illegal, // $CB: WAI currently unsupported
OPC_6502_CC,
OPC_6502_CD,
OPC_6502_CE,
OPC_Illegal, // $CF: BBS4 currently unsupported
OPC_6502_D0,
OPC_6502_D1,
OPC_65SC02_D2,
OPC_65C02_NOP11, // $D3
OPC_65C02_NOP24, // $D4
OPC_6502_D5,
OPC_6502_D6,
OPC_Illegal, // $D7: SMB5 currently unsupported
OPC_6502_D8,
OPC_6502_D9,
OPC_65SC02_DA,
OPC_Illegal, // $DB: STP currently unsupported
OPC_65C02_NOP34, // $DC
OPC_6502_DD,
OPC_6502_DE,
OPC_Illegal, // $DF: BBS5 currently unsupported
OPC_6502_E0,
OPC_6502_E1,
OPC_65C02_NOP22, // $E2
OPC_65C02_NOP11, // $E3
OPC_6502_E4,
OPC_6502_E5,
OPC_6502_E6,
OPC_Illegal, // $E7: SMB6 currently unsupported
OPC_6502_E8,
OPC_6502_E9,
OPC_6502_EA,
OPC_65C02_NOP11, // $EB
OPC_6502_EC,
OPC_6502_ED,
OPC_6502_EE,
OPC_Illegal, // $EF: BBS6 currently unsupported
OPC_6502_F0,
OPC_6502_F1,
OPC_65SC02_F2,
OPC_65C02_NOP11, // $F3
OPC_65C02_NOP24, // $F4
OPC_6502_F5,
OPC_6502_F6,
OPC_Illegal, // $F7: SMB7 currently unsupported
OPC_6502_F8,
OPC_6502_F9,
OPC_65SC02_FA,
OPC_65C02_NOP11, // $FB
OPC_65C02_NOP34, // $FC
OPC_6502_FD,
OPC_6502_FE,
OPC_Illegal, // $FF: BBS7 currently unsupported
};
/* Tables with opcode handlers */
static const OPFunc* Handlers[2] = {OP6502Table, OP65C02Table};
/*****************************************************************************/
/* Code */
/*****************************************************************************/
void IRQRequest (void)
/* Generate an IRQ */
{
/* Remember the request */
HaveIRQRequest = 1;
}
void NMIRequest (void)
/* Generate an NMI */
{
/* Remember the request */
HaveNMIRequest = 1;
}
void Reset (void)
/* Generate a CPU RESET */
{
/* Reset the CPU */
HaveIRQRequest = 0;
HaveNMIRequest = 0;
/* Bits 5 and 4 aren't used, and always are 1! */
Regs.SR = 0x30;
Regs.PC = MemReadWord (0xFFFC);
}
unsigned ExecuteInsn (void)
/* Execute one CPU instruction */
{
/* If we have an NMI request, handle it */
if (HaveNMIRequest) {
HaveNMIRequest = 0;
PUSH (PCH);
PUSH (PCL);
PUSH (Regs.SR & ~BF);
SET_IF (1);
if (CPU != CPU_6502)
{
SET_DF (0);
}
Regs.PC = MemReadWord (0xFFFA);
Cycles = 7;
} else if (HaveIRQRequest && GET_IF () == 0) {
HaveIRQRequest = 0;
PUSH (PCH);
PUSH (PCL);
PUSH (Regs.SR & ~BF);
SET_IF (1);
if (CPU != CPU_6502)
{
SET_DF (0);
}
Regs.PC = MemReadWord (0xFFFE);
Cycles = 7;
} else {
/* Normal instruction - read the next opcode */
unsigned char OPC = MemReadByte (Regs.PC);
/* Execute it */
Handlers[CPU][OPC] ();
}
/* Count cycles */
TotalCycles += Cycles;
/* Return the number of clock cycles needed by this insn */
return Cycles;
}
unsigned long GetCycles (void)
/* Return the total number of cycles executed */
{
/* Return the total number of cycles */
return TotalCycles;
}
| 20.723856 | 91 | 0.493184 | [
"3d"
] |
683ba529fb3f82aec0cff48573b4b21686945cdf | 4,650 | h | C | files/oled_i2c_inline.h | cyclonus101/avr-ina219-oled | 80092b0db392fe5fd757b43c46e960f81e4f55c4 | [
"MIT"
] | null | null | null | files/oled_i2c_inline.h | cyclonus101/avr-ina219-oled | 80092b0db392fe5fd757b43c46e960f81e4f55c4 | [
"MIT"
] | null | null | null | files/oled_i2c_inline.h | cyclonus101/avr-ina219-oled | 80092b0db392fe5fd757b43c46e960f81e4f55c4 | [
"MIT"
] | null | null | null | #include <avr/io.h>
#include <avr/pgmspace.h>
#include <util/twi.h>
#include "i2c_inline.h"
#include <stdlib.h>
#include <stdio.h>
#ifndef OLED_I2C_H
#define OLED_I2C_H
#define ARR_SIZE(x) (sizeof(x) / sizeof(x[0]))
#define FONT5_MAXCHARS 25
#define FONT5 5
#define OLED_ADD0 0x78 //? try 3D or 3B , 3c is default or 78?
#define CONSTRAST_RESET_CMD 0x7F
#define CONTRAST_CMD 0x81
#define DISPLAYRAM_CMD 0xA4
#define DISPLAYALL_CMD 0xA5
#define NORMAL_DISPLAY_CMD 0xA6 //
#define INVERSE_DISPLAY_CMD 0xA7
#define DISPLAY_OFF_CMD 0xAE // sleep/reset
#define DISPLAY_ON_CMD 0xAF //display on in normal mode
#define RIGHT_SCROLL 0x26
#define LEFT_SCROLLL 0x27
#define UPRIGHT_SCROL 0x29
#define UPLEFT_SCROLL 0x2A
#define START_ADDRESS 0x00
#define END_ADDRESS 0x10
#define ADDRESS_MODE_ADD 0x20
#define HORIZONTAL_MODE_CMD 0x20 //horizontal add mode
#define VERTICAL_MODE_CMD 0x21 //vertical add mode
#define SETPAGE_MODECMD 0x22 // page addr + resets pointers for mode
#define INVALID_CMD 0x23 //do not use
#define COLUMN_ADD 21
#define SET_PAGE_ADD 22
#define PAGE_CMD 0xB0
#define CONTRAST_ADD 0x81
#define CONTRAST_DEF_CMD 0x7F
//HARDWARE DEFINES
#define SEGMENT_NOREMAP_CMD 0xA0
#define SEGMENT_REMAP_CMD 0xA1
#define COM_NOREMAP_CMD 0xC0
#define COM_REMAP_CMD 0xC8
//
#define CLOCKDIV_ADD 0xD5
#define CLOCKDIV_DEF_CMD 0x80
//
#define DISPLAYOFFSET_CMD 0xD3
//CHARGE PUMP
//if
#define CHARGEPUMP_ADD 0x8D
#define CHARGEPUMP_ENABLE_CMD 0x14
#define CHARGEPUMP_DISENABLE_CMD 0x10
//MUX Ratio
#define MUX_ADD 0xA8
#define MUX_32_CMD 0x1F //32
#define MUX_64_CMD 0x3F //64
//display offsets
#define DISPLAY_OFFSET_ADD 0xD3
#define DISPLAY_OFFSET_DISABLE_CMD 0x00
//display startline
#define DISPLAY_STARTLINE_DEF_CMD 0x40
//com pin ocnfig
#define COMPIN_ADD 0xDA
#define COMPIN_CMD 0x02
// OSC FREQ
#define OSC_FREQ_ADD 0xD5
#define OSC_FREQ_DEF_CMD 0x80
//
#define DISPLAY_ENABLE_CMD 0xAF
#define DISPLAY_DISABLE_CMD 0xA4
//
#define PAGEADD_LN_0_CMD 0x00
#define PAGEADD_HN_0_CMD 0x10
//
#define PAGE_END 128
#define MAX_CHARS 26
#define ASCII_OFFSET 32 //my font starts at 0x20 which is space
//---------------------------------------
#define CONTINUE_DATA 0x40
#define CONTINUE_CMD 0x00
#define NO_CONTINUE_DATA 0xC0
#define NO_CONTINUE_CMD 0x80
//-----------------------------------------------
#define DUMMY_BYTE_00 0x00
#define DUMMY_BYTE_FF 0xFF
#define SCROLL_STOP_CMD 0x2E
#define SCROLL_START_CMD 0x2F
// ENUM ------------------------------------------
enum OLED_PAGES
{
PAGE0,
PAGE1,
PAGE2,
PAGE3,
PAGE4,
PAGE5,
PAGE6,
PAGE7
};
enum OLED_FRAMES
{
FRAMES5,
FRAMES64,
FRAMES128,
FRAMES256,
FRAMES3,
FRAMES4,
FRAMES2
//more frames = slower, less frames = faster
//2 =fastest, 256 = slowest
//25 or 64 are the preferable default values
};
//----------------------------------------------------------
typedef struct
{
unsigned char page_buffer[128];
unsigned char address;
unsigned char buffer_limit;
} OLED;
typedef struct
{
unsigned char contrast;
} OLED_SETTINGS;
extern void itoa10_asm(unsigned int number, char *array);
//BASIC FUNCTIONS-----------------------------------------------------------------
unsigned char oled_initDefault32(unsigned char address);
unsigned char oled_selectPageAndColumn(unsigned char address, unsigned char page, unsigned char column);
unsigned char oled_writeBufferToPage(OLED *ptr);
void oled_writeFlashToBuffer(const char *input, OLED *oled_ptr);
void oled_writeNumStringToBuffer(char *input, OLED *oled_ptr);
unsigned char oled_writeIntAsFloat(OLED *ptr, unsigned char decimal);
unsigned char oled_pageAddressScheme(unsigned char address);
unsigned char oled_writeCommand(unsigned char address, unsigned char cmd);
unsigned char oled_writeContrast(unsigned char address, unsigned char constrast);
unsigned char oled_HorizontalScroll(unsigned char address, unsigned char s_page,unsigned char e_page, unsigned char frames,unsigned char direction);
unsigned char oled_clearDisplay(unsigned char oled_address);
unsigned char oled_writeDisplay(unsigned char address, const char *msg, unsigned char column, unsigned char page);
// OLD FUNCTIONS
unsigned char oled_select_page(unsigned char address, unsigned char page);
unsigned char oled_wr_page(OLED *ptr, unsigned char size);
unsigned char oled_page_startcolumn(unsigned char address, unsigned char position);
#endif
| 24.34555 | 150 | 0.708172 | [
"3d"
] |
683c62b304cc7d48ed0145281953c3ae44bfd734 | 11,573 | h | C | inc/data.h | subakioinc/RDDRONE-BMS772 | ac8d770def74284edf79cdb061de7b6f3cbce9a3 | [
"BSD-3-Clause"
] | null | null | null | inc/data.h | subakioinc/RDDRONE-BMS772 | ac8d770def74284edf79cdb061de7b6f3cbce9a3 | [
"BSD-3-Clause"
] | null | null | null | inc/data.h | subakioinc/RDDRONE-BMS772 | ac8d770def74284edf79cdb061de7b6f3cbce9a3 | [
"BSD-3-Clause"
] | null | null | null | /****************************************************************************
* nxp_bms/BMS_v1/inc/data.h
*
* BSD 3-Clause License
*
* Copyright 2020 NXP
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
** ###################################################################
** Filename : data.h
** Project : SmartBattery_RDDRONE_BMS772
** Processor : S32K144
** Version : 1.00
** Date : 2020-03-17
** Abstract :
** data module.
** This module contains all functions needed for shared data
**
** ###################################################################*/
/*!
** @file Data.h
**
** @version 01.00
**
** @brief
** Data module. this module contains the functions for the shared memory
**
*/
#ifndef DATA_H_
#define DATA_H_
/*******************************************************************************
* Includes
******************************************************************************/
#include <stdio.h>
#include <string.h>
#include "BMS_data_types.h"
/*******************************************************************************
* types
******************************************************************************/
/* @brief this callback function is used to handle the parameter change */
//typedef int (*parameterChangeCallbackFunction)(int argc, char *argv[]);
/*! @brief this callback function is used to handle the parameter change */
typedef int (*parameterChangeCallbackFunction)(parameterKind_t changedParameter, void *newValue);
/*******************************************************************************
* public functions
******************************************************************************/
/*!
* @brief this function is needed to use the data_setParameter and data_getParameter
* it will initialize the mutex and return the outcome of the pthread_mutex_init function
*
* @param p_parameterChangeCallbackFunction the address of the function to start a task to handle a parameter change
*
* @return If successful, the function will return zero (OK). Otherwise, an error number will be returned to indicate the error:
* @example if(data_initialize())
* {
* // do something with the error
* }
*/
int data_initialize(parameterChangeCallbackFunction p_parameterChangeCallbackFunction);
/*!
* @brief function to the type a certain parameter from the data struct in data.c
* this function could be used before the data_setParameter or data_getParameter function
*
* @param parameterKind the parameter of which the type should be returned, from the parameterKind enum in BMS_data_types.h
*
* @retval the type of the parameter as a valueType_t enum value, defined in BMS_data_types.h
* it will return STRINGVAL if the parameterKind was NONE
*
* @example valueType_t paramType;
* switch(paramType)
* {
* case FLOATVAL: // so somthing with floating points values
* break;
* case STRINGVAL: // do somthing with string values
* break;
* case default: // something with int32_t values (uint16 and uint8 can be set and get with int32)
* break;
* }
*
*/
valueType_t data_getType(parameterKind_t parameterKind);
/*!
* @brief function to get a certain parameter from the data struct in data.c
* this function could be used after the data_setParameter function
* there are 2 ways to get the parameter, either with the outData parameter
* or with the return value of the function. other may be NULL
* the outLenght parameter is used get the lenght of the data in bytes, this may be NULL
* data_initializeData should have been called once
*
* @param parameterKind the parameter value it wants, from the parameterKind enum in BMS_data_types.h
* @param outData pointer to the value that needs to become the parameter value, could be int32_t, float or char*
* @param outLenght pointer to the value that needs to become the lenght of the data (in bytes)
* only used with characters, otherwise it may be NULL
*
* @retval a void pointer to the value
* @example int32_t lvGetParam;
* uint8_t *pReadUint8_tData = NULL;
* pReadUint8_tData = data_getParameter(STATE_OF_CHARGE, &lvGetParam, NULL);
* if(pReadUint8_tData != NULL)
* {
* // do something with value
* }
* else
* {
* // something went wrong!
* }
* other example:
* char *GetString = malloc(sizeof(char[32]));
* uint16_t *Lenght = malloc(sizeof(uint16_t));
* data_getParameter(MODEL_NAME, GetString, Lenght);
* free(GetString);
* free(Lenght);
*/
void* data_getParameter(parameterKind_t parameterKind, void* outData, uint16_t* outLength);
/*!
* @brief function to set a certain parameter in the data struct
* after this, the value can be read with the data_setParameter funciton
* this function only sets the new value if it is within the range
* of the parameter as discribed in BMS_data_limits.h
* it is possible to signal if a parameter has changed (work in progress!)
* data_initialize should have been called once
*
* @param parameterKind the setting it wants to set from the parameterKind enum in BMS_data_types.h
* @param inNewValue a pointer to the value it will be
*
* @retval is -1 when something went wrong, 0 when it went right
* @example: int32_t newValue = 3; or float newValue = 3.3
* if(data_setParameter(STATE_OF_CHARGE, &newValue))
* {
* // it went wrong!
* }
*
* for model name:
* char newModelName[] = "New model name\0";
* if(data_setParameter(MODEL_NAME, newModelName))
* {
* // it went wrong!
* }
*/
int data_setParameter(parameterKind_t parameterKind, void* inNewValue);
/*!
* @brief function to lock the mutex (make sure that no other tasks/threads can acces/change the data)
* make sure the mutex is unlocked again with data_unlockMutex
* should always be used with data_unlockMutex
*
* @param none
*
* @retval 0 if succeeded, otherwise the error of pthread_mutex_lock
*
* @example uint8_t stateOfCharge;
* data_lockMutex();
* stateOfCharge = *(data_getAdr(STATE_OF_CHARGE));
* data_unlockMutex();
*
*/
int data_lockMutex(void);
/*!
* @brief function to unlock the mutex (make sure that other tasks/threads can acces/change the data)
* make sure the mutex is locked with the data_lockMutex function before calling this funciton
* should always be used with the data_lockMutex
*
* @param none
*
* @retval 0 if succeeded, otherwise the error of pthread_mutex_unlock
*
* @example uint8_t stateOfCharge;
* data_lockMutex();
* stateOfCharge = *(data_getAdr(STATE_OF_CHARGE));
* data_unlockMutex();
*
*/
int data_unlockMutex(void);
/*!
* @brief function to get the address of a certain parameter from the data struct in data.c
* this function is faster than the get or set function
* this function should be used with the data_lockMutex() and data_unlockMutex() functions
*
*
* @param parameterKind the parameter of which the address should be returned, from the parameterKind enum in BMS_data_types.h
*
* @retval an void pointer addres to the value
* @warning be sure to lock te mutex before this function and unlock it after.
* shouldn't be used to set a variable!
* use with caution, a variable could be changed with this function but there are no limit checks
* there is alno no check if the varaible has changed (the signal for other functions)
*
* @example uint8_t stateOfCharge;
* data_lockMutex();
* stateOfCharge = *(data_getAdr(STATE_OF_CHARGE));
* data_unlockMutex();
*
*/
void* data_getAdr(parameterKind_t parameterKind);
/*!
* @brief function to get the unit as a strings of a certain parameter *
*
* @param parameterKind the parameter of which the unit should be returned,
* from the parameterKind enum in BMS_data_types.h
*
* @retval an char pointer addres to the value
*
*/
char* data_getUnit(parameterKind_t parameterKind);
/*!
* @brief function to set a bit in the status flags (status_flags)
* @note if the flags are S_FLAGS_UKNOWN, clear the status_flags first.
*
* @param bit the bit that needs to change in the status_flags variable (0-7) use the STATUS_*_BIT defines for it
* @param value the new value of this bit as a bool
*
* @retval 0 if succeeded, otherwise the error of pthread_mutex_unlock
*
* @example if(data_statusFlagBit(STATUS_OVERLOAD_BIT, 1))
* {
* // do something with the error
* }
*
*/
int data_statusFlagBit(uint8_t bit, bool value);
/*!
* @brief function to save the parameters in flash
* @note The eeeprom is used for this (4KB)
* @note Multi-thread protected
*
* @retval 0 if it went OK, negative otherwise
*/
int data_saveParameters(void);
/*!
* @brief function to load the parameters from flash
* @note The eeeprom is used for this (4KB)
* @note Multi-thread protected
*
* @retval 0 if it went OK, negative otherwise
*/
int data_loadParameters(void);
/*!
* @brief this function will set the default values of the BMS to the data struct
* @note Multi-thread protected
*
* @param none
*
* @return 0 if succeeded, negative otherwise
*/
int data_setDefaultParameters(void);
/*******************************************************************************
* EOF
******************************************************************************/
#endif /* DATA_H_ */
| 38.83557 | 130 | 0.623175 | [
"model"
] |
68475d7aaf498374606916f078b92a572d89cbce | 4,091 | h | C | lonestar/experimental/ordered/avi/libElm/libShapesEvaluated/ShapesEvaluatedP13D.h | rohankadekodi/compilers_project | 2f9455a5d0c516b9f1766afd1cdac1b86c930ec0 | [
"BSD-3-Clause"
] | null | null | null | lonestar/experimental/ordered/avi/libElm/libShapesEvaluated/ShapesEvaluatedP13D.h | rohankadekodi/compilers_project | 2f9455a5d0c516b9f1766afd1cdac1b86c930ec0 | [
"BSD-3-Clause"
] | 7 | 2020-02-27T19:24:51.000Z | 2020-04-10T21:04:28.000Z | lonestar/experimental/ordered/avi/libElm/libShapesEvaluated/ShapesEvaluatedP13D.h | rohankadekodi/compilers_project | 2f9455a5d0c516b9f1766afd1cdac1b86c930ec0 | [
"BSD-3-Clause"
] | 2 | 2021-07-26T14:46:51.000Z | 2021-11-09T11:32:09.000Z | /*
* This file belongs to the Galois project, a C++ library for exploiting parallelism.
* The code is being released under the terms of the 3-Clause BSD License (a
* copy is located in LICENSE.txt at the top-level directory).
*
* Copyright (C) 2018, The University of Texas at Austin. All rights reserved.
* UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS
* SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF
* PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF
* DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH
* RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances
* shall University be liable for incidental, special, indirect, direct or
* consequential damages or loss of profits, interruption of business, or
* related expenses which may arise from use of Software or Documentation,
* including but not limited to those resulting from defects in Software and/or
* Documentation, or loss or inaccuracy of data of any kind.
*/
/**
* ShapesEvaluatedP13D.h
* DG++
*
* Created by Ramsharan Rangarajan.
*
* Copyright (c) 2006 Adrian Lew
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject
* to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SHAPESEVALUATEDP13D
#define SHAPESEVALUATEDP13D
#include "ShapesEvaluated.h"
#include "Quadrature.h"
#include "Linear.h"
/**
\brief Shape functions for P13D elements: Linear functions on tetrahedra.
It containes two types of traces
1) ShapesP13D::Faces are linear functions on triangles and their dofs are
those associated with the nodes of the triangular face.
2) ShapesP13D::FaceOne, ShapesP13D::FaceTwo, ShapesP13D::FaceThree and
ShapesP13D::FaceFour are the full set of linear shape functions in the
elements evaluated at quadrature points in each one of the faces. Instead of
having 3 dofs per field per face, there are 3 dofs per field per face. Some
of these values are trivially zero, i.e., those of the shape function
associated to the node opposite to the face where the quadrature point is. As
was the done in ShapesP12D, these are provided since ocassionally it may be
necessary to have the same number of dofs as the bulk fields. In the most
general case of arbitrary bases, there is generally no shape function that is
zero on the face, and hence bulk and trace fields have the same number of
dofs.
*/
class ShapesP13D : public SpecificShapesEvaluated {
protected:
static const size_t bctMap[];
public:
static const Shape* const P13D;
static const Shape* const P12D;
typedef ShapesEvaluated__<P13D, Tet_1::Bulk> Bulk;
typedef ShapesEvaluated__<P12D, Triangle_1::Bulk> Faces;
typedef ShapesEvaluated__<P13D, Tet_1::FaceOne> FaceOne; // 2-1-0
typedef ShapesEvaluated__<P13D, Tet_1::FaceTwo> FaceTwo; // 2-0-3
typedef ShapesEvaluated__<P13D, Tet_1::FaceThree> FaceThree; // 2-3-1
typedef ShapesEvaluated__<P13D, Tet_1::FaceFour> FaceFour; // 0-1-3
};
#endif
| 43.521277 | 85 | 0.760694 | [
"shape"
] |
d034ef095f80c6044ceec141f61ad89185b19bf9 | 1,943 | h | C | src/modules/thread/Channel.h | KanoComputing/love2d | 6d532add21ccc5715a040c8ce4ec2ce65db9dd4d | [
"Zlib"
] | 1 | 2016-12-04T18:20:07.000Z | 2016-12-04T18:20:07.000Z | src/modules/thread/Channel.h | KanoComputing/love2d | 6d532add21ccc5715a040c8ce4ec2ce65db9dd4d | [
"Zlib"
] | null | null | null | src/modules/thread/Channel.h | KanoComputing/love2d | 6d532add21ccc5715a040c8ce4ec2ce65db9dd4d | [
"Zlib"
] | null | null | null | /**
* Copyright (c) 2006-2016 LOVE Development Team
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
**/
#ifndef LOVE_THREAD_CHANNEL_H
#define LOVE_THREAD_CHANNEL_H
// STL
#include <queue>
#include <string>
// LOVE
#include "common/Variant.h"
#include "threads.h"
namespace love
{
namespace thread
{
class Channel : public love::Object
{
// FOR WRAPPER USE ONLY
friend void retainVariant(Channel *, Variant *);
friend void releaseVariant(Channel *, Variant *);
friend int w_Channel_performAtomic(lua_State *);
public:
Channel();
~Channel();
static Channel *getChannel(const std::string &name);
unsigned long push(Variant *var);
void supply(Variant *var); // blocking push
Variant *pop();
Variant *demand(); // blocking pop
Variant *peek();
int getCount();
void clear();
void retain();
void release();
private:
Channel(const std::string &name);
void lockMutex();
void unlockMutex();
Mutex *mutex;
Conditional *cond;
std::queue<Variant *> queue;
bool named;
std::string name;
unsigned long sent;
unsigned long received;
}; // Channel
} // thread
} // love
#endif // LOVE_THREAD_CHANNEL_H
| 23.409639 | 77 | 0.726197 | [
"object"
] |
d048a86c7fc99c724228403158e3cb68d48106be | 86,870 | c | C | head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev.c | dplbsd/soc2013 | c134f5e2a5725af122c94005c5b1af3720706ce3 | [
"BSD-2-Clause"
] | null | null | null | head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev.c | dplbsd/soc2013 | c134f5e2a5725af122c94005c5b1af3720706ce3 | [
"BSD-2-Clause"
] | null | null | null | head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/vdev.c | dplbsd/soc2013 | c134f5e2a5725af122c94005c5b1af3720706ce3 | [
"BSD-2-Clause"
] | null | null | null | /*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* Copyright 2011 Nexenta Systems, Inc. All rights reserved.
* Copyright (c) 2013 by Delphix. All rights reserved.
* Copyright 2013 Martin Matuska <mm@FreeBSD.org>. All rights reserved.
*/
#include <sys/zfs_context.h>
#include <sys/fm/fs/zfs.h>
#include <sys/spa.h>
#include <sys/spa_impl.h>
#include <sys/dmu.h>
#include <sys/dmu_tx.h>
#include <sys/vdev_impl.h>
#include <sys/uberblock_impl.h>
#include <sys/metaslab.h>
#include <sys/metaslab_impl.h>
#include <sys/space_map.h>
#include <sys/zio.h>
#include <sys/zap.h>
#include <sys/fs/zfs.h>
#include <sys/arc.h>
#include <sys/zil.h>
#include <sys/dsl_scan.h>
#include <sys/trim_map.h>
SYSCTL_DECL(_vfs_zfs);
SYSCTL_NODE(_vfs_zfs, OID_AUTO, vdev, CTLFLAG_RW, 0, "ZFS VDEV");
/*
* Virtual device management.
*/
static vdev_ops_t *vdev_ops_table[] = {
&vdev_root_ops,
&vdev_raidz_ops,
&vdev_mirror_ops,
&vdev_replacing_ops,
&vdev_spare_ops,
#ifdef _KERNEL
&vdev_geom_ops,
#else
&vdev_disk_ops,
#endif
&vdev_file_ops,
&vdev_missing_ops,
&vdev_hole_ops,
NULL
};
/*
* Given a vdev type, return the appropriate ops vector.
*/
static vdev_ops_t *
vdev_getops(const char *type)
{
vdev_ops_t *ops, **opspp;
for (opspp = vdev_ops_table; (ops = *opspp) != NULL; opspp++)
if (strcmp(ops->vdev_op_type, type) == 0)
break;
return (ops);
}
/*
* Default asize function: return the MAX of psize with the asize of
* all children. This is what's used by anything other than RAID-Z.
*/
uint64_t
vdev_default_asize(vdev_t *vd, uint64_t psize)
{
uint64_t asize = P2ROUNDUP(psize, 1ULL << vd->vdev_top->vdev_ashift);
uint64_t csize;
for (int c = 0; c < vd->vdev_children; c++) {
csize = vdev_psize_to_asize(vd->vdev_child[c], psize);
asize = MAX(asize, csize);
}
return (asize);
}
/*
* Get the minimum allocatable size. We define the allocatable size as
* the vdev's asize rounded to the nearest metaslab. This allows us to
* replace or attach devices which don't have the same physical size but
* can still satisfy the same number of allocations.
*/
uint64_t
vdev_get_min_asize(vdev_t *vd)
{
vdev_t *pvd = vd->vdev_parent;
/*
* If our parent is NULL (inactive spare or cache) or is the root,
* just return our own asize.
*/
if (pvd == NULL)
return (vd->vdev_asize);
/*
* The top-level vdev just returns the allocatable size rounded
* to the nearest metaslab.
*/
if (vd == vd->vdev_top)
return (P2ALIGN(vd->vdev_asize, 1ULL << vd->vdev_ms_shift));
/*
* The allocatable space for a raidz vdev is N * sizeof(smallest child),
* so each child must provide at least 1/Nth of its asize.
*/
if (pvd->vdev_ops == &vdev_raidz_ops)
return (pvd->vdev_min_asize / pvd->vdev_children);
return (pvd->vdev_min_asize);
}
void
vdev_set_min_asize(vdev_t *vd)
{
vd->vdev_min_asize = vdev_get_min_asize(vd);
for (int c = 0; c < vd->vdev_children; c++)
vdev_set_min_asize(vd->vdev_child[c]);
}
vdev_t *
vdev_lookup_top(spa_t *spa, uint64_t vdev)
{
vdev_t *rvd = spa->spa_root_vdev;
ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
if (vdev < rvd->vdev_children) {
ASSERT(rvd->vdev_child[vdev] != NULL);
return (rvd->vdev_child[vdev]);
}
return (NULL);
}
vdev_t *
vdev_lookup_by_guid(vdev_t *vd, uint64_t guid)
{
vdev_t *mvd;
if (vd->vdev_guid == guid)
return (vd);
for (int c = 0; c < vd->vdev_children; c++)
if ((mvd = vdev_lookup_by_guid(vd->vdev_child[c], guid)) !=
NULL)
return (mvd);
return (NULL);
}
void
vdev_add_child(vdev_t *pvd, vdev_t *cvd)
{
size_t oldsize, newsize;
uint64_t id = cvd->vdev_id;
vdev_t **newchild;
ASSERT(spa_config_held(cvd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
ASSERT(cvd->vdev_parent == NULL);
cvd->vdev_parent = pvd;
if (pvd == NULL)
return;
ASSERT(id >= pvd->vdev_children || pvd->vdev_child[id] == NULL);
oldsize = pvd->vdev_children * sizeof (vdev_t *);
pvd->vdev_children = MAX(pvd->vdev_children, id + 1);
newsize = pvd->vdev_children * sizeof (vdev_t *);
newchild = kmem_zalloc(newsize, KM_SLEEP);
if (pvd->vdev_child != NULL) {
bcopy(pvd->vdev_child, newchild, oldsize);
kmem_free(pvd->vdev_child, oldsize);
}
pvd->vdev_child = newchild;
pvd->vdev_child[id] = cvd;
cvd->vdev_top = (pvd->vdev_top ? pvd->vdev_top: cvd);
ASSERT(cvd->vdev_top->vdev_parent->vdev_parent == NULL);
/*
* Walk up all ancestors to update guid sum.
*/
for (; pvd != NULL; pvd = pvd->vdev_parent)
pvd->vdev_guid_sum += cvd->vdev_guid_sum;
}
void
vdev_remove_child(vdev_t *pvd, vdev_t *cvd)
{
int c;
uint_t id = cvd->vdev_id;
ASSERT(cvd->vdev_parent == pvd);
if (pvd == NULL)
return;
ASSERT(id < pvd->vdev_children);
ASSERT(pvd->vdev_child[id] == cvd);
pvd->vdev_child[id] = NULL;
cvd->vdev_parent = NULL;
for (c = 0; c < pvd->vdev_children; c++)
if (pvd->vdev_child[c])
break;
if (c == pvd->vdev_children) {
kmem_free(pvd->vdev_child, c * sizeof (vdev_t *));
pvd->vdev_child = NULL;
pvd->vdev_children = 0;
}
/*
* Walk up all ancestors to update guid sum.
*/
for (; pvd != NULL; pvd = pvd->vdev_parent)
pvd->vdev_guid_sum -= cvd->vdev_guid_sum;
}
/*
* Remove any holes in the child array.
*/
void
vdev_compact_children(vdev_t *pvd)
{
vdev_t **newchild, *cvd;
int oldc = pvd->vdev_children;
int newc;
ASSERT(spa_config_held(pvd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
for (int c = newc = 0; c < oldc; c++)
if (pvd->vdev_child[c])
newc++;
newchild = kmem_alloc(newc * sizeof (vdev_t *), KM_SLEEP);
for (int c = newc = 0; c < oldc; c++) {
if ((cvd = pvd->vdev_child[c]) != NULL) {
newchild[newc] = cvd;
cvd->vdev_id = newc++;
}
}
kmem_free(pvd->vdev_child, oldc * sizeof (vdev_t *));
pvd->vdev_child = newchild;
pvd->vdev_children = newc;
}
/*
* Allocate and minimally initialize a vdev_t.
*/
vdev_t *
vdev_alloc_common(spa_t *spa, uint_t id, uint64_t guid, vdev_ops_t *ops)
{
vdev_t *vd;
vd = kmem_zalloc(sizeof (vdev_t), KM_SLEEP);
if (spa->spa_root_vdev == NULL) {
ASSERT(ops == &vdev_root_ops);
spa->spa_root_vdev = vd;
spa->spa_load_guid = spa_generate_guid(NULL);
}
if (guid == 0 && ops != &vdev_hole_ops) {
if (spa->spa_root_vdev == vd) {
/*
* The root vdev's guid will also be the pool guid,
* which must be unique among all pools.
*/
guid = spa_generate_guid(NULL);
} else {
/*
* Any other vdev's guid must be unique within the pool.
*/
guid = spa_generate_guid(spa);
}
ASSERT(!spa_guid_exists(spa_guid(spa), guid));
}
vd->vdev_spa = spa;
vd->vdev_id = id;
vd->vdev_guid = guid;
vd->vdev_guid_sum = guid;
vd->vdev_ops = ops;
vd->vdev_state = VDEV_STATE_CLOSED;
vd->vdev_ishole = (ops == &vdev_hole_ops);
mutex_init(&vd->vdev_dtl_lock, NULL, MUTEX_DEFAULT, NULL);
mutex_init(&vd->vdev_stat_lock, NULL, MUTEX_DEFAULT, NULL);
mutex_init(&vd->vdev_probe_lock, NULL, MUTEX_DEFAULT, NULL);
for (int t = 0; t < DTL_TYPES; t++) {
space_map_create(&vd->vdev_dtl[t], 0, -1ULL, 0,
&vd->vdev_dtl_lock);
}
txg_list_create(&vd->vdev_ms_list,
offsetof(struct metaslab, ms_txg_node));
txg_list_create(&vd->vdev_dtl_list,
offsetof(struct vdev, vdev_dtl_node));
vd->vdev_stat.vs_timestamp = gethrtime();
vdev_queue_init(vd);
vdev_cache_init(vd);
return (vd);
}
/*
* Allocate a new vdev. The 'alloctype' is used to control whether we are
* creating a new vdev or loading an existing one - the behavior is slightly
* different for each case.
*/
int
vdev_alloc(spa_t *spa, vdev_t **vdp, nvlist_t *nv, vdev_t *parent, uint_t id,
int alloctype)
{
vdev_ops_t *ops;
char *type;
uint64_t guid = 0, islog, nparity;
vdev_t *vd;
ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
if (nvlist_lookup_string(nv, ZPOOL_CONFIG_TYPE, &type) != 0)
return (SET_ERROR(EINVAL));
if ((ops = vdev_getops(type)) == NULL)
return (SET_ERROR(EINVAL));
/*
* If this is a load, get the vdev guid from the nvlist.
* Otherwise, vdev_alloc_common() will generate one for us.
*/
if (alloctype == VDEV_ALLOC_LOAD) {
uint64_t label_id;
if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ID, &label_id) ||
label_id != id)
return (SET_ERROR(EINVAL));
if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
return (SET_ERROR(EINVAL));
} else if (alloctype == VDEV_ALLOC_SPARE) {
if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
return (SET_ERROR(EINVAL));
} else if (alloctype == VDEV_ALLOC_L2CACHE) {
if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
return (SET_ERROR(EINVAL));
} else if (alloctype == VDEV_ALLOC_ROOTPOOL) {
if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_GUID, &guid) != 0)
return (SET_ERROR(EINVAL));
}
/*
* The first allocated vdev must be of type 'root'.
*/
if (ops != &vdev_root_ops && spa->spa_root_vdev == NULL)
return (SET_ERROR(EINVAL));
/*
* Determine whether we're a log vdev.
*/
islog = 0;
(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_LOG, &islog);
if (islog && spa_version(spa) < SPA_VERSION_SLOGS)
return (SET_ERROR(ENOTSUP));
if (ops == &vdev_hole_ops && spa_version(spa) < SPA_VERSION_HOLES)
return (SET_ERROR(ENOTSUP));
/*
* Set the nparity property for RAID-Z vdevs.
*/
nparity = -1ULL;
if (ops == &vdev_raidz_ops) {
if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NPARITY,
&nparity) == 0) {
if (nparity == 0 || nparity > VDEV_RAIDZ_MAXPARITY)
return (SET_ERROR(EINVAL));
/*
* Previous versions could only support 1 or 2 parity
* device.
*/
if (nparity > 1 &&
spa_version(spa) < SPA_VERSION_RAIDZ2)
return (SET_ERROR(ENOTSUP));
if (nparity > 2 &&
spa_version(spa) < SPA_VERSION_RAIDZ3)
return (SET_ERROR(ENOTSUP));
} else {
/*
* We require the parity to be specified for SPAs that
* support multiple parity levels.
*/
if (spa_version(spa) >= SPA_VERSION_RAIDZ2)
return (SET_ERROR(EINVAL));
/*
* Otherwise, we default to 1 parity device for RAID-Z.
*/
nparity = 1;
}
} else {
nparity = 0;
}
ASSERT(nparity != -1ULL);
vd = vdev_alloc_common(spa, id, guid, ops);
vd->vdev_islog = islog;
vd->vdev_nparity = nparity;
if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PATH, &vd->vdev_path) == 0)
vd->vdev_path = spa_strdup(vd->vdev_path);
if (nvlist_lookup_string(nv, ZPOOL_CONFIG_DEVID, &vd->vdev_devid) == 0)
vd->vdev_devid = spa_strdup(vd->vdev_devid);
if (nvlist_lookup_string(nv, ZPOOL_CONFIG_PHYS_PATH,
&vd->vdev_physpath) == 0)
vd->vdev_physpath = spa_strdup(vd->vdev_physpath);
if (nvlist_lookup_string(nv, ZPOOL_CONFIG_FRU, &vd->vdev_fru) == 0)
vd->vdev_fru = spa_strdup(vd->vdev_fru);
/*
* Set the whole_disk property. If it's not specified, leave the value
* as -1.
*/
if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_WHOLE_DISK,
&vd->vdev_wholedisk) != 0)
vd->vdev_wholedisk = -1ULL;
/*
* Look for the 'not present' flag. This will only be set if the device
* was not present at the time of import.
*/
(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_NOT_PRESENT,
&vd->vdev_not_present);
/*
* Get the alignment requirement.
*/
(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ASHIFT, &vd->vdev_ashift);
/*
* Retrieve the vdev creation time.
*/
(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_CREATE_TXG,
&vd->vdev_crtxg);
/*
* If we're a top-level vdev, try to load the allocation parameters.
*/
if (parent && !parent->vdev_parent &&
(alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_SPLIT)) {
(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_METASLAB_ARRAY,
&vd->vdev_ms_array);
(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_METASLAB_SHIFT,
&vd->vdev_ms_shift);
(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_ASIZE,
&vd->vdev_asize);
(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVING,
&vd->vdev_removing);
}
if (parent && !parent->vdev_parent && alloctype != VDEV_ALLOC_ATTACH) {
ASSERT(alloctype == VDEV_ALLOC_LOAD ||
alloctype == VDEV_ALLOC_ADD ||
alloctype == VDEV_ALLOC_SPLIT ||
alloctype == VDEV_ALLOC_ROOTPOOL);
vd->vdev_mg = metaslab_group_create(islog ?
spa_log_class(spa) : spa_normal_class(spa), vd);
}
/*
* If we're a leaf vdev, try to load the DTL object and other state.
*/
if (vd->vdev_ops->vdev_op_leaf &&
(alloctype == VDEV_ALLOC_LOAD || alloctype == VDEV_ALLOC_L2CACHE ||
alloctype == VDEV_ALLOC_ROOTPOOL)) {
if (alloctype == VDEV_ALLOC_LOAD) {
(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_DTL,
&vd->vdev_dtl_smo.smo_object);
(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_UNSPARE,
&vd->vdev_unspare);
}
if (alloctype == VDEV_ALLOC_ROOTPOOL) {
uint64_t spare = 0;
if (nvlist_lookup_uint64(nv, ZPOOL_CONFIG_IS_SPARE,
&spare) == 0 && spare)
spa_spare_add(vd);
}
(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_OFFLINE,
&vd->vdev_offline);
(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_RESILVERING,
&vd->vdev_resilvering);
/*
* When importing a pool, we want to ignore the persistent fault
* state, as the diagnosis made on another system may not be
* valid in the current context. Local vdevs will
* remain in the faulted state.
*/
if (spa_load_state(spa) == SPA_LOAD_OPEN) {
(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_FAULTED,
&vd->vdev_faulted);
(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_DEGRADED,
&vd->vdev_degraded);
(void) nvlist_lookup_uint64(nv, ZPOOL_CONFIG_REMOVED,
&vd->vdev_removed);
if (vd->vdev_faulted || vd->vdev_degraded) {
char *aux;
vd->vdev_label_aux =
VDEV_AUX_ERR_EXCEEDED;
if (nvlist_lookup_string(nv,
ZPOOL_CONFIG_AUX_STATE, &aux) == 0 &&
strcmp(aux, "external") == 0)
vd->vdev_label_aux = VDEV_AUX_EXTERNAL;
}
}
}
/*
* Add ourselves to the parent's list of children.
*/
vdev_add_child(parent, vd);
*vdp = vd;
return (0);
}
void
vdev_free(vdev_t *vd)
{
spa_t *spa = vd->vdev_spa;
/*
* vdev_free() implies closing the vdev first. This is simpler than
* trying to ensure complicated semantics for all callers.
*/
vdev_close(vd);
ASSERT(!list_link_active(&vd->vdev_config_dirty_node));
ASSERT(!list_link_active(&vd->vdev_state_dirty_node));
/*
* Free all children.
*/
for (int c = 0; c < vd->vdev_children; c++)
vdev_free(vd->vdev_child[c]);
ASSERT(vd->vdev_child == NULL);
ASSERT(vd->vdev_guid_sum == vd->vdev_guid);
/*
* Discard allocation state.
*/
if (vd->vdev_mg != NULL) {
vdev_metaslab_fini(vd);
metaslab_group_destroy(vd->vdev_mg);
}
ASSERT0(vd->vdev_stat.vs_space);
ASSERT0(vd->vdev_stat.vs_dspace);
ASSERT0(vd->vdev_stat.vs_alloc);
/*
* Remove this vdev from its parent's child list.
*/
vdev_remove_child(vd->vdev_parent, vd);
ASSERT(vd->vdev_parent == NULL);
/*
* Clean up vdev structure.
*/
vdev_queue_fini(vd);
vdev_cache_fini(vd);
if (vd->vdev_path)
spa_strfree(vd->vdev_path);
if (vd->vdev_devid)
spa_strfree(vd->vdev_devid);
if (vd->vdev_physpath)
spa_strfree(vd->vdev_physpath);
if (vd->vdev_fru)
spa_strfree(vd->vdev_fru);
if (vd->vdev_isspare)
spa_spare_remove(vd);
if (vd->vdev_isl2cache)
spa_l2cache_remove(vd);
txg_list_destroy(&vd->vdev_ms_list);
txg_list_destroy(&vd->vdev_dtl_list);
mutex_enter(&vd->vdev_dtl_lock);
for (int t = 0; t < DTL_TYPES; t++) {
space_map_unload(&vd->vdev_dtl[t]);
space_map_destroy(&vd->vdev_dtl[t]);
}
mutex_exit(&vd->vdev_dtl_lock);
mutex_destroy(&vd->vdev_dtl_lock);
mutex_destroy(&vd->vdev_stat_lock);
mutex_destroy(&vd->vdev_probe_lock);
if (vd == spa->spa_root_vdev)
spa->spa_root_vdev = NULL;
kmem_free(vd, sizeof (vdev_t));
}
/*
* Transfer top-level vdev state from svd to tvd.
*/
static void
vdev_top_transfer(vdev_t *svd, vdev_t *tvd)
{
spa_t *spa = svd->vdev_spa;
metaslab_t *msp;
vdev_t *vd;
int t;
ASSERT(tvd == tvd->vdev_top);
tvd->vdev_ms_array = svd->vdev_ms_array;
tvd->vdev_ms_shift = svd->vdev_ms_shift;
tvd->vdev_ms_count = svd->vdev_ms_count;
svd->vdev_ms_array = 0;
svd->vdev_ms_shift = 0;
svd->vdev_ms_count = 0;
if (tvd->vdev_mg)
ASSERT3P(tvd->vdev_mg, ==, svd->vdev_mg);
tvd->vdev_mg = svd->vdev_mg;
tvd->vdev_ms = svd->vdev_ms;
svd->vdev_mg = NULL;
svd->vdev_ms = NULL;
if (tvd->vdev_mg != NULL)
tvd->vdev_mg->mg_vd = tvd;
tvd->vdev_stat.vs_alloc = svd->vdev_stat.vs_alloc;
tvd->vdev_stat.vs_space = svd->vdev_stat.vs_space;
tvd->vdev_stat.vs_dspace = svd->vdev_stat.vs_dspace;
svd->vdev_stat.vs_alloc = 0;
svd->vdev_stat.vs_space = 0;
svd->vdev_stat.vs_dspace = 0;
for (t = 0; t < TXG_SIZE; t++) {
while ((msp = txg_list_remove(&svd->vdev_ms_list, t)) != NULL)
(void) txg_list_add(&tvd->vdev_ms_list, msp, t);
while ((vd = txg_list_remove(&svd->vdev_dtl_list, t)) != NULL)
(void) txg_list_add(&tvd->vdev_dtl_list, vd, t);
if (txg_list_remove_this(&spa->spa_vdev_txg_list, svd, t))
(void) txg_list_add(&spa->spa_vdev_txg_list, tvd, t);
}
if (list_link_active(&svd->vdev_config_dirty_node)) {
vdev_config_clean(svd);
vdev_config_dirty(tvd);
}
if (list_link_active(&svd->vdev_state_dirty_node)) {
vdev_state_clean(svd);
vdev_state_dirty(tvd);
}
tvd->vdev_deflate_ratio = svd->vdev_deflate_ratio;
svd->vdev_deflate_ratio = 0;
tvd->vdev_islog = svd->vdev_islog;
svd->vdev_islog = 0;
}
static void
vdev_top_update(vdev_t *tvd, vdev_t *vd)
{
if (vd == NULL)
return;
vd->vdev_top = tvd;
for (int c = 0; c < vd->vdev_children; c++)
vdev_top_update(tvd, vd->vdev_child[c]);
}
/*
* Add a mirror/replacing vdev above an existing vdev.
*/
vdev_t *
vdev_add_parent(vdev_t *cvd, vdev_ops_t *ops)
{
spa_t *spa = cvd->vdev_spa;
vdev_t *pvd = cvd->vdev_parent;
vdev_t *mvd;
ASSERT(spa_config_held(spa, SCL_ALL, RW_WRITER) == SCL_ALL);
mvd = vdev_alloc_common(spa, cvd->vdev_id, 0, ops);
mvd->vdev_asize = cvd->vdev_asize;
mvd->vdev_min_asize = cvd->vdev_min_asize;
mvd->vdev_max_asize = cvd->vdev_max_asize;
mvd->vdev_ashift = cvd->vdev_ashift;
mvd->vdev_state = cvd->vdev_state;
mvd->vdev_crtxg = cvd->vdev_crtxg;
vdev_remove_child(pvd, cvd);
vdev_add_child(pvd, mvd);
cvd->vdev_id = mvd->vdev_children;
vdev_add_child(mvd, cvd);
vdev_top_update(cvd->vdev_top, cvd->vdev_top);
if (mvd == mvd->vdev_top)
vdev_top_transfer(cvd, mvd);
return (mvd);
}
/*
* Remove a 1-way mirror/replacing vdev from the tree.
*/
void
vdev_remove_parent(vdev_t *cvd)
{
vdev_t *mvd = cvd->vdev_parent;
vdev_t *pvd = mvd->vdev_parent;
ASSERT(spa_config_held(cvd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
ASSERT(mvd->vdev_children == 1);
ASSERT(mvd->vdev_ops == &vdev_mirror_ops ||
mvd->vdev_ops == &vdev_replacing_ops ||
mvd->vdev_ops == &vdev_spare_ops);
cvd->vdev_ashift = mvd->vdev_ashift;
vdev_remove_child(mvd, cvd);
vdev_remove_child(pvd, mvd);
/*
* If cvd will replace mvd as a top-level vdev, preserve mvd's guid.
* Otherwise, we could have detached an offline device, and when we
* go to import the pool we'll think we have two top-level vdevs,
* instead of a different version of the same top-level vdev.
*/
if (mvd->vdev_top == mvd) {
uint64_t guid_delta = mvd->vdev_guid - cvd->vdev_guid;
cvd->vdev_orig_guid = cvd->vdev_guid;
cvd->vdev_guid += guid_delta;
cvd->vdev_guid_sum += guid_delta;
}
cvd->vdev_id = mvd->vdev_id;
vdev_add_child(pvd, cvd);
vdev_top_update(cvd->vdev_top, cvd->vdev_top);
if (cvd == cvd->vdev_top)
vdev_top_transfer(mvd, cvd);
ASSERT(mvd->vdev_children == 0);
vdev_free(mvd);
}
int
vdev_metaslab_init(vdev_t *vd, uint64_t txg)
{
spa_t *spa = vd->vdev_spa;
objset_t *mos = spa->spa_meta_objset;
uint64_t m;
uint64_t oldc = vd->vdev_ms_count;
uint64_t newc = vd->vdev_asize >> vd->vdev_ms_shift;
metaslab_t **mspp;
int error;
ASSERT(txg == 0 || spa_config_held(spa, SCL_ALLOC, RW_WRITER));
/*
* This vdev is not being allocated from yet or is a hole.
*/
if (vd->vdev_ms_shift == 0)
return (0);
ASSERT(!vd->vdev_ishole);
/*
* Compute the raidz-deflation ratio. Note, we hard-code
* in 128k (1 << 17) because it is the current "typical" blocksize.
* Even if SPA_MAXBLOCKSIZE changes, this algorithm must never change,
* or we will inconsistently account for existing bp's.
*/
vd->vdev_deflate_ratio = (1 << 17) /
(vdev_psize_to_asize(vd, 1 << 17) >> SPA_MINBLOCKSHIFT);
ASSERT(oldc <= newc);
mspp = kmem_zalloc(newc * sizeof (*mspp), KM_SLEEP);
if (oldc != 0) {
bcopy(vd->vdev_ms, mspp, oldc * sizeof (*mspp));
kmem_free(vd->vdev_ms, oldc * sizeof (*mspp));
}
vd->vdev_ms = mspp;
vd->vdev_ms_count = newc;
for (m = oldc; m < newc; m++) {
space_map_obj_t smo = { 0, 0, 0 };
if (txg == 0) {
uint64_t object = 0;
error = dmu_read(mos, vd->vdev_ms_array,
m * sizeof (uint64_t), sizeof (uint64_t), &object,
DMU_READ_PREFETCH);
if (error)
return (error);
if (object != 0) {
dmu_buf_t *db;
error = dmu_bonus_hold(mos, object, FTAG, &db);
if (error)
return (error);
ASSERT3U(db->db_size, >=, sizeof (smo));
bcopy(db->db_data, &smo, sizeof (smo));
ASSERT3U(smo.smo_object, ==, object);
dmu_buf_rele(db, FTAG);
}
}
vd->vdev_ms[m] = metaslab_init(vd->vdev_mg, &smo,
m << vd->vdev_ms_shift, 1ULL << vd->vdev_ms_shift, txg);
}
if (txg == 0)
spa_config_enter(spa, SCL_ALLOC, FTAG, RW_WRITER);
/*
* If the vdev is being removed we don't activate
* the metaslabs since we want to ensure that no new
* allocations are performed on this device.
*/
if (oldc == 0 && !vd->vdev_removing)
metaslab_group_activate(vd->vdev_mg);
if (txg == 0)
spa_config_exit(spa, SCL_ALLOC, FTAG);
return (0);
}
void
vdev_metaslab_fini(vdev_t *vd)
{
uint64_t m;
uint64_t count = vd->vdev_ms_count;
if (vd->vdev_ms != NULL) {
metaslab_group_passivate(vd->vdev_mg);
for (m = 0; m < count; m++)
if (vd->vdev_ms[m] != NULL)
metaslab_fini(vd->vdev_ms[m]);
kmem_free(vd->vdev_ms, count * sizeof (metaslab_t *));
vd->vdev_ms = NULL;
}
}
typedef struct vdev_probe_stats {
boolean_t vps_readable;
boolean_t vps_writeable;
int vps_flags;
} vdev_probe_stats_t;
static void
vdev_probe_done(zio_t *zio)
{
spa_t *spa = zio->io_spa;
vdev_t *vd = zio->io_vd;
vdev_probe_stats_t *vps = zio->io_private;
ASSERT(vd->vdev_probe_zio != NULL);
if (zio->io_type == ZIO_TYPE_READ) {
if (zio->io_error == 0)
vps->vps_readable = 1;
if (zio->io_error == 0 && spa_writeable(spa)) {
zio_nowait(zio_write_phys(vd->vdev_probe_zio, vd,
zio->io_offset, zio->io_size, zio->io_data,
ZIO_CHECKSUM_OFF, vdev_probe_done, vps,
ZIO_PRIORITY_SYNC_WRITE, vps->vps_flags, B_TRUE));
} else {
zio_buf_free(zio->io_data, zio->io_size);
}
} else if (zio->io_type == ZIO_TYPE_WRITE) {
if (zio->io_error == 0)
vps->vps_writeable = 1;
zio_buf_free(zio->io_data, zio->io_size);
} else if (zio->io_type == ZIO_TYPE_NULL) {
zio_t *pio;
vd->vdev_cant_read |= !vps->vps_readable;
vd->vdev_cant_write |= !vps->vps_writeable;
if (vdev_readable(vd) &&
(vdev_writeable(vd) || !spa_writeable(spa))) {
zio->io_error = 0;
} else {
ASSERT(zio->io_error != 0);
zfs_ereport_post(FM_EREPORT_ZFS_PROBE_FAILURE,
spa, vd, NULL, 0, 0);
zio->io_error = SET_ERROR(ENXIO);
}
mutex_enter(&vd->vdev_probe_lock);
ASSERT(vd->vdev_probe_zio == zio);
vd->vdev_probe_zio = NULL;
mutex_exit(&vd->vdev_probe_lock);
while ((pio = zio_walk_parents(zio)) != NULL)
if (!vdev_accessible(vd, pio))
pio->io_error = SET_ERROR(ENXIO);
kmem_free(vps, sizeof (*vps));
}
}
/*
* Determine whether this device is accessible.
*
* Read and write to several known locations: the pad regions of each
* vdev label but the first, which we leave alone in case it contains
* a VTOC.
*/
zio_t *
vdev_probe(vdev_t *vd, zio_t *zio)
{
spa_t *spa = vd->vdev_spa;
vdev_probe_stats_t *vps = NULL;
zio_t *pio;
ASSERT(vd->vdev_ops->vdev_op_leaf);
/*
* Don't probe the probe.
*/
if (zio && (zio->io_flags & ZIO_FLAG_PROBE))
return (NULL);
/*
* To prevent 'probe storms' when a device fails, we create
* just one probe i/o at a time. All zios that want to probe
* this vdev will become parents of the probe io.
*/
mutex_enter(&vd->vdev_probe_lock);
if ((pio = vd->vdev_probe_zio) == NULL) {
vps = kmem_zalloc(sizeof (*vps), KM_SLEEP);
vps->vps_flags = ZIO_FLAG_CANFAIL | ZIO_FLAG_PROBE |
ZIO_FLAG_DONT_CACHE | ZIO_FLAG_DONT_AGGREGATE |
ZIO_FLAG_TRYHARD;
if (spa_config_held(spa, SCL_ZIO, RW_WRITER)) {
/*
* vdev_cant_read and vdev_cant_write can only
* transition from TRUE to FALSE when we have the
* SCL_ZIO lock as writer; otherwise they can only
* transition from FALSE to TRUE. This ensures that
* any zio looking at these values can assume that
* failures persist for the life of the I/O. That's
* important because when a device has intermittent
* connectivity problems, we want to ensure that
* they're ascribed to the device (ENXIO) and not
* the zio (EIO).
*
* Since we hold SCL_ZIO as writer here, clear both
* values so the probe can reevaluate from first
* principles.
*/
vps->vps_flags |= ZIO_FLAG_CONFIG_WRITER;
vd->vdev_cant_read = B_FALSE;
vd->vdev_cant_write = B_FALSE;
}
vd->vdev_probe_zio = pio = zio_null(NULL, spa, vd,
vdev_probe_done, vps,
vps->vps_flags | ZIO_FLAG_DONT_PROPAGATE);
/*
* We can't change the vdev state in this context, so we
* kick off an async task to do it on our behalf.
*/
if (zio != NULL) {
vd->vdev_probe_wanted = B_TRUE;
spa_async_request(spa, SPA_ASYNC_PROBE);
}
}
if (zio != NULL)
zio_add_child(zio, pio);
mutex_exit(&vd->vdev_probe_lock);
if (vps == NULL) {
ASSERT(zio != NULL);
return (NULL);
}
for (int l = 1; l < VDEV_LABELS; l++) {
zio_nowait(zio_read_phys(pio, vd,
vdev_label_offset(vd->vdev_psize, l,
offsetof(vdev_label_t, vl_pad2)),
VDEV_PAD_SIZE, zio_buf_alloc(VDEV_PAD_SIZE),
ZIO_CHECKSUM_OFF, vdev_probe_done, vps,
ZIO_PRIORITY_SYNC_READ, vps->vps_flags, B_TRUE));
}
if (zio == NULL)
return (pio);
zio_nowait(pio);
return (NULL);
}
static void
vdev_open_child(void *arg)
{
vdev_t *vd = arg;
vd->vdev_open_thread = curthread;
vd->vdev_open_error = vdev_open(vd);
vd->vdev_open_thread = NULL;
}
boolean_t
vdev_uses_zvols(vdev_t *vd)
{
if (vd->vdev_path && strncmp(vd->vdev_path, ZVOL_DIR,
strlen(ZVOL_DIR)) == 0)
return (B_TRUE);
for (int c = 0; c < vd->vdev_children; c++)
if (vdev_uses_zvols(vd->vdev_child[c]))
return (B_TRUE);
return (B_FALSE);
}
void
vdev_open_children(vdev_t *vd)
{
taskq_t *tq;
int children = vd->vdev_children;
/*
* in order to handle pools on top of zvols, do the opens
* in a single thread so that the same thread holds the
* spa_namespace_lock
*/
if (B_TRUE || vdev_uses_zvols(vd)) {
for (int c = 0; c < children; c++)
vd->vdev_child[c]->vdev_open_error =
vdev_open(vd->vdev_child[c]);
return;
}
tq = taskq_create("vdev_open", children, minclsyspri,
children, children, TASKQ_PREPOPULATE);
for (int c = 0; c < children; c++)
VERIFY(taskq_dispatch(tq, vdev_open_child, vd->vdev_child[c],
TQ_SLEEP) != 0);
taskq_destroy(tq);
}
/*
* Prepare a virtual device for access.
*/
int
vdev_open(vdev_t *vd)
{
spa_t *spa = vd->vdev_spa;
int error;
uint64_t osize = 0;
uint64_t max_osize = 0;
uint64_t asize, max_asize, psize;
uint64_t ashift = 0;
ASSERT(vd->vdev_open_thread == curthread ||
spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
ASSERT(vd->vdev_state == VDEV_STATE_CLOSED ||
vd->vdev_state == VDEV_STATE_CANT_OPEN ||
vd->vdev_state == VDEV_STATE_OFFLINE);
vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
vd->vdev_cant_read = B_FALSE;
vd->vdev_cant_write = B_FALSE;
vd->vdev_min_asize = vdev_get_min_asize(vd);
/*
* If this vdev is not removed, check its fault status. If it's
* faulted, bail out of the open.
*/
if (!vd->vdev_removed && vd->vdev_faulted) {
ASSERT(vd->vdev_children == 0);
ASSERT(vd->vdev_label_aux == VDEV_AUX_ERR_EXCEEDED ||
vd->vdev_label_aux == VDEV_AUX_EXTERNAL);
vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
vd->vdev_label_aux);
return (SET_ERROR(ENXIO));
} else if (vd->vdev_offline) {
ASSERT(vd->vdev_children == 0);
vdev_set_state(vd, B_TRUE, VDEV_STATE_OFFLINE, VDEV_AUX_NONE);
return (SET_ERROR(ENXIO));
}
error = vd->vdev_ops->vdev_op_open(vd, &osize, &max_osize, &ashift);
/*
* Reset the vdev_reopening flag so that we actually close
* the vdev on error.
*/
vd->vdev_reopening = B_FALSE;
if (zio_injection_enabled && error == 0)
error = zio_handle_device_injection(vd, NULL, ENXIO);
if (error) {
if (vd->vdev_removed &&
vd->vdev_stat.vs_aux != VDEV_AUX_OPEN_FAILED)
vd->vdev_removed = B_FALSE;
vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
vd->vdev_stat.vs_aux);
return (error);
}
vd->vdev_removed = B_FALSE;
/*
* Recheck the faulted flag now that we have confirmed that
* the vdev is accessible. If we're faulted, bail.
*/
if (vd->vdev_faulted) {
ASSERT(vd->vdev_children == 0);
ASSERT(vd->vdev_label_aux == VDEV_AUX_ERR_EXCEEDED ||
vd->vdev_label_aux == VDEV_AUX_EXTERNAL);
vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
vd->vdev_label_aux);
return (SET_ERROR(ENXIO));
}
if (vd->vdev_degraded) {
ASSERT(vd->vdev_children == 0);
vdev_set_state(vd, B_TRUE, VDEV_STATE_DEGRADED,
VDEV_AUX_ERR_EXCEEDED);
} else {
vdev_set_state(vd, B_TRUE, VDEV_STATE_HEALTHY, 0);
}
/*
* For hole or missing vdevs we just return success.
*/
if (vd->vdev_ishole || vd->vdev_ops == &vdev_missing_ops)
return (0);
if (vd->vdev_ops->vdev_op_leaf) {
vd->vdev_notrim = B_FALSE;
trim_map_create(vd);
}
for (int c = 0; c < vd->vdev_children; c++) {
if (vd->vdev_child[c]->vdev_state != VDEV_STATE_HEALTHY) {
vdev_set_state(vd, B_TRUE, VDEV_STATE_DEGRADED,
VDEV_AUX_NONE);
break;
}
}
osize = P2ALIGN(osize, (uint64_t)sizeof (vdev_label_t));
max_osize = P2ALIGN(max_osize, (uint64_t)sizeof (vdev_label_t));
if (vd->vdev_children == 0) {
if (osize < SPA_MINDEVSIZE) {
vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
VDEV_AUX_TOO_SMALL);
return (SET_ERROR(EOVERFLOW));
}
psize = osize;
asize = osize - (VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE);
max_asize = max_osize - (VDEV_LABEL_START_SIZE +
VDEV_LABEL_END_SIZE);
} else {
if (vd->vdev_parent != NULL && osize < SPA_MINDEVSIZE -
(VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE)) {
vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
VDEV_AUX_TOO_SMALL);
return (SET_ERROR(EOVERFLOW));
}
psize = 0;
asize = osize;
max_asize = max_osize;
}
vd->vdev_psize = psize;
/*
* Make sure the allocatable size hasn't shrunk.
*/
if (asize < vd->vdev_min_asize) {
vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
VDEV_AUX_BAD_LABEL);
return (SET_ERROR(EINVAL));
}
if (vd->vdev_asize == 0) {
/*
* This is the first-ever open, so use the computed values.
* For testing purposes, a higher ashift can be requested.
*/
vd->vdev_asize = asize;
vd->vdev_max_asize = max_asize;
vd->vdev_ashift = MAX(ashift, vd->vdev_ashift);
} else {
/*
* Make sure the alignment requirement hasn't increased.
*/
if (ashift > vd->vdev_top->vdev_ashift) {
vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
VDEV_AUX_BAD_LABEL);
return (EINVAL);
}
vd->vdev_max_asize = max_asize;
}
/*
* If all children are healthy and the asize has increased,
* then we've experienced dynamic LUN growth. If automatic
* expansion is enabled then use the additional space.
*/
if (vd->vdev_state == VDEV_STATE_HEALTHY && asize > vd->vdev_asize &&
(vd->vdev_expanding || spa->spa_autoexpand))
vd->vdev_asize = asize;
vdev_set_min_asize(vd);
/*
* Ensure we can issue some IO before declaring the
* vdev open for business.
*/
if (vd->vdev_ops->vdev_op_leaf &&
(error = zio_wait(vdev_probe(vd, NULL))) != 0) {
vdev_set_state(vd, B_TRUE, VDEV_STATE_FAULTED,
VDEV_AUX_ERR_EXCEEDED);
return (error);
}
/*
* If a leaf vdev has a DTL, and seems healthy, then kick off a
* resilver. But don't do this if we are doing a reopen for a scrub,
* since this would just restart the scrub we are already doing.
*/
if (vd->vdev_ops->vdev_op_leaf && !spa->spa_scrub_reopen &&
vdev_resilver_needed(vd, NULL, NULL))
spa_async_request(spa, SPA_ASYNC_RESILVER);
return (0);
}
/*
* Called once the vdevs are all opened, this routine validates the label
* contents. This needs to be done before vdev_load() so that we don't
* inadvertently do repair I/Os to the wrong device.
*
* If 'strict' is false ignore the spa guid check. This is necessary because
* if the machine crashed during a re-guid the new guid might have been written
* to all of the vdev labels, but not the cached config. The strict check
* will be performed when the pool is opened again using the mos config.
*
* This function will only return failure if one of the vdevs indicates that it
* has since been destroyed or exported. This is only possible if
* /etc/zfs/zpool.cache was readonly at the time. Otherwise, the vdev state
* will be updated but the function will return 0.
*/
int
vdev_validate(vdev_t *vd, boolean_t strict)
{
spa_t *spa = vd->vdev_spa;
nvlist_t *label;
uint64_t guid = 0, top_guid;
uint64_t state;
for (int c = 0; c < vd->vdev_children; c++)
if (vdev_validate(vd->vdev_child[c], strict) != 0)
return (SET_ERROR(EBADF));
/*
* If the device has already failed, or was marked offline, don't do
* any further validation. Otherwise, label I/O will fail and we will
* overwrite the previous state.
*/
if (vd->vdev_ops->vdev_op_leaf && vdev_readable(vd)) {
uint64_t aux_guid = 0;
nvlist_t *nvl;
uint64_t txg = spa_last_synced_txg(spa) != 0 ?
spa_last_synced_txg(spa) : -1ULL;
if ((label = vdev_label_read_config(vd, txg)) == NULL) {
vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
VDEV_AUX_BAD_LABEL);
return (0);
}
/*
* Determine if this vdev has been split off into another
* pool. If so, then refuse to open it.
*/
if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_SPLIT_GUID,
&aux_guid) == 0 && aux_guid == spa_guid(spa)) {
vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
VDEV_AUX_SPLIT_POOL);
nvlist_free(label);
return (0);
}
if (strict && (nvlist_lookup_uint64(label,
ZPOOL_CONFIG_POOL_GUID, &guid) != 0 ||
guid != spa_guid(spa))) {
vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
VDEV_AUX_CORRUPT_DATA);
nvlist_free(label);
return (0);
}
if (nvlist_lookup_nvlist(label, ZPOOL_CONFIG_VDEV_TREE, &nvl)
!= 0 || nvlist_lookup_uint64(nvl, ZPOOL_CONFIG_ORIG_GUID,
&aux_guid) != 0)
aux_guid = 0;
/*
* If this vdev just became a top-level vdev because its
* sibling was detached, it will have adopted the parent's
* vdev guid -- but the label may or may not be on disk yet.
* Fortunately, either version of the label will have the
* same top guid, so if we're a top-level vdev, we can
* safely compare to that instead.
*
* If we split this vdev off instead, then we also check the
* original pool's guid. We don't want to consider the vdev
* corrupt if it is partway through a split operation.
*/
if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID,
&guid) != 0 ||
nvlist_lookup_uint64(label, ZPOOL_CONFIG_TOP_GUID,
&top_guid) != 0 ||
((vd->vdev_guid != guid && vd->vdev_guid != aux_guid) &&
(vd->vdev_guid != top_guid || vd != vd->vdev_top))) {
vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
VDEV_AUX_CORRUPT_DATA);
nvlist_free(label);
return (0);
}
if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE,
&state) != 0) {
vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
VDEV_AUX_CORRUPT_DATA);
nvlist_free(label);
return (0);
}
nvlist_free(label);
/*
* If this is a verbatim import, no need to check the
* state of the pool.
*/
if (!(spa->spa_import_flags & ZFS_IMPORT_VERBATIM) &&
spa_load_state(spa) == SPA_LOAD_OPEN &&
state != POOL_STATE_ACTIVE)
return (SET_ERROR(EBADF));
/*
* If we were able to open and validate a vdev that was
* previously marked permanently unavailable, clear that state
* now.
*/
if (vd->vdev_not_present)
vd->vdev_not_present = 0;
}
return (0);
}
/*
* Close a virtual device.
*/
void
vdev_close(vdev_t *vd)
{
spa_t *spa = vd->vdev_spa;
vdev_t *pvd = vd->vdev_parent;
ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
/*
* If our parent is reopening, then we are as well, unless we are
* going offline.
*/
if (pvd != NULL && pvd->vdev_reopening)
vd->vdev_reopening = (pvd->vdev_reopening && !vd->vdev_offline);
vd->vdev_ops->vdev_op_close(vd);
vdev_cache_purge(vd);
if (vd->vdev_ops->vdev_op_leaf)
trim_map_destroy(vd);
/*
* We record the previous state before we close it, so that if we are
* doing a reopen(), we don't generate FMA ereports if we notice that
* it's still faulted.
*/
vd->vdev_prevstate = vd->vdev_state;
if (vd->vdev_offline)
vd->vdev_state = VDEV_STATE_OFFLINE;
else
vd->vdev_state = VDEV_STATE_CLOSED;
vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
}
void
vdev_hold(vdev_t *vd)
{
spa_t *spa = vd->vdev_spa;
ASSERT(spa_is_root(spa));
if (spa->spa_state == POOL_STATE_UNINITIALIZED)
return;
for (int c = 0; c < vd->vdev_children; c++)
vdev_hold(vd->vdev_child[c]);
if (vd->vdev_ops->vdev_op_leaf)
vd->vdev_ops->vdev_op_hold(vd);
}
void
vdev_rele(vdev_t *vd)
{
spa_t *spa = vd->vdev_spa;
ASSERT(spa_is_root(spa));
for (int c = 0; c < vd->vdev_children; c++)
vdev_rele(vd->vdev_child[c]);
if (vd->vdev_ops->vdev_op_leaf)
vd->vdev_ops->vdev_op_rele(vd);
}
/*
* Reopen all interior vdevs and any unopened leaves. We don't actually
* reopen leaf vdevs which had previously been opened as they might deadlock
* on the spa_config_lock. Instead we only obtain the leaf's physical size.
* If the leaf has never been opened then open it, as usual.
*/
void
vdev_reopen(vdev_t *vd)
{
spa_t *spa = vd->vdev_spa;
ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
/* set the reopening flag unless we're taking the vdev offline */
vd->vdev_reopening = !vd->vdev_offline;
vdev_close(vd);
(void) vdev_open(vd);
/*
* Call vdev_validate() here to make sure we have the same device.
* Otherwise, a device with an invalid label could be successfully
* opened in response to vdev_reopen().
*/
if (vd->vdev_aux) {
(void) vdev_validate_aux(vd);
if (vdev_readable(vd) && vdev_writeable(vd) &&
vd->vdev_aux == &spa->spa_l2cache &&
!l2arc_vdev_present(vd))
l2arc_add_vdev(spa, vd);
} else {
(void) vdev_validate(vd, B_TRUE);
}
/*
* Reassess parent vdev's health.
*/
vdev_propagate_state(vd);
}
int
vdev_create(vdev_t *vd, uint64_t txg, boolean_t isreplacing)
{
int error;
/*
* Normally, partial opens (e.g. of a mirror) are allowed.
* For a create, however, we want to fail the request if
* there are any components we can't open.
*/
error = vdev_open(vd);
if (error || vd->vdev_state != VDEV_STATE_HEALTHY) {
vdev_close(vd);
return (error ? error : ENXIO);
}
/*
* Recursively initialize all labels.
*/
if ((error = vdev_label_init(vd, txg, isreplacing ?
VDEV_LABEL_REPLACE : VDEV_LABEL_CREATE)) != 0) {
vdev_close(vd);
return (error);
}
return (0);
}
void
vdev_metaslab_set_size(vdev_t *vd)
{
/*
* Aim for roughly 200 metaslabs per vdev.
*/
vd->vdev_ms_shift = highbit(vd->vdev_asize / 200);
vd->vdev_ms_shift = MAX(vd->vdev_ms_shift, SPA_MAXBLOCKSHIFT);
}
void
vdev_dirty(vdev_t *vd, int flags, void *arg, uint64_t txg)
{
ASSERT(vd == vd->vdev_top);
ASSERT(!vd->vdev_ishole);
ASSERT(ISP2(flags));
ASSERT(spa_writeable(vd->vdev_spa));
if (flags & VDD_METASLAB)
(void) txg_list_add(&vd->vdev_ms_list, arg, txg);
if (flags & VDD_DTL)
(void) txg_list_add(&vd->vdev_dtl_list, arg, txg);
(void) txg_list_add(&vd->vdev_spa->spa_vdev_txg_list, vd, txg);
}
/*
* DTLs.
*
* A vdev's DTL (dirty time log) is the set of transaction groups for which
* the vdev has less than perfect replication. There are four kinds of DTL:
*
* DTL_MISSING: txgs for which the vdev has no valid copies of the data
*
* DTL_PARTIAL: txgs for which data is available, but not fully replicated
*
* DTL_SCRUB: the txgs that could not be repaired by the last scrub; upon
* scrub completion, DTL_SCRUB replaces DTL_MISSING in the range of
* txgs that was scrubbed.
*
* DTL_OUTAGE: txgs which cannot currently be read, whether due to
* persistent errors or just some device being offline.
* Unlike the other three, the DTL_OUTAGE map is not generally
* maintained; it's only computed when needed, typically to
* determine whether a device can be detached.
*
* For leaf vdevs, DTL_MISSING and DTL_PARTIAL are identical: the device
* either has the data or it doesn't.
*
* For interior vdevs such as mirror and RAID-Z the picture is more complex.
* A vdev's DTL_PARTIAL is the union of its children's DTL_PARTIALs, because
* if any child is less than fully replicated, then so is its parent.
* A vdev's DTL_MISSING is a modified union of its children's DTL_MISSINGs,
* comprising only those txgs which appear in 'maxfaults' or more children;
* those are the txgs we don't have enough replication to read. For example,
* double-parity RAID-Z can tolerate up to two missing devices (maxfaults == 2);
* thus, its DTL_MISSING consists of the set of txgs that appear in more than
* two child DTL_MISSING maps.
*
* It should be clear from the above that to compute the DTLs and outage maps
* for all vdevs, it suffices to know just the leaf vdevs' DTL_MISSING maps.
* Therefore, that is all we keep on disk. When loading the pool, or after
* a configuration change, we generate all other DTLs from first principles.
*/
void
vdev_dtl_dirty(vdev_t *vd, vdev_dtl_type_t t, uint64_t txg, uint64_t size)
{
space_map_t *sm = &vd->vdev_dtl[t];
ASSERT(t < DTL_TYPES);
ASSERT(vd != vd->vdev_spa->spa_root_vdev);
ASSERT(spa_writeable(vd->vdev_spa));
mutex_enter(sm->sm_lock);
if (!space_map_contains(sm, txg, size))
space_map_add(sm, txg, size);
mutex_exit(sm->sm_lock);
}
boolean_t
vdev_dtl_contains(vdev_t *vd, vdev_dtl_type_t t, uint64_t txg, uint64_t size)
{
space_map_t *sm = &vd->vdev_dtl[t];
boolean_t dirty = B_FALSE;
ASSERT(t < DTL_TYPES);
ASSERT(vd != vd->vdev_spa->spa_root_vdev);
mutex_enter(sm->sm_lock);
if (sm->sm_space != 0)
dirty = space_map_contains(sm, txg, size);
mutex_exit(sm->sm_lock);
return (dirty);
}
boolean_t
vdev_dtl_empty(vdev_t *vd, vdev_dtl_type_t t)
{
space_map_t *sm = &vd->vdev_dtl[t];
boolean_t empty;
mutex_enter(sm->sm_lock);
empty = (sm->sm_space == 0);
mutex_exit(sm->sm_lock);
return (empty);
}
/*
* Reassess DTLs after a config change or scrub completion.
*/
void
vdev_dtl_reassess(vdev_t *vd, uint64_t txg, uint64_t scrub_txg, int scrub_done)
{
spa_t *spa = vd->vdev_spa;
avl_tree_t reftree;
int minref;
ASSERT(spa_config_held(spa, SCL_ALL, RW_READER) != 0);
for (int c = 0; c < vd->vdev_children; c++)
vdev_dtl_reassess(vd->vdev_child[c], txg,
scrub_txg, scrub_done);
if (vd == spa->spa_root_vdev || vd->vdev_ishole || vd->vdev_aux)
return;
if (vd->vdev_ops->vdev_op_leaf) {
dsl_scan_t *scn = spa->spa_dsl_pool->dp_scan;
mutex_enter(&vd->vdev_dtl_lock);
if (scrub_txg != 0 &&
(spa->spa_scrub_started ||
(scn && scn->scn_phys.scn_errors == 0))) {
/*
* We completed a scrub up to scrub_txg. If we
* did it without rebooting, then the scrub dtl
* will be valid, so excise the old region and
* fold in the scrub dtl. Otherwise, leave the
* dtl as-is if there was an error.
*
* There's little trick here: to excise the beginning
* of the DTL_MISSING map, we put it into a reference
* tree and then add a segment with refcnt -1 that
* covers the range [0, scrub_txg). This means
* that each txg in that range has refcnt -1 or 0.
* We then add DTL_SCRUB with a refcnt of 2, so that
* entries in the range [0, scrub_txg) will have a
* positive refcnt -- either 1 or 2. We then convert
* the reference tree into the new DTL_MISSING map.
*/
space_map_ref_create(&reftree);
space_map_ref_add_map(&reftree,
&vd->vdev_dtl[DTL_MISSING], 1);
space_map_ref_add_seg(&reftree, 0, scrub_txg, -1);
space_map_ref_add_map(&reftree,
&vd->vdev_dtl[DTL_SCRUB], 2);
space_map_ref_generate_map(&reftree,
&vd->vdev_dtl[DTL_MISSING], 1);
space_map_ref_destroy(&reftree);
}
space_map_vacate(&vd->vdev_dtl[DTL_PARTIAL], NULL, NULL);
space_map_walk(&vd->vdev_dtl[DTL_MISSING],
space_map_add, &vd->vdev_dtl[DTL_PARTIAL]);
if (scrub_done)
space_map_vacate(&vd->vdev_dtl[DTL_SCRUB], NULL, NULL);
space_map_vacate(&vd->vdev_dtl[DTL_OUTAGE], NULL, NULL);
if (!vdev_readable(vd))
space_map_add(&vd->vdev_dtl[DTL_OUTAGE], 0, -1ULL);
else
space_map_walk(&vd->vdev_dtl[DTL_MISSING],
space_map_add, &vd->vdev_dtl[DTL_OUTAGE]);
mutex_exit(&vd->vdev_dtl_lock);
if (txg != 0)
vdev_dirty(vd->vdev_top, VDD_DTL, vd, txg);
return;
}
mutex_enter(&vd->vdev_dtl_lock);
for (int t = 0; t < DTL_TYPES; t++) {
/* account for child's outage in parent's missing map */
int s = (t == DTL_MISSING) ? DTL_OUTAGE: t;
if (t == DTL_SCRUB)
continue; /* leaf vdevs only */
if (t == DTL_PARTIAL)
minref = 1; /* i.e. non-zero */
else if (vd->vdev_nparity != 0)
minref = vd->vdev_nparity + 1; /* RAID-Z */
else
minref = vd->vdev_children; /* any kind of mirror */
space_map_ref_create(&reftree);
for (int c = 0; c < vd->vdev_children; c++) {
vdev_t *cvd = vd->vdev_child[c];
mutex_enter(&cvd->vdev_dtl_lock);
space_map_ref_add_map(&reftree, &cvd->vdev_dtl[s], 1);
mutex_exit(&cvd->vdev_dtl_lock);
}
space_map_ref_generate_map(&reftree, &vd->vdev_dtl[t], minref);
space_map_ref_destroy(&reftree);
}
mutex_exit(&vd->vdev_dtl_lock);
}
static int
vdev_dtl_load(vdev_t *vd)
{
spa_t *spa = vd->vdev_spa;
space_map_obj_t *smo = &vd->vdev_dtl_smo;
objset_t *mos = spa->spa_meta_objset;
dmu_buf_t *db;
int error;
ASSERT(vd->vdev_children == 0);
if (smo->smo_object == 0)
return (0);
ASSERT(!vd->vdev_ishole);
if ((error = dmu_bonus_hold(mos, smo->smo_object, FTAG, &db)) != 0)
return (error);
ASSERT3U(db->db_size, >=, sizeof (*smo));
bcopy(db->db_data, smo, sizeof (*smo));
dmu_buf_rele(db, FTAG);
mutex_enter(&vd->vdev_dtl_lock);
error = space_map_load(&vd->vdev_dtl[DTL_MISSING],
NULL, SM_ALLOC, smo, mos);
mutex_exit(&vd->vdev_dtl_lock);
return (error);
}
void
vdev_dtl_sync(vdev_t *vd, uint64_t txg)
{
spa_t *spa = vd->vdev_spa;
space_map_obj_t *smo = &vd->vdev_dtl_smo;
space_map_t *sm = &vd->vdev_dtl[DTL_MISSING];
objset_t *mos = spa->spa_meta_objset;
space_map_t smsync;
kmutex_t smlock;
dmu_buf_t *db;
dmu_tx_t *tx;
ASSERT(!vd->vdev_ishole);
tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
if (vd->vdev_detached) {
if (smo->smo_object != 0) {
int err = dmu_object_free(mos, smo->smo_object, tx);
ASSERT0(err);
smo->smo_object = 0;
}
dmu_tx_commit(tx);
return;
}
if (smo->smo_object == 0) {
ASSERT(smo->smo_objsize == 0);
ASSERT(smo->smo_alloc == 0);
smo->smo_object = dmu_object_alloc(mos,
DMU_OT_SPACE_MAP, 1 << SPACE_MAP_BLOCKSHIFT,
DMU_OT_SPACE_MAP_HEADER, sizeof (*smo), tx);
ASSERT(smo->smo_object != 0);
vdev_config_dirty(vd->vdev_top);
}
mutex_init(&smlock, NULL, MUTEX_DEFAULT, NULL);
space_map_create(&smsync, sm->sm_start, sm->sm_size, sm->sm_shift,
&smlock);
mutex_enter(&smlock);
mutex_enter(&vd->vdev_dtl_lock);
space_map_walk(sm, space_map_add, &smsync);
mutex_exit(&vd->vdev_dtl_lock);
space_map_truncate(smo, mos, tx);
space_map_sync(&smsync, SM_ALLOC, smo, mos, tx);
space_map_vacate(&smsync, NULL, NULL);
space_map_destroy(&smsync);
mutex_exit(&smlock);
mutex_destroy(&smlock);
VERIFY(0 == dmu_bonus_hold(mos, smo->smo_object, FTAG, &db));
dmu_buf_will_dirty(db, tx);
ASSERT3U(db->db_size, >=, sizeof (*smo));
bcopy(smo, db->db_data, sizeof (*smo));
dmu_buf_rele(db, FTAG);
dmu_tx_commit(tx);
}
/*
* Determine whether the specified vdev can be offlined/detached/removed
* without losing data.
*/
boolean_t
vdev_dtl_required(vdev_t *vd)
{
spa_t *spa = vd->vdev_spa;
vdev_t *tvd = vd->vdev_top;
uint8_t cant_read = vd->vdev_cant_read;
boolean_t required;
ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
if (vd == spa->spa_root_vdev || vd == tvd)
return (B_TRUE);
/*
* Temporarily mark the device as unreadable, and then determine
* whether this results in any DTL outages in the top-level vdev.
* If not, we can safely offline/detach/remove the device.
*/
vd->vdev_cant_read = B_TRUE;
vdev_dtl_reassess(tvd, 0, 0, B_FALSE);
required = !vdev_dtl_empty(tvd, DTL_OUTAGE);
vd->vdev_cant_read = cant_read;
vdev_dtl_reassess(tvd, 0, 0, B_FALSE);
if (!required && zio_injection_enabled)
required = !!zio_handle_device_injection(vd, NULL, ECHILD);
return (required);
}
/*
* Determine if resilver is needed, and if so the txg range.
*/
boolean_t
vdev_resilver_needed(vdev_t *vd, uint64_t *minp, uint64_t *maxp)
{
boolean_t needed = B_FALSE;
uint64_t thismin = UINT64_MAX;
uint64_t thismax = 0;
if (vd->vdev_children == 0) {
mutex_enter(&vd->vdev_dtl_lock);
if (vd->vdev_dtl[DTL_MISSING].sm_space != 0 &&
vdev_writeable(vd)) {
space_seg_t *ss;
ss = avl_first(&vd->vdev_dtl[DTL_MISSING].sm_root);
thismin = ss->ss_start - 1;
ss = avl_last(&vd->vdev_dtl[DTL_MISSING].sm_root);
thismax = ss->ss_end;
needed = B_TRUE;
}
mutex_exit(&vd->vdev_dtl_lock);
} else {
for (int c = 0; c < vd->vdev_children; c++) {
vdev_t *cvd = vd->vdev_child[c];
uint64_t cmin, cmax;
if (vdev_resilver_needed(cvd, &cmin, &cmax)) {
thismin = MIN(thismin, cmin);
thismax = MAX(thismax, cmax);
needed = B_TRUE;
}
}
}
if (needed && minp) {
*minp = thismin;
*maxp = thismax;
}
return (needed);
}
void
vdev_load(vdev_t *vd)
{
/*
* Recursively load all children.
*/
for (int c = 0; c < vd->vdev_children; c++)
vdev_load(vd->vdev_child[c]);
/*
* If this is a top-level vdev, initialize its metaslabs.
*/
if (vd == vd->vdev_top && !vd->vdev_ishole &&
(vd->vdev_ashift == 0 || vd->vdev_asize == 0 ||
vdev_metaslab_init(vd, 0) != 0))
vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
VDEV_AUX_CORRUPT_DATA);
/*
* If this is a leaf vdev, load its DTL.
*/
if (vd->vdev_ops->vdev_op_leaf && vdev_dtl_load(vd) != 0)
vdev_set_state(vd, B_FALSE, VDEV_STATE_CANT_OPEN,
VDEV_AUX_CORRUPT_DATA);
}
/*
* The special vdev case is used for hot spares and l2cache devices. Its
* sole purpose it to set the vdev state for the associated vdev. To do this,
* we make sure that we can open the underlying device, then try to read the
* label, and make sure that the label is sane and that it hasn't been
* repurposed to another pool.
*/
int
vdev_validate_aux(vdev_t *vd)
{
nvlist_t *label;
uint64_t guid, version;
uint64_t state;
if (!vdev_readable(vd))
return (0);
if ((label = vdev_label_read_config(vd, -1ULL)) == NULL) {
vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
VDEV_AUX_CORRUPT_DATA);
return (-1);
}
if (nvlist_lookup_uint64(label, ZPOOL_CONFIG_VERSION, &version) != 0 ||
!SPA_VERSION_IS_SUPPORTED(version) ||
nvlist_lookup_uint64(label, ZPOOL_CONFIG_GUID, &guid) != 0 ||
guid != vd->vdev_guid ||
nvlist_lookup_uint64(label, ZPOOL_CONFIG_POOL_STATE, &state) != 0) {
vdev_set_state(vd, B_TRUE, VDEV_STATE_CANT_OPEN,
VDEV_AUX_CORRUPT_DATA);
nvlist_free(label);
return (-1);
}
/*
* We don't actually check the pool state here. If it's in fact in
* use by another pool, we update this fact on the fly when requested.
*/
nvlist_free(label);
return (0);
}
void
vdev_remove(vdev_t *vd, uint64_t txg)
{
spa_t *spa = vd->vdev_spa;
objset_t *mos = spa->spa_meta_objset;
dmu_tx_t *tx;
tx = dmu_tx_create_assigned(spa_get_dsl(spa), txg);
if (vd->vdev_dtl_smo.smo_object) {
ASSERT0(vd->vdev_dtl_smo.smo_alloc);
(void) dmu_object_free(mos, vd->vdev_dtl_smo.smo_object, tx);
vd->vdev_dtl_smo.smo_object = 0;
}
if (vd->vdev_ms != NULL) {
for (int m = 0; m < vd->vdev_ms_count; m++) {
metaslab_t *msp = vd->vdev_ms[m];
if (msp == NULL || msp->ms_smo.smo_object == 0)
continue;
ASSERT0(msp->ms_smo.smo_alloc);
(void) dmu_object_free(mos, msp->ms_smo.smo_object, tx);
msp->ms_smo.smo_object = 0;
}
}
if (vd->vdev_ms_array) {
(void) dmu_object_free(mos, vd->vdev_ms_array, tx);
vd->vdev_ms_array = 0;
vd->vdev_ms_shift = 0;
}
dmu_tx_commit(tx);
}
void
vdev_sync_done(vdev_t *vd, uint64_t txg)
{
metaslab_t *msp;
boolean_t reassess = !txg_list_empty(&vd->vdev_ms_list, TXG_CLEAN(txg));
ASSERT(!vd->vdev_ishole);
while (msp = txg_list_remove(&vd->vdev_ms_list, TXG_CLEAN(txg)))
metaslab_sync_done(msp, txg);
if (reassess)
metaslab_sync_reassess(vd->vdev_mg);
}
void
vdev_sync(vdev_t *vd, uint64_t txg)
{
spa_t *spa = vd->vdev_spa;
vdev_t *lvd;
metaslab_t *msp;
dmu_tx_t *tx;
ASSERT(!vd->vdev_ishole);
if (vd->vdev_ms_array == 0 && vd->vdev_ms_shift != 0) {
ASSERT(vd == vd->vdev_top);
tx = dmu_tx_create_assigned(spa->spa_dsl_pool, txg);
vd->vdev_ms_array = dmu_object_alloc(spa->spa_meta_objset,
DMU_OT_OBJECT_ARRAY, 0, DMU_OT_NONE, 0, tx);
ASSERT(vd->vdev_ms_array != 0);
vdev_config_dirty(vd);
dmu_tx_commit(tx);
}
/*
* Remove the metadata associated with this vdev once it's empty.
*/
if (vd->vdev_stat.vs_alloc == 0 && vd->vdev_removing)
vdev_remove(vd, txg);
while ((msp = txg_list_remove(&vd->vdev_ms_list, txg)) != NULL) {
metaslab_sync(msp, txg);
(void) txg_list_add(&vd->vdev_ms_list, msp, TXG_CLEAN(txg));
}
while ((lvd = txg_list_remove(&vd->vdev_dtl_list, txg)) != NULL)
vdev_dtl_sync(lvd, txg);
(void) txg_list_add(&spa->spa_vdev_txg_list, vd, TXG_CLEAN(txg));
}
uint64_t
vdev_psize_to_asize(vdev_t *vd, uint64_t psize)
{
return (vd->vdev_ops->vdev_op_asize(vd, psize));
}
/*
* Mark the given vdev faulted. A faulted vdev behaves as if the device could
* not be opened, and no I/O is attempted.
*/
int
vdev_fault(spa_t *spa, uint64_t guid, vdev_aux_t aux)
{
vdev_t *vd, *tvd;
spa_vdev_state_enter(spa, SCL_NONE);
if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
return (spa_vdev_state_exit(spa, NULL, ENODEV));
if (!vd->vdev_ops->vdev_op_leaf)
return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
tvd = vd->vdev_top;
/*
* We don't directly use the aux state here, but if we do a
* vdev_reopen(), we need this value to be present to remember why we
* were faulted.
*/
vd->vdev_label_aux = aux;
/*
* Faulted state takes precedence over degraded.
*/
vd->vdev_delayed_close = B_FALSE;
vd->vdev_faulted = 1ULL;
vd->vdev_degraded = 0ULL;
vdev_set_state(vd, B_FALSE, VDEV_STATE_FAULTED, aux);
/*
* If this device has the only valid copy of the data, then
* back off and simply mark the vdev as degraded instead.
*/
if (!tvd->vdev_islog && vd->vdev_aux == NULL && vdev_dtl_required(vd)) {
vd->vdev_degraded = 1ULL;
vd->vdev_faulted = 0ULL;
/*
* If we reopen the device and it's not dead, only then do we
* mark it degraded.
*/
vdev_reopen(tvd);
if (vdev_readable(vd))
vdev_set_state(vd, B_FALSE, VDEV_STATE_DEGRADED, aux);
}
return (spa_vdev_state_exit(spa, vd, 0));
}
/*
* Mark the given vdev degraded. A degraded vdev is purely an indication to the
* user that something is wrong. The vdev continues to operate as normal as far
* as I/O is concerned.
*/
int
vdev_degrade(spa_t *spa, uint64_t guid, vdev_aux_t aux)
{
vdev_t *vd;
spa_vdev_state_enter(spa, SCL_NONE);
if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
return (spa_vdev_state_exit(spa, NULL, ENODEV));
if (!vd->vdev_ops->vdev_op_leaf)
return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
/*
* If the vdev is already faulted, then don't do anything.
*/
if (vd->vdev_faulted || vd->vdev_degraded)
return (spa_vdev_state_exit(spa, NULL, 0));
vd->vdev_degraded = 1ULL;
if (!vdev_is_dead(vd))
vdev_set_state(vd, B_FALSE, VDEV_STATE_DEGRADED,
aux);
return (spa_vdev_state_exit(spa, vd, 0));
}
/*
* Online the given vdev.
*
* If 'ZFS_ONLINE_UNSPARE' is set, it implies two things. First, any attached
* spare device should be detached when the device finishes resilvering.
* Second, the online should be treated like a 'test' online case, so no FMA
* events are generated if the device fails to open.
*/
int
vdev_online(spa_t *spa, uint64_t guid, uint64_t flags, vdev_state_t *newstate)
{
vdev_t *vd, *tvd, *pvd, *rvd = spa->spa_root_vdev;
spa_vdev_state_enter(spa, SCL_NONE);
if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
return (spa_vdev_state_exit(spa, NULL, ENODEV));
if (!vd->vdev_ops->vdev_op_leaf)
return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
tvd = vd->vdev_top;
vd->vdev_offline = B_FALSE;
vd->vdev_tmpoffline = B_FALSE;
vd->vdev_checkremove = !!(flags & ZFS_ONLINE_CHECKREMOVE);
vd->vdev_forcefault = !!(flags & ZFS_ONLINE_FORCEFAULT);
/* XXX - L2ARC 1.0 does not support expansion */
if (!vd->vdev_aux) {
for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
pvd->vdev_expanding = !!(flags & ZFS_ONLINE_EXPAND);
}
vdev_reopen(tvd);
vd->vdev_checkremove = vd->vdev_forcefault = B_FALSE;
if (!vd->vdev_aux) {
for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
pvd->vdev_expanding = B_FALSE;
}
if (newstate)
*newstate = vd->vdev_state;
if ((flags & ZFS_ONLINE_UNSPARE) &&
!vdev_is_dead(vd) && vd->vdev_parent &&
vd->vdev_parent->vdev_ops == &vdev_spare_ops &&
vd->vdev_parent->vdev_child[0] == vd)
vd->vdev_unspare = B_TRUE;
if ((flags & ZFS_ONLINE_EXPAND) || spa->spa_autoexpand) {
/* XXX - L2ARC 1.0 does not support expansion */
if (vd->vdev_aux)
return (spa_vdev_state_exit(spa, vd, ENOTSUP));
spa_async_request(spa, SPA_ASYNC_CONFIG_UPDATE);
}
return (spa_vdev_state_exit(spa, vd, 0));
}
static int
vdev_offline_locked(spa_t *spa, uint64_t guid, uint64_t flags)
{
vdev_t *vd, *tvd;
int error = 0;
uint64_t generation;
metaslab_group_t *mg;
top:
spa_vdev_state_enter(spa, SCL_ALLOC);
if ((vd = spa_lookup_by_guid(spa, guid, B_TRUE)) == NULL)
return (spa_vdev_state_exit(spa, NULL, ENODEV));
if (!vd->vdev_ops->vdev_op_leaf)
return (spa_vdev_state_exit(spa, NULL, ENOTSUP));
tvd = vd->vdev_top;
mg = tvd->vdev_mg;
generation = spa->spa_config_generation + 1;
/*
* If the device isn't already offline, try to offline it.
*/
if (!vd->vdev_offline) {
/*
* If this device has the only valid copy of some data,
* don't allow it to be offlined. Log devices are always
* expendable.
*/
if (!tvd->vdev_islog && vd->vdev_aux == NULL &&
vdev_dtl_required(vd))
return (spa_vdev_state_exit(spa, NULL, EBUSY));
/*
* If the top-level is a slog and it has had allocations
* then proceed. We check that the vdev's metaslab group
* is not NULL since it's possible that we may have just
* added this vdev but not yet initialized its metaslabs.
*/
if (tvd->vdev_islog && mg != NULL) {
/*
* Prevent any future allocations.
*/
metaslab_group_passivate(mg);
(void) spa_vdev_state_exit(spa, vd, 0);
error = spa_offline_log(spa);
spa_vdev_state_enter(spa, SCL_ALLOC);
/*
* Check to see if the config has changed.
*/
if (error || generation != spa->spa_config_generation) {
metaslab_group_activate(mg);
if (error)
return (spa_vdev_state_exit(spa,
vd, error));
(void) spa_vdev_state_exit(spa, vd, 0);
goto top;
}
ASSERT0(tvd->vdev_stat.vs_alloc);
}
/*
* Offline this device and reopen its top-level vdev.
* If the top-level vdev is a log device then just offline
* it. Otherwise, if this action results in the top-level
* vdev becoming unusable, undo it and fail the request.
*/
vd->vdev_offline = B_TRUE;
vdev_reopen(tvd);
if (!tvd->vdev_islog && vd->vdev_aux == NULL &&
vdev_is_dead(tvd)) {
vd->vdev_offline = B_FALSE;
vdev_reopen(tvd);
return (spa_vdev_state_exit(spa, NULL, EBUSY));
}
/*
* Add the device back into the metaslab rotor so that
* once we online the device it's open for business.
*/
if (tvd->vdev_islog && mg != NULL)
metaslab_group_activate(mg);
}
vd->vdev_tmpoffline = !!(flags & ZFS_OFFLINE_TEMPORARY);
return (spa_vdev_state_exit(spa, vd, 0));
}
int
vdev_offline(spa_t *spa, uint64_t guid, uint64_t flags)
{
int error;
mutex_enter(&spa->spa_vdev_top_lock);
error = vdev_offline_locked(spa, guid, flags);
mutex_exit(&spa->spa_vdev_top_lock);
return (error);
}
/*
* Clear the error counts associated with this vdev. Unlike vdev_online() and
* vdev_offline(), we assume the spa config is locked. We also clear all
* children. If 'vd' is NULL, then the user wants to clear all vdevs.
*/
void
vdev_clear(spa_t *spa, vdev_t *vd)
{
vdev_t *rvd = spa->spa_root_vdev;
ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
if (vd == NULL)
vd = rvd;
vd->vdev_stat.vs_read_errors = 0;
vd->vdev_stat.vs_write_errors = 0;
vd->vdev_stat.vs_checksum_errors = 0;
for (int c = 0; c < vd->vdev_children; c++)
vdev_clear(spa, vd->vdev_child[c]);
/*
* If we're in the FAULTED state or have experienced failed I/O, then
* clear the persistent state and attempt to reopen the device. We
* also mark the vdev config dirty, so that the new faulted state is
* written out to disk.
*/
if (vd->vdev_faulted || vd->vdev_degraded ||
!vdev_readable(vd) || !vdev_writeable(vd)) {
/*
* When reopening in reponse to a clear event, it may be due to
* a fmadm repair request. In this case, if the device is
* still broken, we want to still post the ereport again.
*/
vd->vdev_forcefault = B_TRUE;
vd->vdev_faulted = vd->vdev_degraded = 0ULL;
vd->vdev_cant_read = B_FALSE;
vd->vdev_cant_write = B_FALSE;
vdev_reopen(vd == rvd ? rvd : vd->vdev_top);
vd->vdev_forcefault = B_FALSE;
if (vd != rvd && vdev_writeable(vd->vdev_top))
vdev_state_dirty(vd->vdev_top);
if (vd->vdev_aux == NULL && !vdev_is_dead(vd))
spa_async_request(spa, SPA_ASYNC_RESILVER);
spa_event_notify(spa, vd, ESC_ZFS_VDEV_CLEAR);
}
/*
* When clearing a FMA-diagnosed fault, we always want to
* unspare the device, as we assume that the original spare was
* done in response to the FMA fault.
*/
if (!vdev_is_dead(vd) && vd->vdev_parent != NULL &&
vd->vdev_parent->vdev_ops == &vdev_spare_ops &&
vd->vdev_parent->vdev_child[0] == vd)
vd->vdev_unspare = B_TRUE;
}
boolean_t
vdev_is_dead(vdev_t *vd)
{
/*
* Holes and missing devices are always considered "dead".
* This simplifies the code since we don't have to check for
* these types of devices in the various code paths.
* Instead we rely on the fact that we skip over dead devices
* before issuing I/O to them.
*/
return (vd->vdev_state < VDEV_STATE_DEGRADED || vd->vdev_ishole ||
vd->vdev_ops == &vdev_missing_ops);
}
boolean_t
vdev_readable(vdev_t *vd)
{
return (!vdev_is_dead(vd) && !vd->vdev_cant_read);
}
boolean_t
vdev_writeable(vdev_t *vd)
{
return (!vdev_is_dead(vd) && !vd->vdev_cant_write);
}
boolean_t
vdev_allocatable(vdev_t *vd)
{
uint64_t state = vd->vdev_state;
/*
* We currently allow allocations from vdevs which may be in the
* process of reopening (i.e. VDEV_STATE_CLOSED). If the device
* fails to reopen then we'll catch it later when we're holding
* the proper locks. Note that we have to get the vdev state
* in a local variable because although it changes atomically,
* we're asking two separate questions about it.
*/
return (!(state < VDEV_STATE_DEGRADED && state != VDEV_STATE_CLOSED) &&
!vd->vdev_cant_write && !vd->vdev_ishole);
}
boolean_t
vdev_accessible(vdev_t *vd, zio_t *zio)
{
ASSERT(zio->io_vd == vd);
if (vdev_is_dead(vd) || vd->vdev_remove_wanted)
return (B_FALSE);
if (zio->io_type == ZIO_TYPE_READ)
return (!vd->vdev_cant_read);
if (zio->io_type == ZIO_TYPE_WRITE)
return (!vd->vdev_cant_write);
return (B_TRUE);
}
/*
* Get statistics for the given vdev.
*/
void
vdev_get_stats(vdev_t *vd, vdev_stat_t *vs)
{
vdev_t *rvd = vd->vdev_spa->spa_root_vdev;
mutex_enter(&vd->vdev_stat_lock);
bcopy(&vd->vdev_stat, vs, sizeof (*vs));
vs->vs_timestamp = gethrtime() - vs->vs_timestamp;
vs->vs_state = vd->vdev_state;
vs->vs_rsize = vdev_get_min_asize(vd);
if (vd->vdev_ops->vdev_op_leaf)
vs->vs_rsize += VDEV_LABEL_START_SIZE + VDEV_LABEL_END_SIZE;
vs->vs_esize = vd->vdev_max_asize - vd->vdev_asize;
mutex_exit(&vd->vdev_stat_lock);
/*
* If we're getting stats on the root vdev, aggregate the I/O counts
* over all top-level vdevs (i.e. the direct children of the root).
*/
if (vd == rvd) {
for (int c = 0; c < rvd->vdev_children; c++) {
vdev_t *cvd = rvd->vdev_child[c];
vdev_stat_t *cvs = &cvd->vdev_stat;
mutex_enter(&vd->vdev_stat_lock);
for (int t = 0; t < ZIO_TYPES; t++) {
vs->vs_ops[t] += cvs->vs_ops[t];
vs->vs_bytes[t] += cvs->vs_bytes[t];
}
cvs->vs_scan_removing = cvd->vdev_removing;
mutex_exit(&vd->vdev_stat_lock);
}
}
}
void
vdev_clear_stats(vdev_t *vd)
{
mutex_enter(&vd->vdev_stat_lock);
vd->vdev_stat.vs_space = 0;
vd->vdev_stat.vs_dspace = 0;
vd->vdev_stat.vs_alloc = 0;
mutex_exit(&vd->vdev_stat_lock);
}
void
vdev_scan_stat_init(vdev_t *vd)
{
vdev_stat_t *vs = &vd->vdev_stat;
for (int c = 0; c < vd->vdev_children; c++)
vdev_scan_stat_init(vd->vdev_child[c]);
mutex_enter(&vd->vdev_stat_lock);
vs->vs_scan_processed = 0;
mutex_exit(&vd->vdev_stat_lock);
}
void
vdev_stat_update(zio_t *zio, uint64_t psize)
{
spa_t *spa = zio->io_spa;
vdev_t *rvd = spa->spa_root_vdev;
vdev_t *vd = zio->io_vd ? zio->io_vd : rvd;
vdev_t *pvd;
uint64_t txg = zio->io_txg;
vdev_stat_t *vs = &vd->vdev_stat;
zio_type_t type = zio->io_type;
int flags = zio->io_flags;
/*
* If this i/o is a gang leader, it didn't do any actual work.
*/
if (zio->io_gang_tree)
return;
if (zio->io_error == 0) {
/*
* If this is a root i/o, don't count it -- we've already
* counted the top-level vdevs, and vdev_get_stats() will
* aggregate them when asked. This reduces contention on
* the root vdev_stat_lock and implicitly handles blocks
* that compress away to holes, for which there is no i/o.
* (Holes never create vdev children, so all the counters
* remain zero, which is what we want.)
*
* Note: this only applies to successful i/o (io_error == 0)
* because unlike i/o counts, errors are not additive.
* When reading a ditto block, for example, failure of
* one top-level vdev does not imply a root-level error.
*/
if (vd == rvd)
return;
ASSERT(vd == zio->io_vd);
if (flags & ZIO_FLAG_IO_BYPASS)
return;
mutex_enter(&vd->vdev_stat_lock);
if (flags & ZIO_FLAG_IO_REPAIR) {
if (flags & ZIO_FLAG_SCAN_THREAD) {
dsl_scan_phys_t *scn_phys =
&spa->spa_dsl_pool->dp_scan->scn_phys;
uint64_t *processed = &scn_phys->scn_processed;
/* XXX cleanup? */
if (vd->vdev_ops->vdev_op_leaf)
atomic_add_64(processed, psize);
vs->vs_scan_processed += psize;
}
if (flags & ZIO_FLAG_SELF_HEAL)
vs->vs_self_healed += psize;
}
vs->vs_ops[type]++;
vs->vs_bytes[type] += psize;
mutex_exit(&vd->vdev_stat_lock);
return;
}
if (flags & ZIO_FLAG_SPECULATIVE)
return;
/*
* If this is an I/O error that is going to be retried, then ignore the
* error. Otherwise, the user may interpret B_FAILFAST I/O errors as
* hard errors, when in reality they can happen for any number of
* innocuous reasons (bus resets, MPxIO link failure, etc).
*/
if (zio->io_error == EIO &&
!(zio->io_flags & ZIO_FLAG_IO_RETRY))
return;
/*
* Intent logs writes won't propagate their error to the root
* I/O so don't mark these types of failures as pool-level
* errors.
*/
if (zio->io_vd == NULL && (zio->io_flags & ZIO_FLAG_DONT_PROPAGATE))
return;
mutex_enter(&vd->vdev_stat_lock);
if (type == ZIO_TYPE_READ && !vdev_is_dead(vd)) {
if (zio->io_error == ECKSUM)
vs->vs_checksum_errors++;
else
vs->vs_read_errors++;
}
if (type == ZIO_TYPE_WRITE && !vdev_is_dead(vd))
vs->vs_write_errors++;
mutex_exit(&vd->vdev_stat_lock);
if (type == ZIO_TYPE_WRITE && txg != 0 &&
(!(flags & ZIO_FLAG_IO_REPAIR) ||
(flags & ZIO_FLAG_SCAN_THREAD) ||
spa->spa_claiming)) {
/*
* This is either a normal write (not a repair), or it's
* a repair induced by the scrub thread, or it's a repair
* made by zil_claim() during spa_load() in the first txg.
* In the normal case, we commit the DTL change in the same
* txg as the block was born. In the scrub-induced repair
* case, we know that scrubs run in first-pass syncing context,
* so we commit the DTL change in spa_syncing_txg(spa).
* In the zil_claim() case, we commit in spa_first_txg(spa).
*
* We currently do not make DTL entries for failed spontaneous
* self-healing writes triggered by normal (non-scrubbing)
* reads, because we have no transactional context in which to
* do so -- and it's not clear that it'd be desirable anyway.
*/
if (vd->vdev_ops->vdev_op_leaf) {
uint64_t commit_txg = txg;
if (flags & ZIO_FLAG_SCAN_THREAD) {
ASSERT(flags & ZIO_FLAG_IO_REPAIR);
ASSERT(spa_sync_pass(spa) == 1);
vdev_dtl_dirty(vd, DTL_SCRUB, txg, 1);
commit_txg = spa_syncing_txg(spa);
} else if (spa->spa_claiming) {
ASSERT(flags & ZIO_FLAG_IO_REPAIR);
commit_txg = spa_first_txg(spa);
}
ASSERT(commit_txg >= spa_syncing_txg(spa));
if (vdev_dtl_contains(vd, DTL_MISSING, txg, 1))
return;
for (pvd = vd; pvd != rvd; pvd = pvd->vdev_parent)
vdev_dtl_dirty(pvd, DTL_PARTIAL, txg, 1);
vdev_dirty(vd->vdev_top, VDD_DTL, vd, commit_txg);
}
if (vd != rvd)
vdev_dtl_dirty(vd, DTL_MISSING, txg, 1);
}
}
/*
* Update the in-core space usage stats for this vdev, its metaslab class,
* and the root vdev.
*/
void
vdev_space_update(vdev_t *vd, int64_t alloc_delta, int64_t defer_delta,
int64_t space_delta)
{
int64_t dspace_delta = space_delta;
spa_t *spa = vd->vdev_spa;
vdev_t *rvd = spa->spa_root_vdev;
metaslab_group_t *mg = vd->vdev_mg;
metaslab_class_t *mc = mg ? mg->mg_class : NULL;
ASSERT(vd == vd->vdev_top);
/*
* Apply the inverse of the psize-to-asize (ie. RAID-Z) space-expansion
* factor. We must calculate this here and not at the root vdev
* because the root vdev's psize-to-asize is simply the max of its
* childrens', thus not accurate enough for us.
*/
ASSERT((dspace_delta & (SPA_MINBLOCKSIZE-1)) == 0);
ASSERT(vd->vdev_deflate_ratio != 0 || vd->vdev_isl2cache);
dspace_delta = (dspace_delta >> SPA_MINBLOCKSHIFT) *
vd->vdev_deflate_ratio;
mutex_enter(&vd->vdev_stat_lock);
vd->vdev_stat.vs_alloc += alloc_delta;
vd->vdev_stat.vs_space += space_delta;
vd->vdev_stat.vs_dspace += dspace_delta;
mutex_exit(&vd->vdev_stat_lock);
if (mc == spa_normal_class(spa)) {
mutex_enter(&rvd->vdev_stat_lock);
rvd->vdev_stat.vs_alloc += alloc_delta;
rvd->vdev_stat.vs_space += space_delta;
rvd->vdev_stat.vs_dspace += dspace_delta;
mutex_exit(&rvd->vdev_stat_lock);
}
if (mc != NULL) {
ASSERT(rvd == vd->vdev_parent);
ASSERT(vd->vdev_ms_count != 0);
metaslab_class_space_update(mc,
alloc_delta, defer_delta, space_delta, dspace_delta);
}
}
/*
* Mark a top-level vdev's config as dirty, placing it on the dirty list
* so that it will be written out next time the vdev configuration is synced.
* If the root vdev is specified (vdev_top == NULL), dirty all top-level vdevs.
*/
void
vdev_config_dirty(vdev_t *vd)
{
spa_t *spa = vd->vdev_spa;
vdev_t *rvd = spa->spa_root_vdev;
int c;
ASSERT(spa_writeable(spa));
/*
* If this is an aux vdev (as with l2cache and spare devices), then we
* update the vdev config manually and set the sync flag.
*/
if (vd->vdev_aux != NULL) {
spa_aux_vdev_t *sav = vd->vdev_aux;
nvlist_t **aux;
uint_t naux;
for (c = 0; c < sav->sav_count; c++) {
if (sav->sav_vdevs[c] == vd)
break;
}
if (c == sav->sav_count) {
/*
* We're being removed. There's nothing more to do.
*/
ASSERT(sav->sav_sync == B_TRUE);
return;
}
sav->sav_sync = B_TRUE;
if (nvlist_lookup_nvlist_array(sav->sav_config,
ZPOOL_CONFIG_L2CACHE, &aux, &naux) != 0) {
VERIFY(nvlist_lookup_nvlist_array(sav->sav_config,
ZPOOL_CONFIG_SPARES, &aux, &naux) == 0);
}
ASSERT(c < naux);
/*
* Setting the nvlist in the middle if the array is a little
* sketchy, but it will work.
*/
nvlist_free(aux[c]);
aux[c] = vdev_config_generate(spa, vd, B_TRUE, 0);
return;
}
/*
* The dirty list is protected by the SCL_CONFIG lock. The caller
* must either hold SCL_CONFIG as writer, or must be the sync thread
* (which holds SCL_CONFIG as reader). There's only one sync thread,
* so this is sufficient to ensure mutual exclusion.
*/
ASSERT(spa_config_held(spa, SCL_CONFIG, RW_WRITER) ||
(dsl_pool_sync_context(spa_get_dsl(spa)) &&
spa_config_held(spa, SCL_CONFIG, RW_READER)));
if (vd == rvd) {
for (c = 0; c < rvd->vdev_children; c++)
vdev_config_dirty(rvd->vdev_child[c]);
} else {
ASSERT(vd == vd->vdev_top);
if (!list_link_active(&vd->vdev_config_dirty_node) &&
!vd->vdev_ishole)
list_insert_head(&spa->spa_config_dirty_list, vd);
}
}
void
vdev_config_clean(vdev_t *vd)
{
spa_t *spa = vd->vdev_spa;
ASSERT(spa_config_held(spa, SCL_CONFIG, RW_WRITER) ||
(dsl_pool_sync_context(spa_get_dsl(spa)) &&
spa_config_held(spa, SCL_CONFIG, RW_READER)));
ASSERT(list_link_active(&vd->vdev_config_dirty_node));
list_remove(&spa->spa_config_dirty_list, vd);
}
/*
* Mark a top-level vdev's state as dirty, so that the next pass of
* spa_sync() can convert this into vdev_config_dirty(). We distinguish
* the state changes from larger config changes because they require
* much less locking, and are often needed for administrative actions.
*/
void
vdev_state_dirty(vdev_t *vd)
{
spa_t *spa = vd->vdev_spa;
ASSERT(spa_writeable(spa));
ASSERT(vd == vd->vdev_top);
/*
* The state list is protected by the SCL_STATE lock. The caller
* must either hold SCL_STATE as writer, or must be the sync thread
* (which holds SCL_STATE as reader). There's only one sync thread,
* so this is sufficient to ensure mutual exclusion.
*/
ASSERT(spa_config_held(spa, SCL_STATE, RW_WRITER) ||
(dsl_pool_sync_context(spa_get_dsl(spa)) &&
spa_config_held(spa, SCL_STATE, RW_READER)));
if (!list_link_active(&vd->vdev_state_dirty_node) && !vd->vdev_ishole)
list_insert_head(&spa->spa_state_dirty_list, vd);
}
void
vdev_state_clean(vdev_t *vd)
{
spa_t *spa = vd->vdev_spa;
ASSERT(spa_config_held(spa, SCL_STATE, RW_WRITER) ||
(dsl_pool_sync_context(spa_get_dsl(spa)) &&
spa_config_held(spa, SCL_STATE, RW_READER)));
ASSERT(list_link_active(&vd->vdev_state_dirty_node));
list_remove(&spa->spa_state_dirty_list, vd);
}
/*
* Propagate vdev state up from children to parent.
*/
void
vdev_propagate_state(vdev_t *vd)
{
spa_t *spa = vd->vdev_spa;
vdev_t *rvd = spa->spa_root_vdev;
int degraded = 0, faulted = 0;
int corrupted = 0;
vdev_t *child;
if (vd->vdev_children > 0) {
for (int c = 0; c < vd->vdev_children; c++) {
child = vd->vdev_child[c];
/*
* Don't factor holes into the decision.
*/
if (child->vdev_ishole)
continue;
if (!vdev_readable(child) ||
(!vdev_writeable(child) && spa_writeable(spa))) {
/*
* Root special: if there is a top-level log
* device, treat the root vdev as if it were
* degraded.
*/
if (child->vdev_islog && vd == rvd)
degraded++;
else
faulted++;
} else if (child->vdev_state <= VDEV_STATE_DEGRADED) {
degraded++;
}
if (child->vdev_stat.vs_aux == VDEV_AUX_CORRUPT_DATA)
corrupted++;
}
vd->vdev_ops->vdev_op_state_change(vd, faulted, degraded);
/*
* Root special: if there is a top-level vdev that cannot be
* opened due to corrupted metadata, then propagate the root
* vdev's aux state as 'corrupt' rather than 'insufficient
* replicas'.
*/
if (corrupted && vd == rvd &&
rvd->vdev_state == VDEV_STATE_CANT_OPEN)
vdev_set_state(rvd, B_FALSE, VDEV_STATE_CANT_OPEN,
VDEV_AUX_CORRUPT_DATA);
}
if (vd->vdev_parent)
vdev_propagate_state(vd->vdev_parent);
}
/*
* Set a vdev's state. If this is during an open, we don't update the parent
* state, because we're in the process of opening children depth-first.
* Otherwise, we propagate the change to the parent.
*
* If this routine places a device in a faulted state, an appropriate ereport is
* generated.
*/
void
vdev_set_state(vdev_t *vd, boolean_t isopen, vdev_state_t state, vdev_aux_t aux)
{
uint64_t save_state;
spa_t *spa = vd->vdev_spa;
if (state == vd->vdev_state) {
vd->vdev_stat.vs_aux = aux;
return;
}
save_state = vd->vdev_state;
vd->vdev_state = state;
vd->vdev_stat.vs_aux = aux;
/*
* If we are setting the vdev state to anything but an open state, then
* always close the underlying device unless the device has requested
* a delayed close (i.e. we're about to remove or fault the device).
* Otherwise, we keep accessible but invalid devices open forever.
* We don't call vdev_close() itself, because that implies some extra
* checks (offline, etc) that we don't want here. This is limited to
* leaf devices, because otherwise closing the device will affect other
* children.
*/
if (!vd->vdev_delayed_close && vdev_is_dead(vd) &&
vd->vdev_ops->vdev_op_leaf)
vd->vdev_ops->vdev_op_close(vd);
/*
* If we have brought this vdev back into service, we need
* to notify fmd so that it can gracefully repair any outstanding
* cases due to a missing device. We do this in all cases, even those
* that probably don't correlate to a repaired fault. This is sure to
* catch all cases, and we let the zfs-retire agent sort it out. If
* this is a transient state it's OK, as the retire agent will
* double-check the state of the vdev before repairing it.
*/
if (state == VDEV_STATE_HEALTHY && vd->vdev_ops->vdev_op_leaf &&
vd->vdev_prevstate != state)
zfs_post_state_change(spa, vd);
if (vd->vdev_removed &&
state == VDEV_STATE_CANT_OPEN &&
(aux == VDEV_AUX_OPEN_FAILED || vd->vdev_checkremove)) {
/*
* If the previous state is set to VDEV_STATE_REMOVED, then this
* device was previously marked removed and someone attempted to
* reopen it. If this failed due to a nonexistent device, then
* keep the device in the REMOVED state. We also let this be if
* it is one of our special test online cases, which is only
* attempting to online the device and shouldn't generate an FMA
* fault.
*/
vd->vdev_state = VDEV_STATE_REMOVED;
vd->vdev_stat.vs_aux = VDEV_AUX_NONE;
} else if (state == VDEV_STATE_REMOVED) {
vd->vdev_removed = B_TRUE;
} else if (state == VDEV_STATE_CANT_OPEN) {
/*
* If we fail to open a vdev during an import or recovery, we
* mark it as "not available", which signifies that it was
* never there to begin with. Failure to open such a device
* is not considered an error.
*/
if ((spa_load_state(spa) == SPA_LOAD_IMPORT ||
spa_load_state(spa) == SPA_LOAD_RECOVER) &&
vd->vdev_ops->vdev_op_leaf)
vd->vdev_not_present = 1;
/*
* Post the appropriate ereport. If the 'prevstate' field is
* set to something other than VDEV_STATE_UNKNOWN, it indicates
* that this is part of a vdev_reopen(). In this case, we don't
* want to post the ereport if the device was already in the
* CANT_OPEN state beforehand.
*
* If the 'checkremove' flag is set, then this is an attempt to
* online the device in response to an insertion event. If we
* hit this case, then we have detected an insertion event for a
* faulted or offline device that wasn't in the removed state.
* In this scenario, we don't post an ereport because we are
* about to replace the device, or attempt an online with
* vdev_forcefault, which will generate the fault for us.
*/
if ((vd->vdev_prevstate != state || vd->vdev_forcefault) &&
!vd->vdev_not_present && !vd->vdev_checkremove &&
vd != spa->spa_root_vdev) {
const char *class;
switch (aux) {
case VDEV_AUX_OPEN_FAILED:
class = FM_EREPORT_ZFS_DEVICE_OPEN_FAILED;
break;
case VDEV_AUX_CORRUPT_DATA:
class = FM_EREPORT_ZFS_DEVICE_CORRUPT_DATA;
break;
case VDEV_AUX_NO_REPLICAS:
class = FM_EREPORT_ZFS_DEVICE_NO_REPLICAS;
break;
case VDEV_AUX_BAD_GUID_SUM:
class = FM_EREPORT_ZFS_DEVICE_BAD_GUID_SUM;
break;
case VDEV_AUX_TOO_SMALL:
class = FM_EREPORT_ZFS_DEVICE_TOO_SMALL;
break;
case VDEV_AUX_BAD_LABEL:
class = FM_EREPORT_ZFS_DEVICE_BAD_LABEL;
break;
default:
class = FM_EREPORT_ZFS_DEVICE_UNKNOWN;
}
zfs_ereport_post(class, spa, vd, NULL, save_state, 0);
}
/* Erase any notion of persistent removed state */
vd->vdev_removed = B_FALSE;
} else {
vd->vdev_removed = B_FALSE;
}
if (!isopen && vd->vdev_parent)
vdev_propagate_state(vd->vdev_parent);
}
/*
* Check the vdev configuration to ensure that it's capable of supporting
* a root pool.
*
* On Solaris, we do not support RAID-Z or partial configuration. In
* addition, only a single top-level vdev is allowed and none of the
* leaves can be wholedisks.
*
* For FreeBSD, we can boot from any configuration. There is a
* limitation that the boot filesystem must be either uncompressed or
* compresses with lzjb compression but I'm not sure how to enforce
* that here.
*/
boolean_t
vdev_is_bootable(vdev_t *vd)
{
#ifdef sun
if (!vd->vdev_ops->vdev_op_leaf) {
char *vdev_type = vd->vdev_ops->vdev_op_type;
if (strcmp(vdev_type, VDEV_TYPE_ROOT) == 0 &&
vd->vdev_children > 1) {
return (B_FALSE);
} else if (strcmp(vdev_type, VDEV_TYPE_RAIDZ) == 0 ||
strcmp(vdev_type, VDEV_TYPE_MISSING) == 0) {
return (B_FALSE);
}
} else if (vd->vdev_wholedisk == 1) {
return (B_FALSE);
}
for (int c = 0; c < vd->vdev_children; c++) {
if (!vdev_is_bootable(vd->vdev_child[c]))
return (B_FALSE);
}
#endif /* sun */
return (B_TRUE);
}
/*
* Load the state from the original vdev tree (ovd) which
* we've retrieved from the MOS config object. If the original
* vdev was offline or faulted then we transfer that state to the
* device in the current vdev tree (nvd).
*/
void
vdev_load_log_state(vdev_t *nvd, vdev_t *ovd)
{
spa_t *spa = nvd->vdev_spa;
ASSERT(nvd->vdev_top->vdev_islog);
ASSERT(spa_config_held(spa, SCL_STATE_ALL, RW_WRITER) == SCL_STATE_ALL);
ASSERT3U(nvd->vdev_guid, ==, ovd->vdev_guid);
for (int c = 0; c < nvd->vdev_children; c++)
vdev_load_log_state(nvd->vdev_child[c], ovd->vdev_child[c]);
if (nvd->vdev_ops->vdev_op_leaf) {
/*
* Restore the persistent vdev state
*/
nvd->vdev_offline = ovd->vdev_offline;
nvd->vdev_faulted = ovd->vdev_faulted;
nvd->vdev_degraded = ovd->vdev_degraded;
nvd->vdev_removed = ovd->vdev_removed;
}
}
/*
* Determine if a log device has valid content. If the vdev was
* removed or faulted in the MOS config then we know that
* the content on the log device has already been written to the pool.
*/
boolean_t
vdev_log_state_valid(vdev_t *vd)
{
if (vd->vdev_ops->vdev_op_leaf && !vd->vdev_faulted &&
!vd->vdev_removed)
return (B_TRUE);
for (int c = 0; c < vd->vdev_children; c++)
if (vdev_log_state_valid(vd->vdev_child[c]))
return (B_TRUE);
return (B_FALSE);
}
/*
* Expand a vdev if possible.
*/
void
vdev_expand(vdev_t *vd, uint64_t txg)
{
ASSERT(vd->vdev_top == vd);
ASSERT(spa_config_held(vd->vdev_spa, SCL_ALL, RW_WRITER) == SCL_ALL);
if ((vd->vdev_asize >> vd->vdev_ms_shift) > vd->vdev_ms_count) {
VERIFY(vdev_metaslab_init(vd, txg) == 0);
vdev_config_dirty(vd);
}
}
/*
* Split a vdev.
*/
void
vdev_split(vdev_t *vd)
{
vdev_t *cvd, *pvd = vd->vdev_parent;
vdev_remove_child(pvd, vd);
vdev_compact_children(pvd);
cvd = pvd->vdev_child[0];
if (pvd->vdev_children == 1) {
vdev_remove_parent(cvd);
cvd->vdev_splitting = B_TRUE;
}
vdev_propagate_state(cvd);
}
void
vdev_deadman(vdev_t *vd)
{
for (int c = 0; c < vd->vdev_children; c++) {
vdev_t *cvd = vd->vdev_child[c];
vdev_deadman(cvd);
}
if (vd->vdev_ops->vdev_op_leaf) {
vdev_queue_t *vq = &vd->vdev_queue;
mutex_enter(&vq->vq_lock);
if (avl_numnodes(&vq->vq_pending_tree) > 0) {
spa_t *spa = vd->vdev_spa;
zio_t *fio;
uint64_t delta;
/*
* Look at the head of all the pending queues,
* if any I/O has been outstanding for longer than
* the spa_deadman_synctime we panic the system.
*/
fio = avl_first(&vq->vq_pending_tree);
delta = gethrtime() - fio->io_timestamp;
if (delta > spa_deadman_synctime(spa)) {
zfs_dbgmsg("SLOW IO: zio timestamp %lluns, "
"delta %lluns, last io %lluns",
fio->io_timestamp, delta,
vq->vq_io_complete_ts);
fm_panic("I/O to pool '%s' appears to be "
"hung on vdev guid %llu at '%s'.",
spa_name(spa),
(long long unsigned int) vd->vdev_guid,
vd->vdev_path);
}
}
mutex_exit(&vq->vq_lock);
}
}
| 26.953149 | 80 | 0.684344 | [
"object",
"vector"
] |
d048b5fc9e5665b28fb36637e58a75088c579841 | 3,028 | h | C | src/utils/random_number.h | rwk-unil/shapeit4 | 16865e593ad50689271ead985dc8f4296d2f491d | [
"MIT"
] | 73 | 2018-12-14T11:49:56.000Z | 2022-02-09T04:43:09.000Z | src/utils/random_number.h | rwk-unil/shapeit4 | 16865e593ad50689271ead985dc8f4296d2f491d | [
"MIT"
] | 70 | 2019-02-12T22:25:07.000Z | 2022-03-23T13:33:44.000Z | src/utils/random_number.h | rwk-unil/shapeit4 | 16865e593ad50689271ead985dc8f4296d2f491d | [
"MIT"
] | 16 | 2018-12-14T18:32:12.000Z | 2022-01-07T08:57:17.000Z | /*******************************************************************************
* Copyright (C) 2018 Olivier Delaneau, University of Lausanne
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
******************************************************************************/
#ifndef _RANDOM_NUMBER_H
#define _RANDOM_NUMBER_H
#include <cfloat>
#include <cstdint>
#include <random>
#include <vector>
class random_number_generator {
protected:
unsigned int seed;
std::mt19937 randomEngine;
std::uniform_int_distribution < unsigned int > uniformDistributionInt;
std::uniform_real_distribution < double > uniformDistributionDouble;
public:
random_number_generator(unsigned int seed = 15052011) : randomEngine(seed), uniformDistributionInt(0, 32768), uniformDistributionDouble(0, 1.0) {
}
~random_number_generator(){
}
void setSeed(unsigned int _seed) {
seed = _seed;
randomEngine.seed(seed);
}
unsigned int getSeed() {
return seed;
}
std::mt19937 & getEngine() {
return randomEngine;
}
unsigned int getInt(unsigned int imin, unsigned int imax) {
return uniformDistributionInt(randomEngine, std::uniform_int_distribution < unsigned int > {imin, imax}.param());
}
unsigned int getInt(unsigned int isize) {
return getInt(0, isize - 1);
}
double getDouble(double fmin, double fmax) {
return uniformDistributionDouble(randomEngine, std::uniform_real_distribution < double > {fmin, fmax}.param());
}
double getDouble() {
return getDouble(0.0, 1.0);
}
bool flipCoin() {
return (getDouble() < 0.5);
}
int sample(std::vector < double > & vec, double sum) {
double csum = vec[0];
double u = getDouble() * sum;
for (int i = 0; i < vec.size() - 1; ++i) {
if ( u < csum ) return i;
csum += vec[i+1];
}
return vec.size() - 1;
}
int sample4(const double * vec, double sum) {
double csum = vec[0];
double u = getDouble() * sum;
for (int i = 0; i < 3; ++i) {
if ( u < csum ) return i;
csum += vec[i+1];
}
return 3;
}
};
#endif
| 29.980198 | 146 | 0.676024 | [
"vector"
] |
d04ac4f01b93adc806c53c915360734ad0b0001f | 3,741 | h | C | json.h | bluszcz/libplurc | 330f447938db3f2e6eaf218b01fb14cb328dc484 | [
"BSD-3-Clause"
] | null | null | null | json.h | bluszcz/libplurc | 330f447938db3f2e6eaf218b01fb14cb328dc484 | [
"BSD-3-Clause"
] | null | null | null | json.h | bluszcz/libplurc | 330f447938db3f2e6eaf218b01fb14cb328dc484 | [
"BSD-3-Clause"
] | null | null | null | /*
* Json parser interface
*
* Copyright 2011 Guo-Fu Tseng <cooldavid@cooldavid.org>
*
* Author: Guo-Fu Tseng <cooldavid@cooldavid.org>
*
* 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.
*
* 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.
*
*/
struct json_value;
typedef struct json_array {
int size;
int asize;
int type;
struct json_value *values;
} JSON_ARRAY;
struct json_object;
typedef struct json_value {
union {
long long integer;
double floating;
char *string;
int boolean;
struct json_array *array;
struct json_object *object;
};
} JSON_VAL;
typedef struct json_key_val {
char *key;
int type;
JSON_VAL value;
} JSON_KV;
typedef struct json_hash_item {
const JSON_KV *kvptr;
struct json_hash_item *next;
} JSON_HASH;
#define KEY_HASH_SIZE 32
typedef struct json_object {
int kvnr; /* Key value pair number */
int akvnr; /* Allocated KV space number */
JSON_HASH keyhash[KEY_HASH_SIZE];
JSON_KV *kv;
} JSON_OBJ;
JSON_OBJ *json_create_obj(const char *str);
void json_free_obj(JSON_OBJ *jo);
void json_print_array(JSON_ARRAY *jo, int indent);
void json_print_obj(JSON_OBJ *jo, int indent);
int json_get_integer(const JSON_OBJ *jo, long long int *val, const char *key);
int json_get_floating(const JSON_OBJ *jo, double *val, const char *key);
int json_get_string(const JSON_OBJ *jo, const char **val, const char *key);
int json_get_boolean(const JSON_OBJ *jo, int *val, const char *key);
int json_get_array(const JSON_OBJ *jo, const JSON_ARRAY **val, const char *key);
int json_get_object(const JSON_OBJ *jo, const JSON_OBJ **val, const char *key);
int json_array_checktype(const JSON_ARRAY *ja, const char *typestr);
int json_array_get_val(const JSON_ARRAY *ja, void *val, int aidx);
#define quote(v) #v
#define dummy_assign(type, value_ptr) \
{ type dummy __attribute__((unused)) = value_ptr; }
#define _json_array_foreach(const_array_ptr, value_ptr, type, aidx) \
for (aidx = 0; \
json_array_checktype(const_array_ptr, quote(type)) && \
json_array_get_val(const_array_ptr, (void *)value_ptr, aidx); \
++aidx)
#define _json_array_foreach_typecheck(const_array_ptr, value_ptr, type, aidx) \
dummy_assign(json_##type##_type, value_ptr) \
_json_array_foreach(const_array_ptr, value_ptr, json_##type##_type, aidx)
#define json_integer_type long long int *
#define json_floating_type double *
#define json_string_type const char **
#define json_boolean_type int *
#define json_array_type const JSON_ARRAY **
#define json_object_type const JSON_OBJ **
#define json_array_foreach_integer(const_array_ptr, value_ptr, aidx) \
_json_array_foreach_typecheck(const_array_ptr, value_ptr, integer, aidx)
#define json_array_foreach_floating(const_array_ptr, value_ptr, aidx) \
_json_array_foreach_typecheck(const_array_ptr, value_ptr, floating, aidx)
#define json_array_foreach_string(const_array_ptr, value_ptr, aidx) \
_json_array_foreach_typecheck(const_array_ptr, value_ptr, string, aidx)
#define json_array_foreach_boolean(const_array_ptr, value_ptr, aidx) \
_json_array_foreach_typecheck(const_array_ptr, value_ptr, boolean, aidx)
#define json_array_foreach_array(const_array_ptr, value_ptr, aidx) \
_json_array_foreach_typecheck(const_array_ptr, value_ptr, array, aidx)
#define json_array_foreach_object(const_array_ptr, value_ptr, aidx) \
_json_array_foreach_typecheck(const_array_ptr, value_ptr, object, aidx)
| 36.676471 | 80 | 0.777332 | [
"object"
] |
d0621fb7e37468668e98aac452f19bd45b2bed18 | 29,542 | h | C | include/cyhal_adc.h | Infineon/mtb-hal-cat2 | ca889d1ecf349f3eb0549558569d1884619eb478 | [
"Apache-2.0"
] | 1 | 2021-05-28T11:30:26.000Z | 2021-05-28T11:30:26.000Z | include/cyhal_adc.h | Infineon/mtb-hal-cat2 | ca889d1ecf349f3eb0549558569d1884619eb478 | [
"Apache-2.0"
] | null | null | null | include/cyhal_adc.h | Infineon/mtb-hal-cat2 | ca889d1ecf349f3eb0549558569d1884619eb478 | [
"Apache-2.0"
] | 4 | 2020-12-14T23:36:18.000Z | 2021-06-21T11:53:04.000Z | /***************************************************************************//**
* \file cyhal_adc.h
*
* \brief
* Provides a high level interface for interacting with the Infineon Analog to
* Digital Converter. This interface abstracts out the chip specific details.
* If any chip specific functionality is necessary, or performance is critical
* the low level functions can be used directly.
*
********************************************************************************
* \copyright
* Copyright 2018-2021 Cypress Semiconductor Corporation (an Infineon company) or
* an affiliate of Cypress Semiconductor Corporation
*
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*******************************************************************************/
/**
* \addtogroup group_hal_adc ADC (Analog to Digital Converter)
* \ingroup group_hal
* \{
* High level interface for interacting with the analog to digital converter (ADC).
*
* \section cyhal_adc_features Features
* Each ADC instance supports one or more selectable channels, each
* of which can perform conversions on a different pin.
* See the device datasheet for details about which pins support ADC conversion.
*
* Both single-ended and differential channels are supported. The values returned
* by the read API are relative to the ADC's voltage range, which is device specific.
* See the BSP documentation for details.
*
* \section cyhal_adc_quickstart Quickstart
* Call \ref cyhal_adc_init to initialize an ADC instance by providing the ADC
* object (<b>obj</b>), input pin (<b>pin</b>) and clock (<b>clk</b>).<br> The input
* pin argument is just to signify which ADC instance to initialize. It does not
* actually reserve the pin or create an ADC channel for it. The clock parameter can
* be left NULL to use an available clock resource with a default frequency.<br>
* Use \ref cyhal_adc_channel_init_diff to initialize one or more channels associated
* with that instance.<br>
* Use \ref cyhal_adc_read for reading the results.<br>
* See \ref subsection_adc_snippet_1.
*
* \note \ref cyhal_adc_read_u16 always returns a 16 bit value in the range
* 0x0000-0xFFFF. If the underlying hardware does not support 16 bit resolution the
* value is scaled linearly to cover the full 16 bits.
*
* \section subsection_adc_snippets Code snippets
* \note Error checking is omitted for clarity
* \subsection subsection_adc_snippet_1 Snippet 1: Simple ADC initialization and reading conversion result
* The following snippet initializes an ADC and one channel.
* One ADC conversion result is returned corresponding to the input at the specified
* pin.
* \snippet hal_adc.c snippet_cyhal_adc_simple_init
*
* \subsection subsection_adc_snippet_2 Snippet 2: Multi-channel ADC initialization and reading conversion result
* The following snippet initializes an ADC with one single-ended channel and one differential channel
* \snippet hal_adc.c snippet_cyhal_adc_multi_init
*
* \subsection subsection_adc_snippet_3 Snippet 3: Asynchronously read multiple channels
* The following snippet illustrates how to asynchronously read multiple scans of multiple channels.
* \snippet hal_adc.c snippet_cyhal_adc_async_read
*
* \subsection subsection_adc_snippet_4 Snippet 4: Continuous scanning
* This snippet shows how to run the ADC in continuous mode and process results as each scan completes.
* \snippet hal_adc.c snippet_cyhal_adc_continuous_read
*/
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include "cy_result.h"
#include "cyhal_hw_types.h"
#include "cyhal_gpio.h"
#if defined(__cplusplus)
extern "C" {
#endif
/** \addtogroup group_hal_results_adc ADC HAL Results
* ADC specific return codes
* \ingroup group_hal_results
* \{ *//**
*/
/** Bad argument */
#define CYHAL_ADC_RSLT_BAD_ARGUMENT \
(CY_RSLT_CREATE_EX(CY_RSLT_TYPE_ERROR, CY_RSLT_MODULE_ABSTRACTION_HAL, CYHAL_RSLT_MODULE_ADC, 0))
/** Failed to initialize ADC clock */
#define CYHAL_ADC_RSLT_FAILED_CLOCK \
(CY_RSLT_CREATE_EX(CY_RSLT_TYPE_ERROR, CY_RSLT_MODULE_ABSTRACTION_HAL, CYHAL_RSLT_MODULE_ADC, 1))
/** Failed to initialize ADC */
#define CYHAL_ADC_RSLT_FAILED_INIT \
(CY_RSLT_CREATE_EX(CY_RSLT_TYPE_ERROR, CY_RSLT_MODULE_ABSTRACTION_HAL, CYHAL_RSLT_MODULE_ADC, 2))
/** No channels available */
#define CYHAL_ADC_RSLT_NO_CHANNELS \
(CY_RSLT_CREATE_EX(CY_RSLT_TYPE_ERROR, CY_RSLT_MODULE_ABSTRACTION_HAL, CYHAL_RSLT_MODULE_ADC, 3))
/**
* \}
*/
/** Number of bits populated with meaningful data by each ADC sample */
#define CYHAL_ADC_BITS 16
/** Maximum value that the ADC can return */
#define CYHAL_ADC_MAX_VALUE ((1 << CYHAL_ADC_BITS) - 1)
/** Possible selections for ADC reference */
typedef enum
{
CYHAL_ADC_REF_INTERNAL, //!< Internal reference. See the BSP documentation for the value of this reference. (Default)
CYHAL_ADC_REF_EXTERNAL, //!< Reference from external pin.
CYHAL_ADC_REF_VDDA, //!< Reference from VDDA (analog supply)
CYHAL_ADC_REF_VDDA_DIV_2, //!< Reference from VDDA (analog supply) divided by 2
} cyhal_adc_vref_t;
/** Vminus selection for single-ended channels */
typedef enum
{
CYHAL_ADC_VNEG_VSSA, //!< Connect vminus to ground.
CYHAL_ADC_VNEG_VREF, //!< Connect vminus to the selected vref (see @ref cyhal_adc_vref_t)
} cyhal_adc_vneg_t;
/** ADC events */
typedef enum
{
CYHAL_ADC_EOS = 1u, //!< End of scan: a scan of all channels has completed. Only applicable when continuously scanning
CYHAL_ADC_ASYNC_READ_COMPLETE = 2u, //!< An asynchronous read operation has completed.
} cyhal_adc_event_t;
/** Selections for ADC input signals */
typedef enum
{
CYHAL_ADC_INPUT_START_SCAN, // !< Start a scan when a signal is received
}
cyhal_adc_input_t;
/** Selections for ADC output signals */
typedef enum
{
CYHAL_ADC_OUTPUT_SCAN_COMPLETE, // !< An output signal should be triggered when a scan is complete
}
cyhal_adc_output_t;
/** Perform standard averaging. Divide the accumulated value by the number of samples.
* @note This is not supported in combination with @ref CYHAL_ADC_AVG_MODE_ACCUMULATE */
#define CYHAL_ADC_AVG_MODE_AVERAGE (1u << 0)
/** Accumulate samples as in @ref CYHAL_ADC_AVG_MODE_AVERAGE, but do not divide by the number of samples */
#define CYHAL_ADC_AVG_MODE_ACCUMULATE (1u << 1)
/** Average mode flag position indices shifted by greater than this are implementation specific. The value
* of this macro is subject to change between HAL versions. */
#define CYHAL_ADC_AVG_MODE_MAX_SHIFT (1u)
/** Selects the default connection for the inverting input to achieve a single-ended channel. This connection
* is controlled by the `vneg` member of @ref cyhal_adc_config_t.
*/
#define CYHAL_ADC_VNEG CYHAL_NC_PIN_VALUE
/** ADC Configuration */
typedef struct
{
/** Whether the ADC samples continuously (true) or only on demand (false).
*
* When configured to true, the ADC will immediately begin scanning all configured channels.
* When configured to false, the ADC will stop continuous scanning at the completion of the current scan
*/
bool continuous_scanning;
/** ADC resolution. See the implementation specific documentation for supported values */
uint8_t resolution;
/** The number of samples that should be averaged together to obtain a result. A value of 1 disables averaging. */
uint16_t average_count;
/** Flags to control the behavior of the averaging functionality when @ref average_count is greater than 1.
* This field contains zero or more flags that are OR'd together. All implementations define
* @ref CYHAL_ADC_AVG_MODE_AVERAGE and @ref CYHAL_ADC_AVG_MODE_ACCUMULATE (though some may not support both modes).
* Some implementations may define other flags to control additional aspects of the averaging functionality; see
* the implementation-specific documentation for details.
*/
uint32_t average_mode_flags;
/** The external voltage reference value, in millivolts.
* If vref is set to @ref CYHAL_ADC_REF_EXTERNAL, this must be nonzero.
* If vref is set to anything other than @ref CYHAL_ADC_REF_EXTERNAL, this must be zero.
*/
uint32_t ext_vref_mv;
/** Vminus selection for single-ended channels */
cyhal_adc_vneg_t vneg;
/** ADC voltage reference */
cyhal_adc_vref_t vref;
/** The GPIO that should be used for the external reference. If @ref CYHAL_ADC_REF_EXTERNAL
* is selected and the current target uses a GPIO for ADC ext_vref (see the BSP documentation),
* this must not be @ref NC. If the current target uses a dedicated pin (not a GPIO) for ADC ext_vref,
* or if any other reference is selected, this must be @ref NC.
*/
cyhal_gpio_t ext_vref;
/** Whether an external bypass capacitor should be used. Depending on the platform this may be required
* to reduce noise at sufficiently high sample rates. See the implementation specific documentation
* for details.
*/
bool is_bypassed;
/** The GPIO pin that should be used for the bypass capacitor. If `is_bypassed` is true and the current target
* uses a GPIO for the bypass capacitor connection, this must not be @ref NC. Otherwise, this must be @ref NC.
* Depending on the device, this may be the same GPIO as `ext_vref`. See the BSP documentation for details.
*/
cyhal_gpio_t bypass_pin;
} cyhal_adc_config_t;
/** ADC Channel Configuration */
typedef struct
{
/** Whether this channel should be sampled when the ADC performs a scan */
bool enabled;
/** Enable or disable averaging for this channel.
* All other aspects of the averging functionality are configured in @ref cyhal_adc_config_t
*/
bool enable_averaging;
/** Minimum time that this channel should be sampled, in nanoseconds. The actual time may be greater
* than this depending on hardware limitations, the sample rate, and the configuration of other channels.
* @note While this value is specified in ns, the underlying hardware generally does not support
* acquisition time with a granularity of 1 ns. See the implementation specific documentation for details.
*/
uint32_t min_acquisition_ns;
} cyhal_adc_channel_config_t;
/** Handler for ADC event callbacks */
typedef void (*cyhal_adc_event_callback_t)(void *callback_arg, cyhal_adc_event_t event);
/** Initialize ADC peripheral
*
* The ADC will be initialized with the following default configuration:
* - Sample rate: See implementation-specific documentation
* - Average count: 1 (averaging disabled).
* - Continuous scanning: false
* - Single ended vneg: @ref CYHAL_ADC_VNEG_VREF
* - Vref: @ref CYHAL_ADC_REF_INTERNAL
* - External vref: @ref NC
* - Bypassed: false
* - Bypass pin: @ref NC
* - Power level: @ref CYHAL_POWER_LEVEL_DEFAULT
*
* To change the configuration, see @ref cyhal_adc_configure
*
* @param[out] obj Pointer to an ADC object. The caller must allocate the memory
* for this object but the init function will initialize its contents.
* @param[in] pin A pin corresponding to the ADC block to initialize
* Note: This pin is not reserved, it is just used to identify which ADC block to allocate.
* If multiple channels will be allocated for a single ADC instance, only one pin should be
* passed here; it does not matter which one. After calling this function once, call
* @ref cyhal_adc_channel_init_diff once for each pin whose value should be measured.
* @param[in] clk The clock to use can be shared, if not provided a new clock will be allocated
* @return The status of the init request. \ref CY_RSLT_SUCCESS is returned on success.
* On failure, a problem specific error code will be returned.
* This error could be from the HAL or lower level driver.<br>
* For all other return codes, please refer to device driver documentation available in the BSP landing page
*/
cy_rslt_t cyhal_adc_init(cyhal_adc_t *obj, cyhal_gpio_t pin, const cyhal_clock_t *clk);
/** Initialize the ADC peripheral and its channels using a configurator generated configuration struct
*
* @param[out] adc Pointer to an adc object. The caller must allocate the memory
* for this object but the init function will initialize its contents.
* @param[out] channels Array of pointers to ADC channel objects. This array must contain
* a minimum of one (non-null) entry per channel that is enabled by the configurator
* @param[in,out] num_channels Length of the `channels` array. If this value is too small for all of the channels
* enabled by the configurator an error will be returned. Will be updated with the
* number of channels that were enabled by the configurator.
* @param[in] cfg Configuration structure generated by the configurator.
* @return The status of the init request
*/
cy_rslt_t cyhal_adc_init_cfg(cyhal_adc_t *adc, cyhal_adc_channel_t** channels, uint8_t* num_channels,
const cyhal_adc_configurator_t *cfg);
/** Uninitialize the ADC peripheral and cyhal_adc_t object
*
* @param[in,out] obj The ADC object
*/
void cyhal_adc_free(cyhal_adc_t *obj);
/** Update the ADC configuration.
*
* @note If a scan is in progress, this may cause it to be interrupted.
*
* @param[in] obj The ADC object
* @param[in] config The configuration to apply
* @return The status of the configuration request
* On failure, a problem specific error code will be returned.
* This error could be from the HAL or lower level driver.<br>
* For all other return codes, please refer to device driver documentation available in the BSP landing page
*/
cy_rslt_t cyhal_adc_configure(cyhal_adc_t *obj, const cyhal_adc_config_t *config);
/** Changes the current operating power level of the ADC.
*
* If the power level is set to @ref CYHAL_POWER_LEVEL_OFF, the ADC will be powered-off
* but it will retain its configuration, so it is not necessary to reconfigure it when changing
* the power level from @ref CYHAL_POWER_LEVEL_OFF to any other value.
*
* @param[in] obj ADC object
* @param[in] power The power level to set
* @return The status of the set power request
* On failure, a problem specific error code will be returned.
* This error could be from the HAL or lower level driver.<br>
* For all other return codes, please refer to device driver documentation available in the BSP landing page
*/
cy_rslt_t cyhal_adc_set_power(cyhal_adc_t *obj, cyhal_power_level_t power);
/** Configure the number of samples per second.
*
* This is the number of times each enabled channel is sampled per second. The total number of samples performed
* by the ADC hardware per second is equal to `sample_rate_hz / num_channels_enabled`.
* Depending on the system clock configuration or limitations of the underlying hardware, it may not be possible
* to achieve precisely the desired sample rate. The `achived_sample_rate_hz` parameter will be updated to indicate
* the sample rate that was achived.
* @note The `achieved_sample_rate_hz` value is only valid while the configuration of the ADC and its channels remains
* umodified. If @ref cyhal_adc_configure, @ref cyhal_adc_channel_init_diff, @ref cyhal_adc_channel_configure,
* or @ref cyhal_adc_channel_free is called, it is necessary to call this function again in order to update the sample rate.
* Therefore, it is recommended to call this function after the ADC and all channels have been configured.
*
* @param[in] obj The ADC object to configure
* @param[in] desired_sample_rate_hz The desired sample rate, in hertz
* @param[out] achieved_sample_rate_hz The achieved sample rate, in hertz
*
* @return The status of the sample rate request. Note that inability to exactly match the requested sample
* rate is not considered an error. It is the application's responsibility to determine whether the achived rate
* is within the tolerance that it requires.
* \ref CY_RSLT_SUCCESS is returned on success.<br>
* On failure, a problem specific error code will be returned. This error could be from the HAL or lower level driver.<br>
* For all other return codes, please refer to device driver documentation available in the BSP landing page
*/
cy_rslt_t cyhal_adc_set_sample_rate(cyhal_adc_t* obj, uint32_t desired_sample_rate_hz, uint32_t* achieved_sample_rate_hz);
/** Initialize a differential ADC channel.
* @note: Some platforms may restrict which pins can be used as part of a differential pair. See the
* implementation-specific documentation for details.
*
* Configures the pin used by ADC.
* @param[out] obj The ADC channel object to initialize
* @param[in] adc The ADC for which the channel should be initialized
* @param[in] vplus Non-inverting input
* @param[in] vminus Inverting input. For a single ended channel, use @ref CYHAL_ADC_VNEG.
* @param[in] cfg The ADC channel configuration
* @return The status of the init request.
* On failure, a problem specific error code will be returned.
* This error could be from the HAL or lower level driver.<br>
* For all other return codes, please refer to device driver documentation available in the BSP landing page
*/
cy_rslt_t cyhal_adc_channel_init_diff(cyhal_adc_channel_t *obj, cyhal_adc_t* adc, cyhal_gpio_t vplus, cyhal_gpio_t vminus, const cyhal_adc_channel_config_t* cfg);
/** Update the ADC channel configuration.
*
* @note If a scan is in progress, this may cause it to be interrupted. It is not valid to change the enabled state
* of a channel while an asynchronous read operation is in progress.
*
* @param[in] obj The ADC channel object
* @param[in] config The configuration to apply
* @return The status of the configuration request
* On failure, a problem specific error code will be returned.
* This error could be from the HAL or lower level driver.<br>
* For all other return codes, please refer to device driver documentation available in the BSP landing page
*/
cy_rslt_t cyhal_adc_channel_configure(cyhal_adc_channel_t *obj, const cyhal_adc_channel_config_t *config);
/** Uninitialize the ADC channel and cyhal_adc_channel_t object
*
* @param[in,out] obj The ADC channel object
*/
void cyhal_adc_channel_free(cyhal_adc_channel_t *obj);
/** Read the value from the ADC pin, represented as an unsigned 16bit value
* where 0x0000 represents the minimum value in the ADC's range, and 0xFFFF
* represents the maximum value in the ADC's range.
* If continous scanning is disabled, this will block while a conversion is
* performed on the selected channel, then return the result. Depending on the
* ADC speed this function may block for some time.
* If continuous scanning is enabled, this will return the value from the most
* recent conversion of the specified channel (if called shortly after enabling
* continuous scanning it may block until at least one conversion has been performed
* on this channel).
*
* @param[in] obj The ADC object
* @return An unsigned 16bit value representing the current input voltage
*/
uint16_t cyhal_adc_read_u16(const cyhal_adc_channel_t *obj);
/** Read the value from ADC pin, represented as a 32-bit signed, right-aligned value.
*
* This is a 'resolution'-bit value, sign-extended to 32 bits. If the vplus signal is
* below the vminus signal, the result will be negative. If the vplus signal is above
* the vminus signal, the result will be positive.
* If continous scanning is disabled, this will block while a conversion is
* performed on the selected channel, then return the result. Depending on the
* ADC speed this function may block for some time.
* If continuous scanning is enabled, this will return the value from the most
* recent conversion of the specified channel (if called shortly after enabling
* continuous scanning it may block until at least one conversion has been performed
* on this channel).
*
* @param[in] obj The ADC object
* @return A signed 32 bit value representing the current input voltage
*/
int32_t cyhal_adc_read(const cyhal_adc_channel_t *obj);
/** Read the value from ADC pin, in microvolts.
*
* If continous scanning is disabled, this will block while a conversion is
* performed on the selected channel, then return the result. Depending on the
* ADC speed this function may block for some time.
* If continuous scanning is enabled, this will return the value from the most
* recent conversion of the specified channel (if called shortly after enabling
* continuous scanning it may block until at least one conversion has been performed
* on this channel).
*
* @param[in] obj The ADC object
* @return An unsigned 32 bit value representing the current input in microvolts
*/
int32_t cyhal_adc_read_uv(const cyhal_adc_channel_t *obj);
/** Scan the specified ADC channels in the background and copy the results
* into the array pointed to by `result_list`.
*
* Results are represented as 32-bit signed, right-aligned values. That is, they are
* 'resolution'-bit values, sign-extended to 32 bits. If the vplus signal is
* below the vminus signal, the result will be negative. If the vplus signal is above
* the vminus signal, the result will be positive.
*
* If continuous scanning is disabled, this will trigger num_scan new scans and copy the results
* into `result_list` once the scan is completed.
*
* If continuous scanning is enabled, this will copy the results of num_scan scans into the result_list as
* they complete, beginning with the most recently completed scan (if one exists).
*
* Scan results are placed sequentially into result_list. That is, result_list will contain all of the results from the
* first scan, followed by all of the results from the second scan, etc. If channels exist that are initialized but not
* enabled, they will consume locations in result_list, but these values are undefined.
*
* When the requested number of scans have been completed, the @ref CYHAL_ADC_ASYNC_READ_COMPLETE event will be raised.
*
* @ref cyhal_adc_set_async_mode can be used to control whether this uses DMA or a SW (CPU-driven) transfer.
*
* @param[in] obj ADC to read from
* @param[in] num_scan The number of scans of each channel that should be read
* @param[in] result_list The array where results should be. This must be of length num_scan * initialized_channels,
* where initialized_channels is the number of channels that have been initialized for this ADC
* (and not later freed) via @ref cyhal_adc_channel_init_diff
* @return The status of the read async request
* On failure, a problem specific error code will be returned.
* This error could be from the HAL or lower level driver.<br>
* For all other return codes, please refer to device driver documentation available in the BSP landing page
*/
cy_rslt_t cyhal_adc_read_async(cyhal_adc_t* obj, size_t num_scan, int32_t* result_list);
/** Scan the specified ADC channels in the background and copy the conversion results in microvolts
* into the array pointed to by `result_list`.
*
* If continuous scanning is disabled, this will trigger num_scan new scans and copy the results
* into `result_list` once the scan is completed.
*
* If continuous scanning is enabled, this will copy the results of num_scan scans into the result_list as
* they complete, beginning with the most recently completed scan (if one exists).
*
* Scan results are placed sequentially into result_list. That is, result_list will contain all of the results from the
* first scan, followed by all of the results from the second scan, etc. If channels exist that are initialized but not
* enabled, they will consume locations in result_list, but these values are undefined.
*
* When the requested number of scans have been completed, the @ref CYHAL_ADC_ASYNC_READ_COMPLETE event will be raised.
*
* @ref cyhal_adc_set_async_mode can be used to control whether this uses DMA or a SW (CPU-driven) transfer.
*
* @param[in] obj ADC to read from
* @param[in] num_scan The number of scans of each channel that should be read
* @param[in] result_list The array where results should be. This must be of length num_scan * initialized_channels,
* where initialized_channels is the number of channels that have been initialized for this ADC
* (and not later freed) via @ref cyhal_adc_channel_init_diff
* @return The status of the read async request
* On failure, a problem specific error code will be returned.
* This error could be from the HAL or lower level driver.<br>
* For all other return codes, please refer to device driver documentation available in the BSP landing page
*/
cy_rslt_t cyhal_adc_read_async_uv(cyhal_adc_t* obj, size_t num_scan, int32_t* result_list);
/** Set the mechanism that is used to perform ADC asynchronous transfers. The default is SW.
* @warning The effect of calling this function while an async transfer is pending is undefined.
*
* @param[in] obj The ADC object
* @param[in] mode The transfer mode
* @param[in] dma_priority The priority, if DMA is used. Valid values are the same as for @ref cyhal_dma_init.
* If DMA is not selected, the only valid value is CYHAL_DMA_PRIORITY_DEFAULT, and no
guarantees are made about prioritization.
* @return The status of the set mode request
* On failure, a problem specific error code will be returned.
* This error could be from the HAL or lower level driver.<br>
* For all other return codes, please refer to device driver documentation available in the BSP landing page
*/
cy_rslt_t cyhal_adc_set_async_mode(cyhal_adc_t *obj, cyhal_async_mode_t mode, uint8_t dma_priority);
/** Register an ADC callback handler
*
* This function will be called when one of the events enabled by \ref cyhal_adc_enable_event occurs.
*
* @param[in] obj The ADC object
* @param[in] callback The callback handler which will be invoked when the interrupt fires
* @param[in] callback_arg Generic argument that will be provided to the callback when called
*/
void cyhal_adc_register_callback(cyhal_adc_t *obj, cyhal_adc_event_callback_t callback, void *callback_arg);
/** Configure ADC events.
*
* When an enabled event occurs, the function specified by \ref cyhal_adc_register_callback will be called.
*
* @param[in] obj The ADC object
* @param[in] event The ADC event type
* @param[in] intr_priority The priority for NVIC interrupt events
* @param[in] enable True to turn on specified events, False to turn off
*/
void cyhal_adc_enable_event(cyhal_adc_t *obj, cyhal_adc_event_t event, uint8_t intr_priority, bool enable);
/** Connects a source signal and enables the specified input
*
* @param[in] obj The ADC object
* @param[in] source Source signal obtained from another driver's cyhal_<PERIPH>_enable_output
* @param[in] input Which input signal to connect to
* @return The status of the connection
*/
cy_rslt_t cyhal_adc_connect_digital(cyhal_adc_t *obj, cyhal_source_t source, cyhal_adc_input_t input);
/** Enables the specified output signal
*
* @param[in] obj The ADC object
* @param[in] output Which output signal to enable
* @param[out] source Pointer to user-allocated source signal object
* which will be initialized by enable_output. \p source should be passed to
* (dis)connect_digital functions to (dis)connect the associated endpoints.
* @return The status of the output enable
*/
cy_rslt_t cyhal_adc_enable_output(cyhal_adc_t *obj, cyhal_adc_output_t output, cyhal_source_t *source);
/** Disconnect a source signal and disable ADC input
*
* @param[in] obj The ADC object
* @param[in] source Source signal from cyhal_<PERIPH>_enable_output to disable
* @param[in] input Which input signal to disconnect
* @return The status of the disconnect
*/
cy_rslt_t cyhal_adc_disconnect_digital(cyhal_adc_t *obj, cyhal_source_t source, cyhal_adc_input_t input);
/** Disables specified output signal from ADC.
*
* @param[in] obj The ADC object
* @param[in] output Which output signal to disable
* @return The status of the disablement
*/
cy_rslt_t cyhal_adc_disable_output(cyhal_adc_t *obj, cyhal_adc_output_t output);
#if defined(__cplusplus)
}
#endif
#ifdef CYHAL_ADC_IMPL_HEADER
#include CYHAL_ADC_IMPL_HEADER
#endif /* CYHAL_ADC_IMPL_HEADER */
/** \} group_hal_adc */
| 51.466899 | 162 | 0.736782 | [
"object"
] |
d06425857efb05e4c032ab968e3c6094f631ed9e | 866 | h | C | src/wvm/wasm-edge/include/po/subcommand.h | metabasenet/metabasenet | e9bc89b22c11981bcf1d71b63b9b66df3a4e54e1 | [
"MIT"
] | null | null | null | src/wvm/wasm-edge/include/po/subcommand.h | metabasenet/metabasenet | e9bc89b22c11981bcf1d71b63b9b66df3a4e54e1 | [
"MIT"
] | null | null | null | src/wvm/wasm-edge/include/po/subcommand.h | metabasenet/metabasenet | e9bc89b22c11981bcf1d71b63b9b66df3a4e54e1 | [
"MIT"
] | null | null | null | // SPDX-License-Identifier: Apache-2.0
//===-- ssvm/po/subcommand.h - SubCommand ---------------------------------===//
//
// Part of the SSVM Project.
//
//===----------------------------------------------------------------------===//
#pragma once
#include "po/helper.h"
#include <string_view>
#include <vector>
namespace SSVM {
namespace PO {
using namespace std::literals;
class SubCommand {
public:
SubCommand() = default;
template <typename... ArgsT>
SubCommand(Description &&D, ArgsT &&...Args)
: SubCommand(std::forward<ArgsT>(Args)...) {
Desc = std::move(D.Value);
}
std::string_view description() const noexcept { return Desc; }
void select() noexcept { Selected = true; }
bool is_selected() const noexcept { return Selected; }
private:
std::string_view Desc;
bool Selected = false;
};
} // namespace PO
} // namespace SSVM
| 24.055556 | 80 | 0.581986 | [
"vector"
] |
d06a1dddac450620f4a20cd22041755156ca13a2 | 5,484 | h | C | lite/backends/nnadapter/nnadapter/driver/mediatek_apu/converter.h | zhenlin-work/Paddle-Lite | 41f61bfce5eb57aef47dfe5cdc4123bb6d6918e1 | [
"Apache-2.0"
] | null | null | null | lite/backends/nnadapter/nnadapter/driver/mediatek_apu/converter.h | zhenlin-work/Paddle-Lite | 41f61bfce5eb57aef47dfe5cdc4123bb6d6918e1 | [
"Apache-2.0"
] | null | null | null | lite/backends/nnadapter/nnadapter/driver/mediatek_apu/converter.h | zhenlin-work/Paddle-Lite | 41f61bfce5eb57aef47dfe5cdc4123bb6d6918e1 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2019 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 <map>
#include <memory>
#include <string>
#include <vector>
#include "driver/mediatek_apu/utility.h"
namespace nnadapter {
namespace mediatek_apu {
const uint32_t INVALID_INDEX = 0xFFFFFFFF;
class Device {
public:
Device() {}
~Device() {}
};
class Context {
public:
explicit Context(void* device, const char* properties);
~Context();
private:
void* device_{nullptr};
void* context_{nullptr};
};
class Program {
public:
explicit Program(Context* context) : context_(context) {}
~Program();
int Build(hal::Model* model, hal::Cache* cache);
int Execute(uint32_t input_count,
hal::Argument* input_arguments,
uint32_t output_count,
hal::Argument* output_arguments);
private:
void Clear();
// Build from model or cache
int BuildFromModel(hal::Model* model);
int BuildFromCache(hal::Cache* cache);
// Operand converters
uint32_t GetMappedIndex(hal::Operand* operand);
uint32_t UpdateIndexMap(hal::Operand* operand, uint32_t index);
uint32_t AddOperand(int32_t* dimensions,
uint32_t dimension_count,
int precision,
float* quant_scales = nullptr,
int32_t* zero_point = nullptr,
uint32_t quant_scale_count = 0,
uint32_t quant_channel_dim = 0,
void* buffer = nullptr);
int AddOperation(NeuronOperationType type,
std::vector<uint32_t>* input_indexes,
std::vector<uint32_t>* output_indexes);
uint32_t AddBool8ConstantOperand(bool value);
uint32_t AddInt32ConstantOperand(int32_t value);
uint32_t AddFloat32ConstantOperand(float value);
uint32_t AddInt32ConstantOperand(int32_t* values, uint32_t num_values);
uint32_t AddFloat32ConstantOperand(float* values, uint32_t num_values);
uint32_t AddInt32ConstantOperand(int32_t* values,
int32_t* dimensions,
uint32_t dimension_count);
uint32_t AddFloat32ConstantOperand(float* values,
int32_t* dimensions,
uint32_t dimension_count);
// Quant8 constant operand with symmetric per-channel quantizion
uint32_t AddQuant8ConstantOperand(int8_t* values,
int32_t* dimensions,
uint32_t dimension_count,
float* quant_scales,
uint32_t quant_scale_count,
uint32_t quant_channel_dim = 0);
// Quant8 constant operand with asymmetric per-layer quantizion
uint32_t AddQuant8ConstantOperand(uint8_t* values,
int32_t* dimensions,
uint32_t dimension_count,
float quant_scale,
int32_t zero_point);
// Quant32 constant operand with symmetric per-layer quantizion
uint32_t AddQuant32ConstantOperand(int32_t* values,
int32_t* dimensions,
uint32_t dimension_count,
float quant_scale);
// Quant8 variable operand with asymmetric per-layer quantizion
uint32_t AddQuant8VariableOperand(int32_t* dimensions,
uint32_t dimension_count,
float quant_scale,
int32_t zero_point);
// Convert a constant and model input operand and map to a Neuron operand
// index
uint32_t ConvertOperand(hal::Operand* operand,
std::vector<int32_t> dimensions = {});
// Operation converters
int ConvertConv2D(hal::Operation* operation);
int ConvertFullyConnected(hal::Operation* operation);
int ConvertPool2D(hal::Operation* operation);
int ConvertElementwise(hal::Operation* operation);
int ConvertSoftmax(hal::Operation* operation);
int ConvertActivation(hal::Operation* operation);
int ConvertReshape(hal::Operation* operation);
int ConvertTranspose(hal::Operation* operation);
int ConvertConcat(hal::Operation* operation);
private:
Context* context_{nullptr};
// Map NNAdapter operand to Neuron operand index
std::map<hal::Operand*, std::vector<uint32_t>> operand_indexes_;
uint32_t operand_index_{0};
std::vector<void*> operand_buffers_;
NeuronModel* model_{nullptr};
NeuronCompilation* compilation_{nullptr};
NeuronExecution* execution_{nullptr};
std::vector<int32_t> input_zero_points_;
std::vector<int32_t> output_zero_points_;
std::string dump_graph_path_;
std::vector<uint8_t>* dump_graph_buffer_{nullptr};
};
} // namespace mediatek_apu
} // namespace nnadapter
| 38.619718 | 75 | 0.641138 | [
"vector",
"model"
] |
d06e3c64eabde9347062eafbb6cef111d0c997b7 | 441 | h | C | src/yars/physics/bullet/Robots.h | kzahedi/YARS | 48d9fe4178d699fba38114d3b299a228da41293d | [
"MIT"
] | 4 | 2017-08-05T03:33:21.000Z | 2021-11-08T09:15:42.000Z | src/yars/physics/bullet/Robots.h | kzahedi/YARS | 48d9fe4178d699fba38114d3b299a228da41293d | [
"MIT"
] | null | null | null | src/yars/physics/bullet/Robots.h | kzahedi/YARS | 48d9fe4178d699fba38114d3b299a228da41293d | [
"MIT"
] | 1 | 2019-03-24T08:35:25.000Z | 2019-03-24T08:35:25.000Z | #ifndef __ROBOTS_H__
#define __ROBOTS_H__
#include "Robot.h"
#include <vector>
using namespace std;
class Robots : public std::vector<Robot*>
{
public:
Robots();
~Robots();
void prePhysicsUpdate();
void postPhysicsUpdate();
void controllerUpdate();
void reset();
bool isReset();
bool isQuit();
int seed();
private:
bool _reset;
bool _quit;
int _seed;
};
#endif // __ROBOTS_H__
| 12.970588 | 41 | 0.628118 | [
"vector"
] |
d073eb0e81660fc15431157965752abe47963442 | 2,590 | h | C | gameplay/src/RenderTarget.h | ecameracci/GamePlay | 4de92c4c6f8047db5dcb7f0dee8541c7e7ea5a80 | [
"Apache-2.0",
"Unlicense"
] | 2,260 | 2015-01-03T06:53:25.000Z | 2020-05-09T21:55:21.000Z | gameplay/src/RenderTarget.h | ecameracci/GamePlay | 4de92c4c6f8047db5dcb7f0dee8541c7e7ea5a80 | [
"Apache-2.0",
"Unlicense"
] | 175 | 2015-01-03T15:35:44.000Z | 2019-10-26T11:54:58.000Z | gameplay/src/RenderTarget.h | ecameracci/GamePlay | 4de92c4c6f8047db5dcb7f0dee8541c7e7ea5a80 | [
"Apache-2.0",
"Unlicense"
] | 929 | 2015-01-01T04:53:21.000Z | 2020-05-06T21:41:12.000Z | #ifndef RENDERTARGET_H_
#define RENDERTARGET_H_
#include "Base.h"
#include "Texture.h"
namespace gameplay
{
/**
* Defines a linear area of display memory and usually resides
* in the display memory of the graphics device.
*/
class RenderTarget : public Ref
{
friend class FrameBuffer;
public:
/**
* Create a RenderTarget and add it to the list of available RenderTargets.
*
* The created RenderTarget contains a 32-bit texture with a single/base mipmap level only.
*
* @param id The ID of the new RenderTarget.
* @param width The width of the new RenderTarget.
* @param height The height of the new RenderTarget.
*
* @return A newly created RenderTarget.
* @script{create}
*/
static RenderTarget* create(const char* id, unsigned int width, unsigned int height, Texture::Format format = Texture::RGBA);
/**
* Create a RenderTarget from the given Texture and add it to the list of
* available RenderTargets.
*
* Note that different hardware and OpenGL versions have different capabilities
* and restrictions on what texture formats are supported as render targets.
*
* @param id The ID of the new RenderTarget.
* @param texture The texture for the new RenderTarget.
*
* @return A newly created RenderTarget.
* @script{create}
*/
static RenderTarget* create(const char* id, Texture* texture);
/**
* Get a named RenderTarget from its ID.
*
* @param id The ID of the RenderTarget to search for.
*
* @return The RenderTarget with the specified ID, or NULL if one was not found.
*/
static RenderTarget* getRenderTarget(const char* id);
/**
* Get the ID of this RenderTarget.
*
* @return The ID of this RenderTarget.
*/
const char* getId() const;
/**
* Get the backing texture of this RenderTarget.
*
* @return The backing texture of this RenderTarget.
*/
Texture* getTexture() const;
/**
* Returns the width of the RenderTarget.
*
* @return The width.
*/
unsigned int getWidth() const;
/**
* Returns the height of the RenderTarget.
*
* @return The height.
*/
unsigned int getHeight() const;
private:
/**
* Constructor.
*/
RenderTarget(const char* id);
/**
* Destructor.
*/
~RenderTarget();
/**
* Hidden copy assignment operator.
*/
RenderTarget& operator=(const RenderTarget&);
std::string _id;
Texture* _texture;
};
}
#endif
| 23.545455 | 129 | 0.632819 | [
"render"
] |
d0797b9d4c0db26c3e9a24c6545c2b287daa9e40 | 2,399 | h | C | include/Crypto/Commitment.h | corymonroe/GrinPlusPlus | bfdcbbcd65872f08270fc3084992eefea234b05e | [
"MIT"
] | null | null | null | include/Crypto/Commitment.h | corymonroe/GrinPlusPlus | bfdcbbcd65872f08270fc3084992eefea234b05e | [
"MIT"
] | null | null | null | include/Crypto/Commitment.h | corymonroe/GrinPlusPlus | bfdcbbcd65872f08270fc3084992eefea234b05e | [
"MIT"
] | null | null | null | #pragma once
// Copyright (c) 2018-2019 David Burkett
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
#include <Crypto/BigInteger.h>
#include <Common/Util/BitUtil.h>
#include <Core/Traits/Printable.h>
#include <Core/Serialization/ByteBuffer.h>
#include <Core/Serialization/Serializer.h>
class Commitment : public Traits::IPrintable
{
public:
//
// Constructors
//
Commitment() = default;
Commitment(CBigInteger<33>&& commitmentBytes)
: m_commitmentBytes(std::move(commitmentBytes))
{
}
Commitment(const CBigInteger<33>& commitmentBytes)
: m_commitmentBytes(commitmentBytes)
{
}
Commitment(const Commitment& other) = default;
Commitment(Commitment&& other) noexcept = default;
//
// Destructor
//
virtual ~Commitment() = default;
//
// Operators
//
Commitment& operator=(const Commitment& other) = default;
Commitment& operator=(Commitment&& other) noexcept = default;
inline bool operator<(const Commitment& rhs) const { return m_commitmentBytes < rhs.GetBytes(); }
inline bool operator!=(const Commitment& rhs) const { return m_commitmentBytes != rhs.GetBytes(); }
inline bool operator==(const Commitment& rhs) const { return m_commitmentBytes == rhs.GetBytes(); }
//
// Getters
//
inline const CBigInteger<33>& GetBytes() const { return m_commitmentBytes; }
inline const std::vector<unsigned char>& GetVec() const { return m_commitmentBytes.GetData(); }
inline const unsigned char* data() const { return m_commitmentBytes.data(); }
//
// Serialization/Deserialization
//
void Serialize(Serializer& serializer) const
{
serializer.AppendBigInteger<33>(m_commitmentBytes);
}
static Commitment Deserialize(ByteBuffer& byteBuffer)
{
return Commitment(byteBuffer.ReadBigInteger<33>());
}
std::string ToHex() const
{
return m_commitmentBytes.ToHex();
}
//
// Traits
//
virtual std::string Format() const override final { return m_commitmentBytes.Format(); }
private:
// The 33 byte commitment.
CBigInteger<33> m_commitmentBytes;
};
namespace std
{
template<>
struct hash<Commitment>
{
size_t operator()(const Commitment& commitment) const
{
const std::vector<unsigned char>& bytes = commitment.GetVec();
return BitUtil::ConvertToU64(bytes[0], bytes[4], bytes[8], bytes[12], bytes[16], bytes[20], bytes[24], bytes[28]);
}
};
} | 25.795699 | 117 | 0.726553 | [
"vector"
] |
d07a98e2ae9cfbcdbaf9f5699d725e3ae2a06882 | 42,035 | h | C | release/src-ra-4300/linux/linux-2.6.36.x/drivers/char/pcm/proslic_api/inc/vdaa.h | zhoutao0712/rtn11pb1 | 09e6b6c7ef4b91be0a9374daeacc3ac9f2fa3a05 | [
"Apache-2.0"
] | 1 | 2022-03-19T06:38:01.000Z | 2022-03-19T06:38:01.000Z | release/src-ra-4300/linux/linux-2.6.36.x/drivers/char/pcm/proslic_api/inc/vdaa.h | zhoutao0712/rtn11pb1 | 09e6b6c7ef4b91be0a9374daeacc3ac9f2fa3a05 | [
"Apache-2.0"
] | null | null | null | release/src-ra-4300/linux/linux-2.6.36.x/drivers/char/pcm/proslic_api/inc/vdaa.h | zhoutao0712/rtn11pb1 | 09e6b6c7ef4b91be0a9374daeacc3ac9f2fa3a05 | [
"Apache-2.0"
] | 1 | 2022-03-19T06:38:03.000Z | 2022-03-19T06:38:03.000Z | /*
** Copyright (c) 2008-2010 by Silicon Laboratories
**
** $Id: vdaa.h 3411 2012-04-04 23:11:51Z nizajerk $
**
** Vdaa.h
** Vdaa VoiceDAA interface header file
**
** Author(s):
** naqamar, laj
**
** Distributed by:
** Silicon Laboratories, Inc
**
** This file contains proprietary information.
** No dissemination allowed without prior written permission from
** Silicon Laboratories, Inc.
**
** File Description:
** This is the header file for the main VoiceDAA API and is used
** in the VoiceDAA demonstration code.
**
** Dependancies:
** Customer Drivers
**
*/
#ifndef VDAA_INTF_H
#define VDAA_INTF_H
#include "si_voice_datatypes.h"
#include "si_voice.h"
/*****************************************************************************/
/** @defgroup VDAA_API VDAA API
* This section covers APIs and definitions related to the VDAA/FXO.
* @{
*/
/*
** Constants
*/
#define BROADCAST 0xff
#define LCS_SCALE_NUM 33 /* Line Current Status Scale */
#define LCS_SCALE_DEN 10 /* Line Current Status Scale */
/*
**
** VDAA Initialization/Configuration Parameter Options
**
*/
/*
** This defines names for the PCM Data Format
*/
typedef enum {
A_LAW = 0, /**< 00 = A-Law. Signed magnitude data format */
U_LAW = 1, /**< 01 = u-Law. Signed magnitude data format */
LINEAR_16_BIT = 3 /**< 11 = 16-bit linear (2s complement data format) */
}tPcmFormat;
/*
** This defines names for the phcf bits
*/
typedef enum {
PCLK_1_PER_BIT = 0,
PCLK_2_PER_BIT = 1
}tPHCF;
/*
** This defines names for the tri bit
*/
typedef enum {
TRI_POS_EDGE = 0,
TRI_NEG_EDGE = 1
}tTRI;
/**
** This defines names for the AC impedance range
*/
typedef enum {
AC_600, /**< 600 Ohms */
AC_900, /**< 900 O */
AC_270__750_150, /**< 270 O + (750 O || 150 nF) and 275 O + (780 O || 150 nF) */
AC_220__820_120, /**< 220 O + (820 O || 120 nF) and 220 O + (820 O || 115 nF) */
AC_370__620_310, /**< 370 O + (620 O || 310 nF) */
AC_320__1050_230, /**< 320 O + (1050 O || 230 nF) */
AC_370__820_110, /**< 370 O + (820 O || 110 nF) */
AC_275__780_115, /**< 275 O + (780 O || 115 nF) */
AC_120__820_110, /**< 120 O + (820 O || 110 nF) */
AC_350__1000_210, /**< 350 O + (1000 O || 210 nF) */
AC_200__680_100, /**< 200 O + (680 O || 100 nF) */
AC_600__2160, /**< 600 O + 2.16 uF */
AC_900__1000, /**< 900 O + 1 uF */
AC_900__2160, /**< 900 O + 2.16 uF */
AC_600__1000, /**< 600 O + 1 uF */
AC_Global_impedance /**< Global impedance */
}tAC_Z;
/**
** This defines names for the DC impedance range
*/
typedef enum {
DC_50, /**< 50 Ohms dc termination is selected */
DC_800 /**< 800 Ohms dc termination is selected */
}tDC_Z;
/**
** This defines names for the ringer impedance range
*/
typedef enum {
RZ_MAX = 0,
RZ_SYNTH = 1
}tRZ;
/**
** This defines names for the dc voltage adjust
*/
typedef enum {
DCV3_1 = 0,
DCV3_2 = 1,
DCV3_35 = 2,
DCV3_5 = 3
}tDCV;
/**
** This defines names for the minimum loop current
*/
typedef enum {
MINI_10MA = 0,
MINI_12MA = 1,
MINI_14MA = 2,
MINI_16MA = 3
}tMINI;
/**
** This defines names for the current limiting enable bit
*/
typedef enum {
ILIM_DISABLED = 0,
ILIM_ENABLED = 1
}tILIM;
/**
** This defines names for the ring detect interupt mode
*/
typedef enum {
RDI_BEG_BURST = 0,
RDI_BEG_END_BURST = 1
}tRDI;
/**
** This defines names for the on hook speed / spark quenching
*/
typedef enum {
OHS_LESS_THAN_0_5MS = 0,
OHS_3MS = 1,
OHS_26MS = 0xE
}tOHS;
/**
** This defines names for the hbe bit
*/
typedef enum {
HYBRID_DISABLED = 0,
HYBRID_ENABLED = 1
}tHBE;
/**
** Gain/Attenuation Select
*/
typedef enum {
XGA_GAIN,
XGA_ATTEN
}tXGA;
/**
** MUTE Control Options
*/
typedef enum {
MUTE_DISABLE_ALL,
MUTE_DISABLE_RX,
MUTE_DISABLE_TX,
MUTE_ENABLE_RX,
MUTE_ENABLE_TX,
MUTE_ENABLE_ALL
}tMUTE;
/**
** This defines names for the ring delay setting
*/
typedef enum {
RDLY_0MS = 0,
RDLY_256MS = 1,
RDLY_512MS = 2,
RDLY_768MS = 3,
RDLY_1024MS = 4,
RDLY_1280MS = 5,
RDLY_1536MS = 6,
RDLY_1792MS = 7
}tRDLY;
/**
** This defines names for the ring timeouts
*/
typedef enum {
RTO_128MS = 1,
RTO_256MS = 2,
RTO_384MS = 3,
RTO_512MS = 4,
RTO_640MS = 5,
RTO_768MS = 6,
RTO_896MS = 7,
RTO_1024MS = 8,
RTO_1152MS = 9,
RTO_1280MS = 10,
RTO_1408MS = 11,
RTO_1536MS = 12,
RTO_1664MS = 13,
RTO_1792MS = 14,
RTO_1920MS = 15
}tRTO;
/**
** This defines names for the ring timeouts
*/
typedef enum {
RCC_100MS = 0,
RCC_150MS = 1,
RCC_200MS = 2,
RCC_256MS = 3,
RCC_384MS = 4,
RCC_512MS = 5,
RCC_640MS = 6,
RCC_1024MS = 7
}tRCC;
/**
** This defines names for the ring validation modes
*/
typedef enum {
RNGV_DISABLED = 0,
RNGV_ENABLED = 1
}tRNGV;
/**
** This defines names for the rfwe bit
*/
typedef enum {
RFWE_HALF_WAVE = 0,
RFWE_FULL_WAVE = 1,
RFWE_RNGV_RING_ENV = 0,
RFWE_RNGV_THRESH_CROSS = 1
}tRFWE;
/**
** This defines names for the rt and rt2 bit
*/
typedef enum {
RT__13_5VRMS_16_5VRMS = 0,
RT__19_35VRMS_23_65VRMS = 1,
RT__40_5VRMS_49_5VRMS = 3
}tRT;
/**
** This defines names for the rt and rt2 bit
*/
typedef enum {
RGDT_ACTIVE_LOW = 0,
RGDT_ACTIVE_HI = 1
}tRPOL;
/**
** This defines names for the interrupts
*/
typedef enum {
POLI,
TGDI,
LCSOI,
DODI,
BTDI,
FTDI,
ROVI,
RDTI,
CVI /**< Current/Voltage Interrupt REGISTER#44 */
}vdaaInt;
/**
** Interrupt Bitmask Fields
*/
typedef enum {
POLM = 1,
TGDM = 2, /**< Si3050 Only */
LCSOM = 4,
DODM = 8,
BTDM = 16,
FDTM = 32,
ROVM = 64,
RDTM = 128
}vdaaIntMask;
/**
** This defines names for the idl bit (obsolete)
*/
typedef enum {
IDL_DISABLED = 0,
IDL_ENABLED = 1
}tIDL;
/**
** This defines names for the ddl bit (obsolete)
*/
typedef enum {
DDL_NORMAL_OPERATION = 0,
DDL_PCM_LOOPBACK = 1
}tDDL;
/**
** Loopback Modes
*/
typedef enum {
LPBK_NONE = 0,
LPBK_IDL = 1,
LPBK_DDL = 2,
LPBK_PCML = 3
}tLpbkMode;
/**
** Loopback Status
*/
typedef enum {
LPBK_DISABLED = 0,
LPBK_ENABLED = 1
}tLpbkStatus;
/**
** This defines names for the interrupt pin modes
*/
typedef enum {
INTE_DISABLED = 0,
INTE_ENABLED = 1
}tInte;
/**
** This defines names for the interrupt pin polarities
*/
typedef enum {
INTE_ACTIVE_LOW = 0,
INTE_ACTIVE_HIGH = 1
}tIntePol;
/**
** This defines names for the pwm settings
*/
typedef enum {
PWM_DELTA_SIGMA = 0,
PWM_CONVENTIONAL_16KHZ = 1,
PWM_CONVENTIONAL_32KHZ = 2
}tPwmMode;
/**
** PWME
*/
typedef enum {
PWM_DISABLED = 0,
PWM_ENABLED
}tPWME;
/**
** RCALD control
*/
typedef enum {
RES_CAL_ENABLED = 0,
RES_CAL_DISABLED
}tRCALD;
/**
** Voice DAA Hook states
*/
enum {
VDAA_DIG_LOOPBACK = 1,
VDAA_ONHOOK = 2,
VDAA_OFFHOOK = 3,
VDAA_ONHOOK_MONITOR = 4
};
/**
** FDT Monitoring Options
*/
enum {
FDT_MONITOR_OFF = 0,
FDT_MONITOR_ON
};
/**
** Offhook Speed Select
*/
typedef enum {
FOH_512,
FOH_128,
FOH_64,
FOH_8
}tFOH;
/**
** Sample Rate Control
*/
typedef enum {
FS_8KHZ,
FS_16KHZ
}tHSSM;
/**
** Line Voltage Force Disable
*/
typedef enum {
LVS_FORCE_ENABLED = 0,
LVS_FORCE_DISABLED
}tLVFD;
/**
** Current/Voltage Monitor Select
*/
typedef enum {
CVS_CURRENT,
CVS_VOLTAGE
}tCVS;
/**
** Current/Voltage Interrupt Polarity
*/
typedef enum {
CVP_BELOW,
CVP_ABOVE
}tCVP;
/**
** Guarded Clear
*/
typedef enum {
GCE_DISABLED = 0,
GCE_ENABLED
}tGCE;
/**
** SPI Mode (Si3050 Only)
*/
typedef enum {
SPIM_TRI_CS,
SPIM_TRI_SCLK
}tSPIM;
/**
** FILT
*/
typedef enum {
FILT_HPF_5HZ,
FILT_HPF_200HZ
}tFILT;
/**
** IIRE
*/
typedef enum {
IIR_DISABLED = 0,
IIR_ENABLED
}tIIRE;
/**
** FULL2
*/
typedef enum {
FULL2_DISABLED = 0,
FULL2_ENABLED
}tFULL2;
/**
** FULL
*/
typedef enum {
FULL_DISABLED = 0,
FULL_ENABLED
}tFULL;
/**
** RG1
*/
typedef enum {
RG1_DISABLED = 0,
RG1_ENABLED
}tRG1;
/**
** -----------------------------
** CONFIGURATION DATA STRUCTURES
** -----------------------------
*/
/**
** (Updated) Structure for General Parameters
*/
typedef struct {
tInte inte; /* INTE */
tIntePol intp; /* INTP */
tRCALD rcald; /* RCALD */
tHSSM hssm; /* HSSM */
tFOH foh; /* FOH */
tLVFD lvfd; /* LVFD */
tCVS cvs; /* CVS */
tCVP cvp; /* CVP */
tGCE gce; /* GCE */
tIIRE iire; /* IIRE */
tFULL2 full2; /* FULL2 */
tFULL full; /* FULL */
tFILT filt; /* FILT */
tRG1 rg1; /* RG1 */
tPwmMode pwmm; /* PWMM Si3050 Only */
tPWME pwmEnable; /* PWME Si3050 Only */
tSPIM spim; /* SPIM Si3050 Only */
} vdaa_General_Cfg;
/**
** (NEW) Structure for Country Presets
*/
typedef struct {
tRZ rz;
tDC_Z dcr;
tAC_Z acim;
tDCV dcv;
tMINI mini;
tILIM ilim;
tOHS ohs_sq;
tHBE hbe;
} vdaa_Country_Cfg;
/**
** (NEW) Structure for Hybrid Presets
*/
typedef struct {
uInt8 hyb1;
uInt8 hyb2;
uInt8 hyb3;
uInt8 hyb4;
uInt8 hyb5;
uInt8 hyb6;
uInt8 hyb7;
uInt8 hyb8;
} vdaa_Hybrid_Cfg;
/**
** Structure for PCM configuration presets
*/
typedef struct {
tPcmFormat pcmFormat;
tPHCF pcmHwy;
tTRI pcm_tri;
} vdaa_PCM_Cfg;
/**
** Defines structure for configuring impedence
** @deprecated: Replace with separate vdaa_Country_Cfg preset
** for country-specific settings and vdaa_Hybrid_Cfg
** presets for hybrid coefficients since it is likely
** that multiple hybrid coefficient sets will be used
** tried during echo training.
*/
typedef struct {
tRZ rz;
tDC_Z dcr;
tAC_Z acim;
uInt8 hyb1;
uInt8 hyb2;
uInt8 hyb3;
uInt8 hyb4;
uInt8 hyb5;
uInt8 hyb6;
uInt8 hyb7;
uInt8 hyb8;
tDCV dcv;
tMINI mini;
tILIM ilim;
tOHS ohs_sq;
tHBE hbe;
} vdaa_Impedance_Cfg;
/** @addtogroup VDAA_AUDIO
* @{
*/
/** @addtogroup VDAA_GAIN_CONTROL
* @{
*/
/*
** (Updated) Structure for Audio path gain preset
*/
typedef struct {
uInt8 mute;
tXGA xga2;
uInt8 acgain2;
tXGA xga3;
uInt8 acgain3;
uInt8 callProgress;
BOOLEAN cpEn;
} vdaa_audioGain_Cfg;
/** @} VDAA_GAIN_CONTROL*/
/** @} */
/*
** Structure for configuring ring detect config
*/
typedef struct {
tRDLY rdly;
tRT rt;
uInt8 rmx;
tRTO rto;
tRCC rcc;
tRNGV rngv;
uInt8 ras;
tRFWE rfwe;
tRDI rdi;
tRPOL rpol;
} vdaa_Ring_Detect_Cfg;
/*
** Defines structure of interrupt data
*/
typedef struct {
vdaaInt *irqs;
uInt8 number;
} vdaaIntType;
/*
** Defines structure for configuring Loop Back
*/
typedef struct {
tIDL isoDigLB;
tDDL digDataLB;
} vdaa_Loopback_Cfg;
/*
** Generic Flag
*/
typedef enum {
VDAA_BIT_SET = 1,
VDAA_BIT_CLEAR = 0
} tVdaaBit;
/*
** Defines structure for daa current status (ring detect/hook stat)
*/
typedef struct {
tVdaaBit ringDetectedNeg;
tVdaaBit ringDetectedPos;
tVdaaBit ringDetected;
tVdaaBit offhook;
tVdaaBit onhookLineMonitor;
} vdaaRingDetectStatusType;
typedef SiVoiceControlInterfaceType vdaaControlInterfaceType;
typedef SiVoiceDeviceType vdaaDeviceType;
typedef SiVoiceChanType vdaaChanType;
/*
** This is the main VoiceDAA interface object pointer
*/
typedef vdaaChanType *vdaaChanType_ptr;
/*
** Defines initialization data structures
*/
typedef struct {
uInt8 address;
uInt8 initValue;
} vdaaRegInit;
typedef enum {
PAR_HANDSET_NOT_DETECTED = 0,
PAR_HANDSET_DETECTED = 1
}vdaaPHDStatus;
/*
** Line In Use Configuration Structure
*/
typedef struct {
vdaaPHDStatus status;
int8 min_onhook_vloop;
int8 min_offhook_vloop;
int16 min_offhook_iloop;
int8 measured_vloop;
int16 measured_iloop;
}vdaa_LIU_Config;
/*
** Function Declarations
*/
/*****************************************************************************/
/** @defgroup VDAA_IF_CONFIG VDAA System control interface functions
* This group of functions is called for allocating memory and configuring
* the ProSLIC API to call specific control interfaces that the user implemented.
* @deprecated One should use the SiVoice equivalent functions. @ref SIVOICE_IF_CFG
* @{
*/
/*****************************************************************************/
/** @defgroup VDAA_MEM Memory allocation/deallocation
* @deprecated One should use the SiVoice equivalent functions located: @ref SIVOICE_MEMORY_IF
* @{
*/
/**
@brief
* Allocate memory and initialize the given structure.
*
* @param[in,out] pCtrlIntf - the structure to initialize
*
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @deprecated Use @ref SiVoice_createControlInterface
*
*/
int Vdaa_createControlInterface (vdaaControlInterfaceType **pCtrlIntf);
/**
@brief
* Destroys the given structure and deallocates memory.
*
* @param[in,out] pCtrlIntf - the structure to destroy/deallocate
*
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @deprecated Use @ref SiVoice_destroyControlInterface
*
*/
int Vdaa_destroyControlInterface (vdaaControlInterfaceType **pCtrlIntf);
/**
* @brief
* Allocate memory and initialize the given structure.
*
* @param[in,out] **pDev - the structure to initialize
*
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @deprecated Use @ref SiVoice_createDevice
*/
int Vdaa_createDevice (vdaaDeviceType **pDev);
/**
* @brief
* Destroys the given structure and deallocates memory.
*
* @param[in,out] **pDev - the structure to initialize
*
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @deprecated Use @ref SiVoice_destroyDevice
*/
int Vdaa_destroyDevice (vdaaDeviceType **pDev);
/**
* @brief
* Allocate memory and initialize the given structure.
*
* @param[in,out] pVdaa - the structure to initialize
*
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @deprecated Use @ref SiVoice_createChannel
*/
int Vdaa_createChannel (vdaaChanType **pVdaa);
/**
* @brief
* Destroys the given structure and deallocates memory.
*
* @param[in,out] pVdaa - the structure to initialize
*
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @deprecated Use @ref Vdaa_destroyChannel
*/
int Vdaa_destroyChannel (vdaaChanType **pVdaa);
/** @} */
/*****************************************************************************/
/** @defgroup VDAA_IO SPI/GCI access routines
* This group of functions are used to associcate the transport mechanism (SPI, GCI) functions with the API. The actual
* functions being references are normally implemented by the customer for their particualr OS and platform.
*
* @deprecated One should use the SiVoice equivalent functions located: @ref SIVOICE_IO
* @{
*/
/**
* @brief
* Associate a interface object with a user supplied datastructure. This
* structure is passed to all the I/O routines that the ProSLIC API calls.
*
* @param[in,out] *pCtrlIntf - which interface to associate
* the user supplied structure with.
* @param[in] hCtrl - the user supplied structure.
*
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @deprecated Use SiVoice_setControlInterfaceCtrlObj
*/
int Vdaa_setControlInterfaceCtrlObj (vdaaControlInterfaceType *pCtrlIntf, void *hCtrl);
/**
* @brief
* Associate a interface object with the reset function.
*
* @param[in,out] pCtrlIntf - which interface to associate
* the user supplied function with.
* @param[in] Reset_fptr - the reset function pointer
*
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @deprecated Use @ref SiVoice_setControlInterfaceReset
*/
int Vdaa_setControlInterfaceReset (vdaaControlInterfaceType *pCtrlIntf, ctrl_Reset_fptr Reset_fptr);
/**
* @brief
* Associate a interface object with the register write function.
*
* @param[in,out] pCtrlIntf - which interface to associate
* the user supplied function with.
* @param[in] WriteRegister_fptr - the register write function pointer
*
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @deprecated Use @ref SiVoice_setControlInterfaceWriteRegister
*/
int Vdaa_setControlInterfaceWriteRegister (vdaaControlInterfaceType *pCtrlIntf, ctrl_WriteRegister_fptr WriteRegister_fptr);
/**
* @brief
* Associate a interface object with the register read function.
*
* @param[in,out] pCtrlIntf - which interface to associate
* the user supplied function with.
* @param[in] ReadRegister_fptr- the register read function pointer
*
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @deprecated Use @ref SiVoice_setControlInterfaceReadRegister
*/
int Vdaa_setControlInterfaceReadRegister (vdaaControlInterfaceType *pCtrlIntf, ctrl_ReadRegister_fptr ReadRegister_fptr);
/**
* @brief
* Associate a interface object with the write RAM function.
*
* @param[in,out] pCtrlIntf - which interface to associate
* the user supplied function with.
* @param[in] WriteRAM_fptr - the reset function pointer
*
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @deprecated Use @ref SiVoice_setControlInterfaceWriteRAM
*/
int Vdaa_setControlInterfaceWriteRAM (vdaaControlInterfaceType *pCtrlIntf, ctrl_WriteRAM_fptr WriteRAM_fptr);
/**
* @brief
* Associate a interface object with the read RAM function.
*
* @param[in,out] pCtrlIntf - which interface to associate
* the user supplied function with.
* @param[in] ReadRAM_fptr - the read RAM function pointer
*
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @deprecated Use SiVoice_setControlInterfaceReadRAM
*/
int Vdaa_setControlInterfaceReadRAM (vdaaControlInterfaceType *pCtrlIntf, ctrl_ReadRAM_fptr ReadRAM_fptr);
/** @} VDAA_IO */
/*****************************************************************************/
/** @defgroup VDAA_TIMER Timer functions
*
* This group of functions associates the customer supplied timer routines with the ProSLIC API.
*
* @deprecated One should use the SiVoice equivalent functions located: @ref SIVOICE_TIMER
* @{
*/
/**
* @brief
* This function associates a timer object - which is user defined, but it is
* used with ALL channels of the particular control interface.
*
* @param[in] pCtrlIntf - which control interface to associate the given timer object with.
* @param[in] hTimer - the timer ojbect that is passed to all timer functions.
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*
* @sa SIVOICE_TIMER Vdaa_setControlInterfaceDelay Vdaa_setControlInterfaceTimeElapsed Vdaa_setControlInterfaceGetTime
* @deprecated Use SiVoice_setControlInterfaceTimerObj
*/
int Vdaa_setControlInterfaceTimerObj (vdaaControlInterfaceType *pCtrlIntf, void *hTimer);
/**
* @brief
* Associate a timer delay function with a given control interface. The
* delay function takes in an argument of the timer object and the time in mSec
* and delays the thread/task for at least the time requested.
*
* @param[in] pCtrlIntf - which control interface to associate the function with.
* @param[in] Delay_fptr - the pointer to the delay function.
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*
* @sa SIVOICE_TIMER Vdaa_setControlInterfaceTimerObj Vdaa_setControlInterfaceTimeElapsed Vdaa_setControlInterfaceGetTime
* @deprecated Use @ref SiVoice_setControlInterfaceDelay
*/
int Vdaa_setControlInterfaceDelay (vdaaControlInterfaceType *pCtrlIntf, system_delay_fptr Delay_fptr);
/**
* @brief
* Associate a time elapsed function with a given control interface. The
* time elapsed function uses the values from the function specified in
* @ref SiVoice_setControlInterfaceGetTime and computes the delta time
* in mSec.
* @param[in] pCtrlIntf - which control interface to associate the function with.
* @param[in] timeElapsed_fptr - the pointer to the elapsed time function.
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @sa SIVOICE_TIMER Vdaa_setControlInterfaceTimerObj Vdaa_setControlInterfaceDelay Vdaa_setControlInterfaceGetTime
* @deprecated Use @ref SiVoice_setControlInterfaceTimeElapsed
*/
int Vdaa_setControlInterfaceTimeElapsed (vdaaControlInterfaceType *pCtrlIntf, system_timeElapsed_fptr timeElapsed_fptr);
/**
* @brief
* Associate a time get function with a given control interface. The
* time get function returns a value in a form of a void pointer that
* is suitable to be used with the function specified in @ref SiVoice_setControlInterfaceTimeElapsed .
* This is typically used as a timestamp of when an event started. The resolution needs to be in terms
* of mSec.
*
* @param[in] pCtrlIntf - which control interface to associate the function with.
* @param[in] getTime_fptr - the pointer to the get time function.
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @sa SIVOICE_TIMER Vdaa_setControlInterfaceTimerObj Vdaa_setControlInterfaceDelay Vdaa_setControlInterfaceTimeElapsed
* @deprecated Use @ref SiVoice_setControlInterfaceGetTime
*/
int Vdaa_setControlInterfaceGetTime (vdaaControlInterfaceType *pCtrlIntf, system_getTime_fptr getTime_fptr);
/** @} VDAA_TIMER */
/*****************************************************************************/
/** @defgroup VDAA_PROCESS VDAA Process control
* @{
*/
/**
* @brief
* This function assoicates a user defined semaphore/critical section
* function with the given interface.
*
* @param[in,out] pCtrlIntf - the interface to associate the function with.
* @param[in] semaphore_fptr - the function pointer for semaphore control.
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*
* @deprecated Use @ref SiVoice_setControlInterfaceSemaphore
*/
int Vdaa_setControlInterfaceSemaphore (vdaaControlInterfaceType *pCtrlIntf, ctrl_Semaphore_fptr semaphore_fptr);
/** @} */
/** @} VDAA_IF_CONFIG */
/*****************************************************************************/
/** @defgroup VDAA_DEBUG Debug
* * This group of functions enables/disables debug messages as well as dump
* register contents.
* @{
*/
/**
* @brief
* This function enables or disables the debug mode, assuming @ref ENABLE_DEBUG is set in the configuration file.
*
* @param[in] pVdaa - which channel to set the debug flag.
* @param[in] debugEn - 0 = Not set, 1 = set.
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @deprecated Use @ref SiVoice_setSWDebugMode
*
*/
int Vdaa_setSWDebugMode (vdaaChanType_ptr pVdaa, int32 debugEn);
/**
* @brief
* This function dumps to console the register contents of several
* registers and RAM locations.
*
* @param[in] pVdaa - which channel to dump the register contents of.
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*
*/
int Vdaa_PrintDebugData (vdaaChanType *pVdaa);
/** @} VDAA_DEBUG */
/*****************************************************************************/
/** @defgroup VDAA_ERROR Return code functions
* This group of functions are used for when the ProSLIC API function does
* not reutrn a standard error value and instead returns back some other value.
* You may call these functions to see if there was an error preset and to clear
* the error state.
* @{
*/
/**
* @brief
* This function returns the error flag that may be set by some function in where
* @ref errorCodeType is not returned.
*
* @note For functions that DO return errorCodeType, the return value here is undefined.
*
* @param[in] pVdaa - which channel to clear the error flag
* @param[in,out] error - The current value of error flag.
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @deprecated Use @ref SiVoice_getErrorFlag
*
* @sa ProSLIC_clearErrorFlag
*/
int Vdaa_getErrorFlag (vdaaChanType_ptr pVdaa, int *error);
/**
* @brief
* This function clears the error flag that may be set by some function in where
* @ref errorCodeType is not returned.
*
* @param[in,out] pVdaa - which channel to clear the error flag
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @deprecated Use @ref SiVoice_clearErrorFlag
*
* @sa ProSLIC_getErrorFlag
*/
int Vdaa_clearErrorFlag (vdaaChanType_ptr pVdaa);
/** @} VDAA_ERROR */
/*****************************************************************************/
/** @defgroup VDAA_AUDIO Audio
* @{
*/
/** @defgroup VDAA_GAIN_CONTROL Gain Control
* This section covers functions that allow one to adjust the audio
* gains - with TX toward the network/SOC/DSP and RX toward the tip/ring.
*
* @{
*/
/**
* @brief
* Sets the TX audio gain (toward the network).
*
* @param[in] pVdaa - which channel to configure
* @param[in] preset - which preset to use (this may be from the constants file)
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*/
int Vdaa_TXAudioGainSetup (vdaaChanType *pVdaa,int32 preset);
/**
* @brief
* Sets the RX audio gain (toward the tip/ring).
*
* @param[in] pVdaa - which channel to configure
* @param[in] preset - which preset to use (this may be from the constants file)
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*/
int Vdaa_RXAudioGainSetup (vdaaChanType *pVdaa,int32 preset);
/** @} VDAA_GAIN_CONTROL */
/*****************************************************************************/
/** @defgroup VDAA_AUDIO_CONTROL Audio control/configuration
* This group of functions is used to configure and control the PCM bus. It is essential that @ref Vdaa_PCMSetup,
* @ref Vdaa_PCMTimeSlotSetup and @ref Vdaa_PCMStart are called prior to any audio processing.
* @{
*/
/**
* @brief
* This configures the PCM bus with parameters such as companding and data latching timing.
*
* @param[in] pVdaa - which channel should be configured
* @param[in] preset - which preset to use from the constants file (see configuration tool, PCM dialog box)
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*
* @sa Vdaa_PCMTimeSlotSetup ProSLIC_PCMStart
*/
int Vdaa_PCMSetup (vdaaChanType *pVdaa,int32 preset);
/**
* @brief
* This configures the ProSLIC to latch and send the PCM data at a particular timeslot in terms of PCM clocks (PCLK).
*
* Typically, for aLaw and uLaw, one can use the following calculation to set the rxcount and txcount parameters:
*
* rxcount = txcount = (channel_number)*8;
*
* For 16 bit linear, one can do the following:
*
* rxcount = txcount = (channel_number)*16;
*
* where channel_number = which ProSLIC channel on the PCM bus. For example, if one were to have 2 dual channel
* VDAA's on the same PCM bus, this value would range from 0 to 3.
*
* @param[in] pVdaa - which channel should be configured
* @param[in] rxcount - how many clocks until reading data from the PCM bus
* @param[in] txcount - how many clocks until writing data to the PCM bus.
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*
* @sa Vdaa_PCMSetup Vdaa_PCMStart
*/
int Vdaa_PCMTimeSlotSetup (vdaaChanType *pVdaa, uInt16 rxcount, uInt16 txcount);
/**
* @brief
* This enables PCM transfer on the given ProSLIC channel.
*
* @param[in] pVdaa - - which channel should be enabled
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*
* @sa ProSLIC_PCMSetup ProSLIC_PCMTimeSlotSetup ProSLIC_PCMStop
*/
int Vdaa_PCMStart (vdaaChanType *pVdaa);
/**
* @brief
* This disables PCM transfer on the given VDAA channel. Typically, this is called for debugging
* purposes only.
*
* @param[in] pVdaa - - which channel should be disabled
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*
* @sa Vdaa_PCMSetup Vdaa_PCMTimeSlotSetup Vdaa_PCMStart
*/
int Vdaa_PCMStop (vdaaChanType *pVdaa);
/**
* @brief
* Program desired mute mode for the given channel.
*
* @param[in] pVdaa - which channel should be modified
* @param[in] mute - what is the desired mode.
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*
*/
int Vdaa_SetAudioMute(vdaaChanType *pVdaa, tMUTE mute);
/**
* @brief
* Program desired loopback test mode for the given channel.
*
* @param[in] pVdaa - which channel should be modified
* @param[in] lpbk_mode - what is the desired loopback mode.
* @param[in] lpbk_status - is this to enable or disable the loopback mode.
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @deprecated This API is depricated as of 5.2.0
* @sa Vdaa_LoopbackSetup
*
*/
int Vdaa_SetLoopbackMode(vdaaChanType_ptr pVdaa, tLpbkMode lpbk_mode, tLpbkStatus lpbk_status);
/**
* @brief
* Program desired loopback test mode for the given channel.
*
* @param[in] pVdaa - which channel should be modified
* @param[in] preset - which of the API configuration tool's preset to use.
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*
*/
int Vdaa_LoopbackSetup (vdaaChanType *pVdaa, int32 preset);
/*****************************************************************************/
/** @} VDAA_AUDIO */
/** @} */
/** @defgroup VDAA_RING Ring detection
* @{
*/
/**
* @brief This function configures ringing detect for the Vdaa.
* @param[in] pVdaa - which channel to program
* @param[in] preset - Index of predefined ring detect setup configuration
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*/
int Vdaa_RingDetectSetup (vdaaChanType *pVdaa,int32 preset);
/**
* @brief This function reads ring detect/hook status and populates the structure passed via pStatus.
* @param[in] pVdaa - Pointer to Voice DAA channel structure
* @param[out] pStatus - updated ring status.
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*/
int Vdaa_ReadRingDetectStatus (vdaaChanType *pVdaa,vdaaRingDetectStatusType *pStatus);
/** @} VDAA_RING */
/*****************************************************************************/
/** @defgroup VDAA_LINE_STATE Line state
* @{
*/
/**
* @brief This function sets the Voice DAA hook status
* @param[in] pVdaa - Pointer to Voice DAA channel structure
* @param[in] newHookStatus - new hook state (VDAA_ONHOOK, VDAA_OFFHOOK, VDAA_DIG_LOOPBACK or VDAA_ONHOOK_MONITOR)
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*/
int Vdaa_SetHookStatus (vdaaChanType *pVdaa,uInt8 newHookStatus);
/**
* @brief This function powers up the Voice DAA lineside device.
* @param[in] pVdaa - Pointer to Voice DAA channel structure
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*/
int Vdaa_PowerupLineside(vdaaChanType_ptr pVdaa);
/**
* @brief This function powers down the Voice DAA lineside device.
* @param[in] pVdaa - Pointer to Voice DAA channel structure
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*/
int Vdaa_PowerdownLineside(vdaaChanType_ptr pVdaa);
/**
* @brief Read VDAA Hook Status
* @param[in] pVdaa - which channel to return the hook status.
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*/
uInt8 Vdaa_GetHookStatus (vdaaChanType *pVdaa);
/** @} VDAA_LINE_STATE */
/*****************************************************************************/
/** @defgroup VDAA_DIAG Diagnostics
* @{
*/
/**
* @brief This function returns the Voice DAA linefeed status.
* @param[in] pVdaa - Pointer to Voice DAA channel structure
* @param[in,out] vloop - Pointer to loop voltage variable (set by this function) - in mV
* @param[in,out] iloop - Pointer to loop current variable (set by this function) - in uA
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*/
int Vdaa_ReadLinefeedStatus (vdaaChanType *pVdaa,int8 *vloop, int16 *iloop);
/**
* @brief This function initializes the vdaa_LIU_Config datastructure for line in use feature
* @param[in,out] liuCfg - Pointer to vdaa_LIU_Config structure (user allocates)
* @param[in] minOnV - minimum onhook loop voltage that indicates no parallel handset is present (mV)
* @param[in] minOffV - minimum offhook loop voltage that indicates no parallel handset is present (mV)
* @param[in] minOffI - minimum offhook loop current that indicates no parallel handset is preset (uA)
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @sa Vdaa_CheckForLineInUse
*/
int Vdaa_InitLineInUseCheck(vdaa_LIU_Config *liuCfg,int8 minOnV,int8 minOffV,int16 minOffI );
/**
* @brief Monitor LVCS to detect intrusion or parallel handset
* @param[in] pVdaa - Pointer to Voice DAA channel structure
* @param[in,out] liuCfg - Pointer to vdaa_LIU_Config structure
* @retval VDAA_ONHOOK or VDAA_OFFHOOK (in use)
* @sa Vdaa_InitLineInUseCheck
*/
uInt8 Vdaa_CheckForLineInUse(vdaaChanType *pVdaa, vdaa_LIU_Config *liuCfg);
/**
* @brief This function can be used to verify that the SPI interface is functioning properly.
* @param[in] pVdaa - Pointer to Voice DAA channel structure
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @deprecated Deprecated in 5.2.0
*/
int Vdaa_VerifyControlInterface (vdaaChanType *pVdaa);
/**
* @brief This function returns the status of the Frame Detect (FDT) bit.
* @param[in] pVdaa - Pointer to Voice DAA channel structure
* @retval int - 0 - Frame NOT detected, 1 = Frame detected
*/
int Vdaa_ReadFDTStatus(vdaaChanType_ptr pVdaa);
/** @} VDAA_DIAG */
/*****************************************************************************/
/** @defgroup VDAA_INTERRUPTS Interrupts
* @{
*/
/**
* @brief Enables ALL interrupts
* @param[in] pVdaa - Pointer to Voice DAA channel structure
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @deprecated Replaced by @ref Vdaa_SetInterruptMask
*/
int Vdaa_EnableInterrupts (vdaaChanType *pVdaa);
/**
* @brief Enables interrupts based on passed 9-bit bitmask. Bit values defined by vdaaIntMask enum.
* @param[in] pVdaa - Pointer to Voice DAA channel structure
* @param[in] bitmask - a logical or of @ref vdaaIntMask enum
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*/
int Vdaa_SetInterruptMask(vdaaChanType *pVdaa, vdaaIntMask bitmask);
/**
* @brief Returns the current interrupt status.
* @param[in] pVdaa - Pointer to Voice DAA channel structure
* @param[out] pIntData - interrupt mask showing which interrupts are set.
* @retval int - the number of interrupts set or RC_IGNORE
*/
int Vdaa_GetInterrupts (vdaaChanType *pVdaa,vdaaIntType *pIntData);
/**
* @brief Clears ALL interrupts
* @param[in] pVdaa - Pointer to Voice DAA channel structure
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*/
int Vdaa_ClearInterrupts (vdaaChanType *pVdaa);
/** @} VDAA_INTERRUPTS */
/*****************************************************************************/
/** @defgroup VDAA_INIT Initialization
* @{
*
* @defgroup VDAA_SOFT_INIT Software initialization
* @{
*/
/**
* @brief
* This function initializes the various channel structure elements.
* This function does not access the chipset directly, so SPI/GCI
* does not need to be up during this function call.
*
* It is suggested to migrate to the @ref SiVoice_SWInitChan in new
* implementations.
*
* @param[in,out] pVdaa - which channel to initialize.
* @param[in] channel - Which channel index is this. For example, for a 4 channel system, this would typically range from 0 to 3.
* @param[in] chipType - chipset family type for example @ref SI321X_TYPE or @ref SI3217X_TYPE
* @param[in] deviceObj - Device structure pointer associated with this channel
* @param[in] pCtrlIntf - Control interface associated with this channel
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @deprecated Use @ref SiVoice_SWInitChan
*/
int Vdaa_SWInitChan (vdaaChanType_ptr pVdaa,int32 channel,int chipType, SiVoiceDeviceType*deviceObj,SiVoiceControlInterfaceType *pCtrlIntf);
/**
* @brief
* This function sets the channel enable status. If NOT set, then when
* the various initialization routines such as @ref Vdaa_SWInitChan is called,
* then this particular channel will NOT be initialized.
*
* This function does not access the chipset directly, so SPI/GCI
* does not need to be up during this function call.
*
* @param[in,out] pVdaa - which channel to return the status.
* @param[in] chanEn - The new value of the channel enable field. 0 = NOT enabled, 1 = enabled.
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*
* @sa Vdaa_getChannelEnable SiVoice_SWInitChan
*/
int Vdaa_setChannelEnable (vdaaChanType_ptr pVdaa, int chanEn);
/**
* @brief
* This function returns back if the channel is enabled or not.
* This function does not access the chipset directly, so SPI/GCI
* does not need to be up during this function call.
*
* @param[in] pVdaa - which channel to return the status.
* @param[in,out] chanEn - The current value of if the channel is enabled. 0 = NOT enabled, 1 = enabled.
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*
* @sa Vdaa_setChannelEnable SiVoice_SWInitChan
*/
int Vdaa_getChannelEnable (vdaaChanType_ptr pVdaa, int* chanEn);
/** @} VDAA_SOFT_INIT */
/*****************************************************************************/
/** @defgroup VDAA_HW_INIT Hardware/line initialization
* @{
*/
/**
* @brief
* This function configures the Voice DAA with a predefined country configuration preset.
*
* @param[in] pVdaa - which channel to initialize
* @param[in] preset - The preset to use to configure the VDAA with.
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*
*/
int Vdaa_CountrySetup (vdaaChanType *pVdaa,int32 preset);
/**
* @brief
* This function configures the Voice DAA digital hybrid with a predefined preset.
*
* @param[in] pVdaa - which channel to initialize
* @param[in] preset - Index of predefined digital hybrid preset
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @sa Vdaa_SetHybridEnable
*/
int Vdaa_HybridSetup (vdaaChanType *pVdaa,int32 preset);
/**
* @brief
* This function sets the impedance coefficients of the Vdaa.
*
* @param[in] pVdaa - which channel to initialize
* @param[in] preset - Index of predefined digital hybrid preset
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*
*/
int Vdaa_ImpedanceSetup (vdaaChanType *pVdaa,int32 preset);
/**
* @brief
* This function fully initializes and loads the general config parameters to all Vdaa devices
* a given daisychain up to a given number.
*
* @param[in] pVdaa - which channel to initialize or start from if size>1
* @param[in] size - the number of channels to initialize, should be at least 1
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*
*/
int Vdaa_Init (vdaaChanType_ptr *pVdaa,int size);
/**
* @brief
* This function fully initializes and loads the general config parameters to all Vdaa devices on
* a given daisychain.
*
* @param[in] pVdaa - Vdaa channel
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*
*/
int Vdaa_InitBroadcast (vdaaChanType_ptr pVdaa);
/**
* @brief
* This function calibrates the ADC (analog to digital converter) of the Vdaa device(s).
*
* @param[in] pVdaa - which channel to calibrate or starting channel if size>1
* @param[in] size - the number of channels to calibrate.
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*
*/
int Vdaa_ADCCal (vdaaChanType_ptr pVdaa, int32 size);
/**
* @brief
* This function controls the Voice DAA digital hybrid.
*
* @param[in] pVdaa - which channel to set/unset
* @param[in] enable - TRUE: enable digital hybrid, FALSE: disable digital hybrid
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*
*/
int Vdaa_SetHybridEnable(vdaaChanType_ptr pVdaa, int enable);
/** @} VDAA_HW_INIT */
/*****************************************************************************/
/**
* @brief Execute a reset on a given channel/daisychain.
* @param[in] pVdaa - the channel to reset
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
* @deprecated Use @ref SiVoice_Reset
*/
int Vdaa_Reset (vdaaChanType *pVdaa);
/**
* @brief Enables watchdog timer
* @param[in] pVdaa - the channel to enable the watchdog
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*/
int Vdaa_EnableWatchdog(vdaaChanType_ptr pVdaa);
/**
* @brief Execute a soft reset on a given channel.
* @param[in] pVdaa - the channel to reset
* @retval int - error from @ref errorCodeType @ref RC_NONE indicates no error.
*/
int Vdaa_SoftReset(vdaaChanType_ptr pVdaa);/** @} VDAA_INIT */
/**
* @brief
* This function returns back a string with the current version of the
* ProSLIC API.
*
* @details
* The string is in the following format MM.mm.vv[.rcX] format, where
* MM is the major number, mm is the minor number and vv is the sub-minor number.
* If this is a release candidate, a .RCx is tacked on - such as RC1 for release
* candidate 1.
*
* @retval char * - returns back a constant string.
*/
char *Vdaa_Version(void);
/** @} MISC */
/** @} VDAA_API */
#endif
| 26.655041 | 140 | 0.682883 | [
"object"
] |
d083792462bcec1eae246d946d2baaa41ca906ea | 16,272 | h | C | shared/ebm_native/SegmentedTensor.h | mikewlange/interpret | cea351c9834fef437cb8853552fa1699fc24f527 | [
"MIT"
] | 1 | 2021-07-27T01:52:41.000Z | 2021-07-27T01:52:41.000Z | shared/ebm_native/SegmentedTensor.h | mikewlange/interpret | cea351c9834fef437cb8853552fa1699fc24f527 | [
"MIT"
] | null | null | null | shared/ebm_native/SegmentedTensor.h | mikewlange/interpret | cea351c9834fef437cb8853552fa1699fc24f527 | [
"MIT"
] | null | null | null | // Copyright (c) 2018 Microsoft Corporation
// Licensed under the MIT license.
// Author: Paul Koch <code@koch.ninja>
#ifndef SEGMENTED_TENSOR_H
#define SEGMENTED_TENSOR_H
#include <type_traits> // std::is_standard_layout
#include <stdlib.h> // malloc, realloc, free
#include <stddef.h> // size_t, ptrdiff_t
#include <string.h> // memcpy
#include "EbmInternal.h" // INLINE_ALWAYS
#include "Logging.h" // EBM_ASSERT & LOG
// TODO: we need to radically change this data structure so that we can efficiently pass it between machines in a cluster AND within/between a GPU/CPU
// This stucture should be:
// EXTERIOR_STRUCTURE -> our external pointers point to here
// offset_to_start_of_real_data (which is the offset_to_MAIN_DATA_STRUCTURE_in_big_endian_format)
// size_of_real_data (from offset_to_MAIN_DATA_STRUCTURE_in_big_endian_format to the last valid value)
// EMPTY_SPACE_FOR_DIMENSIONS_TO_GROW_INTO
// offset_to_MAIN_DATA_STRUCTURE_in_big_endian_format -> our external caller can reduce our memory size to this point optinally to pass between memory
// boundaries
// DIMENSION_0_COUNT (this is the current # of cuts, not the maximum, which we store elsewhere and pass into our class for processing)
// DIMENSION_0_CUT_POINTS
// DIMENSION_1_COUNT (this is the current # of cuts, not the maximum, which we store elsewhere and pass into our class for processing)
// DIMENSION_1_CUT_POINTS
// MAIN_DATA_STRUCTURE -> our internal pointsers point to here
// offset_to_DIMENSION_0_COUNT_or_zero_if_value_array_expanded_and_zero_offset_to_MAIN_DATA_STRUCTURE (we can find all the dimensions from this one offset)
// count_dimensions
// offset_to_external_structure
// is_little_endian_bool_in_big_endian_format (little endian vs big endian)
// all_other_data_that_does_not_resize
// VALUES_ARRAY_FLAT_EXPANDABLE (we've preallocated enough room for this, but we don't always need it)
// EMPTY_SPACE_FOR_VALUES_TO_GROW_INTO
// Reasons:
// - our super-parallel algrithm needs to split up the data and have separate processing cores process their data
// their outputs will be partial histograms. After a single cores does the tree buiding, that core will need to push the model updates to all the
// children nodes
// - in an MPI environment, or a Spark cluster, or in a GPU, we'll need to pass this data structure between nodes, so it will need to be memcopy-able,
// which means no pointers (use 64-bit offsets), and it means that the data needs to be in a single contiguous byte array
// - we might want our external caller to allocate this memory, because perhaps we might want the MPI communication layer or other network protocol to sit
// outside of C++,
// so we want to allocate the memory just once and we need to be able to determine the memory size before allocating it.
// we know ahead of time how many dimensions AND the maximum split points in all dimensions, so it's possible to pre-determine this
// - we use an easy/compatible external structure at the top that our caller can read without knowing our deep internals, but it provides enough
// information for our external caller to identify the core inner data that they can memcopy to annother memory address space
// - so, our external caller has a non-changing memory location that indicates the internal offset where they can start copying data from and a number of
// bytes to copy when they want to pass this memory to annother memory boundary. This essentially strips the useless non-used space away for compression
// - if the caller needs to be allocated on some kind of top boundary, they can optionally start from the top and just add the
// offset_to_start_of_real_data and size_of_real_data together to get the size they need to copy from the top. This will include a little
// empty data at the top, but the empty dimension data is usually much less than the value data for interaction models, and the dimension data should
// almost always be pretty small, so this isn't a problem.
// - once we recieve the interor data structure we can read offset_to_MAIN_DATA_STRUCTURE_in_big_endian_format, which will be in a machine
// independent endian format (big endian), and we can then find our MAIN_DATA_STRUCTURE from there, and from MAIN_DATA_STRUCTURE we can reconstruct
// our original memory size with empty space if we want, optionally
// - the caller can pass us a pointer to the exterior data, and we can then find the offset_to_MAIN_DATA_STRUCTURE_in_big_endian_format from the header
// then we can find our MAIN_DATA_STRUCTURE from there
// - when we expand our tensor, we need to keep the dimension data constant and then we expand the values efficiently
// (starting by moving the last value to where it's eventually going to go). After we've expanded the values, we can expand the dimensions upwards
// by first moving the 0th dimension where it will ultimately end up, then processing each dimension in order
// - if we have dimension 0 at the top, and cut points heading downwards, we'll be reading the data forwards as we process it, which efficiently
// loads it into the cache
// - we don't need to update offset_to_MAIN_DATA_STRUCTURE_in_big_endian_format or the values in the EXTERIOR_STRUCTURE until we return from C++,
// so let it get out of date while we process things internally
// - if the tensor is purely for internal consumption, we don't even need to allocate the EXTERIOR_STRUCTURE and
// offset_to_MAIN_DATA_STRUCTURE_in_big_endian_format,
// so our allocator should have a flag to indicate if these are required or not
// - the maximum number of cuts is part of the feature_group definition, so we don't need to store that and pass that reduntant information arround
// We do store the current number of cuts because that changes. This data structure should therefore have a dependency on the
// feature_group definition since we'll need to read the maximum number of cuts. The pointer to the feature_group class can be passed
// in via the stack to any function that needs that information
// - use 64 bit values for all offsets, since nobody will ever need more than 64 bits
// (you need a non-trivial amount of mass even if you store one bit per atom) and
// we might pass these between 64 and 32 bit processes, but a few 64 bit offsets won't be a problem even for a 32-bit process.
// - EXPANDING:
// - eventually all our tensors will be expanded when doing the model update, because we want to use array lookups instead of binary search when
// applying the model (array lookup is a huge speed boost over binary search)
// - our current and best models start out expanded since we want an easy way to communicate with our caller, and we eventualy expect almost all the
// cuts to be used anyways
// - we might as well also flip to epanded mode whenever all dimensions are fully expanded, even when we think we have a compressed model.
// For things like bools or low numbers of cuts this could be frequent, and the non-compressed model is actually smaller when all dimensions have
// been expanded
// - once we've been expanded, we no longer need the cut points since the cut points are just incrementing integers.
// The maximum number of cuts is stored outside of the data structure already because that's common between all machines/GPUs,
// so we don't need to pass that redundant information arround, so offset_to_start_of_real_data can point directly to
// MAIN_DATA_STRUCTURE directly (which is most optimial for compression)
// - IMPORTANT: if we've been expanded AND offset_to_start_of_real_data points directly to MAIN_DATA_STRUCTURE, then if the external caller
// reduces the data to just the interior used bytes, we still need a way to get to the MAIN_DATA_STRUCTURE. If we use
// offset_to_DIMENSION_0_COUNT_or_zero_if_value_array_expanded_and_zero_offset_to_MAIN_DATA_STRUCTURE to indicate expansion with a zero value then
// we can also use it for the tripple use as the offset_to_MAIN_DATA_STRUCTURE_in_big_endian_format value. Our caller will
// see a zero in what it expects is the offset_to_MAIN_DATA_STRUCTURE_in_big_endian_format, and then it can find MAIN_DATA_STRUCTURE the same
// way it would normally by adding the zero to the address it has. The nice thing is that zero is both big_endian and also little_endian, so it
// works for both.
// - the top item in our MAIN_DATA_STRUCTURE MUST be offset_to_DIMENSION_0_COUNT_or_zero_if_value_array_expanded_and_zero_offset_to_MAIN_DATA_STRUCTURE for
// our efficient tripple use above!
// TODO : put some of this file into .cpp since some of the functions are repeated and they don't need to all be inline!
class SegmentedTensor final {
struct DimensionInfoStack final {
DimensionInfoStack() = default; // preserve our POD status
~DimensionInfoStack() = default; // preserve our POD status
void * operator new(std::size_t) = delete; // we only use malloc/free in this library
void operator delete (void *) = delete; // we only use malloc/free in this library
const ActiveDataType * m_pDivision1;
const ActiveDataType * m_pDivision2;
size_t m_cNewDivisions;
};
static_assert(std::is_standard_layout<DimensionInfoStack>::value,
"We use the struct hack in several places, so disallow non-standard_layout types in general");
static_assert(std::is_trivial<DimensionInfoStack>::value,
"We use memcpy in several places, so disallow non-trivial types in general");
static_assert(std::is_pod<DimensionInfoStack>::value,
"We use a lot of C constructs, so disallow non-POD types in general");
struct DimensionInfoStackExpand final {
DimensionInfoStackExpand() = default; // preserve our POD status
~DimensionInfoStackExpand() = default; // preserve our POD status
void * operator new(std::size_t) = delete; // we only use malloc/free in this library
void operator delete (void *) = delete; // we only use malloc/free in this library
const ActiveDataType * m_pDivision1;
size_t m_iDivision2;
size_t m_cNewDivisions;
};
static_assert(std::is_standard_layout<DimensionInfoStackExpand>::value,
"We use the struct hack in several places, so disallow non-standard_layout types in general");
static_assert(std::is_trivial<DimensionInfoStackExpand>::value,
"We use memcpy in several places, so disallow non-trivial types in general");
static_assert(std::is_pod<DimensionInfoStackExpand>::value,
"We use a lot of C constructs, so disallow non-POD types in general");
struct DimensionInfo final {
DimensionInfo() = default; // preserve our POD status
~DimensionInfo() = default; // preserve our POD status
void * operator new(std::size_t) = delete; // we only use malloc/free in this library
void operator delete (void *) = delete; // we only use malloc/free in this library
size_t m_cDivisions;
ActiveDataType * m_aDivisions;
size_t m_cDivisionCapacity;
};
static_assert(std::is_standard_layout<DimensionInfo>::value,
"We use the struct hack in several places, so disallow non-standard_layout types in general");
static_assert(std::is_trivial<DimensionInfo>::value,
"We use memcpy in several places, so disallow non-trivial types in general");
static_assert(std::is_pod<DimensionInfo>::value,
"We use a lot of C constructs, so disallow non-POD types in general");
// TODO : is this still required after we do tree splitting by pairs??
// we always allocate our array because we don't want to Require Add(...) to check for the null pointer
// always allocate one so that we never have to check if we have sufficient storage when we call Reset with one division and two values
static constexpr size_t k_initialDivisionCapacity = 1;
static constexpr size_t k_initialValueCapacity = 2;
size_t m_cValueCapacity;
size_t m_cVectorLength;
size_t m_cDimensionsMax;
size_t m_cDimensions;
FloatEbmType * m_aValues;
bool m_bExpanded;
// use the "struct hack" since Flexible array member method is not available in C++
// m_aDimensions must be the last item in this struct
// AND this class must be "is_standard_layout" since otherwise we can't guarantee that this item is placed at the bottom
// standard layout classes have some additional odd restrictions like all the member data must be in a single class
// (either the parent or child) if the class is derrived
DimensionInfo m_aDimensions[1];
INLINE_ALWAYS const DimensionInfo * GetDimensions() const {
return ArrayToPointer(m_aDimensions);
}
INLINE_ALWAYS DimensionInfo * GetDimensions() {
return ArrayToPointer(m_aDimensions);
}
public:
SegmentedTensor() = default; // preserve our POD status
~SegmentedTensor() = default; // preserve our POD status
void * operator new(std::size_t) = delete; // we only use malloc/free in this library
void operator delete (void *) = delete; // we only use malloc/free in this library
// TODO: In the future we'll be splitting our work into small sets of residuals and logits owned by
// a node in a distributed system. After each node calculates it's model update (represented by this
// SegmentedTensor class), we'll need to reduce them accross all nodes, before adding together all the
// SegmentedTensor classes and sending back a full update to the Nodes. Since we'll be ferrying info
// back and forth, we'll want to keep it in a more compressed format keeping division and not expanding
// to a direct indexable tensor until after recieved by the nodes. We'll NEED to keep the entire strucutre
// as a single continuous chunk of memory. At the very start will be our regular struct (containing the
// full size of the data region at the top (64 bit since we don't know what processor we'll be on)
// We know the number of dimensions for an feature group at allocation, so we can put the values right below
// that. When we find ourselves expanding dimensions, we can first figure out how much all the values and dimension
// need to grow and then we can directly move each dimension pointed to object without needing to move the full
// values array.
static void Free(SegmentedTensor * const pSegmentedRegion);
static SegmentedTensor * Allocate(const size_t cDimensionsMax, const size_t cVectorLength);
void Reset();
bool SetCountDivisions(const size_t iDimension, const size_t cDivisions);
bool EnsureValueCapacity(const size_t cValues);
bool Copy(const SegmentedTensor & rhs);
bool MultiplyAndCheckForIssues(const FloatEbmType v);
bool Expand(const size_t * const acValuesPerDimension);
void AddExpandedWithBadValueProtection(const FloatEbmType * const aFromValues);
bool Add(const SegmentedTensor & rhs);
#ifndef NDEBUG
bool IsEqual(const SegmentedTensor & rhs) const;
#endif // NDEBUG
INLINE_ALWAYS void SetExpanded() {
m_bExpanded = true;
}
INLINE_ALWAYS bool GetExpanded() {
return m_bExpanded;
}
INLINE_ALWAYS FloatEbmType * GetValues() {
return m_aValues;
}
INLINE_ALWAYS void SetCountDimensions(const size_t cDimensions) {
EBM_ASSERT(cDimensions <= m_cDimensionsMax);
m_cDimensions = cDimensions;
}
INLINE_ALWAYS ActiveDataType * GetDivisionPointer(const size_t iDimension) {
EBM_ASSERT(iDimension < m_cDimensions);
return GetDimensions()[iDimension].m_aDivisions;
}
INLINE_ALWAYS FloatEbmType * GetValuePointer() {
return &m_aValues[0];
}
};
static_assert(std::is_standard_layout<SegmentedTensor>::value,
"We use the struct hack in several places, so disallow non-standard_layout types in general");
static_assert(std::is_trivial<SegmentedTensor>::value,
"We use memcpy in several places, so disallow non-trivial types in general");
static_assert(std::is_pod<SegmentedTensor>::value,
"We use a lot of C constructs, so disallow non-POD types in general");
#endif // SEGMENTED_TENSOR_H
| 66.146341 | 159 | 0.754179 | [
"object",
"model"
] |
d0856395e90ff3985a06c6251c19523be31021a6 | 13,318 | c | C | source-pc/CcspCwmpTcpConnReqHandler/ccsp_cwmp_tcpcrho_operation.c | anis-semmar/ccsp-tr069-pa | 3d0a8faf5339b6dacdcd7ad8869491fb8486126f | [
"Apache-2.0"
] | null | null | null | source-pc/CcspCwmpTcpConnReqHandler/ccsp_cwmp_tcpcrho_operation.c | anis-semmar/ccsp-tr069-pa | 3d0a8faf5339b6dacdcd7ad8869491fb8486126f | [
"Apache-2.0"
] | null | null | null | source-pc/CcspCwmpTcpConnReqHandler/ccsp_cwmp_tcpcrho_operation.c | anis-semmar/ccsp-tr069-pa | 3d0a8faf5339b6dacdcd7ad8869491fb8486126f | [
"Apache-2.0"
] | null | null | null | /*
* If not stated otherwise in this file or this component's Licenses.txt file the
* following copyright and licenses apply:
*
* Copyright 2015 RDK Management
*
* 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 [2014] [Cisco Systems, 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.
**********************************************************************/
/**********************************************************************
module: ccsp_cwmp_tcpcrho_operation.c
For CCSP CWMP protocol implementation
---------------------------------------------------------------
description:
This module implements the advanced operation functions
of CCSP CWMP TCP Connection Request Handler Object.
* CcspCwmpTcpcrhoEngage
* CcspCwmpTcpcrhoCancel
* CcspCwmpTcpcrhoCreateTcpServers
* CcspCwmpTcpcrhoRemoveTcpServers
* CcspCwmpTcpcrhoWorkerInit
* CcspCwmpTcpcrhoWorkerUnload
---------------------------------------------------------------
environment:
platform independent
---------------------------------------------------------------
author:
Kang Quan
---------------------------------------------------------------
revision:
08/19/08 initial revision.
**********************************************************************/
#include "ccsp_cwmp_tcpcrho_global.h"
/**********************************************************************
caller: owner of this object
prototype:
ANSC_STATUS
CcspCwmpTcpcrhoEngage
(
ANSC_HANDLE hThisObject
);
description:
This function is called to engage this object.
argument: ANSC_HANDLE hThisObject
This handle is actually the pointer of this object
itself.
return: status of operation.
**********************************************************************/
ANSC_STATUS
CcspCwmpTcpcrhoEngage
(
ANSC_HANDLE hThisObject
)
{
ANSC_STATUS returnStatus = ANSC_STATUS_SUCCESS;
PCCSP_CWMP_TCPCR_HANDLER_OBJECT pMyObject = (PCCSP_CWMP_TCPCR_HANDLER_OBJECT )hThisObject;
PCCSP_CWMP_TCPCR_HANDLER_PROPERTY pProperty = (PCCSP_CWMP_TCPCR_HANDLER_PROPERTY )&pMyObject->Property;
PANSC_DAEMON_SERVER_TCP_OBJECT pTcpServer = (PANSC_DAEMON_SERVER_TCP_OBJECT)pMyObject->hTcpServer;
ULONG ulEngineCount = 1;
ULONG ulSocketCount = 1;
ULONG ulTcpDsoMode = ANSC_DSTO_MODE_EVENT_SYNC | ANSC_DSTO_MODE_FOREIGN_BUFFER | ANSC_DSTO_MODE_COMPACT;
if ( pMyObject->bActive )
{
return ANSC_STATUS_SUCCESS;
}
else
{
pMyObject->bActive = TRUE;
}
returnStatus = pMyObject->CreateTcpServers((ANSC_HANDLE)pMyObject);
if ( returnStatus != ANSC_STATUS_SUCCESS )
{
CcspTr069PaTraceDebug(("Create TCP server failed\n"));
pMyObject->bActive = FALSE;
return returnStatus;
}
if ( pProperty->ServerMode & CCSP_CWMP_TCPCR_HANDLER_MODE_useXsocket )
{
ulTcpDsoMode |= ANSC_DSTO_MODE_XSOCKET;
}
ulEngineCount = 1;
ulSocketCount = 4;
pTcpServer = (PANSC_DAEMON_SERVER_TCP_OBJECT)pMyObject->hTcpServer;
if ( pTcpServer )
{
#ifdef _ANSC_IPV6_COMPATIBLE_
CcspTr069PaTraceDebug(("Tcp host addr=%s:%d\n",
pProperty->HostAddr,
pProperty->HostPort));
AnscCopyString(pTcpServer->HostName, pProperty->HostAddr);
#else
CcspTr069PaTraceDebug(("Tcp host addr=%d.%d.%d.%d:%d\n",
pProperty->HostAddress.Dot[0],
pProperty->HostAddress.Dot[1],
pProperty->HostAddress.Dot[2],
pProperty->HostAddress.Dot[3],
pProperty->HostPort));
pTcpServer->SetHostAddress ((ANSC_HANDLE)pTcpServer, pProperty->HostAddress.Dot);
#endif
pTcpServer->SetHostPort ((ANSC_HANDLE)pTcpServer, pProperty->HostPort );
pTcpServer->SetMaxMessageSize((ANSC_HANDLE)pTcpServer, CCSP_CWMP_TCPCR_MAX_MSG_SIZE );
pTcpServer->SetEngineCount ((ANSC_HANDLE)pTcpServer, ulEngineCount );
pTcpServer->SetMinSocketCount((ANSC_HANDLE)pTcpServer, 0 );
pTcpServer->SetMaxSocketCount((ANSC_HANDLE)pTcpServer, ulSocketCount );
pTcpServer->SetMode ((ANSC_HANDLE)pTcpServer, ulTcpDsoMode );
returnStatus = pTcpServer->Engage((ANSC_HANDLE)pTcpServer);
if ( returnStatus != ANSC_STATUS_SUCCESS )
{
CcspTr069PaTraceError(("CcspCwmpTcpcrhoEngage - failed to be engaged, CWMP will not run properly!\n"));
pMyObject->bActive = FALSE;
return returnStatus;
}
}
return ANSC_STATUS_SUCCESS;
}
/**********************************************************************
caller: owner of this object
prototype:
ANSC_STATUS
CcspCwmpTcpcrhoCancel
(
ANSC_HANDLE hThisObject
);
description:
This function is called to control the proxy's behavior.
argument: ANSC_HANDLE hThisObject
This handle is actually the pointer of this object
itself.
return: status of operation.
**********************************************************************/
ANSC_STATUS
CcspCwmpTcpcrhoCancel
(
ANSC_HANDLE hThisObject
)
{
ANSC_STATUS returnStatus = ANSC_STATUS_SUCCESS;
PCCSP_CWMP_TCPCR_HANDLER_OBJECT pMyObject = (PCCSP_CWMP_TCPCR_HANDLER_OBJECT )hThisObject;
PCCSP_CWMP_TCPCR_HANDLER_PROPERTY pProperty = (PCCSP_CWMP_TCPCR_HANDLER_PROPERTY )&pMyObject->Property;
PANSC_DAEMON_SERVER_TCP_OBJECT pTcpServer = (PANSC_DAEMON_SERVER_TCP_OBJECT)pMyObject->hTcpServer;
if ( !pMyObject->bActive )
{
return ANSC_STATUS_SUCCESS;
}
else
{
pMyObject->bActive = FALSE;
}
if ( pTcpServer )
{
returnStatus = pTcpServer->Cancel((ANSC_HANDLE)pTcpServer);
}
returnStatus = pMyObject->RemoveTcpServers((ANSC_HANDLE)pMyObject);
return returnStatus;
}
/**********************************************************************
caller: owner of this object
prototype:
ANSC_STATUS
CcspCwmpTcpcrhoCreateTcpServers
(
ANSC_HANDLE hThisObject
);
description:
This function is called to create TCP servers.
argument: ANSC_HANDLE hThisObject
This handle is actually the pointer of this object
itself.
return: status of operation.
**********************************************************************/
ANSC_STATUS
CcspCwmpTcpcrhoCreateTcpServers
(
ANSC_HANDLE hThisObject
)
{
ANSC_STATUS returnStatus = ANSC_STATUS_SUCCESS;
PCCSP_CWMP_TCPCR_HANDLER_OBJECT pMyObject = (PCCSP_CWMP_TCPCR_HANDLER_OBJECT )hThisObject;
PCCSP_CWMP_TCPCR_HANDLER_PROPERTY pProperty = (PCCSP_CWMP_TCPCR_HANDLER_PROPERTY )&pMyObject->Property;
PANSC_DAEMON_SERVER_TCP_OBJECT pTcpServer = (PANSC_DAEMON_SERVER_TCP_OBJECT)pMyObject->hTcpServer;
if ( pProperty->HostPort == 0 && pTcpServer )
{
CcspTr069PaTraceDebug(("Port is 0 on current TcpServer: Server will be removed!!!\n"));
pTcpServer->Remove((ANSC_HANDLE)pTcpServer);
pMyObject->hTcpServer = (ANSC_HANDLE)NULL;
}
else if ( !pTcpServer && pProperty->HostPort != 0 )
{
pTcpServer =
(PANSC_DAEMON_SERVER_TCP_OBJECT)AnscCreateDaemonServerTcp
(
pMyObject->hContainerContext,
(ANSC_HANDLE)pMyObject,
(ANSC_HANDLE)NULL
);
if ( !pTcpServer )
{
CcspTr069PaTraceDebug(("Something wrong in AnscCreateDaemonServerTCP.\n"));
return ANSC_STATUS_RESOURCES;
}
else
{
pMyObject->hTcpServer = (ANSC_HANDLE)pTcpServer;
}
pTcpServer->SetWorker
(
(ANSC_HANDLE)pTcpServer,
pMyObject->hDstoWorker,
sizeof(ANSC_DSTO_WORKER_OBJECT)
);
}
CcspTr069PaTraceDebug(("TCP server created successfully.\n"));
return ANSC_STATUS_SUCCESS;
}
/**********************************************************************
caller: owner of this object
prototype:
ANSC_STATUS
CcspCwmpTcpcrhoRemoveTcpServers
(
ANSC_HANDLE hThisObject
);
description:
This function is called to remove TCP servers.
argument: ANSC_HANDLE hThisObject
This handle is actually the pointer of this object
itself.
return: status of operation.
**********************************************************************/
ANSC_STATUS
CcspCwmpTcpcrhoRemoveTcpServers
(
ANSC_HANDLE hThisObject
)
{
ANSC_STATUS returnStatus = ANSC_STATUS_SUCCESS;
PCCSP_CWMP_TCPCR_HANDLER_OBJECT pMyObject = (PCCSP_CWMP_TCPCR_HANDLER_OBJECT )hThisObject;
PCCSP_CWMP_TCPCR_HANDLER_PROPERTY pProperty = (PCCSP_CWMP_TCPCR_HANDLER_PROPERTY )&pMyObject->Property;
PANSC_DAEMON_SERVER_TCP_OBJECT pTcpServer = (PANSC_DAEMON_SERVER_TCP_OBJECT)pMyObject->hTcpServer;
if ( pTcpServer )
{
pTcpServer->Remove((ANSC_HANDLE)pTcpServer);
pMyObject->hTcpServer = (ANSC_HANDLE)NULL;
}
return ANSC_STATUS_SUCCESS;
}
/**********************************************************************
caller: owner of this object
prototype:
ANSC_STATUS
CcspCwmpTcpcrhoWorkerInit
(
ANSC_HANDLE hThisObject
);
description:
This function is called to control the proxy's behavior.
argument: ANSC_HANDLE hThisObject
This handle is actually the pointer of this object
itself.
return: status of operation.
**********************************************************************/
ANSC_STATUS
CcspCwmpTcpcrhoWorkerInit
(
ANSC_HANDLE hThisObject
)
{
ANSC_STATUS returnStatus = ANSC_STATUS_SUCCESS;
PCCSP_CWMP_TCPCR_HANDLER_OBJECT pMyObject = (PCCSP_CWMP_TCPCR_HANDLER_OBJECT )hThisObject;
PCCSP_CWMP_TCPCR_HANDLER_PROPERTY pProperty = (PCCSP_CWMP_TCPCR_HANDLER_PROPERTY)&pMyObject->Property;
return ANSC_STATUS_SUCCESS;
}
/**********************************************************************
caller: owner of this object
prototype:
ANSC_STATUS
CcspCwmpTcpcrhoWorkerUnload
(
ANSC_HANDLE hThisObject
);
description:
This function is called to control the proxy's behavior.
argument: ANSC_HANDLE hThisObject
This handle is actually the pointer of this object
itself.
return: status of operation.
**********************************************************************/
ANSC_STATUS
CcspCwmpTcpcrhoWorkerUnload
(
ANSC_HANDLE hThisObject
)
{
ANSC_STATUS returnStatus = ANSC_STATUS_SUCCESS;
PCCSP_CWMP_TCPCR_HANDLER_OBJECT pMyObject = (PCCSP_CWMP_TCPCR_HANDLER_OBJECT )hThisObject;
PCCSP_CWMP_TCPCR_HANDLER_PROPERTY pProperty = (PCCSP_CWMP_TCPCR_HANDLER_PROPERTY)&pMyObject->Property;
return ANSC_STATUS_SUCCESS;
}
| 30.545872 | 135 | 0.556165 | [
"object"
] |
d08585de77848520b8e93a68145376cdce68f5b6 | 910 | h | C | src/Camera.h | koladonia/LearnOpenGL | f2e2e032d631ac187112bd1e1aaa7e918043d4ec | [
"MIT"
] | null | null | null | src/Camera.h | koladonia/LearnOpenGL | f2e2e032d631ac187112bd1e1aaa7e918043d4ec | [
"MIT"
] | null | null | null | src/Camera.h | koladonia/LearnOpenGL | f2e2e032d631ac187112bd1e1aaa7e918043d4ec | [
"MIT"
] | null | null | null | #ifndef CAMERA_H
#define CAMERA_H
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <GLFW/glfw3.h>
class Camera
{
public:
const glm::vec3 initialFront = glm::vec3(0.0f, 0.0f, -1.0f);
const glm::vec3 initialUp = glm::vec3(0.0f, 1.0f, 0.0f);
const glm::vec3 initialRight = glm::vec3(1.0f, 0.0f, 0.0f);
Camera(GLFWwindow* window);
void updateP(int width, int height);
void updateV();
const glm::mat4& getV() const;
const glm::mat4& getP() const;
float getYaw();
float getPitch();
glm::vec3 pos = glm::vec3(0.0f, 0.0f, 3.0f);
glm::quat orientation = glm::quat(glm::vec3(0.0f, 0.0f, 0.0f));
float speed = 0.005f;
bool needUpdateV;
bool wasUpdatedV = false;
bool wasUpdatedP = false;
private:
glm::mat4 V;
glm::mat4 P;
};
#endif
| 20.222222 | 64 | 0.684615 | [
"transform"
] |
d0862062b2e4c4070a84fe9bb8066a1557da9c30 | 9,537 | h | C | tensorflow/compiler/xla/service/bfloat16_propagation.h | ashutom/tensorflow-upstream | c16069c19de9e286dd664abb78d0ea421e9f32d4 | [
"Apache-2.0"
] | 10 | 2021-05-25T17:43:04.000Z | 2022-03-08T10:46:09.000Z | tensorflow/compiler/xla/service/bfloat16_propagation.h | CaptainGizzy21/tensorflow | 3457a2b122e50b4d44ceaaed5a663d635e5c22df | [
"Apache-2.0"
] | 1,056 | 2019-12-15T01:20:31.000Z | 2022-02-10T02:06:28.000Z | tensorflow/compiler/xla/service/bfloat16_propagation.h | CaptainGizzy21/tensorflow | 3457a2b122e50b4d44ceaaed5a663d635e5c22df | [
"Apache-2.0"
] | 6 | 2016-09-07T04:00:15.000Z | 2022-01-12T01:47:38.000Z | /* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_BFLOAT16_PROPAGATION_H_
#define TENSORFLOW_COMPILER_XLA_SERVICE_BFLOAT16_PROPAGATION_H_
#include <memory>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "tensorflow/compiler/xla/service/bfloat16_support.h"
#include "tensorflow/compiler/xla/service/hlo_dataflow_analysis.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/service/hlo_pass_interface.h"
#include "tensorflow/core/lib/hash/hash.h"
namespace xla {
// HLO pass which reduces the precision of some HLO instructions to BF16
// according to the backend-specific BFloat16Support rule provided by the
// caller.
//
// This pass can be used to reduce instruction precision without affecting the
// numerical accuracy of the module, i.e., the final output of the module would
// be bitwise identical to that without this pass; this is possible if the
// backend already reduces precision to BF16 on some HLO instructions.
//
// This pass will not modify the signature of a computation, unless it is a
// fusion computation or its only caller is a while.
//
// !!! WARNING !!! This pass can introduce mixed precision in individual HLOs,
// which has two issues:
//
// 1) It does not guarantee to respect the passed-in BFloat16Support
// specification in terms of mixed precision, so the backend may not support an
// HLO that has mixed precision produced by this pass. To address this issue,
// run BFloat16Normalization with the same BFloat16Support after this pass.
//
// 2) In general, mixed precision may break the assumptions of some other HLO
// passes even if the specific backend supports the individual HLOs. Such
// assumptions include that there are no HLOs using mixed precision, or that the
// precision of an HLO's output is determined by its inputs. It should be used
// at the end of the HLO optimization pipeline but before
// BFloat16ConversionFolding. If other passes are needed after this pass, run
// BFloat16MixedPrecisionRemoval first to undo some of the changes made by this
// pass.
class BFloat16Propagation : public HloModulePass {
public:
explicit BFloat16Propagation(const BFloat16Support* bfloat16_support);
~BFloat16Propagation() override = default;
absl::string_view name() const override { return "bfloat16-propagation"; }
// Runs the pass on the given module. Returns whether the module was changed
// (precision reductions were added).
StatusOr<bool> Run(HloModule* module) override;
// Returns whether we should avoid changing the precision of inst regardless
// of the producers and users.
virtual bool ShouldKeepPrecisionUnchanged(const HloInstruction* inst);
// Determines whether we should consider changing the precision of the given
// instruction in the forward pass.
virtual bool InstructionIsCandidateForBF16Output(HloInstruction* hlo);
private:
// ***************************
// Function called and state produced by the forward analysis pass (from
// parameters to root) that determines the candidate HLOs to use BF16 outputs.
// The set of instructions to consider using bfloat16, computed in the forward
// pass.
absl::flat_hash_set<const HloInstruction*> consider_using_bfloat16_;
// ***************************
// Functions called and state produced by the backward pass (from root to
// parameters) that finds opportunities to use BF16.
// Determines the precision for the given instruction in the
// opportunity-finding pass.
void DetermineInstructionPrecision(HloInstruction* hlo, bool skip_parameters);
// Special handling in the opportunity-finding pass for fusion computations.
//
// Precondition: hlo->opcode() == kFusion
void DetermineFusionComputationPrecision(HloInstruction* fusion);
// Reverts changes to BF16 that will not propagate outside a fusion
// computation. This avoids BF16 casts overhead inside a fusion which won't
// save memory bandwidth.
//
// Precondition: hlo->opcode() == kFusion
void RevertIfFusionInternalBF16Changes(HloInstruction* fusion);
// Special handling in the opportunity-finding pass for while computations.
//
// Precondition: hlo->opcode() == kWhile
void DetermineWhileComputationsPrecision(HloInstruction* while_hlo);
// Special handling in the opportunity-finding pass for conditional branches.
//
// Precondition: hlo->opcode() == kConditional
void DetermineConditionalComputationsPrecision(HloInstruction* cond);
// The set of HloInstructions that have been visited in the
// opportunity-finding pass.
absl::flat_hash_set<const HloInstruction*>
instructions_visited_in_backward_pass_;
// The set of HloComputations that have been visited in the
// opportunity-finding pass.
absl::flat_hash_set<const HloComputation*>
computations_visited_in_backward_pass_;
// ***************************
// Functions called by the final inconsistency resolving pass.
// Adjusts the output shapes of HloInstructions such that if two
// HloInstructions have aliasing buffers in their outputs, they must have the
// same precision.
void ResolveInconsistencyOfAliasingBuffers(HloModule* module);
// Resolves inconsistency of aliasing buffers for the given computation, and
// recursively runs on a while instruction's condition and body until a fixed
// point is reached.
bool ResolveInconsistencyOfAliasingBuffersHelper(
HloComputation* computation,
absl::flat_hash_set<const HloComputation*>* visited_computations);
// Makes the parameters of called computations match how they are called by
// the given HLO.
void AdjustCalledComputationParameters(HloInstruction* hlo);
// Makes the root instructions of called computations match how they are used
// by the given HLO.
void AdjustCalledComputationRoot(HloInstruction* hlo);
// ***************************
// Functions called after changes in changes_to_bf16_ are applied.
// Resolves inconsistencies introduced by this pass for fusions with
// tuple-type output.
Status ResolveInconsistentFusions(HloModule* module);
// Converts the literals in kConstant HLOs which have their types changed to
// BF16 by this pass.
Status ResolveConvertedConstants(HloModule* module);
// Skips no-op conversions (same source and target shapes) that can be
// produced this pass, i.e., replaces them in their uses with their operands.
Status SkipNoopConversions(HloModule* module);
// ***************************
// Functions called and state used by two or more passes.
// Returns whether all uses of the given HloInstruction can consume BF16
// input.
bool AllUsersConsumeBF16(const HloInstruction& hlo,
const ShapeIndex& index) const;
// The output element type of the HLO at the given shape index after changes
// in changes_to_bf16_ are applied.
PrimitiveType OutputTypeAfterChange(HloInstruction* hlo,
const ShapeIndex& index) const;
// The element type of the HLO value after changes in changes_to_bf16_ are
// applied.
PrimitiveType ValueTypeAfterChange(const HloValue* value) const;
// If target_type == BF16, adds the HLO at the given index to
// changes_to_bf16_; otherwise, target_type must be F32 and this function
// removes the HLO at the given index from changes_to_bf16_ if it was earlier
// added.
void AddToOrRemoveFromBF16ChangeSet(HloInstruction* hlo,
const ShapeIndex& index,
PrimitiveType target_type);
// The set of F32 HLO values that must be kept in F32.
absl::flat_hash_set<const HloValue*> values_that_must_be_kept_as_f32_;
// Mapping from each HloComputation to the number of callers to it in the
// module. Populated at the beginning of this pass.
absl::flat_hash_map<const HloComputation*, int64> caller_counts_;
// We first store the potential F32-to-BF16 changes to changes_to_bf16_, which
// are subject to further adjustment, then finally applied to the HLOs. This
// avoids setting changed_ to true but all changes are reverted during
// adjustment.
//
// For each HloInstruction, changes_to_bf16_ stores the affected buffers in
// the output as a map from in-place pointers to subshapes to shape indices.
absl::flat_hash_map<HloInstruction*, absl::flat_hash_map<Shape*, ShapeIndex>>
changes_to_bf16_;
// Whether the last processed HLO module has been changed by this pass.
bool changed_ = false;
const BFloat16Support* bfloat16_support_;
std::unique_ptr<HloDataflowAnalysis> dataflow_;
};
} // namespace xla
#endif // TENSORFLOW_COMPILER_XLA_SERVICE_BFLOAT16_PROPAGATION_H_
| 42.959459 | 80 | 0.745413 | [
"shape",
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.