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
f2e24b923c098d5eec6d54465826fa499331141d
2,671
h
C
Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/telecom/AudioState.h
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/telecom/AudioState.h
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/telecom/AudioState.h
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #ifndef __ELASTOS_DROID_TELECOM_AUDIOSTATE_H__ #define __ELASTOS_DROID_TELECOM_AUDIOSTATE_H__ #include "Elastos.Droid.Telecom.h" #include <elastos/core/Object.h> #include <elastos/core/StringBuffer.h> using Elastos::Core::Object; using Elastos::Core::StringBuffer; namespace Elastos { namespace Droid { namespace Telecom { class AudioState : public Object , public IAudioState , public IParcelable { public: CAR_INTERFACE_DECL() AudioState(); CARAPI constructor(); CARAPI constructor( /* [in] */ Boolean isMuted, /* [in] */ Int32 route, /* [in] */ Int32 supportedRouteMask); CARAPI constructor( /* [in] */ IAudioState* state); CARAPI Equals( /* [in] */ IInterface* obj, /* [out] */ Boolean* res); CARAPI ToString( /* [out] */ String* str); CARAPI ReadFromParcel( /* [in] */ IParcel* source); CARAPI WriteToParcel( /* [in] */ IParcel* dest); /** True if the call is muted, false otherwise. */ CARAPI GetIsMuted( /* [out] */ Boolean* result); /** The route to use for the audio stream. */ CARAPI GetRoute( /* [out] */ Int32* result); /** Bit vector of all routes supported by this call. */ CARAPI GetSupportedRouteMask( /* [out] */ Int32* result); static CARAPI_(String) AudioRouteToString( /* [in] */ Int32 route); private: static CARAPI_(void) ListAppend( /* [in] */ StringBuffer* buffer, /* [in] */ const String& str); public: /** True if the call is muted, false otherwise. */ Boolean mIsMuted; /** The route to use for the audio stream. */ Int32 mRoute; /** Bit vector of all routes supported by this call. */ Int32 mSupportedRouteMask; }; } // namespace Telecom } // namespace Droid } // namespace Elastos #endif //__ELASTOS_DROID_TELECOM_AUDIOSTATE_H__
26.445545
75
0.615874
[ "object", "vector" ]
f2e5b1e5b6633d1790cfb30631055cda71d7c827
5,459
h
C
lib/EMBOSS-6.6.0/ajax/core/ajtree.h
alegione/CodonShuffle
bd6674b2eb21ee144a39d6d1e9b7264aba887240
[ "MIT" ]
5
2016-11-11T21:57:49.000Z
2021-07-27T14:13:31.000Z
lib/EMBOSS-6.6.0/ajax/core/ajtree.h
frantallukas10/CodonShuffle
4c408e1a8617f2a52dcb0329bba9617e1be17313
[ "MIT" ]
4
2016-05-15T07:56:25.000Z
2020-05-20T05:21:48.000Z
lib/EMBOSS-6.6.0/ajax/core/ajtree.h
frantallukas10/CodonShuffle
4c408e1a8617f2a52dcb0329bba9617e1be17313
[ "MIT" ]
10
2015-08-19T20:37:46.000Z
2020-04-07T06:49:23.000Z
/* @include ajtree ************************************************************ ** ** AJAX tree functions ** ** These functions create and control trees. ** ** @author Copyright (C) 2004 Peter Rice ** @version $Revision: 1.15 $ ** @modified $Date: 2011/10/19 14:52:22 $ by $Author: rice $ ** @@ ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public ** License along with this library; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, ** MA 02110-1301, USA. ** ******************************************************************************/ #ifndef AJTREE_H #define AJTREE_H /* ========================================================================= */ /* ============================= include files ============================= */ /* ========================================================================= */ #include "ajdefine.h" #include "ajstr.h" AJ_BEGIN_DECLS /* ========================================================================= */ /* =============================== constants =============================== */ /* ========================================================================= */ /* ========================================================================= */ /* ============================== public data ============================== */ /* ========================================================================= */ /* @enum AjETreeType ********************************************************** ** ** Tree type ** ** @value ajETreeAny Any ** @value ajETreeStr String data ** @value ajETreeSpecial Other special data ******************************************************************************/ typedef enum AjOTreeType { ajETreeAny, ajETreeStr, ajETreeSpecial } AjETreeType; #define AjPTreeNode AjOTreeNode* /* @data AjPTree ************************************************************** ** ** Tree data object. Trees are simple linked nodes with back pointers. ** ** Trees can hold any data type. Special functions are available for trees ** of AjPStr values. In general, these functions are the same. Many are ** provided for ease of use to save remembering which calls need special cases. ** ** At the top level, a tree has a list of named nodes and a pointer to the ** top node in the tree. ** ** @new ajTreeNew Creates a new general tree. ** @new ajTreestrNew Creates a new AjPStr tree. ** ** @attr Right [struct AjSTree*] Next tree node ** @attr Left [struct AjSTree*] Previous tree node ** @attr Up [struct AjSTree*] Parent tree node ** @attr Down [struct AjSTree*] First child tree node ** @attr Name [AjPStr] Name string ** @attr Data [void*] Data value ** @attr Freedata [AjBool function] Complex data free function ** @attr Type [AjEnum] Tree type (any, string, etc.) ** @attr Padding [char[4]] Padding to alignment boundary ** @@ ******************************************************************************/ typedef struct AjSTree { struct AjSTree* Right; struct AjSTree* Left; struct AjSTree* Up; struct AjSTree* Down; AjPStr Name; void* Data; AjBool (*Freedata)(void** data); AjEnum Type; char Padding[4]; } AjOTree; #define AjPTree AjOTree* /* ========================================================================= */ /* =========================== public functions ============================ */ /* ========================================================================= */ /* ** Prototype definitions */ AjBool ajTreeAddData(AjPTree thys, const AjPStr name, void* data); AjPTree ajTreeAddNode(AjPTree thys); AjPTree ajTreeAddSubNode(AjPTree thys); AjPTree ajTreeCopy(const AjPTree thys); void ajTreeDel(AjPTree* pthis); void ajTreeExit(void); void ajTreeFree(AjPTree* pthis); AjPTree ajTreeFollow(const AjPTree thys, const AjPTree parent); ajuint ajTreeLength(const AjPTree thys); void ajTreeMap(AjPTree thys, void apply(void** x, void* cl), void* cl); AjPTree ajTreeNew(void); AjPTree ajTreeNewNewick(const AjPStr newick); AjBool ajTreestrAddData(AjPTree thys, const AjPStr name, AjPStr data); AjPTree ajTreestrCopy(const AjPTree thys); void ajTreestrDel(AjPTree* pthis); void ajTreestrFree(AjPTree* pthis); ajuint ajTreestrLength(const AjPTree thys); void ajTreestrMap(AjPTree thys, void apply(AjPStr* x, void* cl), void* cl); AjPTree ajTreestrNew(void); ajuint ajTreestrToArray(const AjPTree thys, AjPStr** array); ajuint ajTreeToArray(const AjPTree thys, void*** array); void ajTreeToNewick(const AjPTree thys, AjPStr* Pnewick); void ajTreeTrace(const AjPTree thys); void ajTreestrTrace(const AjPTree thys); AjPTree ajTreeDown(const AjPTree thys); AjPTree ajTreeNext(const AjPTree thys); AjPTree ajTreePrev(const AjPTree thys); AjPTree ajTreeUp(const AjPTree thys); void ajTreeDummyFunction(void); /* ** End of prototype definitions */ AJ_END_DECLS #endif /* !AJTREE_H */
30.841808
79
0.551383
[ "object" ]
f2e6c9fb955d7d2d76e2e72049b6bebec7ade0e7
1,452
h
C
src/molecule.h
gonsie/ddcMD
d229248898b34630e166966bd00b0c4e0a1a2411
[ "MIT" ]
20
2020-07-28T01:14:22.000Z
2022-03-08T07:28:45.000Z
src/molecule.h
gonsie/ddcMD
d229248898b34630e166966bd00b0c4e0a1a2411
[ "MIT" ]
5
2020-07-29T06:55:57.000Z
2021-12-06T04:58:31.000Z
src/molecule.h
gonsie/ddcMD
d229248898b34630e166966bd00b0c4e0a1a2411
[ "MIT" ]
7
2020-07-28T08:01:32.000Z
2022-03-24T16:38:14.000Z
#ifndef MOLECULE_H #define MOLECULE_H #include "gid.h" #include "species.h" #include "state.h" enum MOLECULE_CLASS { NORMALMOLECULE, GIDORDERED }; typedef struct moleculeType_st { char *name; /* molecule name */ char *objclass; char *value; char *type; /* model */ void *parent; enum MOLECULE_CLASS itype; /* integer label for type */ int index; int nSpecies; SPECIES **species; SPECIES *ownershipSpecies; int ownershipSpeciesOffset; int nMembers; void *parm; /* pointer to parameter */ } MOLECULETYPE; typedef struct molecule_st { unsigned gid; MOLECULETYPE *type; int *list; } MOLECULE; typedef struct moleculeClass { char *name; /* molecule name */ char *objclass; char *value; char *type; /* model */ void *parent; int nMoleculeTypes; MOLECULETYPE **moleculeTypes; int nMoleculesGlobal; int nMolecules; // number of multispecies molecule. int nMoleculesSpecies; MOLECULE *molecule; int nSpecies; SPECIES **species; SPECIES **speciesBuffer; int *speciesIndexToMoleculeIndex; int *speciesToMoleculeOffset; int *list; int orderType; int *orderList; // } MOLECULECLASS; MOLECULECLASS *moleculeClassInit(void *parent, char *name); void moleculeScanState(MOLECULECLASS *moleculeClass, STATE *state); void moleculeDelta(MOLECULECLASS *moleculeClass, STATE *state, THREE_VECTOR *delta); #endif /* Local Variables: */ /* tab-width: 3 */ /* End: */
22.6875
84
0.703857
[ "model" ]
f2ed367ce141b3ce23366f9095b606bac55496bf
4,639
h
C
src/RobotController.h
manusovich/mrc
3b7f74cb72c5141f959feee3dfa4d2f036e80923
[ "MIT" ]
null
null
null
src/RobotController.h
manusovich/mrc
3b7f74cb72c5141f959feee3dfa4d2f036e80923
[ "MIT" ]
null
null
null
src/RobotController.h
manusovich/mrc
3b7f74cb72c5141f959feee3dfa4d2f036e80923
[ "MIT" ]
null
null
null
/** * Robot: geometry, servos, angleLimits, kinematic * RobotController accepts target poses and interpolation methods. * on sucessive calls to compute() it calculates the target Pose and sets the servo angles accordingly * * Kinematic must implement forward() and inverse() * Servos must implement atTargetAngle(), getTargetRadAngle(), setTargetRadAngle(), setCurrentAngleVelocity(), getMaxAngleVelocity(), * getCurrentLogicAngle() * todo use interface */ #ifndef ROBOT_CONTROLLER_H # define ROBOT_CONTROLLER_H #ifndef MOCK_VIRTUAL // used for setting methods to virtual in test environment #define MOCK_VIRTUAL #endif #include "VarSpeedServo.h" #include "Kinematic.h" # define NUMBER_OF_AXIS 6 class RobotController { public: RobotController(VarSpeedServo *servos[], Kinematic &_Kinematic, float logicalAngleLimits[6][2], void(*_logicalToPhysicalAngles)(float[6]), void(*_physicalToLogicalAngles)(float[6])); enum MOVEMENT_METHODS { LINEAR=1, P2P=0, CIRCULAR=2 }; enum STATES { IDLE, MOVING, START_MOVE, PREPARE_MOVE }; enum POSITION { X = 0, Y = 1, Z = 2, A = 3, B = 4, C = 5 }; // when calling process in a loop, transaction prevents execution of a half set command void startTransaction(); void endTransaction(); void stop(); MOCK_VIRTUAL void setMaxVelocity(float velocity); MOCK_VIRTUAL float getMaxVelocity(); MOCK_VIRTUAL void setMovementMethod(MOVEMENT_METHODS method); MOCK_VIRTUAL MOVEMENT_METHODS getMovementMethod(); MOCK_VIRTUAL void getCurrentPose(float currentPose[6]); MOCK_VIRTUAL float getCurrentPose(POSITION position); MOCK_VIRTUAL void runCalibration(); MOCK_VIRTUAL void setTargetPose(float x, float y, float z, float a, float b, float c); MOCK_VIRTUAL void setTargetPose(float pose[6]); MOCK_VIRTUAL void setTargetPose(POSITION position, float value); MOCK_VIRTUAL void getTargetPose(float targetPose[6]); MOCK_VIRTUAL float getTargetPose(POSITION position); // Logical MOCK_VIRTUAL void getCurrentLogicalAngles(float currentAngles[6]); MOCK_VIRTUAL float getCurrentLogicalAngle(unsigned int index); MOCK_VIRTUAL void setTargetLogicalAngles(float targetAngles[6]); //logical MOCK_VIRTUAL void setTargetLogicalAngle(unsigned int index, float targetAngle); MOCK_VIRTUAL void getTargetLogicalAngles(float targetAngles[6]); MOCK_VIRTUAL float getTargetLogicalAngle(unsigned int index); // Physical MOCK_VIRTUAL void getCurrentPhysicalAngles(float angles[6]); MOCK_VIRTUAL float getCurrentPhysicalAngle(unsigned int index); // void setTargetPhysicalAngles(float targetAngles[6]); //logical // MOCK_VIRTUAL void setTargetPhysicalAngle(unsigned int index, // float targetAngle); MOCK_VIRTUAL void getTargetPhysicalAngles(float targetAngles[6]); MOCK_VIRTUAL float getTargetPhysicalAngle(unsigned int index); MOCK_VIRTUAL bool isMoving(); void process(); private: float startAngles[6] = { 0 }; float targetAngles[6] = { 0 }; float targetPose[6] = { 0 }; float logicalAngleLimits[6][2]; bool targetAnglesChanged = false; bool targetPoseChanged = false; float interpolationRotationAngle = 0.0; float rotationAxisVectorNorm[3] = { 0 }; float targetOrientationVectorNorm[3] = { 0 }; float targetOrientationVector[3] = { 0 }; float startOrientationVectorNorm[3] = { 0 }; float startOrientationVector[3] = { 0 }; float startPose[6] = { 0 }; bool moveAsFarAsPossibleOnOutOfBound; bool inTransaction = false; STATES state; float interpolationDistanceIncrement; float interpolationOrientationAngleIncrement; float maxVelocity; Kinematic &_Kinematic; VarSpeedServo *Servos[6]; void (*logicalToPhysicalAngles )(float[6]); void (*physicalToLogicalAngles )(float[6]); MOVEMENT_METHODS movementMethod = MOVEMENT_METHODS::P2P; void _setTargetPose(float x, float y, float z, float a, float b, float c); void _applyTimedTargetAngles(float targetAngles[6], float targetTime = 0); void rodrigues(float ret[3], float unit[3], float v[3], float angleRad); bool _poseEquals(float Pose0[6], float Pose1[6]); bool _anglesEqual(float angles1[6], float angles2[6]); }; #endif // ifndef ROBOT_CONTROLLER_H
31.344595
133
0.685277
[ "geometry" ]
f2f79235aa1737065f923e2621d0a8dc0f60acb6
2,140
h
C
keytechKit/Code/KTServerInfo.h
tclaus/keytechkit
df3e7a2a84b50c1b0fb5587b72aeeb0a737a7cea
[ "MIT" ]
1
2017-07-18T09:28:04.000Z
2017-07-18T09:28:04.000Z
keytechKit/Code/KTServerInfo.h
tclaus/keytechkit
df3e7a2a84b50c1b0fb5587b72aeeb0a737a7cea
[ "MIT" ]
null
null
null
keytechKit/Code/KTServerInfo.h
tclaus/keytechkit
df3e7a2a84b50c1b0fb5587b72aeeb0a737a7cea
[ "MIT" ]
null
null
null
// // KTServerInfo.h // keytechKit // // Created by Thorsten Claus on 13.05.14. // Copyright (c) 2017 Claus-Software. All rights reserved. // #import <Foundation/Foundation.h> #import <RestKit/RestKit.h> /** The keytech serverinfo data is available withoutthe need of a valid user logged in. It provides information about the server and keytech version, a unique servce ID and statistical data. This class must be used as a singelton class */ @interface KTServerInfo : NSObject /** Provides the object Mapping for this class and given objectManager @param manager A shared RKObjectmanager that contains the connection data to the API */ +(RKObjectMapping*)mappingWithManager:(RKObjectManager*)manager; /** Returns a shared instace of the server info object. */ +(instancetype)sharedServerInfo; /** returns TRUE if serverinfo was fetched */ @property (readonly) BOOL isLoaded; @property (readonly) BOOL isLoading; /** Contains the full key-value list of all server properties. */ @property (readonly) NSMutableArray* keyValueList; /** Returns the current API Version from Server */ @property (readonly)NSString *databaseVersion; /** Return the API Kernel version from Server */ @property (readonly)NSString *APIVersion; /** Returns the baseURL for this Serverinfo */ @property (readonly) NSString *baseURL; /** A unique key to identify the current Server */ @property (readonly) NSString *serverID; /** Returns YES if web API supports index Server (SOLR server on vaults) */ @property (readonly) BOOL isIndexServerEnabled; /** Returns the company String used for license generations */ @property (readonly) NSString* licencedCompany; /** Loads the current Serverinfo with globally set ServerURL. Waits until server responds. */ +(instancetype)serverInfo; /** Loads a serverinfo object. @param success Will be called after a successful load of server information @param failure Will be called when request returns with an error. */ -(void)loadWithSuccess:(void(^)(KTServerInfo* serverInfo))success failure:(void(^)(NSError *error))failure; -(void)waitUnitlLoad; @end
22.291667
103
0.743925
[ "object" ]
f2ff18f1800fb3f03a60686791a87b761fc6ef4c
9,313
h
C
applications/ShallowWaterApplication/custom_strategies/velocity_height_residual_based_bdf_scheme.h
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
778
2017-01-27T16:29:17.000Z
2022-03-30T03:01:51.000Z
applications/ShallowWaterApplication/custom_strategies/velocity_height_residual_based_bdf_scheme.h
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
6,634
2017-01-15T22:56:13.000Z
2022-03-31T15:03:36.000Z
applications/ShallowWaterApplication/custom_strategies/velocity_height_residual_based_bdf_scheme.h
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
224
2017-02-07T14:12:49.000Z
2022-03-06T23:09:34.000Z
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Miguel Maso Sotomayor // #ifndef KRATOS_VELOCITY_HEIGHT_RESIDUAL_BASED_BDF_SCHEME_H_INCLUDED #define KRATOS_VELOCITY_HEIGHT_RESIDUAL_BASED_BDF_SCHEME_H_INCLUDED // System includes // External includes // Project includes #include "shallow_water_application_variables.h" #include "solving_strategies/schemes/residual_based_bdf_scheme.h" namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /** * @class VelocityHeightResidualBasedBDFScheme * @ingroup KratosShallowWaterApplication * @brief BDF integration scheme (for dynamic problems) * @details The \f$n\f$ order Backward Differentiation Formula (BDF) method is a two step \f$n\f$ order accurate method. * This scheme is designed to solve a system of the type: * \f[ * \mathbf{M} \frac{du_{n0}}{dt} + \mathbf{K} u_{n0} = \mathbf{f}_{ext} * \f] * @author Miguel Maso Sotomayor */ template<class TSparseSpace, class TDenseSpace> class VelocityHeightResidualBasedBDFScheme : public ResidualBasedBDFScheme<TSparseSpace, TDenseSpace> { public: ///@name Type Definitions ///@{ KRATOS_CLASS_POINTER_DEFINITION(VelocityHeightResidualBasedBDFScheme); typedef Scheme<TSparseSpace,TDenseSpace> BaseType; typedef typename BaseType::Pointer BaseTypePointer; typedef ResidualBasedBDFScheme<TSparseSpace,TDenseSpace> BDFBaseType; typedef typename BDFBaseType::DofsArrayType DofsArrayType; typedef typename BDFBaseType::TSystemMatrixType TSystemMatrixType; typedef typename BDFBaseType::TSystemVectorType TSystemVectorType; typedef typename BDFBaseType::LocalSystemVectorType LocalSystemVectorType; typedef typename BDFBaseType::LocalSystemMatrixType LocalSystemMatrixType; typedef ModelPart::NodesContainerType::iterator NodeIteratorType; ///@} ///@name Life Cycle ///@{ /** * @brief Constructor */ explicit VelocityHeightResidualBasedBDFScheme(const std::size_t Order = 2) : BDFBaseType(Order) {} /** * @brief Copy Constructor */ explicit VelocityHeightResidualBasedBDFScheme(VelocityHeightResidualBasedBDFScheme& rOther) : BDFBaseType(rOther) {} /** * @brief Clone */ BaseTypePointer Clone() override { return BaseTypePointer(new VelocityHeightResidualBasedBDFScheme(*this)); } /** * @brief Destructor */ ~VelocityHeightResidualBasedBDFScheme() override {} ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ /** * @brief Performing the prediction of the solution * @details It predicts the solution for the current step * @param rModelPart The model of the problem to solve * @param rDofSet set of all primary variables * @param rA LHS matrix * @param rDx Incremental update of primary variables * @param rb RHS Vector */ void Predict( ModelPart& rModelPart, DofsArrayType& rDofSet, TSystemMatrixType& rA, TSystemVectorType& rDx, TSystemVectorType& rb ) override { KRATOS_TRY; const double delta_time = rModelPart.GetProcessInfo()[DELTA_TIME]; const int num_nodes = static_cast<int>( rModelPart.Nodes().size() ); const auto it_node_begin = rModelPart.Nodes().begin(); const std::array<const Variable<double>*, 3> var_components = {&VELOCITY_X, &VELOCITY_Y, &HEIGHT}; const std::array<const Variable<double>*, 3> accel_components = {&ACCELERATION_X, &ACCELERATION_Y, &VERTICAL_VELOCITY}; IndexPartition<std::size_t>(num_nodes).for_each([&](std::size_t i){ auto it_node = it_node_begin + i; for (std::size_t j = 0; j < 3; ++j) { if (!it_node->IsFixed(*var_components[j])) { double& un0 = it_node->FastGetSolutionStepValue(*var_components[j]); double un1 = it_node->FastGetSolutionStepValue(*var_components[j], 1); double dot_un1 = it_node->FastGetSolutionStepValue(*accel_components[j], 1); un0 = un1 + delta_time * dot_un1; } } UpdateFirstDerivative(it_node); }); KRATOS_CATCH("VelocityHeightResidualBasedBDFScheme.Predict"); } ///@} ///@name Input and output ///@{ /** * @brief Turn back information as a string. */ std::string Info() const override { return "VelocityHeightResidualBasedBDFScheme"; } ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ /** * @brief Update the first time derivative * @param itNode the node interator */ void UpdateFirstDerivative(NodeIteratorType itNode) override { array_1d<double, 3>& dot_un0 = itNode->FastGetSolutionStepValue(ACCELERATION); double& dot_hn0 = itNode->FastGetSolutionStepValue(VERTICAL_VELOCITY); noalias(dot_un0) = BDFBaseType::mBDF[0] * itNode->FastGetSolutionStepValue(VELOCITY); dot_hn0 = BDFBaseType::mBDF[0] * itNode->FastGetSolutionStepValue(HEIGHT); for (std::size_t i_order = 1; i_order < BDFBaseType::mOrder + 1; ++i_order) { noalias(dot_un0) += BDFBaseType::mBDF[i_order] * itNode->FastGetSolutionStepValue(VELOCITY, i_order); dot_hn0 += BDFBaseType::mBDF[i_order] * itNode->FastGetSolutionStepValue(HEIGHT, i_order); } } /** * @brief Update the second time derivative * @param itNode the node interator */ void UpdateSecondDerivative(NodeIteratorType itNode) override {} /** * @brief It adds the dynamic LHS contribution of the elements * @param rLHS_Contribution The dynamic contribution for the LHS * @param rD The damping matrix * @param rM The mass matrix * @param rCurrentProcessInfo The current process info instance */ void AddDynamicsToLHS( LocalSystemMatrixType& rLHS_Contribution, LocalSystemMatrixType& rD, LocalSystemMatrixType& rM, const ProcessInfo& rCurrentProcessInfo ) override { // Adding mass contribution to the dynamic stiffness if (rM.size1() != 0) { // if M matrix declared noalias(rLHS_Contribution) += rM * BDFBaseType::mBDF[0]; } } /** * @brief It adds the dynamic RHS contribution of the elements * @param rElement The element to compute * @param RHS_Contribution The dynamic contribution for the RHS * @param D The damping matrix * @param M The mass matrix * @param rCurrentProcessInfo The current process info instance */ void AddDynamicsToRHS( Element& rElement, LocalSystemVectorType& rRHS_Contribution, LocalSystemMatrixType& rD, LocalSystemMatrixType& rM, const ProcessInfo& rCurrentProcessInfo ) override { const auto& r_const_element = rElement; const std::size_t this_thread = OpenMPUtils::ThisThread(); // Adding inertia contribution if (rM.size1() != 0) { r_const_element.GetFirstDerivativesVector(BDFBaseType::mVector.dotun0[this_thread], 0); noalias(rRHS_Contribution) -= prod(rM, BDFBaseType::mVector.dotun0[this_thread]); } } /** * @brief It adds the dynamic RHS contribution of the condition * @param rCondition The condition to compute * @param RHS_Contribution The dynamic contribution for the RHS * @param D The damping matrix * @param M The mass matrix * @param rCurrentProcessInfo The current process info instance */ void AddDynamicsToRHS( Condition& rCondition, LocalSystemVectorType& rRHS_Contribution, LocalSystemMatrixType& rD, LocalSystemMatrixType& rM, const ProcessInfo& rCurrentProcessInfo ) override { const auto& r_const_condition = rCondition; const std::size_t this_thread = OpenMPUtils::ThisThread(); // Adding inertia contribution if (rM.size1() != 0) { r_const_condition.GetFirstDerivativesVector(BDFBaseType::mVector.dotun0[this_thread], 0); noalias(rRHS_Contribution) -= prod(rM, BDFBaseType::mVector.dotun0[this_thread]); } } ///@} ///@name Protected Life Cycle ///@{ ///@} }; // Class VelocityHeightResidualBasedBDFScheme ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ ///@} } // Namespace Kratos #endif // KRATOS_VELOCITY_HEIGHT_RESIDUAL_BASED_BDF_SCHEME_H_INCLUDED defined
29.378549
127
0.636422
[ "vector", "model" ]
6293a21b31b95e0f2a8f7e1c85c8e858210f6490
11,164
h
C
kratos/includes/table_stream.h
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
778
2017-01-27T16:29:17.000Z
2022-03-30T03:01:51.000Z
kratos/includes/table_stream.h
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
6,634
2017-01-15T22:56:13.000Z
2022-03-31T15:03:36.000Z
kratos/includes/table_stream.h
lkusch/Kratos
e8072d8e24ab6f312765185b19d439f01ab7b27b
[ "BSD-4-Clause" ]
224
2017-02-07T14:12:49.000Z
2022-03-06T23:09:34.000Z
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ \. // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Vicente Mataix Ferrandiz // Inspired in bprinter, work of Dat Chu: https://github.com/dattanchu/bprinter // Removing all the dependencies of boost::karma and adding bold fonts and additional functionalities needed // #ifndef KRATOS_TABLE_STREAM_H_INCLUDED #define KRATOS_TABLE_STREAM_H_INCLUDED // System includes #include <iostream> #include <iomanip> #include <vector> #include <string> #include <sstream> // External includes // Project includes #include "includes/serializer.h" #include "includes/shared_pointers.h" #include "includes/exception.h" namespace Kratos { ///@addtogroup KratosCore ///@{ ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ class endl{}; /** * @class TableStream * @ingroup KratosCore * @brief This is a fancy table to stream data in a fancy way * @author Vicente Mataix Ferrandiz */ class TableStream { public: ///@name Type Definitions ///@{ /// Pointer definition of TableStream KRATOS_CLASS_POINTER_DEFINITION(TableStream); ///@} ///@name Life Cycle ///@{ /// Default constructor. TableStream( std::ostream * Output, const std::string& Separator = "|", const bool UseBoldFont = true ) : mOutStream(Output), mSeparator(Separator), mBoldFont(UseBoldFont) { // Initialize values mIndexRow = 0; mIndexColumn = 0; mTableWidth = 0; mFlushLeft = false; } /// Destructor. virtual ~TableStream() = default; ///@} ///@name Operators ///@{ /** * @brief This is the operator << for any kind of input * @param Input The input considered * @return The updated table stream */ template<typename TClass> TableStream& operator<<(TClass Input) { if (typeid(TClass) == typeid(endl)) { while (mIndexColumn != 0) { *this << ""; } } else { if (mIndexColumn == 0) { *mOutStream << "|"; } if(mFlushLeft) { *mOutStream << std::left; } else { *mOutStream << std::right; } // Leave 3 extra space: One for negative sign, one for zero, one for decimal *mOutStream << std::setw(mColumnWidths.at(mIndexColumn)) << Input; if (mIndexColumn == GetNumColumns()-1) { *mOutStream << "|\n"; mIndexRow = mIndexRow + 1; mIndexColumn = 0; } else { *mOutStream << mSeparator; mIndexColumn = mIndexColumn + 1; } } return *this; } /** * @brief This is the operator << just for floats * @param Input The float considered * @return The updated table stream */ TableStream& operator<<(float Input) { OutputDecimalNumber<float>(Input); return *this; } /** * @brief This is the operator << just for doubles * @param Input The double considered * @return The updated table stream */ TableStream& operator<<(double Input) { OutputDecimalNumber<double>(Input); return *this; } ///@} ///@name Operations ///@{ /** * @brief It returns the number of columns * @return The size of mColumnHeaders (the column headers) */ unsigned int GetNumColumns() const { return mColumnHeaders.size(); } /** * @brief It returns the table width * @return mTableWidth: The table width */ unsigned int GetTableWidth() const { return mTableWidth; } /** * @brief Set the separator used for the table */ void SetSeparator(const std::string& Separator) { mSeparator = Separator; } /** * @brief Set if the bold fonts are used for the table */ void SetBold(const bool& UseBoldFont) { mBoldFont = UseBoldFont; } /** * @brief Set the flush orientation to the left */ void SetFlushLeft() { mFlushLeft = true; } /** * @brief Set the flush orientation to the right */ void SetFlushRight() { mFlushLeft = false; } /** * @brief Add a column to our table * @param HeaderName Name to be print for the header * @param ColumnWidth The width of the column must be at least 4 spaces */ void AddColumn( const std::string& HeaderName, const int ColumnWidth ) { KRATOS_ERROR_IF(ColumnWidth < 4) << "Column size has to be >= 4" << std::endl; mColumnHeaders.push_back(HeaderName); mColumnWidths.push_back(ColumnWidth); mTableWidth += ColumnWidth + mSeparator.size(); // for the separator } /** * @brief This function prints the header of the stream */ void PrintHeader() { PrintHorizontalLine(); if (mBoldFont == true) { #if !defined(_WIN32) *mOutStream << "\x1B[1m"; #endif } *mOutStream << "|"; for (unsigned int i = 0; i < GetNumColumns(); ++i) { if(mFlushLeft) { *mOutStream << std::left; } else { *mOutStream << std::right; } *mOutStream << std::setw(mColumnWidths.at(i)) << mColumnHeaders.at(i).substr(0, mColumnWidths.at(i)); if (i != GetNumColumns()-1) { *mOutStream << mSeparator; } } *mOutStream << "|"; if (mBoldFont == true) { #if !defined(_WIN32) *mOutStream << "\x1B[0m"; #endif } *mOutStream << "\n"; PrintHorizontalLine(); } /** * @brief This function prints the footer of the stream */ void PrintFooter() { PrintHorizontalLine(); } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ // Stream related variables std::ostream* mOutStream; // The stream considered std::vector<std::string> mColumnHeaders; // This vector contains the header to print in each column std::vector<int> mColumnWidths; // This vector containts the spaces of each column std::string mSeparator; // The separator considered in each column // The indexes currently used unsigned int mIndexRow; // Index of current row unsigned int mIndexColumn; // Index of current column // Other variables related with the table output unsigned int mTableWidth; // The table width bool mFlushLeft; // If the flush is aligned to the left or the right bool mBoldFont; // If the bold fonts are considered to use in the ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ /** * This functions prints an horizontal line */ void PrintHorizontalLine() { *mOutStream << "+"; // the left bar for (unsigned int i = 0; i< mTableWidth-1; ++i) { *mOutStream << "-"; } *mOutStream << "+"; // the right bar *mOutStream << "\n"; } /** * This functions prints into the stream a double or float value with scientific notation (respeting the spaces asigned) * @param Input The double or float to print */ template<typename TClass> void OutputDecimalNumber(TClass Input) { // If we cannot handle this number, indicate so if (Input < 10*(mColumnWidths.at(mIndexColumn)-1) || Input > 10*mColumnWidths.at(mIndexColumn)) { std::stringstream string_out; string_out << std::setiosflags(std::ios::scientific) << std::setprecision(3) << std::uppercase << std::setw(mColumnWidths.at(mIndexColumn)) << Input; std::string string_to_print = string_out.str(); *mOutStream << string_to_print; } else { *mOutStream << std::setiosflags(std::ios::scientific) << std::setprecision(3) << std::uppercase << std::setw(mColumnWidths.at(mIndexColumn)) << Input; } if (mIndexColumn == GetNumColumns()-1) { *mOutStream << "|\n"; mIndexRow = mIndexRow + 1; mIndexColumn = 0; } else { *mOutStream << mSeparator; mIndexColumn = mIndexColumn + 1; } } ///@} ///@name Private Access ///@{ ///@} ///@name Serialization ///@{ friend class Serializer; void save(Serializer& rSerializer) const { // rSerializer.save("OutStream", mOutStream); rSerializer.save("ColumnHeaders", mColumnHeaders); rSerializer.save("ColumnWidths", mColumnWidths); rSerializer.save("Separator", mSeparator); rSerializer.save("IndexRow", mIndexRow); rSerializer.save("IndexColumn", mIndexColumn); rSerializer.save("TableWidth", mTableWidth); rSerializer.save("FlushLeft", mFlushLeft); rSerializer.save("BoldFont", mBoldFont); } void load(Serializer& rSerializer) { // rSerializer.load("OutStream", mOutStream); rSerializer.load("ColumnHeaders", mColumnHeaders); rSerializer.load("ColumnWidths", mColumnWidths); rSerializer.load("Separator", mSeparator); rSerializer.load("IndexRow", mIndexRow); rSerializer.load("IndexColumn", mIndexColumn); rSerializer.load("TableWidth", mTableWidth); rSerializer.load("FlushLeft", mFlushLeft); rSerializer.load("BoldFont", mBoldFont); } ///@} ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ }; // Class TableStream } // namespace Kratos. #endif
23.503158
124
0.533142
[ "vector" ]
62965616295f5c456ff733926ea5f125b9432070
1,189
h
C
src/fhiclcpp/fhiclcpp/test/types/KeyMap.h
JeffersonLab/ARIEL
49054ac62a84d48e269f7171daabb98e12a0be90
[ "BSD-3-Clause" ]
null
null
null
src/fhiclcpp/fhiclcpp/test/types/KeyMap.h
JeffersonLab/ARIEL
49054ac62a84d48e269f7171daabb98e12a0be90
[ "BSD-3-Clause" ]
2
2021-12-10T14:54:24.000Z
2022-03-25T16:33:23.000Z
fhiclcpp/test/types/KeyMap.h
art-framework-suite/fhicl-cpp
302a8ca52dba4b922812ead406599cd535676252
[ "BSD-3-Clause" ]
2
2020-09-26T01:37:11.000Z
2021-05-03T13:02:24.000Z
#ifndef fhiclcpp_test_types_KeyMap_h #define fhiclcpp_test_types_KeyMap_h #include "fhiclcpp/type_traits.h" #include "fhiclcpp/types/detail/ParameterWalker.h" #include <string> #include <vector> namespace fhicl { class KeyMap : public detail::ParameterWalker<tt::const_flavor::require_const> { public: auto const& result() const { return keys_; }; template <typename T> static auto get(std::string const& n) { KeyMap km; T test{Name(n)}; km.walk_over(test); return km.result(); } private: std::vector<std::string> keys_; void enter_table(detail::TableBase const& tb) override { append(tb.key()); } void enter_sequence(detail::SequenceBase const& sb) override { append(sb.key()); } void atom(detail::AtomBase const& ab) override { append(ab.key()); } void delegated_parameter(detail::DelegateBase const& dp) override { append(dp.key()); } void append(std::string const& k) { keys_.emplace_back(k); } }; } #endif /* fhiclcpp_test_types_KeyMap_h */ // Local variables: // mode: c++ // End:
17.485294
71
0.615643
[ "vector" ]
62969316db9c9edf96ac94b16f86fbd7ec56056a
1,910
h
C
cpp-restsdk/api/RecentApi.h
thracesystems/powermeter-api
7bdab034ff916ee49e986de88f157bd044e981c1
[ "Apache-2.0" ]
null
null
null
cpp-restsdk/api/RecentApi.h
thracesystems/powermeter-api
7bdab034ff916ee49e986de88f157bd044e981c1
[ "Apache-2.0" ]
null
null
null
cpp-restsdk/api/RecentApi.h
thracesystems/powermeter-api
7bdab034ff916ee49e986de88f157bd044e981c1
[ "Apache-2.0" ]
null
null
null
/** * PowerMeter API * API * * The version of the OpenAPI document: 2021.4.1 * * NOTE: This class is auto generated by OpenAPI-Generator 4.3.1. * https://openapi-generator.tech * Do not edit the class manually. */ /* * RecentApi.h * * */ #ifndef POWERMETER_API_RecentApi_H_ #define POWERMETER_API_RecentApi_H_ #include "../ApiClient.h" #include "DashboardAccess.h" #include "DesignAccess.h" #include "ProjectAccess.h" #include "ScenarioAccess.h" #include "SimAccess.h" #include <boost/optional.hpp> namespace powermeter { namespace api { using namespace powermeter::model; class RecentApi { public: explicit RecentApi( std::shared_ptr<const ApiClient> apiClient ); virtual ~RecentApi(); /// <summary> /// /// </summary> /// <remarks> /// Get list of recent design dashboards /// </remarks> pplx::task<std::vector<std::shared_ptr<DashboardAccess>>> recentDashboardList( ) const; /// <summary> /// /// </summary> /// <remarks> /// Get list of recent designs /// </remarks> pplx::task<std::vector<std::shared_ptr<DesignAccess>>> recentDesignList( ) const; /// <summary> /// /// </summary> /// <remarks> /// Get list of recent projects /// </remarks> pplx::task<std::vector<std::shared_ptr<ProjectAccess>>> recentProjectList( ) const; /// <summary> /// /// </summary> /// <remarks> /// Get list of recent project scenarios /// </remarks> pplx::task<std::vector<std::shared_ptr<ScenarioAccess>>> recentScenarioList( ) const; /// <summary> /// /// </summary> /// <remarks> /// Get list of recent sims /// </remarks> pplx::task<std::vector<std::shared_ptr<SimAccess>>> recentSimulationList( ) const; protected: std::shared_ptr<const ApiClient> m_ApiClient; }; } } #endif /* POWERMETER_API_RecentApi_H_ */
19.489796
82
0.624084
[ "vector", "model" ]
629ad7bb347d165dc6d7603aa4bed7ac53262220
1,066
h
C
include/tweedledum/Synthesis/steiner_gauss_synth.h
drewrisinger/tweedledum
1c331a076fa137295193a10e0ed664603ae80c21
[ "MIT" ]
null
null
null
include/tweedledum/Synthesis/steiner_gauss_synth.h
drewrisinger/tweedledum
1c331a076fa137295193a10e0ed664603ae80c21
[ "MIT" ]
null
null
null
include/tweedledum/Synthesis/steiner_gauss_synth.h
drewrisinger/tweedledum
1c331a076fa137295193a10e0ed664603ae80c21
[ "MIT" ]
null
null
null
/*------------------------------------------------------------------------------ | Part of Tweedledum Project. This file is distributed under the MIT License. | See accompanying file /LICENSE for details. *-----------------------------------------------------------------------------*/ #pragma once #include "../IR/Circuit.h" #include "../Target/Device.h" #include "../Utils/Matrix.h" #include <nlohmann/json.hpp> #include <vector> // This implementation is based on: // // Kissinger, Aleks, and Arianne Meijer-van de Griend. "CNOT circuit extraction // for topologically-constrained quantum memories." // arXiv preprint arXiv:1904.00633 (2019). // // I also used staq's (https://github.com/softwareQinc/staq/) trick to deal // with 1's to the left of the diagonal // namespace tweedledum { void steiner_gauss_synth(Circuit& circuit, Device const& device, BMatrix const& matrix, nlohmann::json const& config = {}); Circuit steiner_gauss_synth(Device const& device, BMatrix const& matrix, nlohmann::json const& config = {}); } // namespace tweedledum
34.387097
80
0.620075
[ "vector" ]
62a715c9859d9a74500e67cd25687e94e3f9a87b
2,691
h
C
BTCKeep/Core/Data/BKDataManager.h
Gargo/BTC-Keep
3d7d3b01fc089a866aa40e513160a4f69eb3b2f2
[ "MIT" ]
null
null
null
BTCKeep/Core/Data/BKDataManager.h
Gargo/BTC-Keep
3d7d3b01fc089a866aa40e513160a4f69eb3b2f2
[ "MIT" ]
1
2017-08-10T10:06:56.000Z
2017-08-10T10:07:07.000Z
BTCKeep/Core/Data/BKDataManager.h
Gargo/BTC-Keep
3d7d3b01fc089a866aa40e513160a4f69eb3b2f2
[ "MIT" ]
null
null
null
// // BKDataManager.h // BTCKeep // // Created by Vitali on 9/12/12. // // #import <Foundation/Foundation.h> #import "BSUtilities.h" #import "BKCurrency.h" #import "BKTrade.h" #import "BKTradePair.h" #import "BKOrder.h" #define BKCurrencyEntity @"BKCurrency" #define BKTradeEntity @"BKTrade" #define BKTradePairEntity @"BKTradePair" #define BKOrderEntity @"BKOrder" #define BKKeyId @"id" #define BKKeyIdentifier @"identifier" #define BKKeyPrimaryCurrencyId @"primaryCurrencyId" #define BKKeySecondaryCurrencyId @"secondaryCurrencyId" #define BKKeyTradePairId @"tradePairId" #define BKKeyCreatedAt @"createdAt" #define BKKeyExchangeID @"exchangeID" @interface BKDataManager : NSObject { NSManagedObjectModel *model; NSManagedObjectContext *mainContext; NSPersistentStoreCoordinator *coordinator; } //@property (readonly, strong, nonatomic) NSManagedObjectContext *mainContext; //@property (readonly, strong, nonatomic) NSManagedObjectModel *model; //@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *coordinator; + (instancetype)sharedInstance; - (NSArray *)getMainCurrenciesForExchange:(id)exchange; - (NSArray *)getMainCurrenciesIDsForExchange:(id)exchange; - (NSArray *)getToCurrenciesIDsForSelectedFromCurrencyID:(NSString *)fromCurrencyID forExchange:(id)exchange; - (NSArray *)getCurrenciesForExchange:(id)exchange; - (NSArray *)getTradesForExchange:(id)exchange; - (NSArray *)getTradePairsForExchange:(id)exchange; - (NSArray *)getOrdersForExchange:(id)exchange; - (NSArray *)getTradePairsWithCurrencyId:(NSString *)fromCurrencyId forExchange:(id)exchange; - (BKTradePair *)getTradePairFromCurrencyId:(NSString *)fromCurrencyId toCurrencyId:(NSString *)toCurrencyId forExchange:(id)exchange; - (NSArray *)getTradesWithTradePairId:(NSString *)tradePairId forExchange:(id)exchange; - (NSArray *)getTradeIDsWithTradePairId:(NSString *)tradePairId forExchange:(id)exchange; - (NSArray *)getCurrenciesWithIDs:(NSArray *)ids forExchange:(id)exchange; - (NSArray *)getTradesWithIDs:(NSArray *)ids forExchange:(id)exchange; - (NSArray *)filterEntities:(NSArray *)entities withIDs:(NSArray *)ids forExchange:(id)exchange; //Magical Record - (void)updateEntitityNamed:(NSString *)name identifierName:(NSString *)identifierName filler:(id)filler fillSelector:(SEL)fillSelector fillParams:(id)fillParams deleteOld:(BOOL)deleteOld forExchange:(id)exchange; - (void)updateEntititesNamed:(NSString *)name filler:(id)filler fillParams:(id)fillParams forExchange:(id)exchange; @end
40.772727
213
0.740245
[ "model" ]
62bb337c8dc041c55ce96602e7c3cf8fceef18a4
8,351
h
C
inc/osvr/JointClientKit/JointClientKitC.h
ethanpeng/OSVR-Core
59405fc1b1a25aea051dfbba0be5171fa19b8b30
[ "Apache-2.0" ]
369
2015-03-08T03:12:41.000Z
2022-02-08T22:15:39.000Z
inc/osvr/JointClientKit/JointClientKitC.h
ethanpeng/OSVR-Core
59405fc1b1a25aea051dfbba0be5171fa19b8b30
[ "Apache-2.0" ]
486
2015-03-09T13:29:00.000Z
2020-10-16T00:41:26.000Z
inc/osvr/JointClientKit/JointClientKitC.h
ethanpeng/OSVR-Core
59405fc1b1a25aea051dfbba0be5171fa19b8b30
[ "Apache-2.0" ]
166
2015-03-08T12:03:56.000Z
2021-12-03T13:56:21.000Z
/** @file @brief Header Must be c-safe! @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ /* // Copyright 2015 Sensics, 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 INCLUDED_JointClientKitC_h_GUID_AEF51E42_05FE_4095_DC94_0D1E5CF76A76 #define INCLUDED_JointClientKitC_h_GUID_AEF51E42_05FE_4095_DC94_0D1E5CF76A76 /* Internal Includes */ #include <osvr/JointClientKit/Export.h> #include <osvr/Util/APIBaseC.h> #include <osvr/Util/ReturnCodesC.h> #include <osvr/Util/AnnotationMacrosC.h> #include <osvr/Util/StdInt.h> #include <osvr/Util/ClientOpaqueTypesC.h> /* Library/third-party includes */ /* none */ /* Standard includes */ /* none */ OSVR_EXTERN_C_BEGIN /** @defgroup JointClientKit @brief A limited-purpose library for creating client contexts that operate the server in the same thread. **See cautions.** In rare cases, it may be useful to run the server and client in a **single process**, with their mainloops sharing a **single thread**. Examples include automated tests, special-purpose apps, or apps on platforms that do not support interprocess communication or multiple threads (in which case no async plugins can be used either). This library exists to permit those limited use cases. Use of this library may sound appealing for a number of other use cases, but consider carefully, as there's likely a better way to solve the problem. In particular, this is **not** a good solution for the following: - avoiding having to start the server before your app: there are platform-specific "launch on demand" service techniques that should be used instead. (If they're not yet used in OSVR on the platform you're interested in, file an issue or contribute!) - other desires for simplification: this actually makes the overall user experience more complex, since you're eliminating some of the advantages of OSVR (centralized configuration of hardware-agnostic interfaces used by applications), and taking the responsibility of properly configuring a user's system when they've likely already configured it externally. - seeking to reduce latency due to communication between threads or processes: using this library will almost certainly increase latency, and **will** decrease your framerate if you don't put it in its own thread (and handle locking, etc. yourself), as you'd then have all the device servicing code right in the "hot path" of your app's main loop, instead of running asynchronously at a much higher rate in a separate thread and process. Because it transfers the overhead of having to perform configuration to the client application, reduces modularity, and can reduce performance, this API is not recommended except in very specialized situations. (Probably not your situations, that is - and if it turns out that you do actually need this, you can swap it in easily after writing your application the typical way, since the API only differs in the startup period.) Now that we've covered the warnings... ## General usage The usage pattern is very similar to ClientKit, and most functions you call are actually in ClientKit. The only differences relate to configuring the server that will run jointly: - On startup, you'll usually create a ::OSVR_JointClientOpts with osvrJointClientCreateOptions(), instead of directly creating an ::OSVR_ClientContext. - Call the various @ref JointClientKit methods with the ::OSVR_JointClientOpts you created to queue up server configuration actions. - To get an ::OSVR_ClientContext, you'll call osvrJointClientInit() with your application identifier (as in @ref ClientKit), also passing in the OSVR_JointClientOpts. (That method takes ownership of the options object and deletes it when finished.) - osvrJointClientInit() will create a special client context containg both a client and a server, then execute the actions you queued in the OSVR_JointClientOpts. If all those complete without exception, you'll receive a OSVR_ClientContext that you can proceed to use as normal with all @ref ClientKit methods. If any errors occur, you'll receive a null value instead. @{ */ /** @brief Opaque typedef for options used when starting up a joint client context. Serves as a queue for configuration operations to perform on the server. */ typedef struct OSVR_JointClientContextOptsObject *OSVR_JointClientOpts; /** @brief Creates an empty OSVR_JointClientOpts. The only way to deallocate this object is to pass it to osvrJointClientInit(). @returns the options object - if NULL, an error occurred. */ OSVR_JOINTCLIENTKIT_EXPORT OSVR_JointClientOpts osvrJointClientCreateOptions(); /** @name Server configuration actions @brief Methods that queue up actions to perform on the server when the joint client/server is later created in osvrJointClientInit(). These methods do not perform the actions directly or immediately, and only perform some basic error checking on their inputs: failure in the actions specified may instead be reported later in a failure to create the context. @{ */ /** @brief Queues up the autoloading of plugins. May only be called once per options object. */ OSVR_JOINTCLIENTKIT_EXPORT OSVR_ReturnCode osvrJointClientOptionsAutoloadPlugins(OSVR_JointClientOpts opts); /** @brief Queues up the manual load of a plugin by name. */ OSVR_JOINTCLIENTKIT_EXPORT OSVR_ReturnCode osvrJointClientOptionsLoadPlugin( OSVR_JointClientOpts opts, const char *pluginName); /** @brief Queues up the manual instantiation of a plugin/driver by name with optional parameters (JSON). */ OSVR_JOINTCLIENTKIT_EXPORT OSVR_ReturnCode osvrJointClientOptionsInstantiateDriver(OSVR_JointClientOpts opts, const char *pluginName, const char *driverName, const char *params); /** @brief Queues up the manual addition of an alias to the path tree. */ OSVR_JOINTCLIENTKIT_EXPORT OSVR_ReturnCode osvrJointClientOptionsAddAlias( OSVR_JointClientOpts opts, const char *path, const char *source); /** @brief Queues up the manual addition of aliases specified in JSON to the path tree. */ OSVR_JOINTCLIENTKIT_EXPORT OSVR_ReturnCode osvrJointClientOptionsAddAliases( OSVR_JointClientOpts opts, const char *aliases); /** @brief Queues up the manual addition of a string element to the path tree. */ OSVR_JOINTCLIENTKIT_EXPORT OSVR_ReturnCode osvrJointClientOptionsAddString( OSVR_JointClientOpts opts, const char *path, const char *s); /** @brief Queues up a trigger for hardware detection. */ OSVR_JOINTCLIENTKIT_EXPORT OSVR_ReturnCode osvrJointClientOptionsTriggerHardwareDetect(OSVR_JointClientOpts opts); /** @} */ /** @brief Initialize the library, starting up a "joint" context that also contains a server. @param applicationIdentifier A null terminated string identifying your application. Reverse DNS format strongly suggested. @param opts The configuration options object for starting the joint server operations. Pass NULL/nullptr for default operation: loading of all autoload-enabled plugins, and a hardware detection. If a valid pointer is passed, the enqueued operations will be performed in-order (the default operations will not be performed). Any exceptions thrown will cause the initialization to fail, returning a null context. @returns Client context - will be needed for subsequent calls */ OSVR_JOINTCLIENTKIT_EXPORT OSVR_ClientContext osvrJointClientInit( const char applicationIdentifier[], OSVR_JointClientOpts opts); /** @} */ OSVR_EXTERN_C_END #endif
41.547264
80
0.756197
[ "object" ]
62cdd9185111630910cabbf3965bb12ad4d15a6a
2,122
h
C
src/scene.h
johsteffens/actinon
7e0a4666adf45898ce653947948b713759322bef
[ "Apache-2.0" ]
1
2020-02-18T15:24:33.000Z
2020-02-18T15:24:33.000Z
src/scene.h
johsteffens/actinon
7e0a4666adf45898ce653947948b713759322bef
[ "Apache-2.0" ]
null
null
null
src/scene.h
johsteffens/actinon
7e0a4666adf45898ce653947948b713759322bef
[ "Apache-2.0" ]
null
null
null
/** Tracing and rendering model */ /** Copyright 2017 Johannes Bernhard Steffens * * 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 SCENE_H #define SCENE_H #include "bcore_std.h" #include "vectors.h" #include "interpreter.h" #include "quicktypes.h" /**********************************************************************************************************************/ // renderer-specific object functions /// color on object's surface cl_s obj_color( vc_t o, v3d_s pos ); /**********************************************************************************************************************/ extern bl_t scene_s_overwrite_output_files_g; extern bl_t scene_s_automatic_recover_g; typedef struct image_cps_s image_cps_s; BCORE_DECLARE_FUNCTIONS_OBJ( image_cps_s ) void image_cps_s_set_size( image_cps_s* o, uz_t w, uz_t h, u2_t v ); tp_t image_cps_s_hash( const image_cps_s* o ); void image_cps_s_write_pnm( const image_cps_s* o, sc_t file ); typedef struct scene_s scene_s; BCORE_DECLARE_FUNCTIONS_OBJ( scene_s ) /// clears light & matter void scene_s_clear( scene_s* o ); /// appends light & matter from object; returns number of atomic objects pushed uz_t scene_s_push( scene_s* o, const sr_s* object ); uz_t scene_s_objects( const scene_s* o ); // number of objects sr_s scene_s_meval_key( sr_s* o, meval_s* ev, tp_t key ); void scene_s_create_image_file( scene_s* o, sc_t file ); /**********************************************************************************************************************/ vd_t scene_signal_handler( const bcore_signal_s* o ); #endif // SCENE_H
33.15625
120
0.628652
[ "object", "model" ]
62d7f7729ba3609aaf32193865181f230b01315a
1,910
h
C
cpp/cpp_include/btreenode.h
fengkx/leetcode
03511a046916d7c0910bb6981e8849c6cc3fe335
[ "Unlicense" ]
null
null
null
cpp/cpp_include/btreenode.h
fengkx/leetcode
03511a046916d7c0910bb6981e8849c6cc3fe335
[ "Unlicense" ]
null
null
null
cpp/cpp_include/btreenode.h
fengkx/leetcode
03511a046916d7c0910bb6981e8849c6cc3fe335
[ "Unlicense" ]
null
null
null
#include <vector> #include <string> #include <sstream> using namespace std; // Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) { } TreeNode(int x) : val(x), left(nullptr), right(nullptr) { } TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) { } }; namespace { TreeNode* build_tree_from_vec(const vector<string>& nodes) noexcept { vector<TreeNode*> vec(nodes.size()); vec[0] = new TreeNode(stoi(nodes[0])); size_t parent_idx = 0; int count = 0; for (size_t i = 1; i < nodes.size(); i++) { if (count == 2) { count = 0; parent_idx++; while (parent_idx < nodes.size() && !vec[parent_idx]) parent_idx++; } if (nodes[i] == "null") { count++; continue; } vec[i] = new TreeNode(stoi(nodes[i])); if (count % 2 == 1) { vec[parent_idx]->right = vec[i]; } else { vec[parent_idx]->left = vec[i]; } count++; } return vec[0]; } } /* https://github.com/grewwc/leetcode_build_tree */ // it is NOT efficient, but does its work // we only new, but don't delete (it has memory leak). // It doesn't matter in this case. // here just copy the string, no string_view or (const) reference TreeNode* build_tree(string nodes) { vector<string> vec; // transform "," & "[" & "]" to empty space transform(cbegin(nodes), cend(nodes), begin(nodes), [](char ch) { if (ch != ',' && ch != '[' && ch != ']') { return ch; }; return ' '; }); // use iss to ignore empty space istringstream iss{ move(nodes) }; string next_word; while (!iss.eof()) { iss >> next_word; if (!next_word.empty()) // avoid push_back trailing empty space vec.push_back(move(next_word)); } return build_tree_from_vec(vec); }
22.470588
89
0.586387
[ "vector", "transform" ]
62dbb8206e30861e42424b6148a66828510e0942
9,239
h
C
Backends/include/gambit/Backends/backend_types/Pythia_8_212/wrapper_UserHooks_def.h
GambitBSM/gambit_2.0
a4742ac94a0352585a3b9dcb9b222048a5959b91
[ "Unlicense" ]
1
2021-09-17T22:53:26.000Z
2021-09-17T22:53:26.000Z
Backends/include/gambit/Backends/backend_types/Pythia_8_212/wrapper_UserHooks_def.h
GambitBSM/gambit_2.0
a4742ac94a0352585a3b9dcb9b222048a5959b91
[ "Unlicense" ]
3
2021-07-22T11:23:48.000Z
2021-08-22T17:24:41.000Z
Backends/include/gambit/Backends/backend_types/Pythia_8_212/wrapper_UserHooks_def.h
GambitBSM/gambit_2.0
a4742ac94a0352585a3b9dcb9b222048a5959b91
[ "Unlicense" ]
1
2021-08-14T10:31:41.000Z
2021-08-14T10:31:41.000Z
#ifndef __wrapper_UserHooks_def_Pythia_8_212_h__ #define __wrapper_UserHooks_def_Pythia_8_212_h__ #include <string> #include <vector> #include "wrapper_Info_decl.h" #include "wrapper_Settings_decl.h" #include "wrapper_ParticleData_decl.h" #include "wrapper_Rndm_decl.h" #include "wrapper_BeamParticle_decl.h" #include "wrapper_CoupSM_decl.h" #include "wrapper_SigmaTotal_decl.h" #include "wrapper_SigmaProcess_decl.h" #include "wrapper_Event_decl.h" #include "wrapper_Particle_decl.h" #include "identification.hpp" namespace CAT_3(BACKENDNAME,_,SAFE_VERSION) { namespace Pythia8 { // Member functions: inline bool UserHooks::initAfterBeams() { return get_BEptr()->initAfterBeams(); } inline bool UserHooks::canModifySigma() { return get_BEptr()->canModifySigma(); } inline bool UserHooks::canBiasSelection() { return get_BEptr()->canBiasSelection(); } inline double UserHooks::biasedSelectionWeight() { return get_BEptr()->biasedSelectionWeight(); } inline bool UserHooks::canVetoProcessLevel() { return get_BEptr()->canVetoProcessLevel(); } inline bool UserHooks::doVetoProcessLevel(Pythia8::Event& arg_1) { return get_BEptr()->doVetoProcessLevel__BOSS(*arg_1.get_BEptr()); } inline bool UserHooks::canVetoResonanceDecays() { return get_BEptr()->canVetoResonanceDecays(); } inline bool UserHooks::doVetoResonanceDecays(Pythia8::Event& arg_1) { return get_BEptr()->doVetoResonanceDecays__BOSS(*arg_1.get_BEptr()); } inline bool UserHooks::canVetoPT() { return get_BEptr()->canVetoPT(); } inline double UserHooks::scaleVetoPT() { return get_BEptr()->scaleVetoPT(); } inline bool UserHooks::doVetoPT(int arg_1, const Pythia8::Event& arg_2) { return get_BEptr()->doVetoPT__BOSS(arg_1, *arg_2.get_BEptr()); } inline bool UserHooks::canVetoStep() { return get_BEptr()->canVetoStep(); } inline int UserHooks::numberVetoStep() { return get_BEptr()->numberVetoStep(); } inline bool UserHooks::doVetoStep(int arg_1, int arg_2, int arg_3, const Pythia8::Event& arg_4) { return get_BEptr()->doVetoStep__BOSS(arg_1, arg_2, arg_3, *arg_4.get_BEptr()); } inline bool UserHooks::canVetoMPIStep() { return get_BEptr()->canVetoMPIStep(); } inline int UserHooks::numberVetoMPIStep() { return get_BEptr()->numberVetoMPIStep(); } inline bool UserHooks::doVetoMPIStep(int arg_1, const Pythia8::Event& arg_2) { return get_BEptr()->doVetoMPIStep__BOSS(arg_1, *arg_2.get_BEptr()); } inline bool UserHooks::canVetoPartonLevelEarly() { return get_BEptr()->canVetoPartonLevelEarly(); } inline bool UserHooks::doVetoPartonLevelEarly(const Pythia8::Event& arg_1) { return get_BEptr()->doVetoPartonLevelEarly__BOSS(*arg_1.get_BEptr()); } inline bool UserHooks::retryPartonLevel() { return get_BEptr()->retryPartonLevel(); } inline bool UserHooks::canVetoPartonLevel() { return get_BEptr()->canVetoPartonLevel(); } inline bool UserHooks::doVetoPartonLevel(const Pythia8::Event& arg_1) { return get_BEptr()->doVetoPartonLevel__BOSS(*arg_1.get_BEptr()); } inline bool UserHooks::canSetResonanceScale() { return get_BEptr()->canSetResonanceScale(); } inline double UserHooks::scaleResonance(int arg_1, const Pythia8::Event& arg_2) { return get_BEptr()->scaleResonance__BOSS(arg_1, *arg_2.get_BEptr()); } inline bool UserHooks::canVetoISREmission() { return get_BEptr()->canVetoISREmission(); } inline bool UserHooks::doVetoISREmission(int arg_1, const Pythia8::Event& arg_2, int arg_3) { return get_BEptr()->doVetoISREmission__BOSS(arg_1, *arg_2.get_BEptr(), arg_3); } inline bool UserHooks::canVetoFSREmission() { return get_BEptr()->canVetoFSREmission(); } inline bool UserHooks::doVetoFSREmission(int arg_1, const Pythia8::Event& arg_2, int arg_3, bool arg_4) { return get_BEptr()->doVetoFSREmission__BOSS(arg_1, *arg_2.get_BEptr(), arg_3, arg_4); } inline bool UserHooks::doVetoFSREmission(int arg_1, const Pythia8::Event& arg_2, int arg_3) { return get_BEptr()->doVetoFSREmission__BOSS(arg_1, *arg_2.get_BEptr(), arg_3); } inline bool UserHooks::canVetoMPIEmission() { return get_BEptr()->canVetoMPIEmission(); } inline bool UserHooks::doVetoMPIEmission(int arg_1, const Pythia8::Event& arg_2) { return get_BEptr()->doVetoMPIEmission__BOSS(arg_1, *arg_2.get_BEptr()); } inline bool UserHooks::canReconnectResonanceSystems() { return get_BEptr()->canReconnectResonanceSystems(); } inline bool UserHooks::doReconnectResonanceSystems(int arg_1, Pythia8::Event& arg_2) { return get_BEptr()->doReconnectResonanceSystems__BOSS(arg_1, *arg_2.get_BEptr()); } inline bool UserHooks::canEnhanceEmission() { return get_BEptr()->canEnhanceEmission(); } inline double UserHooks::enhanceFactor(::std::basic_string<char, std::char_traits<char>, std::allocator<char> > arg_1) { return get_BEptr()->enhanceFactor(arg_1); } inline double UserHooks::vetoProbability(::std::basic_string<char, std::char_traits<char>, std::allocator<char> > arg_1) { return get_BEptr()->vetoProbability(arg_1); } inline void UserHooks::setEnhancedEventWeight(double wt) { get_BEptr()->setEnhancedEventWeight(wt); } inline double UserHooks::getEnhancedEventWeight() { return get_BEptr()->getEnhancedEventWeight(); } inline bool UserHooks::canEnhanceTrial() { return get_BEptr()->canEnhanceTrial(); } inline void UserHooks::setEnhancedTrial(double pTIn, double wtIn) { get_BEptr()->setEnhancedTrial(pTIn, wtIn); } inline double UserHooks::getEnhancedTrialPT() { return get_BEptr()->getEnhancedTrialPT(); } inline double UserHooks::getEnhancedTrialWeight() { return get_BEptr()->getEnhancedTrialWeight(); } inline bool UserHooks::canChangeFragPar() { return get_BEptr()->canChangeFragPar(); } inline bool UserHooks::doVetoFragmentation(Pythia8::Particle arg_1) { return get_BEptr()->doVetoFragmentation__BOSS(*arg_1.get_BEptr()); } // Wrappers for original constructors: inline UserHooks::UserHooks(const Pythia8::UserHooks& arg_1) : WrapperBase(__factory0(arg_1)) { get_BEptr()->set_wptr(this); get_BEptr()->set_delete_wrapper(false); } // Special pointer-based constructor: inline UserHooks::UserHooks(Abstract_UserHooks* in) : WrapperBase(in) { get_BEptr()->set_wptr(this); get_BEptr()->set_delete_wrapper(false); } // Assignment operator: inline UserHooks& UserHooks::operator=(const UserHooks& in) { if (this != &in) { get_BEptr()->pointer_assign__BOSS(in.get_BEptr()); } return *this; } // Destructor: inline UserHooks::~UserHooks() { if (get_BEptr() != 0) { get_BEptr()->set_delete_wrapper(false); if (can_delete_BEptr()) { delete BEptr; BEptr = 0; } } set_delete_BEptr(false); } // Returns correctly casted pointer to Abstract class: inline Abstract_UserHooks* Pythia8::UserHooks::get_BEptr() const { return dynamic_cast<Abstract_UserHooks*>(BEptr); } } } #include "gambit/Backends/backend_undefs.hpp" #endif /* __wrapper_UserHooks_def_Pythia_8_212_h__ */
30.592715
128
0.565104
[ "vector" ]
62e1cad43c56fe9653c750dd643a9c16d473cb01
2,004
h
C
include/levels/lvl_squadsBK.h
DerekSlagle/scrabble
eb17f86b8b897fd8edf3fabc3bd90c1d1016e546
[ "MIT" ]
null
null
null
include/levels/lvl_squadsBK.h
DerekSlagle/scrabble
eb17f86b8b897fd8edf3fabc3bd90c1d1016e546
[ "MIT" ]
null
null
null
include/levels/lvl_squadsBK.h
DerekSlagle/scrabble
eb17f86b8b897fd8edf3fabc3bd90c1d1016e546
[ "MIT" ]
null
null
null
#ifndef LVL_SQUADS_H_INCLUDED #define LVL_SQUADS_H_INCLUDED #include "Level.h" #include "../leg_types/legAdapter.h" #include "../pathUtils.h" #include "../button_types/buttonValOnHit.h" #include "../button_types/controlSurface.h" class squad { public: Leg* pLeg = nullptr; std::vector<impactTarget> ITvec;// adapter object movable + path motion std::vector<sf::CircleShape> circVec;// for inertAdaptVec std::vector<sf::Text> healthMsgVec;// for inertAdaptVec sf::Texture ballTxtB;// for above balls sf::CircleShape circ;// template for vector of balls float startDelay = 0.0f, dtLaunch = 0.0f; float v0 = 0.0f;// launch speed float offX = 0.0f, offY = 0.0f;// offset to path bool anyAlive = true; bool init( std::istream& is, std::vector<Leg*>& PathVec ); squad(){} squad( std::istream& is, std::vector<Leg*>& PathVec ) { init( is, PathVec ); } void update( float dt ); void draw( sf::RenderTarget& RT ) const; }; class lvl_squads : public Level { public: sf::Text wasupMsg; std::vector<Leg*> pathVec; std::vector<squad> squadVec; inertialAdapter flingIA; sf::CircleShape flingBall; float flingMass = 3.0f; sf::Texture ballTxtA;// for above // some ui buttonValOnHit gradStrip, dVelStrip; // motion control on paths controlSurface pathControl; buttonRect pathButt[5];// vel+, vel-, brake, <-, -> sf::CircleShape pathCirc;// color indicates which path is controlled void makePathControl( sf::Vector2f hbPos, sf::Vector2f csPos ); std::vector<squad>::iterator squadIter; float brakeRate = 0.5f, accRate = 0.2f; // functions lvl_squads():Level() { std::cout << "Hello from lvl_squads ctor\n"; } virtual bool init(); virtual bool handleEvent( sf::Event& rEvent ); virtual void update( float dt ); virtual void draw( sf::RenderTarget& RT ) const; void cleanup(); virtual ~lvl_squads() { cleanup(); } }; #endif // LVL_SQUADS_H_INCLUDED
30.363636
82
0.666168
[ "object", "vector" ]
62eecee799be481dc1980a02033ff76dcddd41e3
13,547
h
C
include/pgmlink/pgm_chaingraph.h
chaubold/pgmlink
9dfa90dbd2fdeb026fd0b2837155164c17cb848d
[ "MIT" ]
3
2015-08-06T08:26:07.000Z
2016-07-06T01:11:30.000Z
include/pgmlink/pgm_chaingraph.h
chaubold/pgmlink
9dfa90dbd2fdeb026fd0b2837155164c17cb848d
[ "MIT" ]
null
null
null
include/pgmlink/pgm_chaingraph.h
chaubold/pgmlink
9dfa90dbd2fdeb026fd0b2837155164c17cb848d
[ "MIT" ]
null
null
null
/** @file @ingroup pgm @brief The Chaingraph model. */ #ifndef PGMLINK_PGM_CHAINGRAPH_H #define PGMLINK_PGM_CHAINGRAPH_H #include <algorithm> #include <iterator> #include <map> #include <vector> #include <utility> #include <boost/function.hpp> #include <boost/shared_ptr.hpp> #include <boost/bimap.hpp> #include <opengm/inference/inference.hxx> #include <opengm/inference/lpcplex.hxx> #include "pgmlink/pgm.h" #include "pgmlink/hypotheses.h" #include "pgmlink/feature.h" // Both boost and lemon define the same template ignore_unused_variable_warning<T>. // Using boost templates with lemon types triggers ADL and the (MSVC++) compiler can't // resolve the name. Therefore with explicitly define an overload for the two // involved lemon types in the boost namespace. namespace boost { inline void ignore_unused_variable_warning(const lemon::ListDigraphBase::Node& x) { boost::ignore_unused_variable_warning(x); } inline void ignore_unused_variable_warning(const lemon::ListDigraphBase::Arc& x) { boost::ignore_unused_variable_warning(x); } } namespace pgmlink { namespace pgm { namespace chaingraph { typedef opengm::LPCplex<OpengmModel, opengm::Minimizer> OpengmLPCplex; using boost::function; using std::map; using std::vector; class ModelBuilder; /** @brief Chaingraph model formulated as an Opengm graphical model. Represents an opengm model to solve the matching problem in a HypothesesGraph. Use a chaingraph::ModelBuilder to construct the model. During construction of the chaingraph::Model a random variable is added to the graphical model for every node and every arc in the HypothesesGraph. The mapping between nodes resp. arcs and random variables is stored in the fields node_var and arc_var. A node in the HypothesesGraph describes a detection in the link model. The corresponding random variable determines wether it is an actual object or a misdetection. Similarly, an arc is interpreted as a possible link between two objects whose state is determined by the corresponding random variable. @see chaingraph::ModelBuilder @see HypothesesGraph */ class Model { public: typedef HypothesesGraph::Node node_t; typedef HypothesesGraph::Arc arc_t; typedef OpengmModel::IndexType var_t; typedef boost::bimap<node_t, var_t>::left_map node_var_map; typedef boost::bimap<node_t, var_t>::right_map var_node_map; typedef boost::bimap<arc_t, var_t>::left_map arc_var_map; typedef boost::bimap<arc_t, var_t>::right_map var_arc_map; Model(); Model( shared_ptr<OpengmModel>, const node_var_map&, const arc_var_map& ); shared_ptr<OpengmModel> opengm_model; ///< opengm model usually constructed by chaingraph::ModelBuilder const node_var_map& var_of_node() const; ///< maps nodes to random variables representing detections const var_node_map& node_of_var() const; const arc_var_map& var_of_arc() const; ///< maps arcs to random variables representing links const var_arc_map& arc_of_var() const; var_t var_of_node(node_t) const; var_t var_of_arc(arc_t) const; node_t node_of_var(var_t) const; arc_t arc_of_var(var_t) const; enum VarCategory {node_var, arc_var}; VarCategory var_category(var_t) const; enum WeightType {det_weight, mov_weight, div_weight, app_weight, dis_weight, opp_weight}; map<WeightType, vector<OpengmModel::IndexType> > weight_map; ///< associates events with their corresponding weight ids //void set_weights( WeightType, vector<OpengmModel::ValueType> ); //const vector<OpengmModel::ValueType>& get_weights( WeightType ); private: friend class ModelBuilder; void init(); boost::bimap<node_t, var_t> node_var_; boost::bimap<arc_t, var_t> arc_var_; }; class ModelBuilder { public: ModelBuilder(boost::function<double (const Traxel&)> appearance = ConstantFeature(1000), boost::function<double (const Traxel&)> disappearance = ConstantFeature(1000), boost::function<double (const Traxel&, const Traxel&)> move = SquaredDistance(), double opportunity_cost = 0, double forbidden_cost = 100000) : with_detection_vars_(false), with_divisions_(false), appearance_(appearance), disappearance_(disappearance), move_(move), opportunity_cost_(opportunity_cost), forbidden_cost_(forbidden_cost), cplex_timeout_(1e+75) {} virtual chaingraph::ModelBuilder* clone() const = 0; virtual ~ModelBuilder() {} // mandatory parameters function<double (const Traxel&)> appearance() const { return appearance_; } ModelBuilder& appearance( function<double (const Traxel&)> ); function<double (const Traxel&)> disappearance() const { return disappearance_; } ModelBuilder& disappearance( function<double (const Traxel&)> ); function<double (const Traxel&,const Traxel&)> move() const { return move_; } ModelBuilder& move( function<double (const Traxel&,const Traxel&)> ); double opportunity_cost() const { return opportunity_cost_; } ModelBuilder& opportunity_cost( double c ) { opportunity_cost_ = c; return *this; } double forbidden_cost() const { return forbidden_cost_; } ModelBuilder& forbidden_cost( double c ) { forbidden_cost_ = c; return *this; } //// optional parameters // detection vars ModelBuilder& with_detection_vars( function<double (const Traxel&)> detection=ConstantFeature(10), function<double (const Traxel&)> non_detection=ConstantFeature(200)); ModelBuilder& without_detection_vars(); bool has_detection_vars() const { return with_detection_vars_; } function<double (const Traxel&)> detection() const { return detection_; } function<double (const Traxel&)> non_detection() const { return non_detection_; } // divisions ModelBuilder& with_divisions( function<double (const Traxel&,const Traxel&,const Traxel&)> div = KasterDivision(10) ); ModelBuilder& without_divisions(); bool has_divisions() const { return with_divisions_; } function<double (const Traxel&,const Traxel&,const Traxel&)> division() const { return division_; } // build virtual chaingraph::Model* build( const HypothesesGraph& ) const = 0; // refinement void add_hard_constraints( const Model&, const HypothesesGraph&, OpengmLPCplex& ); void fix_detections( const Model&, const HypothesesGraph&, OpengmLPCplex& ); // cplex parameters void set_cplex_timeout( double seconds ); protected: void add_detection_vars( const HypothesesGraph&, Model& ) const; void add_assignment_vars( const HypothesesGraph&, Model& ) const; vector<OpengmModel::IndexType> vars_for_outgoing_factor( const HypothesesGraph&, const Model&, const HypothesesGraph::Node&) const; vector<OpengmModel::IndexType> vars_for_incoming_factor( const HypothesesGraph&, const Model&, const HypothesesGraph::Node&) const; private: static void couple( const chaingraph::Model&, const HypothesesGraph::Node&, const HypothesesGraph::Arc&, OpengmLPCplex& ); bool with_detection_vars_; bool with_divisions_; function<double (const Traxel&)> detection_; function<double (const Traxel&)> non_detection_; function<double (const Traxel&)> appearance_; function<double (const Traxel&)> disappearance_; function<double (const Traxel&,const Traxel&)> move_; function<double (const Traxel&,const Traxel&,const Traxel&)> division_; double opportunity_cost_; double forbidden_cost_; double cplex_timeout_; }; class TrainableModelBuilder : public chaingraph::ModelBuilder { public: TrainableModelBuilder(boost::function<double (const Traxel&)> appearance = ConstantFeature(1000), boost::function<double (const Traxel&)> disappearance = ConstantFeature(1000), boost::function<double (const Traxel&, const Traxel&)> move = SquaredDistance(), double opportunity_cost = 0, double forbidden_cost = 100000) : chaingraph::ModelBuilder(appearance, disappearance, move, opportunity_cost, forbidden_cost) {} virtual TrainableModelBuilder* clone() const; // build virtual chaingraph::Model* build( const HypothesesGraph& ) const; private: void add_detection_factor( const HypothesesGraph&, Model&, const HypothesesGraph::Node& ) const; void add_outgoing_factor( const HypothesesGraph&, Model&, const HypothesesGraph::Node& ) const; void add_incoming_factor( const HypothesesGraph&, Model&, const HypothesesGraph::Node& ) const; }; class ECCV12ModelBuilder : public chaingraph::ModelBuilder { public: ECCV12ModelBuilder(boost::function<double (const Traxel&)> appearance = ConstantFeature(1000), boost::function<double (const Traxel&)> disappearance = ConstantFeature(1000), boost::function<double (const Traxel&, const Traxel&)> move = SquaredDistance(), double opportunity_cost = 0, double forbidden_cost = 100000) : chaingraph::ModelBuilder(appearance, disappearance, move, opportunity_cost, forbidden_cost) {} virtual ECCV12ModelBuilder* clone() const; // build virtual chaingraph::Model* build( const HypothesesGraph& ) const; private: void add_detection_factor( const HypothesesGraph&, Model&, const HypothesesGraph::Node& ) const; void add_outgoing_factor( const HypothesesGraph&, Model&, const HypothesesGraph::Node& ) const; void add_incoming_factor( const HypothesesGraph&, Model&, const HypothesesGraph::Node& ) const; }; /* class ModelTrainer { */ /* public: */ /* template<class IT1, class IT2, class IT3> */ /* std::vector<OpengmModel::ValueType> train(IT1 samples_begin, IT1 samples_end, IT2 node_labels, IT3 arc_labels) const; */ /* }; */ } /* namespace chaingraph */ } /* namespace pgm */ } /* namespace pgmlink */ /**/ /* implementation */ /**/ #include <boost/ptr_container/ptr_vector.hpp> //#include <pgmlink/ext_opengm/structsvm.hxx> #include <iostream> namespace pgmlink { /* template<class IT1, class IT2, class IT3> */ /* std::vector<pgm::OpengmModel::ValueType> pgm::chaingraph::ModelTrainer::train(IT1 samples_begin, IT1 samples_end, IT2 node_labels, IT3 arc_labels) const { */ /* std::cout << "begin training\n"; */ /* // for each sample: build chaingraph model */ /* boost::ptr_vector<pgm::chaingraph::Model> models; */ /* SquaredDistance move; */ /* ConstantFeature appearance(1); */ /* ConstantFeature disappearance(1); */ /* GeometryDivision2 division(0, 0); */ /* ConstantFeature det(10); */ /* ConstantFeature ndet (200); */ /* pgm::chaingraph::TrainableModelBuilder b; */ /* b.move(move) */ /* .appearance(appearance) */ /* .disappearance(disappearance) */ /* //.opportunity_cost(1) */ /* .forbidden_cost(1000000000) */ /* .without_detection_vars() */ /* .without_divisions() */ /* //.with_detection_vars(det, ndet) */ /* //.with_divisions(division); */ /* ; */ /* for(IT1 sample=samples_begin; sample!=samples_end; ++sample){ */ /* models.push_back(b.build(*sample)); */ /* } */ /* // convert HypothesesGraph labels to OpengmModel labels */ /* IT2 cur_node_labels = node_labels; */ /* IT3 cur_arc_labels = arc_labels; */ /* std::vector<std::vector<pgm::OpengmModel::LabelType> > var_labels(std::distance(samples_begin, samples_end)); */ /* for (int i=0; i < std::distance(samples_begin, samples_end); ++i) { */ /* var_labels[i] = std::vector<pgm::OpengmModel::LabelType>(models[i].opengm_model->numberOfVariables()); */ /* for(pgm::chaingraph::Model::var_t var_idx = 0; var_idx < var_labels[i].size(); ++var_idx) { */ /* switch(models[i].var_category(var_idx)) { */ /* case pgm::chaingraph::Model::node_var: { */ /* pgm::chaingraph::Model::node_t n = models[i].node_of_var(var_idx); */ /* var_labels[i][var_idx] = (*cur_node_labels)[n]; */ /* } break; */ /* case pgm::chaingraph::Model::arc_var: { */ /* pgm::chaingraph::Model::arc_t a = models[i].arc_of_var(var_idx); */ /* var_labels[i][var_idx] = (*cur_arc_labels)[a]; */ /* } break; */ /* default: */ /* throw std::runtime_error("chaingraph::ModelTrainer::train(): unknown var category encountered"); */ /* break; */ /* } */ /* } */ /* ++cur_node_labels; */ /* ++cur_arc_labels; */ /* } */ /* //// train with opengm */ /* // prepare input */ /* std::vector<pgm::OpengmModel> ogm_models; */ /* for(size_t i = 0; i < models.size(); ++i) { */ /* ogm_models.push_back(*(models[i].opengm_model)); */ /* } */ /* opengm::StructSvmDlib<pgm::OpengmModel> svm(ogm_models, var_labels); */ /* svm.set_c(10000); */ /* //svm.set_epsilon(0.00); */ /* std::cout << "svm.get_c(): " << svm.get_c() << "\n"; */ /* std::cout << "svm.get_epsilon(): " << svm.get_epsilon() << "\n"; */ /* vector<pgm::OpengmModel::ValueType> w; */ /* svm.train(w); */ /* return w; */ /* } */ } /* namespace pgmlink */ #endif /* PGMLINK_PGM_CHAINGRAPH_H */
39.961652
164
0.674688
[ "object", "vector", "model" ]
62f3c3cd6f67db120d10d5d9d1c8d37d318fa394
750
h
C
examples/todo/routes/list.h
hugglesfox/firestorm
46685ca3416af3326916653efe4e511e94c92ace
[ "MIT" ]
4
2020-09-08T09:31:58.000Z
2020-09-16T09:28:21.000Z
examples/todo/routes/list.h
hugglesfox/firestorm
46685ca3416af3326916653efe4e511e94c92ace
[ "MIT" ]
4
2020-09-18T15:41:54.000Z
2020-09-28T11:58:59.000Z
examples/todo/routes/list.h
hugglesfox/firestorm
46685ca3416af3326916653efe4e511e94c92ace
[ "MIT" ]
null
null
null
#ifndef TOOD_ROUTE_LIST #define TODO_ROUTE_LIST #include "firestorm.h" #include "../middleware.h" #include "../models.h" // A route to list all the todos class ListTodos : public Route { public: UriArgs uri_args; vector<Todo> *db; ListTodos(vector<Todo> *db) : db(db) {} Outcome middlewares() { return MiddleWares<ListTodos>() .add(new Router<ListTodos>(HTTP_GET_METHOD, {"/todos"})) .outcome(*this); } Response response() { vector<json> json_todos; for (Todo todo : *db) { json_todos.push_back(todo.to_json()); } // Make the returned JSON look a bit nicer json response = create_json(); json_set_array(response, "todos", json_todos); return json_data(response); } }; #endif
20.833333
64
0.656
[ "vector" ]
a8713ef4d0714395ad5e0278688e0e5c5123f9ad
3,340
h
C
d_except.h
deadlocked247/mastermind
f50240022364d1f5b98259885c2cbbcc6dc08273
[ "Unlicense", "MIT" ]
null
null
null
d_except.h
deadlocked247/mastermind
f50240022364d1f5b98259885c2cbbcc6dc08273
[ "Unlicense", "MIT" ]
null
null
null
d_except.h
deadlocked247/mastermind
f50240022364d1f5b98259885c2cbbcc6dc08273
[ "Unlicense", "MIT" ]
null
null
null
#ifndef EXCEPTION_CLASSES #define EXCEPTION_CLASSES #include <strstream> #include <string> using namespace std; //This header contains classes for different Exceptions; //Because there are so many classes and each one is very small, //we put the functions in the header rather then a .cpp file class baseException { public: baseException(const string& str = ""): msgString(str) { if (msgString == "") msgString = "Unspecified exception"; } string what() const { return msgString; } // protected allows a derived class to access msgString. // chapter 13 discusses protected in detail protected: string msgString; }; // failure to allocate memory (new() returns NULL) class memoryAllocationError: public baseException { public: memoryAllocationError(const string& msg = ""): baseException(msg) {} }; // function argument out of proper range class rangeError: public baseException { public: rangeError(const string& msg = ""): baseException(msg) {} }; // index out of range class indexRangeError: public baseException { public: indexRangeError(const string& msg, int i, int size): baseException() { char indexString[80]; ostrstream indexErr(indexString, 80); indexErr << msg << " index " << i << " size = " << size << ends; // indexRangeError can modify msgString, since it is in // the protected section of baseException msgString = indexString; } }; // attempt to erase from an empty container class underflowError: public baseException { public: underflowError(const string& msg = ""): baseException(msg) {} }; // attempt to insert into a full container class overflowError: public baseException { public: overflowError(const string& msg = ""): baseException(msg) {} }; // error in expression evaluation class expressionError: public baseException { public: expressionError(const string& msg = ""): baseException(msg) {} }; // bad object reference class referenceError: public baseException { public: referenceError(const string& msg = ""): baseException(msg) {} }; // feature not implemented class notImplementedError: public baseException { public: notImplementedError(const string& msg = ""): baseException(msg) {} }; // date errors class dateError: public baseException { public: dateError(const string& first, int v, const string& last): baseException() { char dateStr[80]; ostrstream dateErr(dateStr, 80); dateErr << first << ' ' << v << ' ' << last << ends; // dateError can modify msgString, since it is in // the protected section of baseException msgString = dateStr; } }; // error in graph class class graphError: public baseException { public: graphError(const string& msg = ""): baseException(msg) {} }; // file open error class fileOpenError: public baseException { public: fileOpenError(const string& fname): baseException() { char errorStr[80]; ostrstream fileErr(errorStr, 80); fileErr << "Cannot open \"" << fname << "\"" << ends; // fileOpenError can modify msgString, since it is in // the protected section of baseException msgString = errorStr; } }; // error in graph class class fileError: public baseException { public: fileError(const string& msg = ""): baseException(msg) {} }; #endif // EXCEPTION_CLASSES
20.365854
69
0.694311
[ "object" ]
a890c203ff3b2e53c9cfeac8e696de7189a71731
6,974
h
C
edk/Window.h
Edimartin/edk-source
de9a152e91344e201669b0421e5f44dea40cebf9
[ "MIT" ]
null
null
null
edk/Window.h
Edimartin/edk-source
de9a152e91344e201669b0421e5f44dea40cebf9
[ "MIT" ]
null
null
null
edk/Window.h
Edimartin/edk-source
de9a152e91344e201669b0421e5f44dea40cebf9
[ "MIT" ]
null
null
null
#ifndef EDK_WINDOW_h #define EDK_WINDOW_h /* Library C++ Window - Manipulate a window in Edk Game Engine Copyright 2013 Eduardo Moura Sales Martins (edimartin@gmail.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifdef printMessages #warning "Inside Window" #endif #pragma once //View to window #include "ViewController.h" #include "ViewGU.h" #include "Types.h" //Events #include "WindowEvents.h" //EDK WINDOW usa SFML #include <SFML/Window.hpp> #include <SFML/Graphics.hpp> #include <SFML/Window/Mouse.hpp> #ifdef printMessages #warning " Compiling Window" #endif /*LIBS -lsfml-window -lsfml-graphics */ //Classe para gerenciamento de janelas EDK /* WINDOW typeID EDK_WINDOW_BAR EDK_WINDOW_RESIZE EDK_WINDOW_BUTTONS EDK_WINDOW_NOBAR EDK_WINDOW_FULLSCREEN */ namespace edk { class Window { public: Window(); ~Window(); bool createWindow(uint32 width, uint32 height/*, uint32 bitsPerPixel*/, char8 *name, typeID design, uint32 depth, uint32 stencil, uint32 antialiasing); bool createWindow(uint32 width, uint32 height/*, uint32 bitsPerPixel*/, const char *name, typeID design, uint32 depth, uint32 stencil, uint32 antialiasing); bool createWindow(uint32 width, uint32 height/*, uint32 bitsPerPixel*/, char8 *name, typeID design); bool createWindow(uint32 width, uint32 height/*, uint32 bitsPerPixel*/, const char *name, typeID design); bool isOpened(); bool isShowing(); bool haveFocus(); void closeWindow(); void clean(); edk::uint32 getViewCount(); bool addSubview(View *addView); View* getSubview(uint64 n); uint64 getSubviewId(View *subView); void removeSubview(View *subView); void removeAllSubview(); void windowRender(bool show); void showWindow(); void hideWindow(); void mouseRender(bool show); void showMouse(); void hideMouse(); bool setMousePosition(vec2i32 pos); bool setMousePosition(int32 x, int32 y); bool setWindowPosition(vec2i32 pos); bool setWindowPosition(int32 x, int32 y); bool setWindowSize(size2ui32 size); bool setWindowSize(uint32 width, uint32 height); //Update the views void updateViews(); bool drawStart(); bool drawEnd(); void drawView(); bool flip(); bool render(); size2ui32 getSize(); size2ui32 getScreenSize(); uint32 getWidth(); uint32 getHeight(); vec2i32 getMousePos(); vec2i32 eventGetMouseMoved(); bool eventLostFocus(); bool eventGainedFocus(); bool eventButtonClose(); bool eventKeyPressed(); bool eventKeyRelease(); bool eventKeyHolded(); uint32 eventGetKeyPressedSize(); uint32 eventGetKeyReleaseSize(); uint32 eventGetKeyHoldedSize(); uint32 eventGetKeyPressed(uint32 pos); uint32 eventGetKeyRelease(uint32 pos); uint32 eventGetKeyHolded(uint32 pos); bool eventMousePressed(); bool eventMouseRelease(); bool eventMouseHolded(); uint8 eventGetMousePressedSize(); uint8 eventGetMouseReleaseSize(); uint8 eventGetMouseHoldedSize(); uint8 eventGetMousePressed(uint32 pos); uint8 eventGetMouseRelease(uint32 pos); uint8 eventGetMouseHolded(uint32 pos); bool eventMouseEnter(); bool eventMouseExit(); bool eventMouseMoved(); int8 getMouseScrollWheel(); bool eventResizeWindow(); size2i32 getResize(); bool loadEvents(); static size2ui32 getDesktopSize(); static uint32 getDesktopBitsPerPixel(); //test if have a controller static bool haveController(edk::uint32 controller); //return the number of buttons of a controller static edk::uint32 getControllerButtonCount(edk::uint32 controller); bool eventControllerButtonPressed(edk::uint32 controller); bool eventControllerButtonRelease(edk::uint32 controller); bool eventControllerButtonHolded(edk::uint32 controller); bool eventControllerAxisMoved(edk::uint32 controller); uint8 eventGetControllerButtonPressedSize(edk::uint32 controller); uint8 eventGetControllerButtonReleaseSize(edk::uint32 controller); uint8 eventGetControllerButtonHoldedSize(edk::uint32 controller); uint8 eventGetControllerAxisMovedSize(edk::uint32 controller); uint8 eventGetControllerButtonPressed(edk::uint32 controller, uint32 pos); uint8 eventGetControllerButtonRelease(edk::uint32 controller, uint32 pos); uint8 eventGetControllerButtonHolded(edk::uint32 controller, uint32 pos); uint32 eventGetControllerAxisIDMoved(edk::uint32 controller, uint32 pos); float32 eventGetControllerAxisMoved(edk::uint32 controller, uint32 pos); float32 eventGetControllerAxisMovedByID(edk::uint32 controller, uint32 id); public: color3f32 cleanColor; // private: //update the viewGU void updateView(edk::View* viewGU); //contactView void mousePressView(edk::ViewController* view, edk::vec2i32 point, edk::vector::Stack<edk::uint32> buttons); void mouseReleaseView(edk::ViewController* view, edk::vec2i32 point, edk::vector::Stack<edk::uint32> buttons); //Atualiza o tamanho da view void updateViewSize(); void cleanEvents(); //update joystick events void updateControllerEvents(); //save focus bool windowFocus; //saveMouseinside bool mouseInside; //save the mousePosition edk::vec2i32 saveMousePos; //janela SFML sf::RenderWindow window; //sf::Window window; //View principal edk::ViewController viewWindow; //renderiza o mouse na tela bool renderMouse; //renderiza a window na tela bool renderWindow; //Guarda se o render da janela esta ativo bool activeRender; //save the size of the window edk::size2ui32 windowSize; edk::WindowEvents events; }; } /* End of namespace edk */ #endif // edk_Window_h
23.640678
160
0.716375
[ "render", "vector" ]
a893b089e8004453bae39fd0f3a40b2593652b17
3,301
h
C
include/math/maths_funcs.h
tobiasbu/raytracer
bc1db0c6aea504b2dc59520fe6245d523fb11ffa
[ "MIT" ]
3
2018-04-13T05:40:11.000Z
2022-01-03T14:43:17.000Z
include/math/maths_funcs.h
tobiasbu/raytracer
bc1db0c6aea504b2dc59520fe6245d523fb11ffa
[ "MIT" ]
2
2017-08-23T19:57:02.000Z
2018-03-06T12:47:40.000Z
include/math/maths_funcs.h
tobiasbu/raytracer
bc1db0c6aea504b2dc59520fe6245d523fb11ffa
[ "MIT" ]
null
null
null
/******************************************************************************\ | OpenGL 4 Example Code. | | Accompanies written series "Anton's OpenGL 4 Tutorials" | | Email: anton at antongerdelan dot net | | First version 27 Jan 2014 | | Copyright Dr Anton Gerdelan, Trinity College Dublin, Ireland. | | See individual libraries' separate legal notices | |******************************************************************************| | Commonly-used maths structures and functions | | Simple-as-possible. No templates. Not optimised. | | Structs vec3, mat4, versor. just hold arrays of floats called "v","m","q", | | respectively. So, for example, to get values from a mat4 do: my_mat.m | | A versor is the proper name for a unit quaternion. | | This is C++ because it's sort-of convenient to be able to use maths operators| \******************************************************************************/ #ifndef _MATHS_FUNCS_H_ #define _MATHS_FUNCS_H_ #include "mat3.h" #include "math/mat4.h" #include "math/vec4.h" #include "math/vec3.h" #include "math/vec2.h" // const used to convert degrees into radians //#define M_PI 3.14159265359 #define TAU 2.0 * M_PI #define ONE_DEG_IN_RAD (2.0 * M_PI) / 360.0 // 0.017444444 #define ONE_RAD_IN_DEG 360.0 / (2.0 * M_PI) //57.2957795 /* stored like this: 0 4 8 12 1 5 9 13 2 6 10 14 3 7 11 15*/ struct versor { versor(); versor operator/ (float rhs); versor operator* (float rhs); versor operator* (const versor& rhs); versor operator+ (const versor& rhs); float q[4]; }; void print(const vec3& v); void print(const vec4& v); void print(const mat3& m); void print(const mat4& m); // vector functions float length(const vec3& v); float length2(const vec3& v); vec3 normalise(const vec3& v); float dot(const vec3& a, const vec3& b); vec3 cross(const vec3& a, const vec3& b); float get_squared_dist(vec3 from, vec3 to); float direction_to_heading(vec3 d); vec3 heading_to_direction(float degrees); // matrix functions mat3 zero_mat3(); mat3 identity_mat3(); /*mat4 zero_mat4(); mat4 identity_mat4(); float determinant(const mat4& mm); mat4 inverse(const mat4& mm); mat4 transpose(const mat4& mm); // affine functions mat4 translate(const mat4& m, const vec3& v); mat4 rotate_x_deg(const mat4& m, float deg); mat4 rotate_y_deg(const mat4& m, float deg); mat4 rotate_z_deg(const mat4& m, float deg); mat4 scale(const mat4& m, const vec3& v); // camera functions mat4 look_at(const vec3& cam_pos, vec3 targ_pos, const vec3& up); mat4 perspective(float fovy, float aspect, float near, float far);*/ // quaternion functions versor quat_from_axis_rad(float radians, float x, float y, float z); versor quat_from_axis_deg(float degrees, float x, float y, float z); mat4 quat_to_mat4(const versor& q); float dot(const versor& q, const versor& r); versor slerp(const versor& q, const versor& r); // overloading wouldn't let me use const versor normalise(versor& q); void print(const versor& q); versor slerp(versor& q, versor& r, float t); #endif
37.511364
80
0.610118
[ "vector" ]
a896e691ead7dd94bca2f8550bf7f73f0bc58665
769
h
C
Project1/Src/Card.h
yokamonian/Skull_Random_Defence
0b9918887d3676b8b56132a6e542494dfcb052bb
[ "Unlicense" ]
null
null
null
Project1/Src/Card.h
yokamonian/Skull_Random_Defence
0b9918887d3676b8b56132a6e542494dfcb052bb
[ "Unlicense" ]
null
null
null
Project1/Src/Card.h
yokamonian/Skull_Random_Defence
0b9918887d3676b8b56132a6e542494dfcb052bb
[ "Unlicense" ]
null
null
null
#pragma once #include "GameNode.h" class Card : public GameNode { /// <summary> /// Card : 게임 내 스컬을 구매하기 위한 UI 중 하나의 클래스. /// 인게임 재화인 골드를 통해 구매하거나 섞는 등의 함수가 담겨있다. /// </summary> private: RECT card; POINT pos; int skullId; int price; int currFrameX; int currFrameY; Image* img; public: virtual HRESULT Init(); HRESULT Init(POINT pos); virtual void Release(); virtual void Render(HDC hdc); int GetPrice() { return price; } RECT GetCardRect() { return card; } void PerchaseCard(); void RerollCard(); void SetCurrFrameY(int _currFrameY) { currFrameY = _currFrameY; } void SetPos(POINT _pos) { pos.x = _pos.x; pos.y = _pos.y; } void ShuffleCard(int skullId); int GetSkullId() { return skullId; } int GetCurrFrameY() { return currFrameY; } };
21.361111
66
0.680104
[ "render" ]
a8a349d64f86bf620f2c77e6c200785af9871806
103,400
c
C
lib/psabpf_table.c
P4-Research/psabpf
55d647c2c27d5c26b5ed662e3c9519bbe0a6741b
[ "Apache-2.0" ]
1
2022-02-08T08:13:38.000Z
2022-02-08T08:13:38.000Z
lib/psabpf_table.c
P4-Research/psabpf
55d647c2c27d5c26b5ed662e3c9519bbe0a6741b
[ "Apache-2.0" ]
18
2022-01-15T07:43:05.000Z
2022-03-24T11:49:42.000Z
lib/psabpf_table.c
P4-Research/psabpf
55d647c2c27d5c26b5ed662e3c9519bbe0a6741b
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2022 Orange * Copyright 2022 Warsaw University of Technology * * 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 <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <bpf/bpf.h> #include <bpf/btf.h> #include <linux/bpf.h> #include <linux/btf.h> #include <psabpf.h> #include "btf.h" #include "common.h" #include "psabpf_table.h" #include "psabpf_counter.h" #include "psabpf_meter.h" void psabpf_table_entry_ctx_init(psabpf_table_entry_ctx_t *ctx) { if (ctx == NULL) return; memset(ctx, 0, sizeof(psabpf_table_entry_ctx_t)); /* 0 is a valid file descriptor */ ctx->table.fd = -1; ctx->default_entry.fd = -1; ctx->btf_metadata.associated_prog = -1; ctx->prefixes.fd = -1; ctx->tuple_map.fd = -1; ctx->cache.fd = -1; psabpf_table_entry_init(&ctx->current_entry); } void psabpf_table_entry_ctx_free(psabpf_table_entry_ctx_t *ctx) { if (ctx == NULL) return; free_btf(&ctx->btf_metadata); close_object_fd(&(ctx->table.fd)); close_object_fd(&(ctx->default_entry.fd)); close_object_fd(&(ctx->prefixes.fd)); close_object_fd(&(ctx->tuple_map.fd)); close_object_fd(&(ctx->cache.fd)); if (ctx->direct_counters_ctx != NULL) { for (unsigned i = 0; i < ctx->n_direct_counters; i++) psabpf_direct_counter_ctx_free(&ctx->direct_counters_ctx[i]); free(ctx->direct_counters_ctx); ctx->direct_counters_ctx = NULL; } ctx->n_direct_counters = 0; if (ctx->direct_meters_ctx != NULL) { for (unsigned i = 0; i < ctx->n_direct_meters; i++) psabpf_direct_meter_ctx_free(&ctx->direct_meters_ctx[i]); free(ctx->direct_meters_ctx); ctx->direct_meters_ctx = NULL; } ctx->n_direct_meters = 0; free_struct_field_descriptor_set(&ctx->table_implementations); free_struct_field_descriptor_set(&ctx->table_implementation_group_marks); if (ctx->current_raw_key == NULL) free(ctx->current_raw_key); ctx->current_raw_key = NULL; psabpf_table_entry_free(&ctx->current_entry); } static uint32_t get_table_value_type_id(psabpf_table_entry_ctx_t *ctx) { return psabtf_get_member_type_id_by_name(ctx->btf_metadata.btf, ctx->table.btf_type_id, "value"); } static int get_value_type(psabpf_table_entry_ctx_t *ctx, const struct btf_type **value_type) { uint32_t value_type_id = get_table_value_type_id(ctx); if (value_type_id == 0) return ENOENT; *value_type = psabtf_get_type_by_id(ctx->btf_metadata.btf, value_type_id); if (value_type == NULL) return EPERM; if (btf_kind(*value_type) != BTF_KIND_STRUCT) { fprintf(stderr, "expected struct as a map value\n"); return EPERM; } return NO_ERROR; } static bool member_is_direct_or_implementation_object(psabpf_btf_t *btf, const struct btf_member *member, const char **name, const char **type_name) { *name = btf__name_by_offset(btf->btf, member->name_off); if (*name == NULL) return false; if (strcmp(*name, "u") == 0) return false; const struct btf_type *type = psabtf_get_type_by_id(btf->btf, member->type); if (type == NULL) return false; *type_name = btf__name_by_offset(btf->btf, type->name_off); if (*type_name == NULL) return false; if (strcmp(*type_name, "bpf_spin_lock") == 0) return false; if (btf_is_int(type)) { /* treat ActionSelector and ActionProfile references as a direct object */ if (str_ends_with(*name, "_ref") || str_ends_with(*name, "_key")) return true; } if (!btf_is_struct(type)) return false; return true; } static int count_direct_objects(psabpf_table_entry_ctx_t *ctx) { if (ctx->btf_metadata.btf == NULL || ctx->table.btf_type_id == 0) return NO_ERROR; const struct btf_type *value_type; int ret = get_value_type(ctx, &value_type); if (ret != NO_ERROR) return ret; unsigned entries = btf_vlen(value_type); const struct btf_member *member = btf_members(value_type); for (unsigned i = 0; i < entries; i++, member++) { const char *member_name = NULL; const char *member_type_name = NULL; if (!member_is_direct_or_implementation_object(&ctx->btf_metadata, member, &member_name, &member_type_name)) continue; size_t member_size = psabtf_get_type_size_by_id(ctx->btf_metadata.btf, member->type); psabpf_counter_type_t counter_type = get_counter_type(&ctx->btf_metadata, member->type); if (counter_type != PSABPF_COUNTER_TYPE_UNKNOWN) { /* DirectCounter */ ctx->n_direct_counters += 1; } else if (strcmp(member_type_name, "meter_value") == 0 && member_size == DIRECT_METER_SIZE) { /* DirectMeter */ ctx->n_direct_meters += 1; } else if (str_ends_with(member_name, "_ref") || str_ends_with(member_name, "_key")) { /* ActionSelector or ActionProfile, skip group mark */ if (str_ends_with(member_name, "_is_group_ref")) continue; ctx->table_implementations.n_fields += 1; } else { fprintf(stderr, "%s: unknown type direct object instance, ignored\n", member_name); continue; } } return NO_ERROR; } static void try_find_group_mark_for_table_impl(psabpf_table_entry_ctx_t *ctx, unsigned table_impl_id) { char expected_name[256]; psabtf_struct_member_md_t md; uint32_t value_type_id = get_table_value_type_id(ctx); if (value_type_id == 0) return; snprintf(expected_name, sizeof(expected_name), "%s_is_group_ref", ctx->table_implementations.fields[table_impl_id].name); if (psabtf_get_member_md_by_name(ctx->btf_metadata.btf, value_type_id, expected_name, &md) != NO_ERROR) return; size_t size = psabtf_get_type_size_by_id(ctx->btf_metadata.btf, md.effective_type_id); if (size != sizeof(uint32_t)) return; ctx->table_implementation_group_marks.fields[table_impl_id].name = NULL; ctx->table_implementation_group_marks.fields[table_impl_id].type = PSABPF_STRUCT_FIELD_TYPE_DATA; ctx->table_implementation_group_marks.fields[table_impl_id].data_offset = md.bit_offset / 8; ctx->table_implementation_group_marks.fields[table_impl_id].data_len = size; } static int init_direct_objects_context(psabpf_table_entry_ctx_t *ctx) { if (ctx->btf_metadata.btf == NULL || ctx->table.btf_type_id == 0) return NO_ERROR; const struct btf_type *value_type; int ret = get_value_type(ctx, &value_type); if (ret != NO_ERROR) return ret; unsigned entries = btf_vlen(value_type); const struct btf_member *member = btf_members(value_type); unsigned current_counter = 0; unsigned current_meter = 0; unsigned current_table_impl = 0; for (unsigned i = 0; i < entries; i++, member++) { const char *member_name = NULL; const char *member_type_name = NULL; if (!member_is_direct_or_implementation_object(&ctx->btf_metadata, member, &member_name, &member_type_name)) continue; size_t member_size = psabtf_get_type_size_by_id(ctx->btf_metadata.btf, member->type); size_t member_offset = btf_member_bit_offset(value_type, i) / 8; psabpf_counter_type_t counter_type = get_counter_type(&ctx->btf_metadata, member->type); if (counter_type != PSABPF_COUNTER_TYPE_UNKNOWN) { psabpf_direct_counter_ctx_init(&ctx->direct_counters_ctx[current_counter]); ctx->direct_counters_ctx[current_counter].name = strdup(member_name); ctx->direct_counters_ctx[current_counter].counter_type = counter_type; ctx->direct_counters_ctx[current_counter].counter_offset = member_offset; ctx->direct_counters_ctx[current_counter].counter_size = member_size; ctx->direct_counters_ctx[current_counter].counter_idx = current_counter; if (ctx->direct_counters_ctx[current_counter].name == NULL) return ENOMEM; ++current_counter; } else if (strcmp(member_type_name, "meter_value") == 0 && member_size == DIRECT_METER_SIZE) { psabpf_direct_meter_ctx_init(&ctx->direct_meters_ctx[current_meter]); ctx->direct_meters_ctx[current_meter].name = strdup(member_name); ctx->direct_meters_ctx[current_meter].meter_offset = member_offset; ctx->direct_meters_ctx[current_meter].meter_size = member_size; ctx->direct_meters_ctx[current_meter].meter_idx = current_meter; if (ctx->direct_meters_ctx[current_meter].name == NULL) return ENOMEM; ++current_meter; } else if (str_ends_with(member_name, "_ref") || str_ends_with(member_name, "_key")) { if (!str_ends_with(member_name, "_is_group_ref")) { char *tbl_impl_name = strdup(member_name); ctx->table_implementations.fields[current_table_impl].data_offset = member_offset; ctx->table_implementations.fields[current_table_impl].data_len = member_size; ctx->table_implementations.fields[current_table_impl].type = PSABPF_STRUCT_FIELD_TYPE_DATA; if (tbl_impl_name == NULL) return ENOMEM; /* Now name contains suffix "_ref" or "_key", remove it. */ unsigned len = strlen(tbl_impl_name); tbl_impl_name[len - 4] = '\0'; ctx->table_implementations.fields[current_table_impl].name = tbl_impl_name; try_find_group_mark_for_table_impl(ctx, current_table_impl); current_table_impl++; } } } return NO_ERROR; } static int init_direct_objects(psabpf_table_entry_ctx_t *ctx) { if (ctx->btf_metadata.btf == NULL || ctx->table.btf_type_id == 0) { fprintf(stderr, "unable to handle direct objects; resetting them if exist\n"); return NO_ERROR; } int ret = count_direct_objects(ctx); if (ret != NO_ERROR) return ret; if (ctx->n_direct_counters > 0) { ctx->direct_counters_ctx = malloc(ctx->n_direct_counters * sizeof(psabpf_direct_counter_context_t)); if (ctx->direct_counters_ctx == NULL) return ENOMEM; } if (ctx->n_direct_meters > 0) { ctx->direct_meters_ctx = malloc(ctx->n_direct_meters * sizeof(psabpf_direct_meter_context_t)); if (ctx->direct_meters_ctx == NULL) { /* Avoid memory corruption */ if (ctx->direct_counters_ctx != NULL) free(ctx->direct_counters_ctx); ctx->direct_counters_ctx = NULL; return ENOMEM; } } if (ctx->table_implementations.n_fields > 0) { /* TODO: here mark table as indirect instead of finding union 'u'? */ ctx->table_implementations.fields = calloc(ctx->table_implementations.n_fields, sizeof(psabpf_struct_field_descriptor_t)); ctx->table_implementation_group_marks.n_fields = ctx->table_implementations.n_fields; ctx->table_implementation_group_marks.fields = calloc(ctx->table_implementation_group_marks.n_fields, sizeof(psabpf_struct_field_descriptor_t)); if (ctx->table_implementations.fields == NULL || ctx->table_implementation_group_marks.fields == NULL) { if (ctx->direct_counters_ctx != NULL) free(ctx->direct_counters_ctx); if (ctx->direct_meters_ctx != NULL) free(ctx->direct_meters_ctx); ctx->direct_counters_ctx = NULL; ctx->direct_meters_ctx = NULL; return ENOMEM; } } return init_direct_objects_context(ctx); } static int open_ternary_table(psabpf_context_t *psabpf_ctx, psabpf_table_entry_ctx_t *ctx, const char *name) { int ret; char derived_name[256]; snprintf(derived_name, sizeof(derived_name), "%s_prefixes", name); ret = open_bpf_map(psabpf_ctx, derived_name, &ctx->btf_metadata, &ctx->prefixes); if (ret != NO_ERROR) { fprintf(stderr, "couldn't open map %s: %s\n", derived_name, strerror(ret)); return ret; } snprintf(derived_name, sizeof(derived_name), "%s_tuples_map", name); ret = open_bpf_map(psabpf_ctx, derived_name, &ctx->btf_metadata, &ctx->tuple_map); if (ret != NO_ERROR) { fprintf(stderr, "couldn't open map %s: %s\n", derived_name, strerror(ret)); return ret; } snprintf(derived_name, sizeof(derived_name), "%s_tuple", name); ret = open_bpf_map(psabpf_ctx, derived_name, &ctx->btf_metadata, &ctx->table); close_object_fd(&(ctx->table.fd)); /* We need only metadata from this map */ if (ret != NO_ERROR) { fprintf(stderr, "couldn't open map %s: %s\n", derived_name, strerror(ret)); return ret; } ctx->is_ternary = true; return NO_ERROR; } int psabpf_table_entry_ctx_tblname(psabpf_context_t *psabpf_ctx, psabpf_table_entry_ctx_t *ctx, const char *name) { if (ctx == NULL || psabpf_ctx == NULL || name == NULL) return EINVAL; /* get the BTF, it is optional so print only warning */ if (load_btf(psabpf_ctx, &ctx->btf_metadata) != NO_ERROR) fprintf(stderr, "warning: couldn't find BTF info\n"); int ret = open_bpf_map(psabpf_ctx, name, &ctx->btf_metadata, &ctx->table); /* if map does not exist, try the ternary table */ if (ret == ENOENT) ret = open_ternary_table(psabpf_ctx, ctx, name); if (ret != NO_ERROR) { fprintf(stderr, "couldn't open table %s: %s\n", name, strerror(ret)); return ret; } /* TODO: detect if value type contains "u" union and then threat table as direct; * in other case as an indirect table (e.g. ActionProfile or ActionSelector). * This may require changes in API */ /* Open map with default entry, ignore error(s), because map is optional */ char map_name[256]; snprintf(map_name, sizeof(map_name), "%s_defaultAction", name); open_bpf_map(psabpf_ctx, map_name, &ctx->btf_metadata, &ctx->default_entry); /* open cache table, this is optional feature for table*/ snprintf(map_name, sizeof(map_name), "%s_cache", name); ret = open_bpf_map(psabpf_ctx, map_name, &ctx->btf_metadata, &ctx->cache); if (ret == NO_ERROR) fprintf(stderr, "found cache for table: %s\n", name); ret = init_direct_objects(ctx); if (ret != NO_ERROR) { fprintf(stderr, "failed to initialize direct objects: %s\n", strerror(ret)); return ret; } return NO_ERROR; } void psabpf_table_entry_ctx_mark_indirect(psabpf_table_entry_ctx_t *ctx) { if (ctx == NULL) return; ctx->is_indirect = true; } bool psabpf_table_entry_ctx_is_indirect(psabpf_table_entry_ctx_t *ctx) { if (ctx == NULL) return false; return ctx->is_indirect; } bool psabpf_table_entry_ctx_has_priority(psabpf_table_entry_ctx_t *ctx) { if (ctx == NULL) return false; return ctx->is_ternary; } void psabpf_table_entry_init(psabpf_table_entry_t *entry) { if (entry == NULL) return; memset(entry, 0, sizeof(psabpf_table_entry_t)); psabpf_matchkey_init(&entry->current_match_key); psabpf_direct_counter_ctx_init(&entry->current_direct_counter_ctx); psabpf_direct_meter_ctx_init(&entry->current_direct_meter_ctx); } void psabpf_table_entry_free(psabpf_table_entry_t *entry) { if (entry == NULL) return; /* free match keys */ for (size_t i = 0; i < entry->n_keys; i++) { psabpf_matchkey_free(entry->match_keys[i]); } if (entry->match_keys) free(entry->match_keys); entry->match_keys = NULL; entry->n_keys = 0; /* free action data */ if (entry->action != NULL) { psabpf_action_free(entry->action); free(entry->action); entry->action = NULL; } /* free DirectCounter instances */ if (entry->direct_counters != NULL) { for (unsigned i = 0; i < entry->n_direct_counters; i++) psabpf_counter_entry_free(&entry->direct_counters[i].counter); free(entry->direct_counters); } entry->direct_counters = NULL; entry->n_direct_counters = 0; /* free DirectMeter instances */ if (entry->direct_meters != NULL) { for (unsigned i = 0; i < entry->n_direct_meters; i++) psabpf_meter_entry_free(&entry->direct_meters[i].meter); free(entry->direct_meters); } entry->direct_meters = NULL; entry->n_direct_meters = 0; /* Iterators */ psabpf_matchkey_free(&entry->current_match_key); psabpf_action_param_free(&entry->current_action_param); psabpf_direct_counter_ctx_free(&entry->current_direct_counter_ctx); psabpf_direct_meter_ctx_free(&entry->current_direct_meter_ctx); } /* can be invoked multiple times */ int psabpf_table_entry_matchkey(psabpf_table_entry_t *entry, psabpf_match_key_t *mk) { if (entry == NULL || mk == NULL) return EINVAL; if (mk->data == NULL) return ENODATA; if (mk->type == PSABPF_LPM) { for (size_t i = 0; i < entry->n_keys; ++i) { if (entry->match_keys[i]->type == PSABPF_LPM) { fprintf(stderr, "only one LPM key is allowed\n"); return EPERM; } } } size_t new_size = (entry->n_keys + 1) * sizeof(psabpf_match_key_t *); psabpf_match_key_t ** tmp = malloc(new_size); psabpf_match_key_t * new_mk = malloc(sizeof(psabpf_match_key_t)); if (tmp == NULL || new_mk == NULL) { if (tmp != NULL) free(tmp); if (new_mk != NULL) free(new_mk); return ENOMEM; } if (entry->n_keys != 0) { memcpy(tmp, entry->match_keys, (entry->n_keys) * sizeof(psabpf_match_key_t *)); } if (entry->match_keys != NULL) free(entry->match_keys); entry->match_keys = tmp; memcpy(new_mk, mk, sizeof(psabpf_match_key_t)); entry->match_keys[entry->n_keys] = new_mk; /* stole data from mk to new_mk */ mk->data = NULL; if (mk->type == PSABPF_TERNARY) mk->u.ternary.mask = NULL; entry->n_keys += 1; return NO_ERROR; } psabpf_match_key_t *psabpf_table_entry_get_next_matchkey(psabpf_table_entry_t *entry) { if (entry == NULL) return NULL; if (entry->current_match_key_id >= entry->n_keys) { entry->current_match_key_id = 0; return NULL; } memcpy(&entry->current_match_key, entry->match_keys[entry->current_match_key_id], sizeof(psabpf_match_key_t)); entry->current_match_key.mem_can_be_freed = false; entry->current_match_key_id += 1; return &entry->current_match_key; } void move_action(psabpf_action_t *dst, psabpf_action_t *src) { if (dst == NULL || src == NULL) return; /* stole action data from src */ memcpy(dst, src, sizeof(psabpf_action_t)); src->params = NULL; src->n_params = 0; } void psabpf_table_entry_action(psabpf_table_entry_t *entry, psabpf_action_t *act) { if (entry == NULL || act == NULL) return; if (entry->action != NULL) return; entry->action = malloc(sizeof(psabpf_action_t)); if (entry->action == NULL) return; move_action(entry->action, act); } /* only for ternary */ void psabpf_table_entry_priority(psabpf_table_entry_t *entry, const uint32_t priority) { if (entry == NULL) return; entry->priority = priority; } uint32_t psabpf_table_entry_get_priority(psabpf_table_entry_t *entry) { if (entry == NULL) return 0; return entry->priority; } void psabpf_matchkey_init(psabpf_match_key_t *mk) { if (mk == NULL) return; memset(mk, 0, sizeof(psabpf_match_key_t)); mk->mem_can_be_freed = true; } void psabpf_matchkey_free(psabpf_match_key_t *mk) { if (mk == NULL) return; if (mk->data != NULL && mk->mem_can_be_freed == true) free(mk->data); mk->data = NULL; if (mk->type == PSABPF_TERNARY) { if (mk->u.ternary.mask != NULL && mk->mem_can_be_freed == true) free(mk->u.ternary.mask); mk->u.ternary.mask = NULL; } } void psabpf_matchkey_type(psabpf_match_key_t *mk, enum psabpf_matchkind_t type) { if (mk == NULL) return; mk->type = type; } int psabpf_matchkey_data(psabpf_match_key_t *mk, const char *data, size_t size) { if (mk == NULL || data == NULL) return EINVAL; if (mk->data != NULL) return EEXIST; mk->data = malloc(size); if (mk->data == NULL) return ENOMEM; memcpy(mk->data, data, size); mk->key_size = size; return NO_ERROR; } enum psabpf_matchkind_t psabpf_matchkey_get_type(psabpf_match_key_t *mk) { if (mk == NULL) return PSABPF_EXACT; return mk->type; } const void *psabpf_matchkey_get_data(psabpf_match_key_t *mk) { if (mk == NULL) return NULL; return mk->data; } size_t psabpf_matchkey_get_data_size(psabpf_match_key_t *mk) { if (mk == NULL) return 0; return mk->key_size; } /* only for lpm */ int psabpf_matchkey_prefix_len(psabpf_match_key_t *mk, uint32_t prefix) { if (mk == NULL) return EINVAL; if (mk->type != PSABPF_LPM) return EINVAL; mk->u.lpm.prefix_len = prefix; return NO_ERROR; } /* only for lpm */ uint32_t psabpf_matchkey_get_prefix_len(psabpf_match_key_t *mk) { if (mk == NULL) return 0; if (mk->type != PSABPF_LPM) return 0; return mk->u.lpm.prefix_len; } /* only for ternary */ int psabpf_matchkey_mask(psabpf_match_key_t *mk, const char *mask, size_t size) { if (mk == NULL || mask == NULL) return EINVAL; if (mk->type != PSABPF_TERNARY) return EINVAL; if (mk->u.ternary.mask != NULL) return EEXIST; mk->u.ternary.mask_size = size; mk->u.ternary.mask = malloc(size); if (mk->u.ternary.mask == NULL) return ENOMEM; memcpy(mk->u.ternary.mask, mask, size); return NO_ERROR; } /* only for ternary */ const void *psabpf_matchkey_get_mask(psabpf_match_key_t *mk) { if (mk == NULL) return NULL; if (mk->type != PSABPF_TERNARY) return NULL; return mk->u.ternary.mask; } /* only for ternary */ size_t psabpf_matchkey_get_mask_size(psabpf_match_key_t *mk) { if (mk == NULL) return 0; if (mk->type != PSABPF_TERNARY) return 0; return mk->u.ternary.mask_size; } /* only for 'range' match */ int psabpf_matchkey_start(psabpf_match_key_t *mk, uint64_t start) { (void) mk; (void) start; return NO_ERROR; } /* only for 'range' match */ int psabpf_matchkey_end(psabpf_match_key_t *mk, uint64_t end) { (void) mk; (void) end; return NO_ERROR; } int psabpf_action_param_create(psabpf_action_param_t *param, const char *data, size_t size) { if (param == NULL || data == NULL) return EINVAL; param->is_group_reference = false; param->mem_can_be_freed = true; param->len = size; if (size == 0) { param->data = NULL; return NO_ERROR; } param->data = malloc(size); if (param->data == NULL) return ENOMEM; memcpy(param->data, data, size); return NO_ERROR; } void psabpf_action_param_free(psabpf_action_param_t *param) { if (param == NULL) return; if (param->data != NULL && param->mem_can_be_freed == true) free(param->data); param->data = NULL; } void psabpf_action_param_mark_group_reference(psabpf_action_param_t *param) { if (param == NULL) return; param->is_group_reference = true; } bool psabpf_action_param_is_group_reference(psabpf_action_param_t *param) { if (param == NULL) return false; return param->is_group_reference; } psabpf_action_param_t *psabpf_action_param_get_next(psabpf_table_entry_t *entry) { if (entry == NULL) return NULL; if (entry->action == NULL) return NULL; if (entry->current_action_param_id >= entry->action->n_params) { entry->current_action_param_id = 0; return NULL; } memcpy(&entry->current_action_param, &entry->action->params[entry->current_action_param_id], sizeof(psabpf_action_param_t)); entry->current_action_param.mem_can_be_freed = false; entry->current_action_param_id += 1; return &entry->current_action_param; } void *psabpf_action_param_get_data(psabpf_action_param_t *param) { if (param == NULL) return NULL; return param->data; } size_t psabpf_action_param_get_data_len(psabpf_action_param_t *param) { if (param == NULL) return 0; return param->len; } const char *psabpf_action_param_get_name(psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry, psabpf_action_param_t *param) { if (ctx == NULL || entry == NULL || param == NULL) return NULL; if (entry->action == NULL || ctx->btf_metadata.btf == NULL || ctx->table.btf_type_id == 0) return NULL; if (ctx->is_indirect) { if (param->param_id >= ctx->table_implementations.n_fields) return NULL; return ctx->table_implementations.fields[param->param_id].name; } /* Find out number of action parameters. Action parameter name is known * only if number of parameter from entry is equal to that number. */ uint32_t value_type_id = get_table_value_type_id(ctx); psabtf_struct_member_md_t union_md = {}; if (psabtf_get_member_md_by_name(ctx->btf_metadata.btf, value_type_id, "u", &union_md) != NO_ERROR) return NULL; psabtf_struct_member_md_t action_md = {}; if (psabtf_get_member_md_by_index(ctx->btf_metadata.btf, union_md.effective_type_id, entry->action->action_id, &action_md) != NO_ERROR) return NULL; const struct btf_type *action_type = psabtf_get_type_by_id(ctx->btf_metadata.btf, action_md.effective_type_id); if (action_type == NULL) return NULL; if (!btf_is_struct(action_type)) return NULL; const unsigned number_of_params = btf_vlen(action_type); if (param->param_id >= number_of_params || entry->action->n_params != number_of_params) return NULL; psabtf_struct_member_md_t param_md = {}; if (psabtf_get_member_md_by_index(ctx->btf_metadata.btf, action_md.effective_type_id, param->param_id, &param_md) != NO_ERROR) return NULL; const char *type_name = btf__name_by_offset(ctx->btf_metadata.btf, param_md.member->name_off); if (type_name != NULL && type_name[0] == '\0') return NULL; return type_name; } void psabpf_action_init(psabpf_action_t *action) { if (action == NULL) return; memset(action, 0, sizeof(psabpf_action_t)); } void psabpf_action_free(psabpf_action_t *action) { if (action == NULL) return; for (size_t i = 0; i < action->n_params; i++) { psabpf_action_param_free(&(action->params[i])); } if (action->params != NULL) free(action->params); action->params = NULL; } void psabpf_action_set_id(psabpf_action_t *action, uint32_t action_id) { if (action == NULL) return; action->action_id = action_id; } uint32_t psabpf_table_get_action_id_by_name(psabpf_table_entry_ctx_t *ctx, const char *name) { if (ctx == NULL || name == NULL) return PSABPF_INVALID_ACTION_ID; if (ctx->btf_metadata.btf == NULL || ctx->table.btf_type_id == 0 || ctx->is_indirect) return PSABPF_INVALID_ACTION_ID; uint32_t value_type_id = get_table_value_type_id(ctx); psabtf_struct_member_md_t union_md = {}; if (psabtf_get_member_md_by_name(ctx->btf_metadata.btf, value_type_id, "u", &union_md) != NO_ERROR) return PSABPF_INVALID_ACTION_ID; psabtf_struct_member_md_t action_md = {}; if (psabtf_get_member_md_by_name(ctx->btf_metadata.btf, union_md.effective_type_id, name, &action_md) != NO_ERROR) return PSABPF_INVALID_ACTION_ID; return action_md.index; } int psabpf_action_param(psabpf_action_t *action, psabpf_action_param_t *param) { if (action == NULL || param == NULL) return EINVAL; if (param->data == NULL && param->len != 0) return ENODATA; if (param->len == 0) return NO_ERROR; size_t new_size = (action->n_params + 1) * sizeof(psabpf_action_param_t); psabpf_action_param_t * tmp = malloc(new_size); if (tmp == NULL) { if (param->data != NULL) free(param->data); param->data = NULL; return ENOMEM; } if (action->n_params != 0) { memcpy(tmp, action->params, (action->n_params) * sizeof(psabpf_action_param_t)); } if (action->params != NULL) free(action->params); action->params = tmp; memcpy(&(action->params[action->n_params]), param, sizeof(psabpf_action_param_t)); action->params[action->n_params].param_id = action->n_params; /* stole data; TODO: check if data owner */ param->data = NULL; action->n_params += 1; return NO_ERROR; } uint32_t psabpf_action_get_id(psabpf_table_entry_t *entry) { if (entry == NULL) return 0; if (entry->action == NULL) return 0; return entry->action->action_id; } const char *psabpf_action_get_name(psabpf_table_entry_ctx_t *ctx, uint32_t action_id) { if (ctx == NULL) return NULL; if (ctx->btf_metadata.btf == NULL || ctx->table.btf_type_id == 0) return NULL; uint32_t value_type_id = get_table_value_type_id(ctx); psabtf_struct_member_md_t union_md = {}; if (psabtf_get_member_md_by_name(ctx->btf_metadata.btf, value_type_id, "u", &union_md) != NO_ERROR) return NULL; psabtf_struct_member_md_t action_md = {}; if (psabtf_get_member_md_by_index(ctx->btf_metadata.btf, union_md.effective_type_id, action_id, &action_md) != NO_ERROR) return NULL; const char *type_name = btf__name_by_offset(ctx->btf_metadata.btf, action_md.member->name_off); if (type_name != NULL && type_name[0] == '\0') return NULL; return type_name; } enum write_flags { WRITE_HOST_ORDER = 0, WRITE_NETWORK_ORDER }; static int write_buffer_btf(char * buffer, size_t buffer_len, size_t offset, void * data, size_t data_len, psabpf_table_entry_ctx_t *ctx, uint32_t dst_type_id, const char *dst_type, enum write_flags flags) { size_t data_type_len = psabtf_get_type_size_by_id(ctx->btf_metadata.btf, dst_type_id); if (offset + data_len > buffer_len || data_len > data_type_len) { fprintf(stderr, "too much data in %s " "(buffer len: %zu; offset: %zu; data size: %zu; type size: %zu)\n", dst_type, buffer_len, offset, data_len, data_type_len); return EAGAIN; } if (flags == WRITE_HOST_ORDER) memcpy(buffer + offset, data, data_len); else if (flags == WRITE_NETWORK_ORDER) { for (size_t i = 0; i < data_len; i++) { buffer[offset + data_type_len - 1 - i] = ((char *) data)[i]; } } return NO_ERROR; } static int fill_key_byte_by_byte(char * buffer, psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry) { size_t bytes_to_write = ctx->table.key_size; uint32_t *lpm_prefix = NULL; if (ctx->table.type == BPF_MAP_TYPE_LPM_TRIE) { const size_t prefix_size = 4; lpm_prefix = (uint32_t *) buffer; if (ctx->table.key_size < prefix_size) { fprintf(stderr, "key size for LPM key is lower than prefix size (4B). BUG???\n"); return EPERM; } buffer += prefix_size; bytes_to_write -= prefix_size; } for (size_t i = 0; i < entry->n_keys; i++) { psabpf_match_key_t *mk = entry->match_keys[i]; if (mk->key_size > bytes_to_write) { fprintf(stderr, "provided keys are too long\n"); return EPERM; } if (ctx->table.type == BPF_MAP_TYPE_LPM_TRIE && mk->type == PSABPF_LPM) { /* copy data in network byte order (in reverse order) */ for (size_t k = 0; k < mk->key_size; ++k) buffer[k] = ((char *) (mk->data))[mk->key_size - k - 1]; } else { memcpy(buffer, mk->data, mk->key_size); } /* write prefix length */ if (ctx->table.type == BPF_MAP_TYPE_LPM_TRIE && mk->type == PSABPF_LPM) { *lpm_prefix = (buffer - ((char *) lpm_prefix) - 4) * 8 + mk->u.lpm.prefix_len; } buffer += mk->key_size; bytes_to_write -= mk->key_size; } /* TODO: maybe we should ignore this case */ if (bytes_to_write > 0) { fprintf(stderr, "provided keys are too short\n"); return EPERM; } return NO_ERROR; } static bool is_table_dummy_key(psabpf_table_entry_ctx_t *ctx, const struct btf_type *key_type, uint32_t key_type_id) { if (btf_kind(key_type) != BTF_KIND_STRUCT) return false; int entries = btf_vlen(key_type); if (entries != 1) return false; psabtf_struct_member_md_t action_md = {}; if (psabtf_get_member_md_by_name(ctx->btf_metadata.btf, key_type_id, "__dummy_table_key", &action_md) == NO_ERROR) return true; return false; } static int fill_key_btf_info(char * buffer, psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry) { uint32_t key_type_id = psabtf_get_member_type_id_by_name(ctx->btf_metadata.btf, ctx->table.btf_type_id, "key"); if (key_type_id == 0) return EAGAIN; const struct btf_type *key_type = psabtf_get_type_by_id(ctx->btf_metadata.btf, key_type_id); if (key_type == NULL) return EAGAIN; if (btf_kind(key_type) == BTF_KIND_INT) { if (entry->n_keys != 1) { fprintf(stderr, "expected 1 key\n"); return EAGAIN; } if (entry->match_keys[0]->key_size > ctx->table.key_size) { fprintf(stderr, "too much data in key\n"); return EPERM; /* byte by byte mode will not fix this */ } memcpy(buffer, entry->match_keys[0]->data, entry->match_keys[0]->key_size); } else if (btf_kind(key_type) == BTF_KIND_STRUCT) { const struct btf_member *member = btf_members(key_type); unsigned entries = btf_vlen(key_type); unsigned expected_entries = entries; if (ctx->table.type == BPF_MAP_TYPE_LPM_TRIE) --expected_entries; /* omit prefix length */ if (is_table_dummy_key(ctx, key_type, key_type_id)) { /* Preserve zeroed bytes if table do not define key */ expected_entries = 0; entries = 0; } if (entry->n_keys != expected_entries) { fprintf(stderr, "expected %u keys, got %zu\n", expected_entries, entry->n_keys); return EAGAIN; } for (unsigned member_idx = 0, key_idx = 0; member_idx < entries; member_idx++, member++) { if (member_idx == 0 && ctx->table.type == BPF_MAP_TYPE_LPM_TRIE) continue; /* skip prefix length */ /* assume that every field is byte aligned */ unsigned offset = btf_member_bit_offset(key_type, member_idx) / 8; psabpf_match_key_t *mk = entry->match_keys[key_idx]; int ret = 0, flags = WRITE_HOST_ORDER; if (ctx->table.type == BPF_MAP_TYPE_LPM_TRIE && mk->type == PSABPF_LPM) flags = WRITE_NETWORK_ORDER; ret = write_buffer_btf(buffer, ctx->table.key_size, offset, mk->data, mk->key_size, ctx, member->type, "key", flags); if (ret != NO_ERROR) return ret; /* write prefix value for LPM field */ if (ctx->table.type == BPF_MAP_TYPE_LPM_TRIE && mk->type == PSABPF_LPM) { uint32_t prefix_value = offset * 8 + mk->u.lpm.prefix_len - 32; psabtf_struct_member_md_t prefix_md; if (psabtf_get_member_md_by_index(ctx->btf_metadata.btf, key_type_id, 0, &prefix_md) != NO_ERROR) return EAGAIN; ret = write_buffer_btf(buffer, ctx->table.key_size, prefix_md.bit_offset / 8, &prefix_value, sizeof(prefix_value), ctx, prefix_md.effective_type_id, "prefix", WRITE_HOST_ORDER); if (ret != NO_ERROR) return ret; } ++key_idx; } } else { fprintf(stderr, "unexpected BTF type for key\n"); return EAGAIN; } return NO_ERROR; } static int fill_value_byte_by_byte(char * buffer, psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry) { size_t bytes_to_write = ctx->table.value_size; /* write action ID */ if (ctx->is_indirect == false) { size_t action_id_len = sizeof(entry->action->action_id); if (action_id_len <= bytes_to_write) { memcpy(buffer, &(entry->action->action_id), action_id_len); buffer += action_id_len; bytes_to_write -= action_id_len; } else { fprintf(stderr, "action id do not fits into value\n"); return EPERM; } } /* write priority */ if (ctx->is_ternary) { size_t priority_len = sizeof(entry->priority); if (priority_len <= bytes_to_write) { memcpy(buffer, &(entry->priority), priority_len); buffer += priority_len; bytes_to_write -= priority_len; } else { fprintf(stderr, "priority do not fits into value\n"); return EPERM; } } for (size_t i = 0; i < entry->action->n_params; i++) { psabpf_action_param_t *param = &(entry->action->params[i]); if (param->len > bytes_to_write) { fprintf(stderr, "provided values are too long\n"); return EPERM; } memcpy(buffer, param->data, param->len); buffer += param->len; bytes_to_write -= param->len; } /* TODO: maybe we should ignore this case */ if (bytes_to_write > 0) { fprintf(stderr, "provided values are too short\n"); return EPERM; } return NO_ERROR; } static int fill_action_id(char * buffer, psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry, uint32_t value_type_id) { psabtf_struct_member_md_t action_md = {}; if (psabtf_get_member_md_by_name(ctx->btf_metadata.btf, value_type_id, "action", &action_md) != NO_ERROR) { fprintf(stderr, "action id entry not found\n"); return EAGAIN; /* Allow fallback to byte by byte mode */ } return write_buffer_btf(buffer, ctx->table.value_size, action_md.bit_offset / 8, &(entry->action->action_id), sizeof(entry->action->action_id), ctx, action_md.effective_type_id, "action id", WRITE_HOST_ORDER); } static int fill_priority(char * buffer, psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry, uint32_t value_type_id) { if (ctx->is_ternary == false) return NO_ERROR; psabtf_struct_member_md_t priority_md = {}; if (psabtf_get_member_md_by_name(ctx->btf_metadata.btf, value_type_id, "priority", &priority_md) != NO_ERROR) { fprintf(stderr, "priority entry not found\n"); return ENOENT; } return write_buffer_btf(buffer, ctx->table.value_size, priority_md.bit_offset / 8, &(entry->priority), sizeof(entry->priority), ctx, priority_md.effective_type_id, "priority", WRITE_HOST_ORDER); } static int fill_action_data(char * buffer, psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry, uint32_t value_type_id) { size_t base_offset, offset; int ret; /* find union with action data */ psabtf_struct_member_md_t action_union_md = {}; if (psabtf_get_member_md_by_name(ctx->btf_metadata.btf, value_type_id, "u", &action_union_md) != NO_ERROR) { fprintf(stderr, "actions data structure not found\n"); return ENOENT; } base_offset = action_union_md.bit_offset / 8; /* find action data structure in the union */ psabtf_struct_member_md_t action_data_md = {}; if (psabtf_get_member_md_by_index(ctx->btf_metadata.btf, action_union_md.effective_type_id, entry->action->action_id, &action_data_md) != NO_ERROR) { fprintf(stderr, "action with id %u does not exist\n", entry->action->action_id); return EPERM; /* not fixable, invalid action ID */ } /* to be sure of offset, take into account offset of action data structure in the union */ base_offset = base_offset + action_data_md.bit_offset / 8; const struct btf_type * data_type = psabtf_get_type_by_id(ctx->btf_metadata.btf, action_data_md.effective_type_id); /* fill action data */ unsigned entries = btf_vlen(data_type); if (entry->action->n_params != entries) { fprintf(stderr, "expected %d action parameters, got %zu\n", entries, entry->action->n_params); return EAGAIN; } const struct btf_member *member = btf_members(data_type); for (unsigned i = 0; i < entries; i++, member++) { offset = btf_member_bit_offset(data_type, i) / 8; ret = write_buffer_btf(buffer, ctx->table.value_size, base_offset + offset, entry->action->params[i].data, entry->action->params[i].len, ctx, member->type, "value", WRITE_HOST_ORDER); if (ret != NO_ERROR) return ret; } return NO_ERROR; } static int fill_action_references(char * buffer, psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry, const struct btf_type *value_type) { int entries = btf_vlen(value_type), ret; const struct btf_member *member = btf_members(value_type); size_t used_params = 0, offset; psabpf_action_param_t * current_data = &(entry->action->params[0]); bool entry_ref_used = false; for (int i = 0; i < entries; i++, member++) { if (used_params >= entry->action->n_params) { fprintf(stderr, "not enough member/group references\n"); return EAGAIN; } const struct btf_type * member_type = psabtf_get_type_by_id(ctx->btf_metadata.btf, member->type); const char * member_name = btf__name_by_offset(ctx->btf_metadata.btf, member->name_off); /* skip errors, non-int members and reserved names */ if (member_name == NULL || btf_kind(member_type) != BTF_KIND_INT) continue; if (strcmp(member_name, "priority") == 0 || strcmp(member_name, "action") == 0) continue; if (str_ends_with(member_name, "_is_group_ref")) { offset = btf_member_bit_offset(value_type, i) / 8; ret = write_buffer_btf(buffer, ctx->table.value_size, offset, &(current_data->is_group_reference), sizeof(current_data->is_group_reference), ctx, member->type, "reference type", WRITE_HOST_ORDER); if (ret != NO_ERROR) return ret; continue; } if (entry_ref_used) { entry_ref_used = false; current_data++; used_params++; if (used_params >= entry->action->n_params) { fprintf(stderr, "not enough member/group references\n"); return EAGAIN; } } /* now we can write reference, hurrah!!! */ offset = btf_member_bit_offset(value_type, i) / 8; ret = write_buffer_btf(buffer, ctx->table.value_size, offset, current_data->data, current_data->len, ctx, member->type, "reference", WRITE_HOST_ORDER); if (ret != NO_ERROR) return ret; entry_ref_used = true; } if (entry_ref_used) used_params++; if (used_params != entry->action->n_params) { fprintf(stderr, "too many member/group references\n"); return EAGAIN; } return NO_ERROR; } static int fill_value_btf_info(char * buffer, psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry) { int ret; uint32_t value_type_id = get_table_value_type_id(ctx); if (value_type_id == 0) return EAGAIN; const struct btf_type *value_type = psabtf_get_type_by_id(ctx->btf_metadata.btf, value_type_id); if (value_type == NULL) return EAGAIN; if (btf_kind(value_type) != BTF_KIND_STRUCT) { fprintf(stderr, "expected struct as a map value\n"); return EAGAIN; } if (ctx->is_indirect == false) { ret = fill_action_id(buffer, ctx, entry, value_type_id); if (ret != NO_ERROR) return ret; ret = fill_action_data(buffer, ctx, entry, value_type_id); if (ret != NO_ERROR) return ret; } else { ret = fill_action_references(buffer, ctx, entry, value_type); if (ret != NO_ERROR) return ret; } ret = fill_priority(buffer, ctx, entry, value_type_id); if (ret != NO_ERROR) return ret; return NO_ERROR; } static int lpm_prefix_to_mask(char * buffer, size_t buffer_len, uint32_t prefix, size_t data_len) { unsigned ff_bytes = prefix / 8; size_t bytes_to_write = ff_bytes; if (prefix % 8 != 0) ++bytes_to_write; if (bytes_to_write > data_len || bytes_to_write > buffer_len) { fprintf(stderr, "LPM prefix too long\n"); return EINVAL; } memset(buffer + data_len - ff_bytes, 0xFF, ff_bytes); if (prefix % 8 != 0) { int byte_prefix[] = {0x00, 0x80, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC, 0xFE, 0xFF}; memset(buffer + data_len - ff_bytes - 1, byte_prefix[prefix % 8], 1); } return NO_ERROR; } static int fill_key_mask_byte_by_byte(char * buffer, psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry) { size_t bytes_to_write = ctx->prefixes.key_size; for (size_t i = 0; i < entry->n_keys; i++) { psabpf_match_key_t *mk = entry->match_keys[i]; size_t data_len = 0; if (mk->type == PSABPF_EXACT) { if (mk->key_size > bytes_to_write) { fprintf(stderr, "provided exact keys mask are too long\n"); return EPERM; } data_len = mk->key_size; memset(buffer, 0xFF, data_len); } else if (mk->type == PSABPF_LPM) { data_len = mk->key_size; int ret = lpm_prefix_to_mask(buffer, bytes_to_write, mk->u.lpm.prefix_len, data_len); if (ret != NO_ERROR) return ret; } else if (mk->type == PSABPF_TERNARY) { if (mk->u.ternary.mask_size > bytes_to_write) { fprintf(stderr, "provided ternary key mask is too long\n"); return EPERM; } if (mk->u.ternary.mask_size != mk->key_size) fprintf(stderr, "warning: key and its mask have different length\n"); data_len = mk->u.ternary.mask_size; memcpy(buffer, mk->u.ternary.mask, data_len); } else { fprintf(stderr, "unsupported key mask type\n"); return EAGAIN; } buffer += data_len; bytes_to_write -= data_len; } /* TODO: maybe we should ignore this case */ if (bytes_to_write > 0) { fprintf(stderr, "provided key masks are too short\n"); return EPERM; } return NO_ERROR; } static int fill_key_mask_btf(char * buffer, psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry) { /* Use key type to generate mask */ uint32_t key_type_id = psabtf_get_member_type_id_by_name(ctx->btf_metadata.btf, ctx->table.btf_type_id, "key"); if (key_type_id == 0) return EAGAIN; const struct btf_type *key_type = psabtf_get_type_by_id(ctx->btf_metadata.btf, key_type_id); if (key_type == NULL) return EAGAIN; if (btf_kind(key_type) != BTF_KIND_STRUCT) return EAGAIN; const struct btf_member *member = btf_members(key_type); unsigned entries = btf_vlen(key_type); if (entry->n_keys != entries) { fprintf(stderr, "expected %d keys, got %zu\n", entries, entry->n_keys); return EAGAIN; } /* Prepare temporary mask buffer for current field. Every field size <= key_size */ char * tmp_mask = malloc(ctx->table.key_size); if (tmp_mask == NULL) return ENOMEM; int ret = EAGAIN; for (unsigned i = 0; i < entries; i++, member++) { psabpf_match_key_t *mk = entry->match_keys[i]; unsigned offset = btf_member_bit_offset(key_type, i) / 8; size_t size = psabtf_get_type_size_by_id(ctx->btf_metadata.btf, member->type); ret = EAGAIN; memset(tmp_mask, 0, ctx->table.key_size); if (mk->type == PSABPF_EXACT) { if (size > ctx->table.key_size) break; memset(tmp_mask, 0xFF, size); ret = write_buffer_btf(buffer, ctx->prefixes.key_size, offset, tmp_mask, size, ctx, member->type, "exact mask key", WRITE_HOST_ORDER); } else if (mk->type == PSABPF_LPM) { ret = lpm_prefix_to_mask(tmp_mask, size, mk->u.lpm.prefix_len, size); if (ret != NO_ERROR) { ret = EAGAIN; break; } ret = write_buffer_btf(buffer, ctx->prefixes.key_size, offset, tmp_mask, size, ctx, member->type, "lpm mask key", WRITE_HOST_ORDER); } else if (mk->type == PSABPF_TERNARY) { ret = write_buffer_btf(buffer, ctx->prefixes.key_size, offset, mk->u.ternary.mask, mk->u.ternary.mask_size, ctx, member->type, "ternary mask key", WRITE_HOST_ORDER); } else { fprintf(stderr, "unsupported key mask type\n"); } if (ret != NO_ERROR) break; } free(tmp_mask); return ret; } /* Please use this function instead of using directly family of fill_*() functions */ static int construct_buffer(char * buffer, size_t buffer_len, psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry, int (*btf_info_func)(char *, psabpf_table_entry_ctx_t *, psabpf_table_entry_t *), int (*byte_by_byte_func)(char *, psabpf_table_entry_ctx_t *, psabpf_table_entry_t *)) { /* When BTF info mode fails we can fallback to byte by byte mode */ int return_code = EAGAIN; if (ctx->btf_metadata.btf != NULL && ctx->table.btf_type_id != 0) { memset(buffer, 0, buffer_len); return_code = btf_info_func(buffer, ctx, entry); if (return_code == EAGAIN) fprintf(stderr, "falling back to byte by byte mode\n"); } if (return_code == EAGAIN) { memset(buffer, 0, buffer_len); return_code = byte_by_byte_func(buffer, ctx, entry); } return return_code; } static int handle_direct_counter_write(const char *key, char *value, psabpf_bpf_map_descriptor_t *map, psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry, uint64_t bpf_flags) { /* 1. Entry provided - build counter based on it (on update and add) * 2. Entry not provided - init to zero on add (already done), on update copy old value */ if (ctx->n_direct_counters == 0) return NO_ERROR; if (bpf_flags == BPF_EXIST) { char *old_value_buffer = NULL; old_value_buffer = malloc(map->value_size); if (old_value_buffer == NULL) return ENOMEM; memset(old_value_buffer, 0, map->value_size); int err = bpf_map_lookup_elem(map->fd, key, old_value_buffer); if (err != 0) { free(old_value_buffer); return ENOENT; } /* copy existing values, they might be overwritten later */ for (unsigned i = 0; i < ctx->n_direct_counters; i++) { memcpy(value + ctx->direct_counters_ctx[i].counter_offset, old_value_buffer + ctx->direct_counters_ctx[i].counter_offset, ctx->direct_counters_ctx[i].counter_size); } if (old_value_buffer != NULL) free(old_value_buffer); } for (unsigned i = 0; i < entry->n_direct_counters; i++) { unsigned idx = entry->direct_counters[i].counter_idx; if (idx >= ctx->n_direct_counters) return EINVAL; psabpf_direct_counter_context_t *dc_ctx = &ctx->direct_counters_ctx[idx]; psabpf_counter_context_t counter_ctx = { .counter_type = dc_ctx->counter_type, .counter.value_size = dc_ctx->counter_size, }; int ret = convert_counter_entry_to_data(&counter_ctx, &entry->direct_counters[i].counter, (uint8_t *) value + ctx->direct_counters_ctx[i].counter_offset); if (ret != NO_ERROR) return ret; } return NO_ERROR; } static int handle_direct_meter_write(char *value, psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry) { /* Configure meters only when provided, otherwise leave it uninitialized */ for (unsigned i = 0; i < entry->n_direct_meters; i++) { unsigned idx = entry->direct_meters[i].meter_idx; if (idx >= ctx->n_direct_meters) return EINVAL; psabpf_direct_meter_context_t *dm_ctx = &ctx->direct_meters_ctx[idx]; if (dm_ctx->meter_size != DIRECT_METER_SIZE) return EINVAL; convert_meter_entry_to_data(&entry->direct_meters[i].meter, (psabpf_meter_data_t *) (value + dm_ctx->meter_offset)); } return NO_ERROR; } static int handle_direct_objects_write(const char *key, char *value, psabpf_bpf_map_descriptor_t *map, psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry, uint64_t bpf_flags) { if (ctx->is_indirect || ctx->btf_metadata.btf == NULL || ctx->table.btf_type_id == 0) return NO_ERROR; int ret = handle_direct_meter_write(value, ctx, entry); if (ret != NO_ERROR) return ret; return handle_direct_counter_write(key, value, map, ctx, entry, bpf_flags); } struct ternary_table_prefix_metadata { size_t tuple_id_offset; size_t tuple_id_size; size_t next_mask_offset; size_t next_mask_size; size_t has_next_offset; size_t has_next_size; }; static int get_ternary_table_prefix_md(psabpf_table_entry_ctx_t *ctx, struct ternary_table_prefix_metadata *md) { psabtf_struct_member_md_t member; md->tuple_id_size = sizeof(uint32_t); md->next_mask_size = ctx->table.key_size; md->has_next_size = sizeof(uint8_t); /* Lets guess offsets (they will be fixed with BTF if available) */ md->tuple_id_offset = 0; /* at the beginning of the structure */ md->next_mask_offset = ctx->table.key_size > 4 ? 8 : 4; /* after tuple_id field */ md->has_next_offset = md->next_mask_offset + md->next_mask_size; /* after next_mask field */ if (ctx->btf_metadata.btf == NULL || ctx->prefixes.btf_type_id == 0) return NO_ERROR; uint32_t type_id = psabtf_get_member_type_id_by_name(ctx->btf_metadata.btf, ctx->prefixes.btf_type_id, "value"); if (type_id == 0) return EPERM; /* tuple id */ if (psabtf_get_member_md_by_name(ctx->btf_metadata.btf, type_id, "tuple_id", &member) != NO_ERROR) return EPERM; md->tuple_id_size = psabtf_get_type_size_by_id(ctx->btf_metadata.btf, member.effective_type_id); md->tuple_id_offset = member.bit_offset / 8; /* next mask */ if (psabtf_get_member_md_by_name(ctx->btf_metadata.btf, type_id, "next_tuple_mask", &member) != NO_ERROR) return EPERM; md->next_mask_size = psabtf_get_type_size_by_id(ctx->btf_metadata.btf, member.effective_type_id); md->next_mask_offset = member.bit_offset / 8; /* has next */ if (psabtf_get_member_md_by_name(ctx->btf_metadata.btf, type_id, "has_next", &member) != NO_ERROR) return EPERM; md->has_next_size = psabtf_get_type_size_by_id(ctx->btf_metadata.btf, member.effective_type_id); md->has_next_offset = member.bit_offset / 8; /* validate size and offset */ if (md->tuple_id_offset + md->tuple_id_size > ctx->prefixes.value_size || md->next_mask_offset + md->next_mask_size > ctx->prefixes.value_size || md->has_next_offset + md->has_next_size > ctx->prefixes.value_size || md->next_mask_size != ctx->table.key_size) { fprintf(stderr, "BUG: invalid size or offset in the mask\n"); return EPERM; } return NO_ERROR; } static int add_ternary_table_prefix(char *new_prefix, char *prefix_value, psabpf_table_entry_ctx_t *ctx) { int err = NO_ERROR; uint32_t tuple_id = 0; struct ternary_table_prefix_metadata prefix_md; if (get_ternary_table_prefix_md(ctx, &prefix_md) != NO_ERROR) { fprintf(stderr, "failed to obtain offsets and sizes of prefix\n"); return EPERM; } char *key = malloc(ctx->prefixes.key_size); char *value = malloc(ctx->prefixes.value_size); if (key == NULL || value == NULL) { fprintf(stderr, "not enough memory\n"); err = ENOMEM; goto clean_up; } /* Process head */ memset(key, 0, ctx->prefixes.key_size); err = bpf_map_lookup_elem(ctx->prefixes.fd, key, value); if (err != 0) { /* Construct head, it will be added later */ memset(value, 0, ctx->prefixes.value_size); *((uint32_t *) (value + prefix_md.tuple_id_offset)) = tuple_id; } /* Iterate over every prefix to the last one */ while (true) { uint8_t has_next = *((uint8_t *) (value + prefix_md.has_next_offset)); if (has_next == 0) break; /* Get next prefix */ memcpy(key, value + prefix_md.next_mask_offset, prefix_md.next_mask_size); err = bpf_map_lookup_elem(ctx->prefixes.fd, key, value); if (err != 0) { err = errno; fprintf(stderr, "detected data inconsistency in prefixes, aborting\n"); goto clean_up; } /* Find highest tuple id */ uint32_t current_tuple_id = *((uint32_t *) (value + prefix_md.tuple_id_offset)); if (current_tuple_id > tuple_id) tuple_id = current_tuple_id; } /* First add new prefix to avoid data inconsistency */ memset(prefix_value, 0, ctx->prefixes.value_size); *((uint32_t *) (prefix_value + prefix_md.tuple_id_offset)) = ++tuple_id; err = bpf_map_update_elem(ctx->prefixes.fd, new_prefix, prefix_value, BPF_NOEXIST); if (err != 0) goto clean_up; /* Update previous node */ memcpy(value + prefix_md.next_mask_offset, new_prefix, prefix_md.next_mask_size); *((uint8_t *) (value + prefix_md.has_next_offset)) = 1; err = bpf_map_update_elem(ctx->prefixes.fd, key, value, BPF_ANY); if (err != 0) goto clean_up; err = NO_ERROR; clean_up: if (key != NULL) free(key); if (value != NULL) free(value); return err; } static int ternary_table_add_tuple_and_open(psabpf_table_entry_ctx_t *ctx, const uint32_t tuple_id) { int err; struct bpf_create_map_attr attr = { .key_size = ctx->table.key_size, .value_size = ctx->table.value_size, .max_entries = ctx->table.max_entries, .map_type = ctx->table.type, }; ctx->table.fd = bpf_create_map_xattr(&attr); if (ctx->table.fd < 0) { err = errno; fprintf(stderr, "failed to create tuple %u: %s\n", tuple_id, strerror(err)); return err; } /* add tuple to tuples map */ err = bpf_map_update_elem(ctx->tuple_map.fd, &tuple_id, &(ctx->table.fd), 0); if (err != 0) { err = errno; fprintf(stderr, "failed to add tuple %u: %s\n", tuple_id, strerror(err)); close_object_fd(&(ctx->table.fd)); } return err; } static int ternary_table_open_tuple(psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry, char **key_mask, uint64_t bpf_flags) { if (ctx->prefixes.fd < 0 || ctx->tuple_map.fd < 0 || ctx->table.fd >= 0) { fprintf(stderr, "ternary table not properly opened. BUG?\n"); return EINVAL; } if (ctx->table.key_size != ctx->prefixes.key_size) { fprintf(stderr, "key and its mask have different length. BUG?\n"); return EINVAL; } if (ctx->tuple_map.key_size != 4 || ctx->tuple_map.value_size != 4) { fprintf(stderr, "key/value size of tuples map have to be 4B.\n"); return EINVAL; } int err = NO_ERROR; char *value_mask = malloc(ctx->prefixes.value_size); *key_mask = malloc(ctx->prefixes.key_size); if (*key_mask == NULL || value_mask == NULL) { fprintf(stderr, "not enough memory\n"); err = ENOMEM; goto clean_up; } memset(*key_mask, 0, ctx->prefixes.key_size); memset(value_mask, 0, ctx->prefixes.value_size); err = construct_buffer(*key_mask, ctx->prefixes.key_size, ctx, entry, fill_key_mask_btf, fill_key_mask_byte_by_byte); if (err != NO_ERROR) goto clean_up; /* prefixes head protection - check whether mask is different from all 0 */ bool mask_is_valid = false; for (unsigned i = 0; i < ctx->prefixes.key_size; i++) { if ((*key_mask)[i] != 0) { mask_is_valid = true; break; } } if (mask_is_valid == false) { fprintf(stderr, "invalid key mask: all bytes are zeroed - use default action instead\n"); err = EINVAL; goto clean_up; } err = bpf_map_lookup_elem(ctx->prefixes.fd, *key_mask, value_mask); /* It is not allowed to add new prefix when updating existing entry */ if (err != 0 && bpf_flags != BPF_EXIST) { err = add_ternary_table_prefix(*key_mask, value_mask, ctx); if (err != NO_ERROR) { fprintf(stderr, "unable to add new prefix\n"); goto clean_up; } } else if (err != 0) { fprintf(stderr, "entry with prefix not found\n"); err = ENOENT; goto clean_up; } struct ternary_table_prefix_metadata prefix_md; if (get_ternary_table_prefix_md(ctx, &prefix_md) != NO_ERROR) { fprintf(stderr, "failed to obtain offsets and sizes of prefix\n"); err = EPERM; goto clean_up; } uint32_t tuple_id = *((uint32_t *) (value_mask + prefix_md.tuple_id_offset)); uint32_t inner_map_id; err = bpf_map_lookup_elem(ctx->tuple_map.fd, &tuple_id, &inner_map_id); if (err == 0) { ctx->table.fd = bpf_map_get_fd_by_id(inner_map_id); err = NO_ERROR; } else { if (bpf_flags == BPF_EXIST) { fprintf(stderr, "tuple not found\n"); err = ENOENT; goto clean_up; } err = ternary_table_add_tuple_and_open(ctx, tuple_id); } clean_up: if (value_mask != NULL) free(value_mask); return err; } static void ternary_table_close_tuple(psabpf_table_entry_ctx_t *ctx) { /* Allow for reuse table context with the same table but other tuple (inner map). */ if (ctx->is_ternary) close_object_fd(&(ctx->table.fd)); } int delete_all_map_entries(psabpf_bpf_map_descriptor_t *map) { fprintf(stderr, "removing all entries from table\n"); char * key = malloc(map->key_size); char * next_key = malloc(map->key_size); char * value = calloc(1, map->value_size); int error_code = NO_ERROR; if (key == NULL || next_key == NULL || value == NULL) { fprintf(stderr, "not enough memory\n"); error_code = ENOMEM; goto clean_up; } if (bpf_map_get_next_key(map->fd, NULL, next_key) != 0) goto clean_up; /* table empty */ do { /* Swap buffers, so next_key will become key and next_key may be reused */ char * tmp_key = next_key; next_key = key; key = tmp_key; /* Ignore error(s) from bpf_map_delete_elem(). In some cases key may exist * but entry not exists (e.g. array map in map). So in any case we have to * iterate over all keys and try to delete it. It is not possible to remove * entry from array map, in such case reset entries to zero value. */ if (map->type == BPF_MAP_TYPE_ARRAY) bpf_map_update_elem(map->fd, key, value, BPF_ANY); else bpf_map_delete_elem(map->fd, key); } while (bpf_map_get_next_key(map->fd, key, next_key) == 0); clean_up: if (key) free(key); if (next_key) free(next_key); if (value) free(value); return error_code; } int clear_table_cache(psabpf_bpf_map_descriptor_t *map) { if (map == NULL || map->fd < 0) return NO_ERROR; fprintf(stderr, "clearing table cache: "); return delete_all_map_entries(map); } static int psabpf_table_entry_write(psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry, uint64_t bpf_flags) { char *key_buffer = NULL; char *key_mask_buffer = NULL; char *value_buffer = NULL; int return_code = NO_ERROR; if (ctx == NULL || entry == NULL) return EINVAL; if (ctx->is_ternary) { return_code = ternary_table_open_tuple(ctx, entry, &key_mask_buffer, bpf_flags); if (return_code != NO_ERROR) goto clean_up; } if (ctx->table.fd < 0) { fprintf(stderr, "can't add entry: table not opened\n"); return_code = EBADF; goto clean_up; } if (ctx->table.key_size == 0 || ctx->table.value_size == 0) { fprintf(stderr, "zero-size key or value is not supported\n"); return_code = ENOTSUP; goto clean_up; } if (entry->action == NULL) { fprintf(stderr, "missing action specification\n"); return_code = ENODATA; goto clean_up; } /* prepare buffers for map key/value */ key_buffer = malloc(ctx->table.key_size); value_buffer = malloc(ctx->table.value_size); if (key_buffer == NULL || value_buffer == NULL) { fprintf(stderr, "not enough memory\n"); return_code = ENOMEM; goto clean_up; } return_code = construct_buffer(key_buffer, ctx->table.key_size, ctx, entry, fill_key_btf_info, fill_key_byte_by_byte); if (return_code != NO_ERROR) { fprintf(stderr, "failed to construct key\n"); goto clean_up; } return_code = construct_buffer(value_buffer, ctx->table.value_size, ctx, entry, fill_value_btf_info, fill_value_byte_by_byte); if (return_code != NO_ERROR) { fprintf(stderr, "failed to construct value\n"); goto clean_up; } if (ctx->is_ternary == true && key_mask_buffer != NULL) mem_bitwise_and((uint32_t *) key_buffer, (uint32_t *) key_mask_buffer, ctx->table.key_size); /* Handle direct objects */ return_code = handle_direct_objects_write(key_buffer, value_buffer, &ctx->table, ctx, entry, bpf_flags); if (return_code != NO_ERROR) { fprintf(stderr, "failed to handle direct objects: %s\n", strerror(return_code)); goto clean_up; } /* update map */ if (ctx->table.type == BPF_MAP_TYPE_ARRAY) bpf_flags = BPF_ANY; return_code = bpf_map_update_elem(ctx->table.fd, key_buffer, value_buffer, bpf_flags); if (return_code != 0) { return_code = errno; fprintf(stderr, "failed to set up entry: %s\n", strerror(errno)); } else { return_code = clear_table_cache(&ctx->cache); if (return_code != NO_ERROR) { fprintf(stderr, "failed to clear cache: %s\n", strerror(return_code)); } } clean_up: if (key_buffer != NULL) free(key_buffer); if (key_mask_buffer != NULL) free(key_mask_buffer); if (value_buffer != NULL) free(value_buffer); if (ctx->is_ternary) ternary_table_close_tuple(ctx); return return_code; } int psabpf_table_entry_add(psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry) { return psabpf_table_entry_write(ctx, entry, BPF_NOEXIST); } int psabpf_table_entry_update(psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry) { return psabpf_table_entry_write(ctx, entry, BPF_EXIST); } static int prepare_ternary_table_delete(psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry, char **key_mask) { if (entry->n_keys != 0) return ternary_table_open_tuple(ctx, entry, key_mask, BPF_EXIST); delete_all_map_entries(&ctx->prefixes); fprintf(stderr, "removing entries from tuples_map, this may take a while\n"); delete_all_map_entries(&ctx->tuple_map); /* Unpinning inner maps for our table is not required * because they are not pinned by this tool. */ return NO_ERROR; } static int ternary_table_remove_prefix(psabpf_table_entry_ctx_t *ctx, const char *key_mask) { int err = NO_ERROR; char *prev_key_mask = malloc(ctx->prefixes.key_size); char *prev_value_mask = malloc(ctx->prefixes.value_size); char *value_mask = malloc(ctx->prefixes.value_size); if (prev_key_mask == NULL || prev_value_mask == NULL || value_mask == NULL) { fprintf(stderr, "not enough memory\n"); err = ENOMEM; goto clean_up; } if (bpf_map_lookup_elem(ctx->prefixes.fd, key_mask, value_mask) != 0) { err = errno; fprintf(stderr, "unable to obtain prefix: %s\n", strerror(err)); goto clean_up; } struct ternary_table_prefix_metadata prefix_md; if ((err = get_ternary_table_prefix_md(ctx, &prefix_md)) != NO_ERROR) { fprintf(stderr, "failed to obtain offsets and sizes of prefix\n"); goto clean_up; } /* find previous prefix */ bool prev_prefix_found = false; memset(prev_key_mask, 0, ctx->prefixes.key_size); err = bpf_map_lookup_elem(ctx->prefixes.fd, prev_key_mask, prev_value_mask); if (err != 0) { err = errno; fprintf(stderr, "head not found: %s\n", strerror(err)); goto clean_up; } while (true) { /* it is an previous prefix? */ if (memcmp(prev_value_mask + prefix_md.next_mask_offset, key_mask, prefix_md.next_mask_size) == 0) { prev_prefix_found = true; break; } /* get next prefix */ uint8_t has_next = *((uint8_t *) (prev_value_mask + prefix_md.has_next_offset)); if (has_next == 0) break; memcpy(prev_key_mask, prev_value_mask + prefix_md.next_mask_offset, prefix_md.next_mask_size); if (bpf_map_lookup_elem(ctx->prefixes.fd, prev_key_mask, prev_value_mask) != 0) break; } if (prev_prefix_found == false) { fprintf(stderr, "detected data inconsistency in prefixes: no previous prefix\n"); } else { /* copy next_mask and has_next to the previous prefix */ memcpy(prev_value_mask + prefix_md.next_mask_offset, value_mask + prefix_md.next_mask_offset, prefix_md.next_mask_size); memcpy(prev_value_mask + prefix_md.has_next_offset, value_mask + prefix_md.has_next_offset, prefix_md.has_next_size); err = bpf_map_update_elem(ctx->prefixes.fd, prev_key_mask, prev_value_mask, BPF_EXIST); if (err != 0) { err = errno; fprintf(stderr, "failed to update previous prefix: %s\n", strerror(err)); goto clean_up; } } /* there are no prefixes that points to removing prefix, so it can be safely removed now */ if (bpf_map_delete_elem(ctx->prefixes.fd, key_mask) != 0) fprintf(stderr, "warning: failed to remove prefix from prefixes list\n"); /* also remove tuple from tuple_map */ uint32_t tuple_id = *((uint32_t *) (value_mask + prefix_md.tuple_id_offset)); if (bpf_map_delete_elem(ctx->tuple_map.fd, &tuple_id) != 0) fprintf(stderr, "warning: failed to remove tuple from tuples_map\n"); /* unpinning not required - inner map is not pinned by this tool*/ err = NO_ERROR; clean_up: if (prev_key_mask != NULL) free(prev_key_mask); if (prev_value_mask != NULL) free(prev_value_mask); if (value_mask != NULL) free(value_mask); return err; } static int post_ternary_table_delete(psabpf_table_entry_ctx_t *ctx, const char *key_mask) { if (ctx->is_ternary == false || ctx->table.fd < 0) return NO_ERROR; if (key_mask == NULL) return ENODATA; int err = NO_ERROR; char *tuple_next_key = malloc(ctx->table.key_size); if (tuple_next_key == NULL) { fprintf(stderr, "not enough memory\n"); err = ENOMEM; goto clean_up; } if (bpf_map_get_next_key(ctx->table.fd, NULL, tuple_next_key) != 0) { err = ternary_table_remove_prefix(ctx, key_mask); } clean_up: if (tuple_next_key != NULL) free(tuple_next_key); close_object_fd(&(ctx->table.fd)); return err; } int psabpf_table_entry_del(psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry) { char *key_buffer = NULL; char *key_mask_buffer = NULL; int return_code = NO_ERROR; if (ctx == NULL || entry == NULL) return EINVAL; if (ctx->is_ternary) { return_code = prepare_ternary_table_delete(ctx, entry, &key_mask_buffer); if (return_code != NO_ERROR) { fprintf(stderr, "failed to prepare ternary table for delete\n"); goto clean_up; } if (entry->n_keys == 0) goto clean_up; } if (ctx->table.fd < 0) { fprintf(stderr, "can't delete entry: table not opened\n"); return EBADF; } if (ctx->table.key_size == 0) { fprintf(stderr, "zero-size key is not supported\n"); return ENOTSUP; } /* remove all entries from table if key is not present */ if (entry->n_keys == 0) { if (ctx->table.type == BPF_MAP_TYPE_ARRAY) fprintf(stderr, "removing entries from array map may take a while\n"); return_code = delete_all_map_entries(&ctx->table); if (return_code == NO_ERROR) { return_code = clear_table_cache(&ctx->cache); if (return_code != NO_ERROR) { fprintf(stderr, "failed to clear table cache: %s\n", strerror(return_code)); } } return return_code; } /* prepare buffers for map key */ key_buffer = malloc(ctx->table.key_size); if (key_buffer == NULL) { fprintf(stderr, "not enough memory\n"); return_code = ENOMEM; goto clean_up; } return_code = construct_buffer(key_buffer, ctx->table.key_size, ctx, entry, fill_key_btf_info, fill_key_byte_by_byte); if (return_code != NO_ERROR) { fprintf(stderr, "failed to construct key\n"); goto clean_up; } if (ctx->is_ternary == true && key_mask_buffer != NULL) mem_bitwise_and((uint32_t *) key_buffer, (uint32_t *) key_mask_buffer, ctx->table.key_size); /* delete pointed entry */ return_code = bpf_map_delete_elem(ctx->table.fd, key_buffer); if (return_code != 0) { return_code = errno; fprintf(stderr, "failed to delete entry: %s\n", strerror(errno)); } else { return_code = clear_table_cache(&ctx->cache); if (return_code != NO_ERROR) { fprintf(stderr, "failed to clear cache: %s\n", strerror(return_code)); } } clean_up: /* cleanup ternary table */ if (ctx->is_ternary) post_ternary_table_delete(ctx, key_mask_buffer); if (key_buffer != NULL) free(key_buffer); if (key_mask_buffer != NULL) free(key_mask_buffer); return return_code; } int psabpf_table_entry_set_default_entry(psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry) { /* For default entry array map is used, it always has key 32-bit width and its value is assumed to be 0. */ const uint32_t key = 0; char *value_buffer = NULL; int return_code = NO_ERROR; if (ctx == NULL || entry == NULL) return EINVAL; if (ctx->default_entry.fd < 0) { fprintf(stderr, "can't add default entry: table not opened or table has no default entry\n"); return EBADF; } if (ctx->default_entry.key_size != sizeof(key) || ctx->default_entry.value_size == 0 || ctx->default_entry.value_size != ctx->table.value_size) { fprintf(stderr, "key size or value is not supported\n"); return ENOTSUP; } if (entry->action == NULL) { fprintf(stderr, "missing action specification\n"); return ENODATA; } /* prepare buffer for map value */ value_buffer = malloc(ctx->default_entry.value_size); if (value_buffer == NULL) { fprintf(stderr, "not enough memory\n"); return ENOMEM; } return_code = construct_buffer(value_buffer, ctx->default_entry.value_size, ctx, entry, fill_value_btf_info, fill_value_byte_by_byte); if (return_code != NO_ERROR) { fprintf(stderr, "failed to construct value\n"); goto clean_up; } /* Handle direct objects - default entry always exists * and is treated like a regular entry, including with regards to direct resources */ return_code = handle_direct_objects_write((void *) &key, value_buffer, &ctx->default_entry, ctx, entry, BPF_EXIST); if (return_code != NO_ERROR) { fprintf(stderr, "failed to handle direct objects: %s\n", strerror(return_code)); goto clean_up; } /* update map */ return_code = bpf_map_update_elem(ctx->default_entry.fd, &key, value_buffer, BPF_ANY); if (return_code != 0) { return_code = errno; fprintf(stderr, "failed to set up entry: %s\n", strerror(errno)); } else { return_code = clear_table_cache(&ctx->cache); if (return_code != NO_ERROR) { fprintf(stderr, "failed to clear cache: %s\n", strerror(return_code)); } } clean_up: if (value_buffer != NULL) free(value_buffer); return return_code; } static int parse_table_value_no_btf(psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry, const void *value) { size_t buffer_size = ctx->table.value_size; /* Action ID */ if (ctx->is_indirect == false) { if (buffer_size < sizeof(uint32_t)) { fprintf(stderr, "too small value type\n"); return EINVAL; } entry->action->action_id = *((uint32_t *) value); value += sizeof(uint32_t); buffer_size -= sizeof(uint32_t); } /* Priority */ if (ctx->is_ternary) { if (buffer_size < sizeof(uint32_t)) { fprintf(stderr, "too small value type\n"); return EINVAL; } entry->priority = *((uint32_t *) value); value += sizeof(uint32_t); buffer_size -= sizeof(uint32_t); } /* Action data, without BTF we can only return binary blob */ if (buffer_size > 0) { entry->action->params = malloc(sizeof(psabpf_action_param_t)); if (entry->action->params == NULL) return ENOMEM; entry->action->n_params = 1; return psabpf_action_param_create(&entry->action->params[0], value, buffer_size); } return NO_ERROR; } static int parse_table_value_action(psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry, const void *value, uint32_t value_type_id) { /* Get action ID */ psabtf_struct_member_md_t action_id_md = {}; if (psabtf_get_member_md_by_name(ctx->btf_metadata.btf, value_type_id, "action", &action_id_md) != NO_ERROR) return ENOENT; size_t action_id_size = psabtf_get_type_size_by_id(ctx->btf_metadata.btf, action_id_md.effective_type_id); if (action_id_size > sizeof(entry->action->action_id)) return EINVAL; entry->action->action_id = 0; memcpy(&entry->action->action_id, value + action_id_md.bit_offset / 8, action_id_size); /* Get action params */ psabtf_struct_member_md_t union_md = {}; if (psabtf_get_member_md_by_name(ctx->btf_metadata.btf, value_type_id, "u", &union_md) != NO_ERROR) return EINVAL; psabtf_struct_member_md_t action_md = {}; if (psabtf_get_member_md_by_index(ctx->btf_metadata.btf, union_md.effective_type_id, entry->action->action_id, &action_md) != NO_ERROR) return EINVAL; const struct btf_type *action_type = psabtf_get_type_by_id(ctx->btf_metadata.btf, action_md.effective_type_id); if (action_type == NULL) return EINVAL; if (!btf_is_struct(action_type)) return EINVAL; const unsigned number_of_params = btf_vlen(action_type); if (number_of_params == 0) return NO_ERROR; entry->action->params = malloc(number_of_params * sizeof(psabpf_action_param_t)); if (entry->action->params == NULL) return ENOMEM; entry->action->n_params = number_of_params; const size_t base_offset = (union_md.bit_offset + action_md.bit_offset) / 8; const struct btf_member *member = btf_members(action_type); for (unsigned i = 0; i < number_of_params; i++, member++) { psabtf_struct_member_md_t param_md = {}; if (psabtf_get_member_md_by_index(ctx->btf_metadata.btf, action_md.effective_type_id, i, &param_md) != NO_ERROR) return EINVAL; size_t offset = base_offset + param_md.bit_offset / 8; size_t size = psabtf_get_type_size_by_id(ctx->btf_metadata.btf, param_md.effective_type_id); if (size + offset > ctx->table.value_size) return EINVAL; int ret = psabpf_action_param_create(&entry->action->params[i], value + offset, size); entry->action->params[i].param_id = i; if (ret != NO_ERROR) return ret; } return NO_ERROR; } static int parse_table_value_priority(psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry, const void *value, uint32_t value_type_id) { if (ctx->is_ternary == false) return NO_ERROR; psabtf_struct_member_md_t priority_md = {}; if (psabtf_get_member_md_by_name(ctx->btf_metadata.btf, value_type_id, "priority", &priority_md) != NO_ERROR) return ENOENT; size_t size = psabtf_get_type_size_by_id(ctx->btf_metadata.btf, priority_md.effective_type_id); if (size > sizeof(entry->priority)) return EINVAL; entry->priority = 0; memcpy(&entry->priority, value + priority_md.bit_offset / 8, size); return NO_ERROR; } static int parse_table_value_direct_counter(psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry, const void *value) { if (ctx->n_direct_counters == 0) return NO_ERROR; entry->direct_counters = malloc(ctx->n_direct_counters * sizeof(psabpf_direct_counter_entry_t)); if (entry->direct_counters == NULL) return ENOMEM; for (unsigned i = 0; i < ctx->n_direct_counters; i++) { psabpf_counter_entry_init(&entry->direct_counters[i].counter); entry->direct_counters[i].counter_idx = ctx->direct_counters_ctx[i].counter_idx; convert_counter_data_to_entry(value + ctx->direct_counters_ctx[i].counter_offset, ctx->direct_counters_ctx[i].counter_size, ctx->direct_counters_ctx[i].counter_type, &entry->direct_counters[i].counter); } entry->n_direct_counters = ctx->n_direct_counters; return NO_ERROR; } static int parse_table_value_direct_meter(psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry, const void *value) { if (ctx->n_direct_meters == 0) return NO_ERROR; entry->direct_meters = malloc(ctx->n_direct_meters * sizeof(psabpf_direct_meter_entry_t)); if (entry->direct_meters == NULL) return ENOMEM; for (unsigned i = 0; i < ctx->n_direct_meters; i++) { psabpf_meter_entry_init(&entry->direct_meters[i].meter); entry->direct_meters[i].meter_idx = ctx->direct_meters_ctx[i].meter_idx; convert_meter_data_to_entry(value + ctx->direct_meters_ctx[i].meter_offset, &entry->direct_meters[i].meter); } entry->n_direct_meters = ctx->n_direct_meters; return NO_ERROR; } static int parse_table_value_direct_objects(psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry, const void *value) { int ret = parse_table_value_direct_counter(ctx, entry, value); if (ret != NO_ERROR) return ret; ret = parse_table_value_direct_meter(ctx, entry, value); if (ret != NO_ERROR) return ret; return NO_ERROR; } static int parse_table_value_references(psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry, const void *value) { unsigned number_of_implementations = ctx->table_implementations.n_fields; if (number_of_implementations < 1) return NO_ERROR; entry->action->params = malloc(number_of_implementations * sizeof(psabpf_action_param_t)); if (entry->action->params == NULL) return ENOMEM; entry->action->n_params = number_of_implementations; for (unsigned i = 0; i < number_of_implementations; i++) { psabpf_action_param_create(&entry->action->params[i], value + ctx->table_implementations.fields[i].data_offset, ctx->table_implementations.fields[i].data_len); entry->action->params[i].param_id = i; if (ctx->table_implementation_group_marks.fields[i].type == PSABPF_STRUCT_FIELD_TYPE_DATA) { /* Has group mark */ const uint32_t *is_group = value + ctx->table_implementation_group_marks.fields[i].data_offset; if (*is_group != 0) entry->action->params[i].is_group_reference = true; } } return NO_ERROR; } static int parse_table_value_btf_info(psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry, const void *value) { int ret; uint32_t value_type_id = get_table_value_type_id(ctx); if (value_type_id == 0) return ENOENT; if (ctx->is_indirect == false) { ret = parse_table_value_action(ctx, entry, value, value_type_id); if (ret != NO_ERROR) return ret; } else { ret = parse_table_value_references(ctx, entry, value); if (ret != NO_ERROR) return ret; } ret = parse_table_value_priority(ctx, entry, value, value_type_id); if (ret != NO_ERROR) return ret; ret = parse_table_value_direct_objects(ctx, entry, value); if (ret != NO_ERROR) return ret; return NO_ERROR; } static int parse_table_value(psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry, const void *value) { entry->action = malloc(sizeof(psabpf_action_t)); if (entry->action == NULL) return ENOMEM; psabpf_action_init(entry->action); if (ctx->btf_metadata.btf == NULL || ctx->table.btf_type_id == 0) return parse_table_value_no_btf(ctx, entry, value); return parse_table_value_btf_info(ctx, entry, value); } int psabpf_table_entry_get(psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry) { char *key_buffer = NULL; char *key_mask_buffer = NULL; char *value_buffer = NULL; int return_code = NO_ERROR; if (ctx == NULL || entry == NULL) return EINVAL; if (entry->n_keys == 0 || entry->match_keys == NULL) { fprintf(stderr, "can't get entry: missing key\n"); return ENODATA; } if (ctx->is_ternary) { return_code = ternary_table_open_tuple(ctx, entry, &key_mask_buffer, BPF_EXIST); if (return_code != NO_ERROR) goto clean_up; } if (ctx->table.fd < 0) { fprintf(stderr, "can't get entry: table not opened\n"); return_code = EBADF; goto clean_up; } if (ctx->table.key_size == 0 || ctx->table.value_size == 0) { fprintf(stderr, "zero-size key or value is not supported\n"); return_code = EINVAL; goto clean_up; } /* Prepare entry - remove everything but not key */ size_t tmp_n_keys = entry->n_keys; entry->n_keys = 0; void *tmp_keys = entry->match_keys; entry->match_keys = NULL; psabpf_table_entry_free(entry); psabpf_table_entry_init(entry); entry->n_keys = tmp_n_keys; entry->match_keys = tmp_keys; /* prepare buffers for map key/value */ key_buffer = malloc(ctx->table.key_size); value_buffer = malloc(ctx->table.value_size); if (key_buffer == NULL || value_buffer == NULL) { fprintf(stderr, "not enough memory\n"); return_code = ENOMEM; goto clean_up; } return_code = construct_buffer(key_buffer, ctx->table.key_size, ctx, entry, fill_key_btf_info, fill_key_byte_by_byte); if (return_code != NO_ERROR) { fprintf(stderr, "failed to construct key\n"); goto clean_up; } if (ctx->is_ternary == true && key_mask_buffer != NULL) mem_bitwise_and((uint32_t *) key_buffer, (uint32_t *) key_mask_buffer, ctx->table.key_size); return_code = bpf_map_lookup_elem(ctx->table.fd, key_buffer, value_buffer); if (return_code != 0) { return_code = errno; fprintf(stderr, "failed to get entry: %s\n", strerror(return_code)); goto clean_up; } /* No need to parse key - already provided by user */ /* Parse value */ return_code = parse_table_value(ctx, entry, value_buffer); if (return_code != NO_ERROR) fprintf(stderr, "failed to parse entry: %s\n", strerror(return_code)); clean_up: if (key_buffer != NULL) free(key_buffer); if (key_mask_buffer != NULL) free(key_mask_buffer); if (value_buffer != NULL) free(value_buffer); if (ctx->is_ternary) ternary_table_close_tuple(ctx); return return_code; } static int parse_table_key_no_btf(psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry, const void *key, const void *key_mask) { psabpf_match_key_t mk; psabpf_matchkey_init(&mk); if (ctx->is_ternary) { psabpf_matchkey_type(&mk, PSABPF_TERNARY); psabpf_matchkey_data(&mk, key, ctx->table.key_size); psabpf_matchkey_mask(&mk, key_mask, ctx->table.key_size); } else if (ctx->table.type == BPF_MAP_TYPE_LPM_TRIE) { psabpf_matchkey_type(&mk, PSABPF_LPM); /* We should change byte order back to host order. It isn't doable because * there is no information how long is the last field - this is the only one * field in the network byte order. */ psabpf_matchkey_data(&mk, key + sizeof(uint32_t), ctx->table.key_size - sizeof(uint32_t)); psabpf_matchkey_prefix_len(&mk, *((uint32_t *) key)); } else { psabpf_matchkey_type(&mk, PSABPF_EXACT); psabpf_matchkey_data(&mk, key, ctx->table.key_size); } psabpf_table_entry_matchkey(entry, &mk); psabpf_matchkey_free(&mk); return NO_ERROR; } static enum psabpf_matchkind_t decode_key_field_type_btf_info(psabpf_table_entry_ctx_t *ctx, const void *field_mask, size_t field_len, uint32_t type_fields, uint32_t field_id) { if (ctx->is_ternary) { /* LPM is not distinguishable from ternary field. Exact can be detected when mask has all-set bits. */ for (size_t i = 0; i < field_len; ++i) { if (*((uint8_t *)(field_mask + i)) != 0xFF) return PSABPF_TERNARY; } } else if (ctx->table.type == BPF_MAP_TYPE_LPM_TRIE) { /* Last field is lpm, others are exact. */ if (field_id + 1 == type_fields) return PSABPF_LPM; } return PSABPF_EXACT; } static int parse_table_key_add_key_field(psabpf_table_entry_t *entry, int field_type, const void *field_data, const void *field_mask, uint32_t prefix, size_t field_len) { if (field_len < 1) return ENODATA; psabpf_match_key_t mk; psabpf_matchkey_init(&mk); if (field_type == PSABPF_TERNARY) { psabpf_matchkey_type(&mk, PSABPF_TERNARY); psabpf_matchkey_data(&mk, field_data, field_len); psabpf_matchkey_mask(&mk, field_mask, field_len); } else if (field_type == PSABPF_LPM) { psabpf_matchkey_type(&mk, PSABPF_LPM); psabpf_matchkey_data(&mk, field_data, field_len); /* Convert network byte order into host order */ swap_byte_order(mk.data, mk.key_size); psabpf_matchkey_prefix_len(&mk, prefix); } else if (field_type == PSABPF_EXACT) { psabpf_matchkey_type(&mk, PSABPF_EXACT); psabpf_matchkey_data(&mk, field_data, field_len); } int ret = psabpf_table_entry_matchkey(entry, &mk); psabpf_matchkey_free(&mk); return ret; } static int parse_table_key_btf_info(psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry, const void *key, const void *key_mask) { uint32_t key_type_id = psabtf_get_member_type_id_by_name(ctx->btf_metadata.btf, ctx->table.btf_type_id, "key"); if (key_type_id == 0) return EINVAL; const struct btf_type *key_type = psabtf_get_type_by_id(ctx->btf_metadata.btf, key_type_id); if (key_type == NULL) return EINVAL; if (btf_kind(key_type) == BTF_KIND_INT) { int field_type = decode_key_field_type_btf_info(ctx, key_mask, ctx->table.key_size, 1, 0); uint32_t prefix = 0; if (field_type == PSABPF_LPM) { prefix = *((uint32_t *) key); key = key + sizeof(uint32_t); } return parse_table_key_add_key_field(entry, field_type, key, key_mask, prefix, ctx->table.key_size); } if (btf_kind(key_type) != BTF_KIND_STRUCT) return EINVAL; const struct btf_member *member = btf_members(key_type); unsigned entries = btf_vlen(key_type); uint32_t global_prefix = 0; for (unsigned member_idx = 0; member_idx < entries; member_idx++, member++) { if (member_idx == 0 && ctx->table.type == BPF_MAP_TYPE_LPM_TRIE) { global_prefix = *((uint32_t *) key); continue; } if (is_table_dummy_key(ctx, key_type, key_type_id)) continue; /* assume that every field is byte aligned */ unsigned offset = btf_member_bit_offset(key_type, member_idx) / 8; unsigned member_size = psabtf_get_type_size_by_id(ctx->btf_metadata.btf, member->type); int field_type = decode_key_field_type_btf_info(ctx, key_mask + offset, member_size, entries, member_idx); uint32_t prefix = global_prefix + 32 - offset * 8; int ret = parse_table_key_add_key_field(entry, field_type, key + offset, key_mask + offset, prefix, member_size); if (ret != NO_ERROR) return ret; } return NO_ERROR; } static int parse_table_key(psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry, const void *key, const void *key_mask) { if (ctx->btf_metadata.btf == NULL || ctx->table.btf_type_id == 0) return parse_table_key_no_btf(ctx, entry, key, key_mask); return parse_table_key_btf_info(ctx, entry, key, key_mask); } static int get_next_ternary_table_key_mask(psabpf_table_entry_ctx_t *ctx) { int ret_code = NO_ERROR; void *prefix_value = NULL; void *next_key = NULL; uint8_t has_next_mask; uint32_t tuple_id; uint32_t inner_map_id; struct ternary_table_prefix_metadata prefix_md; if ((ret_code = get_ternary_table_prefix_md(ctx, &prefix_md)) != NO_ERROR) return ret_code; prefix_value = malloc(ctx->prefixes.value_size); next_key = malloc(ctx->table.key_size); /* Iterate in order assumed by data plane algorithm */ if (ctx->current_raw_key_mask == NULL) ctx->current_raw_key_mask = calloc(1, ctx->prefixes.key_size); if (prefix_value == NULL || next_key == NULL || ctx->current_raw_key_mask == NULL) { ret_code = ENOMEM; goto clean_up; } for (unsigned i = 0; i < ctx->prefixes.max_entries; ++i) { /* Let's see if current mask has next key entry. */ if (ctx->table.fd >= 0) { if (bpf_map_get_next_key(ctx->table.fd, ctx->current_raw_key, next_key) == 0) break; } /* No next key, get current mask metadata. */ if (bpf_map_lookup_elem(ctx->prefixes.fd, ctx->current_raw_key_mask, prefix_value) != 0) { ret_code = ENOENT; break; } has_next_mask = *((uint8_t *) (prefix_value + prefix_md.has_next_offset)); if (has_next_mask == 0) break; /* Restart get next key for next tuple. */ if (ctx->current_raw_key != NULL) free(ctx->current_raw_key); ctx->current_raw_key = NULL; /* Go to the next tuple. */ ternary_table_close_tuple(ctx); memcpy(ctx->current_raw_key_mask, prefix_value + prefix_md.next_mask_offset, ctx->prefixes.key_size); if (bpf_map_lookup_elem(ctx->prefixes.fd, ctx->current_raw_key_mask, prefix_value) != 0) { ret_code = ENOENT; break; } tuple_id = *((uint32_t *) (prefix_value + prefix_md.tuple_id_offset)); if (bpf_map_lookup_elem(ctx->tuple_map.fd, &tuple_id, &inner_map_id) != 0) { ret_code = ENOENT; break; } ctx->table.fd = bpf_map_get_fd_by_id(inner_map_id); } clean_up: if (prefix_value != NULL) free(prefix_value); if (next_key != NULL) free(next_key); if (ret_code != NO_ERROR && ctx->current_raw_key_mask != NULL) { free(ctx->current_raw_key_mask); ctx->current_raw_key_mask = NULL; } return ret_code; } psabpf_table_entry_t *psabpf_table_entry_get_next(psabpf_table_entry_ctx_t *ctx) { psabpf_table_entry_t *ret_instance = NULL; void *next_key = NULL; /* do not free */ void *value_buffer = NULL; if (ctx == NULL) return NULL; if (ctx->is_ternary) { if (get_next_ternary_table_key_mask(ctx) != NO_ERROR) { if (ctx->table.fd < 0) return NULL; /* Silently ignore error when table is empty */ fprintf(stderr, "failed to iterate over table key masks\n"); return NULL; } } if (ctx->table.fd < 0) { fprintf(stderr, "can't get entry: table not opened\n"); return NULL; } if (ctx->table.key_size == 0 || ctx->table.value_size == 0) { fprintf(stderr, "zero-size key or value is not supported\n"); return NULL; } next_key = malloc(ctx->table.key_size); if (next_key == NULL) { fprintf(stderr, "not enough memory\n"); goto clean_up; } if (bpf_map_get_next_key(ctx->table.fd, ctx->current_raw_key, next_key) != 0) { /* restart iteration */ if (ctx->is_ternary) ternary_table_close_tuple(ctx); if (ctx->current_raw_key != NULL) free(ctx->current_raw_key); ctx->current_raw_key = NULL; if (ctx->current_raw_key_mask != NULL) free(ctx->current_raw_key_mask); ctx->current_raw_key_mask = NULL; goto clean_up; } if (ctx->current_raw_key != NULL) free(ctx->current_raw_key); ctx->current_raw_key = next_key; value_buffer = malloc(ctx->table.value_size); if (value_buffer == NULL || ctx->current_raw_key == NULL) { fprintf(stderr, "not enough memory\n"); goto clean_up; } int return_code = bpf_map_lookup_elem(ctx->table.fd, ctx->current_raw_key, value_buffer); if (return_code != 0) { return_code = errno; fprintf(stderr, "failed to get entry: %s\n", strerror(return_code)); goto clean_up; } psabpf_table_entry_free(&ctx->current_entry); psabpf_table_entry_init(&ctx->current_entry); /* Parse key */ return_code = parse_table_key(ctx, &ctx->current_entry, ctx->current_raw_key, ctx->current_raw_key_mask); if (return_code != NO_ERROR) { fprintf(stderr, "failed to parse entry: %s\n", strerror(return_code)); goto clean_up; } /* Parse value */ return_code = parse_table_value(ctx, &ctx->current_entry, value_buffer); if (return_code != NO_ERROR) { fprintf(stderr, "failed to parse entry: %s\n", strerror(return_code)); goto clean_up; } ret_instance = &ctx->current_entry; clean_up: if (value_buffer) free(value_buffer); return ret_instance; } int psabpf_table_entry_get_default_entry(psabpf_table_entry_ctx_t *ctx, psabpf_table_entry_t *entry) { if (ctx == NULL || entry == NULL) return EINVAL; uint32_t key_buffer = 0; char *value_buffer = NULL; int return_code = NO_ERROR; if (ctx == NULL || entry == NULL) return EINVAL; if (ctx->default_entry.fd < 0) { fprintf(stderr, "can't get default entry: table not opened or not exists\n"); return EBADF; } if (ctx->default_entry.value_size == 0 || ctx->default_entry.value_size != ctx->table.value_size) { fprintf(stderr, "invalid value size for a default entry\n"); return EINVAL; } /* Prepare entry - remove everything from entry */ psabpf_table_entry_free(entry); psabpf_table_entry_init(entry); value_buffer = malloc(ctx->table.value_size); if (value_buffer == NULL) { fprintf(stderr, "not enough memory\n"); return ENOMEM; } return_code = bpf_map_lookup_elem(ctx->default_entry.fd, &key_buffer, value_buffer); if (return_code != 0) { return_code = errno; fprintf(stderr, "failed to get default entry: %s\n", strerror(return_code)); goto clean_up; } /* No need to parse key - it does not exist */ /* Parse value */ return_code = parse_table_value(ctx, entry, value_buffer); if (return_code != NO_ERROR) fprintf(stderr, "failed to parse default entry: %s\n", strerror(return_code)); clean_up: if (value_buffer != NULL) free(value_buffer); return return_code; }
34.908845
139
0.635909
[ "object" ]
a8b9063f8a721346e8a8bf82ced272c134059cf6
16,335
h
C
src/k2/connector/pggate/catalog/table_info_handler.h
futurewei-cloud/chogori-sql
29b1ffd6610616c8571b96aa2366bccc3685e9c0
[ "Apache-2.0" ]
3
2021-07-05T09:00:18.000Z
2022-03-18T20:08:33.000Z
src/k2/connector/pggate/catalog/table_info_handler.h
futurewei-cloud/chogori-sql
29b1ffd6610616c8571b96aa2366bccc3685e9c0
[ "Apache-2.0" ]
11
2021-09-24T16:52:30.000Z
2022-03-15T23:12:37.000Z
src/k2/connector/pggate/catalog/table_info_handler.h
futurewei-cloud/chogori-sql
29b1ffd6610616c8571b96aa2366bccc3685e9c0
[ "Apache-2.0" ]
1
2021-07-05T09:01:58.000Z
2021-07-05T09:01:58.000Z
/* MIT License Copyright(c) 2020 Futurewei Cloud 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. */ #pragma once #include <string> #include <vector> #include "pggate/catalog/sql_catalog_defaults.h" #include "pggate/catalog/sql_catalog_entity.h" #include "pggate/k2_adapter.h" #include "entities/entity_ids.h" #include "catalog_log.h" namespace k2pg { namespace sql { namespace catalog { using k2pg::gate::CreateScanReadResult; using k2pg::gate::K2Adapter; using k2pg::sql::PgObjectId; using k2pg::Status; struct CreateMetaTablesResult { Status status; }; struct CreateUpdateTableResult { Status status; }; struct CopySKVTableResult { Status status; }; struct GetTableResult { Status status; std::shared_ptr<TableInfo> tableInfo; }; struct GetTableSchemaResult { Status status; std::shared_ptr<TableInfo> tableInfo; }; struct ListTablesResult { Status status; std::vector<std::shared_ptr<TableInfo>> tableInfos; }; struct ListTableIdsResult { Status status; std::vector<std::string> tableIds; }; struct CopyTableResult { Status status; std::shared_ptr<TableInfo> tableInfo; int num_index = 0; }; struct CreateSKVSchemaResult { Status status; }; struct PersistTableMetaResult { Status status; }; struct PersistIndexMetaResult { Status status; }; struct DeleteTableResult { Status status; }; struct DeleteIndexResult { Status status; }; struct GetBaseTableIdResult { Status status; std::string baseTableId; }; struct GetTableTypeInfoResult { Status status; bool isShared; bool isIndex; }; struct CreateIndexTableResult { Status status; std::shared_ptr<IndexInfo> indexInfo; }; struct CreateIndexTableParams { std::string index_name; uint32_t table_oid; Schema index_schema; bool is_unique; bool is_shared; bool is_not_exist; bool skip_index_backfill; IndexPermissions index_permissions; }; class TableInfoHandler { public: typedef std::shared_ptr<TableInfoHandler> SharedPtr; TableInfoHandler(std::shared_ptr<K2Adapter> k2_adapter); ~TableInfoHandler(); // Design Note: (tables mapping to SKV schema) // 1. Any table primary index(must have) is mapped to a SKV schema, and if it have secondary index(s), each one is mapped to its own SKV schema. // 2. Following three SKV schemas are for three system meta tables holding all table/index definition(aka. meta), i.e. tablemeta(table identities and basic info), tablecolumnmeta(column def), indexcolumnmeta(index column def) // 3. The schema name for meta tables are hardcoded constant, e.g. tablemeta's is CatalogConsts::skv_schema_name_table_meta // 4. The schema name for user table/secondary index are the table's TableId(), which is a string presentation of UUID containing tables's pguid (for details, see std::string PgObjectId::GetTableId(const PgOid& table_oid)) // 5. As of now, before embedded table(s) are supported, all tables are flat in relationship with each other. Thus, all tables(meta or user) have two prefix fields "TableId" and "IndexId" in their SKV schema, // so that all rows in a table and index are clustered together in K2. // For a primary index, the TableId is the PgOid(uint32 but saved as int64_t in K2) of this table, and IndexId is 0 // For a secondary index, The TableId is the PgOid of base table(primary index), and IndexId is its own PgOid. // For three system tables which is not defined in PostgreSQL originally, the PgOid of them are taken from unused system Pgoid range 4800-4803 (for detail, see CatalogConsts::oid_table_meta) // schema of table information k2::dto::Schema skv_schema_table_meta { .name = CatalogConsts::skv_schema_name_table_meta, .version = 1, .fields = std::vector<k2::dto::SchemaField> { {k2::dto::FieldType::INT64T, "SchemaTableId", false, false}, // const PgOid CatalogConsts::oid_table_meta = 4800; {k2::dto::FieldType::INT64T, "SchemaIndexId", false, false}, // 0 {k2::dto::FieldType::STRING, "TableId", false, false}, {k2::dto::FieldType::STRING, "TableName", false, false}, {k2::dto::FieldType::INT64T, "TableOid", false, false}, {k2::dto::FieldType::STRING, "TableUuid", false, false}, {k2::dto::FieldType::BOOL, "IsSysTable", false, false}, {k2::dto::FieldType::BOOL, "IsShared", false, false}, {k2::dto::FieldType::BOOL, "IsIndex", false, false}, {k2::dto::FieldType::BOOL, "IsUnique", false, false}, {k2::dto::FieldType::STRING, "BaseTableId", false, false}, {k2::dto::FieldType::INT16T, "IndexPermission", false, false}, {k2::dto::FieldType::INT32T, "NextColumnId", false, false}, {k2::dto::FieldType::INT32T, "SchemaVersion", false, false}}, .partitionKeyFields = std::vector<uint32_t> { 0, 1, 2}, .rangeKeyFields = std::vector<uint32_t> {} }; // schema to store table column schema information k2::dto::Schema skv_schema_tablecolumn_meta { .name = CatalogConsts::skv_schema_name_tablecolumn_meta, .version = 1, .fields = std::vector<k2::dto::SchemaField> { {k2::dto::FieldType::INT64T, "SchemaTableId", false, false}, // const PgOid CatalogConsts::oid_tablecolumn_meta = 4801; {k2::dto::FieldType::INT64T, "SchemaIndexId", false, false}, // 0 {k2::dto::FieldType::STRING, "TableId", false, false}, {k2::dto::FieldType::INT32T, "ColumnId", false, false}, {k2::dto::FieldType::STRING, "ColumnName", false, false}, {k2::dto::FieldType::INT16T, "ColumnType", false, false}, {k2::dto::FieldType::BOOL, "IsNullable", false, false}, {k2::dto::FieldType::BOOL, "IsPrimary", false, false}, {k2::dto::FieldType::BOOL, "IsHash", false, false}, {k2::dto::FieldType::INT32T, "Order", false, false}, {k2::dto::FieldType::INT16T, "SortingType", false, false}}, .partitionKeyFields = std::vector<uint32_t> { 0 , 1, 2}, .rangeKeyFields = std::vector<uint32_t> {3} }; // schema to store index column schema information k2::dto::Schema skv_schema_indexcolumn_meta { .name = CatalogConsts::skv_schema_name_indexcolumn_meta, .version = 1, .fields = std::vector<k2::dto::SchemaField> { {k2::dto::FieldType::INT64T, "SchemaTableId", false, false}, // const PgOid CatalogConsts::oid_indexcolumn_meta = 4802; {k2::dto::FieldType::INT64T, "SchemaIndexId", false, false}, // 0 {k2::dto::FieldType::STRING, "TableId", false, false}, {k2::dto::FieldType::INT32T, "ColumnId", false, false}, {k2::dto::FieldType::STRING, "ColumnName", false, false}, {k2::dto::FieldType::INT16T, "ColumnType", false, false}, {k2::dto::FieldType::BOOL, "IsNullable", false, false}, {k2::dto::FieldType::BOOL, "IsHash", false, false}, {k2::dto::FieldType::BOOL, "IsRange", false, false}, {k2::dto::FieldType::INT32T, "Order", false, false}, {k2::dto::FieldType::INT16T, "SortingType", false, false}, {k2::dto::FieldType::INT32T, "BaseColumnId", false, false}}, .partitionKeyFields = std::vector<uint32_t> { 0, 1, 2}, .rangeKeyFields = std::vector<uint32_t> {3} }; // create above three meta tables for a DB CreateMetaTablesResult CreateMetaTables(std::shared_ptr<PgTxnHandler> txnHandler, const std::string& collection_name); // Create or update a user defined table fully, including all its secondary indexes if any. CreateUpdateTableResult CreateOrUpdateTable(std::shared_ptr<PgTxnHandler> txnHandler, const std::string& collection_name, std::shared_ptr<TableInfo> table); GetTableResult GetTable(std::shared_ptr<PgTxnHandler> txnHandler, const std::string& collection_name, const std::string& database_name, const std::string& table_id); GetTableSchemaResult GetTableSchema(std::shared_ptr<PgTxnHandler> txnHandler, std::shared_ptr<DatabaseInfo> database_info, const std::string& table_id, std::shared_ptr<IndexInfo> index_info, std::function<std::shared_ptr<DatabaseInfo>(const std::string&)> fnc_db, std::function<std::shared_ptr<PgTxnHandler>()> fnc_tx); ListTablesResult ListTables(std::shared_ptr<PgTxnHandler> txnHandler, const std::string& collection_name, const std::string& database_name, bool isSysTableIncluded); ListTableIdsResult ListTableIds(std::shared_ptr<PgTxnHandler> txnHandler, const std::string& collection_name, bool isSysTableIncluded); // CopyTable (meta and data) fully including secondary indexes, currently only support cross different database. CopyTableResult CopyTable(std::shared_ptr<PgTxnHandler> target_txnHandler, const std::string& target_coll_name, const std::string& target_database_name, uint32_t target_database_oid, std::shared_ptr<PgTxnHandler> source_txnHandler, const std::string& source_coll_name, const std::string& source_database_name, const std::string& source_table_id); CreateSKVSchemaResult CreateIndexSKVSchema(std::shared_ptr<PgTxnHandler> txnHandler, const std::string& collection_name, std::shared_ptr<TableInfo> table, const IndexInfo& index_info); PersistIndexMetaResult PersistIndexMeta(std::shared_ptr<PgTxnHandler> txnHandler, const std::string& collection_name, std::shared_ptr<TableInfo> table, const IndexInfo& index_info); DeleteTableResult DeleteTableMetadata(std::shared_ptr<PgTxnHandler> txnHandler, const std::string& collection_name, std::shared_ptr<TableInfo> table); DeleteTableResult DeleteTableData(std::shared_ptr<PgTxnHandler> txnHandler, const std::string& collection_name, std::shared_ptr<TableInfo> table); DeleteIndexResult DeleteIndexMetadata(std::shared_ptr<PgTxnHandler> txnHandler, const std::string& collection_name, const std::string& index_id); DeleteIndexResult DeleteIndexData(std::shared_ptr<PgTxnHandler> txnHandler, const std::string& collection_name, const std::string& index_id); GetBaseTableIdResult GetBaseTableId(std::shared_ptr<PgTxnHandler> txnHandler, const std::string& collection_name, const std::string& index_id); // check if passed id is that for a table or index, and if it is a shared table/index(just one instance shared by all databases and resides in primary cluster) GetTableTypeInfoResult GetTableTypeInfo(std::shared_ptr<PgTxnHandler> txnHandler, const std::string& collection_name, const std::string& table_id); // create index table (handle create if exists flag) CreateIndexTableResult CreateIndexTable(std::shared_ptr<PgTxnHandler> txnHandler, std::shared_ptr<DatabaseInfo> database_info, std::shared_ptr<TableInfo> base_table_info, CreateIndexTableParams &index_params); private: CopySKVTableResult CopySKVTable(std::shared_ptr<PgTxnHandler> target_txnHandler, const std::string& target_coll_name, const std::string& target_schema_name, uint32_t target_schema_version, std::shared_ptr<PgTxnHandler> source_txnHandler, const std::string& source_coll_name, const std::string& source_schema_name, uint32_t source_schema_version, PgOid source_table_oid, PgOid source_index_oid); // A SKV Schema of perticular version is not mutable, thus, we only create a new specified version if that version doesn't exists yet CreateSKVSchemaResult CreateTableSKVSchema(std::shared_ptr<PgTxnHandler> txnHandler, const std::string& collection_name, std::shared_ptr<TableInfo> table); // Persist (user) table's definition/meta into three sytem meta tables. PersistTableMetaResult PersistTableMeta(std::shared_ptr<PgTxnHandler> txnHandler, const std::string& collection_name, std::shared_ptr<TableInfo> table); std::shared_ptr<k2::dto::Schema> DeriveSKVSchemaFromTableInfo(std::shared_ptr<TableInfo> table); std::vector<std::shared_ptr<k2::dto::Schema>> DeriveIndexSchemas(std::shared_ptr<TableInfo> table); std::shared_ptr<k2::dto::Schema> DeriveIndexSchema(const IndexInfo& index_info); k2::dto::SKVRecord DeriveTableMetaRecord(const std::string& collection_name, std::shared_ptr<TableInfo> table); k2::dto::SKVRecord DeriveTableMetaRecordOfIndex(const std::string& collection_name, const IndexInfo& index, bool is_sys_table, int32_t next_column_id); std::vector<k2::dto::SKVRecord> DeriveTableColumnMetaRecords(const std::string& collection_name, std::shared_ptr<TableInfo> table); std::vector<k2::dto::SKVRecord> DeriveIndexColumnMetaRecords(const std::string& collection_name, const IndexInfo& index, const Schema& base_tablecolumn_schema); k2::dto::FieldType ToK2Type(DataType type); DataType ToSqlType(k2::dto::FieldType type); Status FetchTableMetaSKVRecord(std::shared_ptr<PgTxnHandler> txnHandler, const std::string& collection_name, const std::string& table_id, k2::dto::SKVRecord& resultSKVRecord); // TODO: change following API return Status instead of throw exception std::vector<k2::dto::SKVRecord> FetchIndexMetaSKVRecords(std::shared_ptr<PgTxnHandler> txnHandler, const std::string& collection_name, const std::string& base_table_id); std::vector<k2::dto::SKVRecord> FetchTableColumnMetaSKVRecords(std::shared_ptr<PgTxnHandler> txnHandler, const std::string& collection_name, const std::string& table_id); std::vector<k2::dto::SKVRecord> FetchIndexColumnMetaSKVRecords(std::shared_ptr<PgTxnHandler> txnHandler, const std::string& collection_name, const std::string& table_id); std::shared_ptr<TableInfo> BuildTableInfo(const std::string& database_id, const std::string& database_name, k2::dto::SKVRecord& table_meta, std::vector<k2::dto::SKVRecord>& table_columns); IndexInfo BuildIndexInfo(std::shared_ptr<PgTxnHandler> txnHandler, const std::string& collection_name, k2::dto::SKVRecord& index_table_meta); IndexInfo BuildIndexInfo(std::shared_ptr<TableInfo> base_table_info, std::string index_name, uint32_t table_oid, std::string index_uuid, const Schema& index_schema, bool is_unique, bool is_shared, IndexPermissions index_permissions); void AddDefaultPartitionKeys(std::shared_ptr<k2::dto::Schema> schema); // Build a range record for a scan, optionally using third param table_id when applicable(e.g. in sys table). k2::dto::SKVRecord buildRangeRecord(const std::string& collection_name, std::shared_ptr<k2::dto::Schema> schema, PgOid table_oid, PgOid index_oid, std::optional<std::string> table_id); std::shared_ptr<k2::dto::Schema> table_meta_SKVSchema_; std::shared_ptr<k2::dto::Schema> tablecolumn_meta_SKVSchema_; std::shared_ptr<k2::dto::Schema> indexcolumn_meta_SKVSchema_; std::shared_ptr<K2Adapter> k2_adapter_; }; } // namespace catalog } // namespace sql } // namespace k2pg
50.261538
408
0.710193
[ "vector" ]
a8c60ee815e314b4c550635606c88c6bbe02a7c0
291
h
C
include/engine/GameScreen.h
nickfourtimes/overbourn
4fe0260222c454d9651b9fd6a5597148bdf0900d
[ "MIT" ]
null
null
null
include/engine/GameScreen.h
nickfourtimes/overbourn
4fe0260222c454d9651b9fd6a5597148bdf0900d
[ "MIT" ]
1
2020-06-08T14:31:17.000Z
2020-06-08T14:31:17.000Z
include/engine/GameScreen.h
nickfourtimes/overbourn
4fe0260222c454d9651b9fd6a5597148bdf0900d
[ "MIT" ]
null
null
null
#pragma once #include <SDL.h> class GameScreen { private: protected: public: GameScreen(); virtual ~GameScreen(); virtual void Init() = 0; virtual void Clean() = 0; virtual void Process(Uint32, SDL_Event&) = 0; virtual void Update(Uint32) = 0; virtual void Render(Uint32) = 0; };
15.315789
46
0.687285
[ "render" ]
a8c707551884e77845b1067f0b32681cb4133bb4
10,384
c
C
source/blender/python/generic/bpy_internal_import.c
linluofeng/upbge
50bc9bc923a41411461d662c0fddd58d1f0b3ab3
[ "Naumen", "Condor-1.1", "MS-PL" ]
1
2022-01-11T10:02:21.000Z
2022-01-11T10:02:21.000Z
source/blender/python/generic/bpy_internal_import.c
linluofeng/upbge
50bc9bc923a41411461d662c0fddd58d1f0b3ab3
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
source/blender/python/generic/bpy_internal_import.c
linluofeng/upbge
50bc9bc923a41411461d662c0fddd58d1f0b3ab3
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
/* * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** \file * \ingroup pygen * * This file defines replacements for pythons '__import__' and 'imp.reload' * functions which can import from blender textblocks. * * \note * This should eventually be replaced by import hooks (pep 302). */ #include <Python.h> #include <stddef.h> #include "MEM_guardedalloc.h" #include "DNA_text_types.h" #include "BLI_listbase.h" #include "BLI_path_util.h" #include "BLI_string.h" #include "BLI_utildefines.h" #include "BKE_main.h" /* UNUSED */ #include "BKE_text.h" /* txt_to_buf */ #include "py_capi_utils.h" #include "bpy_internal_import.h" /* own include */ static Main *bpy_import_main = NULL; static ListBase bpy_import_main_list; static PyMethodDef bpy_import_meth; static PyMethodDef bpy_reload_meth; static PyObject *imp_reload_orig = NULL; /* 'builtins' is most likely PyEval_GetBuiltins() */ /** * \note to the discerning developer, yes - this is nasty * monkey-patching our own import into Python's builtin 'imp' module. * * However Python's alternative is to use import hooks, * which are implemented in a way that we can't use our own importer as a * fall-back (instead we must try and fail - raise an exception every time). * Since importing from blenders text-blocks is not the common case * I prefer to use Pythons import by default and fall-back to * Blenders - which we can only do by intercepting import calls I'm afraid. * - Campbell */ void bpy_import_init(PyObject *builtins) { PyObject *item; PyObject *mod; PyDict_SetItemString(builtins, "__import__", item = PyCFunction_New(&bpy_import_meth, NULL)); Py_DECREF(item); /* move reload here * XXX, use import hooks */ mod = PyImport_ImportModuleLevel("importlib", NULL, NULL, NULL, 0); if (mod) { PyObject *mod_dict = PyModule_GetDict(mod); /* blender owns the function */ imp_reload_orig = PyDict_GetItemString(mod_dict, "reload"); Py_INCREF(imp_reload_orig); PyDict_SetItemString(mod_dict, "reload", item = PyCFunction_New(&bpy_reload_meth, NULL)); Py_DECREF(item); Py_DECREF(mod); } else { BLI_assert(!"unable to load 'importlib' module."); } } static void free_compiled_text(Text *text) { if (text->compiled) { Py_DECREF((PyObject *)text->compiled); } text->compiled = NULL; } struct Main *bpy_import_main_get(void) { return bpy_import_main; } void bpy_import_main_set(struct Main *maggie) { bpy_import_main = maggie; } void bpy_import_main_extra_add(struct Main *maggie) { BLI_addhead(&bpy_import_main_list, maggie); } void bpy_import_main_extra_remove(struct Main *maggie) { BLI_remlink_safe(&bpy_import_main_list, maggie); } /* returns a dummy filename for a textblock so we can tell what file a text block comes from */ void bpy_text_filename_get(char *fn, size_t fn_len, Text *text) { BLI_snprintf( fn, fn_len, "%s%c%s", ID_BLEND_PATH(bpy_import_main, &text->id), SEP, text->id.name + 2); } bool bpy_text_compile(Text *text) { char fn_dummy[FILE_MAX]; PyObject *fn_dummy_py; char *buf; bpy_text_filename_get(fn_dummy, sizeof(fn_dummy), text); /* if previously compiled, free the object */ free_compiled_text(text); fn_dummy_py = PyC_UnicodeFromByte(fn_dummy); buf = txt_to_buf(text, NULL); text->compiled = Py_CompileStringObject(buf, fn_dummy_py, Py_file_input, NULL, -1); MEM_freeN(buf); Py_DECREF(fn_dummy_py); if (PyErr_Occurred()) { PyErr_Print(); PyErr_Clear(); PySys_SetObject("last_traceback", NULL); free_compiled_text(text); return false; } else { return true; } } PyObject *bpy_text_import(Text *text) { char modulename[MAX_ID_NAME + 2]; int len; if (!text->compiled) { if (bpy_text_compile(text) == false) { return NULL; } } len = strlen(text->id.name + 2); BLI_strncpy(modulename, text->id.name + 2, len); modulename[len - 3] = '\0'; /* remove .py */ return PyImport_ExecCodeModule(modulename, text->compiled); } PyObject *bpy_text_import_name(const char *name, int *found) { Text *text; char txtname[MAX_ID_NAME - 2]; int namelen = strlen(name); // XXX Main *maggie = bpy_import_main ? bpy_import_main : G_MAIN; Main *maggie = bpy_import_main; *found = 0; if (!maggie) { printf("ERROR: bpy_import_main_set() was not called before running python. this is a bug.\n"); return NULL; } /* we know this cant be importable, the name is too long for blender! */ if (namelen >= (MAX_ID_NAME - 2) - 3) { return NULL; } memcpy(txtname, name, namelen); memcpy(&txtname[namelen], ".py", 4); text = BLI_findstring(&maggie->texts, txtname, offsetof(ID, name) + 2); if (text) { *found = 1; return bpy_text_import(text); } /* If we still haven't found the module try additional modules form bpy_import_main_list */ maggie = bpy_import_main_list.first; while (maggie && !text) { text = BLI_findstring(&maggie->texts, txtname, offsetof(ID, name) + 2); maggie = maggie->next; } if (!text) { return NULL; } else { *found = 1; } return bpy_text_import(text); } /* * find in-memory module and recompile */ PyObject *bpy_text_reimport(PyObject *module, int *found) { Text *text; const char *name; const char *filepath; // XXX Main *maggie = bpy_import_main ? bpy_import_main : G_MAIN; Main *maggie = bpy_import_main; if (!maggie) { printf("ERROR: bpy_import_main_set() was not called before running python. this is a bug.\n"); return NULL; } *found = 0; /* get name, filename from the module itself */ if ((name = PyModule_GetName(module)) == NULL) { return NULL; } { PyObject *module_file = PyModule_GetFilenameObject(module); if (module_file == NULL) { return NULL; } filepath = _PyUnicode_AsString(module_file); Py_DECREF(module_file); if (filepath == NULL) { return NULL; } } /* look up the text object */ text = BLI_findstring(&maggie->texts, BLI_path_basename(filepath), offsetof(ID, name) + 2); /* uh-oh.... didn't find it */ if (!text) { return NULL; } else { *found = 1; } if (bpy_text_compile(text) == false) { return NULL; } /* make into a module */ return PyImport_ExecCodeModule(name, text->compiled); } static PyObject *blender_import(PyObject *UNUSED(self), PyObject *args, PyObject *kw) { PyObject *exception, *err, *tb; const char *name; int found = 0; PyObject *globals = NULL, *locals = NULL, *fromlist = NULL; int level = 0; /* relative imports */ PyObject *newmodule; static const char *_keywords[] = {"name", "globals", "locals", "fromlist", "level", NULL}; static _PyArg_Parser _parser = {"s|OOOi:bpy_import_meth", _keywords, 0}; if (!_PyArg_ParseTupleAndKeywordsFast( args, kw, &_parser, &name, &globals, &locals, &fromlist, &level)) { return NULL; } /* import existing builtin modules or modules that have been imported already */ newmodule = PyImport_ImportModuleLevel(name, globals, locals, fromlist, level); if (newmodule) { return newmodule; } PyErr_Fetch(&exception, &err, &tb); /* get the python error in case we cant import as blender text either */ /* importing from existing modules failed, see if we have this module as blender text */ newmodule = bpy_text_import_name(name, &found); if (newmodule) { /* found module as blender text, ignore above exception */ PyErr_Clear(); Py_XDECREF(exception); Py_XDECREF(err); Py_XDECREF(tb); /* printf("imported from text buffer...\n"); */ } else if (found == 1) { /* blender text module failed to execute but was found, use its error message */ Py_XDECREF(exception); Py_XDECREF(err); Py_XDECREF(tb); return NULL; } else { /* no blender text was found that could import the module * reuse the original error from PyImport_ImportModuleEx */ PyErr_Restore(exception, err, tb); } return newmodule; } /* * our reload() module, to handle reloading in-memory scripts */ static PyObject *blender_reload(PyObject *UNUSED(self), PyObject *module) { PyObject *exception, *err, *tb; PyObject *newmodule = NULL; int found = 0; /* try reimporting from file */ /* in Py3.3 this just calls imp.reload() which we overwrite, causing recursive calls */ // newmodule = PyImport_ReloadModule(module); newmodule = PyObject_CallFunctionObjArgs(imp_reload_orig, module, NULL); if (newmodule) { return newmodule; } /* no file, try importing from memory */ PyErr_Fetch(&exception, &err, &tb); /*restore for probable later use */ newmodule = bpy_text_reimport(module, &found); if (newmodule) { /* found module as blender text, ignore above exception */ PyErr_Clear(); Py_XDECREF(exception); Py_XDECREF(err); Py_XDECREF(tb); /* printf("imported from text buffer...\n"); */ } else if (found == 1) { /* blender text module failed to execute but was found, use its error message */ Py_XDECREF(exception); Py_XDECREF(err); Py_XDECREF(tb); return NULL; } else { /* no blender text was found that could import the module * reuse the original error from PyImport_ImportModuleEx */ PyErr_Restore(exception, err, tb); } return newmodule; } static PyMethodDef bpy_import_meth = {"bpy_import_meth", (PyCFunction)blender_import, METH_VARARGS | METH_KEYWORDS, "blenders import"}; static PyMethodDef bpy_reload_meth = { "bpy_reload_meth", (PyCFunction)blender_reload, METH_O, "blenders reload"};
26.901554
98
0.680663
[ "object" ]
a8cb67046312873b62395590d47eb35f1cb833f1
2,328
h
C
cpp/Platform.Disposables/Disposable[TPrimary, TAuxiliary].h
linksplatform/Disposables
8805eca02e1d9590e86a947a692271590750f41b
[ "MIT" ]
1
2020-12-19T11:57:43.000Z
2020-12-19T11:57:43.000Z
cpp/Platform.Disposables/Disposable[TPrimary, TAuxiliary].h
linksplatform/Disposables
8805eca02e1d9590e86a947a692271590750f41b
[ "MIT" ]
49
2019-07-12T11:03:01.000Z
2022-02-17T14:15:13.000Z
cpp/Platform.Disposables/Disposable[TPrimary, TAuxiliary].h
linksplatform/Disposables
8805eca02e1d9590e86a947a692271590750f41b
[ "MIT" ]
5
2019-07-27T16:06:45.000Z
2021-08-03T17:02:25.000Z
namespace Platform::Disposables { template <typename ...> class Disposable; template <typename TPrimary, typename TAuxiliary> class Disposable<TPrimary, TAuxiliary> : public Disposable<TPrimary> { public: const TAuxiliary AuxiliaryObject; public: Disposable(TPrimary object, TAuxiliary auxiliaryObject, std::function<void(TPrimary, TAuxiliary)> action) : Disposable<TPrimary>(object) { AuxiliaryObject = auxiliaryObject; OnDispose += [&](auto manual, auto wasDisposed) { if (!wasDisposed) { this->action(Object, AuxiliaryObject); } }; } public: Disposable(TPrimary object, TAuxiliary auxiliaryObject, std::function<void()> action) : Disposable<TPrimary>(object, action) { return AuxiliaryObject = auxiliaryObject; } public: Disposable(TPrimary object, TAuxiliary auxiliaryObject, Disposal disposal) : Disposable<TPrimary>(object, disposal) { return AuxiliaryObject = auxiliaryObject; } public: Disposable(TPrimary object, TAuxiliary auxiliaryObject) : Disposable<TPrimary>(object) { return AuxiliaryObject = auxiliaryObject; } public: Disposable(TPrimary object) : Disposable<TPrimary>(object) { } public: Disposable(std::tuple<TPrimary, TAuxiliary, std::function<void(TPrimary, TAuxiliary)>> tuple) : Disposable(std::get<0>(tuple), std::get<1>(tuple), std::get<2>(tuple)) { } public: Disposable(std::tuple<TPrimary, TAuxiliary, std::function<void()>> tuple) : Disposable(std::get<0>(tuple), std::get<1>(tuple), std::get<2>(tuple)) { } public: Disposable(std::tuple<TPrimary, TAuxiliary, Disposal> tuple) : Disposable(std::get<0>(tuple), std::get<1>(tuple), std::get<2>(tuple)) { } public: Disposable(std::tuple<TPrimary, TAuxiliary> tuple) : Disposable(std::get<0>(tuple), std::get<1>(tuple)) { } public: operator TPrimary() const { return this->Object; } public: operator TAuxiliary() const { return this->AuxiliaryObject; } protected: void Dispose(bool manual, bool wasDisposed) override { this->RaiseOnDisposeEvent(manual, wasDisposed); AuxiliaryObject.TryDispose(); Object.TryDispose(); } }; }
47.510204
186
0.651632
[ "object" ]
a8ccf85335a08a0f58bcd70cab90fe61fd4606f8
10,563
h
C
admin/snapin/dsadmin/dscookie.h
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/snapin/dsadmin/dscookie.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/snapin/dsadmin/dscookie.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1992 - 1999 // // File: DSCookie.h // // Contents: DS Cookie functions // // History: 02-Oct-96 WayneSc Created // //-------------------------------------------------------------------------- #ifndef __DSCOOKIE_H__ #define __DSCOOKIE_H__ #include "dscache.h" #include "uinode.h" // Forward prototypes class CContextMenuVerbs; ///////////////////////////////////////////////////////////////////////////// // CDSCookieInfoBase : extra inof for special classes we know about class CDSCookieInfoBase { public: enum cookieClass { base, group, connection }; CDSCookieInfoBase() { m_class = base; } virtual ~CDSCookieInfoBase() { } cookieClass GetClass() { return m_class;} virtual LPCWSTR GetFriendlyClassName() { return L"";} protected: cookieClass m_class; }; ///////////////////////////////////////////////////////////////////////////// // CDSCookieInfoGroup : extra info for groups class CDSCookieInfoGroup : public CDSCookieInfoBase { public: CDSCookieInfoGroup() { m_class = group; m_GroupType = 0; } virtual LPCWSTR GetFriendlyClassName() { return GetGroupTypeStringHelper(m_GroupType); } INT m_GroupType; }; ///////////////////////////////////////////////////////////////////////////// // CDSCookieInfoConnection : extra info for nTDSConnection objects class CDSCookieInfoConnection : public CDSCookieInfoBase { public: CDSCookieInfoConnection() { m_class = connection; m_nOptions = 0; m_fFRSConnection = FALSE; } CString m_strFRSComputerReference; // not always present int m_nOptions; BOOL m_fFRSConnection; }; ///////////////////////////////////////////////////////////////////////////// // CDSCookie // CODEWORK these flags come from ntdsa.h /* Object Class independent bits */ // NOTE: These flags MAY have different behaviour in different NCs. // For example, the FLAG_CONFIG_foo flags only have meaning inside the // configuration NC. the FLAG_DOMAIN_foo flags have meaning only outside the // configuration NC. #define FLAG_DISALLOW_DELETE 0x80000000 #define FLAG_CONFIG_ALLOW_RENAME 0x40000000 #define FLAG_CONFIG_ALLOW_MOVE 0x20000000 #define FLAG_CONFIG_ALLOW_LIMITED_MOVE 0x10000000 #define FLAG_DOMAIN_DISALLOW_RENAME 0x08000000 #define FLAG_DOMAIN_DISALLOW_MOVE 0x04000000 // Bit flags for options attribute on NTDS-Connection objects. #define NTDSCONN_OPT_IS_GENERATED ( 1 << 0 ) /* object generated by DS, not admin */ /* Object Class specific bits, by object class */ /* CrossReference objects */ #define FLAG_CR_NTDS_NC 0x00000001 // NC is in NTDS (not VC or foreign) #define FLAG_CR_NTDS_DOMAIN 0x00000002 // NC is a domain (not non-domain NC) // end of ntdsa.h class CDSCookie : public CNodeData { public: CDSCookie(); virtual ~CDSCookie(); //operators public: // values retrieved from the cache item (per class values) int GetImage(BOOL bOpen); // base and DS GUID* GetGUID(); // base and DS LPCWSTR GetClass(); LPCWSTR GetLocalizedClassName(); // Value management functions void SetName(LPCWSTR lpszName) { m_strName = lpszName;} LPCWSTR GetName() { return m_strName; } void SetPath(LPCWSTR lpszPath) { m_strPath = lpszPath;} LPCWSTR GetPath(void) { return m_strPath;} void SetSystemFlags(int iSystemFlags) { m_iSystemFlags=iSystemFlags;} int GetSystemFlags(void) { return m_iSystemFlags; } void SetDesc(LPCWSTR lpszDesc) { m_strDesc = lpszDesc;} LPCWSTR GetDesc() { return m_strDesc; } void SetCacheItem(CDSClassCacheItemBase* pCacheItem) { ASSERT(pCacheItem != NULL); m_pCacheItem = pCacheItem; } void SetChildList(WCHAR **ppList); WCHAR ** GetChildList(void) { return m_ppChildList; } void SetChildCount(int cChildCount) { m_cChildCount=cChildCount;} int GetChildCount(void) { return m_cChildCount; } LPCWSTR GetChildListEntry(int iChildIndex) { ASSERT(iChildIndex >= 0 && iChildIndex < GetChildCount()); return m_ppChildList[iChildIndex]; } BOOL IsDisabled() { return m_bDisabled; } void SetDisabled() { m_bDisabled=TRUE; } void ReSetDisabled() { m_bDisabled=FALSE; } BOOL IsNonExpiringPwd() { return m_bNonExpiringPassword; } void SetNonExpiringPwd() { m_bNonExpiringPassword = TRUE; } void ReSetNonExpiringPwd() { m_bNonExpiringPassword = FALSE; } BOOL IsContainerClass() { if (m_pCacheItem == NULL) { ASSERT(FALSE); // should never happen return TRUE; } // ask the class cache item about it return m_pCacheItem->IsContainer(); } CDSCookieInfoBase* GetExtraInfo() { return m_pExtraInfo;} void SetExtraInfo(CDSCookieInfoBase* pExtraInfo) { ASSERT(pExtraInfo != NULL); if (m_pExtraInfo != NULL) delete m_pExtraInfo; m_pExtraInfo = pExtraInfo; } CStringList& GetParentClassSpecificStrings(void) { return m_strlistParentClassSpecificStrings; } SYSTEMTIME* GetModifiedTime() { return m_pModifiedTime; } void SetModifiedTime(SYSTEMTIME* pModifiedTime) { if (m_pModifiedTime == NULL) { m_pModifiedTime = (SYSTEMTIME*)malloc(sizeof(SYSTEMTIME)); } if (m_pModifiedTime != NULL) { memcpy(m_pModifiedTime, pModifiedTime, sizeof(SYSTEMTIME)); } } //attributes private: CString m_strName; CString m_strPath; int m_iSystemFlags; // systemFlags of the node CString m_strDesc; WCHAR **m_ppChildList; // list of allowable child classes int m_cChildCount; // count of items in above list BOOL m_bDisabled; // only valid if class is sec. princ. BOOL m_bNonExpiringPassword; // only valid if class is sec. princ. // We enumerate additional attributes depending on the class of the parent. CStringList m_strlistParentClassSpecificStrings; SYSTEMTIME* m_pModifiedTime; CDSClassCacheItemBase* m_pCacheItem; CDSCookieInfoBase* m_pExtraInfo; }; ///////////////////////////////////////////////////////////////////////////// // CDSUINode : UI node corresponding to a DS object (result of an ADSI query) class CDSUINode : public CUINode { public: CDSUINode(CUINode* pParentNode); // override of pure virtual functions virtual void SetName(LPCWSTR lpszName) { GetCookie()->SetName(lpszName);} virtual LPCWSTR GetName() { return GetCookie()->GetName();} virtual void SetDesc(LPCWSTR lpszDesc) { GetCookie()->SetDesc(lpszDesc);} virtual LPCWSTR GetDesc() { return GetCookie()->GetDesc();} int GetImage(BOOL bOpen) { return GetCookie()->GetImage(bOpen);} virtual GUID* GetGUID() { return GetCookie()->GetGUID();} virtual LPCWSTR GetDisplayString(int nCol, CDSColumnSet* pColumnSet); CDSCookie* GetCookie() { // assume that the cast succeeds CDSCookie* pCookie = dynamic_cast<CDSCookie*>(m_pNodeData); ASSERT(pCookie != NULL); return pCookie; } void SetCookie(CDSCookie* pCookie) { ASSERT(m_pNodeData == NULL); m_pNodeData = pCookie; } // end port virtual CDSColumnSet* GetColumnSet(CDSComponentData* pComponentData); // // These set the state of the standard context menu items // virtual BOOL IsDeleteAllowed(CDSComponentData* pComponentData, BOOL* pbHide); virtual BOOL IsRenameAllowed(CDSComponentData* pComponentData, BOOL* pbHide); virtual BOOL IsRefreshAllowed(CDSComponentData* pComponentData, BOOL* pbHide); virtual BOOL ArePropertiesAllowed(CDSComponentData* pComponentData, BOOL* pbHide); virtual BOOL IsCutAllowed(CDSComponentData* pComponentData, BOOL* pbHide); virtual BOOL IsCopyAllowed(CDSComponentData* pComponentData, BOOL* pbHide); virtual BOOL IsPasteAllowed(CDSComponentData* pComponentData, BOOL* pbHide); virtual CContextMenuVerbs* GetContextMenuVerbsObject(CDSComponentData* pComponentData); virtual BOOL HasPropertyPages(LPDATAOBJECT pDataObject); }; // REVIEW_MARCOC_PORT: this is just to get going, cannot assume this ever inline CDSCookie* GetDSCookieFromUINode(CUINode* pUINode) { ASSERT(pUINode != NULL); CDSUINode* pDSUINode = dynamic_cast<CDSUINode*>(pUINode); ASSERT(pDSUINode != NULL); return pDSUINode->GetCookie(); } ///////////////////////////////////////////////////////////////////////////// // CDSThreadQueryInfo typedef enum DSQueryType { unk, rootFolder, dsFolder, queryFolder }; class CDSThreadQueryInfo : public CThreadQueryInfo { public: CDSThreadQueryInfo() { m_bOneLevel = TRUE; m_QueryType = unk; } void SetQueryDSQueryParameters(DSQueryType QueryType, LPCWSTR lpszPath, LPCWSTR lpszClass, LPCWSTR lpszQueryString, UINT nMaxItemCount, BOOL bOneLevel, LPCWSTR lpszColumnSetID) { ASSERT(m_QueryType == unk); ASSERT(QueryType != unk); m_QueryType = QueryType; SetMaxItemCount(nMaxItemCount); m_szPath = lpszPath; m_szClass = lpszClass; m_szQueryString = lpszQueryString; m_bOneLevel = bOneLevel; m_szColumnSetID = lpszColumnSetID; } BOOL IsOneLevel() { return m_bOneLevel;} DSQueryType GetType() { return m_QueryType;} LPCWSTR GetPath() { return m_szPath;} LPCWSTR GetClass() { return m_szClass;} LPCWSTR GetQueryString() { return m_szQueryString;} LPCWSTR GetColumnSetID() { return m_szColumnSetID;} private: BOOL m_bOneLevel; DSQueryType m_QueryType; CString m_szPath; CString m_szClass; CString m_szQueryString; CString m_szColumnSetID; }; ///////////////////////////////////////////////////////////////////////////// // CThreadQueryResult class CThreadQueryResult { public: CThreadQueryResult() { m_hr = S_OK; m_bOwnMemory = TRUE; } ~CThreadQueryResult() { if (m_bOwnMemory) { while (!m_nodeList.IsEmpty()) delete m_nodeList.RemoveHead(); } } CUINodeList m_nodeList; HRESULT m_hr; BOOL m_bOwnMemory; }; #endif //__DSCOOKIE_H__
27.797368
92
0.634479
[ "object" ]
a8cdfb1fb9672c51624aecabc4f87027a5e347e7
1,745
h
C
jml/boosting/classifier_mlp_averager.h
etnrlz/rtbkit
0d9cd9e2ee2d7580a27453ad0a2d815410d87091
[ "Apache-2.0" ]
737
2015-01-04T01:40:46.000Z
2022-03-07T10:09:23.000Z
jml/boosting/classifier_mlp_averager.h
TuanTranEngineer/rtbkit
502d06acc3f8d90438946b6ae742190f2f4b4fbb
[ "Apache-2.0" ]
56
2015-01-05T16:01:03.000Z
2020-06-22T19:02:37.000Z
jml/boosting/classifier_mlp_averager.h
TuanTranEngineer/rtbkit
502d06acc3f8d90438946b6ae742190f2f4b4fbb
[ "Apache-2.0" ]
329
2015-01-01T06:54:27.000Z
2022-02-12T22:21:02.000Z
/* classifier_mlp_averager.h -*- C++ -*- Jeremy Barnes, 2 September 2005 Copyright (c) 2005 Jeremy Barnes. All rights reserved. $Source$ Classifier class using an MlpAverager interface. */ #ifndef __boosting__classifier_mlp_averager_h__ #define __boosting__classifier_mlp_averager_h__ #include "config.h" #include "classifier.h" namespace ML { /*****************************************************************************/ /* Classifier_MLP_Averager */ /*****************************************************************************/ /** Class that has an MlpAverager interface but uses a classifier underneath. */ class Classifier_MLP_Averager { public: //---------------------------------------- // Constructor, Destructor //---------------------------------------- Classifier_MLP_Averager (); Classifier_MLP_Averager ( DB::Store_Reader& store ); ~Classifier_MLP_Averager (); //---------------------------------------- // computeScore: Returns the decoded output //---------------------------------------- std::vector<double> computeScore(const std::vector<double>& fv) const; //---------------------------------------- // Read - Write the averager //---------------------------------------- void read ( const std::string & fName ); void reconstitute(DB::Store_Reader & store); // Check if the averager has been initialized bool valid () const; private: ML::Classifier classifier; }; } // namespace ML #endif /* __boosting__classifier_mlp_averager_h__ */
29.576271
80
0.463037
[ "vector" ]
a8d84bc516b8cefe21590c0ebf60505675437c99
3,220
h
C
src/SvgStream.h
cb4ds/vdiffr
456e9da25c38446922171c606d619d9d53682b75
[ "Apache-2.0" ]
1
2021-11-20T13:23:58.000Z
2021-11-20T13:23:58.000Z
src/SvgStream.h
cb4ds/vdiffr
456e9da25c38446922171c606d619d9d53682b75
[ "Apache-2.0" ]
null
null
null
src/SvgStream.h
cb4ds/vdiffr
456e9da25c38446922171c606d619d9d53682b75
[ "Apache-2.0" ]
null
null
null
#ifndef __SVG_STREAM__ #define __SVG_STREAM__ #include <fstream> #include <sstream> #include <Rcpp.h> #include "utils.h" class SvgStream { public: virtual ~SvgStream() {}; virtual void write(int data) = 0; virtual void write(double data) = 0; virtual void write(const char* data) = 0; virtual void write(const std::string& data) = 0; virtual void write(char data) = 0; void put(char data) { write(data); } virtual void flush() = 0; virtual void finish() = 0; }; template <typename T> SvgStream& operator<<(SvgStream& object, const T& data) { object.write(data); return object; } template <> SvgStream& operator<<(SvgStream& object, const double& data) { // Make sure negative zeros are converted to positive zero for // reproducibility of SVGs object.write(dbl_format(data)); return object; } class SvgStreamFile : public SvgStream { std::ofstream stream_; public: SvgStreamFile(const std::string& path) { stream_.open(R_ExpandFileName(path.c_str())); if (stream_.fail()) Rcpp::stop("cannot open stream " + path); stream_ << std::fixed << std::setprecision(2); } void write(int data) { stream_ << data; } void write(double data) { stream_ << data; } void write(const char* data) { stream_ << data; } void write(char data) { stream_ << data; } void write(const std::string& data) { stream_ << data; } // Adding a final newline here creates problems on Windows when // seeking back to original position. So we only write the newline // in finish() void flush() { stream_ << "</svg>"; stream_.seekp(-6, std::ios_base::cur); stream_.flush(); } void finish() { stream_ << "</svg>\n"; stream_.flush(); } ~SvgStreamFile() { stream_.close(); } }; class SvgStreamString : public SvgStream { std::stringstream stream_; Rcpp::Environment env_; public: SvgStreamString(Rcpp::Environment env): env_(env) { stream_ << std::fixed << std::setprecision(2); env_["is_closed"] = false; } void write(int data) { stream_ << data; } void write(double data) { stream_ << data; } void write(const char* data) { stream_ << data; } void write(char data) { stream_ << data; } void write(const std::string& data) { stream_ << data; } void flush() { } void finish() { // When device is closed, stream_ will be destroyed, so we can no longer // get the svg string from stream_. In this case, we save the final string // to the environment env, so that R can read from env$svg_string even // after device is closed. env_["is_closed"] = true; stream_.flush(); std::string svgstr = stream_.str(); // If the current svg is empty, we also make the string empty // Otherwise append "</svg>" to make it a valid SVG if(!svgstr.empty()) { svgstr.append("</svg>"); } env_["svg_string"] = svgstr; } Rcpp::XPtr<std::stringstream> string_src() { // `false` means this pointer should not be "deleted" by R // The object will be automatically destroyed when device is closed return Rcpp::XPtr<std::stringstream>(&stream_, false); } }; #endif
25.76
78
0.635404
[ "object" ]
a8e987e5d109727d4fe98c56a5b3608bfb59b4c1
6,149
c
C
cnn_card_embedded_code.X/main.c
PaulKlinger/cnn_card
2e4b5c4947a5a38b841f1dd2b3bad1d89c03fe8b
[ "MIT" ]
77
2020-11-22T17:55:31.000Z
2022-01-16T23:31:46.000Z
cnn_card_embedded_code.X/main.c
PaulKlinger/cnn_card
2e4b5c4947a5a38b841f1dd2b3bad1d89c03fe8b
[ "MIT" ]
null
null
null
cnn_card_embedded_code.X/main.c
PaulKlinger/cnn_card
2e4b5c4947a5a38b841f1dd2b3bad1d89c03fe8b
[ "MIT" ]
3
2020-11-23T23:06:56.000Z
2021-05-14T11:17:51.000Z
#include "config.h" #include <avr/io.h> #include <util/delay.h> #include <avr/sleep.h> #include <avr/interrupt.h> #include "model/model.h" #include "util/led_control.h" #include "util/buttons.h" #include "util/sleep.h" #include "fun/startup_anim.h" #include "fun/gol.h" FUSES = { .APPEND = 0, .BODCFG = ACTIVE_DIS_gc | LVL_BODLEVEL0_gc | SAMPFREQ_1KHZ_gc | SLEEP_DIS_gc, .BOOTEND = 0, .OSCCFG = FREQSEL_20MHZ_gc, .SYSCFG0 = CRCSRC_NOCRC_gc | RSTPINCFG_UPDI_gc, .SYSCFG1 = SUT_64MS_gc, .WDTCFG = PERIOD_OFF_gc | WINDOW_OFF_gc, }; uint8_t filter_idx = 0; ISR(PORTB_PORT_vect) { /* This is only used to wake the MCU, so we do nothing here. */ /* clear interrupt flag */ VPORTB.INTFLAGS |= PORT_INT3_bm; } ISR(RTC_PIT_vect) { /* interrupt triggered pwm, only used when the main loop is busy */ run_pwm_cycle(); /* TRIGB interrupt flag has to be cleared manually */ RTC.PITINTFLAGS = RTC_PI_bm; } void rtc0_init(){ while (RTC.STATUS > 0) { /* Wait for all register to be synchronized */} RTC.CLKSEL = RTC_CLKSEL_INT32K_gc; /* Clock Select: Internal 32kHz OSC */ /* 10 min period * (should never reach this, as we reset on auto shutdown at <10 min) */ RTC.PER = 60 * 10; RTC.CTRLA = RTC_PRESCALER_DIV32768_gc/* Prescaling Factor: RTC Clock / 32768 */ | 1 << RTC_RTCEN_bp /* Enable: enabled */ | 0 << RTC_RUNSTDBY_bp; /* Run In Standby: disabled */ while (RTC.PITSTATUS > 0) {} /* set PIT period (for PWM during calculations) but don't enable it * most of the time we'll just run PWM in main loop so it's faster. */ RTC.PITINTCTRL = RTC_PI_bm; RTC.PITCTRLA = RTC_PERIOD_CYC512_gc; // = 64 Hz } void usart_spi_init(){ PORTB.PIN0CTRL |= PORT_INVEN_bm; USART0.CTRLA = USART_RS4850_bm; USART0.CTRLB |= USART_TXEN_bm; /* enable TX (but not RX) */ /* change mode to master SPI */ USART0.CTRLC = USART_CMODE_MSPI_gc ; /* set baud factor to 1 -> f_baud = 2MHz for CLK_PER = 4MHz*/ USART0.BAUDL = (1 << 6); } void run_model_with_pwm() { // enable interrupt pwm during model calculations RTC.PITCTRLA |= RTC_PITEN_bm; run_model_and_set_led_brightness(filter_idx); // disable interrupt pwm again RTC.PITCTRLA &= ~RTC_PITEN_bm; } void reset_input_state() { filter_idx = 0; clear_led_brightness(); set_led_brightness(1, 1, MAX_PWM_LEVEL); set_led_brightness(1, 2, MAX_PWM_LEVEL); set_led_brightness(2, 2, MAX_PWM_LEVEL); set_led_brightness(3, 1, MAX_PWM_LEVEL); set_led_brightness(3, 2, MAX_PWM_LEVEL); set_led_brightness(3, 3, MAX_PWM_LEVEL); set_filter_leds(filter_idx); update_pwm_pattern(); run_model_with_pwm(); update_pwm_pattern(); } void sleep_and_reset() { turn_off_leds(); go_to_sleep(); run_startup_animation(); reset_input_state(); } void handle_buttons(){ int8_t pressed = read_buttons(); if (pressed == -1) { return; } else if (pressed == FILTER_BUTTON) { if (check_glider()) { run_gol(); } else { filter_idx = (filter_idx + 1) % N_FILTERS; } run_model_with_pwm(); set_filter_leds(filter_idx); update_pwm_pattern(); } else if (pressed == PWR_BUTTON) { sleep_and_reset(); } else { uint8_t row = pressed / 5; uint8_t col = pressed % 5; set_led_brightness(row, col, get_led_on(row, col) ? 0 : MAX_PWM_LEVEL ); run_model_with_pwm(); update_pwm_pattern(); } } void main_loop() { while (1) { run_pwm_cycle(); handle_buttons(); if (RTC.CNT > AUTO_SHUTDOWN_TIME_s) { sleep_and_reset(); } } } int main(void) { /* Configure clock prescaler for 4MHz */ _PROTECTED_WRITE( CLKCTRL.MCLKCTRLB, CLKCTRL_PDIV_2X_gc /* Prescaler division: 2X */ | CLKCTRL_PEN_bm /* Prescaler enable: enabled */ ); /* Enable pullups for low power consumption (20uA -> 0.1uA (afair))*/ PORTA.PIN0CTRL |= PORT_PULLUPEN_bm; PORTA.PIN1CTRL |= PORT_PULLUPEN_bm; PORTA.PIN2CTRL |= PORT_PULLUPEN_bm; PORTA.PIN3CTRL |= PORT_PULLUPEN_bm; PORTA.PIN4CTRL |= PORT_PULLUPEN_bm; PORTA.PIN5CTRL |= PORT_PULLUPEN_bm; PORTA.PIN6CTRL |= PORT_PULLUPEN_bm; PORTA.PIN7CTRL |= PORT_PULLUPEN_bm; PORTB.PIN0CTRL |= PORT_PULLUPEN_bm; PORTB.PIN1CTRL |= PORT_PULLUPEN_bm; PORTB.PIN2CTRL |= PORT_PULLUPEN_bm; PORTB.PIN3CTRL |= PORT_PULLUPEN_bm; PORTB.PIN4CTRL |= PORT_PULLUPEN_bm; PORTB.PIN5CTRL |= PORT_PULLUPEN_bm; PORTB.PIN6CTRL |= PORT_PULLUPEN_bm; PORTB.PIN7CTRL |= PORT_PULLUPEN_bm; PORTC.PIN0CTRL |= PORT_PULLUPEN_bm; PORTC.PIN1CTRL |= PORT_PULLUPEN_bm; PORTC.PIN2CTRL |= PORT_PULLUPEN_bm; PORTC.PIN3CTRL |= PORT_PULLUPEN_bm; PORTC.PIN4CTRL |= PORT_PULLUPEN_bm; PORTC.PIN5CTRL |= PORT_PULLUPEN_bm; PORTC.PIN6CTRL |= PORT_PULLUPEN_bm; PORTC.PIN7CTRL |= PORT_PULLUPEN_bm; /* Enable interrupt on power button * (this is only for wakeup)*/ PORTB.PIN3CTRL = (PORTB.PIN3CTRL & ~PORT_ISC_gm) | PORT_ISC_BOTHEDGES_gc; sei(); rtc0_init(); usart_spi_init(); // shift register output disable VPORTC.OUT |= PIN2_bm; // GPIO led row/col off VPORTC.OUT &= ~PIN4_bm; VPORTC.OUT |= PIN5_bm; // turn off individual leds VPORTB.OUT |= (PIN4_bm | PIN5_bm | PIN6_bm); VPORTB.DIR = (PIN0_bm | PIN1_bm | PIN2_bm | PIN4_bm | PIN5_bm | PIN6_bm); VPORTC.DIR |= (PIN2_bm | PIN4_bm | PIN5_bm); turn_off_leds(); /* shift register output enable */ VPORTC.OUT &= ~PIN2_bm; init_pwm_data(); // sleep sleep_and_reset(); main_loop(); }
26.055085
84
0.607416
[ "model" ]
a8ece3d1c527e6ecc64d876a388e5157584b2438
468
h
C
src/gui/transformation/abstract_transformation.h
lii-enac/djnn-cpp
f27c5ba3186186ee22c93ae91c16063556e929b6
[ "BSD-2-Clause" ]
4
2018-09-11T14:27:57.000Z
2019-12-16T21:06:26.000Z
src/gui/transformation/abstract_transformation.h
lii-enac/djnn-cpp
f27c5ba3186186ee22c93ae91c16063556e929b6
[ "BSD-2-Clause" ]
null
null
null
src/gui/transformation/abstract_transformation.h
lii-enac/djnn-cpp
f27c5ba3186186ee22c93ae91c16063556e929b6
[ "BSD-2-Clause" ]
2
2018-06-11T14:15:30.000Z
2019-01-09T12:23:35.000Z
#pragma once #include "gui/abstract_gobj.h" namespace djnn { class AbstractTransformation : public AbstractGObj { public: AbstractTransformation (ParentProcess* parent, const string& name); AbstractTransformation (); virtual ~AbstractTransformation (); virtual void transform( double& x, double& y) {} virtual void inverse_transform( double& x, double& y) {} AbstractGShape* pick_analytical (PickAnalyticalContext& pac) override; }; }
27.529412
74
0.730769
[ "transform" ]
a8f646de23bd056f7f0b93881e77436ed69f9f13
1,798
h
C
third_party/blink/renderer/core/style/svg_dash_array.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
third_party/blink/renderer/core/style/svg_dash_array.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
third_party/blink/renderer/core/style/svg_dash_array.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 (C) 2004, 2005, 2007 Nikolas Zimmermann <zimmermann@kde.org> 2004, 2005 Rob Buis <buis@kde.org> Copyright (C) Research In Motion Limited 2010. All rights reserved. Based on khtml code by: Copyright (C) 2000-2003 Lars Knoll (knoll@kde.org) (C) 2000 Antti Koivisto (koivisto@kde.org) (C) 2000-2003 Dirk Mueller (mueller@kde.org) (C) 2002-2003 Apple Computer, Inc. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_SVG_DASH_ARRAY_H_ #define THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_SVG_DASH_ARRAY_H_ #include "third_party/blink/renderer/platform/geometry/length.h" #include "third_party/blink/renderer/platform/wtf/ref_counted.h" #include "third_party/blink/renderer/platform/wtf/vector.h" namespace blink { using SVGDashArray = base::RefCountedData<WTF::Vector<Length>>; // TODO(fs): Should return const. SVGDashArray* EmptyDashArray(); } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_CORE_STYLE_SVG_DASH_ARRAY_H_
39.955556
77
0.739711
[ "geometry", "vector" ]
a8f81214ef81ac9f6e8d1a0c78aa8a3d2a6daa80
838
h
C
cases/spherical_surfers/param/post/objects/surfer__us_1o0__surftimeconst_8o0__reorientationtime_4o0/pz/group/_member/passive/choice.h
C0PEP0D/sheld0n
497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc
[ "MIT" ]
null
null
null
cases/spherical_surfers/param/post/objects/surfer__us_1o0__surftimeconst_8o0__reorientationtime_4o0/pz/group/_member/passive/choice.h
C0PEP0D/sheld0n
497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc
[ "MIT" ]
null
null
null
cases/spherical_surfers/param/post/objects/surfer__us_1o0__surftimeconst_8o0__reorientationtime_4o0/pz/group/_member/passive/choice.h
C0PEP0D/sheld0n
497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc
[ "MIT" ]
null
null
null
#ifndef C0P_PARAM_POST_OBJECTS_SURFER__US_1O0__SURFTIMECONST_8O0__REORIENTATIONTIME_4O0_PZ_GROUP_MEMBER_PASSIVE_CHOICE_H #define C0P_PARAM_POST_OBJECTS_SURFER__US_1O0__SURFTIMECONST_8O0__REORIENTATIONTIME_4O0_PZ_GROUP_MEMBER_PASSIVE_CHOICE_H #pragma once // choose your post #include "core/post/objects/object/post/passive/position/core.h" #include "param/post/objects/surfer__us_1o0__surftimeconst_8o0__reorientationtime_4o0/pz/group/_member/passive/position/parameters.h" namespace c0p { template<typename TypeSurferUs1O0Surftimeconst8O0Reorientationtime4O0Step> using PostSurferUs1O0Surftimeconst8O0Reorientationtime4O0PzGroupMemberPassive = PostPostPassivePosition<PostSurferUs1O0Surftimeconst8O0Reorientationtime4O0PzGroupMemberPassivePositionParameters, TypeSurferUs1O0Surftimeconst8O0Reorientationtime4O0Step>; } #endif
55.866667
256
0.909308
[ "object" ]
d1075794f87fe117f7c403e04ec629960823ff70
6,077
h
C
PrivateFrameworks/VoiceMemos.framework/RCWaveformGenerator.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
36
2016-04-20T04:19:04.000Z
2018-10-08T04:12:25.000Z
PrivateFrameworks/VoiceMemos.framework/RCWaveformGenerator.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
null
null
null
PrivateFrameworks/VoiceMemos.framework/RCWaveformGenerator.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
10
2016-06-16T02:40:44.000Z
2019-01-15T03:31:45.000Z
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/VoiceMemos.framework/VoiceMemos */ @interface RCWaveformGenerator : NSObject { RCExtAudioFilePipe * _activeExtAudioFile; bool _canceled; NSObject<OS_dispatch_semaphore> * _digestPausedSemaphore; unsigned long long _framesConsumedSinceLastFlush; long long _framesNeededForNextDB; long long _framesNeededForNextFlush; NSMutableArray * _internalFinishedLoadingBlockUUIDs; NSMutableArray * _internalFinishedLoadingBlocks; bool _isSampleRateKnown; NSError * _loadingError; NSOperationQueue * _loadingQueue; NSObject<OS_dispatch_queue> * _notificationQueue; long long _overviewUnitsPerSecond; unsigned long long _pauseCount; struct vector<float, std::__1::allocator<float> > { float *__begin_; float *__end_; struct __compressed_pair<float *, std::__1::allocator<float> > { float *__first_; } __end_cap_; } _powerLevelBuffer; float _powerLevelBufferLastPushedValue; unsigned long long _powerLevelsConsumedSinceLastFlush; NSObject<OS_dispatch_queue> * _queue; struct PowerMeter { bool mInstantaneousMode; double mSampleRate; double mPeakDecay1; double mPeakDecay; double mDecay1; double mDecay; int mPrevBlockSize; int mPeakHoldCount; double mPeak; double mAveragePowerPeak; double mMaxPeak; struct AudioUnitMeterClipping { float peakValueSinceLastCall; unsigned char sawInfinity; unsigned char sawNotANumber; } mClipping; double mAveragePowerF; float m_vAvePower[16]; int mAveragePowerI; } _samplePowerMeter; double _segmentFlushInterval; long long _state; double _totalDigestedTime; double _totalFlushedTime; NSHashTable * _weakObservers; } @property (nonatomic, readonly) bool canceled; @property (nonatomic, readonly) bool finished; @property (nonatomic, readonly) bool idle; @property (nonatomic, readonly) bool loadable; @property (nonatomic) long long overviewUnitsPerSecond; @property (nonatomic) bool paused; @property (nonatomic, readonly) double segmentFlushInterval; @property (nonatomic, readonly) long long state; - (id).cxx_construct; - (void).cxx_destruct; - (void)_appendAveragePowerLevel:(float)arg1; - (void)_appendAveragePowerLevelsByDigestingTimeRange:(struct { double x1; double x2; })arg1 inExtAudioFile:(id)arg2 sourceFormat:(struct AudioStreamBasicDescription { double x1; unsigned int x2; unsigned int x3; unsigned int x4; unsigned int x5; unsigned int x6; unsigned int x7; unsigned int x8; unsigned int x9; }*)arg3 outputFormat:(struct AudioStreamBasicDescription { double x1; unsigned int x2; unsigned int x3; unsigned int x4; unsigned int x5; unsigned int x6; unsigned int x7; unsigned int x8; unsigned int x9; }*)arg4; - (void)_appendAveragePowerLevelsByDigestingWaveformSegments:(id)arg1; - (void)_appendPowerMeterValuesFromDataInAudioFile:(id)arg1 progressBlock:(id /* block */)arg2; - (void)_appendPowerMeterValuesFromSampleBuffer:(struct opaqueCMSampleBuffer { }*)arg1; - (void)_finishLoadingByTerminating:(bool)arg1 loadingFinishedBlockTimeoutDate:(id)arg2 loadingFinishedBlock:(id /* block */)arg3; - (bool)_isCanceled; - (void)_onLoadingQueue_appendPowerMeterValuesFromRawAudioData:(void*)arg1 frameCount:(long long)arg2 format:(const struct AudioStreamBasicDescription { double x1; unsigned int x2; unsigned int x3; unsigned int x4; unsigned int x5; unsigned int x6; unsigned int x7; unsigned int x8; unsigned int x9; }*)arg3 isPredigest:(bool)arg4; - (void)_onLoadingQueue_appendSegment:(id)arg1; - (void)_onLoadingQueue_digestAveragePowerLevel:(float)arg1; - (void)_onLoadingQueue_flushRemainingData; - (void)_onLoadingQueue_flushWaveformSegment:(id)arg1; - (void)_onLoadingQueue_flushWithNextSegmentWithEndTime:(double)arg1 isPredigest:(bool)arg2; - (void)_onLoadingQueue_pushAveragePowerLevel:(float)arg1; - (void)_onQueue_appendAveragePowerLevelsByDigestingTimeRange:(struct { double x1; double x2; })arg1 inExtAudioFile:(id)arg2 sourceFormat:(struct AudioStreamBasicDescription { double x1; unsigned int x2; unsigned int x3; unsigned int x4; unsigned int x5; unsigned int x6; unsigned int x7; unsigned int x8; unsigned int x9; }*)arg3 outputFormat:(struct AudioStreamBasicDescription { double x1; unsigned int x2; unsigned int x3; unsigned int x4; unsigned int x5; unsigned int x6; unsigned int x7; unsigned int x8; unsigned int x9; }*)arg4; - (void)_performInternalFinishedLoadingBlocksAndFinishObservers; - (void)_performLoadingFinishedBlock:(id /* block */)arg1 internalBlockUUID:(id)arg2 isTimeout:(bool)arg3; - (void)_performObserversBlock:(id /* block */)arg1; - (void)addSegmentOutputObserver:(id)arg1; - (bool)appendAveragePowerLevel:(float)arg1; - (bool)appendAveragePowerLevelsByDigestingContentsOfAudioFileURL:(id)arg1 progressBlock:(id /* block */)arg2; - (bool)appendAveragePowerLevelsByDigestingSampleBuffer:(struct opaqueCMSampleBuffer { }*)arg1; - (bool)appendAveragePowerLevelsByDigestingWaveform:(id)arg1; - (bool)appendAveragePowerLevelsByDigestingWaveformSegments:(id)arg1; - (void)beginLoading; - (bool)canceled; - (void)finishLoadingWithCompletionTimeoutDate:(id)arg1 completionBlock:(id /* block */)arg2; - (bool)finished; - (void)flushPendingCapturedSampleBuffers; - (bool)idle; - (id)init; - (id)initWithSamplingParametersFromGenerator:(id)arg1; - (id)initWithSegmentFlushInterval:(double)arg1; - (bool)loadable; - (long long)overviewUnitsPerSecond; - (bool)paused; - (void)removeSegmentOutputObserver:(id)arg1; - (double)segmentFlushInterval; - (void)setOverviewUnitsPerSecond:(long long)arg1; - (void)setPaused:(bool)arg1; - (long long)state; - (id)synchronouslyApproximateWaveformForAVContentURL:(id)arg1 byReadingCurrentFileAheadTimeRange:(struct { double x1; double x2; })arg2; - (void)terminateLoadingImmediately; - (double)totalDigestedTime; - (double)totalFlushedTime; @end
52.387931
537
0.76518
[ "vector" ]
d10ad0c109e0735f833a2eb2f197b73f0df33c4f
5,260
c
C
example/sprites.c
mrk-its/obx2elf
9a9c27789750c6d9c6131edaea5477eac85ca57c
[ "Apache-2.0", "MIT" ]
null
null
null
example/sprites.c
mrk-its/obx2elf
9a9c27789750c6d9c6131edaea5477eac85ca57c
[ "Apache-2.0", "MIT" ]
null
null
null
example/sprites.c
mrk-its/obx2elf
9a9c27789750c6d9c6131edaea5477eac85ca57c
[ "Apache-2.0", "MIT" ]
null
null
null
#include <string.h> extern void init_sprites(); extern void multi_show_sprites(); extern void multi_animuj(); extern char shp0_01, shp0_23; extern char shp1_01, shp1_23; extern char shp2_01, shp2_23; extern char shp3_01, shp3_23; extern char shp4_01, shp4_23; extern char shp5_01, shp5_23; extern char shp6_01, shp6_23; extern char shp7_01, shp7_23; extern unsigned char sprite_c0[16]; extern unsigned char sprite_c1[16]; extern unsigned char sprite_shape[16]; extern unsigned char sprite_x[16]; extern unsigned char sprite_y[16]; extern unsigned char sprite_anim_speed[16]; extern unsigned char sprite_anim[16]; unsigned char *_charsets = (unsigned char *)0x3e0; char **_shape_tab01 = (char **)0x100; char **_shape_tab23 = (char **)0x200; volatile unsigned char *SDMCTL = (volatile unsigned char *)0x22f; volatile char **SDLPTR = (volatile char **)0x230; volatile char **DLPTRS = (volatile char **)0xd402; volatile unsigned char *DMACTL = (volatile unsigned char *)0xd400; volatile unsigned char *CHBASE = (volatile unsigned char *)0xd409; volatile unsigned char *RTCLK = (volatile unsigned char *) 20; /* .macro addShape (idx, nam) mwa #%%nam._01 shape_tab01+%%idx*2 mwa #%%nam._23 shape_tab23+%%idx*2 .endm .macro addSprite (num, c0, c1, shape, x, y, speed, anim) mva #%%c0 sprite_c0+%%num mva #%%c1 sprite_c1+%%num mva #%%shape sprite_shape+%%num ;ksztalt startowy mva #%%x sprite_x+%%num mva #%%y sprite_y+%%num mva #%%speed sprite_anim_speed+%%num ;predko�� animacji mva #%%anim sprite_anim+%%num ;maska dla liczby klatek animacji .endm */ static __attribute__((aligned(1024))) char dlist[] = { 0xF0, 0xc2, 0x40, 0xbc, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x41, 0x00, 0x36 }; void add_shape(int n, char *shp_01, char *shp_23) { _shape_tab01[n] = shp_01; _shape_tab23[n] = shp_23; } void add_sprite(int n, unsigned char color1, unsigned char color2, unsigned char shape, unsigned char x, unsigned char y, unsigned char anim_speed, unsigned char anim_mask) { sprite_c0[n] = color1; sprite_c1[n] = color2; sprite_shape[n] = shape; sprite_x[n] = x; sprite_y[n] = y; sprite_anim_speed[n] = anim_speed; sprite_anim[n] = anim_mask; } void wait_vbl() { unsigned char c = *RTCLK; while(*RTCLK == c); } // [int(math.sin(2 * math.pi * i / 256) * 128) for i in range(256)] static unsigned char SIN_TABLE[256] = { 0x00, 0x03, 0x06, 0x09, 0x0c, 0x0f, 0x12, 0x15, 0x18, 0x1b, 0x1e, 0x21, 0x24, 0x27, 0x2a, 0x2d, 0x30, 0x33, 0x36, 0x39, 0x3b, 0x3e, 0x41, 0x43, 0x46, 0x49, 0x4b, 0x4e, 0x50, 0x52, 0x55, 0x57, 0x59, 0x5b, 0x5e, 0x60, 0x62, 0x64, 0x66, 0x67, 0x69, 0x6b, 0x6c, 0x6e, 0x70, 0x71, 0x72, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7b, 0x7c, 0x7d, 0x7d, 0x7e, 0x7e, 0x7e, 0x7e, 0x7e, 0x7f, 0x7e, 0x7e, 0x7e, 0x7e, 0x7e, 0x7d, 0x7d, 0x7c, 0x7b, 0x7b, 0x7a, 0x79, 0x78, 0x77, 0x76, 0x75, 0x74, 0x72, 0x71, 0x70, 0x6e, 0x6c, 0x6b, 0x69, 0x67, 0x66, 0x64, 0x62, 0x60, 0x5e, 0x5b, 0x59, 0x57, 0x55, 0x52, 0x50, 0x4e, 0x4b, 0x49, 0x46, 0x43, 0x41, 0x3e, 0x3b, 0x39, 0x36, 0x33, 0x30, 0x2d, 0x2a, 0x27, 0x24, 0x21, 0x1e, 0x1b, 0x18, 0x15, 0x12, 0x0f, 0x0c, 0x09, 0x06, 0x03, 0x00, 0xfd, 0xfa, 0xf7, 0xf4, 0xf1, 0xee, 0xeb, 0xe8, 0xe5, 0xe2, 0xdf, 0xdc, 0xd9, 0xd6, 0xd3, 0xd0, 0xcd, 0xca, 0xc7, 0xc5, 0xc2, 0xbf, 0xbd, 0xba, 0xb7, 0xb5, 0xb2, 0xb0, 0xae, 0xab, 0xa9, 0xa7, 0xa5, 0xa2, 0xa0, 0x9e, 0x9c, 0x9a, 0x99, 0x97, 0x95, 0x94, 0x92, 0x90, 0x8f, 0x8e, 0x8c, 0x8b, 0x8a, 0x89, 0x88, 0x87, 0x86, 0x85, 0x85, 0x84, 0x83, 0x83, 0x82, 0x82, 0x82, 0x82, 0x82, 0x81, 0x82, 0x82, 0x82, 0x82, 0x82, 0x83, 0x83, 0x84, 0x85, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8e, 0x8f, 0x90, 0x92, 0x94, 0x95, 0x97, 0x99, 0x9a, 0x9c, 0x9e, 0xa0, 0xa2, 0xa5, 0xa7, 0xa9, 0xab, 0xae, 0xb0, 0xb2, 0xb5, 0xb7, 0xba, 0xbd, 0xbf, 0xc2, 0xc5, 0xc7, 0xca, 0xcd, 0xd0, 0xd3, 0xd6, 0xd9, 0xdc, 0xdf, 0xe2, 0xe5, 0xe8, 0xeb, 0xee, 0xf1, 0xf4, 0xf7, 0xfa, 0xfd, }; signed char sin(unsigned char alpha) { return SIN_TABLE[alpha]; } int main() { *(char **)&dlist[sizeof(dlist)-2] = dlist; *SDLPTR = dlist; wait_vbl(); // *CHBASE = 0xe0; for(int i=0; i<32; i++) _charsets[i] = 0xe0; init_sprites(); *DMACTL = 0x3d; *SDMCTL = 0x3d; add_shape(0, &shp0_01, &shp0_23); add_shape(1, &shp1_01, &shp1_23); add_shape(2, &shp2_01, &shp2_23); add_shape(3, &shp3_01, &shp3_23); add_shape(4, &shp4_01, &shp4_23); add_shape(5, &shp5_01, &shp5_23); add_shape(6, &shp6_01, &shp6_23); add_shape(7, &shp7_01, &shp7_23); for(int i=0; i<8; i++) { add_sprite(i, i * 2 * 16 + 8, (i * 2 + 1) * 16 + 4, i % 8, 0, 0, 1, 0xff); } memset((void *)0xe000, 0, 1024); unsigned int alpha = 0; while(1) { wait_vbl(); multi_show_sprites(); // multi_animuj(); sprite_x[0] += 1; for(int i=0; i<8; i++) { sprite_x[i] = 128 - 4 + sin(alpha + i * 20) / 2; sprite_y[i] = 112 + sin(70 + alpha + i * 20) * 3 / 4; } alpha = alpha - 1; // sprite_y += 2; } }
35.782313
174
0.640875
[ "shape" ]
a4b3b3596209b190ea2402bab6640d2452faa1b7
1,032
h
C
include/scope_guard.h
yiliangwu880/svr_util
576a78b4f3c0c92626781e5844f43d5e36740371
[ "BSD-3-Clause" ]
1
2020-01-15T02:55:07.000Z
2020-01-15T02:55:07.000Z
include/scope_guard.h
yiliangwu880/svr_util
576a78b4f3c0c92626781e5844f43d5e36740371
[ "BSD-3-Clause" ]
null
null
null
include/scope_guard.h
yiliangwu880/svr_util
576a78b4f3c0c92626781e5844f43d5e36740371
[ "BSD-3-Clause" ]
null
null
null
/* //使用例子: SCOPE_GUARD(delete point;); ScopeGuard sg([&] { exe; }); sg.Dismiss(); */ #pragma once #include <vector> #include <list> #include <set> #include <time.h> #include "typedef.h" #include <functional> namespace su { class ScopeGuard { private: std::function<void()> m_excute; bool m_is_dismissed; public: explicit ScopeGuard(std::function<void()> &&onExitScope) : m_excute(std::move(onExitScope)) , m_is_dismissed(false) { } ~ScopeGuard() { if (!m_is_dismissed) { m_excute(); } } void Dismiss() { m_is_dismissed = true; } private: // noncopyable ScopeGuard(ScopeGuard const&); ScopeGuard& operator=(ScopeGuard const&); }; #define SCOPEGUARD_LINENAME_CAT(name, line) name##line #define SCOPEGUARD_LINENAME(name, line) SCOPEGUARD_LINENAME_CAT(name, line) //多一层,避免__LINE__直接变化成字符串"__LINE__" //最简化用法。 注意upvalue全部是&,别用野对象。 #define SCOPE_GUARD(exe) ScopeGuard SCOPEGUARD_LINENAME(EXIT, __LINE__)([&] { exe; }) } //end namespace su //end file
16.380952
110
0.669574
[ "vector" ]
a4ba63f7c8993f9fed8be6ace7cacaca2db5ac2f
1,034
h
C
aztec/third_party/lua_electron/third_party/electronbind/include/electron_bind.h
viccsneto/aztec
a49e269c53f19d2de22f0d297908c917f36c658d
[ "MIT" ]
null
null
null
aztec/third_party/lua_electron/third_party/electronbind/include/electron_bind.h
viccsneto/aztec
a49e269c53f19d2de22f0d297908c917f36c658d
[ "MIT" ]
null
null
null
aztec/third_party/lua_electron/third_party/electronbind/include/electron_bind.h
viccsneto/aztec
a49e269c53f19d2de22f0d297908c917f36c658d
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <unordered_map> #include <stdexcept> #include <memory> #include <vector> class ElectronWindow; class ElectronInstance; class ElectronMessage; class ElectronBind { public: class Exception : public std::runtime_error { public: Exception(const char *message) : std::runtime_error(message) { } }; static ElectronBind *Instance(); static void Release(); void UnregisterBrowserWindow(ElectronWindow* window); private: ElectronBind(); ~ElectronBind(); bool FindElectron(); std::shared_ptr<ElectronInstance> CreateBrowserInstance(const char *command_line_args = NULL); void RegisterBrowserWindow(ElectronWindow *window); std::vector<std::string> *SplitPath(const char *path); private: static ElectronBind *s_instance; std::string m_electron_path; std::string m_electron_name; unsigned int m_browser_count; unsigned long m_pid; std::unordered_map<std::string, ElectronWindow *> m_browser_windows; private: friend class ElectronWindow; };
22.478261
96
0.748549
[ "vector" ]
a4c4e803c6550d211c4e25c232ebb28c06757cb6
3,884
c
C
nitan/maze/battle1/npc/guarder.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
1
2019-03-27T07:25:16.000Z
2019-03-27T07:25:16.000Z
nitan/maze/battle1/npc/guarder.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
nitan/maze/battle1/npc/guarder.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
#include <ansi.h> #define MAX_SKILL 700 inherit NPC; void create() { set_name(HIY "守護者" NOR, ({ "guarder",})); set("title", HIR "" NOR); set("gender", "男性"); set("age", 22+random(23)); set("long", @LONG 他帶着一副冰冷的面具,無法辨識模樣。 LONG); set("attitude", "friendly"); set("str", 80); set("int", 80); set("con", 80); set("dex", 80); set("per", 1); set("shen_type", 0); set("qi", 50000000); set("max_qi", 50000000); set("jing", 920000000); set("max_jing", 920000000); set("jingli", 92000000); set("max_jingli", 92000000); set("neili", 400000); set("max_neili", 400000); set("jiali", 4000); set("combat_exp", 2000000000); set("scborn/ok", 1); set("special_skill/guimai", 1); set_skill("force", MAX_SKILL); set_skill("pixie-jian", MAX_SKILL); set_skill("surge-force", MAX_SKILL); set_skill("six-finger", MAX_SKILL); set_skill("sword", MAX_SKILL); set_skill("finger", MAX_SKILL); set_skill("whip", MAX_SKILL); set_skill("dodge", MAX_SKILL); set_skill("parry", MAX_SKILL); set_skill("unarmed", MAX_SKILL); set_skill("strike", MAX_SKILL); set_skill("zuoyou-hubo", 500); set_skill("literate", MAX_SKILL); set_skill("throwing", MAX_SKILL); set_skill("jingluo-xue", 500); set_skill("martial-cognize", MAX_SKILL); map_skill("force", "surge-force"); map_skill("sword", "pixie-jian"); map_skill("dodge", "pixie-jian"); map_skill("parry", "pixie-jian"); map_skill("unarmed", "pixie-jian"); map_skill("finger", "liumai-shenjian"); prepare_skill("finger", "six-finger"); set_temp("apply/attack",100000); set_temp("apply/defense", MAX_SKILL * 10); set_temp("apply/damage", MAX_SKILL * 5); set_temp("apply/unarmed_damage", MAX_SKILL * 5); set_temp("apply/armor", MAX_SKILL * 10); set_temp("apply/fy", 80); set_temp("apply/qy", 80); set("chat_chance_combat", 120); set("chat_msg_combat", ({ (: command("perform sword.duo and sword.gui") :), (: command("perform sword.pi and sword.po") :), (: exert_function, "recover" :), (: exert_function, "powerup" :), (: perform_action, "sword.jian twice" :), (: perform_action, "finger.tian twice" :), }) ); setup(); carry_object("/clone/weapon/changjian")->wield(); carry_object("/clone/cloth/baipao")->wear(); } int accept_fight(object ob) { kill_ob(ob); return -1; } int accept_kill(object ob) { return 1; } int accept_hit(object ob) { kill_ob(ob); return -1; } void heart_beat() { object env; if (query("neili") < 1 && random(50) == 1) set("neili", query("max_neili")); // 守護房間出口 env = environment(this_object()); if (objectp(env)) { if (query_temp("guardfor") != env->query("guard_dir")) command("guard " + env->query("guard_dir")); } return ::heart_beat(); } varargs void die(object killer) { object me; int i; me = this_object(); if( !killer ) killer = me->query_last_damage_from(); if( objectp(killer) && userp(killer) && query_temp("battle/team_name", killer) != query_temp("battle/team_name", me) ) { BATTLEFIELD_D->add_killnpc_score(killer, 1); } ::die(killer); } void unconcious() { die(query_last_damage_from()); }
26.421769
96
0.518538
[ "object" ]
a4c6f59719efaefffb624fb2a667645545a58ebb
25,035
c
C
core/src/main/resources/org/teavm/backend/c/heap.c
shannah/cn1-teavm-builds
35fa3da0cabeefb3f796852e00f2c7dd8e5b3d17
[ "Apache-2.0" ]
1
2016-03-04T12:46:35.000Z
2016-03-04T12:46:35.000Z
core/src/main/resources/org/teavm/backend/c/heap.c
shannah/cn1-teavm-builds
35fa3da0cabeefb3f796852e00f2c7dd8e5b3d17
[ "Apache-2.0" ]
5
2019-11-13T05:55:08.000Z
2021-01-20T23:02:34.000Z
core/src/main/resources/org/teavm/backend/c/heap.c
shannah/cn1-teavm-builds
35fa3da0cabeefb3f796852e00f2c7dd8e5b3d17
[ "Apache-2.0" ]
1
2015-06-07T13:24:12.000Z
2015-06-07T13:24:12.000Z
#include "runtime.h" #include <string.h> #include <stdint.h> #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <wchar.h> #include <wctype.h> #include <uchar.h> #ifndef TEAVM_WINDOWS_LOG #define TEAVM_OUTPUT_STRING(s) fprintf(stderr, s) #else #define TEAVM_OUTPUT_STRING(s) OutputDebugStringW(L##s) #endif void teavm_outOfMemory() { TEAVM_OUTPUT_STRING("Application crashed due to lack of free memory\n"); teavm_gc_writeHeapDump(); abort(); } static wchar_t* teavm_gc_dumpDirectory = NULL; #if TEAVM_MEMORY_TRACE void teavm_gc_assertSize(int32_t size) { if (size % sizeof(void*) != 0) { abort(); } } #endif void teavm_gc_allocate(void* address, int32_t size) { #if TEAVM_MEMORY_TRACE teavm_gc_assertAddress(address); teavm_gc_assertSize(size); size /= sizeof(void*); uint8_t* map = teavm_gc_heapMap + (((char*) address - (char*) teavm_gc_heapAddress) / sizeof(void*)); if (*map != 0) { fprintf(stderr, "[GC] trying allocate at memory in use at: %d\n", (int) ((char*) address - (char*) teavm_gc_heapAddress)); abort(); } *map++ = 1; for (int32_t i = 1; i < size; ++i) { if (*map != 0) { fprintf(stderr, "[GC] trying allocate at memory in use at: %d\n", (int) ((char*) address - (char*) teavm_gc_heapAddress)); abort(); } *map++ = 2; } #endif } void teavm_gc_free(void* address, int32_t size) { #if TEAVM_MEMORY_TRACE teavm_gc_assertAddress(address); teavm_gc_assertSize(size); int32_t offset = (int32_t) (((char*) address - (char*) teavm_gc_heapAddress) / sizeof(void*)); uint8_t* markMap = teavm_gc_markMap + offset; size /= sizeof(void*); for (int32_t i = 0; i < size; ++i) { if (markMap[i] != 0) { fprintf(stderr, "[GC] trying to release reachable object at: %d\n", (int) ((char*) address - (char*) teavm_gc_heapAddress)); abort(); } } uint8_t* map = teavm_gc_heapMap + offset; memset(map, 0, size); #endif } void teavm_gc_assertFree(void* address, int32_t size) { #if TEAVM_MEMORY_TRACE teavm_gc_assertAddress(address); teavm_gc_assertSize(size); int32_t offset = (int32_t) (((char*) address - (char*) teavm_gc_heapAddress) / sizeof(void*)); uint8_t* map = teavm_gc_heapMap + offset; size /= sizeof(void*); for (int32_t i = 0; i < size; ++i) { if (map[i] != 0) { fprintf(stderr, "[GC] memory supposed to be free at: %d\n", (int) ((char*) address - (char*) teavm_gc_heapAddress)); abort(); } } #endif } void teavm_gc_initMark() { #if TEAVM_MEMORY_TRACE memset(teavm_gc_markMap, 0, teavm_gc_availableBytes / sizeof(void*)); #endif } int32_t teavm_gc_objectSize(void* address) { TeaVM_Class* cls = TEAVM_CLASS_OF(address); if (cls->itemType == NULL) { return cls->size; } int32_t itemSize = cls->itemType->flags & 2 ? cls->itemType->size : sizeof(void*); TeaVM_Array* array = (TeaVM_Array*) address; char* size = TEAVM_ALIGN((void*) sizeof(TeaVM_Array), itemSize); size += array->size * itemSize; size = TEAVM_ALIGN(size, sizeof(void*)); return (int32_t) (intptr_t) size; } void teavm_gc_mark(void* address) { #if TEAVM_MEMORY_TRACE if (address < teavm_gc_heapAddress || (char*) address >= (char*) teavm_gc_heapAddress + teavm_gc_availableBytes) { return; } teavm_gc_assertAddress(address); int32_t offset = (int32_t) (((char*) address - (char*) teavm_gc_heapAddress) / sizeof(void*)); uint8_t* map = teavm_gc_heapMap + offset; uint8_t* markMap = teavm_gc_markMap + offset; int32_t size = teavm_gc_objectSize(address); teavm_gc_assertSize(size); size /= sizeof(void*); if (*map++ != 1 || *markMap != 0) { fprintf(stderr, "[GC] assertion failed marking object at: %d\n", (int) ((char*) address - (char*) teavm_gc_heapAddress)); abort(); } *markMap++ = 1; for (int32_t i = 1; i < size; ++i) { if (*map++ != 2 || *markMap != 0) { abort(); } *markMap++ = 1; } #endif } void teavm_gc_move(void* from, void* to, int32_t size) { #if TEAVM_MEMORY_TRACE teavm_gc_assertAddress(from); teavm_gc_assertAddress(to); teavm_gc_assertSize(size); uint8_t* mapFrom = teavm_gc_heapMap + (((char*) from - (char*) teavm_gc_heapAddress) / sizeof(void*)); uint8_t* mapTo = teavm_gc_heapMap + (((char*) to - (char*) teavm_gc_heapAddress) / sizeof(void*)); size /= sizeof(void*); if (mapFrom > mapTo) { for (int32_t i = 0; i < size; ++i) { if (mapFrom[i] == 0 || mapTo[i] != 0) { fprintf(stderr, "[GC] assertion failed moving object from: %d to %d\n", (int) ((char*) from - (char*) teavm_gc_heapAddress), (int) ((char*) to - (char*) teavm_gc_heapAddress)); abort(); } mapTo[i] = mapFrom[i]; mapFrom[i] = 0; } } else { for (int32_t i = size - 1; i >= 0; --i) { if (mapFrom[i] == 0 || mapTo[i] != 0) { abort(); } mapTo[i] = mapFrom[i]; mapFrom[i] = 0; } } #endif } static FILE* teavm_gc_traceFile = NULL; static FILE* teavm_gc_openDumpFile(wchar_t* name) { wchar_t* fullName = name; size_t fullNameLen = wcslen(name); if (teavm_gc_dumpDirectory != NULL) { size_t prefixLen = wcslen(teavm_gc_dumpDirectory); size_t nameLen = fullNameLen; fullNameLen = nameLen + prefixLen; fullName = malloc((prefixLen + nameLen + 1) * sizeof(wchar_t)); memcpy(fullName, teavm_gc_dumpDirectory, prefixLen * sizeof(wchar_t)); memcpy(fullName + prefixLen, name, (nameLen + 1) * sizeof(wchar_t)); } FILE* result; #ifdef _MSC_VER _wfopen_s(&result, fullName, L"w"); #else size_t fullNameMbSize = 3 * (fullNameLen + 1); char* fullNameMb = malloc(fullNameMbSize); mbstate_t state = { 0 }; wcsrtombs(fullNameMb, (const wchar_t **) &fullName, fullNameMbSize, &state); result = fopen(fullNameMb, "w"); free(fullNameMb); #endif if (fullName != name) { free(fullName); } return result; } #if TEAVM_MEMORY_TRACE static void teavm_writeHeapMemory(char* name) { #ifdef TEAVM_GC_LOG if (teavm_gc_traceFile == NULL) { teavm_gc_traceFile = teavm_gc_openDumpFile(L"teavm-gc-trace.txt"); } FILE* file = teavm_gc_traceFile; fprintf(file, "%s:", name); int32_t numbers = 4096; int64_t mapSize = teavm_gc_availableBytes / sizeof(void*); for (int i = 0; i < numbers; ++i) { int64_t start = mapSize * i / numbers; int64_t end = mapSize * (i + 1) / numbers; int count = 0; for (int j = start; j < end; ++j) { if (teavm_gc_heapMap[j] != 0) { count++; } } int rate = count * 4096 / (end - start); fprintf(file, " %d", rate); } fprintf(file, "\n"); fflush(file); #endif } void teavm_gc_checkHeapConsistency() { TeaVM_Object* obj = teavm_gc_heapAddress; while ((char*) obj < (char*) teavm_gc_heapAddress + teavm_gc_availableBytes) { int32_t size; if (obj->header == 0) { size = obj->hash; teavm_gc_assertFree(obj, size); } else { teavm_verify(obj); TeaVM_Class* cls = TEAVM_CLASS_OF(obj); if (cls->itemType != NULL) { if (!(cls->itemType->flags & 2)) { char* offset = NULL; offset += sizeof(TeaVM_Array); offset = TEAVM_ALIGN(offset, sizeof(void*)); void** data = (void**)((char*)obj + (uintptr_t)offset); int32_t size = ((TeaVM_Array*)obj)->size; for (int32_t i = 0; i < size; ++i) { teavm_verify(data[i]); } } } else { while (cls != NULL) { int32_t kind = (cls->flags >> 7) & 7; if (kind == 1) { } else if (kind == 2) { } else { int16_t* layout = cls->layout; if (layout != NULL) { int16_t size = *layout++; for (int32_t i = 0; i < size; ++i) { void** ptr = (void**) ((char*) obj + *layout++); teavm_verify(*ptr); } } } cls = cls->superclass; } } size = teavm_gc_objectSize(obj); } obj = (TeaVM_Object*) ((char*) obj + size); } } #endif void teavm_gc_gcStarted() { #if TEAVM_MEMORY_TRACE teavm_writeHeapMemory("start"); teavm_gc_checkHeapConsistency(); #endif } void teavm_gc_sweepCompleted() { #if TEAVM_MEMORY_TRACE teavm_writeHeapMemory("sweep"); teavm_gc_checkHeapConsistency(); #endif } void teavm_gc_defragCompleted() { #if TEAVM_MEMORY_TRACE teavm_writeHeapMemory("defrag"); #endif } void teavm_gc_setDumpDirectory(const wchar_t* path) { #if TEAVM_MEMORY_TRACE if (teavm_gc_dumpDirectory != NULL) { free(teavm_gc_dumpDirectory); } size_t pathLen = wcslen(path); size_t bytesLen = sizeof(wchar_t) * (pathLen + 1); teavm_gc_dumpDirectory = malloc(bytesLen); memcpy(teavm_gc_dumpDirectory, path, bytesLen); #endif } #if TEAVM_HEAP_DUMP static char* teavm_hexChars = "0123456789abcdef"; static void teavm_gc_escapeJsonString(FILE* out, char16_t* str) { while (1) { char16_t c = (char32_t) *str++; if (c == 0) { break; } switch (c) { case '\n': fputc('\\', out); fputc('n', out); break; case '\r': fputc('\\', out); fputc('r', out); break; case '\t': fputc('\\', out); fputc('t', out); break; case '\b': fputc('\\', out); fputc('b', out); break; case '\f': fputc('\\', out); fputc('f', out); break; case '\"': fputc('\\', out); fputc('\"', out); break; case '\\': fputc('\\', out); fputc('\\', out); break; default: if (c < ' ' || c >= 127) { fputc('\\', out); fputc('u', out); fputc(teavm_hexChars[(c >> 12) & 15], out); fputc(teavm_hexChars[(c >> 8) & 15], out); fputc(teavm_hexChars[(c >> 4) & 15], out); fputc(teavm_hexChars[c & 15], out); } else { fputc(c, out); } break; } } } static uint8_t teavm_gc_fieldTypeSize(uint8_t type) { switch (type) { case TEAVM_FIELD_TYPE_OBJECT: case TEAVM_FIELD_TYPE_ARRAY: return sizeof(void*); case TEAVM_FIELD_TYPE_BOOLEAN: case TEAVM_FIELD_TYPE_BYTE: return 1; case TEAVM_FIELD_TYPE_CHAR: case TEAVM_FIELD_TYPE_SHORT: return 2; case TEAVM_FIELD_TYPE_INT: case TEAVM_FIELD_TYPE_FLOAT: return 4; case TEAVM_FIELD_TYPE_LONG: case TEAVM_FIELD_TYPE_DOUBLE: return 8; default: return 0; } } static void teavm_gc_writeHeapDumpData(FILE* out, unsigned char* base, uint8_t size) { uint64_t value = *(uint64_t*) base; size *= 2; for (int i = size - 1; i >= 0; --i) { int shift = i * 4; fputc(teavm_hexChars[(value >> shift) & 15], out); } } static char* teavm_gc_fieldTypeName(uint8_t type) { switch (type) { case TEAVM_FIELD_TYPE_OBJECT: return "object"; case TEAVM_FIELD_TYPE_ARRAY: return "array"; case TEAVM_FIELD_TYPE_BOOLEAN: return "boolean"; case TEAVM_FIELD_TYPE_BYTE: return "byte"; case TEAVM_FIELD_TYPE_CHAR: return "char"; case TEAVM_FIELD_TYPE_SHORT: return "short"; case TEAVM_FIELD_TYPE_INT: return "int"; case TEAVM_FIELD_TYPE_LONG: return "long"; case TEAVM_FIELD_TYPE_FLOAT: return "float"; case TEAVM_FIELD_TYPE_DOUBLE: return "double"; default: return "unknown"; } } static char* teavm_gc_primitiveTypeName(int32_t type) { switch (type) { case 0: return "boolean"; case 1: return "byte"; case 2: return "short"; case 3: return "char"; case 4: return "int"; case 5: return "long"; case 6: return "float"; case 7: return "double"; default: return "unknown"; } } static void teavm_gc_writeHeapDumpClasses(FILE* out) { fprintf(out, "\"classes\":["); for (int i = 0; i < teavm_classReferencesCount; ++i) { if (i > 0) { fprintf(out, ",\n"); } TeaVM_Class* cls = teavm_classReferences[i]; fprintf(out, "{\"id\":%" PRIuPTR, (uintptr_t) cls); if (cls->name != NULL && !(cls->flags & 2) && cls->itemType == NULL) { fprintf(out, ",\"name\":"); char16_t* name = teavm_stringToC16(*cls->name); fprintf(out, "\""); teavm_gc_escapeJsonString(out, name); fprintf(out, "\""); free(name); } if (cls->flags & 2) { fprintf(out, ",\"primitive\":\"%s\"", teavm_gc_primitiveTypeName((cls->flags >> 3) & 7)); } else if (cls->itemType != NULL) { fprintf(out, ",\"item\":%" PRIuPTR, (uintptr_t) cls->itemType); } else { fprintf(out, ",\"size\":%" PRId32, cls->size); fprintf(out, ",\"super\":"); if (cls->superclass != NULL) { fprintf(out, "%" PRIuPTR, (uintptr_t) cls->superclass); } else { fprintf(out, "null"); } if (cls->fieldDescriptors != NULL) { fprintf(out, ",\"fields\":["); for (int j = 0; j < cls->fieldDescriptors->count; ++j) { if (j > 0) { fprintf(out, ","); } TeaVM_FieldDescriptor* field = &cls->fieldDescriptors->data[j]; fprintf(out, "{\"name\":\""); teavm_gc_escapeJsonString(out, field->name); fprintf(out, "\",\"type\":\"%s\"}", teavm_gc_fieldTypeName(field->type)); } fprintf(out, "]"); } if (cls->staticFieldDescriptors != NULL) { fprintf(out, ",\"staticFields\":["); for (int j = 0; j < cls->staticFieldDescriptors->count; ++j) { if (j > 0) { fprintf(out, ","); } TeaVM_StaticFieldDescriptor* field = &cls->staticFieldDescriptors->data[j]; fprintf(out, "{\"name\":\""); teavm_gc_escapeJsonString(out, field->name); fprintf(out, "\",\"type\":\"%s\"}", teavm_gc_fieldTypeName(field->type)); } fprintf(out, "]"); fprintf(out, ",\"data\":\""); for (int j = 0; j < cls->staticFieldDescriptors->count; ++j) { TeaVM_StaticFieldDescriptor* field = &cls->staticFieldDescriptors->data[j]; teavm_gc_writeHeapDumpData(out, field->offset, teavm_gc_fieldTypeSize(field->type)); } fprintf(out, "\""); } } fprintf(out, "}"); } fprintf(out, "\n]"); } static int teavm_gc_classDepth(TeaVM_Class* cls) { int depth = 0; while (cls) { depth++; cls = cls->superclass; } return depth; } static void teavm_gc_writeHeapDumpObject(FILE* out, TeaVM_Object* obj) { TeaVM_Class* cls = TEAVM_CLASS_OF(obj); fprintf(out, "{\"id\":%" PRIuPTR ",\"class\":%" PRIuPTR, (uintptr_t) obj, (uintptr_t) cls); if (cls->itemType != NULL) { int32_t itemSize; if (cls->itemType->flags & 2) { itemSize = cls->itemType->size; } else { itemSize = sizeof(void*); } char* offset = NULL; offset += sizeof(TeaVM_Array); offset = TEAVM_ALIGN(offset, itemSize); unsigned char* data = (unsigned char*) obj + (uintptr_t) offset; int32_t size = ((TeaVM_Array*) obj)->size; fprintf(out, ",\"data\":\""); int32_t limit = size * itemSize; for (int32_t i = 0; i < limit; i += itemSize) { teavm_gc_writeHeapDumpData(out, data + i, itemSize); } fprintf(out, "\""); } else { fprintf(out, ",\"data\":\""); int classDepth = teavm_gc_classDepth(cls); TeaVM_Class** classes = malloc(classDepth * sizeof(TeaVM_Class*)); int i = classDepth; while (cls != NULL) { classes[--i] = cls; cls = cls->superclass; } for (; i < classDepth; ++i) { cls = classes[i]; if (cls->fieldDescriptors != NULL) { TeaVM_FieldDescriptors* fieldDescriptors = cls->fieldDescriptors; for (int j = 0; j < fieldDescriptors->count; ++j) { TeaVM_FieldDescriptor* field = &fieldDescriptors->data[j]; teavm_gc_writeHeapDumpData(out, (unsigned char*) obj + field->offset, teavm_gc_fieldTypeSize(field->type)); } } } fprintf(out, "\""); } fprintf(out, "}"); } static void teavm_gc_writeHeapDumpObjects(FILE* out) { fprintf(out, "\"objects\":["); int first = 1; TeaVM_Object* obj = teavm_gc_heapAddress; while ((char*) obj < (char*) teavm_gc_heapAddress + teavm_gc_availableBytes) { int32_t size; if (obj->header == 0) { size = obj->hash; } else { if (!first) { fprintf(out, ","); } first = 0; fprintf(out, "\n"); teavm_gc_writeHeapDumpObject(out, obj); size = teavm_gc_objectSize(obj); } obj = (TeaVM_Object*) ((char*) obj + size); } TeaVM_HashtableEntrySet* strings = teavm_stringHashtableData; while (strings != NULL) { for (int32_t i = 0; i < strings->size; ++i) { TeaVM_String* str = strings->data[i].data; if ((char*) str >= (char*) teavm_gc_heapAddress && (char*) str < (char*) teavm_gc_heapAddress + teavm_gc_availableBytes) { break; } if (!first) { fprintf(out, ","); } first = 0; fprintf(out, "\n"); teavm_gc_writeHeapDumpObject(out, (TeaVM_Object*) str); fprintf(out, ",\n"); teavm_gc_writeHeapDumpObject(out, (TeaVM_Object*) str->characters); } strings = strings->next; } fprintf(out, "\n]"); } static void teavm_gc_writeHeapDumpStack(FILE* out) { fprintf(out, "\"stack\":["); TeaVM_StackFrame* frame = teavm_stackTop; int first = 1; while (frame != NULL) { if (!first) { fprintf(out, ","); } first = 0; fprintf(out, "\n{"); void** data = &((struct { TeaVM_StackFrame frame; void* data; }*) frame)->data; TeaVM_CallSite* callSite = TEAVM_FIND_CALLSITE(frame->callSiteId, frame); if (callSite->location != NULL) { TeaVM_MethodLocation* method = callSite->location->method; if (method != NULL) { if (method->fileName != NULL) { fprintf(out, "\"file\":\""); char16_t* mbName = teavm_stringToC16(*method->fileName); teavm_gc_escapeJsonString(out, mbName); fprintf(out, "\","); free(mbName); } if (method->className != NULL) { fprintf(out, "\"class\":\""); char16_t* mbName = teavm_stringToC16(*method->className); teavm_gc_escapeJsonString(out, mbName); fprintf(out, "\","); free(mbName); } if (method->methodName != NULL) { fprintf(out, "\"method\":\""); char16_t* mbName = teavm_stringToC16(*method->methodName); teavm_gc_escapeJsonString(out, mbName); fprintf(out, "\","); free(mbName); } } if (callSite->location->lineNumber >= 0) { fprintf(out, "\"line\":%" PRId32 ",", callSite->location->lineNumber); } } fprintf(out, "\"roots\":["); int rootsFirst = 1; for (int32_t i = 0; i < frame->size; ++i) { if (data[i] != NULL) { if (!rootsFirst) { fprintf(out, ","); } rootsFirst = 0; fprintf(out, "%" PRIuPTR, (uintptr_t) data[i]); } } fprintf(out, "]}"); frame = frame->next; } fprintf(out, "\n]"); } static void teavm_gc_writeHeapDumpTo(FILE* out) { fprintf(out, "{\n"); fprintf(out, "\"pointerSize\":%u,\n", (unsigned int) sizeof(void*)); teavm_gc_writeHeapDumpClasses(out); fprintf(out, ",\n"); teavm_gc_writeHeapDumpObjects(out); fprintf(out, ",\n"); teavm_gc_writeHeapDumpStack(out); fprintf(out, "\n}"); } #endif void teavm_gc_writeHeapDump() { #if TEAVM_HEAP_DUMP teavm_gc_fixHeap(); FILE* out = teavm_gc_openDumpFile(L"teavm-heap-dump.json"); if (out == NULL) { fprintf(stdout, "Error: could not write heap dump"); return; } teavm_gc_writeHeapDumpTo(out); fclose(out); #endif }
34.722607
133
0.465548
[ "object" ]
a4de4ef5abe0e839794c520d02ea9e17c363b7ca
2,513
h
C
libs/DS4_SDK/samples/saving/customscenedata/myscenemodel.h
Red54/reality
510d4f5fde2f4c5535482f1ea199f914102b8a2a
[ "BSD-3-Clause" ]
null
null
null
libs/DS4_SDK/samples/saving/customscenedata/myscenemodel.h
Red54/reality
510d4f5fde2f4c5535482f1ea199f914102b8a2a
[ "BSD-3-Clause" ]
null
null
null
libs/DS4_SDK/samples/saving/customscenedata/myscenemodel.h
Red54/reality
510d4f5fde2f4c5535482f1ea199f914102b8a2a
[ "BSD-3-Clause" ]
null
null
null
/********************************************************************** Copyright (C) 2002-2012 DAZ 3D, Inc. All Rights Reserved. This file is part of the DAZ Studio SDK. This file may be used only in accordance with the DAZ Studio SDK license provided with the DAZ Studio SDK. The contents of this file may not be disclosed to third parties, copied or duplicated in any form, in whole or in part, without the prior written permission of DAZ 3D, Inc, except as explicitly allowed in the DAZ Studio SDK license. See http://www.daz3d.com to contact DAZ 3D, Inc or for more information about the DAZ Studio SDK. **********************************************************************/ #pragma once /***************************** Include files *****************************/ #include <dzcustomdata.h> #include <dzassetextraobjectio.h> /***************************** Forwards *****************************/ struct MyReadContext; /***************************** Class definitions *****************************/ class MySceneModel : public DzSceneData { Q_OBJECT public: MySceneModel(); ~MySceneModel(); bool isEmpty(); public slots: const QString& coolText(); void setCoolText(const QString&); signals: void coolTextChanged(const QString&); private: QString m_coolText; }; class MySceneModelIO : public DzExtraSceneDataIO { Q_OBJECT public: MySceneModelIO(); ~MySceneModelIO(); // DzExtraSceneDataIO virtual DzSceneData* createDataItem( const DzFileIOSettings *opts ) const; virtual bool shouldWrite( QObject* object, const DzFileIOSettings* opts ) const; virtual DzError writeExtraInstance( QObject* object, IDzJsonIO* io, const DzFileIOSettings* opts ) const; virtual DzAssetJsonObject* startInstanceRead( DzAssetJsonItem* parentItem ); virtual DzError applyInstanceToObject( QObject* object, const DzFileIOSettings* opts ) const; virtual DzError resolveInstance( QObject* object, const DzFileIOSettings* opts ) const; // for reading MyReadContext* m_context; }; struct MyReadContext { MyReadContext(DzAssetFile& file) : m_file(file) {} DzAssetFile& m_file; QString m_coolText; }; class ReadMySceneModel : public DzAssetJsonObject { public: ReadMySceneModel(MyReadContext* context) : DzAssetJsonObject(context->m_file), m_context(context) {} virtual bool addMember( const QString &name, const QString &val ); MyReadContext* m_context; };
28.235955
110
0.635097
[ "object", "3d" ]
a4e907afd858bf7838033c35d47c330c04b2a943
702
h
C
ST/sensor_tag/android/src/system/middlewares/juma/mesh/mesh.h
JUMA-IO/JUMA_Demos
f74579b318f6414b0c6a362a888bcfc9a7509362
[ "MIT" ]
9
2016-01-14T03:00:39.000Z
2018-01-28T14:40:48.000Z
ST/sensor_tag/android/src/system/middlewares/juma/mesh/mesh.h
JUMA-IO/JUMA_Demos
f74579b318f6414b0c6a362a888bcfc9a7509362
[ "MIT" ]
3
2016-04-15T03:34:21.000Z
2016-05-05T01:37:11.000Z
ST/sensor_tag/android/src/system/middlewares/juma/mesh/mesh.h
JUMA-IO/JUMA_Demos
f74579b318f6414b0c6a362a888bcfc9a7509362
[ "MIT" ]
23
2016-01-12T02:58:37.000Z
2021-06-22T14:22:54.000Z
#ifndef _MESH_H_ #define _MESH_H_ #include "bluenrg_sdk_api.h" #include "bluenrg_sdk_host_api.h" typedef struct _mesh_manuf_data_t{ uint8_t len; //total data length uint8_t data_type; // advertise data type uint16_t adv_info_number; // advertising information number uint16_t data; // user data }mesh_manuf_data_t; enum mesh_status_t { mesh_ok = 0, mesh_failed = 1, }; /*mesh rx scan data handle*/ void mesh_rx_scan_data(void* data); /*mesh rx host message handle*/ void mesh_rx_host_message(void* data); /*mesh disconnect handle*/ void mesh_disconnect_handle(void* data); /*mesh on message*/ void mesh_on_message(void* data); #endif
20.647059
65
0.706553
[ "mesh" ]
a4ea2dfc9020eba3427969575a51003193f64ed2
2,736
h
C
src/coroutine/co_select.h
Lab-Zjt/liblily
ca92f5f14335f7a836646d661da3e6fce9be04d4
[ "Apache-2.0" ]
null
null
null
src/coroutine/co_select.h
Lab-Zjt/liblily
ca92f5f14335f7a836646d661da3e6fce9be04d4
[ "Apache-2.0" ]
null
null
null
src/coroutine/co_select.h
Lab-Zjt/liblily
ca92f5f14335f7a836646d661da3e6fce9be04d4
[ "Apache-2.0" ]
1
2020-04-14T18:17:16.000Z
2020-04-14T18:17:16.000Z
#ifndef LILY_SRC_COROUTINE_CO_SELECT_H_ #define LILY_SRC_COROUTINE_CO_SELECT_H_ #include "co_chan.h" #include "epoller.h" #include <vector> #include <functional> #include <sys/epoll.h> #include <sys/eventfd.h> #include <unistd.h> namespace lily { // 表示一种case template<typename T> struct Case { Channel<T> &chan; std::function<void(T)> func; template<typename F> Case(Channel<T> &ch, F &&f):chan(ch), func(std::forward<F>(f)) {} }; template<typename T, typename F> Case<T> CreateCase(Channel<T> &ch, F &&f) { return Case<T>(ch, std::forward<F>(f)); } struct DefaultCase {}; static Channel<DefaultCase> _default; template<typename ...Args> inline static void foreachHelper(Args ...args) {} // 模拟golang的select语法 template<typename ...Ts> class Selector { private: using HandlerPtr = std::unique_ptr<std::function<void()>>; private: // 防止析构 std::vector<HandlerPtr> m_func_vec; Epoller m_epoll; HandlerPtr m_default_handler; bool m_has_default = false; public: // 初始化Selector template<typename T> int fillSelector(Case<T> &&t) { HandlerPtr handler(new std::function<void()>(std::bind([this](Channel<T> &ch, std::function<void(T)> fn) { // 尝试从ch中获取一个元素 auto ptr = ch.try_fetch(); // 获取失败(多个协程同时被唤醒,该元素已被消耗) if (ptr == nullptr) { return; } // 消耗掉对应的event fd的值 size_t buf; read(ch.GetEventFd(), &buf, sizeof(buf)); // 调用回调函数 fn(std::move(*ptr)); }, std::ref(t.chan), std::move(t.func)))); epoll_event ev[1]; ev->events = EPOLLIN; ev->data.ptr = handler.get(); // 防止析构 m_func_vec.emplace_back(std::move(handler)); m_epoll.Add(t.chan.GetEventFd(), ev); return 0; } int fillSelector(Case<DefaultCase> &&t) { m_default_handler = HandlerPtr(new std::function<void()>(std::bind( [this](Channel<DefaultCase> &ch, std::function<void(DefaultCase)> fn) { // 调用回调函数 fn(DefaultCase{}); }, std::ref(t.chan), std::move(t.func)))); m_has_default = true; return 0; } explicit Selector(Case<Ts> &&...chans) { foreachHelper(fillSelector(std::move(chans))...); } void Select() { std::vector<epoll_event> ev(1); if (m_has_default) { if (m_epoll.Epoll(ev, 0) <= 0) { (*m_default_handler)(); return; } } else { m_epoll.Epoll(ev, -1); } // 调用handle函数 (*static_cast<std::function<void()> *>(ev.front().data.ptr))(); } }; template<typename ...Ts> inline Selector<Ts...> Select(Case<Ts> &&...cases) { return Selector<Ts...>(std::move(cases)...); } } #endif
27.36
112
0.592471
[ "vector" ]
a4f5302871dfcef8da3e9ad818c7326b170af1cb
3,205
h
C
TAO/tao/AnyTypeCode/Objref_TypeCode.h
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tao/AnyTypeCode/Objref_TypeCode.h
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tao/AnyTypeCode/Objref_TypeCode.h
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// -*- C++ -*- //============================================================================= /** * @file Objref_TypeCode.h * * $Id: Objref_TypeCode.h 96398 2012-11-28 07:33:51Z johnnyw $ * * Header file for * @c tk_abstract_interface, * @c tk_component, * @c tk_home, * @c tk_local_interface, * @c tk_native and * @c tk_objref * @c CORBA::TypeCodes. * * @author Ossama Othman <ossama@dre.vanderbilt.edu> */ //============================================================================= #ifndef TAO_OBJREF_TYPECODE_H #define TAO_OBJREF_TYPECODE_H #include /**/ "ace/pre.h" #include "tao/AnyTypeCode/TypeCode.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ #include "tao/AnyTypeCode/TypeCode_Base_Attributes.h" TAO_BEGIN_VERSIONED_NAMESPACE_DECL namespace TAO { namespace TypeCode { /** * @class Objref_Base * * @brief @c CORBA::TypeCode implementation for an OMG IDL * @c object and object-like types. * * This class implements a @c CORBA::TypeCode for an OMG IDL * @c object (interface) and object-like types (abstract * interface, component, home, local interface and native). */ template <typename StringType, class RefCountPolicy> class Objref : public CORBA::TypeCode, private RefCountPolicy { public: /// Constructor. Objref (CORBA::TCKind kind, char const * id, char const * name); /** * @name TAO-specific @c CORBA::TypeCode Methods * * Methods required by TAO's implementation of the * @c CORBA::TypeCode class. * * @see @c CORBA::TypeCode */ //@{ virtual bool tao_marshal (TAO_OutputCDR & cdr, CORBA::ULong offset) const; virtual void tao_duplicate (void); virtual void tao_release (void); //@} protected: /** * @name @c TAO CORBA::TypeCode Template Methods * * @c tk_abstract_interface, @c tk_component, @c * tk_local_interface, @c tk_native and @c tk_objref * @c CORBA::TypeCode -specific template methods. * * @see @c CORBA::TypeCode */ //@{ virtual CORBA::Boolean equal_i (CORBA::TypeCode_ptr tc) const; virtual CORBA::Boolean equivalent_i (CORBA::TypeCode_ptr tc) const; virtual CORBA::TypeCode_ptr get_compact_typecode_i (void) const; virtual char const * id_i (void) const; virtual char const * name_i (void) const; protected: /// Base attributes (@c id and @c name). Base_Attributes<StringType> attributes_; }; } // End namespace TypeCode } // End namespace TAO TAO_END_VERSIONED_NAMESPACE_DECL #ifdef __ACE_INLINE__ # include "tao/AnyTypeCode/Objref_TypeCode.inl" #endif /* __ACE_INLINE__ */ #ifdef ACE_TEMPLATES_REQUIRE_SOURCE # include "tao/AnyTypeCode/Objref_TypeCode.cpp" #endif /* ACE_TEMPLATES_REQUIRE_SOURCE */ #ifdef ACE_TEMPLATES_REQUIRE_PRAGMA # pragma implementation ("Objref_TypeCode.cpp") #endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */ #include /**/ "ace/post.h" #endif /* TAO_OBJREF_TYPECODE_H */
26.056911
79
0.609048
[ "object" ]
a4f6ddecbc3ee52f75e585b62ea4da91a7fd3e79
343
h
C
engine/vulkan_render/vulkan_render_data.h
ilopit/agea
9825b661a5e34bb8efe858e52d35656a396bc925
[ "MIT" ]
null
null
null
engine/vulkan_render/vulkan_render_data.h
ilopit/agea
9825b661a5e34bb8efe858e52d35656a396bc925
[ "MIT" ]
null
null
null
engine/vulkan_render/vulkan_render_data.h
ilopit/agea
9825b661a5e34bb8efe858e52d35656a396bc925
[ "MIT" ]
null
null
null
#pragma once #include "agea_minimal.h" #include "vulkan_render/vulkan_render_fwds.h" #include <string> namespace agea { struct render_data { std::string id() const; bool visible = true; render::mesh_data* mesh = nullptr; render::material_data* material = nullptr; glm::mat4 transform_matrix; }; } // namespace agea
14.913043
46
0.696793
[ "mesh", "render" ]
a4fa73e5bec9e1197f849310cb7300174124bac6
33,315
h
C
modules/core/include/ecvl/core/imgproc.h
simleo/ecvl
6e6088c45677892e347fb612ef4a6c81b48d2e08
[ "MIT" ]
9
2020-01-22T09:49:09.000Z
2021-05-23T19:00:00.000Z
modules/core/include/ecvl/core/imgproc.h
simleo/ecvl
6e6088c45677892e347fb612ef4a6c81b48d2e08
[ "MIT" ]
27
2020-01-21T17:20:12.000Z
2022-03-29T18:15:42.000Z
modules/core/include/ecvl/core/imgproc.h
simleo/ecvl
6e6088c45677892e347fb612ef4a6c81b48d2e08
[ "MIT" ]
3
2020-01-22T10:16:56.000Z
2020-06-03T12:21:46.000Z
/* * ECVL - European Computer Vision Library * Version: 0.3.4 * copyright (c) 2021, Università degli Studi di Modena e Reggio Emilia (UNIMORE), AImageLab * Authors: * Costantino Grana (costantino.grana@unimore.it) * Federico Bolelli (federico.bolelli@unimore.it) * Michele Cancilla (michele.cancilla@unimore.it) * Laura Canalini (laura.canalini@unimore.it) * Stefano Allegretti (stefano.allegretti@unimore.it) * All rights reserved. */ #ifndef ECVL_IMGPROC_H_ #define ECVL_IMGPROC_H_ #include <random> #include "image.h" #include "saturate_cast.h" namespace ecvl { /** @brief Enum class representing the ECVL thresholding types. @anchor ThresholdingType */ enum class ThresholdingType { BINARY, /**< \f[\texttt{dst} (x,y) = \fork{\texttt{maxval}}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{0}{otherwise}\f] */ BINARY_INV, /**< \f[\texttt{dst} (x,y) = \fork{0}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{maxval}}{otherwise}\f] */ }; /** @brief Enum class representing the ECVL interpolation types. @anchor InterpolationType */ enum class InterpolationType { nearest, /**< Nearest neighbor interpolation */ linear, /**< Bilinear interpolation */ area, /**< Resampling using pixel area relation. It may be a preferred method for image decimation, as it gives moire-free results. But when the image is zoomed, it is similar to the nearest method. */ cubic, /**< Bicubic interpolation */ lanczos4 /**< Lanczos interpolation over 8x8 neighborhood */ }; /** @brief Given an InterpolationType, the GetOpenCVInterpolation function returns the associated OpenCV enum value. @param[in] interp Interpolation type, see @ref InterpolationType. @return Associated OpenCV enum value. */ int GetOpenCVInterpolation(InterpolationType interp); /** @brief Resizes an Image to the specified dimensions The function resizes Image src and outputs the result in dst. @param[in] src The input Image. @param[out] dst The output resized Image. @param[in] newdims std::vector<int> that specifies the new size of each dimension. The vector size must match the src Image dimensions, excluding the color channel. @param[in] interp InterpolationType to be used. Default is InterpolationType::linear. */ void ResizeDim(const ecvl::Image& src, ecvl::Image& dst, const std::vector<int>& newdims, InterpolationType interp = InterpolationType::linear); /** @brief Resizes an Image by scaling the dimensions to a given scale factor The function resizes Image src and outputs the result in dst. @param[in] src The input Image. @param[out] dst The output rescaled Image. @param[in] scales std::vector<double> that specifies the scale to apply to each dimension. The vector size must match the src Image dimensions, excluding the color channel. @param[in] interp InterpolationType to be used. Default is InterpolationType::linear. */ void ResizeScale(const ecvl::Image& src, ecvl::Image& dst, const std::vector<double>& scales, InterpolationType interp = InterpolationType::linear); /** @brief Flips an Image The Flip2D procedure vertically flips an Image. @param[in] src The input Image. @param[out] dst The output flipped Image. */ void Flip2D(const ecvl::Image& src, ecvl::Image& dst); /** @brief Mirrors an Image The Mirror2D procedure horizontally flips an Image. @param[in] src The input Image. @param[out] dst The output mirrored Image. */ void Mirror2D(const ecvl::Image& src, ecvl::Image& dst); /** @brief Rotates an Image The Rotate2D procedure rotates an Image of a given angle (expressed in degrees) in a clockwise manner, with respect to a given center. The value of unknown pixels in the output Image are set to 0. The output Image is guaranteed to have the same dimensions as the input one. An optional scale parameter can be provided: this won't change the output Image size, but the image is scaled during rotation. Different interpolation types are available, see @ref InterpolationType. @param[in] src The input Image. @param[out] dst The output rotated Image. @param[in] angle The rotation angle in degrees. @param[in] center A std::vector<double> representing the coordinates of the rotation center. If empty, the center of the image is used. @param[in] scale Optional scaling factor. @param[in] interp Interpolation type used. Default is InterpolationType::linear. */ void Rotate2D(const ecvl::Image& src, ecvl::Image& dst, double angle, const std::vector<double>& center = {}, double scale = 1.0, InterpolationType interp = InterpolationType::linear); /** @brief Rotates an Image resizing the output accordingly. The RotateFullImage2D procedure rotates an Image of a given angle (expressed in degrees) in a clockwise manner. The value of unknown pixels in the output Image are set to 0. The output Image is guaranteed to contain all the pixels of the rotated image. Thus, its dimensions can be different from those of the input. An optional scale parameter can be provided. Different interpolation types are available, see @ref InterpolationType. @param[in] src The input Image. @param[out] dst The rotated output Image. @param[in] angle The rotation angle in degrees. @param[in] scale Optional scaling factor. @param[in] interp Interpolation type used. Default is InterpolationType::linear. */ void RotateFullImage2D(const ecvl::Image& src, ecvl::Image& dst, double angle, double scale = 1.0, InterpolationType interp = InterpolationType::linear); /** @brief Copies the source Image into destination Image changing the color space. The ChangeColorSpace procedure converts the color space of the source Image into the specified color space. New data are copied into destination Image. Source and destination can be contiguous or not and can also be the same Image. @param[in] src The input Image to convert in the new color space. @param[out] dst The output Image in the "new_type" color space. @param[in] new_type The new color space in which the src Image must be converted. */ void ChangeColorSpace(const Image& src, Image& dst, ColorType new_type); /** @brief Applies a fixed threshold to an input Image. The Threshold() function applies a fixed thresholding to an input Image. The function is useful to get a binary image out of a grayscale (ColorType::GRAY) Image or to remove noise filtering out pixels with too small or too large values. Anyway, the function can be applied to any input Image. The pixels up to "thresh" value will be set to 0, the pixels above this value will be set to "maxvalue" if "thresh_type" is ThresholdingType::BINARY (default). The opposite will happen if "thresh_type" is ThresholdingType::BINARY_INV. @param[in] src Input Image on which to apply the threshold. @param[out] dst The output thresholded Image. @param[in] thresh Threshold value. @param[in] maxval The maximum values in the thresholded Image. @param[in] thresh_type Type of threshold to be applied, see @ref ThresholdingType. The default value is ThresholdingType::BINARY. */ void Threshold(const Image& src, Image& dst, double thresh, double maxval, ThresholdingType thresh_type = ThresholdingType::BINARY); /** @brief Applies multiple thresholds to the input Image. The Threshold() function applies multiple thresholding to the input Image. The resulting Image is quantized based on the provided thresholds values. Output values will range uniformly from minval to maxval. @param[in] src Input Image on which to apply the threshold. @param[out] dst The output thresholded Image. @param[in] thresholds Threshold values. @param[in] minval The minimum value in the output Image. Default is 0. @param[in] maxval The maximum value in the output Image. Default is 255. */ void MultiThreshold(const Image& src, Image& dst, const std::vector<int>& thresholds, int minval = 0, int maxval = 255); /** @brief Calculates the Otsu thresholding value. The OtsuThreshold() function calculates the Otsu threshold value over a given input Image. The Image must be of ColorType::GRAY. This function implements the algorithm described in \cite Otsu1979. @param[in] src Input Image on which to calculate the Otsu threshold value. @return Otsu threshold value. */ int OtsuThreshold(const Image& src); /** @brief Calculates the Otsu thresholding values. The OtsuThreshold() function calculates the Otsu threshold values over a given input Image. The source Image must be of ColorType::GRAY. The number of thresholds to be found is defined by the n_thresholds parameter (default is 2). This function implement the algorithm described in \cite Liao2001. @param[in] src Input Image on which to calculate the Otsu threshold value. @param[in] n_thresholds Number of thresholds to be found using the Otsu multi threshold algorithm variation. @return Otsu thresholds value in a vector of ints. */ std::vector<int> OtsuMultiThreshold(const Image& src, int n_thresholds = 2); /** @brief Convolves an Image with a kernel @param[in] src Input Image. @param[out] dst Output Image. @param[in] ker Convolution kernel. @param[in] type Destination ecvl::DataType. If DataType::none, the same of src is used. */ void Filter2D(const Image& src, Image& dst, const Image& ker, DataType type = DataType::none /* type of border */); /** @brief Convolves an Image with a couple of 1-dimensional kernels @param[in] src Input Image. @param[out] dst Output Image. @param[in] kerX Convolution kernel for the X-axis. @param[in] kerY Convolution kernel for the Y-axis. @param[in] type Destination ecvl::DataType. If DataType::none, the same of src is used. */ void SeparableFilter2D(const Image& src, Image& dst, const std::vector<double>& kerX, const std::vector<double>& kerY, DataType type = DataType::none); /** @brief Blurs an Image using a Gaussian kernel. @param[in] src Input Image. @param[out] dst Output Image. @param[in] sizeX Horizontal size of the kernel. Must be positive and odd. @param[in] sizeY Vertical size of the kernel. Must be positive and odd. @param[in] sigmaX Gaussian kernel standard deviation in X direction. @param[in] sigmaY Gaussian kernel standard deviation in Y direction. If zero, sigmaX is used. If both are zero, they are calculated from sizeX and sizeY. */ void GaussianBlur(const Image& src, Image& dst, int sizeX, int sizeY, double sigmaX, double sigmaY = 0); void GaussianBlur(const Image& src, Image& dst, double sigma); /** @brief Adds Laplace distributed noise to an Image. @param[in] src Input Image. @param[out] dst Output Image. @param[in] std_dev Standard deviation of the noise generating distribution. Suggested values are around 255 * 0.05 for uint8 Images. */ void AdditiveLaplaceNoise(const Image& src, Image& dst, double std_dev); /** @brief Adds Poisson distributed noise to an Image. @param[in] src Input Image. @param[out] dst Output Image. @param[in] lambda Lambda parameter of the Poisson distribution. */ void AdditivePoissonNoise(const Image& src, Image& dst, double lambda); /** @brief Adjust contrast by scaling each pixel value X to 255 * ((X/255) ** gamma). @param[in] src Input Image. @param[out] dst Output Image. @param[in] gamma Exponent for the contrast adjustment. */ void GammaContrast(const Image& src, Image& dst, double gamma); /** @brief Sets rectangular areas within an Image to zero. @param[in] src Input Image. @param[out] dst Output Image. @param[in] p Probability of any rectangle being set to zero. @param[in] drop_size Size of rectangles in percentage of the input Image. @param[in] per_channel Whether to use the same value for all channels of a pixel or not. */ void CoarseDropout(const Image& src, Image& dst, double p, double drop_size, bool per_channel); /** @brief Calculate the integral image of the source Image. @param[in] src Input Image. It must be with ColorType::GRAY, "xyc" and DataType::uint8. @param[out] dst Output Image. @param[in] dst_type DataType of the destination Image. */ void IntegralImage(const Image& src, Image& dst, DataType dst_type = DataType::float64); /** @brief Calculate the Non-Maxima suppression of the source Image. @param[in] src Input Image. It must be with ColorType::GRAY, "xyc" and DataType::int32. @param[out] dst Output Image. */ void NonMaximaSuppression(const Image& src, Image& dst); /** @brief Get the `n` maximum values that are in the source Image. @param[in] src Input Image. It must be with ColorType::GRAY, "xyc" and DataType::int32. @param[in] n How many values must be returned. @return vector of Point2i containing the coordinates of the n max values of the Image. */ std::vector<ecvl::Point2i> GetMaxN(const Image& src, size_t n); /** @brief Labels connected components in a binary Image The ConnectedComponentsLabeling() procedure implement the Spaghetti algorithm described in \cite Bolelli2019, an extremely efficient algorithm to label connected components inside binary images using 8-way connectivity. @param[in] src Input Image. It must be with channels "xyc", only one color channel and DataType::uint8. @param[out] dst Output Image. */ void ConnectedComponentsLabeling(const Image& src, Image& dst); /** @brief Finds contours in a binary image @param[in] src Input Image. It must be with channels "xyc", only one color channel and DataType::uint8. @param[out] contours Output contours. */ void FindContours(const Image& src, std::vector<std::vector<Point2i>>& contours); /** @brief Stack a sequence of Images along the depth dimension (images width and height must match) @param[in] src vector of input Images. It must be with channels "xyc". @param[out] dst Output Image. */ void Stack(const std::vector<Image>& src, Image& dst); /** @brief Horizontal concatenation of images (with the same number of rows) @param[in] src vector of input Images. @param[out] dst Output Image. */ void HConcat(const std::vector<Image>& src, Image& dst); /** @brief Vertical concatenation of images (with the same number of columns) @param[in] src vector of input Images. @param[out] dst Output Image. */ void VConcat(const std::vector<Image>& src, Image& dst); /** @brief Enum class representing the ECVL morphology types. @anchor MorphType */ enum class MorphType { MORPH_ERODE , MORPH_DILATE , MORPH_OPEN , /**< an opening operation \f[\texttt{dst} = \mathrm{open} ( \texttt{src} , \texttt{element} )= \mathrm{dilate} ( \mathrm{erode} ( \texttt{src} , \texttt{element} ))\f] */ MORPH_CLOSE , /**< a closing operation */ /**< \f[\texttt{dst} = \mathrm{close} ( \texttt{src} , \texttt{element} )= \mathrm{erode} ( \mathrm{dilate} ( \texttt{src} , \texttt{element} ))\f]*/ MORPH_GRADIENT, /**< a morphological gradient */ /**< \f[\texttt{dst} = \mathrm{morph\_grad} ( \texttt{src} , \texttt{element} )= \mathrm{dilate} ( \texttt{src} , \texttt{element} )- \mathrm{erode} ( \texttt{src} , \texttt{element} )\f] */ MORPH_TOPHAT , /**< "top hat" */ /**< \f[\texttt{dst} = \mathrm{tophat} ( \texttt{src} , \texttt{element} )= \texttt{src} - \mathrm{open} ( \texttt{src} , \texttt{element} )\f] */ MORPH_BLACKHAT, /**< "black hat" */ /**< \f[\texttt{dst} = \mathrm{blackhat} ( \texttt{src} , \texttt{element} )= \mathrm{close} ( \texttt{src} , \texttt{element} )- \texttt{src}\f] */ MORPH_HITMISS /**< "hit or miss". */ /**< Only supported for DataType::uint8 binary images.*/ }; /** @brief Enum class representing the ECVL border types. @anchor BorderType */ enum class BorderType { BORDER_CONSTANT, //!< `iiiiii|abcdefgh|iiiiiii` with some specified `i` BORDER_REPLICATE, //!< `aaaaaa|abcdefgh|hhhhhhh` BORDER_REFLECT, //!< `fedcba|abcdefgh|hgfedcb` BORDER_WRAP, //!< `cdefgh|abcdefgh|abcdefg` BORDER_REFLECT_101, //!< `gfedcb|abcdefgh|gfedcba` BORDER_TRANSPARENT //!< `uvwxyz|abcdefgh|ijklmno` }; /** @brief Performs advanced morphological transformations using an erosion and dilation as basic operations. @param[in] src Input Image. @param[out] dst Output Image. @param[in] op Type of a morphological operation, see MorphType. @param[in] kernel Structuring element. @param[in] anchor Anchor position with the kernel. Negative values mean that the anchor is at the kernel center. @param[in] iterations Number of times erosion and dilation are applied. @param[in] border_type Pixel extrapolation method, see BorderType. BorderType::BORDER_WRAP is not supported. @param[in] border_value Border value in case of a constant border. */ void Morphology(const Image& src, Image& dst, MorphType op, Image& kernel, Point2i anchor = { -1, -1 }, int iterations = 1, BorderType border_type = BorderType::BORDER_CONSTANT, const int& border_value = 0 /*morphologyDefaultBorderValue()*/ ); /** @brief Enum class representing the ECVL inpaint types. @anchor InpaintType */ enum class InpaintType { INPAINT_NS, //!< Use Navier-Stokes based method INPAINT_TELEA //!< Use the algorithm proposed by Alexandru Telea }; /** @brief Restores the selected region in an image using the region neighborhood. @param[in] src Input Image. @param[out] dst Output Image. @param[in] inpaintMask Inpainting mask, an Image with 1-channel and DataType::uint8. Non-zero pixels indicate the area that needs to be inpainted. @param[in] inpaintRadius Radius of a circular neighborhood of each point inpainted that is considered by the algorithm. @param[in] flag Inpainting method that could be InpaintType::INPAINT_NS or InpaintType::INPAINT_TELEA. */ void Inpaint(const Image& src, Image& dst, const Image& inpaintMask, double inpaintRadius, InpaintType flag = InpaintType::INPAINT_TELEA); /** @brief Calculates the mean and the standard deviation of an Image. @param[in] src Input Image. @param[out] mean Mean of the Image pixels. @param[out] stddev Standard deviation of the Image pixels. */ void MeanStdDev(const Image& src, std::vector<double>& mean, std::vector<double>& stddev); /** @brief Swap rows and columns of an Image. @param[in] src Input Image. @param[out] dst Output transposed Image. */ void Transpose(const Image& src, Image& dst); /** @brief Randomly stretch or reduce each cell of the grid in which the input Image is divided into. Based on https://github.com/albumentations-team/albumentations/blob/master/albumentations/augmentations/transforms.py#L1175 @param[in] src Input Image. @param[out] dst Output Image. @param[in] num_steps Count of grid cells on each side. @param[in] distort_limit Range of distortion steps. @param[in] interp Interpolation type used. Default is InterpolationType::linear. @param[in] border_type Flag used to specify the pixel extrapolation method. Default is BorderType::BORDER_REFLECT_101. @param[in] border_value Padding value if border_type is BorderType::BORDER_CONSTANT. @param[in] seed Seed to use for this function's random number generator. */ void GridDistortion(const Image& src, Image& dst, int num_steps = 5, const std::array<float, 2>& distort_limit = { -0.3f, 0.3f }, InterpolationType interp = InterpolationType::linear, BorderType border_type = BorderType::BORDER_REFLECT_101, const int& border_value = 0, const unsigned seed = std::default_random_engine::default_seed ); /** @brief Elastic deformation of input Image. Based on https://github.com/albumentations-team/albumentations/blob/master/albumentations/augmentations/transforms.py#L1235. @param[in] src Input Image. @param[out] dst Output Image. @param[in] alpha Scaling factor that controls the intensity of the deformation. @param[in] sigma Gaussian kernel standard deviation @param[in] interp Interpolation type used. If src is DataType::int8 or DataType::int32, Interpolation::nearest is used. Default is InterpolationType::linear. @param[in] border_type Flag used to specify the pixel extrapolation method. Default is BorderType::BORDER_REFLECT_101. @param[in] border_value Padding value if border_type is BorderType::BORDER_CONSTANT. @param[in] seed Seed to use for this function's random number generator. */ void ElasticTransform(const Image& src, Image& dst, double alpha = 34., double sigma = 4., InterpolationType interp = InterpolationType::linear, BorderType border_type = BorderType::BORDER_REFLECT_101, const int& border_value = 0, const unsigned seed = std::default_random_engine::default_seed ); /** @brief Barrel / pincushion distortion. Based on https://github.com/albumentations-team/albumentations/blob/master/albumentations/augmentations/transforms.py#L1114 @param[in] src Input Image. @param[out] dst Output Image. @param[in] distort_limit Range to randomly select the intensity of the distortion. @param[in] shift_limit Range of image shifting. @param[in] interp Interpolation type used. Default is InterpolationType::linear. @param[in] border_type Flag used to specify the pixel extrapolation method. Default is BorderType::BORDER_REFLECT_101. @param[in] border_value Padding value if border_type is BorderType::BORDER_CONSTANT. @param[in] seed Seed to use for this function's random number generator. */ void OpticalDistortion(const Image& src, Image& dst, const std::array<float, 2>& distort_limit = { -0.3f, 0.3f }, const std::array<float, 2>& shift_limit = { -0.1f, 0.1f }, InterpolationType interp = InterpolationType::linear, BorderType border_type = BorderType::BORDER_REFLECT_101, const int& border_value = 0, const unsigned seed = std::default_random_engine::default_seed ); /** @brief Adds salt noise (white pixels) to an Image. @param[in] src Input Image. @param[out] dst Output Image. @param[in] p Probability of replacing a pixel with salt noise. @param[in] per_channel If true, noise is not considered pixel-wise but channel-wise. @param[in] seed Seed to use for this function's random number generator. */ void Salt(const Image& src, Image& dst, double p, bool per_channel = false, const unsigned seed = std::default_random_engine::default_seed); /** @brief Adds pepper noise (black pixels) to an Image. @param[in] src Input Image. @param[out] dst Output Image. @param[in] p Probability of replacing a pixel with pepper noise. @param[in] per_channel If true, noise is not considered pixel-wise but channel-wise. @param[in] seed Seed to use for this function's random number generator. */ void Pepper(const Image& src, Image& dst, double p, bool per_channel = false, const unsigned seed = std::default_random_engine::default_seed); /** @brief Adds salt and pepper noise (white and black pixels) to an Image. White and black pixels are equally likely. @param[in] src Input Image. @param[out] dst Output Image. @param[in] p Probability of replacing a pixel with salt and pepper noise. @param[in] per_channel If true, noise is not considered pixel-wise but channel-wise. @param[in] seed Seed to use for this function's random number generator. */ void SaltAndPepper(const Image& src, Image& dst, double p, bool per_channel = false, const unsigned seed = std::default_random_engine::default_seed); /** @brief Corrects each voxel's time-series. Slice timing correction works by using (Hanning-windowed) sinc interpolation to shift each time-series by an appropriate fraction of a TR relative to the middle of the TR period. The default slice order acquisition is from the bottom of the brain to the top. @param[in] src Input Image. It must be with channels "xyzt" and with spacings (distance between consecutive voxels on each dimensions). @param[out] dst Output Image. It will be with DataType::float32. @param[in] odd Slices were acquired with interleaved order (0, 2, 4... 1, 3, 5...) @param[in] down Slices were acquired from the top of the brain to the bottom */ void SliceTimingCorrection(const Image& src, Image& dst, bool odd = false, bool down = false); /** @brief Calculate all raw image moments of the source Image up to the specified order. When working with a 2D image, naming the pixel intensities as \f$I(x,y)\f$, raw image moments \f$M_{ij}\f$ are calculated with the following formula: \f$ M_{ij} = \sum_x{\sum_y{x^iy^jI(x,y)}} \f$ The following properties can be derived from raw image moments: - Area (for binary images) or sum of grey level (for grayscale images): \f$M_{00} \f$, accessible through moments(0,0) <em>i.e.</em> moments(x,y); - Centroid: \f$\{\bar{x}, \bar{y}\} = \{\frac{M_{10}}{M_{00}}, \frac{M_{01}}{M_{00}}\}\f$. The formula above can be accordingly extended when working with higher dimensions. <b>Note that raw moments are neither translation, scale nor rotation invariant</b>. Moments are stored in the output moments Image in the same order as for source channels. The output moments Image will be on the same device of the source Image. @param[in] src Input Image on which calculating row moments up to the specified order. It must be a grayscale (ColorType::GRAY) or a data (ColorType::none) Image. @param[out] moments Output data (ColorType:none) Image containing the computed raw image moments. The moments DataType is specified by the type parameter. The size of the Image will be (order + 1, order + 1) @param[in] order Raw image moments will be calculated up to the specified order. Default is 3. @param[in] type Specify the ecvl::DataType to be used for the moments Image. It could be either DataType::float32 or DataType::float64. Default is DataType::float64. */ void Moments(const Image& src, Image& moments, int order = 3, DataType type = DataType::float64); /** @brief Calculate all central image moments of the source Image up to the specified order. When working with a 2D image, naming \f$\bar{x} = \frac{M_{10}}{M_{00}}\f$ and \f$\bar{y} = \frac{M_{01}}{M_{00}}\f$ the components of the centroid (see documentation of Moments() for more details) and \f$I(x,y)\f$ the pixel intensities, the central moments are calculated with the following formula: \f$ \mu_{ij} = \sum_x{\sum_y{(x-\bar{x})^i(y-\bar{y})^jI(x,y)}} \f$ The central moments up to order 3 are then: \f$\mu_{00} = M_{00}\f$,<br/> \f$\mu_{01} = 0\f$,<br/> \f$\mu_{10} = 0\f$,<br/> \f$\mu_{11} = M_{11} - \bar{x}M_{01} = M_{11} - \bar{y}M_{10}\f$,<br/> \f$\mu_{20} = M_{20} - \bar{x}M_{10}\f$,<br/> \f$\mu_{02} = M_{02} - \bar{y}M_{01}\f$,<br/> \f$\mu_{21} = M_{21} - 2\bar{x}M_{11} - \bar{y}M_{20} + 2\bar{x}^2M_{01}\f$,<br/> \f$\mu_{12} = M_{12} - 2\bar{y}M_{11} - \bar{x}M_{02} + 2\bar{y}^2M_{10}\f$,<br/> \f$\mu_{30} = M_{30} - 3\bar{x}M_{20} + 2\bar{x}^2M_{10}\f$,<br/> \f$\mu_{03} = M_{03} - 3\bar{y}M_{02} + 2\bar{y}^2M_{01}\f$<br/> The formula above can be accordingly extended when working with higher dimensions. <b>Note that central moments are translational invariant</b>. Moments are stored in the output moments Image in the same order as for source channels. The output moments Image will be on the same device of the source Image. Information about image orientation can be derived from the covariance matrix of the image \f$I(x,y)\f$, constructed with the second order central moments: \f$cov[I(x,y)] = \begin{bmatrix}\mu_{20}' & \mu_{11}'\\ \mu_{11}' & \mu_{02}'\end{bmatrix}\f$ where \f$\mu_{20}' = \frac{\mu_{20}}{\mu_{00}} = \frac{M_{20}}{M_{00}} − \bar{x}^2\f$<br/> \f$\mu_{02}' = \frac{\mu_{02}}{\mu_{00}} = \frac{M_{02}}{M_{00}} − \bar{y}^2\f$<br/> \f$\mu_{11}' = \frac{\mu_{11}}{\mu_{00}} = \frac{M_{11}}{M_{00}} − \bar{x}\bar{y}\f$<br/> The <b>eigenvectors</b> of the \f$cov[I(x,y)]\f$ matrix correspond to the major and minor axes of the image intensity. The orientation can be extracted as: \f$\theta = \frac{1}{2}arctan(\frac{2\mu_{11}'}{\mu_{20}' - \mu_{02}'})\f$ On the other hand, the <b>eigenvalues</b> of the \f$cov[I(x,y)]\f$ matrix are given by: \f$\lambda_i = \frac{\mu_{20}' + \mu_{02}'}{2} \pm \frac{\sqrt{4\mu_{11}'^2 + (\mu_{20}' - \mu_{02}')^2}}{2} \f$ Eigenvalues are proportional to the square length of the eigenvector axes. The half-axes of the ellipse generated by the eigenvectors are given by \f$\frac{d}{\sqrt{\lambda_1}}\f$ and \f$\frac{d}{\sqrt{\lambda_2}}\f$ where \f$d\f$ is the proportional factor. Considering that the moment \f$\mu_{00} = M_{00}\f$ is the area (when the image is binary) of the image objects we can easily calculate \f$d\f$ using the following equation: \f$\mu_{00} = \pi \frac{d^2}{\sqrt{\lambda_1 \lambda_2}}\f$ Additionally, the eccentricity of the image can be calculates as: \f$e = \sqrt{1 - \frac{\lambda_2}{\lambda_1}}\f$ @param[in] src Input Image on which calculating row moments up to the specified order. It must be a grayscale (ColorType::GRAY) or a data (ColorType::none) Image. @param[out] moments Output data (ColorType:none) Image containing the computed raw image moments. The moments DataType is specified by the type parameter. The size of the Image will be (order + 1, order + 1) @param[in] center Vector (std::vector<double>) representing the center coordinates: they can be calculated from raw moments. As an example, for a 2d image center coordinates are given by \f$(\frac{M_{10}}{M_{00}}, \frac{M_{01}}{M_{00}})\f$. See Moments() documentation for more details. center.size() and src.dims_ must match in size (except for the 'c' channel). The source axes order must be the same used to specify center coordinates. @param[in] order Raw image moments will be calculated up to the specified order. Default is 3. @param[in] type Specify the ecvl::DataType to be used for the moments Image. It could be either DataType::float32 or DataType::float64. Default is DataType::float64. */ void CentralMoments(const Image& src, Image& moments, std::vector<double> center, int order = 3, DataType type = DataType::float64); /** @brief Draw an ellipse over the specified Image. @param[inout] src Image on which draw the ellipse. @param[in] center Center of the ellipse to be drawn. @param[in] axes Half of the size of the ellipse axes. @param[in] angle Ellipse rotation angle. It must be in degrees. @param[in] color Ellipse color. It can be either a number (e.g. {255}) or an RGB value (e.g. {40, 40, 40}) @param[in] thickness Thickness of the ellipse border. If negative all the pixell of the ellipse will be filled with the specified color value. Default is 1. */ void DrawEllipse(Image& src, ecvl::Point2i center, ecvl::Size2i axes, double angle, const ecvl::Scalar& color, int thickness = 1); /** @brief Remove color channel from the input Image. The DropColorChannel() procedure remove the color channel ("c") from the specified input Image, modifying all the other attribute accordingly. This function can be only applied on Images with ColorType::GRAY, <em>i.e.</em> images having the color channel dimension equal to 1. @param[inout] src Image from which to drop the color channel. */ void DropColorChannel(Image& src); /** @brief Normalize Image image with mean and standard deviation. The Normalize creates an Image in which each pixel of the Image is subtracted by mean and divide by std. Useful to normalize a dataset, in fact normalization helps to get the data within a range and which helps in making training of neural networks a lot faster. @param[in] src Image to normalize. @param[out] dst Output normalized Image. @param[in] mean Mean to use for normalization. @param[in] std Standard deviation to use for normalization. */ void Normalize(const Image& src, Image& dst, const double& mean, const double& std); /** @brief Normalize xyc Image image with separate mean and standard deviation for each color channel. The Normalize creates an Image in which each pixel of the input xyc Image is subtracted by the mean and divide by the std for its channel. Useful to normalize a dataset, in fact normalization helps to get the data within a range and which helps in making training of neural networks a lot faster. @param[in] src Image to normalize. @param[out] dst Output normalized Image. @param[in] mean Vector of means to use for normalization. @param[in] std Vector of standard deviations to use for normalization. */ void Normalize(const Image& src, Image& dst, const std::vector<double>& mean, const std::vector<double>& std); /** @brief Crops the given image at the center. The function crops Image src at the center and outputs the result in dst. @param[in] src The input Image. @param[out] dst The output resized Image. @param[in] size std::vector<int> specifies the desired output size of the crop. Must be in the order [w,h]. */ void CenterCrop(const ecvl::Image& src, ecvl::Image& dst, const std::vector<int>& size); /** @brief Linearly scale an Image into a new range. The function linearly rescale the Image having values in [min,max] into a new arbitrary range [new_min,new_max]. @param[in] src The input Image. @param[out] dst The output resized Image. @param[in] new_min double which indicates the new minimum value. @param[in] new_max double which indicates the new maximum value. */ void ScaleTo(const Image& src, Image& dst, const double& new_min, const double& new_max); /** @example example_moments.cpp This is an example application of the raw and central moments. */ /** @example example_imgproc.cpp Image processing examples. */ /** @example example_threshold.cpp This is an Otsu (single an multi-threshold) usage example. */ } // namespace ecvl #endif // ECVL_IMGPROC_H_
47.797704
210
0.735855
[ "vector" ]
35023d31c161c90867f643500ef329c221d7d700
127
h
C
graphics/glmInclude.h
Dawlau/GalleryArt-3D-OpenGL
3930aec73c5803d34ef857c0aae6de5360b75865
[ "MIT" ]
null
null
null
graphics/glmInclude.h
Dawlau/GalleryArt-3D-OpenGL
3930aec73c5803d34ef857c0aae6de5360b75865
[ "MIT" ]
null
null
null
graphics/glmInclude.h
Dawlau/GalleryArt-3D-OpenGL
3930aec73c5803d34ef857c0aae6de5360b75865
[ "MIT" ]
null
null
null
#include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "glm/gtx/transform.hpp" #include "glm/gtc/type_ptr.hpp"
31.75
39
0.76378
[ "transform" ]
3503f365871223eae5c496f774d06604b5e9b928
2,156
h
C
MT589/commandmodewindow.h
devborz/mt589-simulator
979c19d4efae09e95742a055bfd457b24772737d
[ "MIT" ]
null
null
null
MT589/commandmodewindow.h
devborz/mt589-simulator
979c19d4efae09e95742a055bfd457b24772737d
[ "MIT" ]
1
2021-12-11T04:43:42.000Z
2021-12-11T04:43:42.000Z
MT589/commandmodewindow.h
devborz/mt589-simulator
979c19d4efae09e95742a055bfd457b24772737d
[ "MIT" ]
null
null
null
#ifndef COMMANDMODEWINDOW_H #define COMMANDMODEWINDOW_H #include <QLCDNumber> #include <QMainWindow> #include <romwindow.h> #include <QTableWidgetItem> #include <emulator.hpp> #include <sstream> #include <mainwindow.h> #include <createisa.h> namespace Ui { class CommandModeWindow; } class CommandModeWindow : public QMainWindow { Q_OBJECT public: explicit CommandModeWindow(QWidget *parent = nullptr); ~CommandModeWindow(); MK589 mk; std::shared_ptr<MainWindow> mainWindow = nullptr; void prepareISAWindowText(); private slots: void on_open_rom_triggered(); void on_save_triggered(); void on_save_as_triggered(); void on_open_triggered(); void on_open_microcommand_mode_triggered(); void on_resetButton_clicked(); void on_stepButton_clicked(); void on_runButton_clicked(); void on_endButton_clicked(); void on_ramWidget_cellChanged(int row, int column); void update_on_cpu_data(); void setupRegs(); void changeCurrentRow(WORD oldRow, WORD newRow); void on_load_isa_triggered(); void on_load_rom_triggered(); void on_createISAButton_clicked(); void on_load_ram_triggered(); private: Ui::CommandModeWindow *ui; ROMWindow romWindow; CreateISA isaWindow; std::vector<std::shared_ptr<QLCDNumber>> regLCDs = {}; std::vector<std::shared_ptr<QTableWidgetItem>> items; std::string toHex(unsigned int value); unsigned int parseHex(const std::string& str); WORD parseCommand(const std::string& str); std::map<std::string, WORD> isa_commands = { {"INCA", 0x0100}, {"MOVA", 0x03}, {"ADDA", 0x02}, {"POP", 0x0500}, {"PUSH", 0x04}, {"IS", 0x0600}, {"INVA", 0x0700}, {"SHAR", 0x08}, {"SHAL", 0x09}, {"JMP", 0xA} }; std::map<std::string, std::string> isa_regs = { {"REG0", "PC"}, {"REG1", "SP"}, {"REG8", "A"}, }; WORD* PC; bool loaded = false; bool mkwrite = false; std::vector<QLabel*> reg_labels; std::string current_filename = ""; }; #endif // COMMANDMODEWINDOW_H
18.912281
58
0.646568
[ "vector" ]
35093b94342b476849482691abdcb4b4ae82a1d0
50,599
c
C
linux/drivers/char/mcfserial.c
CodeAsm/PS1Linux
8c3c4d9ffccf446dd061a38186efc924da8a66be
[ "CC0-1.0" ]
4
2020-01-01T20:26:42.000Z
2021-10-17T21:51:58.000Z
linux/drivers/char/mcfserial.c
CodeAsm/PS1Linux
8c3c4d9ffccf446dd061a38186efc924da8a66be
[ "CC0-1.0" ]
4
2020-07-23T11:20:30.000Z
2020-07-24T20:09:09.000Z
linux/drivers/char/mcfserial.c
CodeAsm/PS1Linux
8c3c4d9ffccf446dd061a38186efc924da8a66be
[ "CC0-1.0" ]
null
null
null
/* * mcfserial.c -- serial driver for ColdFire internal UARTS. * * Copyright (c) 1999-2001 Greg Ungerer <gerg@lineo.com> * Copyright (c) 2000-2001 Lineo, Inc. <www.lineo.com> * * Based on code from 68332serial.c which was: * * Copyright (C) 1995 David S. Miller (davem@caip.rutgers.edu) * Copyright (C) 1998 TSHG * Copyright (c) 1999 Rt-Control Inc. <jeff@uclinux.org> */ #include <linux/module.h> #include <linux/errno.h> #include <linux/signal.h> #include <linux/sched.h> #include <linux/timer.h> #include <linux/wait.h> #include <linux/interrupt.h> #include <linux/tty.h> #include <linux/tty_flip.h> #include <linux/config.h> #include <linux/major.h> #include <linux/string.h> #include <linux/fcntl.h> #include <linux/mm.h> #include <linux/kernel.h> #include <linux/serialP.h> #ifdef CONFIG_LEDMAN #include <linux/ledman.h> #endif #include <linux/console.h> #include <linux/version.h> #include <linux/init.h> #include <asm/io.h> #include <asm/irq.h> #include <asm/system.h> #include <asm/segment.h> #include <asm/semaphore.h> #include <asm/bitops.h> #include <asm/delay.h> #include <asm/coldfire.h> #include <asm/mcfsim.h> #include <asm/mcfuart.h> #include <asm/nettel.h> #if LINUX_VERSION_CODE < 0x020100 #define queue_task_irq_off queue_task #define copy_from_user(a,b,c) memcpy_fromfs(a,b,c) #define copy_to_user(a,b,c) memcpy_tofs(a,b,c) #else #include <asm/uaccess.h> #endif #include "mcfserial.h" /* * the only event we use */ #undef RS_EVENT_WRITE_WAKEUP #define RS_EVENT_WRITE_WAKEUP 0 #if LINUX_VERSION_CODE >= 0x020100 struct timer_list mcfrs_timer_struct; #endif /* * Default console baud rate, we use this as the default * for all ports so init can just open /dev/console and * keep going. Perhaps one day the cflag settings for the * console can be used instead. */ #if defined(CONFIG_M5272) #define CONSOLE_BAUD_RATE 19200 #define DEFAULT_CBAUD B19200 #endif #ifndef CONSOLE_BAUD_RATE #define CONSOLE_BAUD_RATE 9600 #define DEFAULT_CBAUD B9600 #endif int mcfrs_console_inited = 0; int mcfrs_console_port = -1; int mcfrs_console_baud = CONSOLE_BAUD_RATE; int mcfrs_console_cbaud = DEFAULT_CBAUD; DECLARE_TASK_QUEUE(mcf_tq_serial); /* * Driver data structures. */ struct tty_driver mcfrs_serial_driver, mcfrs_callout_driver; static int mcfrs_serial_refcount; /* serial subtype definitions */ #define SERIAL_TYPE_NORMAL 1 #define SERIAL_TYPE_CALLOUT 2 /* number of characters left in xmit buffer before we ask for more */ #define WAKEUP_CHARS 256 /* Debugging... */ #undef SERIAL_DEBUG_OPEN #undef SERIAL_DEBUG_FLOW #define _INLINE_ inline #define IRQBASE 73 /* * Configuration table, UARTs to look for at startup. */ static struct mcf_serial mcfrs_table[] = { { 0, (MCF_MBAR+MCFUART_BASE1), IRQBASE, ASYNC_BOOT_AUTOCONF }, /* ttyS0 */ { 0, (MCF_MBAR+MCFUART_BASE2), IRQBASE+1, ASYNC_BOOT_AUTOCONF }, /* ttyS1 */ }; #define NR_PORTS (sizeof(mcfrs_table) / sizeof(struct mcf_serial)) static struct tty_struct *mcfrs_serial_table[NR_PORTS]; static struct termios *mcfrs_serial_termios[NR_PORTS]; static struct termios *mcfrs_serial_termios_locked[NR_PORTS]; /* * This is used to figure out the divisor speeds and the timeouts. */ static int mcfrs_baud_table[] = { 0, 50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800, 9600, 19200, 38400, 57600, 115200, 230400, 460800, 0 }; #define MCFRS_BAUD_TABLE_SIZE \ (sizeof(mcfrs_baud_table)/sizeof(mcfrs_baud_table[0])) #ifndef MIN #define MIN(a,b) ((a) < (b) ? (a) : (b)) #endif #ifdef CONFIG_MAGIC_SYSRQ /* * Magic system request keys. Used for debugging... */ extern int magic_sysrq_key(int ch); #endif /* * tmp_buf is used as a temporary buffer by serial_write. We need to * lock it in case the copy_from_user blocks while swapping in a page, * and some other program tries to do a serial write at the same time. * Since the lock will only come under contention when the system is * swapping and available memory is low, it makes sense to share one * buffer across all the serial ports, since it significantly saves * memory if large numbers of serial ports are open. */ static unsigned char mcfrs_tmp_buf[4096]; /* This is cheating */ #if LINUX_VERSION_CODE < 0x020100 static struct semaphore mcfrs_tmp_buf_sem = MUTEX; #else static DECLARE_MUTEX(mcfrs_tmp_buf_sem); #endif /* * Forware declarations... */ static void mcfrs_change_speed(struct mcf_serial *info); static inline int serial_paranoia_check(struct mcf_serial *info, dev_t device, const char *routine) { #ifdef SERIAL_PARANOIA_CHECK static const char *badmagic = "Warning: bad magic number for serial struct (%d, %d) in %s\n"; static const char *badinfo = "Warning: null mcf_serial for (%d, %d) in %s\n"; if (!info) { printk(badinfo, MAJOR(device), MINOR(device), routine); return 1; } if (info->magic != SERIAL_MAGIC) { printk(badmagic, MAJOR(device), MINOR(device), routine); return 1; } #endif return 0; } /* * Sets or clears DTR and RTS on the requested line. */ static void mcfrs_setsignals(struct mcf_serial *info, int dtr, int rts) { volatile unsigned char *uartp; unsigned long flags; #if 0 printk("%s(%d): mcfrs_setsignals(info=%x,dtr=%d,rts=%d)\n", __FILE__, __LINE__, info, dtr, rts); #endif save_flags(flags); cli(); if (dtr >= 0) { #if defined(CONFIG_NETtel) && defined(CONFIG_M5307) if (dtr) { info->sigs |= TIOCM_DTR; ppdata &= ~(info->line ? NETtel_DTR1 : NETtel_DTR0); } else { info->sigs &= ~TIOCM_DTR; ppdata |= (info->line ? NETtel_DTR1 : NETtel_DTR0); } *((volatile unsigned short *) (MCF_MBAR+MCFSIM_PADAT)) = ppdata; #endif } if (rts >= 0) { uartp = (volatile unsigned char *) info->addr; if (rts) { info->sigs |= TIOCM_RTS; uartp[MCFUART_UOP1] = MCFUART_UOP_RTS; } else { info->sigs &= ~TIOCM_RTS; uartp[MCFUART_UOP0] = MCFUART_UOP_RTS; } } restore_flags(flags); return; } /* * Gets values of serial signals. */ static int mcfrs_getsignals(struct mcf_serial *info) { volatile unsigned char *uartp; unsigned long flags; int sigs; #if defined(CONFIG_NETtel) && defined(CONFIG_M5307) unsigned short ppdata; #endif #if 0 printk("%s(%d): mcfrs_getsignals(info=%x)\n", __FILE__, __LINE__); #endif save_flags(flags); cli(); uartp = (volatile unsigned char *) info->addr; sigs = (uartp[MCFUART_UIPR] & MCFUART_UIPR_CTS) ? 0 : TIOCM_CTS; sigs |= (info->sigs & TIOCM_RTS); #if defined(CONFIG_NETtel) && defined(CONFIG_M5307) ppdata = *((volatile unsigned short *) (MCF_MBAR+MCFSIM_PADAT)); if (info->line == 0) { sigs |= (ppdata & NETtel_DCD0) ? 0 : TIOCM_CD; sigs |= (ppdata & NETtel_DTR0) ? 0 : TIOCM_DTR; } else if (info->line == 1) { sigs |= (ppdata & NETtel_DCD1) ? 0 : TIOCM_CD; sigs |= (ppdata & NETtel_DTR1) ? 0 : TIOCM_DTR; } #endif restore_flags(flags); return(sigs); } /* * ------------------------------------------------------------ * mcfrs_stop() and mcfrs_start() * * This routines are called before setting or resetting tty->stopped. * They enable or disable transmitter interrupts, as necessary. * ------------------------------------------------------------ */ static void mcfrs_stop(struct tty_struct *tty) { volatile unsigned char *uartp; struct mcf_serial *info = (struct mcf_serial *)tty->driver_data; unsigned long flags; if (serial_paranoia_check(info, tty->device, "mcfrs_stop")) return; save_flags(flags); cli(); uartp = (volatile unsigned char *) info->addr; info->imr &= ~MCFUART_UIR_TXREADY; uartp[MCFUART_UIMR] = info->imr; restore_flags(flags); } static void mcfrs_start(struct tty_struct *tty) { volatile unsigned char *uartp; struct mcf_serial *info = (struct mcf_serial *)tty->driver_data; unsigned long flags; if (serial_paranoia_check(info, tty->device, "mcfrs_start")) return; save_flags(flags); cli(); if (info->xmit_cnt && info->xmit_buf) { uartp = (volatile unsigned char *) info->addr; info->imr |= MCFUART_UIR_TXREADY; uartp[MCFUART_UIMR] = info->imr; } restore_flags(flags); } /* * ---------------------------------------------------------------------- * * Here starts the interrupt handling routines. All of the following * subroutines are declared as inline and are folded into * mcfrs_interrupt(). They were separated out for readability's sake. * * Note: mcfrs_interrupt() is a "fast" interrupt, which means that it * runs with interrupts turned off. People who may want to modify * mcfrs_interrupt() should try to keep the interrupt handler as fast as * possible. After you are done making modifications, it is not a bad * idea to do: * * gcc -S -DKERNEL -Wall -Wstrict-prototypes -O6 -fomit-frame-pointer serial.c * * and look at the resulting assemble code in serial.s. * * - Ted Ts'o (tytso@mit.edu), 7-Mar-93 * ----------------------------------------------------------------------- */ /* * This routine is used by the interrupt handler to schedule * processing in the software interrupt portion of the driver. */ static _INLINE_ void mcfrs_sched_event(struct mcf_serial *info, int event) { info->event |= 1 << event; queue_task(&info->tqueue, &mcf_tq_serial); mark_bh(CM206_BH); } static _INLINE_ void receive_chars(struct mcf_serial *info, struct pt_regs *regs, unsigned short rx) { volatile unsigned char *uartp; struct tty_struct *tty = info->tty; unsigned char status, ch; if (!tty) return; #if defined(CONFIG_LEDMAN) ledman_cmd(LEDMAN_CMD_SET, info->line ? LEDMAN_COM2_RX : LEDMAN_COM1_RX); #endif uartp = (volatile unsigned char *) info->addr; while ((status = uartp[MCFUART_USR]) & MCFUART_USR_RXREADY) { if (tty->flip.count >= TTY_FLIPBUF_SIZE) break; ch = uartp[MCFUART_URB]; info->stats.rx++; #ifdef CONFIG_MAGIC_SYSRQ if (mcfrs_console_inited && (info->line == mcfrs_console_port)) { if (magic_sysrq_key(ch)) continue; } #endif tty->flip.count++; if (status & MCFUART_USR_RXERR) uartp[MCFUART_UCR] = MCFUART_UCR_CMDRESETERR; if (status & MCFUART_USR_RXBREAK) { info->stats.rxbreak++; *tty->flip.flag_buf_ptr++ = TTY_BREAK; } else if (status & MCFUART_USR_RXPARITY) { info->stats.rxparity++; *tty->flip.flag_buf_ptr++ = TTY_PARITY; } else if (status & MCFUART_USR_RXOVERRUN) { info->stats.rxoverrun++; *tty->flip.flag_buf_ptr++ = TTY_OVERRUN; } else if (status & MCFUART_USR_RXFRAMING) { info->stats.rxframing++; *tty->flip.flag_buf_ptr++ = TTY_FRAME; } else { *tty->flip.flag_buf_ptr++ = 0; } *tty->flip.char_buf_ptr++ = ch; } queue_task(&tty->flip.tqueue, &tq_timer); return; } static _INLINE_ void transmit_chars(struct mcf_serial *info) { volatile unsigned char *uartp; #if defined(CONFIG_LEDMAN) ledman_cmd(LEDMAN_CMD_SET, info->line ? LEDMAN_COM2_TX : LEDMAN_COM1_TX); #endif uartp = (volatile unsigned char *) info->addr; if (info->x_char) { /* Send special char - probably flow control */ uartp[MCFUART_UTB] = info->x_char; info->x_char = 0; info->stats.tx++; } if ((info->xmit_cnt <= 0) || info->tty->stopped) { info->imr &= ~MCFUART_UIR_TXREADY; uartp[MCFUART_UIMR] = info->imr; return; } while (uartp[MCFUART_USR] & MCFUART_USR_TXREADY) { uartp[MCFUART_UTB] = info->xmit_buf[info->xmit_tail++]; info->xmit_tail = info->xmit_tail & (SERIAL_XMIT_SIZE-1); info->stats.tx++; if (--info->xmit_cnt <= 0) break; } if (info->xmit_cnt < WAKEUP_CHARS) mcfrs_sched_event(info, RS_EVENT_WRITE_WAKEUP); return; } /* * This is the serial driver's generic interrupt routine */ void mcfrs_interrupt(int irq, void *dev_id, struct pt_regs *regs) { struct mcf_serial *info; unsigned char isr; info = &mcfrs_table[(irq - IRQBASE)]; isr = (((volatile unsigned char *)info->addr)[MCFUART_UISR]) & info->imr; if (isr & MCFUART_UIR_RXREADY) receive_chars(info, regs, isr); if (isr & MCFUART_UIR_TXREADY) transmit_chars(info); #if 0 if (isr & MCFUART_UIR_DELTABREAK) { printk("%s(%d): delta break!\n", __FILE__, __LINE__); receive_chars(info, regs, isr); } #endif return; } /* * ------------------------------------------------------------------- * Here ends the serial interrupt routines. * ------------------------------------------------------------------- */ /* * This routine is used to handle the "bottom half" processing for the * serial driver, known also the "software interrupt" processing. * This processing is done at the kernel interrupt level, after the * mcfrs_interrupt() has returned, BUT WITH INTERRUPTS TURNED ON. This * is where time-consuming activities which can not be done in the * interrupt driver proper are done; the interrupt driver schedules * them using mcfrs_sched_event(), and they get done here. */ static void do_serial_bh(void) { run_task_queue(&mcf_tq_serial); } static void do_softint(void *private_) { struct mcf_serial *info = (struct mcf_serial *) private_; struct tty_struct *tty; tty = info->tty; if (!tty) return; if (test_and_clear_bit(RS_EVENT_WRITE_WAKEUP, &info->event)) { if ((tty->flags & (1 << TTY_DO_WRITE_WAKEUP)) && tty->ldisc.write_wakeup) (tty->ldisc.write_wakeup)(tty); wake_up_interruptible(&tty->write_wait); } } /* * Change of state on a DCD line. */ void mcfrs_modem_change(struct mcf_serial *info, int dcd) { if (info->count == 0) return; if (info->flags & ASYNC_CHECK_CD) { if (dcd) { wake_up_interruptible(&info->open_wait); } else if (!((info->flags & ASYNC_CALLOUT_ACTIVE) && (info->flags & ASYNC_CALLOUT_NOHUP))) { schedule_task(&info->tqueue_hangup); } } } #if defined(CONFIG_NETtel) && defined(CONFIG_M5307) unsigned short mcfrs_ppstatus; /* * This subroutine is called when the RS_TIMER goes off. It is used * to monitor the state of the DCD lines - since they have no edge * sensors and interrupt generators. */ static void mcfrs_timer(unsigned long arg) { unsigned short ppstatus, dcdval; int i; ppstatus = *((volatile unsigned short *) (MCF_MBAR + MCFSIM_PADAT)) & (NETtel_DCD0 | NETtel_DCD1); if (ppstatus != mcfrs_ppstatus) { for (i = 0; (i < 2); i++) { dcdval = (i ? NETtel_DCD1 : NETtel_DCD0); if ((ppstatus & dcdval) != (mcfrs_ppstatus & dcdval)) { mcfrs_modem_change(&mcfrs_table[i], ((ppstatus & dcdval) ? 0 : 1)); } } } mcfrs_ppstatus = ppstatus; #if LINUX_VERSION_CODE < 0x020100 /* Re-arm timer */ timer_table[RS_TIMER].expires = jiffies + HZ/25; timer_active |= 1 << RS_TIMER; #else mcfrs_timer_struct.expires = jiffies + HZ/25; add_timer(&mcfrs_timer_struct); #endif } #endif /* CONFIG_NETtel */ /* * This routine is called from the scheduler tqueue when the interrupt * routine has signalled that a hangup has occurred. The path of * hangup processing is: * * serial interrupt routine -> (scheduler tqueue) -> * do_serial_hangup() -> tty->hangup() -> mcfrs_hangup() * */ static void do_serial_hangup(void *private_) { struct mcf_serial *info = (struct mcf_serial *) private_; struct tty_struct *tty; tty = info->tty; if (!tty) return; tty_hangup(tty); } static int startup(struct mcf_serial * info) { volatile unsigned char *uartp; unsigned long flags; if (info->flags & ASYNC_INITIALIZED) return 0; if (!info->xmit_buf) { info->xmit_buf = (unsigned char *) get_free_page(GFP_KERNEL); if (!info->xmit_buf) return -ENOMEM; } save_flags(flags); cli(); #if defined(CONFIG_NETtel) && defined(CONFIG_M5307) /* * Set up poll timer. It is used to check DCD status. */ #if LINUX_VERSION_CODE < 0x020100 if ((timer_active & (1 << RS_TIMER)) == 0) { timer_table[RS_TIMER].expires = jiffies + HZ/25; timer_active |= 1 << RS_TIMER; } #endif #endif #ifdef SERIAL_DEBUG_OPEN printk("starting up ttyS%d (irq %d)...\n", info->line, info->irq); #endif /* * Reset UART, get it into known state... */ uartp = (volatile unsigned char *) info->addr; uartp[MCFUART_UCR] = MCFUART_UCR_CMDRESETRX; /* reset RX */ uartp[MCFUART_UCR] = MCFUART_UCR_CMDRESETTX; /* reset TX */ mcfrs_setsignals(info, 1, 1); if (info->tty) clear_bit(TTY_IO_ERROR, &info->tty->flags); info->xmit_cnt = info->xmit_head = info->xmit_tail = 0; /* * and set the speed of the serial port */ mcfrs_change_speed(info); /* * Lastly enable the UART transmitter and receiver, and * interrupt enables. */ info->imr = MCFUART_UIR_RXREADY; uartp[MCFUART_UCR] = MCFUART_UCR_RXENABLE | MCFUART_UCR_TXENABLE; uartp[MCFUART_UIMR] = info->imr; info->flags |= ASYNC_INITIALIZED; restore_flags(flags); return 0; } /* * This routine will shutdown a serial port; interrupts are disabled, and * DTR is dropped if the hangup on close termio flag is on. */ static void shutdown(struct mcf_serial * info) { volatile unsigned char *uartp; unsigned long flags; if (!(info->flags & ASYNC_INITIALIZED)) return; #ifdef SERIAL_DEBUG_OPEN printk("Shutting down serial port %d (irq %d)....\n", info->line, info->irq); #endif save_flags(flags); cli(); /* Disable interrupts */ uartp = (volatile unsigned char *) info->addr; uartp[MCFUART_UIMR] = 0; /* mask all interrupts */ uartp[MCFUART_UCR] = MCFUART_UCR_CMDRESETRX; /* reset RX */ uartp[MCFUART_UCR] = MCFUART_UCR_CMDRESETTX; /* reset TX */ if (!info->tty || (info->tty->termios->c_cflag & HUPCL)) mcfrs_setsignals(info, 0, 0); if (info->xmit_buf) { free_page((unsigned long) info->xmit_buf); info->xmit_buf = 0; } if (info->tty) set_bit(TTY_IO_ERROR, &info->tty->flags); info->flags &= ~ASYNC_INITIALIZED; restore_flags(flags); } /* * This routine is called to set the UART divisor registers to match * the specified baud rate for a serial port. */ static void mcfrs_change_speed(struct mcf_serial *info) { volatile unsigned char *uartp; unsigned int baudclk, cflag; unsigned long flags; unsigned char mr1, mr2; int i; if (!info->tty || !info->tty->termios) return; cflag = info->tty->termios->c_cflag; if (info->addr == 0) return; #if 0 printk("%s(%d): mcfrs_change_speed()\n", __FILE__, __LINE__); #endif i = cflag & CBAUD; if (i & CBAUDEX) { i &= ~CBAUDEX; if (i < 1 || i > 4) info->tty->termios->c_cflag &= ~CBAUDEX; else i += 15; } if (i == 0) { mcfrs_setsignals(info, 0, -1); return; } baudclk = ((MCF_CLK / 32) / mcfrs_baud_table[i]); info->baud = mcfrs_baud_table[i]; mr1 = MCFUART_MR1_RXIRQRDY | MCFUART_MR1_RXERRCHAR; mr2 = 0; switch (cflag & CSIZE) { case CS5: mr1 |= MCFUART_MR1_CS5; break; case CS6: mr1 |= MCFUART_MR1_CS6; break; case CS7: mr1 |= MCFUART_MR1_CS7; break; case CS8: default: mr1 |= MCFUART_MR1_CS8; break; } if (cflag & PARENB) { if (cflag & PARODD) mr1 |= MCFUART_MR1_PARITYODD; else mr1 |= MCFUART_MR1_PARITYEVEN; } else { mr1 |= MCFUART_MR1_PARITYNONE; } if (cflag & CSTOPB) mr2 |= MCFUART_MR2_STOP2; else mr2 |= MCFUART_MR2_STOP1; if (cflag & CRTSCTS) { mr1 |= MCFUART_MR1_RXRTS; mr2 |= MCFUART_MR2_TXCTS; } if (cflag & CLOCAL) info->flags &= ~ASYNC_CHECK_CD; else info->flags |= ASYNC_CHECK_CD; uartp = (volatile unsigned char *) info->addr; save_flags(flags); cli(); #if 0 printk("%s(%d): mr1=%x mr2=%x baudclk=%x\n", __FILE__, __LINE__, mr1, mr2, baudclk); #endif /* Note: pg 12-16 of MCF5206e User's Manual states that a software reset should be performed prior to changing UMR1,2, UCSR, UACR, bit 7 */ uartp[MCFUART_UCR] = MCFUART_UCR_CMDRESETRX; /* reset RX */ uartp[MCFUART_UCR] = MCFUART_UCR_CMDRESETTX; /* reset TX */ uartp[MCFUART_UCR] = MCFUART_UCR_CMDRESETMRPTR; /* reset MR pointer */ uartp[MCFUART_UMR] = mr1; uartp[MCFUART_UMR] = mr2; uartp[MCFUART_UBG1] = (baudclk & 0xff00) >> 8; /* set msb byte */ uartp[MCFUART_UBG2] = (baudclk & 0xff); /* set lsb byte */ uartp[MCFUART_UCSR] = MCFUART_UCSR_RXCLKTIMER | MCFUART_UCSR_TXCLKTIMER; uartp[MCFUART_UCR] = MCFUART_UCR_RXENABLE | MCFUART_UCR_TXENABLE; mcfrs_setsignals(info, 1, -1); restore_flags(flags); return; } static void mcfrs_flush_chars(struct tty_struct *tty) { volatile unsigned char *uartp; struct mcf_serial *info = (struct mcf_serial *)tty->driver_data; unsigned long flags; if (serial_paranoia_check(info, tty->device, "mcfrs_flush_chars")) return; if (info->xmit_cnt <= 0 || tty->stopped || tty->hw_stopped || !info->xmit_buf) return; /* Enable transmitter */ save_flags(flags); cli(); uartp = (volatile unsigned char *) info->addr; info->imr |= MCFUART_UIR_TXREADY; uartp[MCFUART_UIMR] = info->imr; restore_flags(flags); } static int mcfrs_write(struct tty_struct * tty, int from_user, const unsigned char *buf, int count) { volatile unsigned char *uartp; struct mcf_serial *info = (struct mcf_serial *)tty->driver_data; unsigned long flags; int c, total = 0; #if 0 printk("%s(%d): mcfrs_write(tty=%x,from_user=%d,buf=%x,count=%d)\n", __FILE__, __LINE__, tty, from_user, buf, count); #endif if (serial_paranoia_check(info, tty->device, "mcfrs_write")) return 0; if (!tty || !info->xmit_buf) return 0; save_flags(flags); while (1) { cli(); c = MIN(count, MIN(SERIAL_XMIT_SIZE - info->xmit_cnt - 1, SERIAL_XMIT_SIZE - info->xmit_head)); if (c <= 0) { restore_flags(flags); break; } if (from_user) { down(&mcfrs_tmp_buf_sem); copy_from_user(mcfrs_tmp_buf, buf, c); restore_flags(flags); cli(); c = MIN(c, MIN(SERIAL_XMIT_SIZE - info->xmit_cnt - 1, SERIAL_XMIT_SIZE - info->xmit_head)); memcpy(info->xmit_buf + info->xmit_head, mcfrs_tmp_buf, c); up(&mcfrs_tmp_buf_sem); } else memcpy(info->xmit_buf + info->xmit_head, buf, c); info->xmit_head = (info->xmit_head + c) & (SERIAL_XMIT_SIZE-1); info->xmit_cnt += c; restore_flags(flags); buf += c; count -= c; total += c; } cli(); uartp = (volatile unsigned char *) info->addr; info->imr |= MCFUART_UIR_TXREADY; uartp[MCFUART_UIMR] = info->imr; restore_flags(flags); return total; } static int mcfrs_write_room(struct tty_struct *tty) { struct mcf_serial *info = (struct mcf_serial *)tty->driver_data; int ret; if (serial_paranoia_check(info, tty->device, "mcfrs_write_room")) return 0; ret = SERIAL_XMIT_SIZE - info->xmit_cnt - 1; if (ret < 0) ret = 0; return ret; } static int mcfrs_chars_in_buffer(struct tty_struct *tty) { struct mcf_serial *info = (struct mcf_serial *)tty->driver_data; if (serial_paranoia_check(info, tty->device, "mcfrs_chars_in_buffer")) return 0; return info->xmit_cnt; } static void mcfrs_flush_buffer(struct tty_struct *tty) { struct mcf_serial *info = (struct mcf_serial *)tty->driver_data; unsigned long flags; if (serial_paranoia_check(info, tty->device, "mcfrs_flush_buffer")) return; save_flags(flags); cli(); info->xmit_cnt = info->xmit_head = info->xmit_tail = 0; restore_flags(flags); wake_up_interruptible(&tty->write_wait); if ((tty->flags & (1 << TTY_DO_WRITE_WAKEUP)) && tty->ldisc.write_wakeup) (tty->ldisc.write_wakeup)(tty); } /* * ------------------------------------------------------------ * mcfrs_throttle() * * This routine is called by the upper-layer tty layer to signal that * incoming characters should be throttled. * ------------------------------------------------------------ */ static void mcfrs_throttle(struct tty_struct * tty) { struct mcf_serial *info = (struct mcf_serial *)tty->driver_data; #ifdef SERIAL_DEBUG_THROTTLE char buf[64]; printk("throttle %s: %d....\n", _tty_name(tty, buf), tty->ldisc.chars_in_buffer(tty)); #endif if (serial_paranoia_check(info, tty->device, "mcfrs_throttle")) return; if (I_IXOFF(tty)) info->x_char = STOP_CHAR(tty); /* Turn off RTS line (do this atomic) */ } static void mcfrs_unthrottle(struct tty_struct * tty) { struct mcf_serial *info = (struct mcf_serial *)tty->driver_data; #ifdef SERIAL_DEBUG_THROTTLE char buf[64]; printk("unthrottle %s: %d....\n", _tty_name(tty, buf), tty->ldisc.chars_in_buffer(tty)); #endif if (serial_paranoia_check(info, tty->device, "mcfrs_unthrottle")) return; if (I_IXOFF(tty)) { if (info->x_char) info->x_char = 0; else info->x_char = START_CHAR(tty); } /* Assert RTS line (do this atomic) */ } /* * ------------------------------------------------------------ * mcfrs_ioctl() and friends * ------------------------------------------------------------ */ static int get_serial_info(struct mcf_serial * info, struct serial_struct * retinfo) { struct serial_struct tmp; if (!retinfo) return -EFAULT; memset(&tmp, 0, sizeof(tmp)); tmp.type = info->type; tmp.line = info->line; tmp.port = info->addr; tmp.irq = info->irq; tmp.flags = info->flags; tmp.baud_base = info->baud_base; tmp.close_delay = info->close_delay; tmp.closing_wait = info->closing_wait; tmp.custom_divisor = info->custom_divisor; copy_to_user(retinfo,&tmp,sizeof(*retinfo)); return 0; } static int set_serial_info(struct mcf_serial * info, struct serial_struct * new_info) { struct serial_struct new_serial; struct mcf_serial old_info; int retval = 0; if (!new_info) return -EFAULT; copy_from_user(&new_serial,new_info,sizeof(new_serial)); old_info = *info; if (!suser()) { if ((new_serial.baud_base != info->baud_base) || (new_serial.type != info->type) || (new_serial.close_delay != info->close_delay) || ((new_serial.flags & ~ASYNC_USR_MASK) != (info->flags & ~ASYNC_USR_MASK))) return -EPERM; info->flags = ((info->flags & ~ASYNC_USR_MASK) | (new_serial.flags & ASYNC_USR_MASK)); info->custom_divisor = new_serial.custom_divisor; goto check_and_exit; } if (info->count > 1) return -EBUSY; /* * OK, past this point, all the error checking has been done. * At this point, we start making changes..... */ info->baud_base = new_serial.baud_base; info->flags = ((info->flags & ~ASYNC_FLAGS) | (new_serial.flags & ASYNC_FLAGS)); info->type = new_serial.type; info->close_delay = new_serial.close_delay; info->closing_wait = new_serial.closing_wait; check_and_exit: retval = startup(info); return retval; } /* * get_lsr_info - get line status register info * * Purpose: Let user call ioctl() to get info when the UART physically * is emptied. On bus types like RS485, the transmitter must * release the bus after transmitting. This must be done when * the transmit shift register is empty, not be done when the * transmit holding register is empty. This functionality * allows an RS485 driver to be written in user space. */ static int get_lsr_info(struct mcf_serial * info, unsigned int *value) { volatile unsigned char *uartp; unsigned long flags; unsigned char status; save_flags(flags); cli(); uartp = (volatile unsigned char *) info->addr; status = (uartp[MCFUART_USR] & MCFUART_USR_TXEMPTY) ? TIOCSER_TEMT : 0; restore_flags(flags); put_user(status,value); return 0; } /* * This routine sends a break character out the serial port. */ static void send_break( struct mcf_serial * info, int duration) { volatile unsigned char *uartp; unsigned long flags; if (!info->addr) return; current->state = TASK_INTERRUPTIBLE; #if LINUX_VERSION_CODE < 0x020100 current->timeout = jiffies + duration; #endif uartp = (volatile unsigned char *) info->addr; save_flags(flags); cli(); uartp[MCFUART_UCR] = MCFUART_UCR_CMDBREAKSTART; #if LINUX_VERSION_CODE < 0x020100 schedule(); #else schedule_timeout(jiffies + duration); #endif uartp[MCFUART_UCR] = MCFUART_UCR_CMDBREAKSTOP; restore_flags(flags); } static int mcfrs_ioctl(struct tty_struct *tty, struct file * file, unsigned int cmd, unsigned long arg) { struct mcf_serial * info = (struct mcf_serial *)tty->driver_data; unsigned int val; int retval, error; int dtr, rts; if (serial_paranoia_check(info, tty->device, "mcfrs_ioctl")) return -ENODEV; if ((cmd != TIOCGSERIAL) && (cmd != TIOCSSERIAL) && (cmd != TIOCSERCONFIG) && (cmd != TIOCSERGWILD) && (cmd != TIOCSERSWILD) && (cmd != TIOCSERGSTRUCT)) { if (tty->flags & (1 << TTY_IO_ERROR)) return -EIO; } switch (cmd) { case TCSBRK: /* SVID version: non-zero arg --> no break */ retval = tty_check_change(tty); if (retval) return retval; tty_wait_until_sent(tty, 0); if (!arg) send_break(info, HZ/4); /* 1/4 second */ return 0; case TCSBRKP: /* support for POSIX tcsendbreak() */ retval = tty_check_change(tty); if (retval) return retval; tty_wait_until_sent(tty, 0); send_break(info, arg ? arg*(HZ/10) : HZ/4); return 0; case TIOCGSOFTCAR: error = verify_area(VERIFY_WRITE, (void *) arg,sizeof(long)); if (error) return error; put_user(C_CLOCAL(tty) ? 1 : 0, (unsigned long *) arg); return 0; case TIOCSSOFTCAR: get_user(arg, (unsigned long *) arg); tty->termios->c_cflag = ((tty->termios->c_cflag & ~CLOCAL) | (arg ? CLOCAL : 0)); return 0; case TIOCGSERIAL: error = verify_area(VERIFY_WRITE, (void *) arg, sizeof(struct serial_struct)); if (error) return error; return get_serial_info(info, (struct serial_struct *) arg); case TIOCSSERIAL: return set_serial_info(info, (struct serial_struct *) arg); case TIOCSERGETLSR: /* Get line status register */ error = verify_area(VERIFY_WRITE, (void *) arg, sizeof(unsigned int)); if (error) return error; else return get_lsr_info(info, (unsigned int *) arg); case TIOCSERGSTRUCT: error = verify_area(VERIFY_WRITE, (void *) arg, sizeof(struct mcf_serial)); if (error) return error; copy_to_user((struct mcf_serial *) arg, info, sizeof(struct mcf_serial)); return 0; case TIOCMGET: if ((error = verify_area(VERIFY_WRITE, (void *) arg, sizeof(unsigned int)))) return(error); val = mcfrs_getsignals(info); put_user(val, (unsigned int *) arg); break; case TIOCMBIS: if ((error = verify_area(VERIFY_WRITE, (void *) arg, sizeof(unsigned int)))) return(error); #if LINUX_VERSION_CODE < 0x020100 val = get_user((unsigned int *) arg); #else get_user(val, (unsigned int *) arg); #endif rts = (val & TIOCM_RTS) ? 1 : -1; dtr = (val & TIOCM_DTR) ? 1 : -1; mcfrs_setsignals(info, dtr, rts); break; case TIOCMBIC: if ((error = verify_area(VERIFY_WRITE, (void *) arg, sizeof(unsigned int)))) return(error); #if LINUX_VERSION_CODE < 0x020100 val = get_user((unsigned int *) arg); #else get_user(val, (unsigned int *) arg); #endif rts = (val & TIOCM_RTS) ? 0 : -1; dtr = (val & TIOCM_DTR) ? 0 : -1; mcfrs_setsignals(info, dtr, rts); break; case TIOCMSET: if ((error = verify_area(VERIFY_WRITE, (void *) arg, sizeof(unsigned int)))) return(error); #if LINUX_VERSION_CODE < 0x020100 val = get_user((unsigned int *) arg); #else get_user(val, (unsigned int *) arg); #endif rts = (val & TIOCM_RTS) ? 1 : 0; dtr = (val & TIOCM_DTR) ? 1 : 0; mcfrs_setsignals(info, dtr, rts); break; default: return -ENOIOCTLCMD; } return 0; } static void mcfrs_set_termios(struct tty_struct *tty, struct termios *old_termios) { struct mcf_serial *info = (struct mcf_serial *)tty->driver_data; if (tty->termios->c_cflag == old_termios->c_cflag) return; mcfrs_change_speed(info); if ((old_termios->c_cflag & CRTSCTS) && !(tty->termios->c_cflag & CRTSCTS)) { tty->hw_stopped = 0; mcfrs_setsignals(info, -1, 1); #if 0 mcfrs_start(tty); #endif } } /* * ------------------------------------------------------------ * mcfrs_close() * * This routine is called when the serial port gets closed. First, we * wait for the last remaining data to be sent. Then, we unlink its * S structure from the interrupt chain if necessary, and we free * that IRQ if nothing is left in the chain. * ------------------------------------------------------------ */ static void mcfrs_close(struct tty_struct *tty, struct file * filp) { volatile unsigned char *uartp; struct mcf_serial *info = (struct mcf_serial *)tty->driver_data; unsigned long flags; if (!info || serial_paranoia_check(info, tty->device, "mcfrs_close")) return; save_flags(flags); cli(); if (tty_hung_up_p(filp)) { restore_flags(flags); return; } #ifdef SERIAL_DEBUG_OPEN printk("mcfrs_close ttyS%d, count = %d\n", info->line, info->count); #endif if ((tty->count == 1) && (info->count != 1)) { /* * Uh, oh. tty->count is 1, which means that the tty * structure will be freed. Info->count should always * be one in these conditions. If it's greater than * one, we've got real problems, since it means the * serial port won't be shutdown. */ printk("mcfrs_close: bad serial port count; tty->count is 1, " "info->count is %d\n", info->count); info->count = 1; } if (--info->count < 0) { printk("mcfrs_close: bad serial port count for ttyS%d: %d\n", info->line, info->count); info->count = 0; } if (info->count) { restore_flags(flags); return; } info->flags |= ASYNC_CLOSING; /* * Save the termios structure, since this port may have * separate termios for callout and dialin. */ if (info->flags & ASYNC_NORMAL_ACTIVE) info->normal_termios = *tty->termios; if (info->flags & ASYNC_CALLOUT_ACTIVE) info->callout_termios = *tty->termios; /* * Now we wait for the transmit buffer to clear; and we notify * the line discipline to only process XON/XOFF characters. */ tty->closing = 1; if (info->closing_wait != ASYNC_CLOSING_WAIT_NONE) tty_wait_until_sent(tty, info->closing_wait); /* * At this point we stop accepting input. To do this, we * disable the receive line status interrupts, and tell the * interrupt driver to stop checking the data ready bit in the * line status register. */ info->imr &= ~MCFUART_UIR_RXREADY; uartp = (volatile unsigned char *) info->addr; uartp[MCFUART_UIMR] = info->imr; #if 0 /* FIXME: do we need to keep this enabled for console?? */ if (mcfrs_console_inited && (mcfrs_console_port == info->line)) { /* Do not disable the UART */ ; } else #endif shutdown(info); if (tty->driver.flush_buffer) tty->driver.flush_buffer(tty); if (tty->ldisc.flush_buffer) tty->ldisc.flush_buffer(tty); tty->closing = 0; info->event = 0; info->tty = 0; if (tty->ldisc.num != ldiscs[N_TTY].num) { if (tty->ldisc.close) (tty->ldisc.close)(tty); tty->ldisc = ldiscs[N_TTY]; tty->termios->c_line = N_TTY; if (tty->ldisc.open) (tty->ldisc.open)(tty); } if (info->blocked_open) { if (info->close_delay) { current->state = TASK_INTERRUPTIBLE; #if LINUX_VERSION_CODE < 0x020100 current->timeout = jiffies + info->close_delay; schedule(); #else schedule_timeout(info->close_delay); #endif } wake_up_interruptible(&info->open_wait); } info->flags &= ~(ASYNC_NORMAL_ACTIVE|ASYNC_CALLOUT_ACTIVE| ASYNC_CLOSING); wake_up_interruptible(&info->close_wait); restore_flags(flags); } /* * mcfrs_hangup() --- called by tty_hangup() when a hangup is signaled. */ void mcfrs_hangup(struct tty_struct *tty) { struct mcf_serial * info = (struct mcf_serial *)tty->driver_data; if (serial_paranoia_check(info, tty->device, "mcfrs_hangup")) return; mcfrs_flush_buffer(tty); shutdown(info); info->event = 0; info->count = 0; info->flags &= ~(ASYNC_NORMAL_ACTIVE|ASYNC_CALLOUT_ACTIVE); info->tty = 0; wake_up_interruptible(&info->open_wait); } /* * ------------------------------------------------------------ * mcfrs_open() and friends * ------------------------------------------------------------ */ static int block_til_ready(struct tty_struct *tty, struct file * filp, struct mcf_serial *info) { #if LINUX_VERSION_CODE < 0x020100 struct wait_queue wait = { current, NULL }; #else DECLARE_WAITQUEUE(wait, current); #endif int retval; int do_clocal = 0; /* * If the device is in the middle of being closed, then block * until it's done, and then try again. */ if (info->flags & ASYNC_CLOSING) { interruptible_sleep_on(&info->close_wait); #ifdef SERIAL_DO_RESTART if (info->flags & ASYNC_HUP_NOTIFY) return -EAGAIN; else return -ERESTARTSYS; #else return -EAGAIN; #endif } /* * If this is a callout device, then just make sure the normal * device isn't being used. */ if (tty->driver.subtype == SERIAL_TYPE_CALLOUT) { if (info->flags & ASYNC_NORMAL_ACTIVE) return -EBUSY; if ((info->flags & ASYNC_CALLOUT_ACTIVE) && (info->flags & ASYNC_SESSION_LOCKOUT) && (info->session != current->session)) return -EBUSY; if ((info->flags & ASYNC_CALLOUT_ACTIVE) && (info->flags & ASYNC_PGRP_LOCKOUT) && (info->pgrp != current->pgrp)) return -EBUSY; info->flags |= ASYNC_CALLOUT_ACTIVE; return 0; } /* * If non-blocking mode is set, or the port is not enabled, * then make the check up front and then exit. */ if ((filp->f_flags & O_NONBLOCK) || (tty->flags & (1 << TTY_IO_ERROR))) { if (info->flags & ASYNC_CALLOUT_ACTIVE) return -EBUSY; info->flags |= ASYNC_NORMAL_ACTIVE; return 0; } if (info->flags & ASYNC_CALLOUT_ACTIVE) { if (info->normal_termios.c_cflag & CLOCAL) do_clocal = 1; } else { if (tty->termios->c_cflag & CLOCAL) do_clocal = 1; } /* * Block waiting for the carrier detect and the line to become * free (i.e., not in use by the callout). While we are in * this loop, info->count is dropped by one, so that * mcfrs_close() knows when to free things. We restore it upon * exit, either normal or abnormal. */ retval = 0; add_wait_queue(&info->open_wait, &wait); #ifdef SERIAL_DEBUG_OPEN printk("block_til_ready before block: ttyS%d, count = %d\n", info->line, info->count); #endif info->count--; info->blocked_open++; while (1) { cli(); if (!(info->flags & ASYNC_CALLOUT_ACTIVE)) mcfrs_setsignals(info, 1, 1); sti(); current->state = TASK_INTERRUPTIBLE; if (tty_hung_up_p(filp) || !(info->flags & ASYNC_INITIALIZED)) { #ifdef SERIAL_DO_RESTART if (info->flags & ASYNC_HUP_NOTIFY) retval = -EAGAIN; else retval = -ERESTARTSYS; #else retval = -EAGAIN; #endif break; } if (!(info->flags & ASYNC_CALLOUT_ACTIVE) && !(info->flags & ASYNC_CLOSING) && do_clocal) break; #if LINUX_VERSION_CODE < 0x020100 if (current->signal & ~current->blocked) { #else if (signal_pending(current)) { #endif retval = -ERESTARTSYS; break; } #ifdef SERIAL_DEBUG_OPEN printk("block_til_ready blocking: ttyS%d, count = %d\n", info->line, info->count); #endif schedule(); } current->state = TASK_RUNNING; remove_wait_queue(&info->open_wait, &wait); if (!tty_hung_up_p(filp)) info->count++; info->blocked_open--; #ifdef SERIAL_DEBUG_OPEN printk("block_til_ready after blocking: ttyS%d, count = %d\n", info->line, info->count); #endif if (retval) return retval; info->flags |= ASYNC_NORMAL_ACTIVE; return 0; } /* * This routine is called whenever a serial port is opened. It * enables interrupts for a serial port, linking in its structure into * the IRQ chain. It also performs the serial-specific * initialization for the tty structure. */ int mcfrs_open(struct tty_struct *tty, struct file * filp) { struct mcf_serial *info; int retval, line; line = MINOR(tty->device) - tty->driver.minor_start; if ((line < 0) || (line >= NR_PORTS)) return -ENODEV; info = mcfrs_table + line; if (serial_paranoia_check(info, tty->device, "mcfrs_open")) return -ENODEV; #ifdef SERIAL_DEBUG_OPEN printk("mcfrs_open %s%d, count = %d\n", tty->driver.name, info->line, info->count); #endif info->count++; tty->driver_data = info; info->tty = tty; /* * Start up serial port */ retval = startup(info); if (retval) return retval; retval = block_til_ready(tty, filp, info); if (retval) { #ifdef SERIAL_DEBUG_OPEN printk("mcfrs_open returning after block_til_ready with %d\n", retval); #endif return retval; } if ((info->count == 1) && (info->flags & ASYNC_SPLIT_TERMIOS)) { if (tty->driver.subtype == SERIAL_TYPE_NORMAL) *tty->termios = info->normal_termios; else *tty->termios = info->callout_termios; mcfrs_change_speed(info); } info->session = current->session; info->pgrp = current->pgrp; #ifdef SERIAL_DEBUG_OPEN printk("mcfrs_open ttyS%d successful...\n", info->line); #endif return 0; } /* * Based on the line number set up the internal interrupt stuff. */ static void mcfrs_irqinit(struct mcf_serial *info) { #ifdef CONFIG_M5272 volatile unsigned long *icrp; icrp = (volatile unsigned long *) (MCF_MBAR + MCFSIM_ICR2); switch (info->line) { case 0: *icrp = 0xe0000000; break; case 1: *icrp = 0x0e000000; break; default: printk("SERIAL: don't know how to handle UART %d interrupt?\n", info->line); return; } #else volatile unsigned char *icrp, *uartp; switch (info->line) { case 0: icrp = (volatile unsigned char *) (MCF_MBAR + MCFSIM_UART1ICR); *icrp = /*MCFSIM_ICR_AUTOVEC |*/ MCFSIM_ICR_LEVEL6 | MCFSIM_ICR_PRI1; mcf_setimr(mcf_getimr() & ~MCFSIM_IMR_UART1); break; case 1: icrp = (volatile unsigned char *) (MCF_MBAR + MCFSIM_UART2ICR); *icrp = /*MCFSIM_ICR_AUTOVEC |*/ MCFSIM_ICR_LEVEL6 | MCFSIM_ICR_PRI2; mcf_setimr(mcf_getimr() & ~MCFSIM_IMR_UART2); break; default: printk("SERIAL: don't know how to handle UART %d interrupt?\n", info->line); return; } uartp = (volatile unsigned char *) info->addr; uartp[MCFUART_UIVR] = info->irq; #endif if (request_irq(info->irq, mcfrs_interrupt, SA_INTERRUPT, "ColdFire UART", NULL)) { printk("SERIAL: Unable to attach ColdFire UART %d interrupt " "vector=%d\n", info->line, info->irq); } return; } char *mcfrs_drivername = "ColdFire internal UART serial driver version 1.00\n"; /* * Serial stats reporting... */ int mcfrs_readproc(char *buffer) { struct mcf_serial *info; char str[20]; int len, sigs, i; len = sprintf(buffer, mcfrs_drivername); for (i = 0; (i < NR_PORTS); i++) { info = &mcfrs_table[i]; len += sprintf((buffer + len), "%d: port:%x irq=%d baud:%d ", i, info->addr, info->irq, info->baud); if (info->stats.rx || info->stats.tx) len += sprintf((buffer + len), "tx:%d rx:%d ", info->stats.tx, info->stats.rx); if (info->stats.rxframing) len += sprintf((buffer + len), "fe:%d ", info->stats.rxframing); if (info->stats.rxparity) len += sprintf((buffer + len), "pe:%d ", info->stats.rxparity); if (info->stats.rxbreak) len += sprintf((buffer + len), "brk:%d ", info->stats.rxbreak); if (info->stats.rxoverrun) len += sprintf((buffer + len), "oe:%d ", info->stats.rxoverrun); str[0] = str[1] = 0; if ((sigs = mcfrs_getsignals(info))) { if (sigs & TIOCM_RTS) strcat(str, "|RTS"); if (sigs & TIOCM_CTS) strcat(str, "|CTS"); if (sigs & TIOCM_DTR) strcat(str, "|DTR"); if (sigs & TIOCM_CD) strcat(str, "|CD"); } len += sprintf((buffer + len), "%s\n", &str[1]); } return(len); } /* Finally, routines used to initialize the serial driver. */ static void show_serial_version(void) { printk(mcfrs_drivername); } /* mcfrs_init inits the driver */ static int __init mcfrs_init(void) { struct mcf_serial *info; unsigned long flags; int i; init_bh(CM206_BH, do_serial_bh); /* Setup base handler, and timer table. */ #if defined(CONFIG_NETtel) && defined(CONFIG_M5307) #if LINUX_VERSION_CODE < 0x020100 timer_table[RS_TIMER].fn = mcfrs_timer; timer_table[RS_TIMER].expires = 0; #else init_timer(&mcfrs_timer_struct); mcfrs_timer_struct.function = mcfrs_timer; mcfrs_timer_struct.data = 0; mcfrs_timer_struct.expires = jiffies + HZ/25; add_timer(&mcfrs_timer_struct); #endif #endif show_serial_version(); /* Initialize the tty_driver structure */ memset(&mcfrs_serial_driver, 0, sizeof(struct tty_driver)); mcfrs_serial_driver.magic = TTY_DRIVER_MAGIC; mcfrs_serial_driver.name = "ttyS"; mcfrs_serial_driver.major = TTY_MAJOR; mcfrs_serial_driver.minor_start = 64; mcfrs_serial_driver.num = NR_PORTS; mcfrs_serial_driver.type = TTY_DRIVER_TYPE_SERIAL; mcfrs_serial_driver.subtype = SERIAL_TYPE_NORMAL; mcfrs_serial_driver.init_termios = tty_std_termios; mcfrs_serial_driver.init_termios.c_cflag = mcfrs_console_cbaud | CS8 | CREAD | HUPCL | CLOCAL; mcfrs_serial_driver.flags = TTY_DRIVER_REAL_RAW; mcfrs_serial_driver.refcount = &mcfrs_serial_refcount; mcfrs_serial_driver.table = mcfrs_serial_table; mcfrs_serial_driver.termios = mcfrs_serial_termios; mcfrs_serial_driver.termios_locked = mcfrs_serial_termios_locked; mcfrs_serial_driver.open = mcfrs_open; mcfrs_serial_driver.close = mcfrs_close; mcfrs_serial_driver.write = mcfrs_write; mcfrs_serial_driver.flush_chars = mcfrs_flush_chars; mcfrs_serial_driver.write_room = mcfrs_write_room; mcfrs_serial_driver.chars_in_buffer = mcfrs_chars_in_buffer; mcfrs_serial_driver.flush_buffer = mcfrs_flush_buffer; mcfrs_serial_driver.ioctl = mcfrs_ioctl; mcfrs_serial_driver.throttle = mcfrs_throttle; mcfrs_serial_driver.unthrottle = mcfrs_unthrottle; mcfrs_serial_driver.set_termios = mcfrs_set_termios; mcfrs_serial_driver.stop = mcfrs_stop; mcfrs_serial_driver.start = mcfrs_start; mcfrs_serial_driver.hangup = mcfrs_hangup; /* * The callout device is just like normal device except for * major number and the subtype code. */ mcfrs_callout_driver = mcfrs_serial_driver; mcfrs_callout_driver.name = "cua"; mcfrs_callout_driver.major = TTYAUX_MAJOR; mcfrs_callout_driver.subtype = SERIAL_TYPE_CALLOUT; if (tty_register_driver(&mcfrs_serial_driver)) { printk(__FUNCTION__ ": Couldn't register serial driver\n"); return(-EBUSY); } if (tty_register_driver(&mcfrs_callout_driver)) { printk(__FUNCTION__ ": Couldn't register callout driver\n"); return(-EBUSY); } save_flags(flags); cli(); /* * Configure all the attached serial ports. */ for (i = 0, info = mcfrs_table; (i < NR_PORTS); i++, info++) { info->magic = SERIAL_MAGIC; info->line = i; info->tty = 0; info->custom_divisor = 16; info->close_delay = 50; info->closing_wait = 3000; info->x_char = 0; info->event = 0; info->count = 0; info->blocked_open = 0; info->tqueue.routine = do_softint; info->tqueue.data = info; info->tqueue_hangup.routine = do_serial_hangup; info->tqueue_hangup.data = info; info->callout_termios = mcfrs_callout_driver.init_termios; info->normal_termios = mcfrs_serial_driver.init_termios; #if LINUX_VERSION_CODE < 0x020100 info->open_wait = 0; info->close_wait = 0; #else init_waitqueue_head(&info->open_wait); init_waitqueue_head(&info->close_wait); #endif mcfrs_setsignals(info, 0, 0); mcfrs_irqinit(info); printk("%s%d at 0x%04x (irq = %d)", mcfrs_serial_driver.name, info->line, info->addr, info->irq); printk(" is a builtin ColdFire UART\n"); } restore_flags(flags); return 0; } module_init(mcfrs_init); /* DAVIDM module_exit(mcfrs_fini); */ /****************************************************************************/ /* Serial Console */ /****************************************************************************/ /* * Quick and dirty UART initialization, for console output. */ void mcfrs_init_console(void) { volatile unsigned char *uartp; unsigned int clk; /* * Reset UART, get it into known state... */ uartp = (volatile unsigned char *) (MCF_MBAR + (mcfrs_console_port ? MCFUART_BASE2 : MCFUART_BASE1)); uartp[MCFUART_UCR] = MCFUART_UCR_CMDRESETRX; /* reset RX */ uartp[MCFUART_UCR] = MCFUART_UCR_CMDRESETTX; /* reset TX */ uartp[MCFUART_UCR] = MCFUART_UCR_CMDRESETMRPTR; /* reset MR pointer */ /* * Set port for defined baud , 8 data bits, 1 stop bit, no parity. */ uartp[MCFUART_UMR] = MCFUART_MR1_PARITYNONE | MCFUART_MR1_CS8; uartp[MCFUART_UMR] = MCFUART_MR2_STOP1; clk = ((MCF_CLK / 32) / mcfrs_console_baud); /* Set baud above */ uartp[MCFUART_UBG1] = (clk & 0xff00) >> 8; /* set msb baud */ uartp[MCFUART_UBG2] = (clk & 0xff); /* set lsb baud */ uartp[MCFUART_UCSR] = MCFUART_UCSR_RXCLKTIMER | MCFUART_UCSR_TXCLKTIMER; uartp[MCFUART_UCR] = MCFUART_UCR_RXENABLE | MCFUART_UCR_TXENABLE; mcfrs_console_inited++; return; } /* * Setup for console. Argument comes from the boot command line. */ int mcfrs_console_setup(struct console *cp, char *arg) { int i, n = CONSOLE_BAUD_RATE; if (!cp) return(-1); if (!strncmp(cp->name, "ttyS", 4)) mcfrs_console_port = cp->index; else if (!strncmp(cp->name, "cua", 3)) mcfrs_console_port = cp->index; else return(-1); if (arg) n = simple_strtoul(arg,NULL,0); for (i = 0; i < MCFRS_BAUD_TABLE_SIZE; i++) if (mcfrs_baud_table[i] == n) break; if (i < MCFRS_BAUD_TABLE_SIZE) { mcfrs_console_baud = n; mcfrs_console_cbaud = 0; if (i > 15) { mcfrs_console_cbaud |= CBAUDEX; i -= 15; } mcfrs_console_cbaud |= i; } mcfrs_init_console(); /* make sure baud rate changes */ return(0); } static kdev_t mcfrs_console_device(struct console *c) { return MKDEV(TTY_MAJOR, 64 + c->index); } /* * Output a single character, using UART polled mode. * This is used for console output. */ void mcfrs_put_char(char ch) { volatile unsigned char *uartp; unsigned long flags; int i; uartp = (volatile unsigned char *) (MCF_MBAR + (mcfrs_console_port ? MCFUART_BASE2 : MCFUART_BASE1)); save_flags(flags); cli(); for (i = 0; (i < 0x10000); i++) { if (uartp[MCFUART_USR] & MCFUART_USR_TXREADY) break; } if (i < 0x10000) { uartp[MCFUART_UTB] = ch; for (i = 0; (i < 0x10000); i++) if (uartp[MCFUART_USR] & MCFUART_USR_TXEMPTY) break; } if (i >= 0x10000) mcfrs_init_console(); /* try and get it back */ restore_flags(flags); return; } /* * rs_console_write is registered for printk output. */ void mcfrs_console_write(struct console *cp, const char *p, unsigned len) { if (!mcfrs_console_inited) mcfrs_init_console(); while (len-- > 0) { if (*p == '\n') mcfrs_put_char('\r'); mcfrs_put_char(*p++); } } /* * declare our consoles */ struct console mcfrs_console = { name: "ttyS", write: mcfrs_console_write, read: NULL, device: mcfrs_console_device, wait_key: NULL, unblank: NULL, setup: mcfrs_console_setup, flags: CON_PRINTBUFFER, index: -1, cflag: 0, next: NULL }; void __init mcfrs_console_init() { register_console(&mcfrs_console); } /****************************************************************************/
25.948205
100
0.671318
[ "vector" ]
3514772cce268c7dd2019aad88751e6716a4f950
11,549
h
C
include/FBXLoader.h
ziacko/TinyModels
6842523d2e43bc4ee10c25fb39c25f3c295f9fe7
[ "MIT" ]
null
null
null
include/FBXLoader.h
ziacko/TinyModels
6842523d2e43bc4ee10c25fb39c25f3c295f9fe7
[ "MIT" ]
null
null
null
include/FBXLoader.h
ziacko/TinyModels
6842523d2e43bc4ee10c25fb39c25f3c295f9fe7
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////// // Author: Conan Bourke // Date: January 5 2013 // Brief: Classes to load an FBX scene for use. // All angles are in radians. ////////////////////////////////////////////////////////////////////////// #ifndef __FBXLOADER_H_ #define __FBXLOADER_H_ ////////////////////////////////////////////////////////////////////////// #include <map> #include <vector> #include <string> #include "Paths.h" #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <glm/gtc/matrix_access.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "Utilities.h" /* // warning on using templates within a DLL #pragma warning( disable : 4251 ) // warning on not using microsoft "safe" functions #pragma warning( disable : 4996 ) // DLL declaration for import/export #ifdef AIE_DLL_EXPORT #define AIE_DLL __declspec(dllexport) #else #define AIE_DLL __declspec(dllimport) #endif // AIE_DLL_EXPORT */ #define MAX_PATH 260 #pragma warning( disable : 4049 ) #pragma warning( disable : 4996 ) ////////////////////////////////////////////////////////////////////////// // A complete vertex structure with all the data needed from the FBX file struct FBXVertex { FBXVertex() : position(0,0,0,1), colour(1,1,1,1), normal(0,0,0,0), tangent(0,0,0,0), binormal(0,0,0,0), indices(0,0,0,0), weights(0,0,0,0), uv(0,0), uv2(0,0) {} enum Offsets { PositionOffset = 0, ColourOffset = PositionOffset + sizeof(glm::vec4), NormalOffset = ColourOffset + sizeof(glm::vec4), TangentOffset = NormalOffset + sizeof(glm::vec4), BiNormalOffset = TangentOffset + sizeof(glm::vec4), IndicesOffset = BiNormalOffset + sizeof(glm::vec4), WeightsOffset = IndicesOffset + sizeof(glm::vec4), UVOffset = WeightsOffset + sizeof(glm::vec4), }; glm::vec4 position; glm::vec4 colour; glm::vec4 normal; glm::vec4 tangent; glm::vec4 binormal; glm::vec4 indices; glm::vec4 weights; glm::vec2 uv; glm::vec2 uv2; // don't touch! int fbxControlPointIndex; bool operator == (const FBXVertex& a_Vertex) { if(a_Vertex.position == position && a_Vertex.colour == colour && a_Vertex.normal == normal && a_Vertex.tangent == tangent && a_Vertex.binormal == binormal && a_Vertex.indices == indices && a_Vertex.weights == weights && a_Vertex.uv == uv && a_Vertex.uv2 == uv2) { return true; } else { return false; } } }; // A simple FBX material that supports 8 texture channels struct FBXMaterial { enum TextureTypes { DiffuseTexture = 0, AmbientTexture, GlowTexture, SpecularTexture, GlossTexture, NormalTexture, AlphaTexture, DisplacementTexture, TextureTypes_Count }; FBXMaterial() : ambient(0,0,0,0), diffuse(1,1,1,1), specular(1,1,1,1), emissive(0,0,0,0) { memset(name,0,MAX_PATH); memset(textureFilenames,0,TextureTypes_Count*MAX_PATH); memset(textureIDs,0,TextureTypes_Count * sizeof(unsigned int)); } char name[MAX_PATH]; glm::vec4 ambient; // RGB + Ambient Factor stored in A glm::vec4 diffuse; // RGBA glm::vec4 specular; // RGB + Shininess/Gloss stored in A glm::vec4 emissive; // RGB + Emissive Factor stored in A char textureFilenames[TextureTypes_Count][MAX_PATH]; // GL texture IDs all 0 until textures are assigned by the application unsigned int textureIDs[TextureTypes_Count]; }; // Simple tree node with local/global transforms and children // Also has a void* user data that the application can make use of class Node { public: enum NodeType : unsigned int { NODE = 0, MESH, LIGHT, CAMERA }; Node() : m_nodeType(NODE), m_localTransform(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1), m_globalTransform(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1), m_parent(nullptr), m_userData(nullptr) { m_name[0] = 0; } virtual ~Node() { for (std::vector<Node*>::iterator l_Iter = m_children.begin(); l_Iter != m_children.end(); l_Iter++) delete *l_Iter; } NodeType m_nodeType; char m_name[MAX_PATH]; glm::mat4 m_localTransform; glm::mat4 m_globalTransform; Node* m_parent; std::vector<Node*> m_children; void* m_userData; }; // A simple mesh node that contains an array of vertices and indices used // to represent a triangle mesh. // Also points to a shared material class FBXMeshNode : public Node { public: FBXMeshNode() : m_material(nullptr) { m_nodeType = MESH; } virtual ~FBXMeshNode() {} FBXMaterial* m_material; std::vector<FBXVertex> m_vertices; std::vector<unsigned int> m_indices; }; // A light node that can represent a point, directional, or spot light class FBXLightNode : public Node { public: FBXLightNode() { m_nodeType = LIGHT; } virtual ~FBXLightNode() {} enum LightType : unsigned int { Point = 0, Directional, Spot, }; LightType m_type; bool m_on; glm::vec4 m_colour; // RGB + Light Intensity stored in A float m_innerAngle; // spotlight inner cone angle float m_outerAngle; // spotlight outer cone angle glm::vec4 m_attenuation; // (constant,linear,quadratic,0) }; // A camera node with information to create projection matrix class FBXCameraNode : public Node { public: FBXCameraNode() { m_nodeType = CAMERA; } virtual ~FBXCameraNode() {} float m_aspectRatio; // if 0 then ratio based off screen resolution float m_fieldOfView; // if 0 then orthographic rather than perspective float m_near; float m_far; glm::mat4 m_viewMatrix; }; ////////////////////////////////////////////////////////////////////////// struct FBXKeyFrame { FBXKeyFrame() : m_key(0), m_rotation(0,0,0,1), m_translation(0,0,0,1), m_scale(1,1,1,0) {} unsigned int m_key; glm::vec4 m_rotation; glm::vec4 m_translation; glm::vec4 m_scale; }; struct FBXTrack { FBXTrack() : m_boneIndex(0), m_keyframeCount(0), m_keyframes(nullptr) {} ~FBXTrack() { } unsigned int m_boneIndex; unsigned int m_keyframeCount; FBXKeyFrame* m_keyframes; }; struct FBXAnimation { FBXAnimation() : m_trackCount(0), m_tracks(nullptr), m_startFrame(0), m_endFrame(0) {} ~FBXAnimation() { } unsigned int TotalFrames() const { return m_endFrame - m_startFrame; } float TotalTime(float a_fps = 24.0f) const { return (m_endFrame - m_startFrame) / a_fps; } char m_name[MAX_PATH]; unsigned int m_trackCount; FBXTrack* m_tracks; unsigned int m_startFrame; unsigned int m_endFrame; }; class FBXSkeleton { public: FBXSkeleton() : m_boneCount(0), m_nodes(nullptr), m_bones(nullptr), m_bindPoses(nullptr), m_userData(nullptr) {} ~FBXSkeleton() { delete[] m_nodes; delete[] m_bones; delete[] m_bindPoses; } void Evaluate(const FBXAnimation* a_animation, float a_time, bool a_loop = true, float a_fps = 24.0f); unsigned int m_boneCount; Node** m_nodes; glm::mat4* m_bones; // ready for use in skinning! (bind pose combined) glm::mat4* m_bindPoses; void* m_userData; }; // An FBX scene representing the contents on an FBX file. // Stores individual items within maps, with names as the key. // Also has a pointer to the root of the scene's node tree. class FBXScene { public: FBXScene() : m_root(nullptr) {} ~FBXScene() { Unload(); } // must unload a scene before loading a new one over top bool Load(const char* a_filename); void Unload(); // save/load from binary format that does not need to be parsed bool SaveAIE(const char* a_filename); bool LoadAIE(const char* a_filename); // the folder path of the FBX file // useful for accessing texture locations const char* GetPath() const { return m_path.c_str(); } // the scene arranged in a tree graph Node* GetRoot() const { return m_root; } // the ambient light of the scene const glm::vec4& GetAmbientLight() const { return m_ambientLight; } unsigned int GetMeshCount() const { return m_meshes.size(); } unsigned int GetLightCount() const { return m_lights.size(); } unsigned int GetCameraCount() const { return m_cameras.size(); } unsigned int GetMaterialCount() const { return m_materials.size(); } unsigned int GetSkeletonCount() const { return m_skeletons.size(); } unsigned int GetAnimationCount() const { return m_animations.size(); } FBXMeshNode* GetMeshByName(const char* a_name); FBXLightNode* GetLightByName(const char* a_name); FBXCameraNode* GetCameraByName(const char* a_name); FBXMaterial* GetMaterialByName(const char* a_name); FBXAnimation* GetAnimationByName(const char* a_name); // these methods are slow as the items are stored in a map FBXMeshNode* GetMeshByIndex(unsigned int a_index); FBXLightNode* GetLightByIndex(unsigned int a_index); FBXCameraNode* GetCameraByIndex(unsigned int a_index); FBXMaterial* GetMaterialByIndex(unsigned int a_index); FBXSkeleton* GetSkeletonByIndex(unsigned int a_index) { return m_skeletons[a_index]; } FBXAnimation* GetAnimationByIndex(unsigned int a_index); private: void ExtractObject(Node* a_parent, void* a_object); void ExtractMesh(FBXMeshNode* a_mesh, void* a_object); void ExtractLight(FBXLightNode* a_light, void* a_object); void ExtractCamera(FBXCameraNode* a_camera, void* a_object); void GatherBones(void* a_object); void ExtractSkeleton(FBXSkeleton* a_skeleton, void* a_scene); void ExtractAnimation(void* a_scene); void ExtractAnimationTrack(std::vector<FBXTrack>& a_tracks, void* a_layer, void* a_node); void ExtractSkin(FBXMeshNode* a_mesh, void* a_node); FBXMaterial* ExtractMaterial(void* a_mesh); // helpers used for building meshes unsigned int AddVertGetIndex(std::vector<FBXVertex>& a_vertices, const FBXVertex& a_vertex); void CalculateTangentsBinormals(std::vector<FBXVertex>& a_vertices, const std::vector<unsigned int>& a_indices); void SaveNode(Node* a_node, FILE* a_file); void SaveMeshData(FBXMeshNode* a_mesh, FILE* a_file); void SaveLightData(FBXLightNode* a_light, FILE* a_file); void SaveCameraData(FBXCameraNode* a_camera, FILE* a_file); void LoadNode(std::map<unsigned int,Node*>& nodes, std::map<unsigned int, FBXMaterial*>& materials, FILE* a_file); void LoadMeshData(FBXMeshNode* a_mesh, std::map<unsigned int, FBXMaterial*>& materials, FILE* a_file); void LoadLightData(FBXLightNode* a_light, FILE* a_file); void LoadCameraData(FBXCameraNode* a_camera, FILE* a_file); void ReLink(Node* a_node, std::map<unsigned int, Node*>& nodes); unsigned int NodeCount(Node* a_node); private: Node* m_root; std::string m_path; glm::vec4 m_ambientLight; std::map<std::string,FBXMeshNode*> m_meshes; std::map<std::string,FBXLightNode*> m_lights; std::map<std::string,FBXCameraNode*> m_cameras; std::map<std::string,FBXMaterial*> m_materials; std::vector<FBXSkeleton*> m_skeletons; std::map<std::string,FBXAnimation*> m_animations; }; ////////////////////////////////////////////////////////////////////////// #endif // __FBXLOADER_H_ //////////////////////////////////////////////////////////////////////////
28.800499
117
0.646809
[ "mesh", "vector" ]
bbf4d3abb7a5d6647e6931143d47e3dffc2cf701
2,789
h
C
BoolkaCommon/Structures/Matrix.h
bestdark/BoolkaEngine
35ae68dedb42baacb19908c0aaa047fe7f71f6b2
[ "MIT" ]
27
2021-02-12T10:13:55.000Z
2022-03-24T14:44:06.000Z
BoolkaCommon/Structures/Matrix.h
bestdark/BoolkaEngine
35ae68dedb42baacb19908c0aaa047fe7f71f6b2
[ "MIT" ]
null
null
null
BoolkaCommon/Structures/Matrix.h
bestdark/BoolkaEngine
35ae68dedb42baacb19908c0aaa047fe7f71f6b2
[ "MIT" ]
null
null
null
#pragma once #include "Vector.h" namespace Boolka { // Row major class Matrix4x4 { public: Matrix4x4(); ~Matrix4x4(); Matrix4x4(const Matrix4x4&) = default; Matrix4x4(Matrix4x4&&) = default; Matrix4x4& operator=(const Matrix4x4&) = default; Matrix4x4& operator=(Matrix4x4&&) = default; Matrix4x4(const Vector4& row1, const Vector4& row2, const Vector4& row3, const Vector4& row4); Matrix4x4(std::initializer_list<float> list); Vector4& operator[](size_t i); const Vector4& operator[](size_t i) const; static_assert(sizeof(Vector4) == (sizeof(float) * 4), "GetBuffer assumes contiguous Vector4's form contiguous array of floats"); float* GetBuffer(); const float* GetBuffer() const; Vector4* begin(); Vector4* end(); const Vector4* begin() const; const Vector4* end() const; Matrix4x4 operator-(); Matrix4x4& operator*=(float other); Matrix4x4& operator/=(float other); Matrix4x4 operator*(float other) const; Matrix4x4 operator/(float other) const; Matrix4x4 operator*(const Matrix4x4& other) const; bool operator==(const Matrix4x4& other) const; bool operator!=(const Matrix4x4& other) const; Matrix4x4 Inverse(bool& isSuccessfull) const; Matrix4x4 Transpose() const; static Matrix4x4 GetIdentity(); static Matrix4x4 GetTranslation(float x, float y, float z); static Matrix4x4 GetTranslation(const Vector4& xyz); static Matrix4x4 GetScale(float uniformScale); static Matrix4x4 GetScale(float x, float y, float z); static Matrix4x4 GetRotationX(float angle); static Matrix4x4 GetRotationY(float angle); static Matrix4x4 GetRotationZ(float angle); static Matrix4x4 CalculateView(const Vector4& right, const Vector4& up, const Vector4& forward, const Vector4& position); static Matrix4x4 CalculateProjPerspective(float nearZ, float farZ, float aspectRatio, float fovY); static Matrix4x4 CalculateProjOrtographic(float nearZ, float farZ, float width, float height); // Matrix that transforms UV (-1..1 range) to texcoords(0..1 range) and backwards static Matrix4x4 GetUVToTexCoord(); static Matrix4x4 GetTexCoordToUV(); static Matrix4x4 CalculateCubeMapView(size_t cubeMapFace, const Vector4& position); private: Vector4 m_data[4]; }; Vector4 operator*(const Vector4& first, const Matrix4x4& second); } // namespace Boolka
35.303797
96
0.62137
[ "vector" ]
bbf6aa9f650611bf7e2fe757acbbc881dbe7c106
3,765
h
C
llvm/3.4.2/llvm-3.4.2.src/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldMachO.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/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldMachO.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/lib/ExecutionEngine/RuntimeDyld/RuntimeDyldMachO.h
tangyibin/goblin-core
1940db6e95908c81687b2b22ddd9afbc8db9cdfe
[ "BSD-3-Clause" ]
18
2015-04-23T20:59:52.000Z
2021-11-18T20:06:39.000Z
//===-- RuntimeDyldMachO.h - Run-time dynamic linker for MC-JIT ---*- C++ -*-=// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // MachO support for MC-JIT runtime dynamic linker. // //===----------------------------------------------------------------------===// #ifndef LLVM_RUNTIME_DYLD_MACHO_H #define LLVM_RUNTIME_DYLD_MACHO_H #include "RuntimeDyldImpl.h" #include "llvm/ADT/IndexedMap.h" #include "llvm/Object/MachO.h" #include "llvm/Support/Format.h" using namespace llvm; using namespace llvm::object; namespace llvm { class RuntimeDyldMachO : public RuntimeDyldImpl { bool resolveI386Relocation(uint8_t *LocalAddress, uint64_t FinalAddress, uint64_t Value, bool isPCRel, unsigned Type, unsigned Size, int64_t Addend); bool resolveX86_64Relocation(uint8_t *LocalAddress, uint64_t FinalAddress, uint64_t Value, bool isPCRel, unsigned Type, unsigned Size, int64_t Addend); bool resolveARMRelocation(uint8_t *LocalAddress, uint64_t FinalAddress, uint64_t Value, bool isPCRel, unsigned Type, unsigned Size, int64_t Addend); void resolveRelocation(const SectionEntry &Section, uint64_t Offset, uint64_t Value, uint32_t Type, int64_t Addend, bool isPCRel, unsigned Size); unsigned getMaxStubSize() { if (Arch == Triple::arm || Arch == Triple::thumb) return 8; // 32-bit instruction and 32-bit address else if (Arch == Triple::x86_64) return 8; // GOT entry else return 0; } unsigned getStubAlignment() { return 1; } struct EHFrameRelatedSections { EHFrameRelatedSections() : EHFrameSID(RTDYLD_INVALID_SECTION_ID), TextSID(RTDYLD_INVALID_SECTION_ID), ExceptTabSID(RTDYLD_INVALID_SECTION_ID) {} EHFrameRelatedSections(SID EH, SID T, SID Ex) : EHFrameSID(EH), TextSID(T), ExceptTabSID(Ex) {} SID EHFrameSID; SID TextSID; SID ExceptTabSID; }; // When a module is loaded we save the SectionID of the EH frame section // in a table until we receive a request to register all unregistered // EH frame sections with the memory manager. SmallVector<EHFrameRelatedSections, 2> UnregisteredEHFrameSections; public: RuntimeDyldMachO(RTDyldMemoryManager *mm) : RuntimeDyldImpl(mm) {} virtual void resolveRelocation(const RelocationEntry &RE, uint64_t Value); virtual void processRelocationRef(unsigned SectionID, RelocationRef RelI, ObjectImage &Obj, ObjSectionToIDMap &ObjSectionToID, const SymbolTableMap &Symbols, StubMap &Stubs); virtual bool isCompatibleFormat(const ObjectBuffer *Buffer) const; virtual void registerEHFrames(); virtual void finalizeLoad(ObjSectionToIDMap &SectionMap); }; } // end namespace llvm #endif
36.201923
80
0.536255
[ "object" ]
0113789a1e80f623c544d4e419581e807d28afee
372
h
C
thirdparty/gm/gm/types/vec2iArray.h
moddyz/Pbrt
fa92b09a98d07503e1dc381fcb0e9d9b6ae88915
[ "MIT" ]
2
2020-06-29T00:25:37.000Z
2020-12-08T11:30:46.000Z
thirdparty/gm/gm/types/vec2iArray.h
moddyz/Pbrt
fa92b09a98d07503e1dc381fcb0e9d9b6ae88915
[ "MIT" ]
null
null
null
thirdparty/gm/gm/types/vec2iArray.h
moddyz/Pbrt
fa92b09a98d07503e1dc381fcb0e9d9b6ae88915
[ "MIT" ]
1
2020-12-08T11:30:50.000Z
2020-12-08T11:30:50.000Z
// // This file is auto-generated, please do not modify directly! // #pragma once /// \file vec2iArray.h /// \ingroup gm_types_array #include <gm/gm.h> #include <vector> #include <gm/types/vec2i.h> GM_NS_OPEN /// \typedef Vec2iArray /// \ingroup gm_types_array /// /// Type definition of an array of \ref Vec2i. using Vec2iArray = std::vector< Vec2i >; GM_NS_CLOSE
15.5
62
0.698925
[ "vector" ]
011e8be07b8d99dee3bb4e4d6d8a0913380b988c
2,735
h
C
examples/meta_example/example_tables.h
sinkarl/asp_db
8dc5b40257b438872a689f5894416ae80db7d7ca
[ "MIT" ]
null
null
null
examples/meta_example/example_tables.h
sinkarl/asp_db
8dc5b40257b438872a689f5894416ae80db7d7ca
[ "MIT" ]
null
null
null
examples/meta_example/example_tables.h
sinkarl/asp_db
8dc5b40257b438872a689f5894416ae80db7d7ca
[ "MIT" ]
null
null
null
#ifndef EXAMPLE_TABLES_H #define EXAMPLE_TABLES_H #include "meta.h" #include <algorithm> #include <numeric> #include <iostream> #include <utility> /** * \brief * Пример сруктуры данных, аналогичной таблице в БД * с именем 'example1_info'. * */ struct ASP_TABLE example1_info { field(incremental, id, NOT_NULL); field(text, name, NOT_NULL); /* параметры таблицы */ primary_key(id) }; std::ostream &operator<<(std::ostream &str, const example1_info &e) { return str << e.id << ' ' << e.name << std::endl; } /* преобразовать example2_info.name к строковому представлению, * для примера, запишем в верхнем регистре */ inline std::string name_to_str(const text &name) { std::string res; std::transform(name.begin(), name.end(), res.begin(), ::toupper); return res; } inline void str_to_name(const text &orig, std::string *s) { *s = ""; std::transform(orig.begin(), orig.end(), s->begin(), ::tolower); } /** * \brief Пример сруктуры данных, аналогичной таблице в БД * с именем 'example2_info', хранит ссылку на example1_info. * */ struct ASP_TABLE example2_info { /* todo может id неявным сделать? */ field(incremental, id, NOT_NULL); /* name setup */ field(text, name, NOT_NULL); /* generate functions */ // std::string field2str_name(const std::string &t); // void str2field_name(const std::string &s, std::string *t); str_functions(name, name_to_str, str_to_name) /* strings */ field(container<text>, strings, ARRAY); /* num */ field(int, num); /* pair<bigint id, another_table *> -- * reference to table 'example_info1' with id = pair.first, * (then pair.second == nullptr). * or reference to table 'example_info1' by pointer - pair.second != nullptr, * (then pair.first = -1). * or pair.first > -1, pair.second != nullpt. * But pair.second->id must be equal pair.first **/ field_fkey(bigint, fkey, NOT_NULL); /* функции не тривиальной конвертации поля структуры к строковому * представлению, добавляемому в SQL запросам */ // str_functions(name,) /* параметры таблицы */ primary_key(id) unique_complex(name, num) // reference(fkey, "id in example1_info onupdate cascade ondelete cascade") /* |field|ftable(fkey) |on update|on delete */ reference(fkey, example1_info(id), CASCADE, CASCADE) }; std::ostream &operator<<(std::ostream &str, const example2_info &e) { std::string s; if (e.strings.size()) { s = std::accumulate(std::next(e.strings.begin()), e.strings.end(), e.strings[0], [](std::string &line, const std::string &val) { return line += ", " + val;}); } return str << e.id << ' ' << e.name << ' ' << s << std::endl; } #endif // !EXAMPLE_TABLES_H
29.728261
81
0.653016
[ "transform" ]
011ee6bd3d278da7a9c8bb64c1a8ad01b630ff5b
2,534
c
C
src/C/nss/nss-3.16.1/nspr/pr/src/bthreads/btsem.c
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
34
2015-02-04T18:03:14.000Z
2020-11-10T06:45:28.000Z
B2G/gecko/nsprpub/pr/src/bthreads/btsem.c
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
5
2015-06-30T21:17:00.000Z
2016-06-14T22:31:51.000Z
src/C/nss/nss-3.16.1/nspr/pr/src/bthreads/btsem.c
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
15
2015-10-29T14:21:58.000Z
2022-01-19T07:33:14.000Z
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include <kernel/OS.h> #include "primpl.h" /* ** Create a new semaphore object. */ PR_IMPLEMENT(PRSemaphore*) PR_NewSem (PRUintn value) { PRSemaphore *semaphore; if (!_pr_initialized) _PR_ImplicitInitialization(); semaphore = PR_NEWZAP(PRSemaphore); if (NULL != semaphore) { if ((semaphore->sem = create_sem(value, "nspr_sem")) < B_NO_ERROR) return NULL; else return semaphore; } return NULL; } /* ** Destroy the given semaphore object. ** */ PR_IMPLEMENT(void) PR_DestroySem (PRSemaphore *sem) { status_t result; PR_ASSERT(sem != NULL); result = delete_sem(sem->sem); PR_ASSERT(result == B_NO_ERROR); PR_DELETE(sem); } /* ** Wait on a Semaphore. ** ** This routine allows a calling thread to wait or proceed depending upon ** the state of the semahore sem. The thread can proceed only if the ** counter value of the semaphore sem is currently greater than 0. If the ** value of semaphore sem is positive, it is decremented by one and the ** routine returns immediately allowing the calling thread to continue. If ** the value of semaphore sem is 0, the calling thread blocks awaiting the ** semaphore to be released by another thread. ** ** This routine can return PR_PENDING_INTERRUPT if the waiting thread ** has been interrupted. */ PR_IMPLEMENT(PRStatus) PR_WaitSem (PRSemaphore *sem) { PR_ASSERT(sem != NULL); if (acquire_sem(sem->sem) == B_NO_ERROR) return PR_SUCCESS; else return PR_FAILURE; } /* ** This routine increments the counter value of the semaphore. If other ** threads are blocked for the semaphore, then the scheduler will ** determine which ONE thread will be unblocked. */ PR_IMPLEMENT(void) PR_PostSem (PRSemaphore *sem) { status_t result; PR_ASSERT(sem != NULL); result = release_sem_etc(sem->sem, 1, B_DO_NOT_RESCHEDULE); PR_ASSERT(result == B_NO_ERROR); } /* ** Returns the value of the semaphore referenced by sem without affecting ** the state of the semaphore. The value represents the semaphore value ** at the time of the call, but may not be the actual value when the ** caller inspects it. */ PR_IMPLEMENT(PRUintn) PR_GetValueSem (PRSemaphore *sem) { sem_info info; PR_ASSERT(sem != NULL); get_sem_info(sem->sem, &info); return info.count; }
25.59596
79
0.719021
[ "object" ]
0120de3f384f202716d531f40318859964d3bce9
1,273
h
C
include/symbols.h
proglanguage/anal_ex
83b6cadbb325638185169b59ab955b8349f22c84
[ "MIT" ]
4
2019-04-23T00:33:29.000Z
2021-12-27T21:29:26.000Z
include/symbols.h
proglanguage/anal_ex
83b6cadbb325638185169b59ab955b8349f22c84
[ "MIT" ]
null
null
null
include/symbols.h
proglanguage/anal_ex
83b6cadbb325638185169b59ab955b8349f22c84
[ "MIT" ]
1
2019-05-21T01:22:42.000Z
2019-05-21T01:22:42.000Z
#ifndef __SYMBOLS_H__ #define __SYMBOLS_H__ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "linked_list.h" typedef struct var_info{ char* id; ///> The alias to the variable char* type; ///> The type of the function }var_info; typedef struct proc_info{ char* id; ///> The alias to the variable list* params; ///> Vector of var_info }proc_info; typedef struct func_info{ char* id; ///> The alias to the variable char* r_type; ///> The type id of the return list* params; ///> Vector of var_info }func_info; /*! An struct type that can store variables, functions and procedures informations * \struct info * \typedef info * * \headerfile hash_table.h "hash_table.h" * \author Ailson F. dos Santos ailsonforte@hotmail.com * \var var * \var proc * \var func */ typedef struct info { var_info* var; ///< Variable informations proc_info* proc; ///< Procedure informations func_info* func; ///< Function infomations }info; ///< An struct type that can store variables, functions and procedures informations var_info* create_var_info(char* id, char* type); proc_info* create_proc_info(char* id, list* params); func_info* create_func_info(char* id, char* r_type, list* params); #endif /** __SYMBOLS_H__ **/
28.288889
90
0.703064
[ "vector" ]
0131f4b3cf26f76f8d6e0744ca34a51b693c54e2
4,716
c
C
src/object/table.c
k-mrm/maxc
49619b71697b3a8c62afb4c02d287f1e14267462
[ "MIT" ]
46
2019-03-16T06:32:49.000Z
2021-04-28T09:48:58.000Z
src/object/table.c
k-mrm/maxc
49619b71697b3a8c62afb4c02d287f1e14267462
[ "MIT" ]
3
2020-02-10T14:40:57.000Z
2020-04-16T02:10:39.000Z
src/object/table.c
k-mrm/maxc
49619b71697b3a8c62afb4c02d287f1e14267462
[ "MIT" ]
6
2019-06-29T02:41:17.000Z
2020-04-11T05:19:14.000Z
#include <stdint.h> #include <string.h> #include <stdlib.h> #include "object/mtable.h" #include "object/system.h" #include "object/mexception.h" #include "object/mstr.h" #include "mem.h" static MxcValue table_tostring(MxcObject *); static Type *table_ty; NEW_EXCEPTION(exc_unknownkey, "key error"); #define EXC_UNKNOWN_KEY (&exc_unknownkey) static int primes[] = { 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093 }; static int nslot_from(int c) { static int nprimes = sizeof(primes) / sizeof(int); for(int i = 0; i < nprimes; i++) { if(c < primes[i]) return primes[i]; } return 0; } static struct mentry *new_entry(MxcValue k, MxcValue v) { struct mentry *e = malloc(sizeof(struct mentry)); e->key = k; e->val = v; e->next = NULL; return e; } MxcValue new_table_capa(int capa) { NEW_OBJECT(MTable, table, table_sys); int nslot = nslot_from(capa); table->e = calloc(1, sizeof(struct mentry *) * nslot); table->nslot = nslot; table->nentry = 0; table->default_val = mval_invalid; return mval_obj(table); } static struct mentry *echainadd(struct mentry *e, struct mentry *new) { new->next = e; return new; } static void extendtable(MTable *t) { int oldnslot = t->nslot; t->nslot = nslot_from(t->nentry); t->nentry = 0; struct mentry **old = t->e; t->e = calloc(1, sizeof(struct mentry *) * t->nslot); struct mentry *next; for(int i = 0; i < oldnslot; i++) { for(struct mentry *e = old[i]; e; e = next) { mtable_add(t, e->key, e->val); next = e->next; free(e); } } free(old); } void mtable_add(MTable *t, MxcValue key, MxcValue val) { if(++t->nentry > t->nslot) extendtable(t); uint32_t i = mval_hash32(key) % t->nslot; struct mentry *new = new_entry(key, val); if(t->e[i]) t->e[i] = echainadd(t->e[i], new); else t->e[i] = new; } static void table_dealloc(MxcObject *a) { MTable *t = (MTable *)a; Mxc_free(t); } static void table_gc_mark(MxcObject *a) { if(OBJGCMARKED(a)) return; OBJGCMARK(a); MTable *t = (MTable *)a; for(int i = 0; i < t->nslot; i++) { for(struct mentry *e = t->e[i]; e; e = e->next) { mgc_mark(e->key); mgc_mark(e->val); } } } static void table_gc_guard(MxcObject *a) { OBJGCGUARD(a); MTable *t = (MTable *)a; for(int i = 0; i < t->nslot; i++) { for(struct mentry *e = t->e[i]; e; e = e->next) { mgc_guard(e->key); mgc_guard(e->val); } } } static void table_gc_unguard(MxcObject *a) { OBJGCUNGUARD(a); MTable *t = (MTable *)a; for(int i = 0; i < t->nslot; i++) { for(struct mentry *e = t->e[i]; e; e = e->next) { mgc_unguard(e->key); mgc_unguard(e->val); } } } static MxcValue table_tostring(MxcObject *a) { MxcValue res; MTable *t = (MTable *)a; GC_GUARD(t); if(t->nentry == 0) { res = new_string_static("{}", 2); GC_UNGUARD(t); return res; } res = new_string_static("{", 1); mgc_guard(res); int c = 0; for(int i = 0; i < t->nslot; i++) { for(struct mentry *e = t->e[i]; e; e = e->next) { if(c++ > 0) str_cstr_append(ostr(res), ", ", 2); MxcValue key_s = mval2str(e->key); MxcValue val_s = mval2str(e->val); str_append(ostr(res), ostr(key_s)); str_cstr_append(ostr(res), "=>", 2); str_append(ostr(res), ostr(val_s)); } } str_cstr_append(ostr(res), "}", 1); GC_UNGUARD(t); mgc_unguard(res); return res; } void table_set_default(MTable *t, MxcValue def) { t->default_val = def; } MxcValue tablegetitem(MxcIterable *self, MxcValue index) { MTable *t = (MTable *)self; uint32_t i = mval_hash32(index) % t->nslot; struct mentry *e = NULL; for(e = t->e[i]; e; e = e->next) { if(mval_eq(e->key, index)) break; } if(e) { return e->val; } else if(check_value(t->default_val)) { return t->default_val; } else { mxc_raise(EXC_UNKNOWN_KEY, "unknown key: `%s`", mval2str(index)); return mval_invalid; } } MxcValue tablesetitem(MxcIterable *self, MxcValue index, MxcValue a) { MTable *t = (MTable *)self; uint32_t i = mval_hash32(index) % t->nslot; struct mentry *e = NULL; for(e = t->e[i]; e; e = e->next) { if(mval_eq(e->key, index)) break; } if(e) e->val = a; else mtable_add(t, index, a); return a; } struct mobj_attr table_attr[] = { { "default", offsetof(MTable, default_val), ATTR_READABLE | ATTR_WRITABLE, ATTY_MVALUE, NULL, offsetof(Type, val) }, { NULL }, }; struct mobj_system table_sys = { "table", table_attr, table_tostring, table_dealloc, 0, // TODO table_gc_mark, table_gc_guard, table_gc_unguard, tablegetitem, tablesetitem, 0, 0, 0, 0, };
20.867257
118
0.600721
[ "object" ]
0139d41cd27ecc582157690fe3ee51aac84d256f
2,852
h
C
src/clustering.h
gregorweiss/vsCNN
e48fa589c6fbb11437b0d766f666ccdf3ebc57e3
[ "MIT" ]
6
2020-09-18T10:49:47.000Z
2022-01-04T13:18:24.000Z
src/clustering.h
gregorweiss/vsCNN
e48fa589c6fbb11437b0d766f666ccdf3ebc57e3
[ "MIT" ]
null
null
null
src/clustering.h
gregorweiss/vsCNN
e48fa589c6fbb11437b0d766f666ccdf3ebc57e3
[ "MIT" ]
1
2021-07-08T14:21:16.000Z
2021-07-08T14:21:16.000Z
/* MIT License Copyright (c) 2020, R. Gregor Weiß, Benjamin Ries 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 CNN_CLUSTERING_H #define CNN_CLUSTERING_H #include <vector> #include "datatypes.h" // clstep, Neighbors #include "core.h" // Clustering::Core::Similarity using namespace std; namespace Clustering { vector<vector<unsigned int> > clustering(Clustering::Core::Similarity similarity, vector<vector<float> > &data, const float cut, const unsigned int sim, const int Nkeep, const bool mutual); // USER INTERFACE HIERARCHICAL CLUSTERING // Hierarchical clustering vector<clstep> hierarchical_clustering(Clustering::Core::Similarity similarity, vector<vector<unsigned int> > &clusters, vector<vector<float> > &data, const clstep init_step, const float delta_fe, const unsigned int ndims, const unsigned int Nkeep, const unsigned int Nsplit, const bool mutual); // USER INTERFACE MAPPING // Maps the data which was not used in a initial clustering step onto the exiting clusters vector<vector<unsigned int> > cluster_mapping(vector<vector<unsigned int> > &clusters, vector<vector<float> > &full_data, vector<vector<float> > &reduced_data, map<unsigned int, unsigned int> &frames, vector<clstep> &leaves, const unsigned int slice); }; #endif //CNN_CLUSTERING_H
40.169014
94
0.625526
[ "vector" ]
014828fead6fdaee2115127f3e8e5766daebcb34
31,416
c
C
contrib/gnu/gmake/dist/implicit.c
TheSledgeHammer/2.11BSD
fe61f0b9aaa273783cd027c7b5ec77e95ead2153
[ "BSD-3-Clause" ]
3
2021-05-04T17:09:06.000Z
2021-10-04T07:19:26.000Z
contrib/gnu/gmake/dist/implicit.c
TheSledgeHammer/2.11BSD
fe61f0b9aaa273783cd027c7b5ec77e95ead2153
[ "BSD-3-Clause" ]
null
null
null
contrib/gnu/gmake/dist/implicit.c
TheSledgeHammer/2.11BSD
fe61f0b9aaa273783cd027c7b5ec77e95ead2153
[ "BSD-3-Clause" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* Implicit rule searching for GNU Make. Copyright (C) 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, Inc. This file is part of GNU Make. GNU Make 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, or (at your option) any later version. GNU Make 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 GNU Make; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "make.h" #include "filedef.h" #include "rule.h" #include "dep.h" #include "debug.h" #include "variable.h" #include "job.h" /* struct child, used inside commands.h */ #include "commands.h" /* set_file_variables */ static int pattern_search PARAMS ((struct file *file, int archive, unsigned int depth, unsigned int recursions)); /* For a FILE which has no commands specified, try to figure out some from the implicit pattern rules. Returns 1 if a suitable implicit rule was found, after modifying FILE to contain the appropriate commands and deps, or returns 0 if no implicit rule was found. */ int try_implicit_rule (struct file *file, unsigned int depth) { DBF (DB_IMPLICIT, _("Looking for an implicit rule for `%s'.\n")); /* The order of these searches was previously reversed. My logic now is that since the non-archive search uses more information in the target (the archive search omits the archive name), it is more specific and should come first. */ if (pattern_search (file, 0, depth, 0)) return 1; #ifndef NO_ARCHIVES /* If this is an archive member reference, use just the archive member name to search for implicit rules. */ if (ar_name (file->name)) { DBF (DB_IMPLICIT, _("Looking for archive-member implicit rule for `%s'.\n")); if (pattern_search (file, 1, depth, 0)) return 1; } #endif return 0; } /* Struct idep captures information about implicit prerequisites that come from implicit rules. */ struct idep { struct idep *next; /* struct dep -compatible interface */ char *name; /* name of the prerequisite */ struct file *intermediate_file; /* intermediate file, 0 otherwise */ char *intermediate_pattern; /* pattern for intermediate file */ unsigned char had_stem; /* had % substituted with stem */ unsigned char ignore_mtime; /* ignore_mtime flag */ }; static void free_idep_chain (struct idep *p) { struct idep *n; for (; p != 0; p = n) { n = p->next; if (p->name) { struct file *f = p->intermediate_file; if (f != 0 && (f->stem < f->name || f->stem > f->name + strlen (f->name))) free (f->stem); free (p->name); } free (p); } } /* Scans the BUFFER for the next word with whitespace as a separator. Returns the pointer to the beginning of the word. LENGTH hold the length of the word. */ static char * get_next_word (char *buffer, unsigned int *length) { char *p = buffer, *beg; char c; /* Skip any leading whitespace. */ while (isblank ((unsigned char)*p)) ++p; beg = p; c = *(p++); if (c == '\0') return 0; /* We already found the first value of "c", above. */ while (1) { char closeparen; int count; switch (c) { case '\0': case ' ': case '\t': goto done_word; case '$': c = *(p++); if (c == '$') break; /* This is a variable reference, so read it to the matching close paren. */ if (c == '(') closeparen = ')'; else if (c == '{') closeparen = '}'; else /* This is a single-letter variable reference. */ break; for (count = 0; *p != '\0'; ++p) { if (*p == c) ++count; else if (*p == closeparen && --count < 0) { ++p; break; } } break; case '|': goto done; default: break; } c = *(p++); } done_word: --p; done: if (length) *length = p - beg; return beg; } /* Search the pattern rules for a rule with an existing dependency to make FILE. If a rule is found, the appropriate commands and deps are put in FILE and 1 is returned. If not, 0 is returned. If ARCHIVE is nonzero, FILE->name is of the form "LIB(MEMBER)". A rule for "(MEMBER)" will be searched for, and "(MEMBER)" will not be chopped up into directory and filename parts. If an intermediate file is found by pattern search, the intermediate file is set up as a target by the recursive call and is also made a dependency of FILE. DEPTH is used for debugging messages. */ static int pattern_search (struct file *file, int archive, unsigned int depth, unsigned int recursions) { /* Filename we are searching for a rule for. */ char *filename = archive ? strchr (file->name, '(') : file->name; /* Length of FILENAME. */ unsigned int namelen = strlen (filename); /* The last slash in FILENAME (or nil if there is none). */ char *lastslash; /* This is a file-object used as an argument in recursive calls. It never contains any data except during a recursive call. */ struct file *intermediate_file = 0; /* This linked list records all the prerequisites actually found for a rule along with some other useful information (see struct idep for details). */ struct idep* deps = 0; /* 1 if we need to remove explicit prerequisites, 0 otherwise. */ unsigned int remove_explicit_deps = 0; /* Names of possible dependencies are constructed in this buffer. */ register char *depname = (char *) alloca (namelen + max_pattern_dep_length); /* The start and length of the stem of FILENAME for the current rule. */ register char *stem = 0; register unsigned int stemlen = 0; register unsigned int fullstemlen = 0; /* Buffer in which we store all the rules that are possibly applicable. */ struct rule **tryrules = (struct rule **) xmalloc (num_pattern_rules * max_pattern_targets * sizeof (struct rule *)); /* Number of valid elements in TRYRULES. */ unsigned int nrules; /* The numbers of the rule targets of each rule in TRYRULES that matched the target file. */ unsigned int *matches = (unsigned int *) alloca (num_pattern_rules * sizeof (unsigned int)); /* Each element is nonzero if LASTSLASH was used in matching the corresponding element of TRYRULES. */ char *checked_lastslash = (char *) alloca (num_pattern_rules * sizeof (char)); /* The index in TRYRULES of the rule we found. */ unsigned int foundrule; /* Nonzero if should consider intermediate files as dependencies. */ int intermed_ok; /* Nonzero if we have matched a pattern-rule target that is not just `%'. */ int specific_rule_matched = 0; unsigned int i = 0; /* uninit checks OK */ struct rule *rule; struct dep *dep, *expl_d; char *p, *vname; struct idep *d; struct idep **id_ptr; struct dep **d_ptr; PATH_VAR (stem_str); /* @@ Need to get rid of stem, stemlen, etc. */ #ifndef NO_ARCHIVES if (archive || ar_name (filename)) lastslash = 0; else #endif { /* Set LASTSLASH to point at the last slash in FILENAME but not counting any slash at the end. (foo/bar/ counts as bar/ in directory foo/, not empty in directory foo/bar/.) */ #ifdef VMS lastslash = strrchr (filename, ']'); if (lastslash == 0) lastslash = strrchr (filename, ':'); #else lastslash = strrchr (filename, '/'); #ifdef HAVE_DOS_PATHS /* Handle backslashes (possibly mixed with forward slashes) and the case of "d:file". */ { char *bslash = strrchr (filename, '\\'); if (lastslash == 0 || bslash > lastslash) lastslash = bslash; if (lastslash == 0 && filename[0] && filename[1] == ':') lastslash = filename + 1; } #endif #endif if (lastslash != 0 && lastslash[1] == '\0') lastslash = 0; } /* First see which pattern rules match this target and may be considered. Put them in TRYRULES. */ nrules = 0; for (rule = pattern_rules; rule != 0; rule = rule->next) { /* If the pattern rule has deps but no commands, ignore it. Users cancel built-in rules by redefining them without commands. */ if (rule->deps != 0 && rule->cmds == 0) continue; /* If this rule is in use by a parent pattern_search, don't use it here. */ if (rule->in_use) { DBS (DB_IMPLICIT, (_("Avoiding implicit rule recursion.\n"))); continue; } for (i = 0; rule->targets[i] != 0; ++i) { char *target = rule->targets[i]; char *suffix = rule->suffixes[i]; int check_lastslash; /* Rules that can match any filename and are not terminal are ignored if we're recursing, so that they cannot be intermediate files. */ if (recursions > 0 && target[1] == '\0' && !rule->terminal) continue; if (rule->lens[i] > namelen) /* It can't possibly match. */ continue; /* From the lengths of the filename and the pattern parts, find the stem: the part of the filename that matches the %. */ stem = filename + (suffix - target - 1); stemlen = namelen - rule->lens[i] + 1; /* Set CHECK_LASTSLASH if FILENAME contains a directory prefix and the target pattern does not contain a slash. */ check_lastslash = 0; if (lastslash) { #ifdef VMS check_lastslash = (strchr (target, ']') == 0 && strchr (target, ':') == 0); #else check_lastslash = strchr (target, '/') == 0; #ifdef HAVE_DOS_PATHS /* Didn't find it yet: check for DOS-type directories. */ if (check_lastslash) { char *b = strchr (target, '\\'); check_lastslash = !(b || (target[0] && target[1] == ':')); } #endif #endif } if (check_lastslash) { /* If so, don't include the directory prefix in STEM here. */ unsigned int difference = lastslash - filename + 1; if (difference > stemlen) continue; stemlen -= difference; stem += difference; } /* Check that the rule pattern matches the text before the stem. */ if (check_lastslash) { if (stem > (lastslash + 1) && !strneq (target, lastslash + 1, stem - lastslash - 1)) continue; } else if (stem > filename && !strneq (target, filename, stem - filename)) continue; /* Check that the rule pattern matches the text after the stem. We could test simply use streq, but this way we compare the first two characters immediately. This saves time in the very common case where the first character matches because it is a period. */ if (*suffix != stem[stemlen] || (*suffix != '\0' && !streq (&suffix[1], &stem[stemlen + 1]))) continue; /* Record if we match a rule that not all filenames will match. */ if (target[1] != '\0') specific_rule_matched = 1; /* A rule with no dependencies and no commands exists solely to set specific_rule_matched when it matches. Don't try to use it. */ if (rule->deps == 0 && rule->cmds == 0) continue; /* Record this rule in TRYRULES and the index of the matching target in MATCHES. If several targets of the same rule match, that rule will be in TRYRULES more than once. */ tryrules[nrules] = rule; matches[nrules] = i; checked_lastslash[nrules] = check_lastslash; ++nrules; } } /* If we have found a matching rule that won't match all filenames, retroactively reject any non-"terminal" rules that do always match. */ if (specific_rule_matched) for (i = 0; i < nrules; ++i) if (!tryrules[i]->terminal) { register unsigned int j; for (j = 0; tryrules[i]->targets[j] != 0; ++j) if (tryrules[i]->targets[j][1] == '\0') break; if (tryrules[i]->targets[j] != 0) tryrules[i] = 0; } /* We are going to do second expansion so initialize file variables for the rule. */ initialize_file_variables (file, 0); /* Try each rule once without intermediate files, then once with them. */ for (intermed_ok = 0; intermed_ok == !!intermed_ok; ++intermed_ok) { /* Try each pattern rule till we find one that applies. If it does, expand its dependencies (as substituted) and chain them in DEPS. */ for (i = 0; i < nrules; i++) { struct file *f; unsigned int failed = 0; int check_lastslash; int file_variables_set = 0; rule = tryrules[i]; remove_explicit_deps = 0; /* RULE is nil when we discover that a rule, already placed in TRYRULES, should not be applied. */ if (rule == 0) continue; /* Reject any terminal rules if we're looking to make intermediate files. */ if (intermed_ok && rule->terminal) continue; /* Mark this rule as in use so a recursive pattern_search won't try to use it. */ rule->in_use = 1; /* From the lengths of the filename and the matching pattern parts, find the stem: the part of the filename that matches the %. */ stem = filename + (rule->suffixes[matches[i]] - rule->targets[matches[i]]) - 1; stemlen = namelen - rule->lens[matches[i]] + 1; check_lastslash = checked_lastslash[i]; if (check_lastslash) { stem += lastslash - filename + 1; stemlen -= (lastslash - filename) + 1; } DBS (DB_IMPLICIT, (_("Trying pattern rule with stem `%.*s'.\n"), (int) stemlen, stem)); strncpy (stem_str, stem, stemlen); stem_str[stemlen] = '\0'; /* Temporary assign STEM to file->stem (needed to set file variables below). */ file->stem = stem_str; /* Try each dependency; see if it "exists". */ for (dep = rule->deps; dep != 0; dep = dep->next) { unsigned int len; char *p2; unsigned int order_only = 0; /* Set if '|' was seen. */ /* In an ideal world we would take the dependency line, substitute the stem, re-expand the whole line and chop it into individual prerequisites. Unfortunately this won't work because of the "check_lastslash" twist. Instead, we will have to go word by word, taking $()'s into account, for each word we will substitute the stem, re-expand, chop it up, and, if check_lastslash != 0, add the directory part to each resulting prerequisite. */ p = get_next_word (dep->name, &len); while (1) { int add_dir = 0; int had_stem = 0; if (p == 0) break; /* No more words */ /* Is there a pattern in this prerequisite? */ for (p2 = p; p2 < p + len && *p2 != '%'; ++p2) ; if (dep->need_2nd_expansion) { /* If the dependency name has %, substitute the stem. Watch out, we are going to do something tricky here. If we just replace % with the stem value, later, when we do the second expansion, we will re-expand this stem value once again. This is not good especially if you have certain characters in your stem (like $). Instead, we will replace % with $* and allow the second expansion to take care of it for us. This way (since $* is a simple variable) there won't be additional re-expansion of the stem. */ if (p2 < p + len) { register unsigned int i = p2 - p; bcopy (p, depname, i); bcopy ("$*", depname + i, 2); bcopy (p2 + 1, depname + i + 2, len - i - 1); depname[len + 2 - 1] = '\0'; if (check_lastslash) add_dir = 1; had_stem = 1; } else { bcopy (p, depname, len); depname[len] = '\0'; } /* Set file variables. Note that we cannot do it once at the beginning of the function because of the stem value. */ if (!file_variables_set) { set_file_variables (file); file_variables_set = 1; } p2 = variable_expand_for_file (depname, file); } else { if (p2 < p + len) { register unsigned int i = p2 - p; bcopy (p, depname, i); bcopy (stem_str, depname + i, stemlen); bcopy (p2 + 1, depname + i + stemlen, len - i - 1); depname[len + stemlen - 1] = '\0'; if (check_lastslash) add_dir = 1; had_stem = 1; } else { bcopy (p, depname, len); depname[len] = '\0'; } p2 = depname; } /* Parse the dependencies. */ while (1) { id_ptr = &deps; for (; *id_ptr; id_ptr = &(*id_ptr)->next) ; *id_ptr = (struct idep *) multi_glob ( parse_file_seq (&p2, order_only ? '\0' : '|', sizeof (struct idep), 1), sizeof (struct idep)); /* @@ It would be nice to teach parse_file_seq or multi_glob to add prefix. This would save us some reallocations. */ if (order_only || add_dir || had_stem) { unsigned long l = lastslash - filename + 1; for (d = *id_ptr; d != 0; d = d->next) { if (order_only) d->ignore_mtime = 1; if (add_dir) { char *p = d->name; d->name = xmalloc (strlen (p) + l + 1); bcopy (filename, d->name, l); bcopy (p, d->name + l, strlen (p) + 1); free (p); } if (had_stem) d->had_stem = 1; } } if (!order_only && *p2) { ++p2; order_only = 1; continue; } break; } p += len; p = get_next_word (p, &len); } } /* Reset the stem in FILE. */ file->stem = 0; /* @@ This loop can be combined with the previous one. I do it separately for now for transparency.*/ for (d = deps; d != 0; d = d->next) { char *name = d->name; if (file_impossible_p (name)) { /* If this dependency has already been ruled "impossible", then the rule fails and don't bother trying it on the second pass either since we know that will fail too. */ DBS (DB_IMPLICIT, (d->had_stem ? _("Rejecting impossible implicit prerequisite `%s'.\n") : _("Rejecting impossible rule prerequisite `%s'.\n"), name)); tryrules[i] = 0; failed = 1; break; } DBS (DB_IMPLICIT, (d->had_stem ? _("Trying implicit prerequisite `%s'.\n") : _("Trying rule prerequisite `%s'.\n"), name)); /* If this prerequisite also happened to be explicitly mentioned for FILE skip all the test below since it it has to be built anyway, no matter which implicit rule we choose. */ for (expl_d = file->deps; expl_d != 0; expl_d = expl_d->next) if (streq (dep_name (expl_d), name)) break; if (expl_d != 0) continue; /* The DEP->changed flag says that this dependency resides in a nonexistent directory. So we normally can skip looking for the file. However, if CHECK_LASTSLASH is set, then the dependency file we are actually looking for is in a different directory (the one gotten by prepending FILENAME's directory), so it might actually exist. */ /* @@ dep->changed check is disabled. */ if (((f = lookup_file (name)) != 0 && f->is_target) /*|| ((!dep->changed || check_lastslash) && */ || file_exists_p (name)) continue; /* This code, given FILENAME = "lib/foo.o", dependency name "lib/foo.c", and VPATH=src, searches for "src/lib/foo.c". */ vname = name; if (vpath_search (&vname, (FILE_TIMESTAMP *) 0)) { DBS (DB_IMPLICIT, (_("Found prerequisite `%s' as VPATH `%s'\n"), name, vname)); free (vname); continue; } /* We could not find the file in any place we should look. Try to make this dependency as an intermediate file, but only on the second pass. */ if (intermed_ok) { if (intermediate_file == 0) intermediate_file = (struct file *) alloca (sizeof (struct file)); DBS (DB_IMPLICIT, (_("Looking for a rule with intermediate file `%s'.\n"), name)); bzero ((char *) intermediate_file, sizeof (struct file)); intermediate_file->name = name; if (pattern_search (intermediate_file, 0, depth + 1, recursions + 1)) { d->intermediate_file = intermediate_file; d->intermediate_pattern = intermediate_file->name; intermediate_file->name = xstrdup (name); intermediate_file = 0; continue; } /* If we have tried to find P as an intermediate file and failed, mark that name as impossible so we won't go through the search again later. */ if (intermediate_file->variables) free_variable_set (intermediate_file->variables); file_impossible (name); } /* A dependency of this rule does not exist. Therefore, this rule fails. */ failed = 1; break; } /* This rule is no longer `in use' for recursive searches. */ rule->in_use = 0; if (failed) { /* This pattern rule does not apply. If some of its dependencies succeeded, free the data structure describing them. */ free_idep_chain (deps); deps = 0; } else /* This pattern rule does apply. Stop looking for one. */ break; } /* If we found an applicable rule without intermediate files, don't try with them. */ if (i < nrules) break; rule = 0; } /* RULE is nil if the loop went all the way through the list and everything failed. */ if (rule == 0) goto done; foundrule = i; /* If we are recursing, store the pattern that matched FILENAME in FILE->name for use in upper levels. */ if (recursions > 0) /* Kludge-o-matic */ file->name = rule->targets[matches[foundrule]]; /* FOUND_FILES lists the dependencies for the rule we found. This includes the intermediate files, if any. Convert them into entries on the deps-chain of FILE. */ if (remove_explicit_deps) { /* Remove all the dependencies that didn't come from this implicit rule. */ dep = file->deps; while (dep != 0) { struct dep *next = dep->next; free_dep (dep); dep = next; } file->deps = 0; } expl_d = file->deps; /* We will add them at the end. */ d_ptr = &file->deps; for (d = deps; d != 0; d = d->next) { register char *s; if (d->intermediate_file != 0) { /* If we need to use an intermediate file, make sure it is entered as a target, with the info that was found for it in the recursive pattern_search call. We know that the intermediate file did not already exist as a target; therefore we can assume that the deps and cmds of F below are null before we change them. */ struct file *imf = d->intermediate_file; register struct file *f = lookup_file (imf->name); /* We don't want to delete an intermediate file that happened to be a prerequisite of some (other) target. Mark it as precious. */ if (f != 0) f->precious = 1; else f = enter_file (imf->name); f->deps = imf->deps; f->cmds = imf->cmds; f->stem = imf->stem; f->also_make = imf->also_make; f->is_target = 1; if (!f->precious) { imf = lookup_file (d->intermediate_pattern); if (imf != 0 && imf->precious) f->precious = 1; } f->intermediate = 1; f->tried_implicit = 1; for (dep = f->deps; dep != 0; dep = dep->next) { dep->file = enter_file (dep->name); /* enter_file uses dep->name _if_ we created a new file. */ if (dep->name != dep->file->name) free (dep->name); dep->name = 0; dep->file->tried_implicit |= dep->changed; } } dep = alloc_dep (); dep->ignore_mtime = d->ignore_mtime; s = d->name; /* Hijacking the name. */ d->name = 0; if (recursions == 0) { dep->file = lookup_file (s); if (dep->file == 0) /* enter_file consumes S's storage. */ dep->file = enter_file (s); else /* A copy of S is already allocated in DEP->file->name. So we can free S. */ free (s); } else { dep->name = s; } if (d->intermediate_file == 0 && tryrules[foundrule]->terminal) { /* If the file actually existed (was not an intermediate file), and the rule that found it was a terminal one, then we want to mark the found file so that it will not have implicit rule search done for it. If we are not entering a `struct file' for it now, we indicate this with the `changed' flag. */ if (dep->file == 0) dep->changed = 1; else dep->file->tried_implicit = 1; } *d_ptr = dep; d_ptr = &dep->next; } *d_ptr = expl_d; if (!checked_lastslash[foundrule]) { /* Always allocate new storage, since STEM might be on the stack for an intermediate file. */ file->stem = savestring (stem, stemlen); fullstemlen = stemlen; } else { int dirlen = (lastslash + 1) - filename; /* We want to prepend the directory from the original FILENAME onto the stem. */ fullstemlen = dirlen + stemlen; file->stem = (char *) xmalloc (fullstemlen + 1); bcopy (filename, file->stem, dirlen); bcopy (stem, file->stem + dirlen, stemlen); file->stem[fullstemlen] = '\0'; } file->cmds = rule->cmds; file->is_target = 1; /* Set precious flag. */ { struct file *f = lookup_file (rule->targets[matches[foundrule]]); if (f && f->precious) file->precious = 1; } /* If this rule builds other targets, too, put the others into FILE's `also_make' member. */ if (rule->targets[1] != 0) for (i = 0; rule->targets[i] != 0; ++i) if (i != matches[foundrule]) { struct file *f; struct dep *new = alloc_dep (); /* GKM FIMXE: handle '|' here too */ new->name = p = (char *) xmalloc (rule->lens[i] + fullstemlen + 1); bcopy (rule->targets[i], p, rule->suffixes[i] - rule->targets[i] - 1); p += rule->suffixes[i] - rule->targets[i] - 1; bcopy (file->stem, p, fullstemlen); p += fullstemlen; bcopy (rule->suffixes[i], p, rule->lens[i] - (rule->suffixes[i] - rule->targets[i]) + 1); new->file = enter_file (new->name); new->next = file->also_make; /* Set precious flag. */ f = lookup_file (rule->targets[i]); if (f && f->precious) new->file->precious = 1; /* Set the is_target flag so that this file is not treated as intermediate by the pattern rule search algorithm and file_exists_p cannot pick it up yet. */ new->file->is_target = 1; file->also_make = new; } done: free_idep_chain (deps); free (tryrules); return rule != 0; }
31.959308
81
0.523364
[ "object" ]
014942015e9ec69b7b6dc7f4e1effb2fd05bb83b
2,435
h
C
cpp_project/vs-project/log_server/log_server/Include/Network/tcp_socket.h
sinomiko/project
00fadb0033645f103692f5b06c861939a9d4aa0e
[ "BSD-3-Clause" ]
1
2018-12-30T14:07:42.000Z
2018-12-30T14:07:42.000Z
cpp_project/vs-project/log_server/log_server/Include/Network/tcp_socket.h
sinomiko/project
00fadb0033645f103692f5b06c861939a9d4aa0e
[ "BSD-3-Clause" ]
null
null
null
cpp_project/vs-project/log_server/log_server/Include/Network/tcp_socket.h
sinomiko/project
00fadb0033645f103692f5b06c861939a9d4aa0e
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <cstdint> #include <string> #include <vector> #include "Include/Utils/typedefs.h" class tcp_socket { public: //! possible types of a TCP socket, either a client or a server //! type is used to prevent the used of client specific operations on a server socket (and vice-versa) //! //! UNKNOWN is used when socket type could not be determined for now enum class type { CLIENT, SERVER, UNKNOWN }; public: //! ctor & dtor tcp_socket(void); ~tcp_socket(void) = default; //! custom ctor //! build socket from existing file descriptor tcp_socket(fd_t fd, const std::string& host, std::uint32_t port, type t); //! move ctor tcp_socket(tcp_socket&&); //! copy ctor & assignment operator tcp_socket(const tcp_socket&) = delete; tcp_socket& operator=(const tcp_socket&) = delete; public: //! comparison operator bool operator==(const tcp_socket& rhs) const; bool operator!=(const tcp_socket& rhs) const; public: //! client socket operations std::vector<char> recv(std::size_t size_to_read); std::size_t send(const std::vector<char>& data, std::size_t size_to_write); void connect(const std::string& host, std::uint32_t port); //! server socket operations void bind(const std::string& host, std::uint32_t port); void listen(std::size_t max_connection_queue); tcp_socket accept(void); //! general socket operations void close(void); public: //! get socket name information const std::string& get_host(void) const; std::uint32_t get_port(void) const; //! get socket type type get_type(void) const; //! set type, should be used if some operations determining socket type //! have been done on the behalf of the tcp_socket instance void set_type(type t); //! direct access to the underlying fd fd_t get_fd(void) const; private: //! create a new socket if no socket has been initialized yet void create_socket_if_necessary(void); //! check whether the current socket has an approriate type for that kind of operation //! if current type is UNKNOWN, update internal type with given type void check_or_set_type(type t); private: //! fd associated to the socket fd_t m_fd; //! socket name information std::string m_host; std::uint32_t m_port; //! type of the socket type m_type; };
27.359551
106
0.675565
[ "vector" ]
01566f1e96cce6fe5456c9d0805f695bab3de31b
4,118
h
C
client/include/game/CPickups.h
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
368
2015-01-01T21:42:00.000Z
2022-03-29T06:22:22.000Z
client/include/game/CPickups.h
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
92
2019-01-23T23:02:31.000Z
2022-03-23T19:59:40.000Z
client/include/game/CPickups.h
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
179
2015-02-03T23:41:17.000Z
2022-03-26T08:27:16.000Z
/* Plugin-SDK (Grand Theft Auto San Andreas) header file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #pragma once #include "PluginBase.h" #include "CPickup.h" #include "tPickupMessage.h" #include "eWeaponType.h" class CEntity; extern unsigned int MAX_COLLECTED_PICKUPS; // 20 extern unsigned int MAX_PICKUP_MESSAGES; // 16 extern unsigned int MAX_NUM_PICKUPS; // 620 class CPickups { public: static unsigned char &DisplayHelpMessage; static int &PlayerOnWeaponPickup; static int &StaticCamStartTime; static CVector *StaticCamCoors; static CVehicle *&pPlayerVehicle; static bool &bPickUpcamActivated; static unsigned short &CollectedPickUpIndex; static int *aPickUpsCollected; // static int aPickUpsCollected[20]; static unsigned short &NumMessages; static tPickupMessage *aMessages; // static tPickupMessage aMessages[16] static CPickup *aPickUps; // static CPickup aPickUps[620] static void AddToCollectedPickupsArray(int handle); static void CreatePickupCoorsCloseToCoors(float in_x, float in_y, float in_z, float* out_x, float* out_y, float* out_z); static void CreateSomeMoney(CVector coors, int amount); static void DetonateMinesHitByGunShot(CVector* shotOrigin, CVector* shotTarget); static void DoCollectableEffects(CEntity* entity); static void DoMineEffects(CEntity* entity); static void DoMoneyEffects(CEntity* entity); static void DoPickUpEffects(CEntity* entity); static CPickup* FindPickUpForThisObject(CObject* object); // returns pickup handle static int GenerateNewOne(CVector coors, unsigned int modelId, unsigned char pickupType, unsigned int ammo, unsigned int moneyPerDay, bool isEmpty, char* message); // returns pickup handle static int GenerateNewOne_WeaponType(CVector coors, eWeaponType weaponType, unsigned char pickupType, unsigned int ammo, bool isEmpty, char* message); // returns -1 if this index is not actual static int GetActualPickupIndex(int pickupIndex); static int GetNewUniquePickupIndex(int pickupIndex); // returns pickup handle static int GetUniquePickupIndex(int pickupIndex); // returns TRUE if player got goodies static bool GivePlayerGoodiesWithPickUpMI(unsigned short modelId, int playerId); static void Init(); static bool IsPickUpPickedUp(int pickupHandle); // load pickups from save file; always return TRUE static bool Load(); // returns model id static int ModelForWeapon(eWeaponType weaponType); static void PassTime(unsigned int time); static void PickedUpHorseShoe(); static void PickedUpOyster(); static void PictureTaken(); static bool PlayerCanPickUpThisWeaponTypeAtThisMoment(eWeaponType weaponType); static void ReInit(); static void RemoveMissionPickUps(); static void RemovePickUp(int pickupHandle); static void RemovePickUpsInArea(float cornerA_x, float cornerA_y, float cornerA_z, float cornerB_x, float cornerB_y, float cornerB_z); static void RemovePickupObjects(); // remove pickups with types PICKUP_ONCE_TIMEOUT and PICKUP_MONEY in area static void RemoveUnnecessaryPickups(CVector const& posn, float radius); static void RenderPickUpText(); // save pickups to save file; always return TRUE static bool Save(); // check for pickups in area static bool TestForPickupsInBubble(CVector posn, float radius); // search for pickup in area (radius = 5.5 units) with this weapon model and pickup type and add ammo to this pickup; returns TRUE if merged static bool TryToMerge_WeaponType(CVector posn, eWeaponType weaponType, unsigned char pickupType, unsigned int ammo, bool _IGNORED_ arg4); static void Update(); static void UpdateMoneyPerDay(int pickupHandle, unsigned short money); // returns weapon type (see eWeaponType) static int WeaponForModel(int modelId); }; extern int &CollectPickupBuffer; void ModifyStringLabelForControlSetting(char* stringLabel);
47.883721
167
0.754007
[ "object", "model" ]
016066bd3f96f26a9efc9bba8b610787344692d7
9,826
h
C
include/lwiot/network/xbee/xbeeresponse.h
lwIoT/lwIoT
07d2a3ba962aef508911e453268427b006c57701
[ "Apache-2.0" ]
1
2019-07-05T21:39:23.000Z
2019-07-05T21:39:23.000Z
include/lwiot/network/xbee/xbeeresponse.h
lwIoT/lwiot-core
07d2a3ba962aef508911e453268427b006c57701
[ "Apache-2.0" ]
null
null
null
include/lwiot/network/xbee/xbeeresponse.h
lwIoT/lwiot-core
07d2a3ba962aef508911e453268427b006c57701
[ "Apache-2.0" ]
null
null
null
/* * XBee response (RX) base class. * * @author Michel Megens * @email dev@bietje.net */ #pragma once #include <stdlib.h> #include <lwiot/types.h> #include <lwiot/log.h> #include <lwiot/network/xbee/constants.h> #include <lwiot/network/xbee/xbeeaddress.h> namespace lwiot { class XBeeResponse { public: explicit XBeeResponse(); uint8_t getApiId(); void setApiId(uint8_t apiId); uint8_t getMsbLength(); void setMsbLength(uint8_t msbLength); uint8_t getLsbLength(); void setLsbLength(uint8_t lsbLength); uint8_t getChecksum(); void setChecksum(uint8_t checksum); uint8_t getFrameDataLength(); void setFrameData(uint8_t *frameDataPtr); uint8_t *getFrameData(); void setFrameLength(uint8_t frameLength); uint16_t getPacketLength(); void reset(); void init(); #ifdef SERIES_2 void getZBTxStatusResponse(XBeeResponse &response); void getZBRxResponse(XBeeResponse &response); void getZBExplicitRxResponse(XBeeResponse &response); void getZBRxIoSampleResponse(XBeeResponse &response); #endif #ifdef SERIES_1 void getTxStatusResponse(XBeeResponse &response); void getRx16Response(XBeeResponse &response); void getRx64Response(XBeeResponse &response); void getRx16IoSampleResponse(XBeeResponse &response); void getRx64IoSampleResponse(XBeeResponse &response); #endif void getAtCommandResponse(XBeeResponse &responses); void getRemoteAtCommandResponse(XBeeResponse &response); void getModemStatusResponse(XBeeResponse &response); bool isAvailable(); void setAvailable(bool complete); bool isError(); uint8_t getErrorCode(); void setErrorCode(uint8_t errorCode); protected: uint8_t *_frameDataPtr; private: uint8_t _apiId; uint8_t _msbLength; uint8_t _lsbLength; uint8_t _checksum; uint8_t _frameLength; bool _complete; uint8_t _errorCode; void setCommon(XBeeResponse &target); }; class FrameIdResponse : public XBeeResponse { public: FrameIdResponse(); uint8_t getFrameId(); private: uint8_t _frameId; }; /** * Common functionality for both Series 1 and 2 data RX data packets */ class RxDataResponse : public XBeeResponse { public: RxDataResponse(); /** * Returns the specified index of the payload. The index may be 0 to getDataLength() - 1 * This method is deprecated; use uint8_t* getData() */ uint8_t getData(int index); /** * Returns the payload array. This may be accessed from index 0 to getDataLength() - 1 */ uint8_t *getData(); /** * Returns the length of the payload */ virtual uint8_t getDataLength() = 0; /** * Returns the position in the frame data where the data begins */ virtual uint8_t getDataOffset() = 0; }; // getResponse to return the proper subclass: // we maintain a pointer to each type of response, when a response is parsed, it is allocated only if NULL // can we allocate an object in a function? #ifdef SERIES_2 /** * Represents a Series 2 TX status packet */ class ZBTxStatusResponse : public FrameIdResponse { public: ZBTxStatusResponse(); uint16_t getRemoteAddress(); uint8_t getTxRetryCount(); uint8_t getDeliveryStatus(); uint8_t getDiscoveryStatus(); bool isSuccess(); static const uint8_t API_ID = ZB_TX_STATUS_RESPONSE; }; /** * Represents a Series 2 RX packet */ class ZBRxResponse : public RxDataResponse { public: ZBRxResponse(); XBeeAddress64 &getRemoteAddress64(); uint16_t getRemoteAddress16(); virtual uint8_t getOption(); uint8_t getDataLength(); // frame position where data starts uint8_t getDataOffset(); static const uint8_t API_ID = ZB_RX_RESPONSE; private: XBeeAddress64 _remoteAddress64; }; /** * Represents a Series 2 Explicit RX packet * * Note: The receive these responses, set AO=1. With the default AO=0, * you will receive ZBRxResponses, not knowing exact details. */ class ZBExplicitRxResponse : public ZBRxResponse { public: ZBExplicitRxResponse(); uint8_t getSrcEndpoint(); uint8_t getDstEndpoint(); uint16_t getClusterId(); uint16_t getProfileId(); uint8_t getOption() override; uint8_t getDataLength() override; uint8_t getDataOffset() override; static const uint8_t API_ID = ZB_EXPLICIT_RX_RESPONSE; }; /** * Represents a Series 2 RX I/O Sample packet */ class ZBRxIoSampleResponse : public ZBRxResponse { public: ZBRxIoSampleResponse(); bool containsAnalog(); bool containsDigital(); /** * Returns true if the pin is enabled */ bool isAnalogEnabled(uint8_t pin); /** * Returns true if the pin is enabled */ bool isDigitalEnabled(uint8_t pin); /** * Returns the 10-bit analog reading of the specified pin. * Valid pins include ADC:xxx. */ uint16_t getAnalog(uint8_t pin); /** * Returns true if the specified pin is high/on. * Valid pins include DIO:xxx. */ bool isDigitalOn(uint8_t pin); uint8_t getDigitalMaskMsb(); uint8_t getDigitalMaskLsb(); uint8_t getAnalogMask(); static const uint8_t API_ID = ZB_IO_SAMPLE_RESPONSE; }; #endif #ifdef SERIES_1 /** * Represents a Series 1 TX Status packet */ class TxStatusResponse : public FrameIdResponse { public: TxStatusResponse(); uint8_t getStatus(); bool isSuccess(); static const uint8_t API_ID = TX_STATUS_RESPONSE; }; /** * Represents a Series 1 RX packet */ class RxResponse : public RxDataResponse { public: RxResponse(); // remember rssi is negative but this is unsigned byte so it's up to you to convert uint8_t getRssi(); uint8_t getOption(); bool isAddressBroadcast(); bool isPanBroadcast(); uint8_t getDataLength(); uint8_t getDataOffset(); virtual uint8_t getRssiOffset() = 0; }; /** * Represents a Series 1 16-bit address RX packet */ class Rx16Response : public RxResponse { public: Rx16Response(); uint8_t getRssiOffset(); uint16_t getRemoteAddress16(); static const uint8_t API_ID = RX_16_RESPONSE; protected: uint16_t _remoteAddress; }; /** * Represents a Series 1 64-bit address RX packet */ class Rx64Response : public RxResponse { public: Rx64Response(); uint8_t getRssiOffset(); XBeeAddress64 &getRemoteAddress64(); static const uint8_t API_ID = RX_64_RESPONSE; private: XBeeAddress64 _remoteAddress; }; /** * Represents a Series 1 RX I/O Sample packet */ class RxIoSampleBaseResponse : public RxResponse { public: RxIoSampleBaseResponse(); /** * Returns the number of samples in this packet */ uint8_t getSampleSize(); bool containsAnalog(); bool containsDigital(); /** * Returns true if the specified analog pin is enabled */ bool isAnalogEnabled(uint8_t pin); /** * Returns true if the specified digital pin is enabled */ bool isDigitalEnabled(uint8_t pin); /** * Returns the 10-bit analog reading of the specified pin. * Valid pins include ADC:0-5. Sample index starts at 0 */ uint16_t getAnalog(uint8_t pin, uint8_t sample); /** * Returns true if the specified pin is high/on. * Valid pins include DIO:0-8. Sample index starts at 0 */ bool isDigitalOn(uint8_t pin, uint8_t sample); uint8_t getSampleOffset(); /** * Gets the offset of the start of the given sample. */ uint8_t getSampleStart(uint8_t sample); private: }; class Rx16IoSampleResponse : public RxIoSampleBaseResponse { public: Rx16IoSampleResponse(); uint16_t getRemoteAddress16(); uint8_t getRssiOffset(); static const uint8_t API_ID = RX_16_IO_RESPONSE; }; class Rx64IoSampleResponse : public RxIoSampleBaseResponse { public: Rx64IoSampleResponse(); XBeeAddress64 &getRemoteAddress64(); uint8_t getRssiOffset(); static const uint8_t API_ID = RX_64_IO_RESPONSE; private: XBeeAddress64 _remoteAddress; }; #endif /** * Represents a Modem Status RX packet */ class ModemStatusResponse : public XBeeResponse { public: ModemStatusResponse(); uint8_t getStatus(); static const uint8_t API_ID = MODEM_STATUS_RESPONSE; }; class AtCommandResponse : public FrameIdResponse { public: AtCommandResponse(); virtual uint8_t *getCommand(); virtual uint8_t getStatus(); virtual uint8_t *getValue(); virtual uint8_t getValueLength(); virtual bool isOk(); static const uint8_t API_ID = AT_COMMAND_RESPONSE; }; /** * Represents a Remote AT Command RX packet */ class RemoteAtCommandResponse : public AtCommandResponse { public: RemoteAtCommandResponse(); /** * Returns an array containing the two character command */ uint8_t *getCommand() override; /** * Returns the command status code. * Zero represents a successful command */ uint8_t getStatus() override; /** * Returns an array containing the command value. * This is only applicable to query commands. */ uint8_t *getValue() override; /** * Returns the length of the command value array. */ uint8_t getValueLength() override; /** * Returns the 16-bit address of the remote radio */ uint16_t getRemoteAddress16(); /** * Returns the 64-bit address of the remote radio */ XBeeAddress64 &getRemoteAddress64(); /** * Returns true if command was successful */ bool isOk() override; static constexpr uint8_t API_ID = REMOTE_AT_COMMAND_RESPONSE; private: XBeeAddress64 _remoteAddress64; }; }
20.09407
107
0.680949
[ "object" ]
78616d456aeb32b0c74affd2447684869db42547
2,017
c
C
physics/computational/potts.c
gemm-dev/gemmashay2
caac27eef7720252694a02951a959151871f06cd
[ "MIT" ]
null
null
null
physics/computational/potts.c
gemm-dev/gemmashay2
caac27eef7720252694a02951a959151871f06cd
[ "MIT" ]
null
null
null
physics/computational/potts.c
gemm-dev/gemmashay2
caac27eef7720252694a02951a959151871f06cd
[ "MIT" ]
null
null
null
/* Mathematically, the Potts model is described by the energy function E = J*(Sum over nearest neighbor spins i & j) (1.-delta(si,sj)) The constant J sets the energy scale, and we take J=1 without loss of generality. The spins can take any integer value in the range 0->q-1. The function delta(si,sj) is the Kronecker delta function, which is 1 if si=sj, and zero otherwise. */ #include <stdio.h> #include <stdlib.h> #include <math.h> #define Nx 20 #define Ny 20 #define Qmax 20 double erand48(unsigned short xseed[3]); void update_spins(short spin[Nx][Ny], double beta, short q, unsigned short seed[3]) { int x, y; short trial_spin; double deltaE; for (x=0; x<Nx; x++) { for (y=0; y<Ny; y++) { deltaE = ((spin[x][y]==spin[(x+1)%Nx][y]) + (spin[x][y]==spin[(x-1+Nx)%Nx][y]) + (spin[x][y]==spin[x][(y+1)%Ny]) + (spin[x][y]==spin[x][(y-1+Ny)%Ny])); trial_spin = (spin[x][y] + 1 + (q-1)*erand48(seed)); trial_spin = trial_spin%q; deltaE -= ((trial_spin==spin[(x+1)%Nx][y]) + (trial_spin==spin[(x-1+Nx)%Nx][y]) + (trial_spin==spin[x][(y+1)%Ny]) + (trial_spin==spin[x][(y-1+Ny)%Ny])); if (exp(-beta*deltaE)>erand48(seed)) spin[x][y] = trial_spin; } } } double energy(short spin[Nx][Ny]) { int x, y; double E; E = 0; for (x=0; x<Nx; x++) { for (y=0; y<Ny; y++) { /* spin to the right */ E += (1-(spin[x][y]==spin[(x+1)%Nx][y])); /* spin above */ E += (1-(spin[x][y]==spin[x][(y+1)%Ny])); } } return E/(double)(2.*Nx*Ny); } void magnetization(short spin[Nx][Ny], short q, double M[Qmax]) { int s, x, y; for (s=0; s<q; s++) { M[s] = 0; } for (x=0; x<Nx; x++) { for (y=0; y<Ny; y++) { M[spin[x][y]]++; } } for (s=0; s<q; s++) { M[s] /= (double)(Nx*Ny); } } void init_spins(short spin[Nx][Ny], short q, unsigned short seed[3]) { int x, y; for (x=0; x<Nx; x++) { for (y=0; y<Ny; y++) { spin[x][y] = q*erand48(seed); } } }
19.582524
72
0.535449
[ "model" ]
78629a7cb4e0050a79f372b68301e60d93c65f8a
9,412
h
C
Library/Sources/Stroika/Foundation/Characters/Concrete/String_ExternalMemoryOwnership_StackLifetime.h
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
28
2015-09-22T21:43:32.000Z
2022-02-28T01:35:01.000Z
Library/Sources/Stroika/Foundation/Characters/Concrete/String_ExternalMemoryOwnership_StackLifetime.h
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
98
2015-01-22T03:21:27.000Z
2022-03-02T01:47:00.000Z
Library/Sources/Stroika/Foundation/Characters/Concrete/String_ExternalMemoryOwnership_StackLifetime.h
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
4
2019-02-21T16:45:25.000Z
2022-02-18T13:40:04.000Z
/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #ifndef _Stroika_Foundation_Characters_String_ExternalMemoryOwnership_StackLifetime_h_ #define _Stroika_Foundation_Characters_String_ExternalMemoryOwnership_StackLifetime_h_ 1 #include "../../StroikaPreComp.h" #include "../String.h" /** * \file * * @todo PROBABLY DEPRECATE - 2014-03-18. This IS a good idea as optimization (e.g. for stuff like * callbacks from xerces/sax parser) - but issue is the strings if copied to another thread - you cannot * replace out the rep safely if in the middle of access in another thread. * * DOCUMENT idea (in todo section) in case I someday come up with a better way, but I think as of * 2014-03-18 we must deprecate this. * * String_ExternalMemoryOwnership_StackLifetime * * * @todo Redo implementation of String_StackLifetime - using high-performance algorithm described in the documentation. * * @todo Make another pass over String_ExternalMemoryOwnership_StackLifetime/ReadWrite * documentation, and make clearer, and document the tricky bits loosely * alluded to in the appropriate place if the API is truely DOABLE. * * @todo Review this criticism (below). Not sure still valid: * ** SERIOUS - NOT sure what todo about stuff like c_str() - as doc says below - no obvious limitation on lifetime! I GUESS we must simply ** force such APIs to 'breakreferences' - as the note below says. THAT does appear to fix the problem - but at a cost - maybe too huge cost? * * o Seriously reconsider design / semantics of String_ExternalMemoryOwnership_StackLifetime/String_ExternalMemoryOwnership_StackLifetime_ReadWrite classes. * There maybe a serious / hopeless bug having todo with threads and c_str(). Suppose in one thread we do: * void f() * { * wchar_t buf[1024] = L"fred"; * String_ExternalMemoryOwnership_StackLifetime tmp (buf); * * // Then call some function F() with tmp - where F() passes the value (as a String) to another thread, and that other thread runs for a very long time with the string - just READING * // the string - never MODIFYING it. * // * // THEN - because of second thread owning that string - the refCount is bumped up. And suppose that other string calls s.c_str() - and is ever so briefly using the s.c_str() results - say * // in a printf() call. * // * // Now when String_ExternalMemoryOwnership_StackLifetime goes out of scope - and it notices its refCount != 0, it must somehow MORPH the underlying representation into * // something SAFE (copy all the strings). But thats tricky - ESPECIALLY in light of threads and someone else doing a c_str(). * // * // I guess its not IMPOSSIBLE to fix all this. You could * // (o) On c_str() calls - at least for this class rep - maybe always - BREAKREFERENCES() - so the lifetime of your ptr is garuanteed friendly * // (o) Put in enuf flags and CriticalSection code - so on String_ExternalMemoryOwnership_StackLifetime () - we block until we can * // Copy all the data safely and set a flag saying to free it at the end - as a regular string - not a String_ExternalMemoryOwnership_StackLifetime::Rep (would be nice * // to transform the rep object but thats trickier). * } * * */ namespace Stroika::Foundation::Characters::Concrete { /* * String_ExternalMemoryOwnership_StackLifetime is a subtype of String you can use to construct a String object, so long as the memory pointed to * in the argument has a * o Greater lifetime than the String_ExternalMemoryOwnership_StackLifetime envelope class * o and buffer data never changes value externally to this String represenation * ///REVIEW - PRETTY SURE THIS IS WRONG!!!! - UNSAFE - READONLY SHOULD mean pointer passed in is CONST - so memory may NOT be modified in this case -- LGP 2012-03-28 /// DOBLE CHECK NO ASSIMPTIONS BELOW - WRONG - LINE NOT ASSUMED ANYWHERE * Note that the memory passed in must be READ/WRITE - and may be modified by the String_ExternalMemoryOwnership_StackLifetime ()! * * Strings constructed with this String_ExternalMemoryOwnership_StackLifetime maybe treated like normal strings - passed anywhere, and even modified via the * String APIs. However, the underlying implementation may cache the argument const wchar_t* cString for as long as the lifetime of the envelope class, * and re-use it as needed during this time, so only call this String constructor with great care, and then - only as a performance optimization. * * This particular form of String wrapper CAN be a great performance optimization when a C-string buffer is presented and one must * call a 'String' based API. The argument C-string will be used to handle all the Stroika-String operations, and never modified, and the * association will be broken when the String_ExternalMemoryOwnership_StackLifetime goes out of scope. * * This means its EVEN safe to use in cases where the String object might get assigned to long-lived String variables (the internal data will be * copied in that case). * * For example * * extern String saved; * inline String F(String x) { saved = x; x.InsertAt ('X', 1); saved = x.ToUpperCase () + "fred"; return saved; } * * * void f (const wchar_t* cs) * { * F(L"FRED";); * F(String (L"FRED")); * F(String_ExternalMemoryOwnership_StackLifetime (cs)); * } * * These ALL do essentially the same thing, and are all equally safe. The third call to F () with String_ExternalMemoryOwnership_StackLifetime() * based memory maybe more efficient than the previous two, because the string pointed to be 'cs' never needs to be copied (now malloc/copy needed). * * <<TODO: not sure we have all the CTOR/op= stuff done correctly for this class - must rethink - but only needed to rethink when we do * real optimized implementation >> * * * TODO::::COOPY SOME OF THIS - CLEANUP THESE DCOS * * This class looks and acts like a regular String object, but with the performance advantage * that it requires no (significant) free-store allocation. It allocates a 'rep' object from * block-allocation, and re-uses its argument pointers for actual string character storage. * * Also important, it avoids having todo any copying of the original string. * * It can avoid these costs under MANY - but not ALL circumstances. This underlying String * object may remain highly efficient (working off stack memory) only so long as its original * String_ExternalMemoryOwnership_StackLifetime exsts. Once that goes out of scope * the underlying StringRep must be 'morphed' effectively into a regular string-rep (if there * remain any references. * * Also - SOME APIS (still TBD, but perhaps including c_str()) - will force that morphing * /copying. * * This can STILL be a HUGE performance benefit. Consider a shim API between Xerces and * Stroika - for SAX - where lots of strings are efficiently passed by Xerces - and are forwarded * to Stroika 'SAX' APIs. But consider a usage, where several of the strings are never used. * * The shim would be copying/converting these strings, all for no purpose, since they never * got used. This cost can be almost totally eliminated. * * Plus - many - perhaps even most String API methods can be applied to these ligher cost * strings in that 'SAX Callback' scenario without ever constructing high-cost String objects. * * But - if anyone ever does allocate one of those objects - no biggie. It just gets morphed * and the cost paid then. * * THATS THE PLAN ANYHOW.... */ class String_ExternalMemoryOwnership_StackLifetime : public String { private: using inherited = String; public: explicit String_ExternalMemoryOwnership_StackLifetime (const wchar_t* cString); // DOCUMENT THESE NEW EXTRA CTORS!!! NYI explicit String_ExternalMemoryOwnership_StackLifetime (const wchar_t* start, const wchar_t* end); }; } /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "String_ExternalMemoryOwnership_StackLifetime.inl" #endif /*_Stroika_Foundation_Characters_String_ExternalMemoryOwnership_StackLifetime_h_*/
59.949045
210
0.644071
[ "object", "transform" ]
787c9e4bd9b56c64aef4724960a8c807316f1029
838
h
C
test1_grt_rtw/rtwtypes.h
xiaochen1111/The-Simulatoion-program_for_laboratory
b7ab324b71635e0e0687da1de063f94c140f5645
[ "BSD-2-Clause" ]
null
null
null
test1_grt_rtw/rtwtypes.h
xiaochen1111/The-Simulatoion-program_for_laboratory
b7ab324b71635e0e0687da1de063f94c140f5645
[ "BSD-2-Clause" ]
null
null
null
test1_grt_rtw/rtwtypes.h
xiaochen1111/The-Simulatoion-program_for_laboratory
b7ab324b71635e0e0687da1de063f94c140f5645
[ "BSD-2-Clause" ]
null
null
null
/* * rtwtypes.h * * Code generation for model "test1". * * Model version : 1.1 * Simulink Coder version : 9.5 (R2021a) 14-Nov-2020 * C source code generated on : Fri Jul 16 20:45:21 2021 * * Target selection: grt.tlc * Note: GRT includes extra infrastructure and instrumentation for prototyping * Embedded hardware selection: Intel->x86-64 (Windows64) * Code generation objectives: Unspecified * Validation result: Not run */ #ifndef RTWTYPES_H #define RTWTYPES_H #include "tmwtypes.h" #ifndef POINTER_T #define POINTER_T typedef void * pointer_T; #endif /* Logical type definitions */ #if (!defined(__cplusplus)) #ifndef false #define false (0U) #endif #ifndef true #define true (1U) #endif #endif #endif /* RTWTYPES_H */
22.052632
78
0.639618
[ "model" ]
788d4d1de853d5441b8ef39eff8038639b85c7ce
815
h
C
configuration_loader.h
godzi/gliding_fsesci
15131eb4c94db80e816ede0cb51f05c116fe8fd4
[ "MIT" ]
null
null
null
configuration_loader.h
godzi/gliding_fsesci
15131eb4c94db80e816ede0cb51f05c116fe8fd4
[ "MIT" ]
null
null
null
configuration_loader.h
godzi/gliding_fsesci
15131eb4c94db80e816ede0cb51f05c116fe8fd4
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <stdio.h> #include <stdlib.h> #include <malloc.h> #include <string.h> #include <iostream> #include <cstdlib> #include <fstream> #include "json.hpp" # include <omp.h> #include "configuration.h" #include "library.h" using json = nlohmann::json; SimulationParameters assign_simulation_parameters_from_json(SimulationParameters simp, json jsonobjsimp); Configuration assign_config_from_json(Configuration conf, json jsonobj); SimulationParameters load_simulationparams(std::string paramInputFilename); std::vector <Configuration> load_configuration(std::string paramInputFilename); InitialSetup load_setup(std::string setupFilename, int useInitialSetup); InitialSetup assign_initial_setup_from_json(InitialSetup iSetup, json jsoniSetup); double jsonValuetodouble(json obj);
31.346154
105
0.815951
[ "vector" ]
7890cf988e8ea0a92157112c7038554210c620b1
7,066
h
C
dust/gui/gl-shader.h
signaldust/dust-toolkit
3ef3e2e6610df060003a757073d3ac132b787c6e
[ "Unlicense" ]
1
2021-10-05T16:13:12.000Z
2021-10-05T16:13:12.000Z
dust/gui/gl-shader.h
signaldust/dust-toolkit
3ef3e2e6610df060003a757073d3ac132b787c6e
[ "Unlicense" ]
1
2022-01-18T14:46:31.000Z
2022-01-18T14:46:31.000Z
dust/gui/gl-shader.h
signaldust/dust-toolkit
3ef3e2e6610df060003a757073d3ac132b787c6e
[ "Unlicense" ]
null
null
null
#pragma once // FIXME: this only works on macOS for now.. need to setup gl3w for Windows.. #if defined(__APPLE__) # include <opengl/gl3.h> #elif defined(_WIN32) # include <GL/gl3w.h> #else # error "FIXME: GL headers for platform" #endif #include <vector> #include "dust/core/defs.h" namespace dust { // Compiles a combined shader into a program. // // Prefix should begin with #version, but can contain other things // that should be placed before the main shader. // // Put vertex shader inside "#ifdef VERTEX" block. // Put (optional) geometry shader inside "#ifdef GEOMETRY" block. // Put (optional) fragment shader inside "#ifdef FRAGMENT" block. // // Defines "vs_gs(x)", "vs_fs(x)", "gs_fs(x)" macros to define // input/output variables between shader stages. // // return true on success, false on errors // if errors happen, errorCallback is called with a c-string template <typename ErrorFN> static GLuint compileShaderGL(ErrorFN & errorCallback, const char * text, const char * prefix = "#version 410 core\n") { // add line directives.. // sadly the "filename" part is not standard // and at least Apple just refuses const char * lineVsShader = "\n#define VERTEX" "\n#define vs_gs(x) out x;" "\n#define vs_fs(x) out x;" "\n#define gs_fs(x) " "\n#line 1\n"; const char * lineGsShader = "\n#define GEOMETRY" "\n#define vs_gs(x) in x[];" "\n#define vs_fs(x) " "\n#define gs_fs(x) out x;" "\n#line 1\n"; const char * lineFsShader = "\n#define FRAGMENT" "\n#define vs_gs(x) " "\n#define vs_fs(x) in x;" "\n#define gs_fs(x) in x;" "\n#line 1\n"; const char * vsPtrs[] = { prefix, lineVsShader, text }; const char * gsPtrs[] = { prefix, lineGsShader, text }; const char * fsPtrs[] = { prefix, lineFsShader, text }; GLuint vs = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vs, 3, vsPtrs, 0); glCompileShader(vs); { GLint success = 0; glGetShaderiv(vs, GL_COMPILE_STATUS, &success); if(!success) { debugPrint("Error compiling shader (VS):\n"); const char * line = text; for(int i = 1; *line; ++i) { const char * next = strchr(line, '\n'); if(!next) { printf("%d:\t %s\n", i, line); break; } else { printf("%d:\t %.*s\n", i, int(next - line), line); line = next + 1; } } GLint logSize = 0; glGetShaderiv(vs, GL_INFO_LOG_LENGTH, &logSize); std::vector<char> errorOut(logSize + 1); glGetShaderInfoLog(vs, logSize, &logSize, errorOut.data()); errorCallback(errorOut.data()); glDeleteShader(vs); return false; } } // build program GLuint prog = glCreateProgram(); glAttachShader(prog, vs); glDeleteShader(vs); if(strstr(text, "GEOMETRY")) { GLuint gs = glCreateShader(GL_GEOMETRY_SHADER); glShaderSource(gs, 3, gsPtrs, 0); glCompileShader(gs); { GLint success = 0; glGetShaderiv(gs, GL_COMPILE_STATUS, &success); if(!success) { debugPrint("Error compiling shader (GS):\n"); const char * line = text; for(int i = 1; *line; ++i) { const char * next = strchr(line, '\n'); if(!next) { printf("%d:\t %s\n", i, line); break; } else { printf("%d:\t %.*s\n", i, int(next - line), line); line = next + 1; } } GLint logSize = 0; glGetShaderiv(gs, GL_INFO_LOG_LENGTH, &logSize); std::vector<char> errorOut(logSize + 1); glGetShaderInfoLog(gs, logSize, &logSize, errorOut.data()); errorCallback(errorOut.data()); glDeleteShader(gs); glDeleteProgram(prog); return 0; } } glAttachShader(prog, gs); glDeleteShader(gs); } if(strstr(text, "FRAGMENT")) { GLuint fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 3, fsPtrs, 0); glCompileShader(fs); { GLint success = 0; glGetShaderiv(fs, GL_COMPILE_STATUS, &success); if(!success) { debugPrint("Error compiling shader (FS):\n"); const char * line = text; for(int i = 1; *line; ++i) { const char * next = strchr(line, '\n'); if(!next) { printf("%d:\t %s\n", i, line); break; } else { printf("%d:\t %.*s\n", i, int(next - line), line); line = next + 1; } } GLint logSize = 0; glGetShaderiv(fs, GL_INFO_LOG_LENGTH, &logSize); std::vector<char> errorOut(logSize + 1); glGetShaderInfoLog(fs, logSize, &logSize, errorOut.data()); errorCallback(errorOut.data()); glDeleteShader(fs); glDeleteProgram(prog); return 0; } } glAttachShader(prog, fs); glDeleteShader(fs); } // link glLinkProgram(prog); GLint success = 0; glGetProgramiv(prog, GL_LINK_STATUS, &success); if(!success) { GLint logSize = 0; glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &logSize); std::vector<char> errorOut(logSize + 1); glGetProgramInfoLog(prog, logSize, &logSize, errorOut.data()); errorCallback(errorOut.data()); glDeleteProgram(prog); return 0; } return prog; } };
33.018692
79
0.440136
[ "geometry", "vector" ]
789887c60d230d775579cf8c5859887bbc86606b
4,642
h
C
VisualizationBase/src/ViewItemManager.h
dimitar-asenov/Envision
1ab5c846fca502b7fe73ae4aff59e8746248446c
[ "BSD-3-Clause" ]
75
2015-01-18T13:29:43.000Z
2022-01-14T08:02:01.000Z
VisualizationBase/src/ViewItemManager.h
dimitar-asenov/Envision
1ab5c846fca502b7fe73ae4aff59e8746248446c
[ "BSD-3-Clause" ]
364
2015-01-06T10:20:21.000Z
2018-12-17T20:12:28.000Z
VisualizationBase/src/ViewItemManager.h
dimitar-asenov/Envision
1ab5c846fca502b7fe73ae4aff59e8746248446c
[ "BSD-3-Clause" ]
14
2015-01-09T00:44:24.000Z
2022-02-22T15:01:44.000Z
/*********************************************************************************************************************** ** ** Copyright (c) 2015 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich 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. ** ***********************************************************************************************************************/ #pragma once #include "visualizationbase_api.h" namespace Model { class TreeManager; class Node; } namespace Visualization { class Scene; class ViewItem; class Item; /** * The ViewItemManager manages all the different ViewItems which are part * of a given scene. It is responsible for adding and removing views to and from * the scene, as well as switching between the different views. */ class VISUALIZATIONBASE_API ViewItemManager { public: /** * Creates a new ViewItemManager connected to the given scene. */ ViewItemManager(Scene* scene); ~ViewItemManager(); /** * Creates a new ViewItem and adds it to the manager. The ViewItem is given the name * which is supplied, and positioned at the given position, or at the next free position * if the default argument (-1, -1) is used. */ ViewItem* newViewItem(const QString name = {}, QPoint position = {-1, -1}); /** * Finds the ViewItem with the given name, or nullptr if it doesn't exist. */ ViewItem* viewItem(const QString name); /** * Switches to the given view to be the new current view. The view must * already be known to the manager. */ void switchToView(ViewItem* view); /** * Overload using the view's name. Returns whether switching was successful, * i.e. whether a view with the name was found. */ bool switchToView(const QString viewName); /** * Returns the currently visible ViewItem. Guaranteed to return a valid ViewItem. */ ViewItem* currentViewItem(); /** * Removes all existing ViewItems from the manager. */ void removeAllViewItems(); /** * Removes \a view from the manager. */ void removeViewItem(ViewItem* view); /** * Saves the given view persistently on disk, using the given manager. * Note: The view can still contain nodes handled by other managers. */ void saveView(ViewItem* view, Model::TreeManager* manager) const; /** * Loads the given view from persistent disk storage. If it exists, * it is added to the manager at the given position. */ ViewItem* loadView(QString name, QPoint position = {-1, -1}); QVector<QVector<ViewItem*>> viewItems() const; private: friend class Item; friend class Scene; void cleanupRemovedItem(Visualization::Item* removedItem); void cleanupRemovedNode(Model::Node* removedNode); QPoint nextEmptyPosition() const; const QString DIRECTORY_NAME = "views"; QString fileName(QString viewName, QString managerName) const; ViewItem* loadView(QString name, Model::TreeManager* manager); void addViewItem(ViewItem* view, QPoint position = {-1, -1}); const int VIEW_ITEM_COLUMNS = 3; QVector<QVector<ViewItem*>> viewItems_; ViewItem* currentViewItem_{}; Scene* scene_{}; }; inline QVector<QVector<ViewItem*>> ViewItemManager::viewItems() const { return viewItems_; } }
36.84127
120
0.693667
[ "model" ]
789b022f761c98358ce30d45a969ad2cee223738
3,024
h
C
old2/document/brackets.h
csijh/snipe
2bdcdc8a4e33c952d340458e835c6265def53d19
[ "0BSD" ]
5
2018-09-03T09:13:05.000Z
2018-12-03T12:50:09.000Z
old2/document/brackets.h
csijh/snipe
2bdcdc8a4e33c952d340458e835c6265def53d19
[ "0BSD" ]
6
2018-09-03T14:37:57.000Z
2018-10-10T13:37:54.000Z
old2/document/brackets.h
csijh/snipe
2bdcdc8a4e33c952d340458e835c6265def53d19
[ "0BSD" ]
null
null
null
// Snipe bracket matcher. Free and open source. See licence.txt. // A brackets object keeps track of the brackets in the text, and does // incremental bracket matching. Bracket matching is done forwards from the // start of the text to the cursor, backwards from the end of the text to the // cursor, and then inwards from the outside on the remaining stacks. struct brackets; typedef struct brackets brackets; // Create or free a brackets object. brackets *newBrackets(); void freeBrackets(brackets *bs); // Track insertions, deletions and cursor movements. // void changeBrackets(brackets *bs, op *o); // ---------------------------------------------------------------------------- // Store unmatched brackets up to cursor. (That is indenters plus unmatched // brackets on current line.) Don't need line boundaries! // Insert character before cursor: = normal algorithm // Non-bracket: nothing happens. // Opener: gets pushed on stack. // Closer: gets (mis)matched with open bracket(s) on the stack. // The matched/mismatched brackets are dropped out. // Delete character before cursor. // Non-bracket: nothing happens. // Opener: must be on top of stack, gets popped. // Closer: // must be (mis)matched with an opener not on the stack // and the opener must be since the top opener // therefore search back from cursor to position of top opener // Move cursor right = normal algorithm // Move cursor left = delete // The two stacks are matched out to in. Can that also be done incrementally? // Matched outer brackets are paired. What about a mismatch: // {.... { | ] ....} // It looks like the ] should be mismatched. // The ] can point to the opener that mismatched it. // The algorithm can continue until all stacked brackets are dealt with. // {.... { .. [ | } .. ] ....} ( [ { " /* // 1 1 // 1 ! x 1 // 1 2 2 x 1 // 1 2 x !2 x 1 // Just look at curlies: // {{{{{{{ | }}}} // 1234xxx 4321 // Anything of less priority must be between inner {}, so is mismatched by // one of them. A new curly invalidates anything lesser. A new curly on the // left just accumulates. But a new curly on the right matches a long way up: // {{{{{{{ | }}}}} // 12345xx 54321 // So: just mark as matched or mismatched. // Now what about incremental? Try push left opener. If top right is matched, // the new opener is mismatched. // Normal forward algorithm: // See open bracket, push it. // See close bracket, try to match with top. // {) => drop the close bracket. // () => match and drop both. // (} => drop open bracket and loop. // Either match and drop out, or mismatch and drop out. // Normal reverse algorithm: // See open bracket, pop it. // See close bracket = top. Can't happen. // See close bracket not top. MAYBE reconstruct what happened since the top.
40.32
80
0.624008
[ "object" ]
789ff87873daac175a67ea0b9c8450dbfe704d95
4,935
h
C
headers/KMDriver.h
hikame/Static_UAF_Detector-Renew
1840b890913c29a5a5e04a55f6a428fbc3fbb1d5
[ "MIT" ]
2
2021-01-19T03:58:25.000Z
2021-09-05T09:34:47.000Z
headers/KMDriver.h
hikame/Static_UAF_Detector-Renew
1840b890913c29a5a5e04a55f6a428fbc3fbb1d5
[ "MIT" ]
null
null
null
headers/KMDriver.h
hikame/Static_UAF_Detector-Renew
1840b890913c29a5a5e04a55f6a428fbc3fbb1d5
[ "MIT" ]
null
null
null
/* * KMDriver.h * * Created on: 2017年4月26日 * Author: kame */ #ifndef KMDRIVER_H_ #define KMDRIVER_H_ #include <llvm/IR/DebugInfo.h> #include <llvm/IR/Module.h> #include <llvm/IR/Instructions.h> #include <llvm/ADT/DenseMap.h> #include <llvm/ADT/SmallPtrSet.h> #include <llvm/ADT/StringExtras.h> #include <llvm/Support/Path.h> #include <llvm/Support/raw_ostream.h> #include <llvm/Analysis/BasicAliasAnalysis.h> #include <llvm/Support/CommandLine.h> #include <llvm/PassAnalysisSupport.h> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <iostream> #include <fstream> #include <sstream> #include <string> #include "Common.h" using namespace llvm; //KM: Added to make the console output more verbose. #define VERBOSE_SA #define DEBUG_SA #define MAX_IS_RECORD 100 // #define Ignored_Func_List_Record "./ignored_function_list.conf" // // typedefs // typedef std::vector< std::pair<llvm::Module*, llvm::StringRef> > ModuleList; // Mapping module to its file name. typedef std::unordered_map<llvm::Module*, llvm::StringRef> ModuleNameMap; // The set of all functions. typedef llvm::SmallPtrSet<llvm::Function*, 8> FuncSet; // Mapping from function name to function. typedef std::unordered_map<std::string, llvm::Function*> NameFuncMap; typedef llvm::SmallPtrSet<llvm::CallInst*, 8> CallInstSet; typedef llvm::DenseMap<llvm::Function*, CallInstSet> CallerMap; typedef llvm::DenseMap<llvm::CallInst *, FuncSet> CalleeMap; #ifndef KM_ENUM #define KM_ENUM enum ExecuteRelationship{ Start, Call, Return, Switch_Sure, Switch_NotSure, Branch_True, Branch_False, Branch_Undetermined, Branch_UnConditional, Select_True, Select_False, MallocResult_Failed, MallocResult_Success, Fake_Return_Nonnull, Fake_Return_Null, CMP_True, CMP_False, Symbolic_Index, TODET }; enum TrackTag{ Malloc, Free, Reuse, WTF }; #endif #define ValueRecord Value* //This can be a Value*, MemoryBlock* or FakeValue* std::string GetERString(ExecuteRelationship); std::string GetThreadID(); std::string GetCurrentTime(); extern std::set<ExecuteRelationship> NoPrintSet; //extern GVC_t* rgContext; class UafDetectionPass; class DataLayoutHelper; class UAFSourceSinkManager; struct GlobalContext { unsigned cpLimit = 0; unsigned thdPerCPU = 0; unsigned bbAnaLimit = 1; unsigned funcAnaLimit = 6; unsigned MemThreadHold = 20; DataLayoutHelper* dlHelper = NULL; std::set<ExecuteRelationship> LoopCheckSet; UafDetectionPass* UDP; UAFSourceSinkManager* ssm; bool trustGlobalInit = true; bool continueAAS = false; //continue analysis after sunk; bool printDB = true; bool printWN = false; bool printER = false; bool printTC = false; bool shouldQuit = false; LLVMContext* llvmContext = NULL; std::string outputPath; std::mutex sinkRecordsLock; // mutex lock for log output std::mutex opLock; // mutex lock for thread pool std::mutex tpLock; // mutex lock for get instruction's string std::mutex isLock; std::vector<std::pair<Value*, std::string>> isMap; std::set<std::string> ignoredFuncs; void initIgnoredFuncs(std::string path){ std::fstream fs; char buf[256]; fs.open(path, std::ios::in); if(!fs) { // printf("[ERR] Failed to open %s!!!\n", path.c_str()); // printf("[ERR] Continue without any ignored functions...\n"); return; } while(!fs.eof()){ fs.getline(buf, 256); if(buf[0] == '#') continue; ignoredFuncs.insert(buf); } fs.close(); } std::string GetInstStr(Value* value){ if(value == NULL) return "NULL INST"; std::lock_guard<std::mutex> lg(isLock); for(std::pair<Value*, std::string> pr : isMap){ if(pr.first == value) return pr.second; } std::string instStr; llvm::raw_string_ostream rso(instStr); value->print(rso); if(isMap.size() > MAX_IS_RECORD) isMap.erase(isMap.begin()); isMap.push_back(std::pair<Value*, std::string>(value, instStr)); return instStr; } GlobalContext() { UDP = NULL; ssm = NULL; NumFunctions = 0; } ~GlobalContext() { } // Statistics for allocations. unsigned NumFunctions; bool memAvaliable = true; // Modules. ModuleList Modules; ModuleNameMap ModuleMaps; std::set<std::string> HeapAllocFuncs; }; class IterativeModulePass { protected: GlobalContext *globalContext; const char * ID; public: IterativeModulePass(GlobalContext *Ctx_, const char *ID_) : globalContext(Ctx_), ID(ID_) { } // Run on each module before iterative pass. virtual bool doInitialization(llvm::Module *M) { return true; } // Run on each module after iterative pass. virtual bool doFinalization(llvm::Module *M) { return true; } // Iterative pass. virtual bool doModulePass(llvm::Module *M) { return false; } virtual void run(ModuleList &modules); //~IterativeModulePass(){}; virtual ~IterativeModulePass(){}; }; #endif /* KMDRIVER_H_ */
23.278302
77
0.709017
[ "vector" ]
78b649432d0a3a00cd6193d62f6c690ad0d1a797
2,106
h
C
src/MarkovManager.h
yeeking/MarkovModelCPP
651ad465e672d2340202c2ae4ceee292c0dbc8ee
[ "MIT" ]
1
2021-05-05T18:10:24.000Z
2021-05-05T18:10:24.000Z
src/MarkovManager.h
yeeking/MarkovModelCPP
651ad465e672d2340202c2ae4ceee292c0dbc8ee
[ "MIT" ]
1
2022-01-27T13:47:31.000Z
2022-01-27T13:47:31.000Z
src/dinverno_system/Source/MarkovManager.h
yeeking/goldash-system
f3013f89a042dff2d518c0ed17c1d8ae32c2f436
[ "MIT" ]
null
null
null
/* ============================================================================== MarkovManager.h Created: 30 Oct 2019 3:28:02pm Author: matthew ============================================================================== */ #pragma once #include "MarkovChain.h" /** * Manages a markov chain for training and generation purposes */ class MarkovManager { public: /** * Create a markov manager. chainEventMemoryLength is how many chain events we * remember. Chain events are remembered so we can delete or amplify parts of the chain * using givePositive and giveNegative feedback. */ MarkovManager(unsigned long chainEventMemoryLength=20); ~MarkovManager(); /** add an event to the chain. The manager manages previous events to ensure * that variable orders are passed to the underlying markov model */ void putEvent(state_single symbol); /** * retrieve an event from the underlying markov model. */ state_single getEvent(); /** * returns the order of the model that generated the last event * calls */ int getOrderOfLastEvent(); /** * wipe the underlying model and reset short term input and output memory. */ void reset(); /** * Rotates the sent seq and pops the sent item on the end * [1,2,3], 4 -> [2,3,4] */ void addStateToStateSequence(state_sequence& seq, state_single new_state); /** * Update the chain by removing recently visited parts */ void giveNegativeFeedback(); /** * Update the chain by amplifying recently visited parts */ void givePositiveFeedback(); private: void rememberChainEvent(state_and_observation event); state_sequence inputMemory; state_sequence outputMemory; MarkovChain chain; std::vector<state_and_observation> chainEvents; unsigned long maxChainEventMemory; unsigned long chainEventIndex; };
30.085714
90
0.575973
[ "vector", "model" ]
78c1a207e842fa8eda53e7b316cc9c436ad32442
5,571
h
C
include/perceptive_mpc/costs/BaseAvoidanceCost.h
julius-forks/_fork-pmpc
d18e81ea1bce5a45c0880ee9fed0f520da4029d1
[ "Unlicense" ]
41
2020-07-21T10:57:53.000Z
2022-03-22T05:08:01.000Z
include/perceptive_mpc/costs/BaseAvoidanceCost.h
julius-forks/_fork-pmpc
d18e81ea1bce5a45c0880ee9fed0f520da4029d1
[ "Unlicense" ]
11
2021-07-20T15:47:31.000Z
2022-01-24T10:48:58.000Z
include/perceptive_mpc/costs/BaseAvoidanceCost.h
julius-forks/_fork-pmpc
d18e81ea1bce5a45c0880ee9fed0f520da4029d1
[ "Unlicense" ]
15
2020-07-25T13:55:18.000Z
2022-02-27T08:58:21.000Z
/* * Copyright (c) 2020 Johannes Pankert <pankertj@ethz.ch> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of this work 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. */ #pragma once #include <ocs2_core/cost/RelaxedBarrierCost.h> #include <ocs2_robotic_tools/common/RotationTransforms.h> #include <algorithm> #include <cmath> #include <perceptive_mpc/kinematics/KinematicsInterface.hpp> #include <utility> #include "perceptive_mpc/Definitions.h" // CPPAD stuff #include "cppad/cg/math.hpp" namespace perceptive_mpc { struct BaseAvoidanceCostConfig { double widthX = 0.8; double widthY = 0.7; double reach = 1.1; double sigma = 10; double mu = 1e-3; double delta = 1e-4; std::shared_ptr<const KinematicsInterface<CppAD::AD<CppAD::cg::CG<double>>>> kinematics; }; class BaseAvoidanceCost : public ocs2::RelaxedBarrierCost<Definitions::STATE_DIM_, Definitions::INPUT_DIM_, 2, 0> { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef ocs2::RelaxedBarrierCost<Definitions::STATE_DIM_, Definitions::INPUT_DIM_, 2, 0> BASE; using typename BASE::ad_scalar_t; using typename BASE::dynamic_vector_t; using typename BASE::input_matrix_t; using typename BASE::input_vector_t; using typename BASE::scalar_t; using typename BASE::state_matrix_t; using typename BASE::state_vector_t; using state_cost_matrix_t = Eigen::Matrix<scalar_t, 6, 6>; using typename BASE::intermediate_cost_vector_t; using typename BASE::terminal_cost_vector_t; /** * Constructor */ BaseAvoidanceCost(BaseAvoidanceCostConfig config = BaseAvoidanceCostConfig()); /* * Copy constructor * @param rhs */ BaseAvoidanceCost(const BaseAvoidanceCost& rhs) = default; /** * Default destructor */ ~BaseAvoidanceCost() override = default; BaseAvoidanceCost* clone() const override; // overwrite getDerivative methods and return 0 when we know, that they should always return zero void getIntermediateCostDerivativeTime(scalar_t& dLdt) override final; void getIntermediateCostDerivativeInput(input_vector_t& dLdu) override final; void getIntermediateCostSecondDerivativeInput(input_matrix_t& dLduu) override; void getIntermediateCostDerivativeInputState(input_state_matrix_t& dLdux) override; void getTerminalCost(scalar_t& Phi) override final; void getTerminalCostDerivativeTime(scalar_t& dPhidt) override final; void getTerminalCostDerivativeState(state_vector_t& dPhidx) override final; void getTerminalCostSecondDerivativeState(state_matrix_t& dPhidxx) override; protected: /** * Interface method to the intermediate cost function. * * @tparam scalar type. All the floating point operations should be with this type. * @param [in] time: time. * @param [in] state: state vector. * @param [in] input: input vector. * @param [in] stateDesired: desired state vector. * @param [in] inputDesired: desired input vector. * @param [in] logicVariable: logic variable vector. * @param [out] costValue: cost value. */ virtual void intermediateCostFunction(ad_scalar_t time, const ad_dynamic_vector_t& state, const ad_dynamic_vector_t& input, const ad_dynamic_vector_t& parameters, ad_intermediate_cost_vector_t& costValues) const override; /** * Number of parameters for the intermediate cost function. * This number must be remain constant after the model libraries are created * * @return number of parameters */ virtual size_t getNumIntermediateParameters() const override; /** * Number of parameters for the terminal cost function. * This number must be remain constant after the model libraries are created * * @return number of parameters */ virtual size_t getNumTerminalParameters() const override; private: double widthX_ = 0.8; double widthY_ = 0.7; double reach_ = 1.1; double sigma_ = 10; std::shared_ptr<const KinematicsInterface<CppAD::AD<CppAD::cg::CG<double>>>> kinematics_; ad_scalar_t obstacle1D(const ad_scalar_t& x, const double& width) const; ad_scalar_t obstacle2D(const ad_scalar_t& x, const ad_scalar_t& y) const; }; } // namespace perceptive_mpc
37.641892
137
0.755879
[ "vector", "model" ]
78cf88ce899b66769e3323a84b2cc0f7de265960
843
h
C
iris/iris/platform/win32/PlatformDefine-win32.h
pixelsquare/iris-engine-opengl
5b542333f3c3aed9a66f388a6703dc0daa06b3fb
[ "MIT" ]
null
null
null
iris/iris/platform/win32/PlatformDefine-win32.h
pixelsquare/iris-engine-opengl
5b542333f3c3aed9a66f388a6703dc0daa06b3fb
[ "MIT" ]
null
null
null
iris/iris/platform/win32/PlatformDefine-win32.h
pixelsquare/iris-engine-opengl
5b542333f3c3aed9a66f388a6703dc0daa06b3fb
[ "MIT" ]
null
null
null
#ifndef _PLATFORM_DEFINE_WIN32_H_ #define _PLATFORM_DEFINE_WIN32_H_ #include "platform\PlatformConfig.h" #if TARGET_PLATFORM == PLATFORM_WIN32 #ifdef __MINGW32__ #include <string.h> #endif #if defined(IRIS_STATIC) #define IRIS_DLL #else #if defined(_USRDLL) #define IRIS_DLL __declspec(dllexport) #else /* use a DLL library */ #define IRIS_DLL __declspec(dllimport) #endif #endif #include <assert.h> #include <vector> #include <string> #if IRIS_DEBUG <= 0 #define IRIS_ASSERT(cond) #else #define IRIS_ASSERT(cond) assert(cond) #endif #define IRIS_UNUSED_PARAM(unusedparam) (void)unusedparam /* Define NULL pointer value */ #ifndef NULL #ifdef __cplusplus #define NULL 0 #else #define NULL ((void *)0) #endif #endif #endif // TARGET_PLATFORM == PLATFORM_WIN32 #endif // _PLATFORM_DEFINE_WIN32_H_
19.604651
57
0.736655
[ "vector" ]
78d004a70c28dcd519ddd3128b9479bff04c386b
666
h
C
cases/adaptative_surfers/param/env/objects/surfer__us_8o0__surftimeprefactor_3o25/group/homogeneous/_member/agent/_behaviour/_sensor/velocity_gradients/accurate/parameters.h
C0PEP0D/sheld0n
497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc
[ "MIT" ]
null
null
null
cases/adaptative_surfers/param/env/objects/surfer__us_8o0__surftimeprefactor_3o25/group/homogeneous/_member/agent/_behaviour/_sensor/velocity_gradients/accurate/parameters.h
C0PEP0D/sheld0n
497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc
[ "MIT" ]
null
null
null
cases/adaptative_surfers/param/env/objects/surfer__us_8o0__surftimeprefactor_3o25/group/homogeneous/_member/agent/_behaviour/_sensor/velocity_gradients/accurate/parameters.h
C0PEP0D/sheld0n
497d4ee8b6b1815cd5fa1b378d1b947ee259f4bc
[ "MIT" ]
null
null
null
#ifndef C0P_PARAM_OBJECTS_SURFER__US_8O0__SURFTIMEPREFACTOR_3O25_GROUP_HOMOGENEOUS_MEMBER_AGENT_BEHAVIOUR_SENSOR_VELOCITY_GRADIENTS_ACCURATE_PARAMETERS_H #define C0P_PARAM_OBJECTS_SURFER__US_8O0__SURFTIMEPREFACTOR_3O25_GROUP_HOMOGENEOUS_MEMBER_AGENT_BEHAVIOUR_SENSOR_VELOCITY_GRADIENTS_ACCURATE_PARAMETERS_H #pragma once // app includes #include "core/env/objects/object/agent/behaviour/sensor/velocity_gradients/accurate/prop.h" #include "param/parameters.h" namespace c0p { // Accurate flow velocity gradients sensor parameters struct SurferUs8O0Surftimeprefactor3O25GroupHomogeneousMemberAgentBehaviourSensorVelocityGradientsAccurateParameters { }; } #endif
37
153
0.902402
[ "object" ]
78d37783dfe37dc16e62e659381dfa57adc1b46c
1,093
h
C
engine/ui/Table.h
hisoka999/libsgl
1fb0c0cb0f7266b034463c2baa750cc7d3ac5eec
[ "BSD-3-Clause" ]
null
null
null
engine/ui/Table.h
hisoka999/libsgl
1fb0c0cb0f7266b034463c2baa750cc7d3ac5eec
[ "BSD-3-Clause" ]
null
null
null
engine/ui/Table.h
hisoka999/libsgl
1fb0c0cb0f7266b034463c2baa750cc7d3ac5eec
[ "BSD-3-Clause" ]
null
null
null
#pragma once #ifndef UI_TABLE_H #define UI_TABLE_h #include "Object.h" #include <vector> namespace UI { template <typename T> class Table : public Object { public: Table(UI::Object *parent = nullptr); ~Table(); virtual void render(core::Renderer *renderer); // virtual void postRender(core::Renderer *renderer); virtual void handleEvents(core::Input *input); void setData(std::vector<std::shared_ptr<T>> &data) { m_data = data; } void setHeaderNames(const std::vector<std::string> &headerNames); void setElementFunction(size_t col, std::function<std::string(std::shared_ptr<T>)> displayFunction) { m_cellRenderer[col] = displayFunction; } private: /* data */ std::vector<std::shared_ptr<T>> m_data; std::vector<std::string> m_headerNames; std::vector<std::function<std::string(std::shared_ptr<T>)>> m_cellRenderer; SDL_Color m_borderColor; SDL_Color m_headerColor; }; } // namespace UI #endif
24.840909
107
0.613907
[ "render", "object", "vector" ]
78d6c0f4a3540bc8b8db49afc7afe8adeb3ca9c8
12,850
h
C
src/lib/netlist/plib/gmres.h
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/lib/netlist/plib/gmres.h
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/lib/netlist/plib/gmres.h
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Couriersud #ifndef PLIB_GMRES_H_ #define PLIB_GMRES_H_ /// /// \file gmres.h /// #include "parray.h" #include "pconfig.h" #include "pmatrix_cr.h" #include "vector_ops.h" #include <algorithm> namespace plib { template <int k> struct do_khelper { static constexpr bool value = true; }; template <> struct do_khelper<-1> { static constexpr float value = 0.0; }; template <typename FT, int SIZE> struct mat_precondition_ILU { using mat_type = plib::pmatrix_cr<FT, SIZE>; using matLU_type = plib::pLUmatrix_cr<mat_type>; mat_precondition_ILU(std::size_t size, std::size_t ilu_scale = 4 , std::size_t bw = plib::pmatrix_cr<FT, SIZE>::FILL_INFINITY) : m_mat(narrow_cast<typename mat_type::index_type>(size)) , m_LU(narrow_cast<typename mat_type::index_type>(size)) , m_ILU_scale(narrow_cast<std::size_t>(ilu_scale)) , m_band_width(bw) { } template <typename M> void build(M &fill) { m_mat.build_from_fill_mat(fill, 0); m_LU.build(fill, m_ILU_scale); } template<typename R, typename V> void calc_rhs(R &rhs, const V &v) { m_mat.mult_vec(rhs, v); } void precondition() { m_LU.incomplete_LU_factorization(m_mat); } template<typename V> void solve_inplace(V &v) { m_LU.solveLU(v); } PALIGNAS_VECTOROPT() mat_type m_mat; PALIGNAS_VECTOROPT() matLU_type m_LU; std::size_t m_ILU_scale; std::size_t m_band_width; }; template <typename FT, int SIZE> struct mat_precondition_diag { mat_precondition_diag(std::size_t size, int dummy = 0) : m_mat(size) , m_diag(size) , nzcol(size) { plib::unused_var(dummy); } template <typename M> void build(M &fill) { m_mat.build_from_fill_mat(fill, 0); for (std::size_t i = 0; i< m_diag.size(); i++) { for (std::size_t j = 0; j< m_diag.size(); j++) { std::size_t k=m_mat.row_idx[j]; while (m_mat.col_idx[k] < i && k < m_mat.row_idx[j+1]) k++; if (m_mat.col_idx[k] == i && k < m_mat.row_idx[j+1]) nzcol[i].push_back(k); } nzcol[i].push_back(narrow_cast<std::size_t>(-1)); } } template<typename R, typename V> void calc_rhs(R &rhs, const V &v) { m_mat.mult_vec(rhs, v); } void precondition() { for (std::size_t i = 0; i< m_diag.size(); i++) { // ILUT: 265% FT v(0.0); #if 0 // doesn't works, Mame perforamnce drops significantly% // 136% for (std::size_t j = m_mat.row_idx[i]; j< m_mat.row_idx[i+1]; j++) v += m_mat.A[j] * m_mat.A[j]; m_diag[i] = reciprocal(std::sqrt(v)); #elif 0 // works halfway, i.e. Mame perforamnce 50% // 147% - lowest average solution time with 7.094 for (std::size_t j = m_mat.row_idx[i]; j< m_mat.row_idx[i+1]; j++) v += m_mat.A[j] * m_mat.A[j]; m_diag[i] = m_mat.A[m_mat.diag[i]] / v; #elif 0 // works halfway, i.e. Mame perforamnce 50% // sum over column i // 344% - lowest average solution time with 3.06 std::size_t nzcolp = 0; const auto &nz = nzcol[i]; std::size_t j; while ((j = nz[nzcolp++])!=narrow_cast<std::size_t>(-1)) // NOLINT(bugprone-infinite-loop) { v += m_mat.A[j] * m_mat.A[j]; } m_diag[i] = m_mat.A[m_mat.diag[i]] / v; #elif 0 // works halfway, i.e. Mame perforamnce 50% // 151% for (std::size_t j = m_mat.row_idx[i]; j< m_mat.row_idx[i+1]; j++) v += plib::abs(m_mat.A[j]); m_diag[i] = reciprocal(v); #else // 124% for (std::size_t j = m_mat.row_idx[i]; j< m_mat.row_idx[i+1]; j++) v = std::max(v, plib::abs(m_mat.A[j])); m_diag[i] = reciprocal(v); #endif //m_diag[i] = reciprocal(m_mat.A[m_mat.diag[i]]); } } template<typename V> void solve_inplace(V &v) { for (std::size_t i = 0; i< m_diag.size(); i++) v[i] = v[i] * m_diag[i]; } plib::pmatrix_cr<FT, SIZE> m_mat; plib::parray<FT, SIZE> m_diag; plib::parray<std::vector<std::size_t>, SIZE > nzcol; }; template <typename FT, int SIZE> struct mat_precondition_none { mat_precondition_none(std::size_t size, int dummy = 0) : m_mat(size) { plib::unused_var(dummy); } template <typename M> void build(M &fill) { m_mat.build_from_fill_mat(fill, 0); } template<typename R, typename V> void calc_rhs(R &rhs, const V &v) { m_mat.mult_vec(rhs, v); } void precondition() { } template<typename V> void solve_inplace(V &v) { plib::unused_var(v); } plib::pmatrix_cr<FT, SIZE> m_mat; }; // FIXME: hardcoding RESTART to 20 becomes an issue on very large // systems. template <typename FT, int SIZE, int RESTARTMAX = 16> struct gmres_t { public: using float_type = FT; //constexpr static int RESTART = RESTARTMAX; constexpr static const int RESTART = (SIZE > 0) ? ((SIZE < RESTARTMAX) ? SIZE : RESTARTMAX) : ((SIZE < 0) ? ((-SIZE < RESTARTMAX) ? -SIZE : RESTARTMAX) : RESTARTMAX); explicit gmres_t(std::size_t size) : residual(size) , Ax(size) , m_ht(RESTART +1, RESTART) , m_v(RESTART + 1, size) , m_size(size) , m_use_more_precise_stop_condition(false) { } std::size_t size() const { return (SIZE<=0) ? m_size : narrow_cast<std::size_t>(SIZE); } template <typename OPS, typename VT, typename VRHS> std::size_t solve(OPS &ops, VT &x, const VRHS & rhs, const std::size_t itr_max, float_type accuracy) { // ------------------------------------------------------------------------- // The code below was inspired by code published by John Burkardt under // the LPGL here: // // http://people.sc.fsu.edu/~jburkardt/cpp_src/mgmres/mgmres.html // // The code below was completely written from scratch based on the pseudo code // found here: // // http://de.wikipedia.org/wiki/GMRES-Verfahren // // The Algorithm itself is described in // // Yousef Saad, // Iterative Methods for Sparse Linear Systems, // Second Edition, // SIAM, 20003, // ISBN: 0898715342, // LC: QA188.S17. // //------------------------------------------------------------------------ std::size_t itr_used = 0; auto rho_delta(plib::constants<float_type>::zero()); const std::size_t n = size(); ops.precondition(); if (m_use_more_precise_stop_condition) { // derive residual for a given delta x // // LU y = A dx // // ==> rho / accuracy = sqrt(y * y) // // This approach will approximate the iterative stop condition // based |xnew - xold| pretty precisely. But it is slow, or expressed // differently: The invest doesn't pay off. // vec_set_scalar(residual, accuracy); ops.calc_rhs(Ax, residual); ops.solve_inplace(Ax); const float_type rho_to_accuracy = plib::sqrt(vec_mult2<FT>(Ax)) / accuracy; rho_delta = accuracy * rho_to_accuracy; } else //rho_delta = accuracy * plib::sqrt(vec_mult2<FT>(n, rhs)) // + 1e-4 * std::sqrt(n); rho_delta = accuracy * plib::sqrt(narrow_cast<FT>(n)); // // LU x = b; solve for x; // // Using // // vec_set(n, x, rhs); // ops.solve_inplace(x); // // to get a starting point for x degrades convergence speed compared // to using the last solution for x. while (itr_used < itr_max) { float_type rho; ops.calc_rhs(Ax, x); vec_sub(residual, rhs, Ax); ops.solve_inplace(residual); rho = plib::sqrt(vec_mult2<FT>(residual)); if (rho < rho_delta) return itr_used + 1; // FIXME: The "+" is necessary to avoid link issues // on some systems / compiler versions. Issue reported by // AJR, no details known yet. vec_set_scalar(m_g, +constants<FT>::zero()); m_g[0] = rho; vec_mult_scalar(m_v[0], residual, plib::reciprocal(rho)); if (do_k<RESTART-1>(ops, x, itr_used, rho_delta, true)) // converged break; } return itr_used; } private: static void givens_mult(FT c, FT s, FT & g0, FT & g1 ) { const FT g0_last(g0); g0 = c * g0 - s * g1; g1 = s * g0_last + c * g1; } template <int k, typename OPS, typename VT> bool do_k(OPS &ops, VT &x, std::size_t &itr_used, FT rho_delta, bool dummy) { plib::unused_var(dummy); if (do_k<k-1, OPS>(ops, x, itr_used, rho_delta, do_khelper<k-1>::value)) return true; constexpr const std::size_t kp1 = k + 1; //const std::size_t n = size(); ops.calc_rhs(m_v[kp1], m_v[k]); ops.solve_inplace(m_v[kp1]); for (std::size_t j = 0; j <= k; j++) { m_ht[j][k] = vec_mult<FT>(m_v[kp1], m_v[j]); vec_add_mult_scalar(m_v[kp1], m_v[j], -m_ht[j][k]); } m_ht[kp1][k] = plib::sqrt(vec_mult2<FT>(m_v[kp1])); // FIXME: comparison to zero if (m_ht[kp1][k] != plib::constants<FT>::zero()) vec_scale(m_v[kp1], reciprocal(m_ht[kp1][k])); for (std::size_t j = 0; j < k; j++) givens_mult(m_c[j], m_s[j], m_ht[j][k], m_ht[j+1][k]); const float_type mu = reciprocal(plib::hypot(m_ht[k][k], m_ht[kp1][k])); m_c[k] = m_ht[k][k] * mu; m_s[k] = -m_ht[kp1][k] * mu; m_ht[k][k] = m_c[k] * m_ht[k][k] - m_s[k] * m_ht[kp1][k]; m_ht[kp1][k] = plib::constants<FT>::zero(); givens_mult(m_c[k], m_s[k], m_g[k], m_g[kp1]); const float_type rho = plib::abs(m_g[kp1]); // FIXME .. itr_used = itr_used + 1; if (rho <= rho_delta || k == RESTART-1) { // Solve the system H * y = g // x += m_v[j] * m_y[j] for (std::size_t i = k + 1; i-- > 0;) { auto tmp(m_g[i]); const auto htii=plib::reciprocal(m_ht[i][i]); for (std::size_t j = i + 1; j <= k; j++) tmp -= m_ht[i][j] * m_y[j]; m_y[i] = tmp * htii; vec_add_mult_scalar(x, m_v[i], m_y[i]); } //for (std::size_t i = 0; i <= k; i++) // vec_add_mult_scalar(n, x, m_v[i], m_y[i]); return true; } return false; } template <int k, typename OPS, typename VT> bool do_k(OPS &ops, VT &x, std::size_t &itr_used, FT rho_delta, float dummy) { plib::unused_var(ops, x, itr_used, rho_delta, dummy); return false; } plib::parray<float_type, SIZE> residual; plib::parray<float_type, SIZE> Ax; plib::parray<float_type, RESTART + 1> m_c; // mr + 1 plib::parray<float_type, RESTART + 1> m_g; // mr + 1 plib::parray2D<float_type, RESTART + 1, RESTART> m_ht; // (mr + 1), mr plib::parray<float_type, RESTART + 1> m_s; // mr + 1 plib::parray<float_type, RESTART + 1> m_y; // mr + 1 plib::parray2D<float_type, RESTART + 1, SIZE> m_v; // mr + 1, n std::size_t m_size; bool m_use_more_precise_stop_condition; }; #if 0 // Example of a Chebyshev iteration solver. This one doesn't work yet, // it needs to be extended for non-symmetric matrix operation and // depends on spectral radius estimates - which we don't have. // // Left here as another example. template <typename FT, int SIZE> struct ch_t { public: typedef FT float_type; // FIXME: dirty hack to make this compile static constexpr const std::size_t storage_N = plib::sizeabs<FT, SIZE>::ABS(); // Maximum iterations before a restart ... static constexpr const std::size_t restart_N = (storage_N > 0 ? 20 : 0); ch_t(std::size_t size) : residual(size) , Ax(size) , m_size(size) { } std::size_t size() const { return (SIZE<=0) ? m_size : narrow_cast<std::size_t>(SIZE); } template <typename OPS, typename VT, typename VRHS> std::size_t solve(OPS &ops, VT &x0, const VRHS & rhs, const std::size_t iter_max, float_type accuracy) { ops.precondition(); const FT lmax = 20.0; const FT lmin = 0.0001; const FT d = (lmax+lmin)/2.0; const FT c = (lmax-lmin)/2.0; FT alpha = 0; FT beta = 0; std::size_t itr_used = 0; plib::parray<FT, SIZE> x(size()); plib::parray<FT, SIZE> p(size()); plib::vec_set(size(), x, x0); ops.calc_rhs(Ax, x); vec_sub(size(), rhs, Ax, residual); FT rho_delta = accuracy * std::sqrt(narrow_cast<FT>(size())); rho_delta = 1e-9; for (int i = 0; i < iter_max; i++) { ops.solve_inplace(residual); if (i==0) { vec_set(size(), p, residual); alpha = 2.0 / d; } else { beta = alpha * ( c / 2.0)*( c / 2.0); alpha = reciprocal(d - beta); for (std::size_t k = 0; k < size(); k++) p[k] = residual[k] + beta * p[k]; } plib::vec_add_mult_scalar(size(), p, alpha, x); ops.calc_rhs(Ax, x); plib::vec_sub(size(), rhs, Ax, residual); FT rho = std::sqrt(plib::vec_mult2<FT>(size(), residual)); if (rho < rho_delta) break; itr_used++; } return itr_used; } private: //typedef typename plib::mat_cr_t<FT, SIZE>::index_type mattype; plib::parray<float_type, SIZE> residual; plib::parray<float_type, SIZE> Ax; std::size_t m_size; }; #endif } // namespace plib #endif // PLIB_GMRES_H_
24.429658
104
0.597743
[ "vector" ]
78ea851b15f018040252e7b3d781139e0e822015
1,405
h
C
ModuleImgui.h
raulgonzalezupc/FirstAssigment
9193de31049922787da966695340253d84439bf3
[ "MIT" ]
null
null
null
ModuleImgui.h
raulgonzalezupc/FirstAssigment
9193de31049922787da966695340253d84439bf3
[ "MIT" ]
null
null
null
ModuleImgui.h
raulgonzalezupc/FirstAssigment
9193de31049922787da966695340253d84439bf3
[ "MIT" ]
null
null
null
#ifndef _MODULEIMGUI_H_ #define _MODULEIMGUI_H_ #include "Module.h" #include "Globals.h" #include "GameObject.h" #include "Application.h" #include "SDL.h" #include "imgui/imgui.h" #include "imgui/imgui_impl_opengl3.h" #include "imgui/imgui_impl_sdl.h" #include <vector> using namespace std; enum KeyState { KEY_IDLE = 0, KEY_DOWN, KEY_REPEAT, KEY_UP }; class ModuleImgui : public Module { public: ModuleImgui(); virtual ~ModuleImgui(); bool Init(); update_status PreUpdate(); update_status Update(); const void DrawHierarchy(const std::vector<GameObject*>& objects, int & index); update_status PostUpdate(); bool CleanUp(); void AddLog(const char*, ...); void ShowAboutUI(); void ShowConfigurationUI(); public: SDL_GLContext imguiglcontext; //buttons bool menuButton = false; bool consoleButton = true; bool aboutButton = false; bool configButton = false; bool windowButton = false; bool propertiesButton = true; bool google = false; GameObject* sourceGO = nullptr; bool quit = false; unsigned selected = 0; bool showHierarchy = true; int vram_budget, vram_available; KeyState GetMouseButtonDown(int id) const { return mouse_buttons[id - 1]; } SDL_version compiled; SDL_version linked; bool MouseClick(SDL_MouseButtonEvent& b); KeyState mouse_buttons[5]; ImGuiTextBuffer buffer; bool scrollToBottom; vector<float> fps; vector<float> fpsms; }; #endif
18.733333
80
0.74306
[ "vector" ]
78f118a0f8ba1d0f5f441e555e07c35e2dda16da
758
h
C
aws-cpp-sdk-ssm-incidents/include/aws/ssm-incidents/model/ReplicationSetStatus.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-ssm-incidents/include/aws/ssm-incidents/model/ReplicationSetStatus.h
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-ssm-incidents/include/aws/ssm-incidents/model/ReplicationSetStatus.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/ssm-incidents/SSMIncidents_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace SSMIncidents { namespace Model { enum class ReplicationSetStatus { NOT_SET, ACTIVE, CREATING, UPDATING, DELETING, FAILED }; namespace ReplicationSetStatusMapper { AWS_SSMINCIDENTS_API ReplicationSetStatus GetReplicationSetStatusForName(const Aws::String& name); AWS_SSMINCIDENTS_API Aws::String GetNameForReplicationSetStatus(ReplicationSetStatus value); } // namespace ReplicationSetStatusMapper } // namespace Model } // namespace SSMIncidents } // namespace Aws
21.657143
98
0.766491
[ "model" ]
621abd8e2789176752f3e9c5bcc0b32fb842e2f3
7,520
c
C
src/PolyCEID/output/PolyCEID_one_body_electronic_density_matrix.c
lstella77/polyceid
133fbe5aef2fda9d4927244d5bb609adcdb31c61
[ "MIT" ]
null
null
null
src/PolyCEID/output/PolyCEID_one_body_electronic_density_matrix.c
lstella77/polyceid
133fbe5aef2fda9d4927244d5bb609adcdb31c61
[ "MIT" ]
null
null
null
src/PolyCEID/output/PolyCEID_one_body_electronic_density_matrix.c
lstella77/polyceid
133fbe5aef2fda9d4927244d5bb609adcdb31c61
[ "MIT" ]
null
null
null
/****************************************************************************** Copyright (C) 2011-2012 by Lorenzo Stella <lorenzo DOT stella77 AT gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #include "config.h" #include "PolyCEID_one_body_electronic_density_matrix.h" /********************* FUNCTIONS & MACROS *********************/ //BUGFIX: this was originally DEF int compute_one_body_electronic_density_matrix( const constants constants, state_p state_p, config_p config_p ){ /* constanst */ /* state */ matrix_p one_body_electronic_density_matrix_p; matrix_p one_body_electronic_density_matrix_Ehrenfest_p; matrix_p Ehrenfest_frame_p; matrix_p dummy_matrix_single1_p; matrix_p dummy_matrix_single2_p; /* dummies */ int info=0; one_body_electronic_density_matrix_p = &(state_p->one_body_electronic_density_matrix); one_body_electronic_density_matrix_Ehrenfest_p = &(state_p->one_body_electronic_density_matrix_Ehrenfest); Ehrenfest_frame_p = &(config_p->electrons.Ehrenfest_frame); dummy_matrix_single1_p = &(state_p->dummy_matrix_single1); dummy_matrix_single2_p = &(state_p->dummy_matrix_single2); #ifdef __DEBUG_PLUS__ fprintf( stdout, "DOING: compute_one_body_electronic_density_matrix\n" ); #endif /* __DEBUG_PLUS__ */ if( COMPUTE_ONE_BODY_ELECTRONIC_DENSITY_MATRIX_EHRENFEST( constants, *state_p, *config_p ) ) info=1; /* fprintf( stdout, "one_body_electronic_density_matrix_Ehrenfest\n" ); if( MATRIX_PRINT_PLUS( stdout, *one_body_electronic_density_matrix_Ehrenfest_p ) ) info=1; fprintf( stdout, "\n" ); */ if( MATRIX_ADJOINT( *Ehrenfest_frame_p, *dummy_matrix_single1_p ) ) info=1; /* fprintf( stdout, "Ehrenfest_frame\n" ); if( MATRIX_PRINT_PLUS( stdout, *Ehrenfest_frame_p ) ) info=1; fprintf( stdout, "\n" ); fprintf( stdout, "dummy_matrix_single1\n" ); if( MATRIX_PRINT_PLUS( stdout, *dummy_matrix_single1_p ) ) info=1; fprintf( stdout, "\n" ); */ if( MATRIX_MATRIX_PRODUCT( *one_body_electronic_density_matrix_Ehrenfest_p, *dummy_matrix_single1_p, *dummy_matrix_single2_p ) ) info=1; if( MATRIX_MATRIX_PRODUCT( *Ehrenfest_frame_p, *dummy_matrix_single2_p, *one_body_electronic_density_matrix_p ) ) info=1; /* fprintf( stdout, "one_body_electronic_density_matrix\n" ); if( MATRIX_PRINT_PLUS( stdout, *one_body_electronic_density_matrix_p ) ) info=1; fprintf( stdout, "\n" ); */ return info; } //------------------------------------------ /* utilities */ //------------------------------------------ //BUGFIX: this was originally DEF int compute_one_body_electronic_density_matrix_Ehrenfest( const constants constants, state_p state_p, config_p config_p ){ /* constanst */ int N_levels_single; int N_levels_many; imatrix single_level_occupation; imatrix many_body_hybridisation_table; vector symmetry_coefficient; /* state */ matrix_p mu00_p; matrix_p one_body_electronic_density_matrix_Ehrenfest_p; /* dummies */ complex dummy; complex symmetry_coefficient_loc; int level1, level2; int counter; int i, j, k; int index; int info=0; N_levels_single = constants.N_levels_single; N_levels_many = constants.N_levels_many; single_level_occupation = constants.single_level_occupation; many_body_hybridisation_table = constants.many_body_hybridisation_table; symmetry_coefficient = constants.symmetry_coefficient; one_body_electronic_density_matrix_Ehrenfest_p = &(state_p->one_body_electronic_density_matrix_Ehrenfest); mu00_p = &(config_p->electrons.mu00); #ifdef __DEBUG_PLUS__ fprintf( stdout, "DOING: compute_one_body_electronic_density_matrix_Ehrenfest\n" ); #endif /* __DEBUG_PLUS__ */ /* set matrix to zero */ if( MATRIX_ZERO( *one_body_electronic_density_matrix_Ehrenfest_p ) ) info=1; // Important /* set counter to zero */ counter=0; for( i=0; i<N_levels_many; i++ ){ // diagonal terms for( k=0; k<N_levels_single*SPIN_DEG; k++ ){ // fprintf( stdout, "single_level %d, single_level_occupation %d\n", k, single_level_occupation.imatrix[i][ k ] ); if( single_level_occupation.imatrix[i][ k ] ){ level1 = k /SPIN_DEG; // fprintf( stdout, "OK, level1 = %d\n", level1 ); index = ELECTRON_SINGLE_INDEX( level1, level1 ); /* writing */ one_body_electronic_density_matrix_Ehrenfest_p->matrix[ index ] = CMPLX_SUM( one_body_electronic_density_matrix_Ehrenfest_p->matrix[ index ], mu00_p->matrix[ ELECTRON_MANY_INDEX( i, i ) ] ); } /* end conditional */ } /* end k loop */ // off-diagonal terms for( j=(i+1); j<N_levels_many; j++ ){ if( many_body_hybridisation_table.imatrix[counter][0] != i || many_body_hybridisation_table.imatrix[counter][1] != j ){ fprintf( stderr, "ERROR: inconsistency found in many_body_hybridisation_table ordering [%d,%d]\n", i, j ); fflush( stderr ); info=1; } else{ level1 = many_body_hybridisation_table.imatrix[counter][2]; level2 = many_body_hybridisation_table.imatrix[counter][4]; symmetry_coefficient_loc = symmetry_coefficient.vector[counter]; counter++; if( level1 != N_levels_single && level2 != N_levels_single ){ /* writing */ index = ELECTRON_SINGLE_INDEX( level2, level1 ); //WARNING: reverse ordering! dummy = CMPLX_PRODUCT( symmetry_coefficient_loc, mu00_p->matrix[ ELECTRON_MANY_INDEX( j, i ) ] ); one_body_electronic_density_matrix_Ehrenfest_p->matrix[ index ] = CMPLX_SUM( one_body_electronic_density_matrix_Ehrenfest_p->matrix[ index ], dummy ); // index = ELECTRON_SINGLE_INDEX( level1, level2 ); //WARNING: reverse ordering! dummy = CMPLX_PRODUCT( CONJ( symmetry_coefficient_loc ), mu00_p->matrix[ ELECTRON_MANY_INDEX( i, j ) ] ); //WARNING: CONJ here is redondant one_body_electronic_density_matrix_Ehrenfest_p->matrix[ index ] = CMPLX_SUM( one_body_electronic_density_matrix_Ehrenfest_p->matrix[ index ], dummy ); } } /* end conditional */ } /* end j loop */ } /* end i loop */ return info; } //------------------------------------------
32.982456
191
0.676862
[ "vector" ]
621f59461a75c16f161da00c2329b75c6e845644
4,979
h
C
sorting/sorting_algorithms.h
dus7eh/algorithms
dcd3b0a5d6b48d1f4137f3a4304a47b4bd4c6253
[ "MIT" ]
null
null
null
sorting/sorting_algorithms.h
dus7eh/algorithms
dcd3b0a5d6b48d1f4137f3a4304a47b4bd4c6253
[ "MIT" ]
null
null
null
sorting/sorting_algorithms.h
dus7eh/algorithms
dcd3b0a5d6b48d1f4137f3a4304a47b4bd4c6253
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <iterator> #include <map> template <typename T> void bubble_sort(T first, T last) { for (auto outer = first; outer != last; ++outer) { bool sorted = true; for (auto inner = std::next(first); inner != last; ++inner) { auto prev_it = std::prev(inner); if (*prev_it > *inner) { std::swap(*prev_it, *inner); sorted = false; } } if (sorted) break; } } template <typename T> void insertion_sort(T first, T last) { for (auto it = first; it != last; ++it) { auto greater = std::find_if(first, it, [ref = *it](const auto& val) { return val > ref; }); if (greater != it) { const auto val = *it; std::copy_backward(greater, it, std::next(it)); *greater = val; } } } namespace _merge_detail { template <typename T> void merge(T bit, T mit, T eit) { std::vector<T::value_type> res(std::distance(bit, eit)); const auto left_begin = bit; const auto left_end = mit; auto res_it = res.begin(); while (bit != left_end && mit != eit) { if (*bit <= *mit) *(res_it++) = *(bit++); else *(res_it++) = *(mit++); } std::copy(bit, left_end, res_it); std::copy(mit, eit, res_it); std::copy(res.begin(), res.end(), left_begin); } } template <typename T> void merge_sort(T first, T last) { if (std::next(first) != last) { auto mit = std::next(first, std::distance(first, last) / 2); merge_sort<T>(first, mit); merge_sort<T>(mit, last); _merge_detail::merge<T>(first, mit, last); } } template <typename T> void selection_sort(T first, T last) { for (; first != last; ++first) { auto min_it = std::min_element(first, last); if (min_it != last) std::swap(*first, *min_it); } } namespace _shell_detail { int calculate_interval(const size_t len) { auto interval = 1; while (size_t(interval) < len) interval = interval * 3 + 1; return (interval - 1) / 3; } } template <typename T> void shell_sort(T first, T last) { const auto len = std::distance(first, last); if (!len) return; auto interval = _shell_detail::calculate_interval(len); while (interval) { for (auto it = std::next(first, interval); it != last; ++it) { auto curr_it = it; auto prev_it = std::prev(it, interval); while (*prev_it > *curr_it) { std::swap(*prev_it, *curr_it); curr_it = prev_it; if (std::distance(first, prev_it) < interval) break; prev_it = std::prev(prev_it, interval); } } interval /= 3; } } template <typename T> void quick_sort(T first, T last) { const auto len = std::distance(first, last); if (len > 1) { auto piv = std::prev(last); auto lo = first; auto hi = std::prev(piv); while (lo != hi) { if (*lo > *piv && *piv >= *hi) { std::swap(*lo, *hi); continue; } if (*lo <= *piv) ++lo; else if (*piv < *hi) --hi; } if (*piv < *lo) std::swap(*piv, *lo); // to avoid the need of merge stage if (first != lo) quick_sort(first, std::next(lo)); if (hi != std::prev(piv)) quick_sort(hi, std::next(piv)); } } template <typename T, typename Limits = std::numeric_limits<T::value_type>> void counting_sort(T first, T last, const typename T::value_type min = Limits::min(), const typename T::value_type max = Limits::max()) { std::vector<T::value_type> cache(max - min); for (auto it = first; it != last; ++it) { const int& idx = *it - min; ++cache[idx]; } auto curr = first; T::value_type val = 0; for (auto it = cache.cbegin(); it != cache.cend(); ++it) { for (T::value_type i = *it; i != 0; --i) { *curr = val + min; ++curr; } ++val; } } template <typename T> void counting_compact_sort(T first, T last) { std::map<T::value_type, uint32_t> cache; for (auto it = first; it != last; ++it) { const auto found = cache.find(*it); if (found != cache.end()) ++(found->second); else cache[*it] = 1; } auto curr = first; for (auto entry = cache.begin(); entry != cache.end(); ++entry) { std::fill_n(curr, entry->second, entry->first); std::advance(curr, entry->second); } }
29.288235
138
0.486242
[ "vector" ]
621f9d49714e04fe5137b19a1a8b69b59f0fac01
43,058
h
C
D3MkEntityTree/Structure.h
kenjiuno/D3MkEntityTree
7df5492858c1786a1586fa06d25c89b581d8d3ff
[ "IJG" ]
null
null
null
D3MkEntityTree/Structure.h
kenjiuno/D3MkEntityTree
7df5492858c1786a1586fa06d25c89b581d8d3ff
[ "IJG" ]
null
null
null
D3MkEntityTree/Structure.h
kenjiuno/D3MkEntityTree
7df5492858c1786a1586fa06d25c89b581d8d3ff
[ "IJG" ]
null
null
null
// +-------------------------------------------------- // | // | Structure.h // | // | D3MkEntityTree : Copyright (c) 2004, kentaro-k.21 // | #pragma once #include <list> #include <map> #include <set> #include <vector> using namespace std; #include <vfw.h> #include <atlbase.h> #include "My3DMath.h" #include "DM2RPtr.h" #include "Uzz.h" #include "Doom3RP.h" #include "MemVuff.h" class CLL1R { public: // virtual int ReadByte() = NULL; }; class CLL1Memr : public CLL1R { public: // BYTE *pData; // UINT iPos, nMax; // void Init(BYTE *pData, UINT nLen) { this->pData = pData; this->iPos = 0, nMax = nLen; } // virtual int ReadByte() { int r = -1; if (iPos < nMax) { r = pData[iPos]; iPos++; } return r; } }; class CLL1Leader { // CLL1R &fIn; // int iCur; public: // CLL1Leader(CLL1R &f) : fIn(f) , iCur(-1) { } // bool Next() { iCur = fIn.ReadByte(); if (iCur < 0) return false; return true; } // int Cur() { return iCur; } // bool IsEnd() { if (iCur < 0) return true; return false; } }; class CLL1LeaderProxy { // CLL1Leader &f; public: // CLL1LeaderProxy(CLL1Leader &f) : f(f) { } // bool Next() { return f.Next(); } // int Cur() { return f.Cur(); } // bool IsEnd() { return f.IsEnd(); } protected: // CLL1Leader &GetLeader() { return f; } }; struct CDoom3entityDef { // CString strName; // map<CString, CString> m; // list<CString> o; }; struct CDoom3model { // CString strName, strOffset; // map<CString, CString> channels; // map<CString, CString> anims; // map<CString, CString> m; }; typedef map<CString, CDoom3entityDef> CDoom3entityDefMap; typedef map<CString, CDoom3model> CDoom3modelMap; typedef map<CString, CString> VarMap; typedef set<CString> StrSet_t; typedef vector<pair<CString, CString> > SkinMaterialArray; struct CDoom3skin { // CString strName; // VarMap m; // SkinMaterialArray materialArray; // CDoom3skin() { materialArray.reserve(10); } }; typedef map<CString, CDoom3skin> CDoom3skinMap; struct CSymo; typedef vector<CSymo *> SymoArray; struct CSymo { // enum Symo { symoNo, symoDecimal, symoName, symoIndexo, symoAdd2, symoMul2, symoSub2, symoDiv2, symoMod2, symoAdd1, symoSub1, symoOpEqual, symoOpLess, symoOpLEqual, symoOpGreater, symoOpGEqual, symoOpNotEqual, symoOpLAnd, symoOpLOr, }; // Symo symo; // CString strName; // SymoArray var, ops; // CSymo() { } // CSymo(Symo symo) : symo(symo) { } // CSymo(Symo symo, CString str) : symo(symo) , strName(str) { } // CSymo(const CSymo &s) { *this = s; } // const CSymo &operator =(const CSymo &s) { symo = s.symo; strName = s.strName; UINT i; for (i = 0; i < var.size(); i++) { delete var[i]; } var.resize(s.var.size()); for (i = 0; i < var.size(); i++) { var[i] = new CSymo(*s.var[i]); } for (i = 0; i < ops.size(); i++) { delete ops[i]; } ops.resize(s.ops.size()); for (i = 0; i < ops.size(); i++) { ops[i] = new CSymo(*s.ops[i]); } return s; } // ~CSymo() { Close(); } // void Close() { UINT i; for (i = 0; i < var.size(); i++) delete var[i]; var.clear(); for (i = 0; i < ops.size(); i++) delete ops[i]; ops.clear(); } // int Prio() { return Prio(symo); } // static bool IsOp(Symo symo) { switch (symo) { case symoOpEqual: case symoOpLess: case symoOpLEqual: case symoOpGreater: case symoOpGEqual: case symoOpNotEqual: case symoOpLAnd: case symoOpLOr: case symoAdd2: case symoSub2: case symoMul2: case symoDiv2: case symoMod2: case symoAdd1: case symoSub1: return true; } return false; } // static int Prio(Symo symo) { switch (symo) { case symoOpEqual: case symoOpNotEqual: return 7; case symoOpLAnd: case symoOpLOr: return 8; case symoOpLess: case symoOpLEqual: case symoOpGreater: case symoOpGEqual: return 9; case symoAdd2: case symoSub2: return 10; case symoMul2: case symoDiv2: case symoMod2: return 11; case symoAdd1: case symoSub1: return 12; } return -1; } // LPCSTR GetOpName() const { if (symo == symoNo) return "symoNo"; if (symo == symoDecimal) return "symoDecimal"; if (symo == symoName) return "symoName"; if (symo == symoIndexo) return "symoIndexo"; if (symo == symoAdd2) return "symoAdd2"; if (symo == symoMul2) return "symoMul2"; if (symo == symoSub2) return "symoSub2"; if (symo == symoDiv2) return "symoDiv2"; if (symo == symoMod2) return "symoMod2"; if (symo == symoAdd1) return "symoAdd1"; if (symo == symoSub1) return "symoSub1"; if (symo == symoOpEqual) return "symoOpEqual"; if (symo == symoOpLess) return "symoOpLess"; if (symo == symoOpLEqual) return "symoOpLEqual"; if (symo == symoOpGreater) return "symoOpGreater"; if (symo == symoOpGEqual) return "symoOpGEqual"; if (symo == symoOpNotEqual) return "symoOpNotEqual"; if (symo == symoOpLAnd) return "symoOpLAnd"; if (symo == symoOpLOr) return "symoOpLOr"; return "?"; } // bool IsComplexExpression() const { UINT i; for (i = 0; i < var.size(); i++) { CSymo *so = var[i]; switch (so->symo) { case symoName: case symoIndexo: return true; } } return false; } }; typedef list<CSymo> SymoList; typedef enum { texFlat, texAn, // addnormals texHm, // heightmap texMa, // makeAlpha texMi, // makeIntensity texSn, // smoothnormals texAx, // add texSx, // scale texIa, // invertAlpha texDs, // downsize // q4 } Doom3TexMapType; inline LPCSTR GetTexMapTypeName(Doom3TexMapType x) { switch (x) { case texFlat: return "map"; case texAn: return "addnormals"; case texHm: return "heightmap"; case texMa: return "makeAlpha"; case texMi: return "makeIntensity"; case texSn: return "smoothnormals"; case texAx: return "add"; case texSx: return "scale"; case texIa: return "invertAlpha"; } return "?"; } struct CDoom3materialTex { // Doom3TexMapType tt; // CString strFlat, strAn, strHm, strMa, strMi; // float fHmV; }; typedef enum { bfNo, bfDstAlpha, bfDstColor, bfOne, bfOneMinusDstAlpha, bfOneMinusDstColor, bfOneMinusSrcAlpha, bfOneMinusSrcColor, bfSrcColor, bfZero, bfSrcAlpha, bfNone, // q4 bfBlend, bfAdd, bfBumpMap, bfDiffuseMap, bfSpecularMap, bfFilter, bfDownSize, // q4 } Doom3Blendf; inline LPCSTR GetBlendfName(Doom3Blendf x) { switch (x) { case bfNo: return "bfNo"; case bfDstAlpha: return "bfDstAlpha"; case bfDstColor: return "bfDstColor"; case bfOne: return "bfOne"; case bfOneMinusDstAlpha: return "bfOneMinusDstAlpha"; case bfOneMinusDstColor: return "bfOneMinusDstColor"; case bfOneMinusSrcAlpha: return "bfOneMinusSrcAlpha"; case bfOneMinusSrcColor: return "bfOneMinusSrcColor"; case bfSrcColor: return "bfSrcColor"; case bfZero: return "bfZero"; case bfSrcAlpha: return "bfSrcAlpha"; case bfBlend: return "bfBlend"; case bfAdd: return "bfAdd"; case bfBumpMap: return "bfBumpMap"; case bfDiffuseMap: return "bfDiffuseMap"; case bfSpecularMap: return "bfSpecularMap"; case bfFilter: return "bfFilter"; } return "?"; } struct CDoom3FlatIma { // SizeBuff fv; // UINT cx, cy; // WORD nBitCount, nPitch; // DWORD nDataLen; // BYTE *pData; // CDoom3FlatIma() { Close(); } // bool Create(const CDoom3FlatIma &s); // bool Create(UINT cx, UINT cy, WORD nBitCount); // void Close(); // BYTE *GetVert(UINT y); // CDoom3FlatIma(const CDoom3FlatIma &s) { *this = s; } // const CDoom3FlatIma &operator =(const CDoom3FlatIma &s); }; struct CDoom3materialTexoMap { // Doom3TexMapType tt; // CString strName; // size_t x0, x1; // float v0, v1, v2, v3; }; struct CDoom3materialTexo : vector<CDoom3materialTexoMap> { // size_t iFirst; }; namespace MaterialTexo { struct TexoTex { // virtual bool LoadIma(CString strName, CDoom3FlatIma &rIma) = NULL; }; class TexoEval { // struct Error { }; // TexoTex &rTex; // CDoom3materialTexo &mt; // bool eval(size_t i, CDoom3FlatIma &rIma); public: // TexoEval(TexoTex &rTex, CDoom3materialTexo &mt) : rTex(rTex), mt(mt) { } // bool Eval(CDoom3FlatIma &rIma); }; }; struct CDoom3materialIndent { // VarMap m; // Doom3Blendf bf1, bf2; // CSymo soAlphaTest, soIf, so_scale, so_translate, so_rotate; // CDoom3materialTexo tex; // CDoom3materialIndent() : bf1(bfNo), bf2(bfNo) { } // static bool Parse_blendf1(CString strValue, Doom3Blendf &bf) { if (false); else if (strValue == "none") bf = bfNone; else if (strValue == "blend") bf = bfBlend; else if (strValue == "add") bf = bfAdd; else if (strValue == "bumpmap") bf = bfBumpMap; else if (strValue == "diffusemap") bf = bfDiffuseMap; else if (strValue == "specularmap") bf = bfSpecularMap; else if (strValue == "filter") bf = bfFilter; else return false; return true; } // static bool Parse_blendf2(CString strValue, Doom3Blendf &bf) { if (false); else if (strValue == "gl_dst_alpha") bf = bfDstAlpha; else if (strValue == "gl_dst_color") bf = bfDstColor; else if (strValue == "gl_one") bf = bfOne; else if (strValue == "gl_one_minus_dst_alpha") bf = bfOneMinusDstAlpha; else if (strValue == "gl_one_minus_dst_color") bf = bfOneMinusDstColor; else if (strValue == "gl_one_minus_src_alpha") bf = bfOneMinusSrcAlpha; else if (strValue == "gl_one_minus_src_color") bf = bfOneMinusSrcColor; else if (strValue == "gl_src_color") bf = bfSrcColor; else if (strValue == "gl_zero") bf = bfZero; else if (strValue == "gl_src_alpha") bf = bfSrcAlpha; else return false; return true; } }; typedef vector<CDoom3materialIndent> CDoom3materialIndentArray; struct CDoom3material { // CString strName; // VarMap m; // CDoom3materialIndentArray v; }; typedef map<CString, CDoom3material> CDoom3materialMap; typedef map<CString, CString> InheritMap; typedef multimap<CString, CString> ReverseInheritMap; typedef set<CString> NameSet; typedef vector<float> DecimalArray; struct CDoom3table { // int m; // bool fSnap, fClamp; // DecimalArray vec; // CDoom3table() { m = 0; fSnap = fClamp = false; } // float Eval(float x); }; typedef map<CString, CDoom3table> CDoom3tableMap; typedef enum { gsDoom3, gsQuake4, } GameSel; struct CDoom3Workpad { // CDoom3entityDefMap entityDefMap; // CDoom3modelMap modelMap; // InheritMap inheritMap; // InheritMap inheritModelMap; // ReverseInheritMap rinheritMap; // CDoom3skinMap skinMap; // CDoom3materialMap materialMap; // NameSet mapobjsNames; // CDoom3tableMap tableMap; // GameSel gs; // void CompleteInherit(CDoom3entityDef &entityDef); // void CompleteInherit(CDoom3model &model); // void Close() { entityDefMap.clear(); modelMap.clear(); inheritMap.clear(); inheritModelMap.clear(); rinheritMap.clear(); skinMap.clear(); materialMap.clear(); mapobjsNames.clear(); tableMap.clear(); } // bool Q4() { return (gs == gsQuake4); } // CDoom3table *FindTable(CString strName) { CDoom3tableMap::iterator iterPos = tableMap.find(strName), iterEnd = tableMap.end(); if (iterPos != iterEnd) return &iterPos->second; return NULL; } }; struct CDoom3ContWorkpad { // NameSet entityDefExport, mapobjsExport; // bool fOnly_entityDef, fOnly_mapobjs; }; class CSparseBase : public CLL1LeaderProxy { public: // CSparseBase(CLL1Leader &f) : CLL1LeaderProxy(f) { } protected: // class Error { }; // void KillMe() { throw Error(); // CSparseBase } // bool SkipWs(); // bool IsWs(); // bool IsLineBReak(); // bool IsSPC(); // bool IsInlineComment(); // void ReadTextQuoted(CString &strText); // void ForceMatch(char c, bool fSkipAlWs = true); // bool IsMatch(char c, bool fSkipAlWs = true); // bool IsMatchFinally(char c, bool fSkipAlWs = true); // bool SkipAlWsComment(); // bool ReadTexto(CString &strText); // bool ReadDecimalo(CString &strText); // bool SkipMidBracketContext(); // bool SkipTokensUntilMidBracket(); // void SkipTokensUntilLf(); // void ReadInlineTexto(CString &strText); // void ForceReadTexto(CString &strText); // bool ReadTextTokens(CString &strText); // void Force1(bool fIf) { if (!fIf) KillMe(); } // static bool ParseInt(CString &strValue, int &nValue) { char *psz = NULL; nValue = strtol(strValue, &psz, 10); return psz && (*psz == 0); } // static bool ParseFloat(CString &strValue, float &fValue) { char *psz = NULL; fValue = (float)strtod(strValue, &psz); return psz && (*psz == 0); } }; class CSparseDef : public CSparseBase { // CDoom3Workpad &wk; // void KillMe() { CSparseBase::KillMe(); // CSparseDef } // bool ReadText1(CString &strText, bool fQuotedCondOk = false); // void Parse_entityDef(); // void Parse_model(); // bool ReadText2(CString &strText, bool fQuotedCondOk = false); // void ReadTextBracketInside(CString &strText); // bool ReadText3(CString &strText); // void Parse_sound(); // void Parse_export(); // bool ReadText4(CString &strText); // void Parse_mapDef(); // void Parse_any(); // void Parse_skin(); // void Parse_material(CString strName); // void Parse_indent(CDoom3materialIndentArray &v); // void Parse_table(); // void Parse_guide(); // void Parse_camera(); // void Parse_map(CDoom3materialTexo &tex); // bool Q4() { return wk.Q4(); } public: // CSparseDef(CLL1Leader &fIn, CDoom3Workpad &wk) : CSparseBase(fIn) , wk(wk) { } // bool Parse(); }; struct CMD5AnimFrameBasis { // My3DMath::Vtx3 o, q; // My3DMath::Mtx m; }; struct CMD5AnimJoint { // CString strName; // int iJointRef, nFlags, iVarIndex; }; struct CMD5AnimFramePatch : CMD5AnimFrameBasis { }; typedef vector<CMD5AnimFramePatch> MD5AnimFramePatchArray; typedef vector<CMD5AnimJoint> MD5AnimJointArray; typedef vector<MD5AnimFramePatchArray> MD5AnimFrameArray; struct CMD5AnimDeck { // MD5AnimJointArray joints; // MD5AnimFrameArray frames; // MD5AnimFramePatchArray baseframe; // int nFrameRate; // int nAnimatedComp; // MD5AnimFramePatchArray basejoint; // bool basejointAvail; // CMD5AnimDeck() { basejointAvail = false; } }; class CSparseMD5Anim : public CSparseBase { // CMD5AnimDeck &anim; // void Parse_hierarchy(); // void Parse_bounds(); // void Parse_baseframe(); // void Parse_frame(); // void ReadVtx3(My3DMath::Vtx3 &v); public: // CSparseMD5Anim(CLL1Leader &fIn, CMD5AnimDeck &anim) : CSparseBase(fIn) , anim(anim) { } // bool Parse(); }; namespace NfMD5 { struct MD5MeshJoint_t { // MD5MeshJoint_t *pRefJ; // CString strName; // My3DMath::Vtx3 o; // My3DMath::Quatern q; // int iJ; }; struct MD5MeshWeight_t { // MD5MeshJoint_t *pJ; // My3DMath::Vtx3 o; // float nMass; // int iJ; }; typedef vector<MD5MeshWeight_t *> MD5MeshWeightPtrArray_t; struct MD5MeshVert_t { // MD5MeshWeightPtrArray_t ppW; // My3DMath::Vtx2 o; // int iW, nW; }; struct MD5MeshTri_t { // MD5MeshVert_t *pV[3]; // int iV[3]; }; typedef vector<MD5MeshJoint_t> MD5MeshJointArray_t; typedef vector<MD5MeshWeight_t> MD5MeshWeightArray_t; typedef vector<MD5MeshVert_t> MD5MeshVertArray_t; typedef vector<MD5MeshTri_t> MD5MeshTriArray_t; struct MD5MeshModel_t { // MD5MeshWeightArray_t aW; // MD5MeshVertArray_t aV; // MD5MeshTriArray_t aT; // CString strShader; }; typedef vector<MD5MeshModel_t> MD5MeshModelArray_t; struct MD5MeshDeck_t { // MD5MeshJointArray_t aJ; // MD5MeshModelArray_t aM; }; struct MD5AnimBound_t { // My3DMath::Vtx3 vmin, vmax; }; struct MD5AnimPatch_t { // My3DMath::Vtx3 o, p; // My3DMath::Quatern q; }; typedef vector<MD5AnimPatch_t> MD5AnimFrame_t; struct MD5AnimJoint_t { // CString strName; // MD5AnimJoint_t *pRefJ; // int f6; // int iRefJ; }; typedef vector<MD5AnimBound_t> MD5AnimBoundArray_t; typedef vector<MD5AnimFrame_t> MD5AnimFrameArray_t; typedef vector<MD5AnimJoint_t> MD5AnimJointArray_t; struct MD5AnimDeck_t { // MD5AnimBoundArray_t bounda; // MD5AnimFrameArray_t framea; // MD5AnimJointArray_t jointa; // MD5AnimFrame_t baseframe; // int nFrameRate, nAnimatedComp; }; class ParseMD5Mesh_t : public CSparseBase { // MD5MeshDeck_t &mesh; // UINT iCurMesh; // void Parse_joints(); // void ReadVtx3(My3DMath::Vtx3 &v); // void ReadVtx2(My3DMath::Vtx2 &v); // void Parse_mesh(); public: // ParseMD5Mesh_t(CLL1Leader &fIn, MD5MeshDeck_t &mesh) : CSparseBase(fIn) , mesh(mesh) { } // bool Parse(); }; class ParseMD5Anim_t : public CSparseBase { // MD5AnimDeck_t &anim; // void Parse_hierarchy(); // void Parse_bounds(); // void Parse_baseframe(); // void Parse_frame(); // void ReadVtx3(My3DMath::Vtx3 &v); public: // ParseMD5Anim_t(CLL1Leader &fIn, MD5AnimDeck_t &anim) : CSparseBase(fIn) , anim(anim) { } // bool Parse(); }; }; struct CMD5MeshJoint { // CString strName; // int iJointRef; // CMD5AnimFrameBasis ok; }; struct CMD5MeshMeshVert { // My3DMath::Vtx2 o; // int iWeight, nWeights; }; struct CMD5MeshMeshTri { // int v[3]; }; struct CMD5MeshMeshWeight { // int iJoint; // float nMass; // My3DMath::Vtx3 o; }; typedef vector<CMD5MeshMeshVert> MD5MeshMeshVertArray; typedef vector<CMD5MeshMeshTri> MD5MeshMeshTriArray; typedef vector<CMD5MeshMeshWeight> MD5MeshMeshWeightArray; typedef vector<CMD5MeshJoint> MD5MeshJointArray; struct CMD5MeshMesh { // VarMap m; // MD5MeshMeshVertArray verts; // MD5MeshMeshTriArray tris; // MD5MeshMeshWeightArray weights; // CMD5MeshMesh() { } // void InterpolateVertex(MD5MeshJointArray &j, UINT iVert, My3DMath::Vtx3 &v); }; typedef vector<CMD5MeshMesh> MD5MeshMeshArray; struct CMD5MeshDeck { // MD5MeshJointArray joints; // MD5MeshMeshArray meshes; // CMD5AnimFrameBasis basejoint; // bool basejointAvail; // CMD5MeshDeck() { basejointAvail = false; } }; class CSparseMD5Mesh : public CSparseBase { // CMD5MeshDeck &mesh; // UINT iCurMesh; // void Parse_joints(); // void ReadVtx3(My3DMath::Vtx3 &v); // void ReadVtx2(My3DMath::Vtx2 &v); // void Parse_mesh(); public: // CSparseMD5Mesh(CLL1Leader &fIn, CMD5MeshDeck &mesh) : CSparseBase(fIn) , mesh(mesh) { } // bool Parse(); }; class CSparseSkin : public CSparseBase { // CDoom3Workpad &wk; // void Parse_skin(); public: // CSparseSkin(CLL1Leader &fIn, CDoom3Workpad &wk) : CSparseBase(fIn) , wk(wk) { } // bool Parse(); }; typedef CDM2SPtr<Uzz::CUzz> CUzzPtr; class CUzzExtractor { public: // CUzzPtr pUz; // UINT iEntry; // virtual bool GetData(SizeBuff &sb) { return pUz->Ex(iEntry, sb); } }; class IFileEntity : public IRCI { public: // virtual CString GetPath() = NULL; // virtual bool GetData(SizeBuff &fv) = NULL; // virtual bool GetModifiedTime(FILETIME &ft) = NULL; }; typedef CDM2SPtr<IFileEntity> CFileEntryPtr; class COSFileEntity : public CRCI, public IFileEntity { // CString strFile, strPath; public: // COSFileEntity(LPCTSTR psz, LPCTSTR pszPath) { strFile = psz; strPath = pszPath; } // virtual CString GetPath() { return strPath; } // virtual bool GetData(SizeBuff &fv) { CFile fileIn; ULONGLONG nLen64; int nLen; if (true && fileIn.Open(strFile, 0 |CFile::modeRead |CFile::shareDenyWrite) && (nLen64 = fileIn.GetLength(), nLen = (int)nLen64, nLen64 < 1024*1024*10) && fv.Alloc(nLen) && fileIn.Read(fv.GetData(), nLen) == nLen ) { return true; } return false; } // virtual bool GetModifiedTime(FILETIME &ft) { CFile fileIn; if (true && fileIn.Open(strFile, 0 |CFile::modeRead) && GetFileTime(fileIn.m_hFile, NULL, NULL, &ft) ) { return true; } return false; } // virtual LONG AddRef() { return CRCI::AddRef(); } // virtual LONG Release() { return CRCI::Release(); } }; class CZipFileEntity : public CRCI, public IFileEntity { // CString strPath; // CUzzExtractor ze; // FILETIME ft; public: // CZipFileEntity(const CUzzExtractor &ze, const FILETIME &ft) : ze(ze), ft(ft) { } // virtual CString GetPath() { return strPath; } // virtual bool GetData(SizeBuff &sb) { return ze.GetData(sb); } // virtual bool GetModifiedTime(FILETIME &ft) { ft = this->ft; return true; } // virtual LONG AddRef() { return CRCI::AddRef(); } // virtual LONG Release() { return CRCI::Release(); } }; typedef map<CString, CFileEntryPtr> CEntryMap; class CHtmlMkThumb2 { public: // FILE *f; // int iCol; // int iTable; // CHtmlMkThumb2() { Reset(); } // void Reset() { f = NULL; iCol = -1; } // void MkHead(bool fHead); // void MkTableHead(bool fHead, LPCTSTR pszName = NULL); // void AddThumb(CString strName, CString strHref, CString strHrefThere); }; class CAviMk { // CComPtr<IAVIFile> pAvif; // CComPtr<IAVIStream> pAvisVid; // bool fUseComp, fCont; // UINT iCurFrame; // COMPVARS cv; // BITMAPINFO bi; // UINT nSizeImage; // CString strAvif; public: // CAviMk() { ZeroMemory(&cv, sizeof(cv)); } // ~CAviMk() { Close(); } // bool Create(CString strAvi, int nFrameRate, CSize size); // void Close(bool fOk = false); // bool AddFrame(void *pvData); // UINT GetSizeImage() const { return nSizeImage; } }; struct CSym { // enum Sym { symNo, symDecimal, // 0.0 .0 1. symIndexo, // [ symIndexc, // ] symBracketo,// ( symBracketc,// ) symAdd, // + symMul, // * symSub, // - symDiv, // / symMod, // % symOpLess, // < symOpLEqual, // <= symOpGreater, // > symOpGEqual, // >= symComma, // , symName, // parm7 symOpEqual, // == symOpNotEqual, // != symOpLAnd, // && symOpLOr, // || }; // Sym sym; // CString strName; // CSym() { } // CSym(Sym sym) : sym(sym) { } // bool IsValue() const { switch (sym) { case symDecimal: case symName: return true; } return false; } // bool IsOp1() const { switch (sym) { case symAdd: case symSub: return true; } return false; } // bool IsOp2() const { switch (sym) { case symAdd: case symMul: case symSub: case symDiv: case symMod: case symOpLess: case symOpLEqual: case symOpGreater: case symOpGEqual: case symOpEqual: case symOpNotEqual: case symOpLAnd: case symOpLOr: return true; } return false; } // LPCSTR GetOpName() const { if (sym == symNo) return "symNo"; if (sym == symDecimal) return "symDecimal"; if (sym == symIndexo) return "symIndexo"; if (sym == symIndexc) return "symIndexc"; if (sym == symBracketo) return "symBracketo"; if (sym == symBracketc) return "symBracketc"; if (sym == symAdd) return "symAdd"; if (sym == symMul) return "symMul"; if (sym == symSub) return "symSub"; if (sym == symDiv) return "symDiv"; if (sym == symMod) return "symMod"; if (sym == symOpLess) return "symOpLess"; if (sym == symOpLEqual) return "symOpLEqual"; if (sym == symOpGreater) return "symOpGreater"; if (sym == symOpGEqual) return "symOpGEqual"; if (sym == symComma) return "symComma"; if (sym == symName) return "symName"; if (sym == symOpEqual) return "symOpEqual"; if (sym == symOpNotEqual) return "symOpNotEqual"; if (sym == symOpLAnd) return "symOpLAnd"; if (sym == symOpLOr) return "symOpLOr"; return "?"; } }; typedef list<CSym> SymList; class CSparseExpr : public CSparseBase { // CSym sym; // bool ParseToken(); // void Parse_decimal(); // void Parse_name(); // bool Next(bool fAccum = true); // static inline bool Is_Name(int a) { if (a == '_' || a == '.' || ('0' <= a && a <= '9') || ('a' <= a && a <= 'z') || ('A' <= a && a <= 'Z')) return true; return false; } public: // CSparseExpr(CLL1Leader &f) : CSparseBase(f) { } // bool Parse(SymList &syms); }; class CExprBinder { // struct Error { }; // SymList &syms; // SymList::iterator iterPos, iterEnd; // SymoArray *sa; // bool IsEnd() { return iterPos == iterEnd; } // bool Next() { if (IsEnd()) return false; iterPos++; return true; } // const CSym &Cur() { return *iterPos; } // void KillMe() { throw Error(); // CExprBinder } // void Parse_1(CSym::Sym symEnd, bool fRoot = false); // void Parse_op1(); // void Parse_op2(); // void Parse_value(); // void AddSymo_ops(CSymo::Symo symo) { CSymo *p1 = new CSymo(symo); CSymo *p0 = sa->back(); while (p0->ops.size() != 0) { int v1 = p0->ops.back()->Prio(); int v2 = p1->Prio(); if (v1 < v2) break; p0->var.push_back(p0->ops.back()); p0->ops.pop_back(); } sa->back()->ops.push_back(p1); } // void AddSymo_var(CSymo::Symo symo) { CSymo *p = new CSymo(symo, Cur().strName); sa->back()->var.push_back(p); } // void AddSymo_var(CSymo::Symo symo, CSym sym) { CSymo *p = new CSymo(symo, sym.strName); sa->back()->var.push_back(p); } // void AddSymo_indexo(CSym sym) { CSymo *p = sa->back(); sa->pop_back(); p->symo = CSymo::symoIndexo; p->strName = sym.strName; sa->back()->var.push_back(p); } // void AddSymo_bracketo() { CSymo *p = sa->back(); sa->pop_back(); sa->back()->var.insert(sa->back()->var.end(), p->var.begin(), p->var.end()); p->var.clear(); delete p; } // void EndSymo() { CSymo *p = sa->back(); for (; p->ops.size() != 0; p->ops.pop_back()) p->var.push_back(p->ops.back()); } public: // CSymo so; // CExprBinder(SymList &syms) : syms(syms) { } // ~CExprBinder() { Close(); } // void Close(); // bool Parse(); // void Printo(); // void Printo(SymoArray &sa, int f); }; namespace EvalOp { #define EPS 1E-5 inline double Add1(double v1) { return +v1; } inline double Sub1(double v1) { return -v1; } inline double Add2(double v1, double v2) { return v1 + v2; } inline double Mul2(double v1, double v2) { return v1 * v2; } inline double Sub2(double v1, double v2) { return v1 - v2; } inline double Div2(double v1, double v2) { return v1 / v2; } inline double Mod2(double v1, double v2) { return fmod(v1, v2); } inline double OpEqual(double v1, double v2) { return fabs(v1 - v2) < EPS; } inline double OpLess(double v1, double v2) { return v1 < v2; } inline double OpLEqual(double v1, double v2) { return v1 <= v2; } inline double OpGreater(double v1, double v2) { return v1 > v2; } inline double OpGEqual(double v1, double v2) { return v1 >= v2; } inline double OpNotEqual(double v1, double v2) { return fabs(v1 - v2) > EPS; } inline double OpLAnd(double v1, double v2) { return (int)v1 && (int)v2; } inline double OpLOr(double v1, double v2) { return (int)v1 || (int)v2; } }; class CEvalSampler { public: // virtual float EvalTable(CString strName, float x) { return 0; }; // virtual float EvalNameo(CString strName) { return 0; } }; class CEvalExpr { // struct Error { }; // CEvalSampler &evalTable; // CEvalSampler &evalNameo; // void KillMe() { throw Error(); // CEvalExpr } // void eval(SymoArray &sa); public: // vector<double> vals; // CEvalExpr(CEvalSampler &eval) : evalTable(eval) , evalNameo(eval) { } // bool Eval(SymoArray &sa); // bool Eval(CSymo &so, UINT iIdx); // bool EvalIndexo(CSymo &so); }; class CSparseMapExpr : public CSparseBase { // CDoom3materialTexo &mt; // size_t Parse_map(); public: // CSparseMapExpr(CLL1Leader &f, CDoom3materialTexo &mt) : CSparseBase(f) , mt(mt) { } // bool Parse(); }; struct CLWO2MeshVertex { // My3DMath::Vtx3 v; // My3DMath::Vtx2 vt0; // CLWO2MeshVertex() { v.Empty(); vt0.Empty(); } }; typedef vector<CLWO2MeshVertex> LWO2MeshVertexArray; struct CLWO2MeshPolyMap { // DWORD v, vt0; }; struct CLWO2MeshPoly { // vector<CLWO2MeshPolyMap> verts; // WORD texture; }; typedef vector<CLWO2MeshPoly> LWO2MeshPolyArray; struct CLWO2MeshVertexPatchKey { // DWORD vert, poly; // bool operator <(const CLWO2MeshVertexPatchKey &s) const { if (vert < s.vert) return true; if (vert > s.vert) return false; if (poly < s.poly) return true; if (poly > s.poly) return false; return false; }; }; struct CLWO2MeshVertexPatchVal { // My3DMath::Vtx2 vt0; }; typedef map<CLWO2MeshVertexPatchKey, CLWO2MeshVertexPatchVal> LWO2MeshVertexPatchMap; typedef vector<CString> LWO2MeshTexArray; struct CLWO2MeshDeck { // LWO2MeshVertexArray av; // LWO2MeshPolyArray ap; // LWO2MeshTexArray at0; }; class CSparseLWO2 : public CMemVuff { // struct Error { }; // CLWO2MeshDeck &mesh; // void KillMe() { throw Error(); } // void Read4(DWORD &x4) { if (!ReadDWord(x4)) KillMe(); } // void Read4(float &x4) { if (!ReadDWord((DWORD &)x4)) KillMe(); } // void Read4r(DWORD &x4) { if (!SurelyReadBytes(&x4, 4)) KillMe(); } // void Sure4r(DWORD x4) { DWORD x; Read4r(x); if (x != x4) KillMe(); } // void Skip1() { BYTE x; if (!ReadByte(x)) KillMe(); } // void Skip(UINT v) { if (!SurelySkipBytes(v)) KillMe(); } // void Parse_1(); // bool IsEnd() { return (iData == nData); } // void ReadVtx3(My3DMath::Vtx3 &v3) { Read4(v3.x); Read4(v3.y); Read4(v3.z); } // void ReadVtx2(My3DMath::Vtx2 &v2) { Read4(v2.x); Read4(v2.y); } // void ReadX(DWORD &x) { WORD x0; Read2(x0); if (0xFF00 < x0) { WORD x1; Read2(x1); x = MAKELONG(x1, x0); } else { x = x0; } } // void Read2(WORD &x2) { if (!ReadWord(x2)) KillMe(); } // void Sure2(WORD x2) { WORD x; Read2(x); if (x != x2) KillMe(); } // void ReadName() { CString str; ReadName(str); } // void ReadName(CString &strName) { strName.Empty(); UINT i = 0; for (; ; ) { BYTE x; Read1(x); i++; if (x == 0) break; strName += (char)x; } if (i & 1) { Skip1(); } } // void Read1(BYTE &x) { if (!ReadByte(x)) KillMe(); } public: // CSparseLWO2(CLWO2MeshDeck &mesh) : mesh(mesh) { } // bool Parse(); }; struct CAseMeshVertex { // My3DMath::Vtx3 v; }; typedef vector<CAseMeshVertex> AseMeshVertexArray; struct CAseMeshFace { // DWORD v[3], tf[3]; // WORD tex0; // CAseMeshFace() { tex0 = 0; } }; typedef vector<CAseMeshFace> AseMeshFaceArray; struct CAseMeshTVert { // My3DMath::Vtx2 vt0; }; typedef vector<CAseMeshTVert> AseMeshTVertArray; struct CAseMeshMaterial { // CString strTex; }; typedef vector<CAseMeshMaterial> AseMeshMaterialArray; struct CAseMeshGEOM { // AseMeshVertexArray mva; // AseMeshFaceArray mfa; // AseMeshTVertArray mtva; }; inline void swap(CAseMeshGEOM &r0, CAseMeshGEOM &r1) { r0.mva.swap(r1.mva); r0.mfa.swap(r1.mfa); r0.mtva.swap(r1.mtva); } typedef vector<CAseMeshGEOM> AseMeshGEOMArray; struct CAseMeshDeck { // AseMeshMaterialArray mma; // AseMeshGEOMArray mza; }; class CSparseASE : public CSparseBase { // CAseMeshDeck &mesh; // void KillMe() { CSparseBase::KillMe(); // CSparseASE } // void Parse_1(); // void ReadLeadTexto(CString &str) { ForceMatch('*', false); if (!ReadTexto(str)) KillMe(); } // void Parse_GEOMOBJECT(); // void Parse_MESH(); // void Parse_MATERIAL_LIST(); // bool ReadNameo(CString &strText); // void SkipAny(int nLv = 0); public: // CSparseASE(CLL1Leader &fIn, CAseMeshDeck &mesh) : CSparseBase(fIn) , mesh(mesh) { } // bool Parse(); }; class CTextPlainMk { public: // bool Open(LPCSTR psz) { Close(); if (f = fopen(psz, "wt")) { return true; } return false; } // void Close() { if (f) fclose(f), f = NULL; } protected: // FILE *f; // CTextPlainMk() { f = NULL; } // ~CTextPlainMk() { Close(); } }; class CHwsMan { public: // virtual CString gethhp() { return "D3hhp.hhp"; } // virtual CString gethhc() { return "D3hhp.hhc"; } // virtual CString gethhk() { return "D3hhp.hhk"; } // virtual UINT getindexres(); // virtual UINT gethhpres(); }; class CHwsManq4 : public CHwsMan { // virtual CString gethhp() { return "Q4hhp.hhp"; } // virtual CString gethhc() { return "Q4hhp.hhc"; } // virtual CString gethhk() { return "Q4hhp.hhk"; } // virtual UINT getindexres(); // virtual UINT gethhpres(); }; namespace MSHPP { class CHHKMk : public CTextPlainMk { public: // void MkHeader(bool fHeader = true); // void StartKw(LPCSTR pszDispName); // void WriteKwHref(LPCSTR pszDispAlt, LPCSTR pszHref); // void EndKw(); }; class CHHPMk : public CTextPlainMk { // CHwsMan &rhw; public: // CHHPMk(CHwsMan &rhw): rhw(rhw) { } // bool Mk(LPCSTR pszFiles); }; class CHHCMk : public CTextPlainMk { public: // void MkHeader(bool fHeader = true); // void StartDir(LPCSTR pszDispName, LPCSTR pszHref); // void WriteItem(LPCSTR pszDispName, LPCSTR pszHref); // void EndDir(); }; class CHHKTemplate { // typedef multimap<CString, CString> KwMMap; // KwMMap kmm; public: // void AddKw(CString pszKw, CString pszHref) { kmm.insert(make_pair(pszKw, pszHref)); } // bool Commit(CHHKMk &mk); }; class CHHCTemplate { // typedef multimap<CString, CString> KwMMap; // KwMMap km_entityDef, km_Mapobject; public: // void Add_entityDef(CString strName, CString strHref) { km_entityDef.insert(make_pair(strName, strHref)); } // void Add_Mapobject(CString strName, CString strHref) { km_Mapobject.insert(make_pair(strName, strHref)); } // bool Commit(CHHCMk &mk); }; class CHHPTemplate { // typedef list<CString> FileList; // FileList files; public: // void AddHtml(CString strHref, bool fIs_entityDef = true) { files.push_back(strHref); } // bool Commit(CHHPMk &mk); }; }; typedef map<CString, UINT> MaterialDistributionMMap; typedef multimap<UINT, CString, greater<UINT> > MaterialDistributionRMMap; class CMaterialStats { // struct Data { // Doom3Blendf bf1, bf2; // bool operator <(const Data &s) const { return memcmp(this, &s, sizeof(Data)) < 0; } }; // typedef vector<Data> DataArray; // struct DataArrayLess : less<DataArray> { // bool operator()(const DataArray &s1, const DataArray &s2) const { UINT i; for (i = 0; ; i++) { if (false); else if (s1.size() <= i) { if (s2.size() <= i) return false; return true; } else if (s2.size() <= i) { return false; } if (s1[i] < s2[i]) return true; if (s2[i] < s1[i]) return false; } } }; // struct DataValue { // UINT cx; // list<CString> names; // DataValue() : cx(0) { } // bool operator <(const DataValue &s) const { return (cx < s.cx); } // bool operator >(const DataValue &s) const { return (cx > s.cx); } }; // typedef map<DataArray, DataValue, DataArrayLess> DataMap; // typedef multimap<DataValue, DataArray, greater<DataValue> > DataRMMap; // const CDoom3Workpad &wk; // const MaterialDistributionMMap &mm; // static LPCSTR GetBlendfName(Doom3Blendf x) { switch (x) { case bfNo: return "No"; case bfDstAlpha: return "GL_DST_ALPHA"; case bfDstColor: return "GL_DST_COLOR"; case bfOne: return "GL_ONE"; case bfOneMinusDstAlpha: return "GL_ONE_MINUS_DST_ALPHA"; case bfOneMinusDstColor: return "GL_ONE_MINUS_DST_COLOR"; case bfOneMinusSrcAlpha: return "GL_ONE_MINUS_SRC_ALPHA"; case bfOneMinusSrcColor: return "GL_ONE_MINUS_SRC_COLOR"; case bfSrcColor: return "GL_SRC_COLOR"; case bfZero: return "GL_ZERO"; case bfSrcAlpha: return "GL_SRC_ALPHA"; case bfBlend: return "Blend"; case bfAdd: return "Add"; case bfBumpMap: return "BumpMap"; case bfDiffuseMap: return "DiffuseMap"; case bfSpecularMap: return "SpecularMap"; case bfFilter: return "Filter"; } return "?"; } public: // CMaterialStats(const CDoom3Workpad &wk, const MaterialDistributionMMap &mm) : wk(wk), mm(mm) { } // void Run(); }; struct CV2MapPlane { // plane My3DMath::Vtx3 v; // plane minimal radius float fr; // for texture coord. (x,y,1) * m32 -> (s,t) float m32[2][3]; // CString strTex; // unit vector to move 'origin' My3DMath::Vtx3 v3Up, v3R; }; typedef vector<CV2MapPlane> V2MapPlaneArray_t; struct CV2MapBrush { // V2MapPlaneArray_t pa; }; typedef vector<CV2MapBrush> V2MapBrushArray_t; struct CV2MapPatchDef3Coord { // My3DMath::Vtx3 v; // My3DMath::Vtx2 tv; }; typedef vector<CV2MapPatchDef3Coord> V2MapPatchDef3CoordArray_t; struct CV2MapPatchDef3 { // int cx, cy; // int t[5]; // bool fIs3; // CString strTex; // V2MapPatchDef3CoordArray_t ca; }; typedef vector<CV2MapPatchDef3> V2MapPatchDef3Array_t; struct CV2MapEntity { // VarMap m; // CString strName; // My3DMath::Vtx3 o; // bool fHasBind; // My3DMath::Mtx rotation; // V2MapBrushArray_t va; // V2MapPatchDef3Array_t p3a; }; typedef list<CV2MapEntity> V2MapEntityList_t; typedef map<CString, CV2MapEntity *> V2MapEntityPtrMap_t; typedef multimap<CString, CString> V2MapBindRMMap_t; struct CV2MapDeck { // V2MapEntityList_t ea; // V2MapEntityPtrMap_t em; // V2MapBindRMMap_t vrmm; // StrSet_t vs; // void SearchDep(CString strName, StrSet_t &ss) const; // CV2MapEntity *FindEntity(CString strName) const; }; class CSparseV2Map : public CSparseBase { // MaterialDistributionMMap &mm; // MaterialDistributionMMap mm0; // CV2MapDeck &mesh; // CV2MapDeck mesh0; // bool fStat; // bool fq4; // q4 // char iVer; // void Parse_1(); public: // CSparseV2Map(CLL1Leader &fIn, MaterialDistributionMMap &mm) : CSparseBase(fIn), mm(mm), mesh(mesh0), fStat(true), fq4(false) { } // CSparseV2Map(CLL1Leader &fIn, CV2MapDeck &mesh, bool q4) : CSparseBase(fIn), mm(mm0), mesh(mesh), fStat(false), fq4(q4) { } // bool Parse(); }; class CProcessPriorityEnforcer { // DWORD nSaved; public: // CProcessPriorityEnforcer() { nSaved = 0; } // ~CProcessPriorityEnforcer() { Close(); } // void Close() { if (nSaved != 0) { VERIFY(SetPriorityClass(GetCurrentProcess(), nSaved)); nSaved = 0; } } // void Enforce(DWORD nNew) { DWORD n = GetPriorityClass(GetCurrentProcess()); if (n == 0) return; Close(); nSaved = n; VERIFY(SetPriorityClass(GetCurrentProcess(), nNew)); } }; struct CDoom3ImaPix { // CDoom3FlatIma &rIma; // UINT x, y, x1; // bool fUpdown; // CDoom3ImaPix(CDoom3FlatIma &rIma, bool fUpdown) : rIma(rIma), fUpdown(fUpdown) { x = y = 0; x1 = rIma.nBitCount / 8; ASSERT(x1 != 0); } // bool WritePix(const void *pv, UINT nRepeat) { if (y == rIma.cy) return false; BYTE *pVert = rIma.GetVert(fUpdown ? y : (rIma.cy -y -1)) + x1 * x; const BYTE *p = (const BYTE *)pv; for (UINT iRepeat = 0; iRepeat < nRepeat; iRepeat++, pVert += x1, x++) { if (x == rIma.cx) { x = 0; y++; pVert = rIma.GetVert(fUpdown ? y : (rIma.cy -y -1)); } if (y == rIma.cy) return false; memcpy(pVert, p, x1); } return true; } }; class CSparseTarga : public CMemVuff { // CDoom3FlatIma &rIma; public: // CSparseTarga(CDoom3FlatIma &rIma) : rIma(rIma) { } // bool Parse(); }; class CEaseWriter : public CTextPlainMk { // CMD5MeshDeck &mesh; public: // CEaseWriter(CMD5MeshDeck &mesh) : mesh(mesh) { } // bool Write(); }; class CV2MapWriter : public CTextPlainMk { public: // int iEntity, iPrimitive; // My3DMath::Vtx3 patchDef_forceo; // bool MkHeader(); // bool MkEntityHeader(); // bool MkEntity(CV2MapEntity &entity); // bool MkEntityFooter(); }; struct CBMapPt { // My3DMath::Vtx3 v; // My3DMath::Vtx2 tv; }; struct BMapPtArray_t : vector<CBMapPt> { // CString strTex; // BMapPtArray_t() { } // BMapPtArray_t(size_t i, const value_type &x): vector<CBMapPt>(i, x) { } }; typedef list<BMapPtArray_t> BMapPtArrayList_t; struct CBMEnt { // BMapPtArrayList_t alm; // My3DMath::Mtx rotation; // My3DMath::Vtx3 o; }; typedef list<CBMEnt> BMEntList_t; struct CStrCaseInsensitiveLess_t { // bool operator ()(const CString &s1, const CString &s2) { return s1.CompareNoCase(s2) < 0; } };
16.060425
106
0.597311
[ "mesh", "vector", "model" ]
6224804cac639fd058c306a9f8780e3ad8962880
731
h
C
Development/nmos/lldp_manager.h
rayli-hlit/nmos-cpp
c3f0cf7b31fca669e3523251d1ec39c6b2ac7acb
[ "Apache-2.0" ]
79
2017-09-19T06:40:41.000Z
2022-03-22T03:40:42.000Z
Development/nmos/lldp_manager.h
rayli-hlit/nmos-cpp
c3f0cf7b31fca669e3523251d1ec39c6b2ac7acb
[ "Apache-2.0" ]
200
2018-02-22T17:40:27.000Z
2022-03-28T18:53:21.000Z
Development/nmos/lldp_manager.h
alanb-sony/nmos-cpp
677fd9ddf6a11cf1fb53eddf9375e8b56d1eb83f
[ "Apache-2.0" ]
91
2017-09-20T08:13:59.000Z
2022-03-22T07:27:08.000Z
#ifndef NMOS_LLDP_MANAGER_H #define NMOS_LLDP_MANAGER_H #include <map> #include "cpprest/details/basic_types.h" namespace lldp { class lldp_manager; } namespace slog { class base_gate; } namespace nmos { struct model; struct node_interface; namespace experimental { // make an LLDP manager configured to receive LLDP frames on the specified interfaces // and update the node interfaces JSON data with attached_network_device details // and optionally, transmit LLDP frames for these interfaces lldp::lldp_manager make_lldp_manager(nmos::model& model, const std::map<utility::string_t, node_interface>& interfaces, bool transmit, slog::base_gate& gate); } } #endif
22.151515
166
0.729138
[ "model" ]
6229dbe0136ffa03a689c9e8b771c079ac9a810c
1,230
h
C
OVP/D3D9Client/samples/DX9ExtMFD/MFDWindow.h
Ybalrid/orbiter
7bed82f845ea8347f238011367e07007b0a24099
[ "MIT" ]
null
null
null
OVP/D3D9Client/samples/DX9ExtMFD/MFDWindow.h
Ybalrid/orbiter
7bed82f845ea8347f238011367e07007b0a24099
[ "MIT" ]
null
null
null
OVP/D3D9Client/samples/DX9ExtMFD/MFDWindow.h
Ybalrid/orbiter
7bed82f845ea8347f238011367e07007b0a24099
[ "MIT" ]
null
null
null
// ============================================================== // Copyright (C) 2006 Martin Schweiger // Licensed under the MIT License // ============================================================== #ifndef __MFDWINDOW_H #define __MFDWINDOW_H #define STRICT 1 #include <windows.h> #include "orbitersdk.h" #include "gcCoreAPI.h" class MFDWindow: public ExternMFD { public: MFDWindow (HINSTANCE _hInst, const MFDSPEC &spec); ~MFDWindow (); void Initialise (HWND _hDlg); void SetVessel (OBJHANDLE hV); void SetTitle (); void Resize(); void CheckAspect (LPRECT, DWORD); void RepaintButton (HWND hWnd); void RepaintDisplay(HWND hWnd); void ProcessButton (int bt, int event); void StickToVessel (bool stick); void clbkRefreshDisplay (SURFHANDLE); void clbkRefreshButtons (); void clbkFocusChanged (OBJHANDLE hFocus); private: RECT wr; HSWAP hSwap; HINSTANCE hInst; // instance handle HWND hDlg, hDsp; // dialog and MFD display handles HFONT hBtnFnt; // button font int BW, BH, ds; // button width and height, display size int gap; // geometry parameters int fnth; // button font height bool vstick; // stick to vessel bool bFailed; }; #endif // !__MFDWINDOW_H
26.73913
75
0.634959
[ "geometry" ]
6233f1c398d794b014892911570937b72a48d85d
2,433
h
C
dlls/Game/ui/TextInputBox.h
Mynsu/sirtet_SFML
ad1b64597868959d96d27fcb73fd272f41b21e16
[ "MIT" ]
null
null
null
dlls/Game/ui/TextInputBox.h
Mynsu/sirtet_SFML
ad1b64597868959d96d27fcb73fd272f41b21e16
[ "MIT" ]
null
null
null
dlls/Game/ui/TextInputBox.h
Mynsu/sirtet_SFML
ad1b64597868959d96d27fcb73fd272f41b21e16
[ "MIT" ]
null
null
null
#pragma once namespace ui { class TextInputBox { public: TextInputBox( const sf::RenderWindow& window ) : mIsActive( false ) { mBackground.setSize( sf::Vector2f(window.getSize()) ); mSubWindow.setSize( sf::Vector2f(200, 100) ); } virtual ~TextInputBox( ) = default; void draw( sf::RenderWindow& window ) { window.draw( mBackground ); window.draw( mSubWindow ); window.draw( mTextLabelForTitle ); window.draw( mTextFieldToInput ); } bool processEvent( std::vector<sf::Event>& eventQueue ); bool isActive( ) const { return mIsActive; } void activate( const std::string& title ) { mTextLabelForTitle.setString( title ); mInputTextFieldString.clear( ); mTextFieldToInput.setString( mInputTextFieldString + '_' ); mIsActive = true; } void deactivate( ) { mIsActive = false; } const std::string& inputString( ) { return mInputTextFieldString; } bool loadFont( std::string& fontPath ) { bool result = true; if ( false == mFont.loadFromFile(fontPath) ) { result = false; return result; } mTextLabelForTitle.setFont( mFont ); mTextFieldToInput.setFont( mFont ); return result; } void setPosition( const sf::Vector2f position ) { mSubWindow.setPosition( position ); } void setSize( const sf::Vector2f size ) { mSubWindow.setSize( size ); } void setTitleDimension( const sf::Vector2f relativePosition, const uint16_t fontSize ) { mTextLabelForTitle.setPosition( mSubWindow.getPosition() + relativePosition ); mTextLabelForTitle.setCharacterSize( fontSize ); } void setInputTextFieldDimension( const sf::Vector2f relativePosition, const uint16_t fontSize ) { mTextFieldToInput.setPosition( mSubWindow.getPosition() + relativePosition ); mTextFieldToInput.setCharacterSize( fontSize ); } void setBackgroundColor( const sf::Color color ) { mBackground.setFillColor( color ); } void setColor( const sf::Color color ) { mSubWindow.setFillColor( color ); } void setTitleColor( const sf::Color color ) { mTextLabelForTitle.setFillColor( color ); } void setInputTextFieldColor( const sf::Color color ) { mTextFieldToInput.setFillColor( color ); } private: bool mIsActive; std::string mInputTextFieldString; sf::Font mFont; sf::Text mTextLabelForTitle, mTextFieldToInput; sf::RectangleShape mSubWindow, mBackground; }; }
24.826531
81
0.693383
[ "vector" ]
6237f8ee57b38736650a60181e1820bf2734afd0
1,508
h
C
examples/workbook/art-workbook/EventDisplay3D/EvtDisplayService.h
JeffersonLab/ARIEL
49054ac62a84d48e269f7171daabb98e12a0be90
[ "BSD-3-Clause" ]
null
null
null
examples/workbook/art-workbook/EventDisplay3D/EvtDisplayService.h
JeffersonLab/ARIEL
49054ac62a84d48e269f7171daabb98e12a0be90
[ "BSD-3-Clause" ]
null
null
null
examples/workbook/art-workbook/EventDisplay3D/EvtDisplayService.h
JeffersonLab/ARIEL
49054ac62a84d48e269f7171daabb98e12a0be90
[ "BSD-3-Clause" ]
2
2020-09-26T01:37:11.000Z
2021-05-03T13:02:24.000Z
// // - Event display service used with the EventDisplay3D module to start up the // TApplication and allow forward, backward, and jump-to navigation of events // in the root input file. This is a very much simplified version based on // Nova's event visplay service by Mark Messier. // #ifndef EvtDisplayService_EvtDisplayService_hh #define EvtDisplayService_EvtDisplayService_hh #ifndef __CINT__ #include "fhiclcpp/ParameterSet.h" #include "art/Framework/Services/Registry/ActivityRegistry.h" #include "art/Framework/Services/Registry/ServiceMacros.h" #include "art/Framework/Core/InputSource.h" #include "art/Framework/Principal/Worker.h" #include "canvas/Persistency/Provenance/EventID.h" #include "art/Framework/Principal/Event.h" #include "toyExperiment/Analyzers/EnsureTApplication.h" namespace tex { class EvtDisplayService { public: EvtDisplayService(fhicl::ParameterSet const& pset, art::ActivityRegistry& reg); private: // When this object is intialized, it will ensure that // interactive ROOT is properly initialized EnsureTApplication ensureTApp_; void postBeginJobWorkers(art::InputSource* inputs, std::vector<art::Worker*> const& workers); void postProcessEvent(art::Event const&, art::ScheduleContext); private: art::InputSource* fInputSource; ///< Input source of events public: }; } #endif // __CINT__ DECLARE_ART_SERVICE(tex::EvtDisplayService, LEGACY) #endif // EvtDisplayService_EvtDisplayService_hh
32.085106
83
0.759284
[ "object", "vector" ]
623bb198bc71053826984ab56cfc1cc078c8c6c2
13,550
c
C
Oem/DWFTK/develop/global/src/dwf/w3dtk/hoops/mxmain.c
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
2
2017-04-19T01:38:30.000Z
2020-07-31T03:05:32.000Z
Oem/DWFTK/develop/global/src/dwf/w3dtk/hoops/mxmain.c
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
null
null
null
Oem/DWFTK/develop/global/src/dwf/w3dtk/hoops/mxmain.c
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
1
2021-12-29T10:46:12.000Z
2021-12-29T10:46:12.000Z
/************************************************************************ MxMain.c This file provides the external interface for the LOD module. All communication to and from the outside world should pass through this file, through the function LOD_main. This file should be the only C file that knows about anything from HOOPS Copyright (C) 1998 Michael Garland. See "COPYING.txt" for details. $Id: //DWF/Working_Area/Willie.Zhu/w3dtk/hoops/mxmain.c#1 $ ************************************************************************/ /* #include "hoops.h" */ #include "lod.h" /* * This function handles the interface to the function that extracts the * shell from the hoops metafile. * fmap_intermediate describes the mapping from the original shell faces * to the first triangle in the triangle map */ static int shell_to_model( MxModel *m, int plist_len, const float *plist, int flist_len, const int *flist, int *fmap_intermediate ) { const float *ptrf; const int *ptri; int i, j, count; int num_triangles = 0; int num_shell_faces = 0; for( i = 0, ptrf = plist ; i < plist_len ; i++, ptrf += 3 ) { add_vertex( m, ptrf[0], ptrf[1], ptrf[2] ); } for( ptri = flist ; ptri < flist + flist_len ; ptri += count + 1 ) { count = *ptri; MX_ASSERT( count >= 0 ); fmap_intermediate[ num_shell_faces++ ] = num_triangles; for( j = 3 ; j <= count ; j++ ) { add_face( m, ptri[ 1 ], ptri[ j-1 ], ptri[ j ] ); num_triangles++; } } return num_triangles; } /* end function shell_to_model */ /* model_to_shell * note: There are two levels of indirection in vertex maps-- * 1) the first maps from input vertices to model vertex IDs * 2) the second maps from model vertex IDs to their compacted array * representation that has invalid vertices removed. * vmap_intermediate expresses #2, whereas vmap_final expresses both combined */ static void model_to_shell( MxModel *m, int *pcount, float *plist, int *flist_len, int *flist, int *vmap_final, int vmap_final_len ) { double *fptr_in; float *fptr_out; int *iptr_in, *iptr_out; int i, maxi; int validvertices = 0; int *vmap_intermediate, vmap_intermediate_len; /* in this block we output vertices and create vmap_intermediate */ fptr_out = plist; maxi = vmap_intermediate_len = model_vertex_count( m ); vmap_intermediate = MX_ALLOC( (long)(vmap_intermediate_len * sizeof( int )) ); if( vmap_intermediate == NULL ) MX_ERROR( ERR_INSUFFICIENT_MEMORY, "memory allocation failed" ); for( i = 0 ; i < maxi ; i++ ) { vmap_intermediate[i] = -1; if( vertex_is_valid(m, i) ) { vmap_intermediate[i] = validvertices++; fptr_in = model_vertex( m, i )->elt; fptr_out[0] = (float) (fptr_in[0]); fptr_out[1] = (float) (fptr_in[1]); fptr_out[2] = (float) (fptr_in[2]); fptr_out += 3; } } *pcount = validvertices; /* in this block we output faces * assumes that model has triangles only -- will break otherwise */ iptr_out = flist; maxi = model_face_count( m ); for( i = 0 ; i < maxi ; i++ ) { if( face_is_valid( m, i ) ) { iptr_in = model_face( m, i )->v; iptr_out[0] = 3; iptr_out[1] = vmap_intermediate[ iptr_in[0] ]; iptr_out[2] = vmap_intermediate[ iptr_in[1] ]; iptr_out[3] = vmap_intermediate[ iptr_in[2] ]; MX_ASSERT( ( iptr_out[1] >= 0 ) && ( iptr_out[1] < *pcount) ); MX_ASSERT( ( iptr_out[2] >= 0 ) && ( iptr_out[2] < *pcount) ); MX_ASSERT( ( iptr_out[3] >= 0 ) && ( iptr_out[3] < *pcount) ); iptr_out += 4; } } *flist_len = (int)(iptr_out - flist); /* in this block we create vmap_final, if appropriate */ if( vmap_final != NULL ) { for( i = 0 ; i < vmap_final_len ; i++ ) { vmap_final[i] = vmap_intermediate[ model_vertex_map_entry( m, i ) ]; MX_ASSERT( vmap_final[i] < validvertices ); } } MX_FREE( vmap_intermediate, (long)(vmap_intermediate_len * sizeof( int )) ); } /* end function model_to_shell */ /* model_to_shell_flist_only * When MX_PLACE_ENDPOINTS is used, all representations index back * into the same points array. This corresponds to the HOOPS "conserve memory" * setting. */ static void model_to_shell_flist_only( MxModel *m, int *pcount, int *flist_len, int *flist ) { int *iptr_in, *iptr_out; int i, maxi; int numvertices, validvertices = 0; maxi = numvertices = model_vertex_count( m ); for( i = 0 ; i < maxi ; i++ ) if( vertex_is_valid(m, i) ) validvertices++; *pcount = validvertices; /* pcount may or may not be needed later */ iptr_out = flist; maxi = model_face_count( m ); for( i = 0 ; i < maxi ; i++ ) { if( face_is_valid( m, i ) ) { iptr_in = model_face( m, i )->v; /* assumes triangles only */ iptr_out[0] = 3; /* note: unlike model_to_shell, no vertex mapping */ iptr_out[1] = iptr_in[0]; iptr_out[2] = iptr_in[1]; iptr_out[3] = iptr_in[2]; MX_ASSERT( ( iptr_out[1] >= 0 ) && ( iptr_out[1] < numvertices ) ); MX_ASSERT( ( iptr_out[2] >= 0 ) && ( iptr_out[2] < numvertices ) ); MX_ASSERT( ( iptr_out[3] >= 0 ) && ( iptr_out[3] < numvertices ) ); iptr_out += 4; } } *flist_len = (int)(iptr_out - flist); } /* end function model_to_shell_flist_only */ #if 0 static void create_mapping_list( MxModel *m, int *vertex_map ) { int i, *iptr, *iptr2; if( vertex_map != NULL ) { for( i = 0 ; i < lengthb( &(m->vertex_map) ) ; i++ ) { iptr = (int *) getb ( &(m->vertex_map), i ) ; while( !vertex_is_valid( m, *iptr ) ) { iptr2 = (int *) getb ( &(m->vertex_map), *iptr ); if( *iptr == *iptr2 ) { MX_ASSERT( 0 ); /* we shouldn't be here. Die if debug mode */ break; /* avoid an infinite loop */ } else iptr = iptr2; } MX_ASSERT( vertex_is_valid( m, *iptr ) ); vertex_map[ i ] = *iptr; } } } #endif static void assemble_config( const MxConfig *cfg_in, MxConfig *cfg ) { /* put in default values */ cfg->placement_policy = MX_PLACE_OPTIMAL_BB; cfg->weighting_policy = MX_WEIGHT_AREA; cfg->boundary_weight = 1000.0; cfg->compactness_ratio = 0; cfg->meshing_penalty = 0; cfg->will_join_only = 0; cfg->ratio = 0.5; cfg->max_degree = 15; if( cfg_in != NULL ) { if( cfg_in->placement_policy != MX_USE_DEFAULT ) cfg->placement_policy = cfg_in->placement_policy; if( cfg_in->weighting_policy != MX_USE_DEFAULT ) cfg->weighting_policy = cfg_in->weighting_policy; if( cfg_in->boundary_weight != MX_USE_DEFAULT ) cfg->boundary_weight = cfg_in->boundary_weight; if( cfg_in->compactness_ratio != MX_USE_DEFAULT ) cfg->compactness_ratio = cfg_in->compactness_ratio; if( cfg_in->meshing_penalty != MX_USE_DEFAULT ) cfg->meshing_penalty = cfg_in->meshing_penalty; if( cfg_in->will_join_only != MX_USE_DEFAULT ) cfg->meshing_penalty = cfg_in->meshing_penalty; if( cfg_in->ratio != MX_USE_DEFAULT ) cfg->ratio = cfg_in->ratio; if( cfg_in->max_degree != MX_USE_DEFAULT ) cfg->max_degree = cfg_in->max_degree; } } /* end function assemble_config */ void HU_LOD_Execute( int pcount, const float *plist, int flist_length, const int *flist, MxConfig *cfg_in, int *new_pcount, float *new_points, int *new_flist_length, int *new_flist, int *point_mapping_list, int *face_mapping_list ) { MxModel m; MxQSlim slim; MxConfig cfg; int num_faces; int num_faces_target; int *face_map_intermediate; face_map_intermediate = (int *) MX_ALLOC ((long)(flist_length * sizeof( int )) ); if( face_map_intermediate == NULL ) MX_ERROR( ERR_INSUFFICIENT_MEMORY, "memory allocation failed" ); mxmodel_init( &m, pcount, 100 ); num_faces = shell_to_model( &m, pcount, plist, flist_length, flist, face_map_intermediate ); assemble_config( cfg_in, &cfg ); mxqslim_init( &slim, &m, &cfg ); num_faces = model_face_count( &m ); /* assumes that all faces are valid */ num_faces_target = (int) (cfg.ratio * num_faces); qs_decimate( &slim, num_faces_target ); model_to_shell( &m, new_pcount, new_points, new_flist_length, new_flist, point_mapping_list, pcount ); /* clean up our memory */ mxqslim_cleanup( &slim ); mxmodel_cleanup( &m ); MX_FREE( face_map_intermediate, (long)(flist_length * sizeof( int )) ); /* Prevent VC from complaining about error C4100 */ face_mapping_list; } /* end function HU_LOD_Execute */ /* * helper */ static void recursive_chain_execute ( MxShellChain *root, MxConfig *cfg, MxQSlim *slim, int num_faces_target, int depth ) { int validfaces; int validvertices; qs_decimate( slim, num_faces_target ); validfaces = model_valid_face_count( slim->m ); root->sh.faces = (int *) MX_ALLOC ( (long)(4 * validfaces * sizeof( int )) ); if( root->sh.faces == NULL ) MX_ERROR( ERR_INSUFFICIENT_MEMORY, "memory allocation failed" ); if( cfg->placement_policy == MX_PLACE_ENDPOINTS ) { root->sh.points = NULL; model_to_shell_flist_only( slim->m, &(root->sh.pcount), &(root->sh.flen), root->sh.faces ); root->pointmap = NULL; /* point map is identity */ } else { validvertices = model_valid_vertex_count( slim->m ); root->sh.points = (float *) MX_ALLOC ( (long)(3 * validvertices * sizeof( float )) ); if( root->sh.faces == NULL ) MX_ERROR( ERR_INSUFFICIENT_MEMORY, "memory allocation failed" ); model_to_shell( slim->m, &(root->sh.pcount), root->sh.points, &(root->sh.flen), root->sh.faces, NULL, 0 /* no vertex maps needed */ ); root->pointmap = NULL; /* no support for pointmaps yet */ } if( depth > 0 ) { root->next = (MxShellChain *) MX_ALLOC ( sizeof (MxShellChain) ); if( root->next == NULL ) MX_ERROR( ERR_INSUFFICIENT_MEMORY, "memory allocation failed" ); root->next->next = NULL; recursive_chain_execute( root->next, cfg, slim, (int) (cfg->ratio * num_faces_target), depth - 1 ); } } /* end function recursive_chain_execute */ local void store_a_triangle ( void * info, int convex_triangulation, int v1, int v2, int v3) { MxModel * m = (MxModel *)info; add_face (m, v1, v2, v3); /* Prevent VC from complaining about warning C4100 */ convex_triangulation; } MxShellChain *HU_LOD_Chain_Execute( int point_count, const float *points, int flistlen, int *flist, float ratio, int depth ) { MxModel m; MxQSlim slim; MxConfig cfg; int num_faces; int num_faces_target; MxShellChain *root; int *item, *global_end; int i; mxmodel_init( &m, point_count, 100 ); for (i = 0; i < point_count; ++i) add_vertex (&m, points[3*i+0], points[3*i+1], points[3*i+2]); item = flist; global_end = flist + flistlen; do { int * local_end = item + 1 + *item; /* skip past sub-faces */ while (local_end != global_end && *local_end < 0) local_end += 1 - *local_end; if (*item == 3) store_a_triangle ((void *)&m, 1, item[1], item[2], item[3]); else HU_Triangulate_Face (points, null, item, local_end, store_a_triangle, (void *)&m); item = local_end; } until (item == global_end); assemble_config( null, &cfg ); cfg.ratio = ratio; mxqslim_init( &slim, &m, &cfg ); root = (MxShellChain *) MX_ALLOC ( sizeof (MxShellChain) ); if( root == NULL ) MX_ERROR( ERR_INSUFFICIENT_MEMORY, "memory allocation failed" ); root->next = NULL; num_faces = model_face_count( slim.m ); /* assumes all faces are valid */ num_faces_target = (int) (cfg.ratio * num_faces); recursive_chain_execute( root, &cfg, &slim, num_faces_target, depth ); /* clean up our memory */ mxqslim_cleanup( &slim ); mxmodel_cleanup( &m ); return root; } /* end function HU_LOD_Chain_Execute */
32.185273
86
0.556827
[ "model" ]
6241d922bc1f4f3d377a5df82525b894121a08d5
5,235
h
C
WormsGame/Source/physics.h
DarkAvanger/WormsPhysics
3edf02097e856eab52055e913741c9e8f6e2462e
[ "MIT" ]
null
null
null
WormsGame/Source/physics.h
DarkAvanger/WormsPhysics
3edf02097e856eab52055e913741c9e8f6e2462e
[ "MIT" ]
null
null
null
WormsGame/Source/physics.h
DarkAvanger/WormsPhysics
3edf02097e856eab52055e913741c9e8f6e2462e
[ "MIT" ]
null
null
null
// Changing any physics value while playing will cause the game to break, any physics values should be changed before compiling // Just saw you uploaded 2D physics Example which I could have implemented in my code if I had seen that sooner, //anyway I added some features that can be found in the readme such as playing against the IA or between friends, up to 4 at the same time #include <iostream> #include <string> #include <algorithm> using namespace std; #include "Base.h" class cPhysicsObject { public: cPhysicsObject(float x = 0.0f, float y = 0.0f) { px = x; py = y; } public: float px = 0.0f; // Position float py = 0.0f; float vx = 0.0f; // Velocity float vy = 0.0f; float ax = 0.0f; // Acceleration float ay = 0.0f; float radius = 4.0f; // Rectangle for collisions float fFriction = 0.0f; int nBounceBeforeDeath = -1; // How many time object can bounce before death bool bDead; bool bStable = false; virtual void Draw(Base* engine, float fOffsetX, float fOffsetY, bool bPixel = false) = 0; virtual int BounceDeathAction() = 0; virtual bool Damage(float d) = 0; }; class Rock : public cPhysicsObject { public: Rock(float x = 0.0f, float y = 0.0f) : cPhysicsObject(x, y) { vx = 10.0f * cosf(((float)rand() / (float)RAND_MAX) * 2.0f * 3.14159f); vy = 10.0f * sinf(((float)rand() / (float)RAND_MAX) * 2.0f * 3.14159f); radius = 1.0f; fFriction = 0.8f; bDead = false; bStable = false; nBounceBeforeDeath = 2; } virtual void Draw(Base* engine, float fOffsetX, float fOffsetY, bool bPixel = false) { engine->DrawWireFrameModel(vecModel, px - fOffsetX, py - fOffsetY, atan2f(vy, vx), bPixel ? 0.5f : radius, FG_DARK_GREEN); //Particle explosion } virtual int BounceDeathAction() { return 0; } virtual bool Damage(float d) { return true; } private: static vector<pair<float, float>> vecModel; }; vector<pair<float, float>>DefineRock() { vector<pair<float, float>> vecModel; vecModel.push_back({ 0.0f, 0.0f }); vecModel.push_back({ 1.0f, 0.0f }); vecModel.push_back({ 1.0f, 1.0f }); vecModel.push_back({ 0.0f, 1.0f }); return vecModel; } vector<pair<float, float>> Rock::vecModel = DefineRock(); class cMissile : public cPhysicsObject { public: cMissile(float x = 0.0f, float y = 0.0f, float _vx = 0.0f, float _vy = 0.0f) : cPhysicsObject(x, y) { radius = 2.5f; fFriction = 0.5f; vx = _vx; vy = _vy; bDead = false; nBounceBeforeDeath = 1; bStable = false; } virtual void Draw(Base* engine, float fOffsetX, float fOffsetY, bool bPixel = false) { engine->DrawWireFrameModel(vecModel, px - fOffsetX, py - fOffsetY, atan2f(vy, vx), bPixel ? 0.5f : radius, FG_BLACK); } virtual int BounceDeathAction() { return 20; } virtual bool Damage(float d) { return true; } private: static vector<pair<float, float>> vecModel; }; vector<pair<float, float>> DefineMissile() { vector<pair<float, float>> vecModel; vecModel.push_back({ 0.0f, 0.0f }); vecModel.push_back({ 1.0f, 1.0f }); vecModel.push_back({ 2.0f, 1.0f }); vecModel.push_back({ 2.5f, 0.0f }); vecModel.push_back({ 2.0f, -1.0f }); vecModel.push_back({ 1.0f, -1.0f }); vecModel.push_back({ 0.0f, 0.0f }); vecModel.push_back({ -1.0f, -1.0f }); vecModel.push_back({ -2.5f, -1.0f }); vecModel.push_back({ -2.0f, 0.0f }); vecModel.push_back({ -2.5f, 1.0f }); vecModel.push_back({ -1.0f, 1.0f }); for (auto& v : vecModel) { v.first /= 1.5f; v.second /= 1.5f; } return vecModel; } vector<pair<float, float>> cMissile::vecModel = DefineMissile(); class cWorm : public cPhysicsObject { public: cWorm(float x = 0.0f, float y = 0.0f) : cPhysicsObject(x, y) { radius = 3.5f; fFriction = 0.2f; bDead = false; nBounceBeforeDeath = -1; bStable = false; if (sprWorm == nullptr) sprWorm = new Sprite(L"Assets/worms1.spr"); } virtual void Draw(Base* engine, float fOffsetX, float fOffsetY, bool bPixel = false) { if (bIsPlayable) { engine->DrawPartialSprite(px - fOffsetX - radius, py - fOffsetY - radius, sprWorm, nTeam * 8, 0, 8, 8); for (int i = 0; i < 11 * fHealth; i++) { engine->Draw(px - 5 + i - fOffsetX, py + 5 - fOffsetY, PIXEL_SOLID, FG_BLUE); engine->Draw(px - 5 + i - fOffsetX, py + 6 - fOffsetY, PIXEL_SOLID, FG_BLUE); } } else { engine->DrawPartialSprite(px - fOffsetX - radius, py - fOffsetY - radius, sprWorm, nTeam * 8, 8, 8, 8); } } virtual int BounceDeathAction() { return 0; } virtual bool Damage(float d) { fHealth -= d; if (fHealth <= 0) { fHealth = 0.0f; bIsPlayable = false; } return fHealth > 0; } public: float fShootAngle = 0.0f; float fHealth = 1.0f; int nTeam = 0; bool bIsPlayable = true; private: static Sprite* sprWorm; }; Sprite* cWorm::sprWorm = nullptr; class cTeam { public: vector<cWorm*> vecMembers; int nCurrentMember = 0; int nTeamSize = 0; bool IsTeamAlive() { bool bAllDead = false; for (auto w : vecMembers) bAllDead |= (w->fHealth > 0.0f); return bAllDead; } cWorm* GetNextMember() { do { nCurrentMember++; if (nCurrentMember >= nTeamSize) nCurrentMember = 0; } while (vecMembers[nCurrentMember]->fHealth <= 0); return vecMembers[nCurrentMember]; } };
22.276596
145
0.653104
[ "object", "vector" ]
6256e19c95c36311249bbb225490b9ab90a46995
5,694
c
C
src/libcodec/cipher.c
rajeevvats/klone_webServer
bfa77f491b837278ace8efaab84bef880fc9b225
[ "BSD-3-Clause" ]
86
2015-01-02T10:14:48.000Z
2021-09-11T15:03:04.000Z
src/libcodec/cipher.c
rajeevvats/klone_webServer
bfa77f491b837278ace8efaab84bef880fc9b225
[ "BSD-3-Clause" ]
5
2017-03-14T21:58:44.000Z
2020-01-21T13:36:57.000Z
src/libcodec/cipher.c
rajeevvats/klone_webServer
bfa77f491b837278ace8efaab84bef880fc9b225
[ "BSD-3-Clause" ]
30
2015-03-06T07:57:29.000Z
2019-06-05T16:04:37.000Z
/* * Copyright (c) 2005-2012 by KoanLogic s.r.l. <http://www.koanlogic.com> * All rights reserved. * * This file is part of KLone, and as such it is subject to the license stated * in the LICENSE file which you have received as part of this distribution. * * $Id: cipher.c,v 1.11 2007/10/26 08:57:59 tho Exp $ */ #include "klone_conf.h" #include <u/libu.h> #include <klone/codec.h> #include <klone/ccipher.h> #include <klone/utils.h> enum { CODEC_CIPHER_MAX_INPUT = 4096 /* max src block size for transform() */ }; typedef int (*EVP_Update_t)(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl, const unsigned char *in, int inl); typedef int (*EVP_Final_ex_t)(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl); struct codec_cipher_s { codec_t codec; const EVP_CIPHER *cipher; /* encryption cipher algorithm */ EVP_CIPHER_CTX cipher_ctx; /* encrypt context */ char *cbuf; size_t coff, ccount, cbuf_size; EVP_Update_t update; /* EVP_{Encrypt,Decrypt}Update func ptr */ EVP_Final_ex_t final; /* EVP_{Encrypt,Decrypt}Final_ex func ptr */ }; typedef struct codec_cipher_s codec_cipher_t; static void codec_cbufcpy(codec_cipher_t *cc, char *dst, size_t *dcount) { size_t count; count = U_MIN(*dcount, cc->ccount); memcpy(dst, cc->cbuf + cc->coff, count); cc->ccount -= count; if(cc->ccount) cc->coff += count; else cc->coff = 0; *dcount = count; } static ssize_t cipher_flush(codec_t *codec, char *dst, size_t *dcount) { codec_cipher_t *cc; int wr; dbg_err_if (codec == NULL); dbg_err_if (dst == NULL); dbg_err_if (dcount == NULL); cc = (codec_cipher_t*)codec; for(;;) { if(cc->ccount) { codec_cbufcpy(cc, dst, dcount); return CODEC_FLUSH_CHUNK; /* call flush again */ } if(cc->final) { wr = -1; /* just used to return an int value */ dbg_err_if(!cc->final(&cc->cipher_ctx, cc->cbuf, &wr)); cc->ccount += wr; cc->final = NULL; /* can be called just once */ if(wr) continue; } break; } *dcount = 0; return CODEC_FLUSH_COMPLETE; err: return -1; } static ssize_t cipher_transform(codec_t *codec, char *dst, size_t *dcount, const char *src, size_t src_sz) { codec_cipher_t *cc; ssize_t c; int wr; dbg_err_if (codec == NULL); dbg_err_if (src == NULL); dbg_err_if (dst == NULL); dbg_err_if (dcount == NULL || *dcount == 0); dbg_err_if (src_sz == 0); cc = (codec_cipher_t*)codec; c = 0; for(;;) { if(cc->ccount) { codec_cbufcpy(cc, dst, dcount); return c; /* consumed */ } /* the cbuf must be empty because we need the whole buffer to be sure to have enough output space for EVP_{Encrypt,Decrypt}Update */ c = U_MIN(src_sz, CODEC_CIPHER_MAX_INPUT); wr = -1; /* just used to return an int value */ dbg_err_if(!cc->update(&cc->cipher_ctx, cc->cbuf, &wr, src, c)); cc->ccount += wr; if(wr == 0) { *dcount = 0; break; /* cipher need more input to produce any output */ } } dbg_err_if(c == 0 && *dcount == 0); return c; err: return -1; } static int cipher_free(codec_t *codec) { codec_cipher_t *cc; nop_return_if (codec == NULL, 0); cc = (codec_cipher_t*)codec; U_FREE(cc->cbuf); U_FREE(cc); return 0; } /** * \addtogroup filters * \{ */ /** * \brief Create a cipher \c codec_t object * * Create a cipher \c codec_t object at \p *pcc suitable for encryption or * decryption (depending on \p op). The \p cipher, \p key and \p iv parameters * hold the algorithm, key and initialisation vector respectively, used for * the data transforms. * * \param op one of \c CIPHER_ENCRYPT or \c CIPHER_DECRYPT * \param cipher an OpenSSL \c EVP_CIPHER object * \param key the encryption/decryption key * \param iv the initialisation vector * \param pcc the created codec as a value-result arguement * * \return \c 0 on success, \c ~0 otherwise */ int codec_cipher_create(int op, const EVP_CIPHER *cipher, unsigned char *key, unsigned char *iv, codec_t **pcc) { codec_cipher_t *cc = NULL; dbg_return_if (cipher == NULL, ~0); dbg_return_if (key == NULL, ~0); /* iv can be NULL */ dbg_return_if (pcc == NULL, ~0); cc = u_zalloc(sizeof(codec_cipher_t)); dbg_err_if(cc == NULL); cc->codec.transform = cipher_transform; cc->codec.flush = cipher_flush; cc->codec.free = cipher_free; cc->cipher = cipher; /* be sure that the cipher stuff is loaded */ EVP_add_cipher(cc->cipher); EVP_CIPHER_CTX_init(&cc->cipher_ctx); cc->cbuf_size = CODEC_CIPHER_MAX_INPUT + EVP_CIPHER_block_size(cc->cipher) -1; cc->cbuf = u_malloc(cc->cbuf_size); dbg_err_if(cc->cbuf == NULL); switch(op) { case CIPHER_ENCRYPT: dbg_err_if(!EVP_EncryptInit_ex(&cc->cipher_ctx, cc->cipher, NULL, key, iv)); cc->update = EVP_EncryptUpdate; cc->final = EVP_EncryptFinal_ex; break; case CIPHER_DECRYPT: dbg_err_if(!EVP_DecryptInit_ex(&cc->cipher_ctx, cc->cipher, NULL, key, iv)); cc->update = EVP_DecryptUpdate; cc->final = EVP_DecryptFinal_ex; break; default: dbg_err_if("bad cipher op"); } *pcc = (codec_t*)cc; return 0; err: U_FREE(cc); return ~0; } /** * \} */
24.543103
80
0.59712
[ "object", "vector", "transform" ]
62659dfb70406f20bc57ce8f862d49d9a0e68a8c
1,950
h
C
include/coco/coco.h
kerry-Cho/maskrcnn_benchmark.cpp
f110f7b6d6ac87b919b8f7aa95527c68f74d234a
[ "MIT" ]
99
2019-05-01T15:23:45.000Z
2022-01-30T05:11:40.000Z
include/coco/coco.h
conanhung/maskrcnn_benchmark.cpp
eab9787d3140e003662a31a8e01f7ae39469e9a0
[ "MIT" ]
18
2019-05-21T11:31:44.000Z
2020-04-03T09:59:27.000Z
include/coco/coco.h
conanhung/maskrcnn_benchmark.cpp
eab9787d3140e003662a31a8e01f7ae39469e9a0
[ "MIT" ]
27
2019-05-12T05:41:08.000Z
2021-02-07T01:58:01.000Z
#pragma once #include "rapidjson/document.h" #include <map> #include <string> #include <vector> namespace coco{ using namespace rapidjson; enum Crowd{ none = -1, F = 0, T = 1 }; struct Annotation{ Annotation(const Value& value); Annotation(); int64_t id; int image_id; int category_id; std::vector<std::vector<double>> segmentation; std::vector<int> counts; std::string compressed_rle; std::pair<int, int> size; float area; std::vector<float> bbox; bool iscrowd; }; struct Image{ Image(const Value& value); Image(); // ~Image(); // Image(const Image& other); // Image(Image&& other); // Image& operator=(const Image& other); // Image& operator=(Image&& other); int id; int width; int height; //char* file_name; std::string file_name; }; struct Categories{ Categories(const Value& value); Categories(); int id; std::string name; std::string supercategory; }; struct COCO{ COCO(std::string annotation_file); COCO(); void CreateIndex(); std::vector<int64_t> GetAnnIds(const std::vector<int> imgIds = std::vector<int>{}, const std::vector<int> catIds = std::vector<int>{}, const std::vector<float> areaRng = std::vector<float>{}, Crowd iscrowd=none); //info std::vector<int> GetCatIds(const std::vector<std::string> catNms = std::vector<std::string>{}, const std::vector<std::string> supNms = std::vector<std::string>{}, const std::vector<int> catIds = std::vector<int>{}); std::vector<Annotation> LoadAnns(std::vector<int64_t> ids); std::vector<Image> LoadImgs(std::vector<int> ids); COCO LoadRes(std::string res_file); COCO(const COCO& other); COCO(COCO&& other); COCO operator=(const COCO& other); COCO operator=(COCO&& other); Document dataset; std::map<int64_t, Annotation> anns; std::map<int, Image> imgs; std::map<int, Categories> cats; std::map<int, std::vector<Annotation>> imgToAnns; std::map<int, std::vector<int>> catToImgs; }; }
24.375
217
0.673846
[ "vector" ]
62736312212e42873af3cb95d6d27494c27a46de
15,931
h
C
cxx/diamond_norm_scs.h
Tomographer/QPtomographer
337f0ba1069c8cef30e80a6719e8df9ce1c68997
[ "MIT" ]
2
2019-05-22T01:59:01.000Z
2020-06-05T07:33:46.000Z
cxx/diamond_norm_scs.h
Tomographer/QPtomographer
337f0ba1069c8cef30e80a6719e8df9ce1c68997
[ "MIT" ]
null
null
null
cxx/diamond_norm_scs.h
Tomographer/QPtomographer
337f0ba1069c8cef30e80a6719e8df9ce1c68997
[ "MIT" ]
null
null
null
#ifndef DIAMOND_NORM_SCS_H #define DIAMOND_NORM_SCS_H #include <iostream> #include <Eigen/Eigen> #include <Eigen/SparseCore> #include <boost/math/constants/constants.hpp> #include <tomographer/tools/cxxutil.h> #include "qptomo_use_scs.h" template<typename RealScalarType_, typename BaseLoggerType_ = Tomographer::Logger::VacuumLogger, bool CheckInputs_ = true> class DiamondNormSCSSolver { public: typedef RealScalarType_ RealScalarType; typedef std::complex<RealScalarType> ComplexScalarType; static_assert( std::is_same<RealScalarType, scs_float>::value, "DiamondNormSCSSolver only supports the scs_float scalar type SCS was compiled with."); typedef BaseLoggerType_ BaseLoggerType; static constexpr bool CheckInputs = CheckInputs_; protected: const scs_int DimX; const scs_int DimY; const scs_int DimXY; const scs_float epsilon; Eigen::SparseMatrix<scs_float, Eigen::ColMajor, scs_int> A; Eigen::Matrix<scs_float, Eigen::Dynamic, 1> bVec; Eigen::Matrix<scs_float, Eigen::Dynamic, 1> cVec; ScsCone * cone; ScsData * data; ScsSolution * sol; ScsInfo * info; ScsWork * work; const std::vector<scs_int> sdpcones; Tomographer::Logger::LocalLogger<BaseLoggerType> _logger; private: // helpers for the constructor inline static constexpr scs_int total_constraint_dof(scs_int DimX, scs_int /*DimY*/, scs_int DimXY) { // number of constraints degrees of freedom = dC1x + dC2x + dC3x = dC1x + dC2x * 2 return DimX*(2*DimX+1) + DimXY*(2*DimXY+1) * 2; } inline void init_cone() { // zero cone {x | x = 0 } (dual to the free cone {x | x in R}) cone->f = 0; // positive orthant {x | x >= 0} cone->l = 0; // second-order cone {(t,x) | ||x||_2 <= t} cone->qsize = 0; cone->q = NULL; // positive semidefinite cone { X | min(eig(X)) >= 0, X = X^T } cone->ssize = sdpcones.size(); cone->s = const_cast<scs_int*>(sdpcones.data()); // exponential cone {(x,y,z) | y e^(x/y) <= z, y>0 } cone->ep = 0; // dual exponential cone {(u,v,w) | −u e^(v/u) <= e w, u<0} cone->ed = 0; // power cone {(x,y,z) | x^a * y^(1-a) >= |z|, x>=0, y>=0} cone->psize = 0; // dual power cone {(u,v,w) | (u/a)^a * (v/(1-a))^(1-a) >= |w|, u>=0, v>=0} cone->p = NULL; } inline void init_data() { // store the A matrix in the data: data->m = A.rows(); // rows of A data->n = A.cols(); // columns of A data->A = (ScsMatrix*)std::calloc(1, sizeof(ScsMatrix)); data->A->m = data->m; data->A->n = data->n; // use Eigen's support of Sparse matrices to get correct representation. data->A->x = A.valuePtr(); data->A->i = A.innerIndexPtr(); data->A->p = A.outerIndexPtr(); data->b = bVec.data(); data->c = cVec.data(); // we should probably expose some API to tune these values -- these are // hard-coded for now. data->stgs = (ScsSettings*)std::malloc(sizeof(ScsSettings)); data->stgs->normalize = 1; data->stgs->scale = 5.0; data->stgs->rho_x = 1e-3; data->stgs->max_iters = 2500; data->stgs->eps = epsilon; data->stgs->alpha = 1.5; data->stgs->cg_rate = 2; // no effect as we use direct method and not indirect data->stgs->verbose = 0; data->stgs->warm_start = 0; // warm_start will be set after the first solution } inline void init_work() { work = scs_init(data, cone, info); } public: DiamondNormSCSSolver(const DiamondNormSCSSolver & copy) : DimX(copy.DimX), DimY(copy.DimY), DimXY(copy.DimXY), epsilon(copy.epsilon), A(copy.A), bVec(copy.bVec), // make sure data is initialized, at least outside of the // segment updated in calculate() cVec(copy.cVec), cone(NULL), data(NULL), sol(NULL), info(NULL), work(NULL), sdpcones(copy.sdpcones), _logger(copy._logger) { auto logger = _logger.subLogger(TOMO_ORIGIN); logger.debug("Constructing diamond norm SCS solver -- copy constructor"); // allocate SCS structures cone = (ScsCone*)std::calloc(1, sizeof(ScsCone)); data = (ScsData*)std::calloc(1, sizeof(ScsData)); sol = (ScsSolution*)std::calloc(1, sizeof(ScsSolution)); info = (ScsInfo*)std::calloc(1, sizeof(ScsInfo)); // init the cone init_cone(); // set up the SCS data for A (the Eigen sparse matrix A was copied from other object) init_data(); // initializing working space for SCS init_work(); } DiamondNormSCSSolver(DiamondNormSCSSolver && other) : DimX(other.DimX), DimY(other.DimY), DimXY(other.DimXY), epsilon(other.epsilon), A(std::move(other.A)), bVec(std::move(other.bVec)), // make sure data is initialized, at least // outside of the segment updated in // calculate() cVec(std::move(other.cVec)), cone(other.cone), data(other.data), sol(other.sol), info(other.info), work(other.work), sdpcones(std::move(other.sdpcones)), _logger(other._logger) { auto logger = _logger.subLogger(TOMO_ORIGIN); logger.debug("Constructing diamond norm SCS solver -- move constructor"); // leave other in a well-defined, null state other.cone = NULL; other.data = NULL; other.sol = NULL; other.info = NULL; other.work = NULL; } DiamondNormSCSSolver(const scs_int sysDimX, const scs_int sysDimY, const scs_float epsilon_, BaseLoggerType & baselogger) : DimX(sysDimX), DimY(sysDimY), DimXY(sysDimX * sysDimY), epsilon(epsilon_), A(total_constraint_dof(DimX, DimY, DimXY), 1+DimXY*DimXY), bVec(total_constraint_dof(DimX, DimY, DimXY)), cVec(1+DimXY*DimXY), cone(NULL), data(NULL), sol(NULL), info(NULL), work(NULL), sdpcones{2*DimX, 2*DimXY, 2*DimXY}, _logger(TOMO_ORIGIN, baselogger) { auto logger = _logger.subLogger(TOMO_ORIGIN); logger.debug("Constructing diamond norm SCS solver."); // allocate SCS structures cone = (ScsCone*)std::calloc(1, sizeof(ScsCone)); data = (ScsData*)std::calloc(1, sizeof(ScsData)); sol = (ScsSolution*)std::calloc(1, sizeof(ScsSolution)); info = (ScsInfo*)std::calloc(1, sizeof(ScsInfo)); // cones: // ------------------------------ init_cone(); // prepare the A matrix: // ------------------------------ typedef Eigen::Triplet<scs_float> TT; std::vector<TT> AT; // prepare triplets for sparse A matrix // A has: // ** number of rows = # of constraint degrees of freedom == the three SDP cones // == dC1x + dC2x + dC3x rows (dC1=2*DimX, dC2=2*DimXY, dC3=2*DimXY, dC?x=dC?*(dC?+1)/2) // ** number of columns = 1 + DimXY*DimXY = # of variable degrees of freedom // == 1 + dzR + dzI (dzR = dXY*(dXY+1)/2 , dzI = dXY*(dXY-1)/2) // // dimension of each constraint block (matrix dimension) const scs_int dC1 = 2*DimX; const scs_int dC2 = 2*DimXY; const scs_int dC3 = dC2; // # of degrees of freedom of each constraint block (== number of corresponding rows in A) const scs_int dC1x = dC1*(dC1+1)/2; const scs_int dC2x = dC2*(dC2+1)/2; const scs_int dC3x = dC2x; const scs_int con_offset_1 = 0; const scs_int con_offset_2 = con_offset_1+dC1x; const scs_int con_offset_3 = con_offset_2+dC2x; const scs_int var_alpha_offset = 0; const scs_int var_zRdiag_offset = var_alpha_offset + 1; const scs_int var_zRtri_offset = var_zRdiag_offset + DimXY; const scs_int var_zItri_offset = var_zRtri_offset + DimXY*(DimXY-1)/2; // A(0:dC1*,0) = A("block #1","alpha") = -vec(\Ident_{2dX}) scs_int k = 0; for (scs_int j = 0; j < 2*DimX; ++j) { AT.push_back(TT(k, var_alpha_offset, scs_float(-1))); k += 2*DimX - j; } const scs_float SQRT2 = boost::math::constants::root_two<scs_float>(); using tomo_internal::ltrilinindex; // A(0:dC1x,1:1+dzR) = A("block #1","zR"), // A(0:dC1x,1+dzR:1+dzR+dzI) = A("block #1","zI"), // A(dC1x:dC1x+dC2x,1:1+dzR) = A("block #2","zR"), // A(dC1x:dC1x+dC2x,1+dzR:1+dzR+dzI) = A("block #2","zI"), // A(dC1x+dC2x:dC1x+dC2x+dC3x,1:1+dzR) = A("block #3","zR"), // A(dC1x+dC2x:dC1x+dC2x+dC3x,1+dzR:1+dzR+dzI) = A("block #3","zI"), // scs_int trivarno = 0; for (scs_int ij = 0; ij < DimXY; ++ij) { const scs_int i = ij / DimY; const scs_int j = ij % DimY; for (scs_int ipjp = 0; ipjp < ij; ++ipjp) { const scs_int ip = ipjp / DimY; const scs_int jp = ipjp % DimY; // deal with z^R_{(ij),(i'j')} and z^I_{(ij),(i'j')} //std::cout << "Initializing i,j="<<i<<","<<j<<" i',j'="<<ip<<","<<jp<<" (trivarno="<<trivarno<<") ... \n"; // -------- // BLOCK 1: //std::cout << "\tblock #1 ...\n"; if (j == jp) { // zR: AT.push_back(TT(con_offset_1+ltrilinindex(i, ip, dC1), var_zRtri_offset+trivarno, SQRT2)); AT.push_back(TT(con_offset_1+ltrilinindex(DimX+i, DimX+ip, dC1), var_zRtri_offset+trivarno, SQRT2)); // zI: AT.push_back(TT(con_offset_1+ltrilinindex(DimX+i, ip, dC1), var_zItri_offset+trivarno, SQRT2)); AT.push_back(TT(con_offset_1+ltrilinindex(DimX+ip, i, dC1), var_zItri_offset+trivarno, -SQRT2)); } // BLOCK 2: //std::cout << "\tblock #2 ...\n"; // zR: AT.push_back(TT(con_offset_2+ltrilinindex(ij, ipjp, dC2), var_zRtri_offset+trivarno, -SQRT2)); AT.push_back(TT(con_offset_2+ltrilinindex(DimXY+ij, DimXY+ipjp, dC2), var_zRtri_offset+trivarno, -SQRT2)); // zI: AT.push_back(TT(con_offset_2+ltrilinindex(DimXY+ij, ipjp, dC2), var_zItri_offset+trivarno, -SQRT2)); AT.push_back(TT(con_offset_2+ltrilinindex(DimXY+ipjp, ij, dC2), var_zItri_offset+trivarno, SQRT2)); // BLOCK 3 (same as block 2 for F_{z^R...} and F_{z^I...}: //std::cout << "\tblock #3 ...\n"; // zR: AT.push_back(TT(con_offset_3+ltrilinindex(ij, ipjp, dC3), var_zRtri_offset+trivarno, -SQRT2)); AT.push_back(TT(con_offset_3+ltrilinindex(DimXY+ij, DimXY+ipjp, dC3), var_zRtri_offset+trivarno, -SQRT2)); // zI: AT.push_back(TT(con_offset_3+ltrilinindex(DimXY+ij, ipjp, dC3), var_zItri_offset+trivarno, -SQRT2)); AT.push_back(TT(con_offset_3+ltrilinindex(DimXY+ipjp, ij, dC3), var_zItri_offset+trivarno, SQRT2)); // -------- ++trivarno; } // deal with z^R_{(ij),(ij)}: //std::cout << "Initializing diagonal i,j="<<i<<","<<j<<" = i',j' ij=" << ij <<" ... \n"; // BLOCK 1: AT.push_back(TT(con_offset_1+ltrilinindex(i, i, dC1), var_zRdiag_offset+ij, scs_float(1))); AT.push_back(TT(con_offset_1+ltrilinindex(DimX+i, DimX+i, dC1), var_zRdiag_offset+ij, scs_float(1))); // BLOCK 2: AT.push_back(TT(con_offset_2+ltrilinindex(ij, ij, dC2), var_zRdiag_offset+ij, scs_float(-1))); AT.push_back(TT(con_offset_2+ltrilinindex(DimXY+ij, DimXY+ij, dC2), var_zRdiag_offset+ij, scs_float(-1))); // BLOCK 3: AT.push_back(TT(con_offset_3+ltrilinindex(ij, ij, dC3), var_zRdiag_offset+ij, scs_float(-1))); AT.push_back(TT(con_offset_3+ltrilinindex(DimXY+ij, DimXY+ij, dC3), var_zRdiag_offset+ij, scs_float(-1))); } if (CheckInputs) { // perform some checks for (auto it = AT.begin(); it != AT.end(); ++it) { //std::cout << "A(" << it->row() << "," << it->col() << ") = " << it->value() << "\n"; tomographer_assert(it->row() < dC1x+dC2x+dC3x); tomographer_assert(it->col() < 1+DimXY*DimXY); } //std::cout << "DimX=" << DimX << ", DimXY=" << DimXY // << ", dC1=" << dC1 << ", dC1x=" << dC1x << ", dC2=" << dC2 << ", dC2x=" << dC2x << "\n"; //std::cout << "dC1x+dC2x+dC3x=" << dC1x+dC2x+dC3x << ", 1+DimXY**2=" << 1+DimXY*DimXY << "\n"; } // Finally, populate the A matrix. A.setFromTriplets(AT.begin(), AT.end()); A.makeCompressed(); // B vector // make sure the bVec is zeroed out, because the calcualte() function will only update // the relevant segement inside this vector. bVec.setZero(); // C vector cVec.setZero(); cVec(0) = scs_float(1); // minimize: alpha -- which is the first variable // finally, set up the SCS data structure init_data(); // and the SCS working area init_work(); } ~DiamondNormSCSSolver() { // free workspace variables if (work != NULL) { scs_finish(work); } // free other structures if (cone != NULL) { std::free(cone); } if (data != NULL) { if (data->A != NULL) { std::free(data->A); } if (data->stgs != NULL) { std::free(data->stgs); } std::free(data); } if (sol != NULL) { std::free(sol); } if (info != NULL) { std::free(info); } } inline scs_int dimX() const { return DimX; } inline scs_int dimY() const { return DimY; } inline scs_int dimXY() const { return DimXY; } RealScalarType calculate( const Eigen::Ref<const Eigen::Matrix<ComplexScalarType,Eigen::Dynamic,Eigen::Dynamic> > & Delta ) { auto logger = _logger.subLogger(TOMO_ORIGIN); logger.longdebug([&](std::ostream & stream) { stream << "Calculating the diamond norm of\n" << Delta; }); if (CheckInputs) { tomographer_assert((scs_int)Delta.rows() == DimXY); tomographer_assert(Delta.cols() == Delta.rows()); tomographer_assert( (Delta - Delta.adjoint()).norm() < Delta.rows()*Delta.cols()*Eigen::NumTraits<RealScalarType>::dummy_precision()); } const scs_int con_offset_2 = DimX*(2*DimX+1); const scs_int dC2x = DimXY*(2*DimXY+1); const scs_float SQRT2 = boost::math::constants::root_two<scs_float>(); // copy the lower tri part of // // - [ Delta_R, -Delta_I; // Delta_I, Delta_R ] // // column-wise onto bVec(con_offset_2:con_offset_2+dC2): // scs_int koff = con_offset_2; // offset for the second (lower right) DeltaR's columns in linear index scs_int koff2 = con_offset_2 + dC2x - DimXY*(DimXY+1)/2; for (scs_int j = 0; j < DimXY; ++j) { const scs_int col_below_len = DimXY-j-1; // DeltaR's j-th diagonal element, twice: bVec(koff2) = bVec(koff) = - Delta(j,j).real(); ++koff; ++koff2; // DeltaR's lower part of j-th column, twice: bVec.segment(koff2, col_below_len) = bVec.segment(koff, col_below_len) = - Delta.real().block(j+1, j, col_below_len, 1) * SQRT2; koff += col_below_len; koff2 += col_below_len; // DeltaI's j-th column: bVec.segment(koff, DimXY) = - Delta.imag().col(j) * SQRT2; koff += DimXY; } //std::cout << "bVec = " << bVec << "\n"; // because the SCS data structure directly points to the data in bVec, the SCS problem // is automatically updated in this way // Now solve! scs_int status = scs_solve(work, data, cone, sol, info); // Check that the SDP converged. if (status != SCS_SOLVED) { logger.warning("SCS could not solve the SDP: ended with status %s (code %d)", info->status, status); } scs_float dnorm = (info->pobj + info->dobj)/2; logger.longdebug("[%s] code %d solution is dnorm=%f", info->status, (int)status, (double)dnorm); // Use the current solution as a warm-start for future calls to calculate() if ( ! data->stgs->warm_start ) { data->stgs->warm_start = 1; } return dnorm; } // calculate() }; // class DiamondNormSCSSolver #endif
33.680761
116
0.593309
[ "object", "vector" ]
627eda7f6f27b14ac083c208784bcc021d47d6fd
170
h
C
TileFactory.h
Boyko03/snow
8218d57fa8f01854d2c8aec9d98eb222846db5f7
[ "MIT" ]
null
null
null
TileFactory.h
Boyko03/snow
8218d57fa8f01854d2c8aec9d98eb222846db5f7
[ "MIT" ]
null
null
null
TileFactory.h
Boyko03/snow
8218d57fa8f01854d2c8aec9d98eb222846db5f7
[ "MIT" ]
null
null
null
#pragma once #include "Tile.h" class TileFactory { public: // Creates tile from terrain and object Tile getTile(Tile::Terrains_t terrain, Tile::Objects_t object); };
15.454545
64
0.741176
[ "object" ]
6289517f44a742262687591dc6b99321e49d9eea
27,846
h
C
Fastor/expressions/views/tensor_views_1d.h
mablanchard/Fastor
f5ca2f608bdfee34833d5008a93a3f82ce42ddef
[ "MIT" ]
424
2017-05-15T14:34:30.000Z
2022-03-29T08:58:22.000Z
Fastor/expressions/views/tensor_views_1d.h
manodeep/Fastor
aefce47955dd118f04e7b36bf5dbb2d86997ff8f
[ "MIT" ]
150
2016-12-23T10:08:12.000Z
2022-01-16T03:53:45.000Z
Fastor/expressions/views/tensor_views_1d.h
manodeep/Fastor
aefce47955dd118f04e7b36bf5dbb2d86997ff8f
[ "MIT" ]
43
2017-09-20T19:47:24.000Z
2022-02-22T21:12:49.000Z
#ifndef TENSOR_VIEWS_1D_H #define TENSOR_VIEWS_1D_H #include "Fastor/tensor/Tensor.h" #include "Fastor/tensor/Ranges.h" #include "Fastor/expressions/linalg_ops/linalg_traits.h" namespace Fastor { // 1D const views //-------------------------------------------------------------------------------------// template<typename T, size_t N> struct TensorConstViewExpr<Tensor<T,N>,1>: public AbstractTensor<TensorConstViewExpr<Tensor<T,N>,1>,1> { private: const Tensor<T,N> &_expr; seq _seq; public: using scalar_type = T; using simd_vector_type = typename Tensor<T,N>::simd_vector_type; using simd_abi_type = typename simd_vector_type::abi_type; using V = simd_vector_type; using result_type = Tensor<T,N>; static constexpr FASTOR_INDEX Dimension = 1; static constexpr FASTOR_INDEX Stride = simd_vector_type::Size; static constexpr FASTOR_INDEX rank() {return 1;} constexpr FASTOR_INLINE FASTOR_INDEX size() const {return _seq.size();} constexpr FASTOR_INLINE FASTOR_INDEX dimension(FASTOR_INDEX ) const {return _seq.size();} constexpr const Tensor<T,N>& expr() const {return _expr;} FASTOR_INLINE TensorConstViewExpr(const Tensor<T,N> &_ex, const seq &_s) : _expr(_ex), _seq(_s) { if (_seq._last < 0) _seq._last += N + /*including the end point*/ 1; if (_seq._first < 0) _seq._first += N + /*including the end point*/ 1; } template<typename U> FASTOR_INLINE SIMDVector<U,simd_abi_type> eval(FASTOR_INDEX i) const { SIMDVector<U,simd_abi_type> _vec; vector_setter(_vec,_expr.data(),i*_seq._step+_seq._first,_seq._step); return _vec; } template<typename U> constexpr FASTOR_INLINE U eval_s(FASTOR_INDEX i) const { return _expr.data()[i*_seq._step+_seq._first]; } template<typename U> FASTOR_INLINE SIMDVector<U,simd_abi_type> eval(FASTOR_INDEX i, FASTOR_INDEX j) const { SIMDVector<U,simd_abi_type> _vec; vector_setter(_vec,_expr.data(),(i+j)*_seq._step+_seq._first,_seq._step); return _vec; } template<typename U> constexpr FASTOR_INLINE U eval_s(FASTOR_INDEX i, FASTOR_INDEX j) const { return _expr.data()[(i+j)*_seq._step+_seq._first]; } template<typename U=T> FASTOR_INLINE SIMDVector<U,simd_abi_type> teval(const std::array<int,1>& as) const { SIMDVector<U,simd_abi_type> _vec; vector_setter(_vec,_expr.data(),as[0]*_seq._step+_seq._first,_seq._step); return _vec; } template<typename U=T> constexpr FASTOR_INLINE U teval_s(const std::array<int,1>& as) const { return _expr.data()[as[0]*_seq._step+_seq._first]; } }; // 1D non-const views //-------------------------------------------------------------------------------------// template<typename T, size_t N> struct TensorViewExpr<Tensor<T,N>,1>: public AbstractTensor<TensorViewExpr<Tensor<T,N>,1>,1> { private: Tensor<T,N> &_expr; seq _seq; bool _does_alias = false; constexpr FASTOR_INLINE Tensor<T,N> get_tensor() const {return _expr;} public: using scalar_type = T; using simd_vector_type = typename Tensor<T,N>::simd_vector_type; using simd_abi_type = typename simd_vector_type::abi_type; using V = simd_vector_type; using result_type = Tensor<T,N>; static constexpr FASTOR_INDEX Dimension = 1; static constexpr FASTOR_INDEX Stride = simd_vector_type::Size; static constexpr FASTOR_INDEX rank() {return 1;} constexpr FASTOR_INLINE FASTOR_INDEX size() const {return _seq.size();} constexpr FASTOR_INLINE FASTOR_INDEX dimension(FASTOR_INDEX ) const {return _seq.size();} constexpr const Tensor<T,N>& expr() const {return _expr;} FASTOR_INLINE TensorViewExpr<Tensor<T,N>,1>& noalias() { _does_alias = true; return *this; } FASTOR_INLINE TensorViewExpr(Tensor<T,N> &_ex, const seq &_s) : _expr(_ex), _seq(_s) { if (_seq._last < 0) _seq._last += N + /*including the end point*/ 1; if (_seq._first < 0) _seq._first += N + /*including the end point*/ 1; } // View evalution operators // Copy assignment operators [Needed in addition to generic AbstractTensor overload] //----------------------------------------------------------------------------------// FASTOR_HINT_INLINE void operator=(const TensorViewExpr<Tensor<T,N>,1> &other) { #if !(FASTOR_NO_ALIAS) if (_does_alias) { _does_alias = false; // Evaluate this into a temporary auto tmp_this_tensor = get_tensor(); auto tmp = TensorViewExpr<Tensor<T,N>,1>(tmp_this_tensor,_seq); // Assign other to temporary tmp = other; // assign temporary to this this->operator=(tmp); return; } #endif #ifndef NDEBUG FASTOR_ASSERT(other.size()==this->size(), "TENSOR SIZE MISMATCH"); // Check if shape of tensors match - for this 1D case for loop unnecessary for (FASTOR_INDEX i=0; i<Dimension; ++i) { FASTOR_ASSERT(other.dimension(i)==dimension(i), "TENSOR SHAPE MISMATCH"); } #endif T *FASTOR_RESTRICT _data = _expr.data(); if (_seq._step == 1) { FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { auto _vec = other.template eval<T>(i); _vec.store(&_data[i+_seq._first],false); } for (; i <size(); i++) { _data[i+_seq._first] = other.template eval_s<T>(i); } } else { #ifdef FASTOR_USE_VECTORISED_EXPR_ASSIGN FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { auto _vec_other = other.template eval<T>(i); for (auto j=0; j<simd_vector_type::Size; ++j) { auto idx = (i+j)*_seq._step+_seq._first; _data[idx] = _vec_other[j]; } } for (; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] = other.template eval_s<T>(i); } #else for (FASTOR_INDEX i = 0; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] = other.template eval_s<T>(i); } #endif } } //----------------------------------------------------------------------------------// // AbstractTensor binders //----------------------------------------------------------------------------------// template<typename Derived, size_t DIMS, enable_if_t_<requires_evaluation_v<Derived>,bool> = false> FASTOR_HINT_INLINE void operator=(const AbstractTensor<Derived,DIMS> &other) { const typename Derived::result_type& tmp = evaluate(other.self()); this->operator=(tmp); } template<typename Derived, size_t DIMS, enable_if_t_<!requires_evaluation_v<Derived>,bool> = false> FASTOR_HINT_INLINE void operator=(const AbstractTensor<Derived,DIMS> &other) { #if !(FASTOR_NO_ALIAS) if (_does_alias) { _does_alias = false; // Evaluate this into a temporary auto tmp_this_tensor = get_tensor(); auto tmp = TensorViewExpr<Tensor<T,N>,1>(tmp_this_tensor,_seq); // Assign other to temporary tmp = other; // assign temporary to this this->operator=(tmp); return; } #endif const Derived& other_src = other.self(); #ifndef NDEBUG FASTOR_ASSERT(other_src.size()==this->size(), "TENSOR SIZE MISMATCH"); #endif T *FASTOR_RESTRICT _data = _expr.data(); FASTOR_IF_CONSTEXPR(is_boolean_expression_v<Derived>) { for (FASTOR_INDEX i = 0; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] = other_src.template eval_s<T>(i); } return; } if (_seq._step == 1) { FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { auto _vec = other_src.template eval<T>(i); _vec.store(&_data[i+_seq._first],false); } for (; i <size(); i++) { _data[i+_seq._first] = other_src.template eval_s<T>(i); } } else { #ifdef FASTOR_USE_VECTORISED_EXPR_ASSIGN FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { auto _vec_other = other_src.template eval<T>(i); for (auto j=0; j<simd_vector_type::Size; ++j) { auto idx = (i+j)*_seq._step+_seq._first; _data[idx] = _vec_other[j]; } } for (; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] = other_src.template eval_s<T>(i); } #else for (FASTOR_INDEX i = 0; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] = other_src.template eval_s<T>(i); } #endif } } template<typename Derived, size_t DIMS, enable_if_t_<requires_evaluation_v<Derived>,bool> = false> FASTOR_HINT_INLINE void operator+=(const AbstractTensor<Derived,DIMS> &other) { const typename Derived::result_type& tmp = evaluate(other.self()); this->operator+=(tmp); } template<typename Derived, size_t DIMS, enable_if_t_<!requires_evaluation_v<Derived>,bool> = false> FASTOR_HINT_INLINE void operator+=(const AbstractTensor<Derived,DIMS> &other) { #if !(FASTOR_NO_ALIAS) if (_does_alias) { _does_alias = false; // Evaluate this into a temporary auto tmp_this_tensor = get_tensor(); auto tmp = TensorViewExpr<Tensor<T,N>,1>(tmp_this_tensor,_seq); // Assign other to temporary tmp = other; // assign temporary to this this->operator+=(tmp); return; } #endif const Derived& other_src = other.self(); #ifndef NDEBUG FASTOR_ASSERT(other_src.size()==this->size(), "TENSOR SIZE MISMATCH"); #endif T *FASTOR_RESTRICT _data = _expr.data(); if (_seq._step == 1) { FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { auto _vec = this->template eval<T>(i) + other_src.template eval<T>(i); _vec.store(&_data[i+_seq._first],false); } for (; i <size(); i++) { _data[i+_seq._first] += other_src.template eval_s<T>(i); } } else { #ifdef FASTOR_USE_VECTORISED_EXPR_ASSIGN FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { auto _vec_other = other_src.template eval<T>(i); for (auto j=0; j<simd_vector_type::Size; ++j) { auto idx = (i+j)*_seq._step+_seq._first; _data[idx] += _vec_other[j]; } } for (; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] += other_src.template eval_s<T>(i); } #else for (FASTOR_INDEX i = 0; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] += other_src.template eval_s<T>(i); } #endif } } template<typename Derived, size_t DIMS, enable_if_t_<requires_evaluation_v<Derived>,bool> = false> FASTOR_HINT_INLINE void operator-=(const AbstractTensor<Derived,DIMS> &other) { const typename Derived::result_type& tmp = evaluate(other.self()); this->operator-=(tmp); } template<typename Derived, size_t DIMS, enable_if_t_<!requires_evaluation_v<Derived>,bool> = false> FASTOR_HINT_INLINE void operator-=(const AbstractTensor<Derived,DIMS> &other) { #if !(FASTOR_NO_ALIAS) if (_does_alias) { _does_alias = false; // Evaluate this into a temporary auto tmp_this_tensor = get_tensor(); auto tmp = TensorViewExpr<Tensor<T,N>,1>(tmp_this_tensor,_seq); // Assign other to temporary tmp = other; // assign temporary to this this->operator-=(tmp); return; } #endif const Derived& other_src = other.self(); #ifndef NDEBUG FASTOR_ASSERT(other_src.size()==this->size(), "TENSOR SIZE MISMATCH"); #endif T *FASTOR_RESTRICT _data = _expr.data(); if (_seq._step == 1) { FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { auto _vec = this->template eval<T>(i) - other_src.template eval<T>(i); _vec.store(&_data[i+_seq._first],false); } for (; i <size(); i++) { _data[i+_seq._first] -= other_src.template eval_s<T>(i); } } else { #ifdef FASTOR_USE_VECTORISED_EXPR_ASSIGN FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { auto _vec_other = other_src.template eval<T>(i); for (auto j=0; j<simd_vector_type::Size; ++j) { auto idx = (i+j)*_seq._step+_seq._first; _data[idx] -= _vec_other[j]; } } for (; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] -= other_src.template eval_s<T>(i); } #else for (FASTOR_INDEX i = 0; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] -= other_src.template eval_s<T>(i); } #endif } } template<typename Derived, size_t DIMS, enable_if_t_<requires_evaluation_v<Derived>,bool> = false> FASTOR_HINT_INLINE void operator*=(const AbstractTensor<Derived,DIMS> &other) { const typename Derived::result_type& tmp = evaluate(other.self()); this->operator*=(tmp); } template<typename Derived, size_t DIMS, enable_if_t_<!requires_evaluation_v<Derived>,bool> = false> FASTOR_HINT_INLINE void operator*=(const AbstractTensor<Derived,DIMS> &other) { #if !(FASTOR_NO_ALIAS) if (_does_alias) { _does_alias = false; // Evaluate this into a temporary auto tmp_this_tensor = get_tensor(); auto tmp = TensorViewExpr<Tensor<T,N>,1>(tmp_this_tensor,_seq); // Assign other to temporary tmp = other; // assign temporary to this this->operator*=(tmp); return; } #endif const Derived& other_src = other.self(); #ifndef NDEBUG FASTOR_ASSERT(other_src.size()==this->size(), "TENSOR SIZE MISMATCH"); #endif T *FASTOR_RESTRICT _data = _expr.data(); if (_seq._step == 1) { FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { auto _vec = this->template eval<T>(i) * other_src.template eval<T>(i); _vec.store(&_data[i+_seq._first],false); } for (; i <size(); i++) { _data[i+_seq._first] *= other_src.template eval_s<T>(i); } } else { #ifdef FASTOR_USE_VECTORISED_EXPR_ASSIGN FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { auto _vec_other = other_src.template eval<T>(i); for (auto j=0; j<simd_vector_type::Size; ++j) { auto idx = (i+j)*_seq._step+_seq._first; _data[idx] *= _vec_other[j]; } } for (; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] *= other_src.template eval_s<T>(i); } #else for (FASTOR_INDEX i = 0; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] *= other_src.template eval_s<T>(i); } #endif } } template<typename Derived, size_t DIMS, enable_if_t_<requires_evaluation_v<Derived>,bool> = false> FASTOR_HINT_INLINE void operator/=(const AbstractTensor<Derived,DIMS> &other) { const typename Derived::result_type& tmp = evaluate(other.self()); this->operator/=(tmp); } template<typename Derived, size_t DIMS, enable_if_t_<!requires_evaluation_v<Derived>,bool> = false> FASTOR_HINT_INLINE void operator/=(const AbstractTensor<Derived,DIMS> &other) { #if !(FASTOR_NO_ALIAS) if (_does_alias) { _does_alias = false; // Evaluate this into a temporary auto tmp_this_tensor = get_tensor(); auto tmp = TensorViewExpr<Tensor<T,N>,1>(tmp_this_tensor,_seq); // Assign other to temporary tmp = other; // assign temporary to this this->operator/=(tmp); return; } #endif const Derived& other_src = other.self(); #ifndef NDEBUG FASTOR_ASSERT(other_src.size()==this->size(), "TENSOR SIZE MISMATCH"); #endif T *FASTOR_RESTRICT _data = _expr.data(); if (_seq._step == 1) { FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { auto _vec = this->template eval<T>(i) / other_src.template eval<T>(i); _vec.store(&_data[i+_seq._first],false); } for (; i <size(); i++) { _data[i+_seq._first] /= other_src.template eval_s<T>(i); } } else { #ifdef FASTOR_USE_VECTORISED_EXPR_ASSIGN FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { auto _vec_other = other_src.template eval<T>(i); for (auto j=0; j<simd_vector_type::Size; ++j) { auto idx = (i+j)*_seq._step+_seq._first; _data[idx] /= _vec_other[j]; } } for (; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] /= other_src.template eval_s<T>(i); } #else for (FASTOR_INDEX i = 0; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] /= other_src.template eval_s<T>(i); } #endif } } //----------------------------------------------------------------------------------// // scalar binders //----------------------------------------------------------------------------------// template<typename U=T, enable_if_t_<is_primitive_v_<U>,bool> = false> FASTOR_HINT_INLINE void operator=(U num) { simd_vector_type _vec_other(static_cast<T>(num)); T *FASTOR_RESTRICT _data = _expr.data(); if (_seq._step == 1) { FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { _vec_other.store(&_data[i+_seq._first],false); } for (; i <size(); i++) { _data[i+_seq._first] = num; } } else { #ifdef FASTOR_USE_VECTORISED_EXPR_ASSIGN FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { for (auto j=0; j<simd_vector_type::Size; ++j) { auto idx = (i+j)*_seq._step+_seq._first; _data[idx] = _vec_other[j]; } } for (; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] = num; } #else for (FASTOR_INDEX i = 0; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] = num; } #endif } } template<typename U=T, enable_if_t_<is_primitive_v_<U>,bool> = false> FASTOR_HINT_INLINE void operator+=(U num) { simd_vector_type _vec_other(static_cast<T>(num)); T *FASTOR_RESTRICT _data = _expr.data(); if (_seq._step == 1) { FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { auto _vec = this->template eval<T>(i) + _vec_other; _vec.store(&_data[i+_seq._first],false); } for (; i <size(); i++) { _data[i+_seq._first] += num; } } else { #ifdef FASTOR_USE_VECTORISED_EXPR_ASSIGN FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { for (auto j=0; j<simd_vector_type::Size; ++j) { auto idx = (i+j)*_seq._step+_seq._first; _data[idx] += _vec_other[j]; } } for (; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] += num; } #else for (FASTOR_INDEX i = 0; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] += num; } #endif } } template<typename U=T, enable_if_t_<is_primitive_v_<U>,bool> = false> FASTOR_HINT_INLINE void operator-=(U num) { simd_vector_type _vec_other(static_cast<T>(num)); T *FASTOR_RESTRICT _data = _expr.data(); if (_seq._step == 1) { FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { auto _vec = this->template eval<T>(i) - _vec_other; _vec.store(&_data[i+_seq._first],false); } for (; i <size(); i++) { _data[i+_seq._first] -= num; } } else { #ifdef FASTOR_USE_VECTORISED_EXPR_ASSIGN FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { for (auto j=0; j<simd_vector_type::Size; ++j) { auto idx = (i+j)*_seq._step+_seq._first; _data[idx] -= _vec_other[j]; } } for (; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] -= num; } #else for (FASTOR_INDEX i = 0; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] -= num; } #endif } } template<typename U=T, enable_if_t_<is_primitive_v_<U>,bool> = false> FASTOR_HINT_INLINE void operator*=(U num) { simd_vector_type _vec_other(static_cast<T>(num)); T *FASTOR_RESTRICT _data = _expr.data(); if (_seq._step == 1) { FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { auto _vec = this->template eval<T>(i) * _vec_other; _vec.store(&_data[i+_seq._first],false); } for (; i <size(); i++) { _data[i+_seq._first] *= num; } } else { #ifdef FASTOR_USE_VECTORISED_EXPR_ASSIGN FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { for (auto j=0; j<simd_vector_type::Size; ++j) { auto idx = (i+j)*_seq._step+_seq._first; _data[idx] *= _vec_other[j]; } } for (; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] *= num; } #else for (FASTOR_INDEX i = 0; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] *= num; } #endif } } template<typename U=T, enable_if_t_<is_primitive_v_<U> && !is_integral_v_<U>,bool> = false> FASTOR_HINT_INLINE void operator/=(U num) { T inum = T(1) / static_cast<T>(num); simd_vector_type _vec_other(inum); T *FASTOR_RESTRICT _data = _expr.data(); if (_seq._step == 1) { FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { auto _vec = this->template eval<T>(i) * _vec_other; _vec.store(&_data[i+_seq._first],false); } for (; i <size(); i++) { _data[i+_seq._first] *= inum; } } else { #ifdef FASTOR_USE_VECTORISED_EXPR_ASSIGN FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { for (auto j=0; j<simd_vector_type::Size; ++j) { auto idx = (i+j)*_seq._step+_seq._first; _data[idx] *= _vec_other[j]; } } for (; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] *= inum; } #else for (FASTOR_INDEX i = 0; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] *= inum; } #endif } } template<typename U=T, enable_if_t_<is_primitive_v_<U> && is_integral_v_<U>,bool> = false> FASTOR_HINT_INLINE void operator/=(U num) { simd_vector_type _vec_other(static_cast<T>(num)); T *FASTOR_RESTRICT _data = _expr.data(); if (_seq._step == 1) { FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { auto _vec = this->template eval<T>(i) / _vec_other; _vec.store(&_data[i+_seq._first],false); } for (; i <size(); i++) { _data[i+_seq._first] /= num; } } else { #ifdef FASTOR_USE_VECTORISED_EXPR_ASSIGN FASTOR_INDEX i; for (i = 0; i <ROUND_DOWN(size(),Stride); i+=Stride) { for (auto j=0; j<simd_vector_type::Size; ++j) { auto idx = (i+j)*_seq._step+_seq._first; _data[idx] /= _vec_other[j]; } } for (; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] /= num; } #else for (FASTOR_INDEX i = 0; i <size(); i++) { auto idx = i*_seq._step+_seq._first; _data[idx] /= num; } #endif } } //----------------------------------------------------------------------------------// template<typename U> FASTOR_INLINE SIMDVector<U,simd_abi_type> eval(FASTOR_INDEX i) const { SIMDVector<U,simd_abi_type> _vec; vector_setter(_vec,_expr.data(),i*_seq._step+_seq._first,_seq._step); return _vec; } template<typename U> constexpr FASTOR_INLINE U eval_s(FASTOR_INDEX i) const { return _expr.data()[i*_seq._step+_seq._first]; } template<typename U> FASTOR_INLINE SIMDVector<U,simd_abi_type> eval(FASTOR_INDEX i, FASTOR_INDEX j) const { SIMDVector<U,simd_abi_type> _vec; vector_setter(_vec,_expr.data(),(i+j)*_seq._step+_seq._first,_seq._step); return _vec; } template<typename U> constexpr FASTOR_INLINE U eval_s(FASTOR_INDEX i, FASTOR_INDEX j) const { return _expr.data()[(i+j)*_seq._step+_seq._first]; } template<typename U=T> FASTOR_INLINE SIMDVector<U,simd_abi_type> teval(const std::array<int,1>& as) const { SIMDVector<U,simd_abi_type> _vec; vector_setter(_vec,_expr.data(),as[0]*_seq._step+_seq._first,_seq._step); return _vec; } template<typename U=T> constexpr FASTOR_INLINE U teval_s(const std::array<int,1>& as) const { return _expr.data()[as[0]*_seq._step+_seq._first]; } }; } // end of namespace Fastor #endif // TENSOR_VIEWS_1D_H
37.62973
104
0.531566
[ "shape" ]
628aae1852321feece6e1f1a5c704011e5239caa
1,877
h
C
tensorflow/compiler/xla/service/cpu/cpu_xfeed.h
EricRemmerswaal/tensorflow
141ff27877579c81a213fa113bd1b474c1749aca
[ "Apache-2.0" ]
190,993
2015-11-09T13:17:30.000Z
2022-03-31T23:05:27.000Z
tensorflow/compiler/xla/service/cpu/cpu_xfeed.h
EricRemmerswaal/tensorflow
141ff27877579c81a213fa113bd1b474c1749aca
[ "Apache-2.0" ]
48,461
2015-11-09T14:21:11.000Z
2022-03-31T23:17:33.000Z
tensorflow/compiler/xla/service/cpu/cpu_xfeed.h
EricRemmerswaal/tensorflow
141ff27877579c81a213fa113bd1b474c1749aca
[ "Apache-2.0" ]
104,981
2015-11-09T13:40:17.000Z
2022-03-31T19:51:54.000Z
/* Copyright 2021 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_CPU_CPU_XFEED_H_ #define TENSORFLOW_COMPILER_XLA_SERVICE_CPU_CPU_XFEED_H_ #include <vector> #include "tensorflow/compiler/xla/literal.h" #include "tensorflow/compiler/xla/service/hlo_cost_analysis.h" #include "tensorflow/compiler/xla/service/shaped_buffer.h" #include "tensorflow/compiler/xla/status.h" // This provides a lower level API than TransferManager that does not depend on // StreamExecutor. It is intended to be used by callers that do not want to use // Stream or StreamExecutor. namespace xla { // Helper function to transfers to infeed on CPU. Status TransferLiteralToInfeedOnCpu(int device_ordinal, const LiteralSlice& literal); // Helper function to transfers from outfeed on CPU. Status TransferLiteralFromOutfeedOnCpu(int device_ordinal, MutableBorrowingLiteral literal); // Helper function to retrieve dynamic shape on CPU. Status ReadDynamicShapesOnCpu(ShapedBuffer* device_buffer, Shape* device_shape, HloCostAnalysis::ShapeSizeFunction shape_size_fn); } // namespace xla #endif // TENSORFLOW_COMPILER_XLA_SERVICE_CPU_CPU_XFEED_H_
40.804348
80
0.73415
[ "shape", "vector" ]
628ba724a133c4a4533d5273eec300e5f351f4a0
1,360
h
C
total-finder/dir_view_panel.h
vlanse/tf
7dc4291325476254f488116276c67dfffbcf06ac
[ "Apache-2.0" ]
null
null
null
total-finder/dir_view_panel.h
vlanse/tf
7dc4291325476254f488116276c67dfffbcf06ac
[ "Apache-2.0" ]
null
null
null
total-finder/dir_view_panel.h
vlanse/tf
7dc4291325476254f488116276c67dfffbcf06ac
[ "Apache-2.0" ]
null
null
null
#pragma once #include "base_panel.h" #include "tab_context.h" #include <QDir> #include <QFocusEvent> #include <QKeyEvent> #include <QWidget> class Ui_DirViewPanel; namespace TotalFinder { class DirModel; class QuickSearchKeyEventHandler; class TabContext; class DirViewPanel: public BasePanel { Q_OBJECT public: explicit DirViewPanel(const TabContext& context, QWidget* parent = nullptr); void SetRootDir(const QDir& dir); QDir GetRootDir() const; QFileInfo GetCurrentSelection() const; void SetFocus() override; QString GetName() const override; private slots: void OnHeaderGeometryChanged(); void OnItemActivated(const QModelIndex& index); void OnAddressBarEnter(); void OnFocusEvent(QFocusEvent event); void OnDirModelChange(); void OnSelectionChanged(const QModelIndex& current, const QModelIndex& previous); void OnShowViewContextMenu(const QPoint& point); void OnRevealInFinder(); void OnOpenTerminal(); private: void HandleItemSelection(const QFileInfo& item); void HandleDirSelection(const QDir& dir); void KeyHandler(Qt::KeyboardModifiers modifier, Qt::Key key, const QString& text) override; Ui_DirViewPanel* Ui; DirModel* Model; QFileInfo CurrentSelection; int CurrentRow; TabContext Context; }; } // namespace TotalFinder
23.859649
95
0.733824
[ "model" ]
628dad27089bb14bcba6f1af439c9680ba3534fd
88,596
h
C
src/blockcom.h
millerta/LaGriT-1
511ef22f3b7e839c7e0484604cd7f6a2278ae6b9
[ "CNRI-Python" ]
73
2017-02-09T17:54:28.000Z
2022-03-09T22:22:32.000Z
src/blockcom.h
millerta/LaGriT-1
511ef22f3b7e839c7e0484604cd7f6a2278ae6b9
[ "CNRI-Python" ]
166
2017-01-26T17:15:45.000Z
2022-03-29T21:36:28.000Z
src/lg_core/blockcom.h
daniellivingston/LaGriT
decd0ce0e5dab068034ef382cabcd134562de832
[ "Intel" ]
63
2017-02-08T21:56:04.000Z
2022-03-24T06:48:36.000Z
block data blockcom implicit none C C####################################################################### C C PURPOSE - C C THIS ROUTINE INITIALIZES DATA IN A NUMBER OF COMMON BLOCKS. C C C INPUT ARGUMENTS - C C NONE C C C OUTPUT ARGUMENTS - C C NONE C C C CHANGE HISTORY - C C $Log: blockcom.h,v $ C Revision 2.00 2007/11/05 19:45:46 spchu C Import to CVS C CPVCS CPVCS Rev 1.1 20 Jun 2001 15:37:04 kuprat CPVCS Propagated Tinka's fix from blockcom_nosb.f: CPVCS fixed error in ielmnode0 for pri and hex CPVCS CPVCS Rev 1.0 Fri Apr 07 10:38:58 2000 dcg CPVCS Initial revision. CPVCS CPVCS Rev 1.2 Wed Apr 05 15:47:30 2000 nnc CPVCS Removed the stub routine that was added to force linking of the CPVCS block data under the Absoft compiler. Instead we now include CPVCS this file in initlagrit_nosb.f. CPVCS CPVCS Rev 1.1 Wed Apr 05 13:34:06 2000 nnc CPVCS Minor source modifications required by the Absoft compiler. CPVCS CPVCS Rev 1.0 24 Jan 2000 16:20:52 dcg CPVCS Initial revision. CPVCS CPVCS Rev 1.58 Fri Nov 12 09:07:24 1999 dcg CPVCS remove unused variables CPVCS CPVCS Rev 1.57 Tue Jun 29 14:25:04 1999 jtg CPVCS removed the tabs ... CPVCS CPVCS Rev 1.56 Tue Jun 29 13:53:30 1999 jtg CPVCS additional local element data structures added (ielmedge2, CPVCS ielmface3,ielmface4,ielmnode0,ielmnode1,ielmnode2,ielmnode3) CPVCS CPVCS Rev 1.55 Wed Sep 30 11:59:22 1998 dcg CPVCS fix qmbuff common CPVCS CPVCS Rev 1.54 Fri Jun 19 16:51:22 1998 dcg CPVCS allow longer dictionary path CPVCS CPVCS Rev 1.53 Wed Nov 26 11:26:58 1997 dcg CPVCS ibm change - remove data statement for variable not in common CPVCS CPVCS Rev 1.52 Wed Nov 19 16:46:44 1997 dcg CPVCS add save statement CPVCS add geometry common block and include file CPVCS CPVCS Rev 1.50 Fri Oct 03 12:07:34 1997 dcg CPVCS fix getcmds common blocks - make lengths match CPVCS lengths in getcmds.f CPVCS CPVCS Rev 1.49 Wed May 14 15:19:14 1997 dcg CPVCS eliminate double initializing of nwrunpar, irunparm(1) CPVCS these were equivalenced in a .h file CPVCS CPVCS Rev 1.48 Mon Apr 14 16:39:10 1997 pvcs CPVCS No change. CPVCS CPVCS Rev 1.47 Tue Nov 05 10:05:12 1996 dcg CPVCS separate integer,real and charater variable in common CPVCS CPVCS Rev 1.46 Wed May 22 10:13:30 1996 dcg CPVCS get nconbnd from mesh object CPVCS CPVCS Rev 1.45 Thu May 16 10:21:42 1996 dcg CPVCS changes for new interface type 3 and for new icontab, xcontab CPVCS CPVCS Rev 1.43 Fri May 03 10:46:58 1996 dcg CPVCS changes for new point type --virtual interfaces CPVCS CPVCS Rev 1.42 Fri Mar 08 09:41:56 1996 jxf CPVCS Added marching cubes tables for prisms. CPVCS CPVCS Rev 1.41 Wed Jan 24 12:21:48 1996 jxf CPVCS Added common block and data for isosurface marching cubes. CPVCS CPVCS Rev 1.40 11/16/95 17:10:16 het CPVCS Modify the inside_hex, inside_tet, inside_quad and inside_tri routines CPVCS CPVCS Rev 1.39 09/13/95 14:34:34 het CPVCS Correct an error CPVCS CPVCS Rev 1.38 08/30/95 21:07:34 het CPVCS Put cmo table data into the cmoatt storage block CPVCS CPVCS Rev 1.37 08/22/95 06:52:06 het CPVCS Split the storage block for CMO variables. CPVCS CPVCS Rev 1.36 07/17/95 16:02:16 dcg CPVCS use names for point types CPVCS CPVCS Rev 1.35 06/07/95 16:13:02 het CPVCS Change character*32 idsb to character*132 idsb CPVCS CPVCS Rev 1.34 06/05/95 10:37:48 het CPVCS Make changes for hybrid_grids CPVCS CPVCS Rev 1.33 05/30/95 07:50:30 het CPVCS Replace mesh_object subroutine parameters by cmo-calls CPVCS CPVCS Rev 1.32 05/26/95 13:23:18 het CPVCS CPVCS CPVCS Rev 1.31 05/23/95 08:55:18 het CPVCS Add the include file for blockini.h CPVCS CPVCS Rev 1.30 05/11/95 13:24:18 het CPVCS Initialize the nwrunprm variable CPVCS CPVCS Rev 1.29 05/05/95 09:23:56 ejl CPVCS Changed name of epsilond to epsilonl. CPVCS CPVCS Rev 1.28 05/04/95 10:16:16 ejl CPVCS Added epsilond, epsilona, epsilonv to the dictionary CPVCS CPVCS Rev 1.27 05/02/95 16:46:20 het CPVCS Correct an error with nwrunpar in blockcom.f CPVCS CPVCS Rev 1.26 05/01/95 08:35:40 het CPVCS Modifiy all the storage block calles for long names CPVCS CPVCS Rev 1.25 03/31/95 12:42:44 dcg CPVCS fix psetc common block to match character*32 lengths CPVCS CPVCS CPVCS Rev 1.22 03/28/95 12:35:14 het CPVCS Add the binary dumpx3d/readx3d commands and correct associated mm-errors. CPVCS CPVCS Rev 1.21 03/23/95 22:57:14 het CPVCS Add the model routines and add the cmo name into the idsbs CPVCS CPVCS Rev 1.20 03/17/95 21:11:22 het CPVCS Add the model and dictionary calles CPVCS CPVCS Rev 1.19 02/16/95 10:37:16 ejl CPVCS Changed some of the entries in the Default Mesh Object. CPVCS CPVCS Rev 1.18 02/10/95 09:09:36 ejl CPVCS New routines: copy, move, delatt, length, list. CPVCS Cleaned up, implicit none. CPVCS CPVCS Rev 1.17 01/31/95 13:20:06 het CPVCS Make cmo a common block variable CPVCS CPVCS Rev 1.16 01/31/95 07:02:42 het CPVCS Add ign1 to the list of default mesh_object variables CPVCS CPVCS Rev 1.15 01/30/95 06:22:30 het CPVCS Fix several cmo errors CPVCS CPVCS Rev 1.14 01/24/95 08:54:42 het CPVCS Correct an error initializiing the cmo data. CPVCS CPVCS CPVCS Rev 1.13 01/23/95 12:41:18 het CPVCS Define the default cmo_attribute table. CPVCS CPVCS CPVCS Rev 1.12 01/19/95 09:51:58 het CPVCS CPVCS CPVCS Rev 1.11 01/13/95 18:20:10 het CPVCS CPVCS CPVCS Rev 1.10 01/09/95 17:32:14 het CPVCS Unicos changes. CPVCS CPVCS CPVCS Rev 1.9 01/02/95 15:11:32 het CPVCS Correct the common for getcmds. CPVCS CPVCS CPVCS Rev 1.8 12/24/94 11:10:38 het CPVCS Remove the xbb() and coord() arrays to the chydro.h include file. CPVCS CPVCS CPVCS Rev 1.7 12/11/94 18:35:20 het CPVCS Fixed an error for the SGI. CPVCS CPVCS CPVCS Rev 1.6 12/09/94 22:48:40 het CPVCS Make changes to support the new cmo_ routines. CPVCS CPVCS CPVCS Rev 1.5 12/06/94 19:09:42 het CPVCS Add the data definition for the current mesh object definition. CPVCS CPVCS CPVCS Rev 1.4 12/02/94 16:18:50 dcg CPVCS changes required to compile on IBM RS6000 CPVCS CPVCS Rev 1.3 11/23/94 10:15:02 dcg CPVCS fixed IBM specific compiler errors CPVCS CPVCS Rev 1.2 11/22/94 14:45:28 dcg CPVCS change default code version information CPVCS CPVCS Rev 1.1 11/17/94 22:04:52 het CPVCS Added block data for the "neibor.h" include file. CPVCS C C####################################################################### C include "chydro.h" include "consts.h" include "cmerge.h" include "local_element.h" save C C ****************************************************************** C C LOG MESSAGES. C character logmess*132 common /logmes1/ logmess C C####################################################################### C C THIS COMDECK CONTAINS NEIGHBOR RECONNECTION DATA. C include "neibor.h" C C C C THESE ARRAYS CONTAIN THE LAST MESSAGE PROCESSED SO THAT IT CAN BE C REPEATED. integer nd,id parameter ( nd=5 ) common /getcmd1i/ id(nd) integer isotyp,isodat integer iiq common /mcube/ isotyp(368), isodat(8,368) C common/kent1/igeom_gwt integer igeom_gwt C C THIS COMMON PROVIDES SPACE FOR A CFTLIB MESSAGE BUFFER. C NOTE: THIS BUFFER IS 64 WORDS LONG FOLLOWED BY 1 WORD THAT C INDICATES HOW MANY CHARACTERS ARE IN THE BUFFER. IF THE C FIRST WORD EQUALS -1, THEN NO MESSAGE IS PRESENT. C C C ****************************************************************** C C INITIALIZE MERGE DATA. integer i, j C data(mtable( 0,i),i=0,59)/1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable( 1,i),i=0,59)/1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable( 2,i),i=0,59)/1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable( 3,i),i=0,59)/1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable( 4,i),i=0,59)/1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable( 5,i),i=0,59)/1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable( 6,i),i=0,59)/1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable( 7,i),i=0,59)/1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable( 8,i),i=0,59)/1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable( 9,i),i=0,59)/1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(10,i),i=0,59)/1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(11,i),i=0,59)/1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(12,i),i=0,59)/1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(13,i),i=0,59)/1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(14,i),i=0,59)/1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(15,i),i=0,59)/1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(16,i),i=0,59)/1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(17,i),i=0,59)/1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(18,i),i=0,59)/1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(19,i),i=0,59)/1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(20,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(21,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(22,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(23,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(24,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(25,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(26,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(27,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(28,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(29,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(30,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(31,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(32,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(33,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(34,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(35,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(36,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(37,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(38,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(39,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(40,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(41,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(42,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(43,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(44,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(45,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(46,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(47,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(48,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(49,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(50,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(51,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(52,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(53,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(54,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(55,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(56,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(57,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(58,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ data(mtable(59,i),i=0,59)/0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0/ C C ****************************************************************** C C C TETRAHEDRON DATA C c comment out initialization and let compiler take care of it c this causes fits on mac os x compilers c because we have 2 instances of pointer sizes c see kfix and xfix in neibor.h c data ntetmax/0/ C ****************************************************************** C C C FITWORD PACKING/UNPACKING DATA FOR TYPE 1 FITWORDS. C data ifitpst1, ifitpen1 / 0, 7 / data ifitpint, ifitpini / 0, 2 / data ifitpvrt, ifitpvin / 3, 4 / data ifitpst2, ifitpen2 / 8, 19 / data ifitpvif, ifitpalb / 8, 9 / data ifitprfl, ifitpfre, ifitpirb, ifitpifb, ifitprfb, ifitpirf * / 10, 11, 12, 13, 14, 15 / data ifitpvrb, ifitpvfb, ifitpvrf, ifitpvir * / 16, 17, 18, 19 / data ifitpinb / 12 / data ifitpst3, ifitpen3 / 20, 29 / data ifitpmrg, ifitpdud / 20, 21 / data ifitpst4, ifitpen4 / 30, 256 / data ifitppin, ifitpcup / 30, 41 / C Point type names data inamprfl, inampfre, inampirb, inampifb, inamprfb, inampirf * , inampint, inampdud, inampmrg, inamppar, inampini * /'rfl','fre','irb','ifb','rfb','ifr','int','dud','mrg','par' * ,'ini'/ data inampvrb, inampvfb, inampvrf, inampvir, inampvif, inampalb * /'vrb','vfb','vrf','vir','vif','alb'/ data inampvrt, inampvin * /'vrt','vin'/ C C C ****************************************************************** C C INITIALIZE NEIGHBOR VARIALBES. C c C __________________________________________________________________ C C SET SOME MERGING COUNTERS. C data npairs, npairs2 / 0, 0 / C C ****************************************************************** C C SET COORDINATE SYSTEM ROTATION MATRIX (CURRENT AND SAVED) AND C COORDINATE SYSTEM ORIGIN (CURRENT AND SAVED) AND C NORMAL COORDINATE SYSTEM FLAGR(0=NORMAL). C data (rotatc(1,i), i=1,3) /1., 0., 0./ data (rotatc(2,i), i=1,3) /0., 1., 0./ data (rotatc(3,i), i=1,3) /0., 0., 1./ data (rotats(1,i), i=1,3) /1., 0., 0./ data (rotats(2,i), i=1,3) /0., 1., 0./ data (rotats(3,i), i=1,3) /0., 0., 1./ data (origc(i), i=1,3) /0., 0., 0./ data normflgc, normflgs / 0, 0 / data (origs(i), i=1,3) /0., 0., 0./ c C INITIALIZE BLOCK DATA STATAMENTS IN THE "NEIBOR.H" INCLUDE FILE. C C C C ****************************************************************** C C "face" DATA C data iflist / 2, 3, 4, * 1, 4, 3, * 1, 2, 4, * 1, 3, 2 / C C ****************************************************************** C C "face3ds" DATA C data iflists / 2, 3, 1, 3, 1, 2, 1, 2, 3 / C C ****************************************************************** C C "ielist" OR EDGELIST DATA C data ielist / 1, 2, * 3, 4, * 1, 3, * 4, 2, * 1, 4, * 2, 3, * 2, 3, * 1, 4, * 2, 4, * 3, 1, * 3, 4, * 1, 2 / C C ****************************************************************** C C "ielist2" OR ALTERNATIVE EDGELIST DATA C data ielist2 / 4, 5, * 6, 2, * 3, 6, * 1, 3, * 5, 1, * 2, 4 / C C ****************************************************************** C C "ifliplst" OR FLIP-LIST DATA C data ifliplst / 1, 4, * 3, 2, * 3, 4, * 2, 4, * 5, 1, * 5, 4, * 2, 6, * 3, 1, * 3, 6, * 2, 5, * 6, 1, * 6, 5 / C C ****************************************************************** C C "itpconv" OR POINT TYPE CONVERSION DATA C data itpconv( 0) / 0 / data itpconv( 2) / 2 / data itpconv(10) / 1 / data itpconv(11) / 1 / data itpconv(12) / 5 / C C ****************************************************************** C C REFLECTED BOUNDARY-POINT INFORMATION. C data nb / 0 / data ibbflag / 0 / data ib / nbpr*0 / data xbb, ybb, zbb / nbpr3*0.0, nbpr3*0.0, nbpr3*0.0 / data ubb, vbb, wbb / nbpr3*0.0, nbpr3*0.0, nbpr3*0.0 / data xbbnorm, ybbnorm, zbbnorm / nbpr*0, nbpr*0, nbpr*0 / data pbb, rbb, ebb,tbb / nbpr*0, nbpr*0, nbpr*0, nbpr*0 / C C C ****************************************************************** C C INITIALIZE THE LOCAL ELEMENT INFO C C data celmnames / 'pnt', * 'lin', * 'tri', * 'qud', * 'tet', * 'pyr', * 'pri', * 'hex', * 'hyb', * 'ply' * / C data ifelmpnt / 1 / data ifelmlin / 2 / data ifelmtri / 3 / data ifelmqud / 4 / data ifelmtet / 5 / data ifelmpyr / 6 / data ifelmpri / 7 / data ifelmhex / 8 / data ifelmhyb / 9 / data ifelmply / 10 / C data nelmnen / 1, 2, 3, 4, 4, 5, 6, 8, 10, 10 / data nelmnef / 0, 2, 3, 4, 4, 5, 5, 6, 10, 10 / data nelmnee / 0, 1, 3, 4, 6, 8, 9, 12, 12, 12 / C C C ***************************************************************** C Define the number of nodes associated with each element face. C C see also ielmface3 C data ielmface0 / 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, * 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, * 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, * 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, * 4, 3, 3, 3, 3, 0, 0, 0, 0, 0, * 3, 3, 4, 4, 4, 0, 0, 0, 0, 0, * 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 * / C C C C ***************************************************************** C Define the list of local nodes associated with each element face. C data ((ielmface1(i,j,1),i=1,maxnee1),j=1,maxnef) / 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0 * / data ((ielmface1(i,j,2),i=1,maxnee1),j=1,maxnef) / 1, 0, 0, 0, * 2, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0 * / data ((ielmface1(i,j,3),i=1,maxnee1),j=1,maxnef) / 2, 3, 0, 0, * 3, 1, 0, 0, * 1, 2, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0 * / data ((ielmface1(i,j,4),i=1,maxnee1),j=1,maxnef) / 1, 2, 0, 0, * 2, 3, 0, 0, * 3, 4, 0, 0, * 4, 1, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0 * / data ((ielmface1(i,j,5),i=1,maxnee1),j=1,maxnef) / 2, 3, 4, 0, * 1, 4, 3, 0, * 1, 2, 4, 0, * 1, 3, 2, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0 * / data ((ielmface1(i,j,6),i=1,maxnee1),j=1,maxnef) / 1, 4, 3, 2, * 1, 2, 5, 0, * 2, 3, 5, 0, * 3, 4, 5, 0, * 4, 1, 5, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0 * / data ((ielmface1(i,j,7),i=1,maxnee1),j=1,maxnef) / 1, 3, 2, 0, * 4, 5, 6, 0, * 1, 2, 5, 4, * 2, 3, 6, 5, * 1, 4, 6, 3, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0 * / data ((ielmface1(i,j,8),i=1,maxnee1),j=1,maxnef) / 1, 4, 3, 2, * 5, 6, 7, 8, * 1, 2, 6, 5, * 2, 3, 7, 6, * 3, 4, 8, 7, * 1, 5, 8, 4, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0 * / data ((ielmface1(i,j,9),i=1,maxnee1),j=1,maxnef) / 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0 * / data ((ielmface1(i,j,10),i=1,maxnee1),j=1,maxnef) / 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0 * / C C C ***************************************************************** C Define the local edges associated with each face. C data ((ielmface2(i,j,1),i=1,maxnee1),j=1,maxnef) / 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0 * / data ((ielmface2(i,j,2),i=1,maxnee1),j=1,maxnef) / 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0 * / data ((ielmface2(i,j,3),i=1,maxnee1),j=1,maxnef) / 3, 0, 0, 0, * 2, 0, 0, 0, * 1, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0 * / data ((ielmface2(i,j,4),i=1,maxnee1),j=1,maxnef) / 1, 0, 0, 0, * 3, 0, 0, 0, * 4, 0, 0, 0, * 2, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0 * / data ((ielmface2(i,j,5),i=1,maxnee1),j=1,maxnef) / 6, 5, 4, 0, * 6, 2, 3, 0, * 5, 3, 1, 0, * 4, 1, 2, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0 * / data ((ielmface2(i,j,6),i=1,maxnee1),j=1,maxnef) / 2, 6, 4, 1, * 1, 5, 3, 0, * 4, 7, 5, 0, * 6, 8, 7, 0, * 2, 3, 8, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0 * / data ((ielmface2(i,j,7),i=1,maxnee1),j=1,maxnef) / 2, 4, 1, 0, * 7, 9, 8, 0, * 1, 5, 7, 3, * 4, 6, 9, 5, * 3, 8, 6, 2, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0 * / data ((ielmface2(i,j,8),i=1,maxnee1),j=1,maxnef) / 2, 6, 4, 1, * 9,11,12,10, * 1, 5, 9, 3, * 4, 7,11, 5, * 6, 8,12, 7, * 3,10, 8, 2, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0 * / data ((ielmface2(i,j,9),i=1,maxnee1),j=1,maxnef) / 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0 * / data ((ielmface2(i,j,10),i=1,maxnee1),j=1,maxnef) / 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0, * 0, 0, 0, 0 * / C C C ***************************************************************** C Define the list of local nodes associated with each edge. C data ((ielmedge1(i,j,1),i=1,2),j=1,maxnee2) / 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0 * / data ((ielmedge1(i,j,2),i=1,2),j=1,maxnee2) / 1, 2, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0 * / data ((ielmedge1(i,j,3),i=1,2),j=1,maxnee2) / 1, 2, * 1, 3, * 2, 3, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0 * / data ((ielmedge1(i,j,4),i=1,2),j=1,maxnee2) / 1, 2, * 1, 4, * 2, 3, * 3, 4, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0 * / data ((ielmedge1(i,j,5),i=1,2),j=1,maxnee2) / 1, 2, * 1, 3, * 1, 4, * 2, 3, * 2, 4, * 3, 4, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0 * / data ((ielmedge1(i,j,6),i=1,2),j=1,maxnee2) / 1, 2, * 1, 4, * 1, 5, * 2, 3, * 2, 5, * 3, 4, * 3, 5, * 4, 5, * 0, 0, * 0, 0, * 0, 0, * 0, 0 * / data ((ielmedge1(i,j,7),i=1,2),j=1,maxnee2) / 1, 2, * 1, 3, * 1, 4, * 2, 3, * 2, 5, * 3, 6, * 4, 5, * 4, 6, * 5, 6, * 0, 0, * 0, 0, * 0, 0 * / data ((ielmedge1(i,j,8),i=1,2),j=1,maxnee2) / 1, 2, * 1, 4, * 1, 5, * 2, 3, * 2, 6, * 3, 4, * 3, 7, * 4, 8, * 5, 6, * 5, 8, * 6, 7, * 7, 8 * / data ((ielmedge1(i,j,9),i=1,2),j=1,maxnee2) / 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0 * / data ((ielmedge1(i,j,10),i=1,2),j=1,maxnee2) / 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0, * 0, 0 * / C C C ***************************************************************** C C Define the list of local faces associated with each edge. C C ielmedge2(1:2,1:nelmnee(itettyp(iel)),1:nelmtypes) C C jface=ielmedge2(i,j,ielmtyp) C jface is the i-th face touching the current edge j C for the current element type ielmtyp C C order is so that ielmedge2 1->2 consistently ordered C with ielmedge1 1->2. C C [for tri,qud: it is the i-th face iface C (using the face label for the face=edge topological object) C around the current node j C (the node being the effective "edge" for the 2d object), C and is ordered consistently with order of element) C data ((ielmedge2(i,j, 1),i=1,2),j=1,maxnee2) !pnt * / 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 / data ((ielmedge2(i,j, 2),i=1,2),j=1,maxnee2) !lin * / 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 / data ((ielmedge2(i,j, 3),i=1,2),j=1,maxnee2) !tri * / 3, 2, 1, 3, 2, 1, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 / data ((ielmedge2(i,j, 4),i=1,2),j=1,maxnee2) !qud * / 1, 4, 2, 1, 3, 2, 4, 3, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 / data ((ielmedge2(i,j, 5),i=1,2),j=1,maxnee2) !tet * / 4, 3, 2, 4, 3, 2, 4, 1, 1, 3, 2, 1, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 / data ((ielmedge2(i,j, 6),i=1,2),j=1,maxnee2) !pyr * / 1, 2, 5, 1, 2, 5, 1, 3, 3, 2, 1, 4, * 4, 3, 5, 4, 0, 0, 0, 0, 0, 0, 0, 0 / data ((ielmedge2(i,j, 7),i=1,2),j=1,maxnee2) !pri * / 1, 3, 5, 1, 3, 5, 1, 4, 4, 3, 5, 4, * 3, 2, 2, 5, 4, 2, 0, 0, 0, 0, 0, 0 / data ((ielmedge2(i,j, 8),i=1,2),j=1,maxnee2) !hex * / 1, 3, 6, 1, 3, 6, 1, 4, 4, 3, 1, 5, * 5, 4, 6, 5, 3, 2, 2, 6, 4, 2, 5, 2 / data ((ielmedge2(i,j, 9),i=1,2),j=1,maxnee2) !hyb * / 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 / data ((ielmedge2(i,j,10),i=1,2),j=1,maxnee2) !ply * / 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 / C C ***************************************************************** C C Define the local face to face element type relation C C ielmface3(1:nelmnef(itettyp(iel)),1:nelmtypes) C C jelmtyp=ielmface3(i,ielmtyp) C jelmtyp if the element type for the i-th face of the current element ielmtyp C C same as ielmface0 for all current element types, but keep in C case this changes in the future (eg, using polygon face type "ply") C data ielmface3 / 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, * 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, * 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, * 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, * 4, 3, 3, 3, 3, 0, 0, 0, 0, 0, * 3, 3, 4, 4, 4, 0, 0, 0, 0, 0, * 4, 4, 4, 4, 4, 4, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 * / C C C C ***************************************************************** C C Define the local face to neighbor local face relation C C ielmface4(1:ielmface0(j,itettyp(iel)),1:nelmnef(itettyp(iel)),1:nelmtypes) C C jface=ielmface4(i,j,ielmtyp) C jface is the i-th face across the i-th edge ielmface2(i,j,ielmtyp) C from the current face j C C [for tri,qud: face jface (face=edge topological object using face label) C across i-th local node inode=ielmface1(i,j,ielmtyp)] C data ((ielmface4(i,j, 1),i=1,maxnee1),j=1,maxnef) !pnt * / 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmface4(i,j, 2),i=1,maxnee1),j=1,maxnef) !lin * / 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmface4(i,j, 3),i=1,maxnee1),j=1,maxnef) !tri * / 3, 2, 0, 0, 1, 3, 0, 0, 2, 1, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmface4(i,j, 4),i=1,maxnee1),j=1,maxnef) !qud * / 4, 2, 0, 0, 1, 3, 0, 0, 2, 4, 0, 0, * 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmface4(i,j, 5),i=1,maxnee1),j=1,maxnef) !tet * / 2, 3, 4, 0, 1, 4, 3, 0, 1, 2, 4, 0, * 1, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmface4(i,j, 6),i=1,maxnee1),j=1,maxnef) !pyr * / 5, 4, 3, 2, 1, 3, 5, 0, 1, 4, 2, 0, * 1, 5, 3, 0, 1, 2, 4, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmface4(i,j, 7),i=1,maxnee1),j=1,maxnef) !pri * / 5, 4, 3, 0, 3, 4, 5, 0, 1, 4, 2, 5, * 1, 5, 2, 3, 3, 2, 4, 1, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmface4(i,j, 8),i=1,maxnee1),j=1,maxnef) !hex * / 6, 5, 4, 3, 3, 4, 5, 6, 1, 4, 2, 6, * 1, 5, 2, 3, 1, 6, 2, 4, 3, 2, 5, 1, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmface4(i,j, 9),i=1,maxnee1),j=1,maxnef) !hyb * / 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmface4(i,j,10),i=1,maxnee1),j=1,maxnef) !ply * / 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / C C ***************************************************************** C C Define the number of ("opposite nodes",edges,faces) associated w each node C C ielmnode0(1:nelmnen(itettyp(iel)),1:nelmtypes) C C analogous to ielmface0, this is the max values of the C "counter" for the ielmnodeX C C for "opposite node" definition: see ielmnode1 C data ielmnode0 * / 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, * 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, * 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, * 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, * 3, 3, 3, 3, 4, 0, 0, 0, 0, 0, * 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, * 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 / C C ***************************************************************** C C Define the local node to "opposite" local node relation C C ielmnode1(1:ielmnode0(j,itettyp(iel)),1:nelmnen(itettyp(iel)),1:nelmtypes) C C jnode=ielmnode1(i,j,ielmtyp) C jnode is node at other end of the i-th edge ielmnode2(i,j,ielmtyp) C for the current node j of the current element ielmtyp C C order is positive interior angle C C "opposite node" means node at opposite end of the adjacent edge of the C ielmnode2 relation C C [for tri,qud: uses edge label for face=edge topological object] C [for lin: this gives the node on the other side of the element] C data ((ielmnode1(i,j, 1),i=1,maxnee1),j=1,maxnen) !pnt * / 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode1(i,j, 2),i=1,maxnee1),j=1,maxnen) !lin * / 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode1(i,j, 3),i=1,maxnee1),j=1,maxnen) !tri * / 2, 3, 0, 0, 3, 1, 0, 0, 1, 2, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode1(i,j, 4),i=1,maxnee1),j=1,maxnen) !qud * / 2, 4, 0, 0, 3, 1, 0, 0, 4, 2, 0, 0, * 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode1(i,j, 5),i=1,maxnee1),j=1,maxnen) !tet * / 2, 3, 4, 0, 1, 4, 3, 0, 1, 2, 4, 0, * 1, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode1(i,j, 6),i=1,maxnee1),j=1,maxnen) !pyr * / 2, 4, 5, 0, 3, 1, 5, 0, 4, 2, 5, 0, * 1, 3, 5, 0, 1, 4, 3, 2, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode1(i,j, 7),i=1,maxnee1),j=1,maxnen) !pri * / 2, 3, 4, 0, 3, 1, 5, 0, 1, 2, 6, 0, * 6, 5, 1, 0, 4, 6, 2, 0, 5, 4, 3, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode1(i,j, 8),i=1,maxnee1),j=1,maxnen) !hex * / 2, 4, 5, 0, 3, 1, 6, 0, 4, 2, 7, 0, * 1, 3, 8, 0, 8, 6, 1, 0, 5, 7, 2, 0, * 6, 8, 3, 0, 7, 5, 4, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode1(i,j, 9),i=1,maxnee1),j=1,maxnen) !hyb * / 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode1(i,j,10),i=1,maxnee1),j=1,maxnen) !ply * / 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / C C ***************************************************************** C C Define the local node to adjacent local edges relation C C ielmnode2(1:ielmnode0(j,itettyp(iel)),1:nelmnen(itettyp(iel)),1:nelmtypes) C C jedge=ielmnode1(i,j,ielmtyp) C jedge if the i-th edge connected connected to the current node i C of the current element type ielmtyp C C order is positive interior angle (edge order same order as opp node) C C [for tri,qud: this uses the edge label for the face=edge topological object] C [for lin: this uses the edge label which is topologically the "interior"] C data ((ielmnode2(i,j, 1),i=1,maxnee1),j=1,maxnen) !pnt * / 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode2(i,j, 2),i=1,maxnee1),j=1,maxnen) !lin * / 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode2(i,j, 3),i=1,maxnee1),j=1,maxnen) !tri * / 1, 2, 0, 0, 3, 1, 0, 0, 2, 3, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode2(i,j, 4),i=1,maxnee1),j=1,maxnen) !qud * / 1, 2, 0, 0, 3, 1, 0, 0, 4, 3, 0, 0, * 2, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode2(i,j, 5),i=1,maxnee1),j=1,maxnen) !tet * / 1, 2, 3, 0, 1, 5, 4, 0, 2, 4, 6, 0, * 3, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode2(i,j, 6),i=1,maxnee1),j=1,maxnen) !pyr * / 1, 2, 3, 0, 4, 1, 5, 0, 6, 4, 7, 0, * 2, 6, 8, 0, 3, 8, 7, 5, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode2(i,j, 7),i=1,maxnee1),j=1,maxnen) !pri * / 1, 2, 3, 0, 4, 1, 5, 0, 2, 4, 6, 0, * 8, 7, 3, 0, 7, 9, 5, 0, 9, 8, 6, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode2(i,j, 8),i=1,maxnee1),j=1,maxnen) !hex * / 1, 2, 3, 0, 4, 1, 5, 0, 6, 4, 7, 0, * 2, 6, 8, 0, 10, 9, 3, 0, 9,11, 5, 0, * 11,12, 7, 0, 12,10, 8, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode2(i,j, 9),i=1,maxnee1),j=1,maxnen) !hyb * / 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode2(i,j,10),i=1,maxnee1),j=1,maxnen) !ply * / 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / C C ***************************************************************** C C Define the local node to adjacent local faces relation C C ielmnode3(1:ielmnode0(j,itettyp(iel)),1:nelmnen(itettyp(iel)),1:nelmtypes) C C jface=ielmnode3(i,j,ielmtyp) C jface is the face between the i-th and (i+1)-th edges C ielmnode2 (i,j,ielmtyp), ielmnode2(i+1,j,ielmtyp) C of adjacent to the current node j of the current element typ ielmtyp C C order is positive interior angle (face 1 between opp edge/node 1,2 etc) C C [for tri,qud: this uses the face label for the face=edge topological object] C [for lin: this gives the edge label which is topologically the "interior"] C data ((ielmnode3(i,j, 1),i=1,maxnee1),j=1,maxnen) !pnt * / 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode3(i,j, 2),i=1,maxnee1),j=1,maxnen) !lin * / 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode3(i,j, 3),i=1,maxnee1),j=1,maxnen) !tri * / 3, 2, 0, 0, 1, 3, 0, 0, 2, 1, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode3(i,j, 4),i=1,maxnee1),j=1,maxnen) !qud * / 1, 4, 0, 0, 2, 1, 0, 0, 3, 2, 0, 0, * 4, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode3(i,j, 5),i=1,maxnee1),j=1,maxnen) !tet * / 4, 2, 3, 0, 3, 1, 4, 0, 4, 1, 2, 0, * 2, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode3(i,j, 6),i=1,maxnee1),j=1,maxnen) !pyr * / 1, 5, 2, 0, 1, 2, 3, 0, 1, 3, 4, 0, * 1, 4, 5, 0, 5, 4, 3, 2, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode3(i,j, 7),i=1,maxnee1),j=1,maxnen) !pri * / 1, 5, 3, 0, 1, 3, 4, 0, 1, 4, 5, 0, * 2, 3, 5, 0, 2, 4, 3, 0, 2, 5, 4, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode3(i,j, 8),i=1,maxnee1),j=1,maxnen) !hex * / 1, 6, 3, 0, 1, 3, 4, 0, 1, 4, 5, 0, * 1, 5, 6, 0, 2, 3, 6, 0, 2, 4, 3, 0, * 2, 5, 4, 0, 2, 6, 5, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode3(i,j, 9),i=1,maxnee1),j=1,maxnen) !hyb * / 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / data ((ielmnode3(i,j,10),i=1,maxnee1),j=1,maxnen) !ply * / 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, * 0, 0, 0, 0 / C ****************************************************************** C C DATA FOR ISOSURFACE.F MARCHING CUBES C C C First 16 are for tets and only go out to 4 in the first index. C data(isodat(1,iiq),iiq=1,16)/0,1,2,1,3,1,2,4,4,2,1,3,1,2,1,0/ data(isodat(2,iiq),iiq=1,16)/0,2,1,2,1,3,3,3,3,3,3,1,2,1,2,0/ data(isodat(3,iiq),iiq=1,16)/0,3,3,3,2,4,4,2,2,4,4,2,3,3,3,0/ data(isodat(4,iiq),iiq=1,16)/0,4,4,4,4,2,1,1,1,1,2,4,4,4,4,0/ C C The next 256 are for hexes. C data(isodat(iiq,17),iiq=1,8)/1,2,4,3,5,6,8,7/ data(isodat(iiq,18),iiq=1,8)/1,2,4,3,5,6,8,7/ data(isodat(iiq,19),iiq=1,8)/2,3,1,4,6,7,5,8/ data(isodat(iiq,20),iiq=1,8)/1,2,4,3,5,6,8,7/ data(isodat(iiq,21),iiq=1,8)/3,4,2,1,7,8,6,5/ data(isodat(iiq,22),iiq=1,8)/2,3,1,4,6,7,5,8/ data(isodat(iiq,23),iiq=1,8)/2,3,1,4,6,7,5,8/ data(isodat(iiq,24),iiq=1,8)/2,3,1,4,6,7,5,8/ data(isodat(iiq,25),iiq=1,8)/4,1,3,2,8,5,7,6/ data(isodat(iiq,26),iiq=1,8)/4,1,3,2,8,5,7,6/ data(isodat(iiq,27),iiq=1,8)/1,2,4,3,5,6,8,7/ data(isodat(iiq,28),iiq=1,8)/1,2,4,3,5,6,8,7/ data(isodat(iiq,29),iiq=1,8)/3,4,2,1,7,8,6,5/ data(isodat(iiq,30),iiq=1,8)/4,1,3,2,8,5,7,6/ data(isodat(iiq,31),iiq=1,8)/3,4,2,1,7,8,6,5/ data(isodat(iiq,32),iiq=1,8)/1,2,4,3,5,6,8,7/ data(isodat(iiq,33),iiq=1,8)/5,1,8,4,6,2,7,3/ data(isodat(iiq,34),iiq=1,8)/5,1,8,4,6,2,7,3/ data(isodat(iiq,35),iiq=1,8)/1,5,2,6,4,8,3,7/ data(isodat(iiq,36),iiq=1,8)/1,5,2,6,4,8,3,7/ data(isodat(iiq,37),iiq=1,8)/1,2,4,3,5,6,8,7/ data(isodat(iiq,38),iiq=1,8)/1,2,4,3,5,6,8,7/ data(isodat(iiq,39),iiq=1,8)/2,1,6,5,3,4,7,8/ data(isodat(iiq,40),iiq=1,8)/1,2,4,3,5,6,8,7/ data(isodat(iiq,41),iiq=1,8)/1,4,5,8,2,3,6,7/ data(isodat(iiq,42),iiq=1,8)/1,4,5,8,2,3,6,7/ data(isodat(iiq,43),iiq=1,8)/1,2,4,3,5,6,8,7/ data(isodat(iiq,44),iiq=1,8)/1,2,4,3,5,6,8,7/ data(isodat(iiq,45),iiq=1,8)/4,8,1,5,3,7,2,6/ data(isodat(iiq,46),iiq=1,8)/1,4,2,3,5,8,6,7/ data(isodat(iiq,47),iiq=1,8)/1,2,4,3,5,6,8,7/ data(isodat(iiq,48),iiq=1,8)/1,2,4,3,5,6,8,7/ data(isodat(iiq,49),iiq=1,8)/6,5,7,8,2,1,3,4/ data(isodat(iiq,50),iiq=1,8)/2,1,6,5,3,4,7,8/ data(isodat(iiq,51),iiq=1,8)/2,6,3,7,1,5,4,8/ data(isodat(iiq,52),iiq=1,8)/2,1,6,5,3,4,7,8/ data(isodat(iiq,53),iiq=1,8)/2,6,3,7,1,5,4,8/ data(isodat(iiq,54),iiq=1,8)/2,3,1,4,6,7,5,8/ data(isodat(iiq,55),iiq=1,8)/2,6,3,7,1,5,4,8/ data(isodat(iiq,56),iiq=1,8)/2,3,1,4,6,7,5,8/ data(isodat(iiq,57),iiq=1,8)/2,3,1,4,6,7,5,8/ data(isodat(iiq,58),iiq=1,8)/1,5,2,6,4,8,3,7/ data(isodat(iiq,59),iiq=1,8)/2,3,1,4,6,7,5,8/ data(isodat(iiq,60),iiq=1,8)/2,1,3,4,6,5,7,8/ data(isodat(iiq,61),iiq=1,8)/3,2,7,6,4,1,8,5/ data(isodat(iiq,62),iiq=1,8)/2,3,1,4,6,7,5,8/ data(isodat(iiq,63),iiq=1,8)/2,3,1,4,6,7,5,8/ data(isodat(iiq,64),iiq=1,8)/2,3,1,4,6,7,5,8/ data(isodat(iiq,65),iiq=1,8)/6,5,7,8,2,1,3,4/ data(isodat(iiq,66),iiq=1,8)/5,6,1,2,8,7,4,3/ data(isodat(iiq,67),iiq=1,8)/6,2,5,1,7,3,8,4/ data(isodat(iiq,68),iiq=1,8)/2,1,6,5,3,4,7,8/ data(isodat(iiq,69),iiq=1,8)/6,7,2,3,5,8,1,4/ data(isodat(iiq,70),iiq=1,8)/2,1,6,5,3,4,7,8/ data(isodat(iiq,71),iiq=1,8)/6,2,7,3,5,1,8,4/ data(isodat(iiq,72),iiq=1,8)/2,1,6,5,3,4,7,8/ data(isodat(iiq,73),iiq=1,8)/5,1,8,4,6,2,7,3/ data(isodat(iiq,74),iiq=1,8)/5,1,8,4,6,2,7,3/ data(isodat(iiq,75),iiq=1,8)/1,5,2,6,4,8,3,7/ data(isodat(iiq,76),iiq=1,8)/1,5,2,6,4,8,3,7/ data(isodat(iiq,77),iiq=1,8)/1,2,4,3,5,6,8,7/ data(isodat(iiq,78),iiq=1,8)/1,2,4,3,5,6,8,7/ data(isodat(iiq,79),iiq=1,8)/2,1,6,5,3,4,7,8/ data(isodat(iiq,80),iiq=1,8)/1,2,4,3,5,6,8,7/ data(isodat(iiq,81),iiq=1,8)/7,6,8,5,3,2,4,1/ data(isodat(iiq,82),iiq=1,8)/3,4,2,1,7,8,6,5/ data(isodat(iiq,83),iiq=1,8)/6,7,2,3,5,8,1,4/ data(isodat(iiq,84),iiq=1,8)/2,6,3,7,1,5,4,8/ data(isodat(iiq,85),iiq=1,8)/7,3,6,2,8,4,5,1/ data(isodat(iiq,86),iiq=1,8)/3,4,2,1,7,8,6,5/ data(isodat(iiq,87),iiq=1,8)/3,2,7,6,4,1,8,5/ data(isodat(iiq,88),iiq=1,8)/3,2,4,1,7,6,8,5/ data(isodat(iiq,89),iiq=1,8)/3,7,4,8,2,6,1,5/ data(isodat(iiq,90),iiq=1,8)/4,3,8,7,1,2,5,6/ data(isodat(iiq,91),iiq=1,8)/3,4,2,1,7,8,6,5/ data(isodat(iiq,92),iiq=1,8)/3,4,2,1,7,8,6,5/ data(isodat(iiq,93),iiq=1,8)/3,7,4,8,2,6,1,5/ data(isodat(iiq,94),iiq=1,8)/3,4,2,1,7,8,6,5/ data(isodat(iiq,95),iiq=1,8)/3,4,2,1,7,8,6,5/ data(isodat(iiq,96),iiq=1,8)/3,4,2,1,7,8,6,5/ data(isodat(iiq,97),iiq=1,8)/6,5,7,8,2,1,3,4/ data(isodat(iiq,98),iiq=1,8)/5,8,6,7,1,4,2,3/ data(isodat(iiq,99),iiq=1,8)/6,5,7,8,2,1,3,4/ data(isodat(iiq,100),iiq=1,8)/6,2,5,1,7,3,8,4/ data(isodat(iiq,101),iiq=1,8)/7,6,8,5,3,2,4,1/ data(isodat(iiq,102),iiq=1,8)/4,8,1,5,3,7,2,6/ data(isodat(iiq,103),iiq=1,8)/6,7,2,3,5,8,1,4/ data(isodat(iiq,104),iiq=1,8)/2,6,3,7,1,5,4,8/ data(isodat(iiq,105),iiq=1,8)/8,5,4,1,7,6,3,2/ data(isodat(iiq,106),iiq=1,8)/8,5,4,1,7,6,3,2/ data(isodat(iiq,107),iiq=1,8)/2,3,1,4,6,7,5,8/ data(isodat(iiq,108),iiq=1,8)/4,1,3,2,8,5,7,6/ data(isodat(iiq,109),iiq=1,8)/8,4,7,3,5,1,6,2/ data(isodat(iiq,110),iiq=1,8)/4,8,1,5,3,7,2,6/ data(isodat(iiq,111),iiq=1,8)/2,3,1,4,6,7,5,8/ data(isodat(iiq,112),iiq=1,8)/2,3,1,4,6,7,5,8/ data(isodat(iiq,113),iiq=1,8)/7,6,8,5,3,2,4,1/ data(isodat(iiq,114),iiq=1,8)/6,2,5,1,7,3,8,4/ data(isodat(iiq,115),iiq=1,8)/6,7,2,3,5,8,1,4/ data(isodat(iiq,116),iiq=1,8)/2,6,3,7,1,5,4,8/ data(isodat(iiq,117),iiq=1,8)/7,3,6,2,8,4,5,1/ data(isodat(iiq,118),iiq=1,8)/2,6,3,7,1,5,4,8/ data(isodat(iiq,119),iiq=1,8)/2,6,3,7,1,5,4,8/ data(isodat(iiq,120),iiq=1,8)/2,6,3,7,1,5,4,8/ data(isodat(iiq,121),iiq=1,8)/7,8,3,4,6,5,2,1/ data(isodat(iiq,122),iiq=1,8)/2,3,1,4,6,7,5,8/ data(isodat(iiq,123),iiq=1,8)/3,2,7,6,4,1,8,5/ data(isodat(iiq,124),iiq=1,8)/2,3,1,4,6,7,5,8/ data(isodat(iiq,125),iiq=1,8)/3,7,2,6,4,8,1,5/ data(isodat(iiq,126),iiq=1,8)/3,2,7,6,4,1,8,5/ data(isodat(iiq,127),iiq=1,8)/3,2,7,6,4,1,8,5/ data(isodat(iiq,128),iiq=1,8)/2,3,1,4,6,7,5,8/ data(isodat(iiq,129),iiq=1,8)/6,5,7,8,2,1,3,4/ data(isodat(iiq,130),iiq=1,8)/5,6,8,7,1,2,4,3/ data(isodat(iiq,131),iiq=1,8)/6,5,7,8,2,1,3,4/ data(isodat(iiq,132),iiq=1,8)/6,2,5,1,7,3,8,4/ data(isodat(iiq,133),iiq=1,8)/7,6,8,5,3,2,4,1/ data(isodat(iiq,134),iiq=1,8)/6,2,5,1,7,3,8,4/ data(isodat(iiq,135),iiq=1,8)/6,7,2,3,5,8,1,4/ data(isodat(iiq,136),iiq=1,8)/2,6,3,7,1,5,4,8/ data(isodat(iiq,137),iiq=1,8)/8,7,5,6,4,3,1,2/ data(isodat(iiq,138),iiq=1,8)/5,8,6,7,1,4,2,3/ data(isodat(iiq,139),iiq=1,8)/7,6,8,5,3,2,4,1/ data(isodat(iiq,140),iiq=1,8)/2,1,6,5,3,4,7,8/ data(isodat(iiq,141),iiq=1,8)/7,8,3,4,6,5,2,1/ data(isodat(iiq,142),iiq=1,8)/2,3,1,4,6,7,5,8/ data(isodat(iiq,143),iiq=1,8)/2,6,3,7,1,5,4,8/ data(isodat(iiq,144),iiq=1,8)/2,3,1,4,6,7,5,8/ data(isodat(iiq,145),iiq=1,8)/8,5,4,1,7,6,3,2/ data(isodat(iiq,146),iiq=1,8)/5,1,8,4,6,2,7,3/ data(isodat(iiq,147),iiq=1,8)/4,1,3,2,8,5,7,6/ data(isodat(iiq,148),iiq=1,8)/1,4,5,8,2,3,6,7/ data(isodat(iiq,149),iiq=1,8)/4,3,8,7,1,2,5,6/ data(isodat(iiq,150),iiq=1,8)/4,1,3,2,8,5,7,6/ data(isodat(iiq,151),iiq=1,8)/3,7,4,8,2,6,1,5/ data(isodat(iiq,152),iiq=1,8)/4,1,3,2,8,5,7,6/ data(isodat(iiq,153),iiq=1,8)/4,8,1,5,3,7,2,6/ data(isodat(iiq,154),iiq=1,8)/4,8,1,5,3,7,2,6/ data(isodat(iiq,155),iiq=1,8)/4,1,3,2,8,5,7,6/ data(isodat(iiq,156),iiq=1,8)/4,1,3,2,8,5,7,6/ data(isodat(iiq,157),iiq=1,8)/4,3,8,7,1,2,5,6/ data(isodat(iiq,158),iiq=1,8)/4,1,3,2,8,5,7,6/ data(isodat(iiq,159),iiq=1,8)/4,3,1,2,8,7,5,6/ data(isodat(iiq,160),iiq=1,8)/4,1,3,2,8,5,7,6/ data(isodat(iiq,161),iiq=1,8)/8,5,4,1,7,6,3,2/ data(isodat(iiq,162),iiq=1,8)/5,1,8,4,6,2,7,3/ data(isodat(iiq,163),iiq=1,8)/5,6,1,2,8,7,4,3/ data(isodat(iiq,164),iiq=1,8)/1,5,4,8,2,6,3,7/ data(isodat(iiq,165),iiq=1,8)/8,4,7,3,5,1,6,2/ data(isodat(iiq,166),iiq=1,8)/4,8,1,5,3,7,2,6/ data(isodat(iiq,167),iiq=1,8)/4,1,3,2,8,5,7,6/ data(isodat(iiq,168),iiq=1,8)/1,4,5,8,2,3,6,7/ data(isodat(iiq,169),iiq=1,8)/8,5,4,1,7,6,3,2/ data(isodat(iiq,170),iiq=1,8)/5,1,8,4,6,2,7,3/ data(isodat(iiq,171),iiq=1,8)/1,4,5,8,2,3,6,7/ data(isodat(iiq,172),iiq=1,8)/1,4,5,8,2,3,6,7/ data(isodat(iiq,173),iiq=1,8)/4,8,1,5,3,7,2,6/ data(isodat(iiq,174),iiq=1,8)/4,8,1,5,3,7,2,6/ data(isodat(iiq,175),iiq=1,8)/4,1,3,2,8,5,7,6/ data(isodat(iiq,176),iiq=1,8)/4,1,3,2,8,5,7,6/ data(isodat(iiq,177),iiq=1,8)/5,8,6,7,1,4,2,3/ data(isodat(iiq,178),iiq=1,8)/5,1,8,4,6,2,7,3/ data(isodat(iiq,179),iiq=1,8)/6,5,7,8,2,1,3,4/ data(isodat(iiq,180),iiq=1,8)/5,6,1,2,8,7,4,3/ data(isodat(iiq,181),iiq=1,8)/7,6,8,5,3,2,4,1/ data(isodat(iiq,182),iiq=1,8)/1,2,4,3,5,6,8,7/ data(isodat(iiq,183),iiq=1,8)/7,3,6,2,8,4,5,1/ data(isodat(iiq,184),iiq=1,8)/1,2,4,3,5,6,8,7/ data(isodat(iiq,185),iiq=1,8)/8,7,5,6,4,3,1,2/ data(isodat(iiq,186),iiq=1,8)/5,1,8,4,6,2,7,3/ data(isodat(iiq,187),iiq=1,8)/5,1,8,4,6,2,7,3/ data(isodat(iiq,188),iiq=1,8)/1,5,2,6,4,8,3,7/ data(isodat(iiq,189),iiq=1,8)/7,8,3,4,6,5,2,1/ data(isodat(iiq,190),iiq=1,8)/3,4,2,1,7,8,6,5/ data(isodat(iiq,191),iiq=1,8)/3,7,4,8,2,6,1,5/ data(isodat(iiq,192),iiq=1,8)/1,2,4,3,5,6,8,7/ data(isodat(iiq,193),iiq=1,8)/5,8,6,7,1,4,2,3/ data(isodat(iiq,194),iiq=1,8)/5,1,8,4,6,2,7,3/ data(isodat(iiq,195),iiq=1,8)/6,5,7,8,2,1,3,4/ data(isodat(iiq,196),iiq=1,8)/5,6,1,2,8,7,4,3/ data(isodat(iiq,197),iiq=1,8)/7,6,8,5,3,2,4,1/ data(isodat(iiq,198),iiq=1,8)/8,5,4,1,7,6,3,2/ data(isodat(iiq,199),iiq=1,8)/6,7,2,3,5,8,1,4/ data(isodat(iiq,200),iiq=1,8)/1,5,2,6,4,8,3,7/ data(isodat(iiq,201),iiq=1,8)/8,5,7,6,4,1,3,2/ data(isodat(iiq,202),iiq=1,8)/5,1,8,4,6,2,7,3/ data(isodat(iiq,203),iiq=1,8)/5,1,8,4,6,2,7,3/ data(isodat(iiq,204),iiq=1,8)/5,1,8,4,6,2,7,3/ data(isodat(iiq,205),iiq=1,8)/8,7,5,6,4,3,1,2/ data(isodat(iiq,206),iiq=1,8)/1,4,5,8,2,3,6,7/ data(isodat(iiq,207),iiq=1,8)/1,2,4,3,5,6,8,7/ data(isodat(iiq,208),iiq=1,8)/1,2,4,3,5,6,8,7/ data(isodat(iiq,209),iiq=1,8)/8,7,5,6,4,3,1,2/ data(isodat(iiq,210),iiq=1,8)/8,5,4,1,7,6,3,2/ data(isodat(iiq,211),iiq=1,8)/7,3,6,2,8,4,5,1/ data(isodat(iiq,212),iiq=1,8)/3,4,2,1,7,8,6,5/ data(isodat(iiq,213),iiq=1,8)/7,8,3,4,6,5,2,1/ data(isodat(iiq,214),iiq=1,8)/4,3,8,7,1,2,5,6/ data(isodat(iiq,215),iiq=1,8)/7,3,6,2,8,4,5,1/ data(isodat(iiq,216),iiq=1,8)/3,4,2,1,7,8,6,5/ data(isodat(iiq,217),iiq=1,8)/8,4,7,3,5,1,6,2/ data(isodat(iiq,218),iiq=1,8)/8,4,5,1,7,3,6,2/ data(isodat(iiq,219),iiq=1,8)/3,7,4,8,2,6,1,5/ data(isodat(iiq,220),iiq=1,8)/4,3,8,7,1,2,5,6/ data(isodat(iiq,221),iiq=1,8)/4,3,8,7,1,2,5,6/ data(isodat(iiq,222),iiq=1,8)/4,3,8,7,1,2,5,6/ data(isodat(iiq,223),iiq=1,8)/3,7,4,8,2,6,1,5/ data(isodat(iiq,224),iiq=1,8)/3,4,2,1,7,8,6,5/ data(isodat(iiq,225),iiq=1,8)/8,7,5,6,4,3,1,2/ data(isodat(iiq,226),iiq=1,8)/8,5,4,1,7,6,3,2/ data(isodat(iiq,227),iiq=1,8)/6,5,7,8,2,1,3,4/ data(isodat(iiq,228),iiq=1,8)/5,6,1,2,8,7,4,3/ data(isodat(iiq,229),iiq=1,8)/7,8,6,5,3,4,2,1/ data(isodat(iiq,230),iiq=1,8)/8,4,7,3,5,1,6,2/ data(isodat(iiq,231),iiq=1,8)/7,6,8,5,3,2,4,1/ data(isodat(iiq,232),iiq=1,8)/4,1,3,2,8,5,7,6/ data(isodat(iiq,233),iiq=1,8)/8,5,4,1,7,6,3,2/ data(isodat(iiq,234),iiq=1,8)/8,5,4,1,7,6,3,2/ data(isodat(iiq,235),iiq=1,8)/4,8,1,5,3,7,2,6/ data(isodat(iiq,236),iiq=1,8)/5,1,8,4,6,2,7,3/ data(isodat(iiq,237),iiq=1,8)/8,4,7,3,5,1,6,2/ data(isodat(iiq,238),iiq=1,8)/4,8,1,5,3,7,2,6/ data(isodat(iiq,239),iiq=1,8)/4,3,8,7,1,2,5,6/ data(isodat(iiq,240),iiq=1,8)/4,1,3,2,8,5,7,6/ data(isodat(iiq,241),iiq=1,8)/7,6,8,5,3,2,4,1/ data(isodat(iiq,242),iiq=1,8)/5,8,6,7,1,4,2,3/ data(isodat(iiq,243),iiq=1,8)/7,6,3,2,8,5,4,1/ data(isodat(iiq,244),iiq=1,8)/6,5,7,8,2,1,3,4/ data(isodat(iiq,245),iiq=1,8)/7,6,8,5,3,2,4,1/ data(isodat(iiq,246),iiq=1,8)/8,7,5,6,4,3,1,2/ data(isodat(iiq,247),iiq=1,8)/7,3,6,2,8,4,5,1/ data(isodat(iiq,248),iiq=1,8)/6,7,2,3,5,8,1,4/ data(isodat(iiq,249),iiq=1,8)/8,7,5,6,4,3,1,2/ data(isodat(iiq,250),iiq=1,8)/8,5,4,1,7,6,3,2/ data(isodat(iiq,251),iiq=1,8)/7,3,6,2,8,4,5,1/ data(isodat(iiq,252),iiq=1,8)/3,4,2,1,7,8,6,5/ data(isodat(iiq,253),iiq=1,8)/7,8,3,4,6,5,2,1/ data(isodat(iiq,254),iiq=1,8)/3,7,4,8,2,6,1,5/ data(isodat(iiq,255),iiq=1,8)/7,3,6,2,8,4,5,1/ data(isodat(iiq,256),iiq=1,8)/3,4,2,1,7,8,6,5/ data(isodat(iiq,257),iiq=1,8)/6,5,7,8,2,1,3,4/ data(isodat(iiq,258),iiq=1,8)/5,8,6,7,1,4,2,3/ data(isodat(iiq,259),iiq=1,8)/6,5,7,8,2,1,3,4/ data(isodat(iiq,260),iiq=1,8)/6,5,7,8,2,1,3,4/ data(isodat(iiq,261),iiq=1,8)/7,6,8,5,3,2,4,1/ data(isodat(iiq,262),iiq=1,8)/6,5,7,8,2,1,3,4/ data(isodat(iiq,263),iiq=1,8)/7,6,8,5,3,2,4,1/ data(isodat(iiq,264),iiq=1,8)/6,5,7,8,2,1,3,4/ data(isodat(iiq,265),iiq=1,8)/8,7,5,6,4,3,1,2/ data(isodat(iiq,266),iiq=1,8)/8,5,4,1,7,6,3,2/ data(isodat(iiq,267),iiq=1,8)/5,8,6,7,1,4,2,3/ data(isodat(iiq,268),iiq=1,8)/5,1,8,4,6,2,7,3/ data(isodat(iiq,269),iiq=1,8)/8,7,5,6,4,3,1,2/ data(isodat(iiq,270),iiq=1,8)/8,5,4,1,7,6,3,2/ data(isodat(iiq,271),iiq=1,8)/7,6,8,5,3,2,4,1/ data(isodat(iiq,272),iiq=1,8)/1,2,4,3,5,6,8,7/ C C The next 32 are for pyramids. C data(isodat(iiq,273),iiq=1,8)/8*0/ data(isodat(iiq,274),iiq=1,8)/1,2,3,4,5,0,0,0/ data(isodat(iiq,275),iiq=1,8)/2,1,3,5,0,0,0,0/ data(isodat(iiq,276),iiq=1,8)/1,2,3,4,5,0,0,0/ data(isodat(iiq,277),iiq=1,8)/3,2,1,4,0,0,0,0/ data(isodat(iiq,278),iiq=1,8)/1,3,4,5,2,0,0,0/ data(isodat(iiq,279),iiq=1,8)/1,2,3,4,5,0,0,0/ data(isodat(iiq,280),iiq=1,8)/1,5,4,3,2,0,0,0/ data(isodat(iiq,281),iiq=1,8)/4,3,1,5,0,0,0,0/ data(isodat(iiq,282),iiq=1,8)/1,4,5,2,3,0,0,0/ data(isodat(iiq,283),iiq=1,8)/1,2,3,4,5,0,0,0/ data(isodat(iiq,284),iiq=1,8)/1,5,2,3,4,0,0,0/ data(isodat(iiq,285),iiq=1,8)/1,4,3,2,5,0,0,0/ data(isodat(iiq,286),iiq=1,8)/1,5,2,3,4,0,0,0/ data(isodat(iiq,287),iiq=1,8)/1,5,2,3,4,0,0,0/ data(isodat(iiq,288),iiq=1,8)/5,2,1,4,0,0,0,0/ data(isodat(iiq,289),iiq=1,8)/5,2,1,4,0,0,0,0/ data(isodat(iiq,290),iiq=1,8)/1,5,2,3,4,0,0,0/ data(isodat(iiq,291),iiq=1,8)/1,5,2,3,4,0,0,0/ data(isodat(iiq,292),iiq=1,8)/1,4,3,2,5,0,0,0/ data(isodat(iiq,293),iiq=1,8)/1,5,2,3,4,0,0,0/ data(isodat(iiq,294),iiq=1,8)/1,2,3,4,5,0,0,0/ data(isodat(iiq,295),iiq=1,8)/1,4,5,2,3,0,0,0/ data(isodat(iiq,296),iiq=1,8)/4,3,1,5,0,0,0,0/ data(isodat(iiq,297),iiq=1,8)/1,5,4,3,2,0,0,0/ data(isodat(iiq,298),iiq=1,8)/1,2,3,4,5,0,0,0/ data(isodat(iiq,299),iiq=1,8)/1,3,4,5,2,0,0,0/ data(isodat(iiq,300),iiq=1,8)/3,2,1,4,0,0,0,0/ data(isodat(iiq,301),iiq=1,8)/1,2,3,4,5,0,0,0/ data(isodat(iiq,302),iiq=1,8)/2,1,3,5,0,0,0,0/ data(isodat(iiq,303),iiq=1,8)/1,2,3,4,5,0,0,0/ data(isodat(iiq,304),iiq=1,8)/8*0/ C C The next 64 are for prisms. C data(isodat(iiq,305),iiq=1,8)/8*0/ data(isodat(iiq,306),iiq=1,8)/1,2,3,4,5,6,0,0/ data(isodat(iiq,307),iiq=1,8)/2,1,3,5,4,6,0,0/ data(isodat(iiq,308),iiq=1,8)/1,2,3,4,5,6,0,0/ data(isodat(iiq,309),iiq=1,8)/3,1,2,6,4,5,0,0/ data(isodat(iiq,310),iiq=1,8)/1,3,2,4,6,5,0,0/ data(isodat(iiq,311),iiq=1,8)/3,2,1,6,5,4,0,0/ data(isodat(iiq,312),iiq=1,8)/1,2,3,4,5,6,0,0/ data(isodat(iiq,313),iiq=1,8)/4,1,5,6,2,4,0,0/ data(isodat(iiq,314),iiq=1,8)/1,2,3,4,5,6,0,0/ data(isodat(iiq,315),iiq=1,8)/1,2,3,4,5,6,0,0/ data(isodat(iiq,316),iiq=1,8)/1,2,3,4,5,6,0,0/ data(isodat(iiq,317),iiq=1,8)/1,3,2,4,6,5,0,0/ data(isodat(iiq,318),iiq=1,8)/1,3,2,4,6,5,0,0/ data(isodat(iiq,319),iiq=1,8)/1,2,3,4,5,6,0,0/ data(isodat(iiq,320),iiq=1,8)/5,6,4,2,3,1,0,0/ data(isodat(iiq,321),iiq=1,8)/5,2,4,6,1,3,0,0/ data(isodat(iiq,322),iiq=1,8)/2,1,3,5,4,6,0,0/ data(isodat(iiq,323),iiq=1,8)/2,1,3,5,4,6,0,0/ data(isodat(iiq,324),iiq=1,8)/2,1,3,5,4,6,0,0/ data(isodat(iiq,325),iiq=1,8)/2,3,1,5,6,4,0,0/ data(isodat(iiq,326),iiq=1,8)/2,3,1,5,6,4,0,0/ data(isodat(iiq,327),iiq=1,8)/2,3,1,5,6,4,0,0/ data(isodat(iiq,328),iiq=1,8)/4,6,5,1,3,2,0,0/ data(isodat(iiq,329),iiq=1,8)/5,4,6,2,1,3,0,0/ data(isodat(iiq,330),iiq=1,8)/3,2,1,6,5,4,0,0/ data(isodat(iiq,331),iiq=1,8)/3,1,2,6,4,5,0,0/ data(isodat(iiq,332),iiq=1,8)/3,1,2,6,4,5,0,0/ data(isodat(iiq,333),iiq=1,8)/6,5,4,3,2,1,0,0/ data(isodat(iiq,334),iiq=1,8)/3,2,1,6,5,4,0,0/ data(isodat(iiq,335),iiq=1,8)/3,1,2,6,4,5,0,0/ data(isodat(iiq,336),iiq=1,8)/6,3,4,5,1,2,0,0/ data(isodat(iiq,337),iiq=1,8)/6,3,4,5,1,2,0,0/ data(isodat(iiq,338),iiq=1,8)/3,1,2,6,4,5,0,0/ data(isodat(iiq,339),iiq=1,8)/3,2,1,6,5,4,0,0/ data(isodat(iiq,340),iiq=1,8)/6,5,4,3,2,1,0,0/ data(isodat(iiq,341),iiq=1,8)/3,1,2,6,4,5,0,0/ data(isodat(iiq,342),iiq=1,8)/3,1,2,6,4,5,0,0/ data(isodat(iiq,343),iiq=1,8)/3,2,1,6,5,4,0,0/ data(isodat(iiq,344),iiq=1,8)/5,4,6,2,1,3,0,0/ data(isodat(iiq,345),iiq=1,8)/4,6,5,1,3,2,0,0/ data(isodat(iiq,346),iiq=1,8)/2,3,1,5,6,4,0,0/ data(isodat(iiq,347),iiq=1,8)/5,6,4,2,3,1,0,0/ data(isodat(iiq,348),iiq=1,8)/2,3,1,5,6,4,0,0/ data(isodat(iiq,349),iiq=1,8)/2,1,3,5,4,6,0,0/ data(isodat(iiq,350),iiq=1,8)/2,1,3,5,4,6,0,0/ data(isodat(iiq,351),iiq=1,8)/2,1,3,5,4,6,0,0/ data(isodat(iiq,352),iiq=1,8)/5,2,4,6,1,3,0,0/ data(isodat(iiq,353),iiq=1,8)/5,6,4,2,3,1,0,0/ data(isodat(iiq,354),iiq=1,8)/4,6,5,1,3,2,0,0/ data(isodat(iiq,355),iiq=1,8)/1,3,2,4,6,5,0,0/ data(isodat(iiq,356),iiq=1,8)/1,3,2,4,6,5,0,0/ data(isodat(iiq,357),iiq=1,8)/1,2,3,4,5,6,0,0/ data(isodat(iiq,358),iiq=1,8)/1,2,3,4,5,6,0,0/ data(isodat(iiq,359),iiq=1,8)/1,2,3,4,5,6,0,0/ data(isodat(iiq,360),iiq=1,8)/4,1,5,6,2,3,0,0/ data(isodat(iiq,361),iiq=1,8)/1,2,3,4,5,6,0,0/ data(isodat(iiq,362),iiq=1,8)/2,3,1,5,6,4,0,0/ data(isodat(iiq,363),iiq=1,8)/3,1,2,6,4,5,0,0/ data(isodat(iiq,364),iiq=1,8)/3,1,2,6,4,5,0,0/ data(isodat(iiq,365),iiq=1,8)/1,2,3,4,5,6,0,0/ data(isodat(iiq,366),iiq=1,8)/2,1,3,5,4,6,0,0/ data(isodat(iiq,367),iiq=1,8)/1,2,3,4,5,6,0,0/ data(isodat(iiq,368),iiq=1,8)/8*0/ C C First 16 are for tets. C data(isotyp(iiq),iiq=1,368)/0,1,1,2,1,2,2,1,1,2,2,1,2,1,1,0, C C The next 256 are for hexes. C * 0,1,1,3,1,6,3,7,1,3,6,7,3,7,7,15,1,3,6, * 7,24,25,25,27,6,7,22,23,25,39,30,31,1,6,3,7,6, * 22,7,23,24,25,25,39,25,30,27,31,3,7,7,15,25,30,39, * 31,25,27,30,31,60,61,61,63,1,24,6,25,3,25,7,39,6, * 25,22,30,7,27,23,31,6,25,22,30,25,60,30,61,22,30,0, * 107,30,61,107,111,3,25,7,27,7,30,15,31,25,60,30,61,39, * 61,31,63,7,39,23,31,27,61,31,63,30,61,107,111,61,126,111, * 127,1,6,24,25,6,22,25,30,3,7,25,27,7,23,39,31,3, * 7,25,39,25,30,60,61,7,15,30,31,27,31,61,63,6,22,25, * 30,22,0,30,107,25,30,60,61,30,107,61,111,7,23,27,31,30, * 107,61,111,39,31,61,63,61,111,126,127,3,25,25,60,7,30,27, * 61,7,39,30,61,15,31,31,63,7,27,30,61,39,61,61,126,23, * 31,107,111,31,63,111,127,7,30,39,61,23,107,31,111,27,61,61, * 126,31,111,63,127,15,31,31,63,31,111,63,127,31,63,111,127, * 63,127,127,0, C C The next 32 are for pyramids. C * 0,5,1,2,1,2,3,3,1,2,4,4,3,3,2,1,1,2,3,3,4,4,2,1,3,3,2,1,2, * 1,5,0, C C The next 64 are for prisms. C * 0,1,1,3,1,3,3,2,1,7,4,5,4,5,6,3,1,4,7,5,4,6,5,3, * 3,5,5,7,6,4,4,1,1,4,4,6,7,5,5,3,3,5,6,4,5,7,4,1, * 3,6,5,4,5,4,7,1,2,3,3,1,3,1,1,0/ C C ******************************************************************* C C Add Kent Smith's geometry factor for the GWT algorithm C data igeom_gwt / 0 / C C data pie/ 3.141592653589793 / end C *******************************************************************
48.759494
82
0.361247
[ "mesh", "geometry", "object", "model" ]
d1223581cbc6f3e88fa9110ddb5ebb79c929314f
3,394
h
C
lib/flow/Field.h
yyr/vapor
cdebac81212ffa3f811064bbd7625ffa9089782e
[ "BSD-3-Clause" ]
null
null
null
lib/flow/Field.h
yyr/vapor
cdebac81212ffa3f811064bbd7625ffa9089782e
[ "BSD-3-Clause" ]
null
null
null
lib/flow/Field.h
yyr/vapor
cdebac81212ffa3f811064bbd7625ffa9089782e
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************* * OSU Flow Vector Field * * * * * * Created: Han-Wei Shen, Liya Li * * The Ohio State University * * Date: 06/2005 * * * * Vector Field: 3D Static or Time-Varying * *************************************************************************/ #ifndef _VECTOR_FIELD_H_ #define _VECTOR_FIELD_H_ #include "header.h" #include "Grid.h" #include "Solution.h" #include <vapor/DataMgr.h> ////////////////////////////////////////////////////////////////////////// // vector field class ////////////////////////////////////////////////////////////////////////// namespace VAPoR { class FLOW_API CVectorField : public VetsUtil::MyBase { private: Grid* m_pGrid; // grid Solution* m_pSolution; // vector data int m_nTimeSteps; public: // constructor and deconstructor CVectorField(); CVectorField(Grid* pGrid, Solution* pSolution, int timesteps); ~CVectorField(); // reset void Reset(void); // field functions bool isTimeVarying(void); int getFieldValue(VECTOR3& pos, const float t, VECTOR3& fieldData); bool is_in_grid(VECTOR3& pos) {return (m_pGrid->isInRegion(pos));} int at_comp(const int i, const int j, const int k, const float t, VECTOR3& dataValue); void getDimension(int& xdim, int& ydim, int& zdim); int GetTimeSteps(void) {return m_nTimeSteps;} void SetSolutionGrid(int t, RegularGrid** pUGrid, RegularGrid** pVGrid, RegularGrid** pWGrid, bool periodicDims[3]) {m_pSolution->SetGrid(t, *pUGrid, *pVGrid, *pWGrid, periodicDims);} void ClearSolutionGrid(int t) {m_pSolution->SetGrid(t, 0, 0, 0, 0);} int GetStartTime(void) { return m_pSolution->GetStartTime(); } int GetEndTime(void) { return m_pSolution->GetEndTime(); } void SetUserTimeStepInc(float timeInc) { m_pSolution->SetUserTimeStepInc(timeInc); } void SetUserTimeSteps(float* pUserTimeSteps) { m_pSolution->SetUserTimeSteps(pUserTimeSteps); } void SetUserTimePerVaporTS(float val){m_pSolution->SetUserTimePerVaporTS(val);} float getTimeScaleFactor(){return m_pSolution->GetTimeScaleFactor();} float GetUserTimePerVaporTS() { return m_pSolution->GetUserTimePerVaporTS();} float GetMinCellVolume() { return m_pGrid->GetMinCellVolume();} }; //Helper class to get data out of a vector field class FLOW_API FieldData { public: //Create a FieldData, with specified field variables, at a specified time step //This is created by VaporFlow, because it has region info ~FieldData(); //This is initialized by the VaporFlow class void setup(CVectorField* fld, CartesianGrid* grd, RegularGrid **xgrid, RegularGrid** ygrid, RegularGrid** zgrid, int tstep, bool periodicDims[3]); float getFieldMag(float point[3]); float getValidFieldMag(float point[3]); //Returns -2 if there is missing value, -1 if out of region void releaseData(DataMgr*); private: //information kept in the FieldData: int timeStep; CVectorField* pField; CartesianGrid* pCartesianGrid; RegularGrid** pUGrid, **pVGrid, **pWGrid; }; };//end VAPoR namespace ////////////////////////////////////////////////////////////////////////// // scalar field class ////////////////////////////////////////////////////////////////////////// #endif
36.494624
185
0.600471
[ "vector", "3d" ]
d12666eed9dc70f71705edad01afefddfa571b9c
40,525
c
C
extern/gtk/gdk/win32/gdkdevicemanager-win32.c
PableteProgramming/download
013e35bb5c085e5dfdb57a3a0a39cdf2fd3064b8
[ "MIT" ]
null
null
null
extern/gtk/gdk/win32/gdkdevicemanager-win32.c
PableteProgramming/download
013e35bb5c085e5dfdb57a3a0a39cdf2fd3064b8
[ "MIT" ]
null
null
null
extern/gtk/gdk/win32/gdkdevicemanager-win32.c
PableteProgramming/download
013e35bb5c085e5dfdb57a3a0a39cdf2fd3064b8
[ "MIT" ]
null
null
null
/* GDK - The GIMP Drawing Kit * Copyright (C) 2009 Carlos Garnacho <carlosg@gnome.org> * * 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, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include <stdlib.h> #include <stdio.h> #include <math.h> #include <gdk/gdk.h> #include "gdkwin32.h" #include "gdkprivate-win32.h" #include "gdkdevicemanager-win32.h" #include "gdkdeviceprivate.h" #include "gdkdevice-win32.h" #include "gdkdevice-virtual.h" #include "gdkdevice-wintab.h" #include "gdkdisplayprivate.h" #include "gdkseatdefaultprivate.h" #define WINTAB32_DLL "Wintab32.dll" #define PACKETDATA (PK_CONTEXT | PK_CURSOR | PK_BUTTONS | PK_X | PK_Y | PK_NORMAL_PRESSURE | PK_ORIENTATION) /* We want everything in absolute mode */ #define PACKETMODE (0) #include <pktdef.h> #define DEBUG_WINTAB 1 /* Verbose debug messages enabled */ #define TWOPI (2 * G_PI) static GList *wintab_contexts = NULL; static GdkSurface *wintab_window = NULL; extern int _gdk_input_ignore_core; typedef UINT (WINAPI *t_WTInfoA) (UINT a, UINT b, LPVOID c); typedef UINT (WINAPI *t_WTInfoW) (UINT a, UINT b, LPVOID c); typedef BOOL (WINAPI *t_WTEnable) (HCTX a, BOOL b); typedef HCTX (WINAPI *t_WTOpenA) (HWND a, LPLOGCONTEXTA b, BOOL c); typedef BOOL (WINAPI *t_WTGetA) (HCTX a, LPLOGCONTEXTA b); typedef BOOL (WINAPI *t_WTSetA) (HCTX a, LPLOGCONTEXTA b); typedef BOOL (WINAPI *t_WTOverlap) (HCTX a, BOOL b); typedef BOOL (WINAPI *t_WTPacket) (HCTX a, UINT b, LPVOID c); typedef int (WINAPI *t_WTQueueSizeSet) (HCTX a, int b); static t_WTInfoA p_WTInfoA; static t_WTInfoW p_WTInfoW; static t_WTEnable p_WTEnable; static t_WTOpenA p_WTOpenA; static t_WTGetA p_WTGetA; static t_WTSetA p_WTSetA; static t_WTOverlap p_WTOverlap; static t_WTPacket p_WTPacket; static t_WTQueueSizeSet p_WTQueueSizeSet; static gboolean default_display_opened = FALSE; G_DEFINE_TYPE (GdkDeviceManagerWin32, gdk_device_manager_win32, G_TYPE_OBJECT) static GdkDevice * create_pointer (GdkDeviceManagerWin32 *device_manager, GType g_type, const char *name, gboolean has_cursor) { return g_object_new (g_type, "name", name, "source", GDK_SOURCE_MOUSE, "has-cursor", has_cursor, "display", _gdk_display, NULL); } static GdkDevice * create_keyboard (GdkDeviceManagerWin32 *device_manager, GType g_type, const char *name) { return g_object_new (g_type, "name", name, "source", GDK_SOURCE_KEYBOARD, "has-cursor", FALSE, "display", _gdk_display, NULL); } static void gdk_device_manager_win32_init (GdkDeviceManagerWin32 *device_manager_win32) { } static void gdk_device_manager_win32_finalize (GObject *object) { GdkDeviceManagerWin32 *device_manager_win32; device_manager_win32 = GDK_DEVICE_MANAGER_WIN32 (object); g_object_unref (device_manager_win32->core_pointer); g_object_unref (device_manager_win32->core_keyboard); G_OBJECT_CLASS (gdk_device_manager_win32_parent_class)->finalize (object); } #if DEBUG_WINTAB static void print_lc(LOGCONTEXT *lc) { g_print ("lcName = %s\n", lc->lcName); g_print ("lcOptions ="); if (lc->lcOptions & CXO_SYSTEM) g_print (" CXO_SYSTEM"); if (lc->lcOptions & CXO_PEN) g_print (" CXO_PEN"); if (lc->lcOptions & CXO_MESSAGES) g_print (" CXO_MESSAGES"); if (lc->lcOptions & CXO_MARGIN) g_print (" CXO_MARGIN"); if (lc->lcOptions & CXO_MGNINSIDE) g_print (" CXO_MGNINSIDE"); if (lc->lcOptions & CXO_CSRMESSAGES) g_print (" CXO_CSRMESSAGES"); g_print ("\n"); g_print ("lcStatus ="); if (lc->lcStatus & CXS_DISABLED) g_print (" CXS_DISABLED"); if (lc->lcStatus & CXS_OBSCURED) g_print (" CXS_OBSCURED"); if (lc->lcStatus & CXS_ONTOP) g_print (" CXS_ONTOP"); g_print ("\n"); g_print ("lcLocks ="); if (lc->lcLocks & CXL_INSIZE) g_print (" CXL_INSIZE"); if (lc->lcLocks & CXL_INASPECT) g_print (" CXL_INASPECT"); if (lc->lcLocks & CXL_SENSITIVITY) g_print (" CXL_SENSITIVITY"); if (lc->lcLocks & CXL_MARGIN) g_print (" CXL_MARGIN"); g_print ("\n"); g_print ("lcMsgBase = %#x, lcDevice = %#x, lcPktRate = %d\n", lc->lcMsgBase, lc->lcDevice, lc->lcPktRate); g_print ("lcPktData ="); if (lc->lcPktData & PK_CONTEXT) g_print (" PK_CONTEXT"); if (lc->lcPktData & PK_STATUS) g_print (" PK_STATUS"); if (lc->lcPktData & PK_TIME) g_print (" PK_TIME"); if (lc->lcPktData & PK_CHANGED) g_print (" PK_CHANGED"); if (lc->lcPktData & PK_SERIAL_NUMBER) g_print (" PK_SERIAL_NUMBER"); if (lc->lcPktData & PK_CURSOR) g_print (" PK_CURSOR"); if (lc->lcPktData & PK_BUTTONS) g_print (" PK_BUTTONS"); if (lc->lcPktData & PK_X) g_print (" PK_X"); if (lc->lcPktData & PK_Y) g_print (" PK_Y"); if (lc->lcPktData & PK_Z) g_print (" PK_Z"); if (lc->lcPktData & PK_NORMAL_PRESSURE) g_print (" PK_NORMAL_PRESSURE"); if (lc->lcPktData & PK_TANGENT_PRESSURE) g_print (" PK_TANGENT_PRESSURE"); if (lc->lcPktData & PK_ORIENTATION) g_print (" PK_ORIENTATION"); if (lc->lcPktData & PK_ROTATION) g_print (" PK_ROTATION"); g_print ("\n"); g_print ("lcPktMode ="); if (lc->lcPktMode & PK_CONTEXT) g_print (" PK_CONTEXT"); if (lc->lcPktMode & PK_STATUS) g_print (" PK_STATUS"); if (lc->lcPktMode & PK_TIME) g_print (" PK_TIME"); if (lc->lcPktMode & PK_CHANGED) g_print (" PK_CHANGED"); if (lc->lcPktMode & PK_SERIAL_NUMBER) g_print (" PK_SERIAL_NUMBER"); if (lc->lcPktMode & PK_CURSOR) g_print (" PK_CURSOR"); if (lc->lcPktMode & PK_BUTTONS) g_print (" PK_BUTTONS"); if (lc->lcPktMode & PK_X) g_print (" PK_X"); if (lc->lcPktMode & PK_Y) g_print (" PK_Y"); if (lc->lcPktMode & PK_Z) g_print (" PK_Z"); if (lc->lcPktMode & PK_NORMAL_PRESSURE) g_print (" PK_NORMAL_PRESSURE"); if (lc->lcPktMode & PK_TANGENT_PRESSURE) g_print (" PK_TANGENT_PRESSURE"); if (lc->lcPktMode & PK_ORIENTATION) g_print (" PK_ORIENTATION"); if (lc->lcPktMode & PK_ROTATION) g_print (" PK_ROTATION"); g_print ("\n"); g_print ("lcMoveMask ="); if (lc->lcMoveMask & PK_CONTEXT) g_print (" PK_CONTEXT"); if (lc->lcMoveMask & PK_STATUS) g_print (" PK_STATUS"); if (lc->lcMoveMask & PK_TIME) g_print (" PK_TIME"); if (lc->lcMoveMask & PK_CHANGED) g_print (" PK_CHANGED"); if (lc->lcMoveMask & PK_SERIAL_NUMBER) g_print (" PK_SERIAL_NUMBER"); if (lc->lcMoveMask & PK_CURSOR) g_print (" PK_CURSOR"); if (lc->lcMoveMask & PK_BUTTONS) g_print (" PK_BUTTONS"); if (lc->lcMoveMask & PK_X) g_print (" PK_X"); if (lc->lcMoveMask & PK_Y) g_print (" PK_Y"); if (lc->lcMoveMask & PK_Z) g_print (" PK_Z"); if (lc->lcMoveMask & PK_NORMAL_PRESSURE) g_print (" PK_NORMAL_PRESSURE"); if (lc->lcMoveMask & PK_TANGENT_PRESSURE) g_print (" PK_TANGENT_PRESSURE"); if (lc->lcMoveMask & PK_ORIENTATION) g_print (" PK_ORIENTATION"); if (lc->lcMoveMask & PK_ROTATION) g_print (" PK_ROTATION"); g_print ("\n"); g_print ("lcBtnDnMask = %#x, lcBtnUpMask = %#x\n", (guint) lc->lcBtnDnMask, (guint) lc->lcBtnUpMask); g_print ("lcInOrgX = %ld, lcInOrgY = %ld, lcInOrgZ = %ld\n", lc->lcInOrgX, lc->lcInOrgY, lc->lcInOrgZ); g_print ("lcInExtX = %ld, lcInExtY = %ld, lcInExtZ = %ld\n", lc->lcInExtX, lc->lcInExtY, lc->lcInExtZ); g_print ("lcOutOrgX = %ld, lcOutOrgY = %ld, lcOutOrgZ = %ld\n", lc->lcOutOrgX, lc->lcOutOrgY, lc->lcOutOrgZ); g_print ("lcOutExtX = %ld, lcOutExtY = %ld, lcOutExtZ = %ld\n", lc->lcOutExtX, lc->lcOutExtY, lc->lcOutExtZ); g_print ("lcSensX = %g, lcSensY = %g, lcSensZ = %g\n", lc->lcSensX / 65536., lc->lcSensY / 65536., lc->lcSensZ / 65536.); g_print ("lcSysMode = %d\n", lc->lcSysMode); g_print ("lcSysOrgX = %d, lcSysOrgY = %d\n", lc->lcSysOrgX, lc->lcSysOrgY); g_print ("lcSysExtX = %d, lcSysExtY = %d\n", lc->lcSysExtX, lc->lcSysExtY); g_print ("lcSysSensX = %g, lcSysSensY = %g\n", lc->lcSysSensX / 65536., lc->lcSysSensY / 65536.); } static void print_cursor (int index) { int size; int i; char *name; BOOL active; WTPKT wtpkt; BYTE buttons; BYTE buttonbits; char *btnnames; char *p; BYTE buttonmap[32]; BYTE sysbtnmap[32]; BYTE npbutton; UINT npbtnmarks[2]; UINT *npresponse; BYTE tpbutton; UINT tpbtnmarks[2]; UINT *tpresponse; DWORD physid; UINT mode; UINT minpktdata; UINT minbuttons; UINT capabilities; size = (*p_WTInfoA) (WTI_CURSORS + index, CSR_NAME, NULL); name = g_malloc (size + 1); (*p_WTInfoA) (WTI_CURSORS + index, CSR_NAME, name); g_print ("NAME: %s\n", name); (*p_WTInfoA) (WTI_CURSORS + index, CSR_ACTIVE, &active); g_print ("ACTIVE: %s\n", active ? "YES" : "NO"); (*p_WTInfoA) (WTI_CURSORS + index, CSR_PKTDATA, &wtpkt); g_print ("PKTDATA: %#x:", (guint) wtpkt); #define BIT(x) if (wtpkt & PK_##x) g_print (" " #x) BIT (CONTEXT); BIT (STATUS); BIT (TIME); BIT (CHANGED); BIT (SERIAL_NUMBER); BIT (BUTTONS); BIT (X); BIT (Y); BIT (Z); BIT (NORMAL_PRESSURE); BIT (TANGENT_PRESSURE); BIT (ORIENTATION); BIT (ROTATION); #undef BIT g_print ("\n"); (*p_WTInfoA) (WTI_CURSORS + index, CSR_BUTTONS, &buttons); g_print ("BUTTONS: %d\n", buttons); (*p_WTInfoA) (WTI_CURSORS + index, CSR_BUTTONBITS, &buttonbits); g_print ("BUTTONBITS: %d\n", buttonbits); size = (*p_WTInfoA) (WTI_CURSORS + index, CSR_BTNNAMES, NULL); g_print ("BTNNAMES:"); if (size > 0) { btnnames = g_malloc (size + 1); (*p_WTInfoA) (WTI_CURSORS + index, CSR_BTNNAMES, btnnames); p = btnnames; while (*p) { g_print (" %s", p); p += strlen (p) + 1; } } g_print ("\n"); (*p_WTInfoA) (WTI_CURSORS + index, CSR_BUTTONMAP, buttonmap); g_print ("BUTTONMAP:"); for (i = 0; i < buttons; i++) g_print (" %d", buttonmap[i]); g_print ("\n"); (*p_WTInfoA) (WTI_CURSORS + index, CSR_SYSBTNMAP, sysbtnmap); g_print ("SYSBTNMAP:"); for (i = 0; i < buttons; i++) g_print (" %d", sysbtnmap[i]); g_print ("\n"); (*p_WTInfoA) (WTI_CURSORS + index, CSR_NPBUTTON, &npbutton); g_print ("NPBUTTON: %d\n", npbutton); (*p_WTInfoA) (WTI_CURSORS + index, CSR_NPBTNMARKS, npbtnmarks); g_print ("NPBTNMARKS: %d %d\n", npbtnmarks[0], npbtnmarks[1]); size = (*p_WTInfoA) (WTI_CURSORS + index, CSR_NPRESPONSE, NULL); g_print ("NPRESPONSE:"); if (size > 0) { npresponse = g_malloc (size); (*p_WTInfoA) (WTI_CURSORS + index, CSR_NPRESPONSE, npresponse); for (i = 0; i < size / sizeof (UINT); i++) g_print (" %d", npresponse[i]); } g_print ("\n"); (*p_WTInfoA) (WTI_CURSORS + index, CSR_TPBUTTON, &tpbutton); g_print ("TPBUTTON: %d\n", tpbutton); (*p_WTInfoA) (WTI_CURSORS + index, CSR_TPBTNMARKS, tpbtnmarks); g_print ("TPBTNMARKS: %d %d\n", tpbtnmarks[0], tpbtnmarks[1]); size = (*p_WTInfoA) (WTI_CURSORS + index, CSR_TPRESPONSE, NULL); g_print ("TPRESPONSE:"); if (size > 0) { tpresponse = g_malloc (size); (*p_WTInfoA) (WTI_CURSORS + index, CSR_TPRESPONSE, tpresponse); for (i = 0; i < size / sizeof (UINT); i++) g_print (" %d", tpresponse[i]); } g_print ("\n"); (*p_WTInfoA) (WTI_CURSORS + index, CSR_PHYSID, &physid); g_print ("PHYSID: %#x\n", (guint) physid); (*p_WTInfoA) (WTI_CURSORS + index, CSR_CAPABILITIES, &capabilities); g_print ("CAPABILITIES: %#x:", capabilities); #define BIT(x) if (capabilities & CRC_##x) g_print (" " #x) BIT (MULTIMODE); BIT (AGGREGATE); BIT (INVERT); #undef BIT g_print ("\n"); if (capabilities & CRC_MULTIMODE) { (*p_WTInfoA) (WTI_CURSORS + index, CSR_MODE, &mode); g_print ("MODE: %d\n", mode); } if (capabilities & CRC_AGGREGATE) { (*p_WTInfoA) (WTI_CURSORS + index, CSR_MINPKTDATA, &minpktdata); g_print ("MINPKTDATA: %d\n", minpktdata); (*p_WTInfoA) (WTI_CURSORS + index, CSR_MINBUTTONS, &minbuttons); g_print ("MINBUTTONS: %d\n", minbuttons); } } #endif static void wintab_init_check (GdkDeviceManagerWin32 *device_manager) { GdkDisplay *display = device_manager->display; static gboolean wintab_initialized = FALSE; GdkDeviceWintab *device; WORD specversion; HCTX *hctx; UINT ndevices, ncursors, ncsrtypes, firstcsr, hardware; BOOL active; DWORD physid; AXIS axis_x, axis_y, axis_npressure, axis_or[3]; UINT devix, cursorix; int i, num_axes = 0; wchar_t devname[100], csrname[100]; char *devname_utf8, *csrname_utf8, *device_name; BOOL defcontext_done; HMODULE wintab32; char *wintab32_dll_path; char dummy; int n, k; if (wintab_initialized) return; wintab_initialized = TRUE; wintab_contexts = NULL; if (_gdk_input_ignore_wintab) return; n = GetSystemDirectory (&dummy, 0); if (n <= 0) return; wintab32_dll_path = g_malloc (n + 1 + strlen (WINTAB32_DLL)); k = GetSystemDirectory (wintab32_dll_path, n); if (k == 0 || k > n) { g_free (wintab32_dll_path); return; } if (!G_IS_DIR_SEPARATOR (wintab32_dll_path[strlen (wintab32_dll_path) -1])) strcat (wintab32_dll_path, G_DIR_SEPARATOR_S); strcat (wintab32_dll_path, WINTAB32_DLL); if ((wintab32 = LoadLibrary (wintab32_dll_path)) == NULL) return; if ((p_WTInfoA = (t_WTInfoA) GetProcAddress (wintab32, "WTInfoA")) == NULL) return; if ((p_WTInfoW = (t_WTInfoW) GetProcAddress (wintab32, "WTInfoW")) == NULL) return; if ((p_WTEnable = (t_WTEnable) GetProcAddress (wintab32, "WTEnable")) == NULL) return; if ((p_WTOpenA = (t_WTOpenA) GetProcAddress (wintab32, "WTOpenA")) == NULL) return; if ((p_WTGetA = (t_WTGetA) GetProcAddress (wintab32, "WTGetA")) == NULL) return; if ((p_WTSetA = (t_WTSetA) GetProcAddress (wintab32, "WTSetA")) == NULL) return; if ((p_WTOverlap = (t_WTOverlap) GetProcAddress (wintab32, "WTOverlap")) == NULL) return; if ((p_WTPacket = (t_WTPacket) GetProcAddress (wintab32, "WTPacket")) == NULL) return; if ((p_WTQueueSizeSet = (t_WTQueueSizeSet) GetProcAddress (wintab32, "WTQueueSizeSet")) == NULL) return; if (!(*p_WTInfoA) (0, 0, NULL)) return; (*p_WTInfoA) (WTI_INTERFACE, IFC_SPECVERSION, &specversion); GDK_NOTE (INPUT, g_print ("Wintab interface version %d.%d\n", HIBYTE (specversion), LOBYTE (specversion))); (*p_WTInfoA) (WTI_INTERFACE, IFC_NDEVICES, &ndevices); (*p_WTInfoA) (WTI_INTERFACE, IFC_NCURSORS, &ncursors); #if DEBUG_WINTAB GDK_NOTE (INPUT, g_print ("NDEVICES: %d, NCURSORS: %d\n", ndevices, ncursors)); #endif /* Create a dummy window to receive wintab events */ wintab_window = _gdk_win32_display_create_surface (display, GDK_SURFACE_TEMP, NULL, -100, -100, 2, 2); g_object_ref (wintab_window); for (devix = 0; devix < ndevices; devix++) { LOGCONTEXT lc; /* We open the Wintab device (hmm, what if there are several, or * can there even be several, probably not?) as a system * pointing device, i.e. it controls the normal Windows * cursor. This seems much more natural. */ (*p_WTInfoW) (WTI_DEVICES + devix, DVC_NAME, devname); devname_utf8 = g_utf16_to_utf8 (devname, -1, NULL, NULL, NULL); #ifdef DEBUG_WINTAB GDK_NOTE (INPUT, (g_print("Device %u: %s\n", devix, devname_utf8))); #endif (*p_WTInfoA) (WTI_DEVICES + devix, DVC_NCSRTYPES, &ncsrtypes); (*p_WTInfoA) (WTI_DEVICES + devix, DVC_FIRSTCSR, &firstcsr); (*p_WTInfoA) (WTI_DEVICES + devix, DVC_HARDWARE, &hardware); (*p_WTInfoA) (WTI_DEVICES + devix, DVC_X, &axis_x); (*p_WTInfoA) (WTI_DEVICES + devix, DVC_Y, &axis_y); (*p_WTInfoA) (WTI_DEVICES + devix, DVC_NPRESSURE, &axis_npressure); (*p_WTInfoA) (WTI_DEVICES + devix, DVC_ORIENTATION, axis_or); defcontext_done = FALSE; if (HIBYTE (specversion) > 1 || LOBYTE (specversion) >= 1) { /* Try to get device-specific default context */ /* Some drivers, e.g. Aiptek, don't provide this info */ if ((*p_WTInfoA) (WTI_DSCTXS + devix, 0, &lc) > 0) defcontext_done = TRUE; #if DEBUG_WINTAB if (defcontext_done) GDK_NOTE (INPUT, (g_print("Using device-specific default context\n"))); else GDK_NOTE (INPUT, (g_print("Note: Driver did not provide device specific default context info despite claiming to support version 1.1\n"))); #endif } if (!defcontext_done) (*p_WTInfoA) (WTI_DEFSYSCTX, 0, &lc); #if DEBUG_WINTAB GDK_NOTE (INPUT, (g_print("Default context:\n"), print_lc(&lc))); #endif lc.lcOptions |= CXO_MESSAGES | CXO_CSRMESSAGES; lc.lcStatus = 0; lc.lcMsgBase = WT_DEFBASE; lc.lcPktRate = 0; lc.lcPktData = PACKETDATA; lc.lcPktMode = PACKETMODE; lc.lcMoveMask = PACKETDATA; lc.lcBtnUpMask = lc.lcBtnDnMask = ~0; lc.lcOutOrgX = axis_x.axMin; lc.lcOutOrgY = axis_y.axMin; lc.lcOutExtX = axis_x.axMax - axis_x.axMin + 1; lc.lcOutExtY = axis_y.axMax - axis_y.axMin + 1; lc.lcOutExtY = -lc.lcOutExtY; /* We want Y growing downward */ #if DEBUG_WINTAB GDK_NOTE (INPUT, (g_print("context for device %u:\n", devix), print_lc(&lc))); #endif hctx = g_new (HCTX, 1); if ((*hctx = (*p_WTOpenA) (GDK_SURFACE_HWND (wintab_window), &lc, TRUE)) == NULL) { g_warning ("gdk_input_wintab_init: WTOpen failed"); return; } GDK_NOTE (INPUT, g_print ("opened Wintab device %u %p\n", devix, *hctx)); wintab_contexts = g_list_append (wintab_contexts, hctx); #if 0 (*p_WTEnable) (*hctx, TRUE); #endif (*p_WTOverlap) (*hctx, TRUE); #if DEBUG_WINTAB GDK_NOTE (INPUT, (g_print("context for device %u after WTOpen:\n", devix), print_lc(&lc))); #endif /* Increase packet queue size to reduce the risk of lost packets. * According to the specs, if the function fails we must try again * with a smaller queue size. */ GDK_NOTE (INPUT, g_print("Attempting to increase queue size\n")); for (i = 128; i >= 1; i >>= 1) { if ((*p_WTQueueSizeSet) (*hctx, i)) { GDK_NOTE (INPUT, g_print("Queue size set to %d\n", i)); break; } } if (!i) GDK_NOTE (INPUT, g_print("Whoops, no queue size could be set\n")); for (cursorix = firstcsr; cursorix < firstcsr + ncsrtypes; cursorix++) { #ifdef DEBUG_WINTAB GDK_NOTE (INPUT, (g_print("Cursor %u:\n", cursorix), print_cursor (cursorix))); #endif active = FALSE; (*p_WTInfoA) (WTI_CURSORS + cursorix, CSR_ACTIVE, &active); if (!active) continue; /* Wacom tablets seem to report cursors corresponding to * nonexistent pens or pucks. At least my ArtPad II reports * six cursors: a puck, pressure stylus and eraser stylus, * and then the same three again. I only have a * pressure-sensitive pen. The puck instances, and the * second instances of the styluses report physid zero. So * at least for Wacom, skip cursors with physid zero. */ (*p_WTInfoA) (WTI_CURSORS + cursorix, CSR_PHYSID, &physid); if (wcscmp (devname, L"WACOM Tablet") == 0 && physid == 0) continue; (*p_WTInfoW) (WTI_CURSORS + cursorix, CSR_NAME, csrname); csrname_utf8 = g_utf16_to_utf8 (csrname, -1, NULL, NULL, NULL); device_name = g_strconcat (devname_utf8, " ", csrname_utf8, NULL); device = g_object_new (GDK_TYPE_DEVICE_WINTAB, "name", device_name, "source", GDK_SOURCE_PEN, "has-cursor", lc.lcOptions & CXO_SYSTEM, "display", display, NULL); device->sends_core = lc.lcOptions & CXO_SYSTEM; if (device->sends_core) { _gdk_device_set_associated_device (device_manager->system_pointer, GDK_DEVICE (device)); _gdk_device_add_physical_device (device_manager->core_pointer, GDK_DEVICE (device)); } g_free (csrname_utf8); device->hctx = *hctx; device->cursor = cursorix; (*p_WTInfoA) (WTI_CURSORS + cursorix, CSR_PKTDATA, &device->pktdata); if (device->pktdata & PK_X) { _gdk_device_add_axis (GDK_DEVICE (device), GDK_AXIS_X, axis_x.axMin, axis_x.axMax, axis_x.axResolution / 65535); num_axes++; } if (device->pktdata & PK_Y) { _gdk_device_add_axis (GDK_DEVICE (device), GDK_AXIS_Y, axis_y.axMin, axis_y.axMax, axis_y.axResolution / 65535); num_axes++; } if (device->pktdata & PK_NORMAL_PRESSURE) { _gdk_device_add_axis (GDK_DEVICE (device), GDK_AXIS_PRESSURE, axis_npressure.axMin, axis_npressure.axMax, axis_npressure.axResolution / 65535); num_axes++; } if (device->pktdata & PK_ORIENTATION) { device->orientation_axes[0] = axis_or[0]; device->orientation_axes[1] = axis_or[1]; /* Wintab gives us azimuth and altitude, which * we convert to x and y tilt in the -1000..1000 range */ _gdk_device_add_axis (GDK_DEVICE (device), GDK_AXIS_XTILT, -1000, 1000, 1000); _gdk_device_add_axis (GDK_DEVICE (device), GDK_AXIS_YTILT, -1000, 1000, 1000); num_axes += 2; } device->last_axis_data = g_new (int, num_axes); GDK_NOTE (INPUT, g_print ("device: (%u) %s axes: %d\n", cursorix, device_name, num_axes)); #if 0 for (i = 0; i < gdkdev->info.num_axes; i++) GDK_NOTE (INPUT, g_print ("... axis %d: %d--%d@%d\n", i, gdkdev->axes[i].min_value, gdkdev->axes[i].max_value, gdkdev->axes[i].resolution)); #endif device_manager->wintab_devices = g_list_append (device_manager->wintab_devices, device); g_free (device_name); } g_free (devname_utf8); } } /* Only initialize Wintab after the default display is set for * the first time. WTOpenA() executes code beyond our control, * and it can cause messages to be sent to the application even * before a window is opened. GDK has to be in a fit state to * handle them when they come. * * https://bugzilla.gnome.org/show_bug.cgi?id=774379 */ static void wintab_default_display_notify_cb (GdkDisplayManager *display_manager) { GdkDeviceManagerWin32 *device_manager = NULL; GdkDisplay *display = gdk_display_get_default(); if (default_display_opened) return; g_assert (display != NULL); device_manager = GDK_DEVICE_MANAGER_WIN32 (_gdk_device_manager); g_assert (display_manager != NULL); default_display_opened = TRUE; GDK_NOTE (INPUT, g_print ("wintab init: doing delayed initialization\n")); wintab_init_check (device_manager); } static void gdk_device_manager_win32_constructed (GObject *object) { GdkDeviceManagerWin32 *device_manager; GdkSeat *seat; GdkDisplayManager *display_manager = NULL; GdkDisplay *default_display = NULL; device_manager = GDK_DEVICE_MANAGER_WIN32 (object); device_manager->core_pointer = create_pointer (device_manager, GDK_TYPE_DEVICE_VIRTUAL, "Virtual Core Pointer", TRUE); device_manager->system_pointer = create_pointer (device_manager, GDK_TYPE_DEVICE_WIN32, "System Aggregated Pointer", FALSE); _gdk_device_virtual_set_active (device_manager->core_pointer, device_manager->system_pointer); _gdk_device_set_associated_device (device_manager->system_pointer, device_manager->core_pointer); _gdk_device_add_physical_device (device_manager->core_pointer, device_manager->system_pointer); device_manager->core_keyboard = create_keyboard (device_manager, GDK_TYPE_DEVICE_VIRTUAL, "Virtual Core Keyboard"); device_manager->system_keyboard = create_keyboard (device_manager, GDK_TYPE_DEVICE_WIN32, "System Aggregated Keyboard"); _gdk_device_virtual_set_active (device_manager->core_keyboard, device_manager->system_keyboard); _gdk_device_set_associated_device (device_manager->system_keyboard, device_manager->core_keyboard); _gdk_device_add_physical_device (device_manager->core_keyboard, device_manager->system_keyboard); _gdk_device_set_associated_device (device_manager->core_pointer, device_manager->core_keyboard); _gdk_device_set_associated_device (device_manager->core_keyboard, device_manager->core_pointer); seat = gdk_seat_default_new_for_logical_pair (device_manager->core_pointer, device_manager->core_keyboard); gdk_display_add_seat (_gdk_display, seat); gdk_seat_default_add_physical_device (GDK_SEAT_DEFAULT (seat), device_manager->system_pointer); gdk_seat_default_add_physical_device (GDK_SEAT_DEFAULT (seat), device_manager->system_keyboard); g_object_unref (seat); /* Only call Wintab init stuff after the default display * is globally known and accessible through the display manager * singleton. Approach lifted from gtkmodules.c. */ display_manager = gdk_display_manager_get (); g_assert (display_manager != NULL); default_display = gdk_display_manager_get_default_display (display_manager); g_assert (default_display == NULL); g_signal_connect (display_manager, "notify::default-display", G_CALLBACK (wintab_default_display_notify_cb), NULL); } static void gdk_device_manager_win32_class_init (GdkDeviceManagerWin32Class *klass) { GObjectClass *object_class = G_OBJECT_CLASS (klass); object_class->finalize = gdk_device_manager_win32_finalize; object_class->constructed = gdk_device_manager_win32_constructed; } void _gdk_input_set_tablet_active (void) { GList *tmp_list; HCTX *hctx; /* Bring the contexts to the top of the overlap order when one of the * application's windows is activated */ if (!wintab_contexts) return; /* No tablet devices found, or Wintab not initialized yet */ GDK_NOTE (INPUT, g_print ("_gdk_input_set_tablet_active: " "Bringing Wintab contexts to the top of the overlap order\n")); tmp_list = wintab_contexts; while (tmp_list) { hctx = (HCTX *) (tmp_list->data); (*p_WTOverlap) (*hctx, TRUE); tmp_list = tmp_list->next; } } static void decode_tilt (int *axis_data, AXIS *axes, PACKET *packet) { double az, el; g_return_if_fail (axis_data != NULL); /* The wintab driver for the Wacom ArtPad II reports * PK_ORIENTATION in CSR_PKTDATA, but the tablet doesn't * actually sense tilt. Catch this by noticing that the * orientation axis's azimuth resolution is zero. * * The same is true of the Huion H610PRO, but in this case * it's the altitude resolution that's zero. GdkEvents with * sensible tilts will need both, so only add the GDK tilt axes * if both wintab axes are going to be well-behaved in use. */ if ((axes == NULL) || (axes[0].axResolution == 0) || (axes[1].axResolution == 0)) { axis_data[0] = 0; axis_data[1] = 0; return; } /* * Tested with a Wacom Intuos 5 touch M (PTH-650) + Wacom drivers 6.3.18-5. * Wintab's reference angle leads gdk's by 90 degrees. */ az = TWOPI * packet->pkOrientation.orAzimuth / (axes[0].axResolution / 65536.); az -= G_PI / 2; el = TWOPI * packet->pkOrientation.orAltitude / (axes[1].axResolution / 65536.); /* X tilt */ axis_data[0] = cos (az) * cos (el) * 1000; /* Y tilt */ axis_data[1] = sin (az) * cos (el) * 1000; } /* * Get the currently active keyboard modifiers (ignoring the mouse buttons) * We could use gdk_surface_get_pointer but that function does a lot of other * expensive things besides getting the modifiers. This code is somewhat based * on build_pointer_event_state from gdkevents-win32.c */ static guint get_modifier_key_state (void) { guint state; state = 0; /* High-order bit is up/down, low order bit is toggled/untoggled */ if (GetKeyState (VK_CONTROL) < 0) state |= GDK_CONTROL_MASK; if (GetKeyState (VK_SHIFT) < 0) state |= GDK_SHIFT_MASK; if (GetKeyState (VK_MENU) < 0) state |= GDK_ALT_MASK; if (GetKeyState (VK_CAPITAL) & 0x1) state |= GDK_LOCK_MASK; return state; } static GdkDeviceWintab * gdk_device_manager_find_wintab_device (GdkDeviceManagerWin32 *device_manager, HCTX hctx, UINT cursor) { GdkDeviceWintab *device; GList *tmp_list; for (tmp_list = device_manager->wintab_devices; tmp_list != NULL; tmp_list = tmp_list->next) { device = tmp_list->data; if (device->hctx == hctx && device->cursor == cursor) return device; } return NULL; } GdkEvent * gdk_input_other_event (GdkDisplay *display, MSG *msg, GdkSurface *window) { GdkDeviceManagerWin32 *device_manager; GdkDeviceWintab *source_device = NULL; GdkDeviceGrabInfo *last_grab; guint key_state; GdkEvent *event; PACKET packet; int num_axes; double x, y; guint translated_buttons, button_diff, button_mask; GdkEventType event_type; int event_button = 0; GdkModifierType event_state; double event_x, event_y; double *axes; /* Translation from tablet button state to GDK button state for * buttons 1-3 - swap button 2 and 3. */ static guint button_map[8] = {0, 1, 4, 5, 2, 3, 6, 7}; if (window != wintab_window) { g_warning ("gdk_input_other_event: not wintab_window?"); return NULL; } device_manager = GDK_DEVICE_MANAGER_WIN32 (_gdk_device_manager); window = gdk_device_get_surface_at_position (device_manager->core_pointer, &x, &y); if (window) g_object_ref (window); GDK_NOTE (EVENTS_OR_INPUT, g_print ("gdk_input_other_event: window=%p %+g%+g\n", window ? GDK_SURFACE_HWND (window) : NULL, x, y)); if (msg->message == WT_PACKET || msg->message == WT_CSRCHANGE) { if (!(*p_WTPacket) ((HCTX) msg->lParam, msg->wParam, &packet)) return NULL; } switch (msg->message) { case WT_PACKET: source_device = gdk_device_manager_find_wintab_device (device_manager, (HCTX) msg->lParam, packet.pkCursor); /* Check this first, as we get WT_PROXIMITY for disabled devices too */ if (device_manager->dev_entered_proximity > 0) { /* This is the same code as in WT_CSRCHANGE. Some drivers send * WT_CSRCHANGE after each WT_PROXIMITY with LOWORD(lParam) != 0, * this code is for those that don't. */ device_manager->dev_entered_proximity -= 1; if (source_device != NULL && source_device->sends_core) { _gdk_device_virtual_set_active (device_manager->core_pointer, GDK_DEVICE (source_device)); _gdk_input_ignore_core += 1; } } else if (source_device != NULL && source_device->sends_core && _gdk_input_ignore_core == 0) { /* A fallback for cases when two devices (disabled and enabled) * were in proximity simultaneously. * In this case the removal of a disabled device would also * make the system pointer active, as we don't know which * device was removed and assume it was the enabled one. * If we are still getting packets for the enabled device, * it means that the device that was removed was the disabled * device, so we must make the enabled device active again and * start ignoring the core pointer events. In practice this means that * removing a disabled device while an enabled device is still * in proximity might briefly make the core pointer active/visible. */ _gdk_device_virtual_set_active (device_manager->core_pointer, GDK_DEVICE (source_device)); _gdk_input_ignore_core += 1; } if (source_device == NULL) return NULL; /* Don't produce any button or motion events while a window is being * moved or resized, see bug #151090. */ if (_modal_operation_in_progress & GDK_WIN32_MODAL_OP_SIZEMOVE_MASK) { GDK_NOTE (EVENTS_OR_INPUT, g_print ("... ignored when moving/sizing\n")); return NULL; } last_grab = _gdk_display_get_last_device_grab (display, GDK_DEVICE (source_device)); if (last_grab && last_grab->surface) { g_object_unref (window); window = g_object_ref (last_grab->surface); } if (window == NULL) { GDK_NOTE (EVENTS_OR_INPUT, g_print ("... is root\n")); return NULL; } num_axes = 0; if (source_device->pktdata & PK_X) source_device->last_axis_data[num_axes++] = packet.pkX; if (source_device->pktdata & PK_Y) source_device->last_axis_data[num_axes++] = packet.pkY; if (source_device->pktdata & PK_NORMAL_PRESSURE) source_device->last_axis_data[num_axes++] = packet.pkNormalPressure; if (source_device->pktdata & PK_ORIENTATION) { decode_tilt (source_device->last_axis_data + num_axes, source_device->orientation_axes, &packet); num_axes += 2; } translated_buttons = button_map[packet.pkButtons & 0x07] | (packet.pkButtons & ~0x07); if (translated_buttons != source_device->button_state) { /* At least one button has changed state so produce a button event * If more than one button has changed state (unlikely), * just care about the first and act on the next the next time * we get a packet */ button_diff = translated_buttons ^ source_device->button_state; /* Gdk buttons are numbered 1.. */ event_button = 1; for (button_mask = 1; button_mask != 0x80000000; button_mask <<= 1, event_button++) { if (button_diff & button_mask) { /* Found a button that has changed state */ break; } } if (!(translated_buttons & button_mask)) { event_type = GDK_BUTTON_RELEASE; } else { event_type = GDK_BUTTON_PRESS; } source_device->button_state ^= button_mask; } else { event_type = GDK_MOTION_NOTIFY; } key_state = get_modifier_key_state (); if (event_type == GDK_BUTTON_PRESS || event_type == GDK_BUTTON_RELEASE) { axes = g_new (double, GDK_AXIS_LAST); _gdk_device_wintab_translate_axes (source_device, window, axes, &event_x, &event_y); event_state = key_state | ((source_device->button_state << 8) & (GDK_BUTTON1_MASK | GDK_BUTTON2_MASK | GDK_BUTTON3_MASK | GDK_BUTTON4_MASK | GDK_BUTTON5_MASK)); event = gdk_button_event_new (event_type, window, device_manager->core_pointer, NULL, _gdk_win32_get_next_tick (msg->time), event_state, event_button, event_x, event_y, axes); GDK_NOTE (EVENTS_OR_INPUT, g_print ("WINTAB button %s:%d %g,%g\n", (event->event_type == GDK_BUTTON_PRESS ? "press" : "release"), ((GdkButtonEvent *) event)->button, ((GdkButtonEvent *) event)->x, ((GdkButtonEvent *) event)->y)); } else { axes = g_new (double, GDK_AXIS_LAST); _gdk_device_wintab_translate_axes (source_device, window, axes, &event_x, &event_y); event_state = key_state | ((source_device->button_state << 8) & (GDK_BUTTON1_MASK | GDK_BUTTON2_MASK | GDK_BUTTON3_MASK | GDK_BUTTON4_MASK | GDK_BUTTON5_MASK)); event = gdk_motion_event_new (window, device_manager->core_pointer, NULL, _gdk_win32_get_next_tick (msg->time), event_state, event_x, event_y, axes); GDK_NOTE (EVENTS_OR_INPUT, g_print ("WINTAB motion: %g,%g\n", ((GdkMotionEvent *) event)->x, ((GdkMotionEvent *) event)->y)); } return event; case WT_CSRCHANGE: if (device_manager->dev_entered_proximity > 0) device_manager->dev_entered_proximity -= 1; if ((source_device = gdk_device_manager_find_wintab_device (device_manager, (HCTX) msg->lParam, packet.pkCursor)) == NULL) return NULL; if (source_device->sends_core) { _gdk_device_virtual_set_active (device_manager->core_pointer, GDK_DEVICE (source_device)); _gdk_input_ignore_core += 1; } return NULL; case WT_PROXIMITY: if (LOWORD (msg->lParam) == 0) { if (_gdk_input_ignore_core > 0) { _gdk_input_ignore_core -= 1; if (_gdk_input_ignore_core == 0) _gdk_device_virtual_set_active (device_manager->core_pointer, device_manager->system_pointer); } } else { device_manager->dev_entered_proximity += 1; } return NULL; } return NULL; }
35.2698
151
0.607576
[ "object" ]
d133c21574fb40ce058eb5970ffa388e0c5803f7
24,128
h
C
tensorstore/util/bfloat16.h
google/tensorstore
8df16a67553debaec098698ceaa5404eaf79634a
[ "BSD-2-Clause" ]
106
2020-04-02T20:00:18.000Z
2022-03-23T20:27:31.000Z
tensorstore/util/bfloat16.h
0xgpapad/tensorstore
dfc2972e54588a7b745afea8b9322b57b26b657a
[ "BSD-2-Clause" ]
28
2020-04-12T02:04:47.000Z
2022-03-23T20:27:03.000Z
tensorstore/util/bfloat16.h
0xgpapad/tensorstore
dfc2972e54588a7b745afea8b9322b57b26b657a
[ "BSD-2-Clause" ]
18
2020-04-08T06:41:30.000Z
2022-02-18T03:05:49.000Z
// Copyright 2021 The TensorStore Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef TENSORSTORE_UTIL_BFLOAT16_H_ #define TENSORSTORE_UTIL_BFLOAT16_H_ #include <cassert> #include <cmath> #include <cstdint> #include <cstring> #include <limits> #include "tensorstore/internal/bit_operations.h" #include "tensorstore/internal/json_fwd.h" // The implementation below is derived from Tensorflow and Eigen: // https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Core/arch/Default/BFloat16.h // // Copyright 2017 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. namespace tensorstore { class bfloat16_t; namespace internal { bfloat16_t NumericFloat32ToBfloat16RoundNearestEven(float v); bfloat16_t Float32ToBfloat16RoundNearestEven(float v); float Bfloat16ToFloat(bfloat16_t v); } // namespace internal /// Storage-only bfloat16 type. /// /// https://en.wikipedia.org/wiki/Bfloat16_floating-point_format /// /// This differs from Eigen::bfloat16 and tensorflow::bfloat16 in that it /// preserves subnormals rather than flushing them to zero, and also preserves /// signaling NaN. class bfloat16_t { public: constexpr bfloat16_t() : rep_(0) {} /// Possibly lossy conversion from any type convertible to `float`. template <typename T, typename = std::enable_if_t<std::is_convertible_v<T, float>>> explicit bfloat16_t(T x) { if constexpr (std::is_same_v<T, bool>) { rep_ = uint16_t(x) * 0x3f80; } else if constexpr (std::is_integral_v<T>) { *this = internal::NumericFloat32ToBfloat16RoundNearestEven( static_cast<float>(x)); } else { *this = internal::Float32ToBfloat16RoundNearestEven(static_cast<float>(x)); } } /// Lossless conversion to float. operator float() const { return internal::Bfloat16ToFloat(*this); } bfloat16_t& operator=(float v) { return *this = static_cast<bfloat16_t>(v); } bfloat16_t& operator=(bool v) { return *this = static_cast<bfloat16_t>(v); } template <typename T> std::enable_if_t<std::is_integral_v<T>, bfloat16_t&> operator=(T v) { return *this = static_cast<bfloat16_t>(v); } /// Define arithmetic operators. Mixed operations involving other floating /// point are supported automatically by the implicit conversion to float. /// However, for operations with only `bfloat16_t` parameters, or with one /// `bfloat16_t` parameter and one integer parameter, we provide an /// implementation that converts the result back to `bfloat16_t` for /// consistency with the builtin floating point operations. #define TENSORSTORE_INTERNAL_BFLOAT16_BINARY_OP(OP) \ friend bfloat16_t operator OP(bfloat16_t a, bfloat16_t b) { \ return bfloat16_t(static_cast<float>(a) OP static_cast<float>(b)); \ } \ template <typename T> \ friend std::enable_if_t<std::is_integral_v<T>, bfloat16_t> operator OP( \ bfloat16_t a, T b) { \ return bfloat16_t(static_cast<float>(a) OP b); \ } \ template <typename T> \ friend std::enable_if_t<std::is_integral_v<T>, bfloat16_t> operator OP( \ T a, bfloat16_t b) { \ return bfloat16_t(a OP static_cast<float>(b)); \ } \ friend bfloat16_t& operator OP##=(bfloat16_t& a, bfloat16_t b) { \ return a = bfloat16_t(static_cast<float>(a) OP static_cast<float>(b)); \ } \ template <typename T> \ friend std::enable_if_t<std::is_integral_v<T>, bfloat16_t&> operator OP##=( \ bfloat16_t& a, T b) { \ return a = bfloat16_t(static_cast<float>(a) OP b); \ } \ /**/ TENSORSTORE_INTERNAL_BFLOAT16_BINARY_OP(+) TENSORSTORE_INTERNAL_BFLOAT16_BINARY_OP(-) TENSORSTORE_INTERNAL_BFLOAT16_BINARY_OP(*) TENSORSTORE_INTERNAL_BFLOAT16_BINARY_OP(/) #undef TENSORSTORE_INTERNAL_BFLOAT16_BINARY_OP /// Unary negation. friend bfloat16_t operator-(bfloat16_t a) { bfloat16_t result; result.rep_ = a.rep_ ^ 0x8000; return result; } /// Unary plus. friend bfloat16_t operator+(bfloat16_t a) { return a; } /// Pre-increment. friend bfloat16_t operator++(bfloat16_t& a) { a += bfloat16_t(1); return a; } /// Pre-decrement. friend bfloat16_t operator--(bfloat16_t& a) { a -= bfloat16_t(1); return a; } /// Post-increment. friend bfloat16_t operator++(bfloat16_t& a, int) { bfloat16_t original_value = a; ++a; return original_value; } /// Post-decrement. friend bfloat16_t operator--(bfloat16_t& a, int) { bfloat16_t original_value = a; --a; return original_value; } // Note: Comparison operators do not need to be defined since they are // provided automatically by the implicit conversion to `float`. /// Conversion to `::nlohmann::json`. template <template <typename U, typename V, typename... Args> class ObjectType /* = std::map*/, template <typename U, typename... Args> class ArrayType /* = std::vector*/, class StringType /*= std::string*/, class BooleanType /* = bool*/, class NumberIntegerType /* = std::int64_t*/, class NumberUnsignedType /* = std::uint64_t*/, class NumberFloatType /* = double*/, template <typename U> class AllocatorType /* = std::allocator*/, template <typename T, typename SFINAE = void> class JSONSerializer /* = adl_serializer*/, class BinaryType /* = std::vector<std::uint8_t>*/> friend void to_json( ::nlohmann::basic_json<ObjectType, ArrayType, StringType, BooleanType, NumberIntegerType, NumberUnsignedType, NumberFloatType, AllocatorType, JSONSerializer, BinaryType>& j, bfloat16_t v) { j = static_cast<NumberFloatType>(v); } // Treat as private: // Workaround for non-constexpr bit_cast implementation. struct bitcast_construct_t {}; explicit constexpr bfloat16_t(bitcast_construct_t, uint16_t rep) : rep_(rep) {} uint16_t rep_; }; inline bool isinf(bfloat16_t x) { return std::isinf(static_cast<float>(x)); } inline bool signbit(bfloat16_t x) { return std::signbit(static_cast<float>(x)); } inline bool isnan(bfloat16_t x) { return std::isnan(static_cast<float>(x)); } inline bool isfinite(bfloat16_t x) { return std::isfinite(static_cast<float>(x)); } inline bfloat16_t abs(bfloat16_t x) { x.rep_ &= 0x7fff; return x; } inline bfloat16_t exp(bfloat16_t a) { return bfloat16_t(std::exp(static_cast<float>(a))); } inline bfloat16_t exp2(bfloat16_t a) { return bfloat16_t(std::exp2(static_cast<float>(a))); } inline bfloat16_t expm1(bfloat16_t a) { return bfloat16_t(std::expm1(static_cast<float>(a))); } inline bfloat16_t log(bfloat16_t a) { return bfloat16_t(std::log(static_cast<float>(a))); } inline bfloat16_t log1p(bfloat16_t a) { return bfloat16_t(std::log1p(static_cast<float>(a))); } inline bfloat16_t log10(bfloat16_t a) { return bfloat16_t(std::log10(static_cast<float>(a))); } inline bfloat16_t log2(bfloat16_t a) { return bfloat16_t(std::log2(static_cast<float>(a))); } inline bfloat16_t sqrt(bfloat16_t a) { return bfloat16_t(std::sqrt(static_cast<float>(a))); } inline bfloat16_t pow(bfloat16_t a, bfloat16_t b) { return bfloat16_t(std::pow(static_cast<float>(a), static_cast<float>(b))); } inline bfloat16_t sin(bfloat16_t a) { return bfloat16_t(std::sin(static_cast<float>(a))); } inline bfloat16_t cos(bfloat16_t a) { return bfloat16_t(std::cos(static_cast<float>(a))); } inline bfloat16_t tan(bfloat16_t a) { return bfloat16_t(std::tan(static_cast<float>(a))); } inline bfloat16_t asin(bfloat16_t a) { return bfloat16_t(std::asin(static_cast<float>(a))); } inline bfloat16_t acos(bfloat16_t a) { return bfloat16_t(std::acos(static_cast<float>(a))); } inline bfloat16_t atan(bfloat16_t a) { return bfloat16_t(std::atan(static_cast<float>(a))); } inline bfloat16_t sinh(bfloat16_t a) { return bfloat16_t(std::sinh(static_cast<float>(a))); } inline bfloat16_t cosh(bfloat16_t a) { return bfloat16_t(std::cosh(static_cast<float>(a))); } inline bfloat16_t tanh(bfloat16_t a) { return bfloat16_t(std::tanh(static_cast<float>(a))); } inline bfloat16_t asinh(bfloat16_t a) { return bfloat16_t(std::asinh(static_cast<float>(a))); } inline bfloat16_t acosh(bfloat16_t a) { return bfloat16_t(std::acosh(static_cast<float>(a))); } inline bfloat16_t atanh(bfloat16_t a) { return bfloat16_t(std::atanh(static_cast<float>(a))); } inline bfloat16_t floor(bfloat16_t a) { return bfloat16_t(std::floor(static_cast<float>(a))); } inline bfloat16_t trunc(bfloat16_t a) { return bfloat16_t(std::trunc(static_cast<float>(a))); } inline bfloat16_t rint(bfloat16_t a) { return bfloat16_t(std::rint(static_cast<float>(a))); } inline bfloat16_t ceil(bfloat16_t a) { return bfloat16_t(std::ceil(static_cast<float>(a))); } inline bfloat16_t fmod(bfloat16_t a, bfloat16_t b) { return bfloat16_t(std::fmod(static_cast<float>(a), static_cast<float>(b))); } inline bfloat16_t fmin(bfloat16_t a, bfloat16_t b) { return bfloat16_t(std::fmin(static_cast<float>(a), static_cast<float>(b))); } inline bfloat16_t fmax(bfloat16_t a, bfloat16_t b) { return bfloat16_t(std::fmax(static_cast<float>(a), static_cast<float>(b))); } inline bfloat16_t nextafter(bfloat16_t from, bfloat16_t to) { const uint16_t from_as_int = internal::bit_cast<uint16_t>(from), to_as_int = internal::bit_cast<uint16_t>(to); const uint16_t sign_mask = 1 << 15; float from_as_float(from), to_as_float(to); if (std::isnan(from_as_float) || std::isnan(to_as_float)) { return bfloat16_t(std::numeric_limits<float>::quiet_NaN()); } if (from_as_int == to_as_int) { return to; } if (from_as_float == 0) { if (to_as_float == 0) { return to; } else { // Smallest subnormal signed like `to`. return internal::bit_cast<bfloat16_t, uint16_t>((to_as_int & sign_mask) | 1); } } uint16_t from_sign = from_as_int & sign_mask; uint16_t to_sign = to_as_int & sign_mask; uint16_t from_abs = from_as_int & ~sign_mask; uint16_t to_abs = to_as_int & ~sign_mask; uint16_t magnitude_adjustment = (from_abs > to_abs || from_sign != to_sign) ? 0xFFFF : 0x0001; return internal::bit_cast<bfloat16_t, uint16_t>(from_as_int + magnitude_adjustment); } namespace internal { inline uint16_t GetFloat32High16(float v) { return static_cast<uint16_t>(bit_cast<uint32_t>(v) >> 16); } /// Converts float32 -> bfloat16, rounding towards zero (truncating). inline bfloat16_t Float32ToBfloat16Truncate(float v) { // IEEE 764 binary32 floating point representation: // // Exponent | Fraction = 0 | Fraction != 0 // ---------------------------------------- // 0 | zero | subnormal // 0x1..0xfe | normal value | normal value // 0xff | +/- infinity | NaN // // For exponents not equal to `0xff`, we can simply truncate the low 16 bits // of the fraction. This may result in a subnormal value becoming zero, but // that is not a problem. // // However, if the exponent is equal to `0xff`, truncating the low 16 bits of // the fraction may convert a NaN to infinity. uint32_t bits = bit_cast<uint32_t>(v); if (std::isnan(v)) { // Set bit 21 (second to highest fraction bit) to 1, to ensure the truncated // fraction still indicates a NaN. This preserves the sign and also // preserves the high bit of the fraction (quiet/signalling NaN bit). bits |= (uint32_t(1) << 21); } return bit_cast<bfloat16_t, uint16_t>(bits >> 16); } /// Converts finite float32 -> bfloat16, rounding to the nearest, or to even in /// the case of a tie. /// /// The input must not be NaN. This is more efficient than the general /// `Float32ToBfloat16RoundNearestEven` conversion in the case that the input is /// known not to be NaN (e.g. for integer conversion by way of float). inline bfloat16_t NumericFloat32ToBfloat16RoundNearestEven(float v) { assert(!std::isnan(v)); // Fast rounding algorithm that rounds a half value to nearest even. This // reduces expected error when we convert a large number of floats. Here // is how it works: // // Definitions: // To convert a float 32 to bfloat16, a float 32 can be viewed as 32 bits // with the following tags: // // Sign | Exp (8 bits) | Frac (23 bits) // S EEEEEEEE FFFFFFLRTTTTTTTTTTTTTTT // // S: Sign bit. // E: Exponent bits. // F: First 6 bits of fraction. // L: Least significant bit of resulting bfloat16 if we truncate away the // rest of the float32. This is also the 7th bit of fraction // R: Rounding bit, 8th bit of fraction. // T: Sticky bits, rest of fraction, 15 bits. // // To round half to nearest even, there are 3 cases where we want to round // down (simply truncate the result of the bits away, which consists of // rounding bit and sticky bits) and two cases where we want to round up // (truncate then add one to the result). // // The fast converting algorithm simply adds lsb (L) to 0x7fff (15 bits of // 1s) as the rounding bias, adds the rounding bias to the input, then // truncates the last 16 bits away. // // To understand how it works, we can analyze this algorithm case by case: // // 1. L = 0, R = 0: // Expect: round down, this is less than half value. // // Algorithm: // - Rounding bias: 0x7fff + 0 = 0x7fff // - Adding rounding bias to input may create any carry, depending on // whether there is any value set to 1 in T bits. // - R may be set to 1 if there is a carry. // - L remains 0. // - Note that this case also handles Inf and -Inf, where all fraction // bits, including L, R and Ts are all 0. The output remains Inf after // this algorithm. // // 2. L = 1, R = 0: // Expect: round down, this is less than half value. // // Algorithm: // - Rounding bias: 0x7fff + 1 = 0x8000 // - Adding rounding bias to input doesn't change sticky bits but // adds 1 to rounding bit. // - L remains 1. // // 3. L = 0, R = 1, all of T are 0: // Expect: round down, this is exactly at half, the result is already // even (L=0). // // Algorithm: // - Rounding bias: 0x7fff + 0 = 0x7fff // - Adding rounding bias to input sets all sticky bits to 1, but // doesn't create a carry. // - R remains 1. // - L remains 0. // // 4. L = 1, R = 1: // Expect: round up, this is exactly at half, the result needs to be // round to the next even number. // // Algorithm: // - Rounding bias: 0x7fff + 1 = 0x8000 // - Adding rounding bias to input doesn't change sticky bits, but // creates a carry from rounding bit. // - The carry sets L to 0, creates another carry bit and propagate // forward to F bits. // - If all the F bits are 1, a carry then propagates to the exponent // bits, which then creates the minimum value with the next exponent // value. Note that we won't have the case where exponents are all 1, // since that's either a NaN (handled in the other if condition) or inf // (handled in case 1). // // 5. L = 0, R = 1, any of T is 1: // Expect: round up, this is greater than half. // // Algorithm: // - Rounding bias: 0x7fff + 0 = 0x7fff // - Adding rounding bias to input creates a carry from sticky bits, // sets rounding bit to 0, then create another carry. // - The second carry sets L to 1. // // Examples: // // Exact half value that is already even: // Input: // Sign | Exp (8 bit) | Frac (first 7 bit) | Frac (last 16 bit) // S E E E E E E E E F F F F F F L RTTTTTTTTTTTTTTT // 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1000000000000000 // // This falls into case 3. We truncate the rest of 16 bits and no // carry is created into F and L: // // Output: // Sign | Exp (8 bit) | Frac (first 7 bit) // S E E E E E E E E F F F F F F L // 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 // // Exact half value, round to next even number: // Input: // Sign | Exp (8 bit) | Frac (first 7 bit) | Frac (last 16 bit) // S E E E E E E E E F F F F F F L RTTTTTTTTTTTTTTT // 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1000000000000000 // // This falls into case 4. We create a carry from R and T, // which then propagates into L and F: // // Output: // Sign | Exp (8 bit) | Frac (first 7 bit) // S E E E E E E E E F F F F F F L // 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 // // // Max denormal value round to min normal value: // Input: // Sign | Exp (8 bit) | Frac (first 7 bit) | Frac (last 16 bit) // S E E E E E E E E F F F F F F L RTTTTTTTTTTTTTTT // 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1111111111111111 // // This falls into case 4. We create a carry from R and T, // propagate into L and F, which then propagates into exponent // bits: // // Output: // Sign | Exp (8 bit) | Frac (first 7 bit) // S E E E E E E E E F F F F F F L // 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 // // Max normal value round to Inf: // Input: // Sign | Exp (8 bit) | Frac (first 7 bit) | Frac (last 16 bit) // S E E E E E E E E F F F F F F L RTTTTTTTTTTTTTTT // 0 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1111111111111111 // // This falls into case 4. We create a carry from R and T, // propagate into L and F, which then propagates into exponent // bits: // // Sign | Exp (8 bit) | Frac (first 7 bit) // S E E E E E E E E F F F F F F L // 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 uint32_t input = bit_cast<uint32_t>(v); const uint32_t lsb = (input >> 16) & 1; const uint32_t rounding_bias = 0x7fff + lsb; input += rounding_bias; return bit_cast<bfloat16_t, uint16_t>(input >> 16); } /// Converts float32 -> bfloat16, rounding to the nearest, or to even in the /// case of a tie. inline bfloat16_t Float32ToBfloat16RoundNearestEven(float v) { if (std::isnan(v)) { return bit_cast<bfloat16_t, uint16_t>( (bit_cast<uint32_t>(v) | (uint32_t(1) << 21)) >> 16); } return NumericFloat32ToBfloat16RoundNearestEven(v); } inline float Bfloat16ToFloat(bfloat16_t v) { return bit_cast<float>(static_cast<uint32_t>(bit_cast<uint16_t>(v)) << 16); } } // namespace internal } // namespace tensorstore namespace std { template <> struct numeric_limits<tensorstore::bfloat16_t> { static constexpr bool is_specialized = true; static constexpr bool is_signed = true; static constexpr bool is_integer = false; static constexpr bool is_exact = false; static constexpr bool has_infinity = true; static constexpr bool has_quiet_NaN = true; static constexpr bool has_signaling_NaN = true; static constexpr float_denorm_style has_denorm = std::denorm_present; static constexpr bool has_denorm_loss = false; static constexpr std::float_round_style round_style = numeric_limits<float>::round_style; static constexpr bool is_iec559 = false; static constexpr bool is_bounded = true; static constexpr bool is_modulo = false; static constexpr int digits = 8; static constexpr int digits10 = 2; static constexpr int max_digits10 = 4; static constexpr int radix = 2; static constexpr int min_exponent = numeric_limits<float>::min_exponent; static constexpr int min_exponent10 = numeric_limits<float>::min_exponent10; static constexpr int max_exponent = numeric_limits<float>::max_exponent; static constexpr int max_exponent10 = numeric_limits<float>::max_exponent10; static constexpr bool traps = numeric_limits<float>::traps; static constexpr bool tinyness_before = numeric_limits<float>::tinyness_before; /// Smallest positive normalized value: 0x1p-126 = 1.175494351e-38 static constexpr tensorstore::bfloat16_t min() { return tensorstore::bfloat16_t( tensorstore::bfloat16_t::bitcast_construct_t{}, static_cast<uint16_t>(0x0080)); } /// Lowest finite negative value: -0x1.fep+127 = -3.38953139e+38 static constexpr tensorstore::bfloat16_t lowest() { return tensorstore::bfloat16_t( tensorstore::bfloat16_t::bitcast_construct_t{}, static_cast<uint16_t>(0xff7f)); } /// Largest finite value: 0x1.fep127 = 3.38953139e+38 static constexpr tensorstore::bfloat16_t max() { return tensorstore::bfloat16_t( tensorstore::bfloat16_t::bitcast_construct_t{}, static_cast<uint16_t>(0x7f7f)); } /// Machine epsilon: 0x1p-7 = 0.0078125 /// /// Equal to `nextafter(bfloat16_t(1), bfloat16_t(2)) - bfloat16_t(1)`. static constexpr tensorstore::bfloat16_t epsilon() { return tensorstore::bfloat16_t( tensorstore::bfloat16_t::bitcast_construct_t{}, static_cast<uint16_t>(0x3c00)); } /// Largest possible rounding error in ULPs (units in the last place): 0.5 static constexpr tensorstore::bfloat16_t round_error() { return tensorstore::bfloat16_t( tensorstore::bfloat16_t::bitcast_construct_t{}, static_cast<uint16_t>(0x3f00)); } static constexpr tensorstore::bfloat16_t infinity() { return tensorstore::bfloat16_t( tensorstore::bfloat16_t::bitcast_construct_t{}, static_cast<uint16_t>(0x7f80)); } static constexpr tensorstore::bfloat16_t quiet_NaN() { return tensorstore::bfloat16_t( tensorstore::bfloat16_t::bitcast_construct_t{}, static_cast<uint16_t>(0x7fc0)); } static constexpr tensorstore::bfloat16_t signaling_NaN() { return tensorstore::bfloat16_t( tensorstore::bfloat16_t::bitcast_construct_t{}, static_cast<uint16_t>(0x7f81)); } /// Smallest positive subnormal value: 0x1p-133 = 9.18354962e-41 static constexpr tensorstore::bfloat16_t denorm_min() { return tensorstore::bfloat16_t( tensorstore::bfloat16_t::bitcast_construct_t{}, static_cast<uint16_t>(0x0001)); } }; } // namespace std #endif // TENSORSTORE_UTIL_BFLOAT16_H_
38.116904
89
0.64564
[ "vector" ]
d14c40498e9db9a8e4fd5976489d0ccbe1ee437d
10,443
h
C
PLC/plc2svg.h
saarbastler/plc
dcf9333878bb7c613b8c280281b39d5e407d0c6e
[ "BSD-2-Clause" ]
null
null
null
PLC/plc2svg.h
saarbastler/plc
dcf9333878bb7c613b8c280281b39d5e407d0c6e
[ "BSD-2-Clause" ]
null
null
null
PLC/plc2svg.h
saarbastler/plc
dcf9333878bb7c613b8c280281b39d5e407d0c6e
[ "BSD-2-Clause" ]
null
null
null
#ifndef _INCLUDE_PLC_2_SVG_H_ #define _INCLUDE_PLC_2_SVG_H_ #include <ostream> #include <sstream> #include <unordered_map> #include "plc2svgbase.h" class Plc2svg : public Plc2svgBase { public: Plc2svg(const PlcAst& plcAst, std::ostream& out, const std::initializer_list<SVGOption> options) : Plc2svgBase(plcAst, out, options) { } template<typename AT> Plc2svg(const PlcAst& plcAst, std::ostream& out, const AT& options) : Plc2svgBase(plcAst, out, options) { } void convertMultiple(const std::vector<std::string>& names) { std::unordered_map<std::string, plc::Expression> resolved; std::vector<const plc::Expression*> expressions; std::unordered_map<std::string,unsigned> toSkip; for (auto it = names.begin(); it != names.end(); it++) { resolved.emplace(*it, plcAst.resolveDependencies(*it, &toSkip)); expressions.emplace_back(&resolved[*it]); } for (auto it = toSkip.begin(); it != toSkip.end(); it++) if (it->second > 1) signalCrossing.emplace(it->first); for (auto it = names.begin(); it != names.end(); it++) resolved[*it].countInputs(inputCountMap); setupParameter(expressions); svg::AreaSize::clear(); unsigned y = 1; for (auto it = names.begin(); it != names.end(); it++) y+= 2 + convert(y, 0, resolved[*it], plc::Term::Unary::None, &plcAst.getVariable(*it)); writeOutput(svg::AreaSize::x(), svg::AreaSize::y()); } void convert(const plc::Expression& expression, const std::string& name) { expression.countInputs(inputCountMap); std::array<const plc::Expression*, 1> a{ &expression }; setupParameter(a); maxLevel = expression.countLevels(); svg::AreaSize::clear(); const Variable& variable = plcAst.getVariable(name); unsigned y= 2 + convert(1, 0, expression, plc::Term::Unary::None, &variable); writeOutput(svg::AreaSize::x(), svg::AreaSize::y()); } private: void countLevelCrossings(unsigned level, const plc::Expression& expression) { while (crossingsPerLevel.size() <= level) crossingsPerLevel.emplace_back(0); if (expression.variable()) { auto find = inputCountMap.find(expression.variable()->name()); if (find != inputCountMap.end()) ++crossingsPerLevel[level]; } for (auto it = expression.terms().begin(); it != expression.terms().end(); it++) if (it->type() == plc::Term::Type::Expression) countLevelCrossings(level + 1, *it->expression()); } template <typename T> void setupParameter(T v) { maxLevel = 0; for (auto it = v.begin(); it != v.end(); it++) { countLevelCrossings(0, **it); unsigned tmp = (*it)->countLevels(); if (tmp > maxLevel) maxLevel = tmp; } unsigned crossings = 0; unsigned chars = 0; for (auto it = inputCountMap.begin(); it != inputCountMap.end(); it++) { unsigned width = unsigned(it->first.length()); if (width > chars) chars = width; if (it->second > 1) crossings++; } crossingsPerLevel.emplace_back(crossings); textWidth = chars * svg::CHAR_CELL_WIDTH; } unsigned convert(unsigned ypos, unsigned level, const plc::Expression& expression, plc::Term::Unary unary, const Variable *variable = nullptr) { //std::cout << "convert Expression " << expression.signalName() << " " << expression.id() << " ypos: " << ypos << " level: " << level << std::endl; unsigned size = 0; unsigned index = 1; unsigned width = textWidth + (maxLevel - level - 1) * (LINE_LENGTH + GATE_WIDTH) + LINE_LENGTH; unsigned outy = (index + ypos) * svg::CHAR_CELL_HEIGHT; for (const plc::Term& term : expression.terms()) { unsigned y = (index + ypos) * svg::CHAR_CELL_HEIGHT; switch (term.type()) { case plc::Term::Type::Identifier: convertInput(term, level, y, width); index++; size++; break; case plc::Term::Type::Expression: { unsigned subSize = 2 + convert(index + ypos, level + 1, *term.expression(), term.unary()); index += subSize; size += subSize; } break; //default: } } unsigned lineX1 = crossingWidthUpToLevel(level) + width; unsigned lineX2 = crossingWidthUpToLevel(level - 1) + width + GATE_WIDTH + LINE_LENGTH; if (unary != plc::Term::Unary::None) lineX2 -= 2 * INVERT_RADIUS; if (expression.op() != plc::Expression::Operator::None /*|| expression.terms().size() > 1*/) { svgOut << svg::Rect(lineX1, ypos * svg::CHAR_CELL_HEIGHT, GATE_WIDTH, (size + 1) * svg::CHAR_CELL_HEIGHT, { BOX }) << svg::Text(lineX1 + CHAR_OFFSET, (1 + ypos) * svg::CHAR_CELL_HEIGHT + CHAR_OFFSET_Y, operatorSymbol(expression.op()), {}); if ( hasOption(SVGOption::BoxText)) { std::ostringstream tid; tid << 't' << gateCssClass(expression); svgOut << svg::Text(lineX1 + CHAR_OFFSET, (2 + ypos) * svg::CHAR_CELL_HEIGHT + CHAR_OFFSET_Y, "", {}, tid.str().c_str()); } lineX1 += GATE_WIDTH; } if (variable) { unsigned len = unsigned(variable->name().length()) * svg::CHAR_CELL_WIDTH; if (int(len) < lineX2 - lineX1) len = lineX2 - lineX1; //if(hasOption(SVGOption::NotInteractive)) svgOut << svg::Line(lineX1, outy, lineX1 + len, outy, { LINK, variableCssClass(*variable) }); //else // svgOut << svg::Line(lineX1, outy, lineX1 + len, outy, { LINK, gateCssClass(expression) }); svgOut << svg::Text(lineX1 + CHAR_OFFSET, (1 + ypos) * svg::CHAR_CELL_HEIGHT + CHAR_OFFSET_Y, variable->name().c_str(), {}); } else { svgOut << svg::Line(lineX1, outy, lineX2, outy, { LINK, gateCssClass(expression) }); if (unary != plc::Term::Unary::None) svgOut << svg::Circle(lineX2 + INVERT_RADIUS, outy, INVERT_RADIUS, { INVERT, gateCssClass(expression) }); if(hasOption(SVGOption::LinkLabels)) svgOut << svg::Text(lineX2 - 3 * svg::CHAR_CELL_WIDTH, (1 + ypos) * svg::CHAR_CELL_HEIGHT + CHAR_OFFSET_Y, gateCssClass(expression), {}); } if(expression.variable() && signalCrossing.find(expression.variable()->name()) != signalCrossing.end()) inputPosition.emplace(expression.variable()->name(), COORD{ lineX1 + CROSSING_WIDTH, outy }); expressionJsEquation(expression); return size; } unsigned crossingWidthUpToLevel(unsigned level) { unsigned crossingWidth = 0; for (int i = int(crossingsPerLevel.size()) - 1; i > int(level); i--) crossingWidth += crossingsPerLevel[i]; return crossingWidth * svg::CHAR_CELL_WIDTH; } void convertInput(const plc::Term& term, unsigned level, unsigned y, unsigned width) { const Variable& variable = *term.variable(); unsigned x = XSTART; auto input = inputPosition.find(term.variable()->name()); std::string cssClass(variableCssClass(variable)); if (input == inputPosition.end() ) { auto inputCount = inputCountMap.find(term.variable()->name()); if (inputCount != inputCountMap.end() && inputCount->second > 1) { //std::cout << "crossing " << term.variable()->name() << ": " << crossingCount << std::endl; inputPosition.emplace(term.variable()->name(), COORD{ XSTART + textWidth + crossingCount * CROSSING_WIDTH, y }); ++crossingCount; } svgOut << svg::Text(x, y + CHAR_OFFSET_Y, term.variable()->name(), { VARIABLE, cssClass.c_str() }, cssClass.c_str()); } else { x = input->second.x; svgOut << svg::Circle(x, input->second.y, JOIN_RADIUS, { JOIN, cssClass.c_str() }) << svg::Line(x, input->second.y, x, y, { LINK, cssClass.c_str() }); input->second.y = y; } int lineX1 = crossingWidthUpToLevel(level) + width; if (term.unary() == plc::Term::Unary::None) svgOut << svg::Line(x, y, lineX1, y, { LINK, cssClass.c_str() }); else svgOut << svg::Line(x, y, lineX1 - 2 * INVERT_RADIUS, y, { LINK, cssClass.c_str() }) << svg::Circle(lineX1 - INVERT_RADIUS, y, INVERT_RADIUS, { INVERT, cssClass.c_str() }); if (hasOption(SVGOption::LinkLabels)) svgOut << svg::Text(lineX1 - 3 * svg::CHAR_CELL_WIDTH, y + CHAR_OFFSET_Y, cssClass.c_str(), {}); } unsigned jsType(const plc::Expression& expression) const { if(expression.variable()) { return static_cast<unsigned>(expression.variable()->type()); } else { return js::Intermediate; } } unsigned jsTypeIndex(const plc::Expression& expression) const { if (expression.variable()) { return expression.variable()->index(); } else { return expression.id(); } } void expressionJsEquation(const plc::Expression& expression) { unsigned type = jsType(expression); if (!hasOption(SVGOption::NotInteractive) || (type != static_cast<unsigned>(Variable::Type::Monoflop) && (type != static_cast<unsigned>(Variable::Type::Output)))) { jsOut << "data[" << jsType(expression) << "][" << jsTypeIndex(expression) << "]= "; bool first = true; char opChar = (expression.op() == plc::Expression::Operator::And) ? '&' : '|'; for (const plc::Term& t : expression.terms()) { if (first) first = false; else jsOut << ' ' << opChar << ' '; if (t.unary() == plc::Term::Unary::Not) jsOut << '!'; switch (t.type()) { case plc::Term::Type::Identifier: { const Variable& v = plcAst.getVariable(t.variable()->name()); jsOut << "data[" << static_cast<int>(v.type()) << "][" << v.index() << ']'; } break; case plc::Term::Type::Expression: jsOut << "data[" << jsType(*t.expression()) << "][" << jsTypeIndex(*t.expression()) << ']'; break; } } jsOut << ";" << std::endl; } } unsigned maxLevel = 0; unsigned crossingCount = 0; unsigned textWidth = 0; std::vector<unsigned> crossingsPerLevel; }; #endif // !_INCLUDE_PLC_2_SVG_H_
32.132308
152
0.585081
[ "vector" ]
d14eddb465e3cd2316ee3c10c147fdbbcf0c0c9f
12,887
h
C
include/Platform/Windows Phone 8.1/UWP/WindowsUIXamlData.h
Alx06/WinObjC
668d3b57b98c69dece2359216bd754d57d89c2a9
[ "MIT" ]
1
2016-02-08T02:29:19.000Z
2016-02-08T02:29:19.000Z
include/Platform/Windows Phone 8.1/UWP/WindowsUIXamlData.h
Alx06/WinObjC
668d3b57b98c69dece2359216bd754d57d89c2a9
[ "MIT" ]
null
null
null
include/Platform/Windows Phone 8.1/UWP/WindowsUIXamlData.h
Alx06/WinObjC
668d3b57b98c69dece2359216bd754d57d89c2a9
[ "MIT" ]
null
null
null
//****************************************************************************** // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // 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. // //****************************************************************************** // WindowsUIXamlData.h // Generated from winmd2objc #pragma once #include "interopBase.h" @class WUXDCurrentChangingEventArgs, WUXDPropertyChangedEventArgs, WUXDBindingBase, WUXDBinding, WUXDBindingExpressionBase, WUXDBindingExpression, WUXDCollectionViewSource, WUXDRelativeSource, WUXDBindingOperations; @class WUXDLoadMoreItemsResult; @protocol WUXDIBinding, WUXDIValueConverter, WUXDIBindingFactory, WUXDIBinding2, WUXDIBindingBase, WUXDIBindingBaseFactory, WUXDIBindingExpression, WUXDIBindingExpressionFactory, WUXDIBindingExpressionBase, WUXDIBindingExpressionBaseFactory, WUXDICollectionViewSource, WUXDICollectionView, WUXDICollectionViewSourceStatics, WUXDICurrentChangingEventArgs, WUXDICurrentChangingEventArgsFactory, WUXDICollectionViewGroup, WUXDICustomProperty, WUXDICustomPropertyProvider, WUXDINotifyPropertyChanged, WUXDIPropertyChangedEventArgs, WUXDIPropertyChangedEventArgsFactory, WUXDIRelativeSource, WUXDIRelativeSourceFactory, WUXDIBindingOperations, WUXDIBindingOperationsStatics, WUXDISupportIncrementalLoading, WUXDICollectionViewFactory; // Windows.UI.Xaml.Data.BindingMode enum _WUXDBindingMode { WUXDBindingModeOneWay = 1, WUXDBindingModeOneTime = 2, WUXDBindingModeTwoWay = 3, }; typedef unsigned WUXDBindingMode; // Windows.UI.Xaml.Data.RelativeSourceMode enum _WUXDRelativeSourceMode { WUXDRelativeSourceModeNone = 0, WUXDRelativeSourceModeTemplatedParent = 1, WUXDRelativeSourceModeSelf = 2, }; typedef unsigned WUXDRelativeSourceMode; // Windows.UI.Xaml.Data.UpdateSourceTrigger enum _WUXDUpdateSourceTrigger { WUXDUpdateSourceTriggerDefault = 0, WUXDUpdateSourceTriggerPropertyChanged = 1, WUXDUpdateSourceTriggerExplicit = 2, }; typedef unsigned WUXDUpdateSourceTrigger; #include "WindowsUIXaml.h" #include "WindowsUIXamlInterop.h" #include "WindowsFoundationCollections.h" #include "WindowsFoundation.h" #include "WindowsUICore.h" // Windows.UI.Xaml.Data.CurrentChangingEventHandler #ifndef __WUXDCurrentChangingEventHandler__DEFINED #define __WUXDCurrentChangingEventHandler__DEFINED typedef void(^WUXDCurrentChangingEventHandler)(RTObject * sender, WUXDCurrentChangingEventArgs * e); #endif // __WUXDCurrentChangingEventHandler__DEFINED // Windows.UI.Xaml.Data.PropertyChangedEventHandler #ifndef __WUXDPropertyChangedEventHandler__DEFINED #define __WUXDPropertyChangedEventHandler__DEFINED typedef void(^WUXDPropertyChangedEventHandler)(RTObject * sender, WUXDPropertyChangedEventArgs * e); #endif // __WUXDPropertyChangedEventHandler__DEFINED // [struct] Windows.UI.Xaml.Data.LoadMoreItemsResult WINRT_EXPORT @interface WUXDLoadMoreItemsResult : NSObject + (instancetype)new; @property unsigned count; @end // Windows.UI.Xaml.Data.CurrentChangingEventHandler #ifndef __WUXDCurrentChangingEventHandler__DEFINED #define __WUXDCurrentChangingEventHandler__DEFINED typedef void(^WUXDCurrentChangingEventHandler)(RTObject * sender, WUXDCurrentChangingEventArgs * e); #endif // __WUXDCurrentChangingEventHandler__DEFINED // Windows.UI.Xaml.Data.PropertyChangedEventHandler #ifndef __WUXDPropertyChangedEventHandler__DEFINED #define __WUXDPropertyChangedEventHandler__DEFINED typedef void(^WUXDPropertyChangedEventHandler)(RTObject * sender, WUXDPropertyChangedEventArgs * e); #endif // __WUXDPropertyChangedEventHandler__DEFINED // Windows.UI.Xaml.Data.IValueConverter #ifndef __WUXDIValueConverter_DEFINED__ #define __WUXDIValueConverter_DEFINED__ @protocol WUXDIValueConverter - (RTObject *)convert:(RTObject *)value targetType:(WUXITypeName *)targetType parameter:(RTObject *)parameter language:(NSString *)language; - (RTObject *)convertBack:(RTObject *)value targetType:(WUXITypeName *)targetType parameter:(RTObject *)parameter language:(NSString *)language; @end #endif // __WUXDIValueConverter_DEFINED__ // Windows.UI.Xaml.Data.ICollectionView #ifndef __WUXDICollectionView_DEFINED__ #define __WUXDICollectionView_DEFINED__ @protocol WUXDICollectionView // Failed to generate property CollectionGroups (Can't marshal Windows.Foundation.Collections.IObservableVector`1<System.Object>) @property (readonly) RTObject * currentItem; @property (readonly) int currentPosition; @property (readonly) BOOL hasMoreItems; @property (readonly) BOOL isCurrentAfterLast; @property (readonly) BOOL isCurrentBeforeFirst; - (EventRegistrationToken)addCurrentChangedEvent:(void(^)(RTObject*, RTObject *))del; - (void)removeCurrentChangedEvent:(EventRegistrationToken)tok; - (EventRegistrationToken)addCurrentChangingEvent:(WUXDCurrentChangingEventHandler)del; - (void)removeCurrentChangingEvent:(EventRegistrationToken)tok; // Failed to generate member get_CollectionGroups (Can't marshal Windows.Foundation.Collections.IObservableVector`1<System.Object>) - (BOOL)moveCurrentTo:(RTObject *)item; - (BOOL)moveCurrentToPosition:(int)index; - (BOOL)moveCurrentToFirst; - (BOOL)moveCurrentToLast; - (BOOL)moveCurrentToNext; - (BOOL)moveCurrentToPrevious; - (void)loadMoreItemsAsync:(unsigned)count success:(void (^)(WUXDLoadMoreItemsResult *))success failure:(void (^)(NSError*))failure; // Could not find base class Windows.Foundation.Collections.IObservableVector`1<System.Object> type information @end #endif // __WUXDICollectionView_DEFINED__ // Windows.UI.Xaml.Data.ICollectionViewGroup #ifndef __WUXDICollectionViewGroup_DEFINED__ #define __WUXDICollectionViewGroup_DEFINED__ @protocol WUXDICollectionViewGroup @property (readonly) RTObject * group; // Failed to generate property GroupItems (Can't marshal Windows.Foundation.Collections.IObservableVector`1<System.Object>) // Failed to generate member get_GroupItems (Can't marshal Windows.Foundation.Collections.IObservableVector`1<System.Object>) @end #endif // __WUXDICollectionViewGroup_DEFINED__ // Windows.UI.Xaml.Data.ICustomProperty #ifndef __WUXDICustomProperty_DEFINED__ #define __WUXDICustomProperty_DEFINED__ @protocol WUXDICustomProperty @property (readonly) BOOL canRead; @property (readonly) BOOL canWrite; @property (readonly) NSString * name; @property (readonly) WUXITypeName * type; - (RTObject *)getValue:(RTObject *)target; - (void)setValue:(RTObject *)target value:(RTObject *)value; - (RTObject *)getIndexedValue:(RTObject *)target index:(RTObject *)index; - (void)setIndexedValue:(RTObject *)target value:(RTObject *)value index:(RTObject *)index; @end #endif // __WUXDICustomProperty_DEFINED__ // Windows.UI.Xaml.Data.ICustomPropertyProvider #ifndef __WUXDICustomPropertyProvider_DEFINED__ #define __WUXDICustomPropertyProvider_DEFINED__ @protocol WUXDICustomPropertyProvider @property (readonly) WUXITypeName * type; - (RTObject<WUXDICustomProperty>*)getCustomProperty:(NSString *)name; - (RTObject<WUXDICustomProperty>*)getIndexedProperty:(NSString *)name type:(WUXITypeName *)type; - (NSString *)getStringRepresentation; @end #endif // __WUXDICustomPropertyProvider_DEFINED__ // Windows.UI.Xaml.Data.INotifyPropertyChanged #ifndef __WUXDINotifyPropertyChanged_DEFINED__ #define __WUXDINotifyPropertyChanged_DEFINED__ @protocol WUXDINotifyPropertyChanged - (EventRegistrationToken)addPropertyChangedEvent:(WUXDPropertyChangedEventHandler)del; - (void)removePropertyChangedEvent:(EventRegistrationToken)tok; @end #endif // __WUXDINotifyPropertyChanged_DEFINED__ // Windows.UI.Xaml.Data.ISupportIncrementalLoading #ifndef __WUXDISupportIncrementalLoading_DEFINED__ #define __WUXDISupportIncrementalLoading_DEFINED__ @protocol WUXDISupportIncrementalLoading @property (readonly) BOOL hasMoreItems; - (void)loadMoreItemsAsync:(unsigned)count success:(void (^)(WUXDLoadMoreItemsResult *))success failure:(void (^)(NSError*))failure; @end #endif // __WUXDISupportIncrementalLoading_DEFINED__ // Windows.UI.Xaml.Data.ICollectionViewFactory #ifndef __WUXDICollectionViewFactory_DEFINED__ #define __WUXDICollectionViewFactory_DEFINED__ @protocol WUXDICollectionViewFactory - (RTObject<WUXDICollectionView>*)createView; @end #endif // __WUXDICollectionViewFactory_DEFINED__ // Windows.UI.Xaml.Data.CurrentChangingEventArgs #ifndef __WUXDCurrentChangingEventArgs_DEFINED__ #define __WUXDCurrentChangingEventArgs_DEFINED__ WINRT_EXPORT @interface WUXDCurrentChangingEventArgs : RTObject + (instancetype)create ACTIVATOR; @property BOOL cancel; @property (readonly) BOOL isCancelable; @end #endif // __WUXDCurrentChangingEventArgs_DEFINED__ // Windows.UI.Xaml.Data.PropertyChangedEventArgs #ifndef __WUXDPropertyChangedEventArgs_DEFINED__ #define __WUXDPropertyChangedEventArgs_DEFINED__ WINRT_EXPORT @interface WUXDPropertyChangedEventArgs : RTObject @property (readonly) NSString * propertyName; @end #endif // __WUXDPropertyChangedEventArgs_DEFINED__ // Windows.UI.Xaml.DependencyObject #ifndef __WXDependencyObject_DEFINED__ #define __WXDependencyObject_DEFINED__ WINRT_EXPORT @interface WXDependencyObject : RTObject + (instancetype)create ACTIVATOR; @property (readonly) WUCCoreDispatcher * dispatcher; - (RTObject *)getValue:(WXDependencyProperty *)dp; - (void)setValue:(WXDependencyProperty *)dp value:(RTObject *)value; - (void)clearValue:(WXDependencyProperty *)dp; - (RTObject *)readLocalValue:(WXDependencyProperty *)dp; - (RTObject *)getAnimationBaseValue:(WXDependencyProperty *)dp; @end #endif // __WXDependencyObject_DEFINED__ // Windows.UI.Xaml.Data.BindingBase #ifndef __WUXDBindingBase_DEFINED__ #define __WUXDBindingBase_DEFINED__ WINRT_EXPORT @interface WUXDBindingBase : WXDependencyObject + (instancetype)create ACTIVATOR; @end #endif // __WUXDBindingBase_DEFINED__ // Windows.UI.Xaml.Data.Binding #ifndef __WUXDBinding_DEFINED__ #define __WUXDBinding_DEFINED__ WINRT_EXPORT @interface WUXDBinding : WUXDBindingBase + (instancetype)create ACTIVATOR; @property WUXDUpdateSourceTrigger updateSourceTrigger; @property (copy) RTObject * targetNullValue; @property (copy) RTObject * fallbackValue; @property (copy) RTObject * source; @property (copy) WUXDRelativeSource * relativeSource; @property (copy) WXPropertyPath * path; @property WUXDBindingMode mode; @property (copy) NSString * elementName; @property (copy) RTObject * converterParameter; @property (copy) NSString * converterLanguage; @property (copy) RTObject<WUXDIValueConverter>* converter; @end #endif // __WUXDBinding_DEFINED__ // Windows.UI.Xaml.Data.BindingExpressionBase #ifndef __WUXDBindingExpressionBase_DEFINED__ #define __WUXDBindingExpressionBase_DEFINED__ WINRT_EXPORT @interface WUXDBindingExpressionBase : RTObject @end #endif // __WUXDBindingExpressionBase_DEFINED__ // Windows.UI.Xaml.Data.BindingExpression #ifndef __WUXDBindingExpression_DEFINED__ #define __WUXDBindingExpression_DEFINED__ WINRT_EXPORT @interface WUXDBindingExpression : WUXDBindingExpressionBase @property (readonly) RTObject * dataItem; @property (readonly) WUXDBinding * parentBinding; - (void)updateSource; @end #endif // __WUXDBindingExpression_DEFINED__ // Windows.UI.Xaml.Data.CollectionViewSource #ifndef __WUXDCollectionViewSource_DEFINED__ #define __WUXDCollectionViewSource_DEFINED__ WINRT_EXPORT @interface WUXDCollectionViewSource : WXDependencyObject + (instancetype)create ACTIVATOR; @property (copy) RTObject * source; @property (copy) WXPropertyPath * itemsPath; @property BOOL isSourceGrouped; @property (readonly) RTObject<WUXDICollectionView>* view; + (WXDependencyProperty *)isSourceGroupedProperty; + (WXDependencyProperty *)itemsPathProperty; + (WXDependencyProperty *)sourceProperty; + (WXDependencyProperty *)viewProperty; @end #endif // __WUXDCollectionViewSource_DEFINED__ // Windows.UI.Xaml.Data.RelativeSource #ifndef __WUXDRelativeSource_DEFINED__ #define __WUXDRelativeSource_DEFINED__ WINRT_EXPORT @interface WUXDRelativeSource : WXDependencyObject + (instancetype)create ACTIVATOR; @property WUXDRelativeSourceMode mode; @end #endif // __WUXDRelativeSource_DEFINED__ // Windows.UI.Xaml.Data.BindingOperations #ifndef __WUXDBindingOperations_DEFINED__ #define __WUXDBindingOperations_DEFINED__ WINRT_EXPORT @interface WUXDBindingOperations : RTObject + (void)setBinding:(WXDependencyObject *)target dp:(WXDependencyProperty *)dp binding:(WUXDBindingBase *)binding; @end #endif // __WUXDBindingOperations_DEFINED__
37.902941
729
0.825949
[ "object" ]