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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1245b38adf676169eadea7e187d99bf2c2b079bc | 6,473 | c | C | ti-f28004x-resources-and-examples/examples_driverlib/examples/i2c/i2c_ex1_loopback.c | UOSupermileage/BLDC-F280049C | dc10e99a24ac2d959789043f883f89eacefcd90d | [
"MIT"
] | 2 | 2021-11-25T13:05:14.000Z | 2022-03-05T14:45:53.000Z | ti-f28004x-resources-and-examples/examples_driverlib/examples/i2c/i2c_ex1_loopback.c | UOSupermileage/BLDC-F280049C | dc10e99a24ac2d959789043f883f89eacefcd90d | [
"MIT"
] | null | null | null | ti-f28004x-resources-and-examples/examples_driverlib/examples/i2c/i2c_ex1_loopback.c | UOSupermileage/BLDC-F280049C | dc10e99a24ac2d959789043f883f89eacefcd90d | [
"MIT"
] | 1 | 2020-11-03T03:37:43.000Z | 2020-11-03T03:37:43.000Z | //#############################################################################
//
// FILE: i2c_ex1_loopback.c
//
// TITLE: I2C Digital Loopback with FIFO Interrupts
//
//! \addtogroup driver_example_list
//! <h1>I2C Digital Loopback with FIFO Interrupts</h1>
//!
//! This program uses the internal loopback test mode of the I2C module. Both
//! the TX and RX I2C FIFOs and their interrupts are used. The pinmux and I2C
//! initialization is done through the sysconfig file.
//!
//! A stream of data is sent and then compared to the received stream.
//! The sent data looks like this: \n
//! 0000 0001 \n
//! 0001 0002 \n
//! 0002 0003 \n
//! .... \n
//! 00FE 00FF \n
//! 00FF 0000 \n
//! etc.. \n
//! This pattern is repeated forever.
//!
//! \b External \b Connections \n
//! - None
//!
//! \b Watch \b Variables \n
//! - \b sData - Data to send
//! - \b rData - Received data
//! - \b rDataPoint - Used to keep track of the last position in the receive
//! stream for error checking
//!
//
//#############################################################################
// $TI Release: F28004x Support Library v1.10.00.00 $
// $Release Date: Tue May 26 17:06:03 IST 2020 $
// $Copyright:
// Copyright (C) 2020 Texas Instruments Incorporated - http://www.ti.com/
//
// 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 Texas Instruments Incorporated 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.
// $
//#############################################################################
//
// Included Files
//
#include "driverlib.h"
#include "device.h"
#include "board.h"
//
// Defines
//
#define SLAVE_ADDRESS 0x3C
//
// Globals
//
uint16_t sData[2]; // Send data buffer
uint16_t rData[2]; // Receive data buffer
uint16_t rDataPoint = 0; // To keep track of where we are in the
// data stream to check received data
//
// Function Prototypes
//
__interrupt void i2cFIFOISR(void);
//
// Main
//
void main(void)
{
uint16_t i;
//
// Initialize device clock and peripherals
//
Device_init();
//
// Disable pin locks and enable internal pullups.
//
Device_initGPIO();
//
// Initialize PIE and clear PIE registers. Disables CPU interrupts.
//
Interrupt_initModule();
//
// Initialize the PIE vector table with pointers to the shell Interrupt
// Service Routines (ISR).
//
Interrupt_initVectorTable();
//
// Board initialization
//
Board_init();
//
// For loopback mode only
//
I2C_setOwnSlaveAddress(myI2C0_BASE, SLAVE_ADDRESS);
//
// Interrupts that are used in this example are re-mapped to ISR functions
// found within this file.
//
Interrupt_register(INT_I2CA_FIFO, &i2cFIFOISR);
//
// Initialize the data buffers
//
for(i = 0; i < 2; i++)
{
sData[i] = i;
rData[i]= 0;
}
//
// Enable interrupts required for this example
//
Interrupt_enable(INT_I2CA_FIFO);
//
// Enable Global Interrupt (INTM) and realtime interrupt (DBGM)
//
EINT;
ERTM;
//
// Loop forever. Suspend or place breakpoints to observe the buffers.
//
while(1)
{
// A FIFO interrupt will be generated for each Tx and Rx based
// on the Interrupt levels configured.
// The ISR will handle pushing/pulling data to/from the TX and
// RX FIFOs resp.
}
}
//
// I2C A Transmit & Receive FIFO ISR.
//
__interrupt void i2cFIFOISR(void)
{
uint16_t i;
//
// If receive FIFO interrupt flag is set, read data
//
if((I2C_getInterruptStatus(myI2C0_BASE) & I2C_INT_RXFF) != 0)
{
for(i = 0; i < 2; i++)
{
rData[i] = I2C_getData(myI2C0_BASE);
}
//
// Check received data
//
for(i = 0; i < 2; i++)
{
if(rData[i] != ((rDataPoint + i) & 0xFF))
{
//
// Something went wrong. rData doesn't contain expected data.
//
ESTOP0;
}
}
rDataPoint = (rDataPoint + 1) & 0xFF;
//
// Clear interrupt flag
//
I2C_clearInterruptStatus(myI2C0_BASE, I2C_INT_RXFF);
}
//
// If transmit FIFO interrupt flag is set, put data in the buffer
//
else if((I2C_getInterruptStatus(myI2C0_BASE) & I2C_INT_TXFF) != 0)
{
for(i = 0; i < 2; i++)
{
I2C_putData(myI2C0_BASE, sData[i]);
}
//
// Send the start condition
//
I2C_sendStartCondition(myI2C0_BASE);
//
// Increment data for next cycle
//
for(i = 0; i < 2; i++)
{
sData[i] = (sData[i] + 1) & 0xFF;
}
//
// Clear interrupt flag
//
I2C_clearInterruptStatus(myI2C0_BASE, I2C_INT_TXFF);
}
//
// Issue ACK
//
Interrupt_clearACKGroup(INTERRUPT_ACK_GROUP8);
}
//
// End of File
//
| 25.892 | 79 | 0.589217 | [
"vector"
] |
1245fb02c670170613ffa1435a1fbbc61b6db87d | 9,625 | h | C | Source/Framework/Core/Physics/TePhysics.h | GameDevery/TweedeFrameworkRedux | 69a28fe171db33d00066b97b9b6bf89f6ef3e3a4 | [
"MIT"
] | 14 | 2022-02-25T15:52:35.000Z | 2022-03-30T18:44:29.000Z | Source/Framework/Core/Physics/TePhysics.h | GameDevery/TweedeFrameworkRedux | 69a28fe171db33d00066b97b9b6bf89f6ef3e3a4 | [
"MIT"
] | null | null | null | Source/Framework/Core/Physics/TePhysics.h | GameDevery/TweedeFrameworkRedux | 69a28fe171db33d00066b97b9b6bf89f6ef3e3a4 | [
"MIT"
] | 1 | 2022-02-28T09:24:05.000Z | 2022-02-28T09:24:05.000Z | #pragma once
#include "TeCorePrerequisites.h"
#include "Physics/TePhysicsCommon.h"
#include "Utility/TeModule.h"
#include "Math/TeVector3.h"
#include <cfloat>
namespace te
{
/** Contains parameters used for initializing the physics system. */
struct PHYSICS_INIT_DESC
{
Vector3 Gravity = Vector3(0.0f, -9.81f, 0.0f); /**< Initial gravity. */
float AirDensity = 1.2f;
float WaterDensity = 1.5f;
float WaterOffset = 0.0f;
Vector3 WaterNormal = Vector3(0.0f, 1.0f, 0.0f);
bool SoftBody = true;
};
/** Provides global physics settings, factory methods for physics objects and scene queries. */
class TE_CORE_EXPORT Physics : public Module<Physics>
{
public:
Physics(const PHYSICS_INIT_DESC& init);
virtual ~Physics() = default;
TE_MODULE_STATIC_HEADER_MEMBER(Physics)
/** @copydoc PhysicsMesh::Create */
virtual SPtr<PhysicsMesh> CreateMesh(const SPtr<MeshData>& meshData) = 0;
/** @copydoc PhysicsHeightField::Create */
virtual SPtr<PhysicsHeightField> CreateHeightField(const SPtr<Texture>& texture) = 0;
/** Creates an object representing the physics scene. Must be manually released via destroyPhysicsScene(). */
virtual SPtr<PhysicsScene> CreatePhysicsScene() = 0;
/** Performs any physics operations. Should be called once per frame. */
virtual void Update() { }
/** Determines if audio reproduction is paused globally. */
virtual void SetPaused(bool paused) = 0;
/** @copydoc SetPaused */
virtual bool IsPaused() const = 0;
/** Enable or disable debug information globally */
virtual void SetDebug(bool debug) = 0;
/** @copydoc SetDebug */
virtual bool IsDebug() = 0;
/** Allow user to see debug information about physical simulation */
virtual void DrawDebug(const SPtr<Camera>& camera, const SPtr<RenderTarget>& renderTarget) = 0;
/** Determines gravity to apply to the scene */
virtual void SetGravity(const Vector3& gravity) = 0;
/** Determines air density to apply to the scene */
virtual void SetAirDensity(const float& airDensity) = 0;
/** Determines water density to apply to the scene */
virtual void SetWaterDensity(const float& waterDensity) = 0;
/** Determines water normal to apply to the scene */
virtual void SetWaterNormal(const Vector3& waterDensity) = 0;
/** Determines water offset to apply to the scene */
virtual void SetWaterOffset(const float& waterOffset) = 0;
/** Checks is the physics simulation update currently in progress. */
bool IsUpdateInProgress() const { return _updateInProgress; }
/** Returns configuration of the physic engine */
const PHYSICS_INIT_DESC& GetDesc() const { return _initDesc; }
protected:
bool _updateInProgress = false;
PHYSICS_INIT_DESC _initDesc;
};
/**
* Physical representation of a scene, allowing creation of new physical objects in the scene and queries against
* those objects. Objects created in different scenes cannot physically interact with eachother.
*/
class TE_CORE_EXPORT PhysicsScene
{
public:
/** Manage collision detection inside a scene */
virtual void TriggerCollisions() = 0;
/** Report collisions inside a scene */
virtual void ReportCollisions() = 0;
/** @copydoc RigidBody::Create */
virtual SPtr<RigidBody> CreateRigidBody(const HSceneObject& linkedSO) = 0;
/** @copydoc MeshSoftBody::Create */
virtual SPtr<MeshSoftBody> CreateMeshSoftBody(const HSceneObject& linkedSO) = 0;
/** @copydoc EllipsoidSoftBody::Create */
virtual SPtr<EllipsoidSoftBody> CreateEllipsoidSoftBody(const HSceneObject& linkedSO) = 0;
/** @copydoc RopeSoftBody::Create */
virtual SPtr<RopeSoftBody> CreateRopeSoftBody(const HSceneObject& linkedSO) = 0;
/** @copydoc PatchSoftBody::Create */
virtual SPtr<PatchSoftBody> CreatePatchSoftBody(const HSceneObject& linkedSO) = 0;
/** Creates a new cone twist joint. */
virtual SPtr<ConeTwistJoint> CreateConeTwistJoint() = 0;
/** Creates a new hinge joint. */
virtual SPtr<HingeJoint> CreateHingeJoint() = 0;
/** Creates a new spherical joint. */
virtual SPtr<SphericalJoint> CreateSphericalJoint() = 0;
/** Creates a new spherical joint. */
virtual SPtr<SliderJoint> CreateSliderJoint() = 0;
/** Creates a new D6 joint. */
virtual SPtr<D6Joint> CreateD6Joint() = 0;
/**
* Creates a new box collider.
*
* @param[in] extents Extents (half size) of the box.
* @param[in] position Position of the collider relative to its parent
* @param[in] rotation Position of the collider relative to its parent
*/
virtual SPtr<BoxCollider> CreateBoxCollider(const Vector3& extents, const Vector3& position,
const Quaternion& rotation) = 0;
/**
* Creates a new plane collider.
*
* @param[in] normal Normal to the plane.
* @param[in] position Position of the collider relative to its parent
* @param[in] rotation Position of the collider relative to its parent
*/
virtual SPtr<PlaneCollider> CreatePlaneCollider(const Vector3& normal, const Vector3& position,
const Quaternion& rotation) = 0;
/**
* Creates a new sphere collider.
*
* @param[in] radius Radius of the sphere geometry.
* @param[in] position Position of the collider.
* @param[in] rotation Rotation of the collider.
*/
virtual SPtr<SphereCollider> CreateSphereCollider(float radius, const Vector3& position,
const Quaternion& rotation) = 0;
/**
* Creates a new cylinder collider.
*
* @param[in] extents Extents (half size) of the cylinder.
* @param[in] position Position of the collider relative to its parent
* @param[in] rotation Position of the collider relative to its parent
*/
virtual SPtr<CylinderCollider> CreateCylinderCollider(const Vector3& extents, const Vector3& position,
const Quaternion& rotation) = 0;
/**
* Creates a new capsule collider.
*
* @param[in] radius Radius of the capsule
* @param[in] height Height of the capsule
* @param[in] position Position of the collider relative to its parent
* @param[in] rotation Position of the collider relative to its parent
*/
virtual SPtr<CapsuleCollider> CreateCapsuleCollider(float radius, float height, const Vector3& position,
const Quaternion& rotation) = 0;
/**
* Creates a new mesh collider.
*
* @param[in] position Position of the collider relative to its parent
* @param[in] rotation Position of the collider relative to its parent
*/
virtual SPtr<MeshCollider> CreateMeshCollider(const Vector3& position, const Quaternion& rotation) = 0;
/**
* Creates a new cone collider.
*
* @param[in] radius Radius of the cone
* @param[in] height Height of the cone
* @param[in] position Position of the collider relative to its parent
* @param[in] rotation Position of the collider relative to its parent
*/
virtual SPtr<ConeCollider> CreateConeCollider(float radius, float height, const Vector3& position,
const Quaternion& rotation) = 0;
/**
* Creates a new height map collider.
*
* @param[in] position Position of the collider relative to its parent
* @param[in] rotation Position of the collider relative to its parent
*/
virtual SPtr<HeightFieldCollider> CreateHeightFieldCollider(const Vector3& position, const Quaternion& rotation) = 0;
/**
* Checks does the ray hit the provided collider.
*
* @param[in] origin Origin of the ray to check.
* @param[in] unitDir Unit direction of the ray to check.
* @param[out] hit Information about the hit. Valid only if the method returns true.
* @param[in] maxDist Maximum distance from the ray origin to search for hits.
* @return True if the ray has hit the collider.
*/
virtual bool RayCast(const Vector3& origin, const Vector3& unitDir, PhysicsQueryHit& hit,
float maxDist = FLT_MAX) const = 0;
/**
* Checks does the ray hit the provided collider.
*
* @param[in] origin Origin of the ray to check.
* @param[in] unitDir Unit direction of the ray to check.
* @param[out] hits Information about all the hits. Valid only if the method returns true.
* @param[in] maxDist Maximum distance from the ray origin to search for hits.
* @return True if the ray has hit the collider.
*/
virtual bool RayCast(const Vector3& origin, const Vector3& unitDir, Vector<PhysicsQueryHit>& hits,
float maxDist = FLT_MAX) const = 0;
protected:
PhysicsScene() = default;
virtual ~PhysicsScene() = default;
protected:
PhysicsDebug* _debug = nullptr;
};
/** Provides easier access to Physics. */
TE_CORE_EXPORT Physics& gPhysics();
}
| 39.609053 | 125 | 0.635844 | [
"mesh",
"geometry",
"object",
"vector"
] |
124c019d1556e1519c914c1be933666a4eec760a | 1,071 | h | C | src/lib/formats/os9_dsk.h | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/lib/formats/os9_dsk.h | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/lib/formats/os9_dsk.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:tim lindner, 68bit
/*********************************************************************
formats/os9_dsk.h
OS-9 disk images
*********************************************************************/
#ifndef MAME_FORMATS_OS9_DSK_H
#define MAME_FORMATS_OS9_DSK_H
#pragma once
#include "wd177x_dsk.h"
class os9_format : public wd177x_format {
public:
os9_format();
virtual const char *name() const override;
virtual const char *description() const override;
virtual const char *extensions() const override;
virtual int identify(util::random_read &io, uint32_t form_factor, const std::vector<uint32_t> &variants) override;
virtual int find_size(util::random_read &io, uint32_t form_factor, const std::vector<uint32_t> &variants) override;
virtual const wd177x_format::format &get_track_format(const format &f, int head, int track) override;
private:
static const format formats[];
static const format formats_track0[];
};
extern const floppy_format_type FLOPPY_OS9_FORMAT;
#endif // MAME_FORMATS_OS9_DSK_H
| 29.75 | 116 | 0.676004 | [
"vector"
] |
124e5418da2182bb5bbc052d186c44d91be3d086 | 1,787 | h | C | System/Library/PrivateFrameworks/CoreSuggestionsInternals.framework/SGNameMappingTransformer.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 2 | 2021-11-02T09:23:27.000Z | 2022-03-28T08:21:57.000Z | System/Library/PrivateFrameworks/CoreSuggestionsInternals.framework/SGNameMappingTransformer.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/CoreSuggestionsInternals.framework/SGNameMappingTransformer.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 1 | 2022-03-28T08:21:59.000Z | 2022-03-28T08:21:59.000Z | /*
* This header is generated by classdump-dyld 1.5
* on Wednesday, October 27, 2021 at 3:16:38 PM Mountain Standard Time
* Operating System: Version 13.5.1 (Build 17F80)
* Image Source: /System/Library/PrivateFrameworks/CoreSuggestionsInternals.framework/CoreSuggestionsInternals
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
#import <libobjc.A.dylib/PMLTransformerProtocol.h>
@class NSDictionary, NSString;
@interface SGNameMappingTransformer : NSObject <PMLTransformerProtocol> {
NSDictionary* _nameMappings;
NSString* _tokenToIgnore;
int _minimumConfidence;
/*^block*/id _confidenceMapper;
}
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
@property (copy,readonly) NSString * description;
@property (copy,readonly) NSString * debugDescription;
+(id)withFullNameMapping:(id)arg1 firstNameMapping:(id)arg2 lastNameMapping:(id)arg3 andPossessive:(id)arg4 ;
+(id)withFullNameMapping:(id)arg1 firstNameMapping:(id)arg2 lastNameMapping:(id)arg3 minimumConfidence:(int)arg4 confidenceMapper:(/*^block*/id)arg5 tokenToIgnore:(id)arg6 andPossessive:(id)arg7 ;
-(BOOL)isEqual:(id)arg1 ;
-(unsigned long long)hash;
-(id)transform:(id)arg1 ;
-(id)toPlistWithChunks:(id)arg1 ;
-(id)initWithPlist:(id)arg1 chunks:(id)arg2 context:(id)arg3 ;
-(id)initWithNameMappings:(id)arg1 minimumConfidence:(int)arg2 confidenceMapper:(/*^block*/id)arg3 tokenToIgnore:(id)arg4 ;
-(id)nameMappingForToken:(id)arg1 withConfidence:(int*)arg2 ;
-(id)detectNames:(id)arg1 ;
-(BOOL)isPossessive:(id)arg1 ;
-(BOOL)isEqualToNameMappingTransformer:(id)arg1 ;
@end
| 44.675 | 196 | 0.719642 | [
"transform"
] |
124e5a75766185d91bab1de7c160d7cc60df1f62 | 1,605 | c | C | src/hss_rel14/hsssec/src/aucpp.c | ywang06/openair-cn | d1d0e45ec749fc49f749c65744084ee09ab1f3e5 | [
"Apache-2.0"
] | 46 | 2019-02-18T02:21:27.000Z | 2022-03-01T15:39:43.000Z | src/hss_rel14/hsssec/src/aucpp.c | ywang06/openair-cn | d1d0e45ec749fc49f749c65744084ee09ab1f3e5 | [
"Apache-2.0"
] | 63 | 2019-02-25T18:14:41.000Z | 2022-02-24T17:54:05.000Z | src/hss_rel14/hsssec/src/aucpp.c | ywang06/openair-cn | d1d0e45ec749fc49f749c65744084ee09ab1f3e5 | [
"Apache-2.0"
] | 36 | 2019-02-19T06:35:07.000Z | 2022-03-17T21:41:44.000Z | /*
* Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenAirInterface Software Alliance licenses this file to You under
* the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*-------------------------------------------------------------------------------
* For more information about the OpenAirInterface (OAI) Software Alliance:
* contact@openairinterface.org
*/
#include "aucpp.h"
#include "auc.h"
uint8_t *
sqn_ms_derive_cpp (
const uint8_t opc[16],
uint8_t * key,
uint8_t * auts,
uint8_t * rand_p)
{
return sqn_ms_derive(opc, key, auts, rand_p);
}
void
generate_random_cpp (
uint8_t * random_p,
ssize_t length)
{
generate_random(random_p, length);
}
int generate_vector_cpp(const uint8_t opc[16], uint64_t imsi, uint8_t key[16], uint8_t plmn[3],
uint8_t sqn[6], auc_vector_t *vector){
return generate_vector(opc, imsi, key, plmn, sqn, vector);
}
| 34.148936 | 95 | 0.680997 | [
"vector"
] |
125bb7785f696bab4948983cb8f0f8b5416ae24c | 6,279 | h | C | OgreMain/include/Vao/OgreVertexBufferPacked.h | Stazer/ogre-next | 4d3aa2aedf4575ac8a9e32a4e2af859562752d51 | [
"MIT"
] | 11 | 2017-01-17T15:02:25.000Z | 2020-11-27T16:54:42.000Z | OgreMain/include/Vao/OgreVertexBufferPacked.h | Stazer/ogre-next | 4d3aa2aedf4575ac8a9e32a4e2af859562752d51 | [
"MIT"
] | 9 | 2016-10-23T20:15:38.000Z | 2018-02-06T11:23:17.000Z | OgreMain/include/Vao/OgreVertexBufferPacked.h | Stazer/ogre-next | 4d3aa2aedf4575ac8a9e32a4e2af859562752d51 | [
"MIT"
] | 3 | 2020-10-15T15:11:41.000Z | 2021-04-04T03:38:54.000Z | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#ifndef _Ogre_VertexBufferPacked_H_
#define _Ogre_VertexBufferPacked_H_
#include "Vao/OgreBufferPacked.h"
#include "Vao/OgreVertexElements.h"
namespace Ogre
{
struct VertexElement2
{
/// The type of element
VertexElementType mType;
/// The meaning of the element
VertexElementSemantic mSemantic;
/// The number of instances to draw using the same per-instance data before
/// advancing in the buffer by one element. This value must be 0 for an
/// element that contains per-vertex data
uint32 mInstancingStepRate;
VertexElement2( VertexElementType type, VertexElementSemantic semantic ) :
mType( type ), mSemantic( semantic ), mInstancingStepRate( 0 ) {}
bool operator == ( const VertexElement2 _r ) const
{
return mType == _r.mType && mSemantic == _r.mSemantic &&
mInstancingStepRate == _r.mInstancingStepRate;
}
bool operator == ( VertexElementSemantic semantic ) const
{
return mSemantic == semantic;
}
/// Warning: Beware a VertexElement2Vec shouldn't be sorted.
/// The order in which they're pushed into the vector defines the offsets
/// in the vertex buffer. Altering the order would cause the GPU to
/// to read garbage when trying to interpret the vertex buffer
/// This operator exists because it's useful when implementing
/// a '<' operator in other structs that contain VertexElement2Vecs
/// (see HlmsPso)
bool operator < ( const VertexElement2 &_r ) const
{
if( this->mType < _r.mType ) return true;
if( this->mType > _r.mType ) return false;
if( this->mSemantic < _r.mSemantic ) return true;
if( this->mSemantic > _r.mSemantic ) return false;
return this->mInstancingStepRate < _r.mInstancingStepRate;
}
};
typedef vector<VertexElement2>::type VertexElement2Vec;
typedef vector<VertexElement2Vec>::type VertexElement2VecVec;
class _OgreExport VertexBufferPacked : public BufferPacked
{
protected:
VertexElement2Vec mVertexElements;
/// Multisource VertexArrayObjects is when VertexArrayObject::mVertexBuffers.size() is greater
/// than 1 (i.e. have position in one vertex buffer, UVs in another.)
/// A VertexBuffer created for multisource can be used/bound for rendering with just one buffer
/// source (i.e. just bind the position buffer during the shadow map pass) or bound together
/// with buffers that have the same mMultiSourceId and mMultiSourcePool.
/// But a VertexBuffer not created for multisource cannot be bound together with other buffers.
///
/// Before you're tempted into creating all your Vertex Buffers as multisource indiscriminately,
/// the main issue is that multisource vertex buffers can heavily fragment GPU memory managed
/// by the VaoManager (unless you know in advance the full number of vertices you need per
/// vertex declaration and reserve this size) or waste a lot of GPU RAM, and/or increase
/// the draw call count.
size_t mMultiSourceId;
MultiSourceVertexBufferPool *mMultiSourcePool;
uint8 mSourceIdx;
public:
VertexBufferPacked( size_t internalBufferStartBytes, size_t numElements, uint32 bytesPerElement,
uint32 numElementsPadding, BufferType bufferType,
void *initialData, bool keepAsShadow,
VaoManager *vaoManager, BufferInterface *bufferInterface,
const VertexElement2Vec &vertexElements, size_t multiSourceId,
MultiSourceVertexBufferPool *multiSourcePool, uint8 sourceIdx );
~VertexBufferPacked();
virtual BufferPackedTypes getBufferPackedType(void) const { return BP_TYPE_VERTEX; }
const VertexElement2Vec& getVertexElements(void) const { return mVertexElements; }
size_t getMultiSourceId(void) { return mMultiSourceId; }
/// Return value may be null
MultiSourceVertexBufferPool* getMultiSourcePool(void) { return mMultiSourcePool; }
/// Source index reference assigned by the MultiSourceVertexBufferPool.
/// This value does not restrict the fact that you can actually assign this buffer to
/// another index (as long as it's with another buffer with the same multisource ID
/// and pool). This value is for internal use.
/// Always 0 for non-multisource vertex buffers.
uint8 _getSourceIndex(void) const { return mSourceIdx; }
};
typedef vector<VertexBufferPacked*>::type VertexBufferPackedVec;
}
#endif
| 46.169118 | 104 | 0.666667 | [
"object",
"vector"
] |
126415ca1683b2f10aedb7caf0a1c099e4a8a780 | 4,661 | h | C | src/sysmonx/matchingengine.h | ansnapx/sysmonx | b9adf0d85474489bc5196a71b71859894003b756 | [
"MIT"
] | 161 | 2019-08-07T23:47:18.000Z | 2022-03-19T07:43:08.000Z | src/sysmonx/matchingengine.h | yangliying666/sysmonx | b9adf0d85474489bc5196a71b71859894003b756 | [
"MIT"
] | 3 | 2019-08-08T17:44:20.000Z | 2020-06-17T02:09:42.000Z | src/sysmonx/matchingengine.h | yangliying666/sysmonx | b9adf0d85474489bc5196a71b71859894003b756 | [
"MIT"
] | 40 | 2019-08-08T02:46:49.000Z | 2022-01-07T04:38:34.000Z | #pragma once
#include "common.h"
#include "matchers\filter_property_processor.h"
#include "matchers\match_event_base.h"
#include "matchers\match_event_sysmon_create_process.h"
using boost::asio::dispatch;
using boost::asio::spawn;
using boost::asio::strand;
using boost::asio::thread_pool;
using boost::asio::yield_context;
namespace MatchHelpers
{
SysmonXTypes::EventID GetEventIDBasedOnName(const SysmonXTypes::EventIDName& eventName);
SysmonXTypes::EventPropertyID GetEventPropertyIDBasedOnName(const SysmonXTypes::EventPropertyName& propertyName);
SysmonXTypes::EventFilterOperation GetEventFilterOperationBasedOnName(const SysmonXTypes::EventConditionFilterName& conditionName);
const SysmonXTypes::MATCHING_TYPE_STRING& GetMatchingDataFromEvent(const SysmonXTypes::EventObject& eventData, const SysmonXTypes::EventPropertyID& eventID);
}
class MatchingEngine
{
public:
static MatchingEngine& Instance()
{
static MatchingEngine instance;
return instance;
}
bool IsInitialized() { return m_isInitialized; };
bool Initialize();
// Entry points for events arriving to the matching engine.
// Code return inmediately after enqueuing security events to be handled by the thread pool
// Design decision: data is not const to allow logic to add attributes while event is processed through the pipeline
void DispatchEvent(SysmonXTypes::EventObject &data)
{
//Quick and dirty evaluation
if (m_isInitialized && m_shouldProcessEvents)
{
spawn(m_pool, boost::bind(&MatchingEngine::ProcessNewEvents, this, data));
}
}
//Matching engine lifecycle
bool DisableEventsProcessing()
{
boost::lock_guard<boost::mutex> lk(m_mutex);
bool ret = false;
if (m_isInitialized)
{
m_shouldProcessEvents = false;
ret = true;
}
return ret;
}
bool EnableEventsProcessing()
{
boost::lock_guard<boost::mutex> lk(m_mutex);
bool ret = false;
if (m_isInitialized)
{
m_shouldProcessEvents = true;
ret = true;
}
return ret;
}
bool AddNewEventFilterCondition(
const SysmonXTypes::EventID &eventID,
const EventPropertyName &propertyName,
const EventFilterEvalGroup &evalGroup,
const EventFilterOperation &operation,
const MATCHING_TYPE_STRING &data);
void ClearEventFilters();
private:
//Object lifecycle
MatchingEngine(const size_t nrThreads = SysmonXDefs::SYSMONX_DEFAULT_WORKER_THREADS):
m_pool(nrThreads), m_dispatchStrand(m_pool.get_executor()) {}
//Object lifecycle
virtual ~MatchingEngine()
{
m_shouldProcessEvents = false;
if (IsInitialized())
{
m_pool.join();
}
}
//Adding New Matcher
template <typename T>
bool AddNewMatcher(const SysmonXTypes::EventID &eventID, std::shared_ptr<T>& matcherPtr)
{
bool ret = false;
if (matcherPtr)
{
//Checking if element is not there
if (m_matchers.find(eventID) == m_matchers.end())
{
m_matchers.insert(std::make_pair(eventID, matcherPtr));
ret = true;
}
}
return ret;
}
//Event Pre processor - Basic filtering happens here
//Supported filters here will run on a concurrent context
bool EventPreProcessor(SysmonXTypes::EventObject &data);
//Event Post processor - Advanced filtering happens here
//Supported filter here will be called in a serialized fashion
bool EventPostProcessor(SysmonXTypes::EventObject &data);
//Event Report Handler
void SendNewReport(SysmonXTypes::EventObject &data);
//Serialized completion handler wrapper
//Report on succesful PostProcessor Filtering
void SerializedEventsHandler(SysmonXTypes::EventObject &data)
{
//Advanced serialized filtering happens here
if (EventPostProcessor(data))
{
//If events pass the pre and post processor filters, it should be schedule to be reported
SendNewReport(data);
}
}
//Handler of new Security Events
void ProcessNewEvents(SysmonXTypes::EventObject &data)
{
//Basic concurrent filtering happens here
if (EventPreProcessor(data))
{
dispatch(m_dispatchStrand, boost::bind(&MatchingEngine::SerializedEventsHandler, this, data));
}
}
//Forcing singleton here
MatchingEngine(const MatchingEngine&) = delete;
MatchingEngine(MatchingEngine&&) = delete;
MatchingEngine& operator=(const MatchingEngine&) = delete;
MatchingEngine& operator=(MatchingEngine&&) = delete;
// Private vars
bool m_isInitialized = false;
bool m_shouldProcessEvents = false;
thread_pool m_pool;
strand<thread_pool::executor_type> m_dispatchStrand;
ReportManager& m_reportManager = ReportManager::Instance();
TraceHelpers::Logger& m_logger = TraceHelpers::Logger::Instance();
ConfigManager& m_config = ConfigManager::Instance();
boost::mutex m_mutex;
MatchEventContainer m_matchers;
}; | 27.098837 | 158 | 0.762926 | [
"object"
] |
12721472622b774c26c5dedd25bc494d44a3852f | 1,243 | h | C | RMExtensionsFramework/NSArray+RMExtension.h | Red-Mak/AllMojis | 287dd447964be0f8c2a0f1e9060e632154e2af21 | [
"MIT"
] | 6 | 2017-08-02T09:28:45.000Z | 2020-11-07T19:22:49.000Z | RMExtensionsFramework/NSArray+RMExtension.h | Red-Mak/AllMojis | 287dd447964be0f8c2a0f1e9060e632154e2af21 | [
"MIT"
] | null | null | null | RMExtensionsFramework/NSArray+RMExtension.h | Red-Mak/AllMojis | 287dd447964be0f8c2a0f1e9060e632154e2af21 | [
"MIT"
] | null | null | null | //
// NSMutableArray+RMExtension.h
// RMExtensionKeyboard
//
// Created by Radhouani Malek on 06/05/2016.
// Copyright © 2016 RedMak. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSMutableArray (RMExtension)
/**
* insert object at the index passed, FIFO used
*
*/
- (void) insertObject:(id)object atIndex:(NSUInteger)index maxObjectsInArray:(NSUInteger)maximumLength;
@end
@interface NSArray (RMExtension)
/*!
Safe subarrayWithRange that checks range.
If the length is out of bounds will return all elements from location to the end.
If the location is out of bounds will return nil.
@param range Range
@result Sub-array
*/
- (NSArray *)subarrayUsingRange:(NSRange)range;
/**
* number of subarray with passed length
*
* @param subArrayLength <#subArrayLength description#>
*
* @return <#return value description#>
*/
- (NSUInteger) numberOfSubArrayWithLength:(NSInteger)subArrayLength;
/**
* array of array(s) where each array.count <= subArrayLength, start from index == 0
*
* @param subArrayLength <#subArrayLength description#>
*
* @return <#return value description#>
*
* @note return a copy of 'self'
*/
- (NSArray*) subArraysWithLength:(NSUInteger)subArrayLength;
@end
| 23.45283 | 103 | 0.726468 | [
"object"
] |
127296de708381f2dcf069bd4ec8af37bf81cd7b | 8,669 | c | C | ThirdParty/raft/canonical/src/progress.c | Pahandrovich/omniscidb | 312809f85c2d9e0027bd2e91c20a7d4c6bc2714a | [
"Apache-2.0"
] | 868 | 2019-05-14T22:11:17.000Z | 2022-02-28T09:15:23.000Z | ThirdParty/raft/canonical/src/progress.c | Pahandrovich/omniscidb | 312809f85c2d9e0027bd2e91c20a7d4c6bc2714a | [
"Apache-2.0"
] | 327 | 2019-05-16T18:07:57.000Z | 2022-02-26T09:34:04.000Z | ThirdParty/raft/canonical/src/progress.c | Pahandrovich/omniscidb | 312809f85c2d9e0027bd2e91c20a7d4c6bc2714a | [
"Apache-2.0"
] | 166 | 2019-05-22T11:17:10.000Z | 2022-02-26T06:58:45.000Z | #include "progress.h"
#include "assert.h"
#include "configuration.h"
#include "log.h"
#include "tracing.h"
/* Set to 1 to enable tracing. */
#if 1
#define tracef(...) Tracef(r->tracer, __VA_ARGS__)
#else
#define tracef(...)
#endif
#ifndef max
#define max(a, b) ((a) < (b) ? (b) : (a))
#endif
#ifndef min
#define min(a, b) ((a) < (b) ? (a) : (b))
#endif
/* Initialize a single progress object. */
static void initProgress(struct raft_progress *p, raft_index last_index)
{
p->next_index = last_index + 1;
p->match_index = 0;
p->snapshot_index = 0;
p->last_send = 0;
p->recent_recv = false;
p->state = PROGRESS__PROBE;
}
int progressBuildArray(struct raft *r)
{
struct raft_progress *progress;
unsigned i;
raft_index last_index = logLastIndex(&r->log);
progress = raft_malloc(r->configuration.n * sizeof *progress);
if (progress == NULL) {
return RAFT_NOMEM;
}
for (i = 0; i < r->configuration.n; i++) {
initProgress(&progress[i], last_index);
if (r->configuration.servers[i].id == r->id) {
progress[i].match_index = r->last_stored;
}
}
r->leader_state.progress = progress;
return 0;
}
int progressRebuildArray(struct raft *r,
const struct raft_configuration *configuration)
{
raft_index last_index = logLastIndex(&r->log);
struct raft_progress *progress;
unsigned i;
unsigned j;
raft_id id;
progress = raft_malloc(configuration->n * sizeof *progress);
if (progress == NULL) {
return RAFT_NOMEM;
}
/* First copy the progress information for the servers that exists both in
* the current and in the new configuration. */
for (i = 0; i < r->configuration.n; i++) {
id = r->configuration.servers[i].id;
j = configurationIndexOf(configuration, id);
if (j == configuration->n) {
/* This server is not present in the new configuration, so we just
* skip it. */
continue;
}
progress[j] = r->leader_state.progress[i];
}
/* Then reset the replication state for servers that are present in the new
* configuration, but not in the current one. */
for (i = 0; i < configuration->n; i++) {
id = configuration->servers[i].id;
j = configurationIndexOf(&r->configuration, id);
if (j < r->configuration.n) {
/* This server is present both in the new and in the current
* configuration, so we have already copied its next/match index
* value in the loop above. */
continue;
}
assert(j == r->configuration.n);
initProgress(&progress[i], last_index);
}
raft_free(r->leader_state.progress);
r->leader_state.progress = progress;
return 0;
}
bool progressIsUpToDate(struct raft *r, unsigned i)
{
struct raft_progress *p = &r->leader_state.progress[i];
raft_index last_index = logLastIndex(&r->log);
return p->next_index == last_index + 1;
}
bool progressShouldReplicate(struct raft *r, unsigned i)
{
struct raft_progress *p = &r->leader_state.progress[i];
raft_time now = r->io->time(r->io);
bool needs_heartbeat = now - p->last_send >= r->heartbeat_timeout;
raft_index last_index = logLastIndex(&r->log);
bool result = false;
/* We must be in a valid state. */
assert(p->state == PROGRESS__PROBE || p->state == PROGRESS__PIPELINE ||
p->state == PROGRESS__SNAPSHOT);
/* The next index to send must be lower than the highest index in our
* log. */
assert(p->next_index <= last_index + 1);
switch (p->state) {
case PROGRESS__SNAPSHOT:
/* Raft will retry sending a Snapshot if the timeout has elapsed. */
result = now - p->last_send >= r->install_snapshot_timeout;
break;
case PROGRESS__PROBE:
/* We send at most one message per heartbeat interval. */
result = needs_heartbeat;
break;
case PROGRESS__PIPELINE:
/* In replication mode we send empty append entries messages only if
* haven't sent anything in the last heartbeat interval. */
result = !progressIsUpToDate(r, i) || needs_heartbeat;
break;
}
return result;
}
raft_index progressNextIndex(struct raft *r, unsigned i)
{
return r->leader_state.progress[i].next_index;
}
raft_index progressMatchIndex(struct raft *r, unsigned i)
{
return r->leader_state.progress[i].match_index;
}
void progressUpdateLastSend(struct raft *r, unsigned i)
{
r->leader_state.progress[i].last_send = r->io->time(r->io);
}
bool progressResetRecentRecv(struct raft *r, const unsigned i)
{
bool prev = r->leader_state.progress[i].recent_recv;
r->leader_state.progress[i].recent_recv = false;
return prev;
}
void progressMarkRecentRecv(struct raft *r, const unsigned i)
{
r->leader_state.progress[i].recent_recv = true;
}
void progressToSnapshot(struct raft *r, unsigned i)
{
struct raft_progress *p = &r->leader_state.progress[i];
p->state = PROGRESS__SNAPSHOT;
p->snapshot_index = logSnapshotIndex(&r->log);
}
void progressAbortSnapshot(struct raft *r, const unsigned i)
{
struct raft_progress *p = &r->leader_state.progress[i];
p->snapshot_index = 0;
p->state = PROGRESS__PROBE;
}
int progressState(struct raft *r, const unsigned i)
{
struct raft_progress *p = &r->leader_state.progress[i];
return p->state;
}
bool progressMaybeDecrement(struct raft *r,
const unsigned i,
raft_index rejected,
raft_index last_index)
{
struct raft_progress *p = &r->leader_state.progress[i];
assert(p->state == PROGRESS__PROBE || p->state == PROGRESS__PIPELINE ||
p->state == PROGRESS__SNAPSHOT);
if (p->state == PROGRESS__SNAPSHOT) {
/* The rejection must be stale or spurious if the rejected index does
* not match the last snapshot index. */
if (rejected != p->snapshot_index) {
return false;
}
progressAbortSnapshot(r, i);
return true;
}
if (p->state == PROGRESS__PIPELINE) {
/* The rejection must be stale if the rejected index is smaller than
* the matched one. */
if (rejected <= p->match_index) {
tracef("match index is up to date -> ignore ");
return false;
}
/* Directly decrease next to match + 1 */
p->next_index = min(rejected, p->match_index + 1);
progressToProbe(r, i);
return true;
}
/* The rejection must be stale or spurious if the rejected index does not
* match the next index minus one. */
if (rejected != p->next_index - 1) {
tracef("rejected index %llu different from next index %lld -> ignore ",
rejected, p->next_index);
return false;
}
p->next_index = min(rejected, last_index + 1);
p->next_index = max(p->next_index, 1);
return true;
}
void progressOptimisticNextIndex(struct raft *r,
unsigned i,
raft_index next_index)
{
struct raft_progress *p = &r->leader_state.progress[i];
p->next_index = next_index;
}
bool progressMaybeUpdate(struct raft *r, unsigned i, raft_index last_index)
{
struct raft_progress *p = &r->leader_state.progress[i];
bool updated = false;
if (p->match_index < last_index) {
p->match_index = last_index;
updated = true;
}
if (p->next_index < last_index + 1) {
p->next_index = last_index + 1;
}
return updated;
}
void progressToProbe(struct raft *r, const unsigned i)
{
struct raft_progress *p = &r->leader_state.progress[i];
/* If the current state is snapshot, we know that the pending snapshot has
* been sent to this peer successfully, so we probe from snapshot_index +
* 1.*/
if (p->state == PROGRESS__SNAPSHOT) {
assert(p->snapshot_index > 0);
p->next_index = max(p->match_index + 1, p->snapshot_index);
p->snapshot_index = 0;
} else {
p->next_index = p->match_index + 1;
}
p->state = PROGRESS__PROBE;
}
void progressToPipeline(struct raft *r, const unsigned i)
{
struct raft_progress *p = &r->leader_state.progress[i];
p->state = PROGRESS__PIPELINE;
}
bool progressSnapshotDone(struct raft *r, const unsigned i)
{
struct raft_progress *p = &r->leader_state.progress[i];
assert(p->state == PROGRESS__SNAPSHOT);
return p->match_index >= p->snapshot_index;
}
#undef tracef
| 29.99654 | 80 | 0.623255 | [
"object"
] |
127bd81323022081a3ae97abbed3f60f82053c2c | 2,239 | h | C | inc/tp_maps/layers/BackgroundLayer.h | QtOpenGL/tp_maps-_OpenGL_engine | cc5fdc60c393cedf5572d9221a8c75ce0237f88c | [
"MIT"
] | null | null | null | inc/tp_maps/layers/BackgroundLayer.h | QtOpenGL/tp_maps-_OpenGL_engine | cc5fdc60c393cedf5572d9221a8c75ce0237f88c | [
"MIT"
] | null | null | null | inc/tp_maps/layers/BackgroundLayer.h | QtOpenGL/tp_maps-_OpenGL_engine | cc5fdc60c393cedf5572d9221a8c75ce0237f88c | [
"MIT"
] | 4 | 2018-08-30T10:01:30.000Z | 2020-10-07T10:55:11.000Z | #ifndef tp_maps_BackgroundLayer_h
#define tp_maps_BackgroundLayer_h
#include "tp_maps/Layer.h"
#include "tp_utils/RefCount.h"
namespace tp_maps
{
class TexturePool;
//##################################################################################################
class TP_MAPS_SHARED_EXPORT BackgroundLayer: public Layer
{
TP_REF_COUNT_OBJECTS("BackgroundLayer");
public:
//################################################################################################
BackgroundLayer(TexturePool* texturePool);
//################################################################################################
~BackgroundLayer() override;
//################################################################################################
enum class Mode
{
Spherical,
TransparentPattern
};
//################################################################################################
Mode mode() const;
//################################################################################################
void setMode(Mode mode);
//################################################################################################
const tp_utils::StringID& textureName() const;
//################################################################################################
void setTextureName(const tp_utils::StringID& textureName);
//################################################################################################
float rotationFactor() const;
//################################################################################################
//! A rotation value between 0 and 1.
void setRotationFactor(float rotationFactor);
//################################################################################################
float gridSpacing() const;
//################################################################################################
void setGridSpacing(float gridSpacing);
protected:
//################################################################################################
void render(RenderInfo& renderInfo) override;
private:
struct Private;
Private* d;
friend struct Private;
};
}
#endif
| 31.097222 | 100 | 0.30996 | [
"render"
] |
127e36fea3573093a05cf198a20a1e24a124234a | 1,989 | h | C | misc.h | isopleth/zetasdr | 03cb1c3e9283d15ab02babbc5a48ad5d0a19aba3 | [
"MIT"
] | 1 | 2021-01-14T15:59:53.000Z | 2021-01-14T15:59:53.000Z | misc.h | isopleth/zetasdr | 03cb1c3e9283d15ab02babbc5a48ad5d0a19aba3 | [
"MIT"
] | null | null | null | misc.h | isopleth/zetasdr | 03cb1c3e9283d15ab02babbc5a48ad5d0a19aba3 | [
"MIT"
] | null | null | null | /**
* Non-Spice simulation of ZetaSDR radio
* http://www.qrz.lt/ly1gp/SDR
*
* Various definitions
*
* Copyright 2019 Jason Leake
*
* 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 <list>
#include <memory>
#include <string>
#include <vector>
// So we can change the precision easily...
using floating = long double;
// 10 picoseconds time step size
constexpr auto TIME_STEP_SIZE = floating{1e-11};
// Extra cycles at the start to get output stable
constexpr auto EXTRA_CYCLES = 100;
// 1 nanosecond resolution in output files
constexpr auto OUTPUT_RESOLUTION = floating{1e-9};
//===================================================================
struct Circuit {
const floating resistance;
const floating capacitance;
const floating lpFreqHz;
Circuit(floating resistance,
floating capacitance,
floating lpFreqHz) : resistance{resistance},
capacitance{capacitance},
lpFreqHz{lpFreqHz} {
}
};
| 31.078125 | 70 | 0.722474 | [
"vector"
] |
128ee2991540448357e8e533de5c2314322205bc | 48,600 | h | C | src/RobotInfo.h | ShihaoWang/Multi-contact-Humanoid-Push-Recovery | 0f40f319d8aece9a172d9864643a4c82bb39b060 | [
"MIT"
] | null | null | null | src/RobotInfo.h | ShihaoWang/Multi-contact-Humanoid-Push-Recovery | 0f40f319d8aece9a172d9864643a4c82bb39b060 | [
"MIT"
] | null | null | null | src/RobotInfo.h | ShihaoWang/Multi-contact-Humanoid-Push-Recovery | 0f40f319d8aece9a172d9864643a4c82bb39b060 | [
"MIT"
] | null | null | null | #ifndef ROBOTINFO_H
#define ROBOTINFO_H
#include <KrisLibrary/robotics/RobotDynamics3D.h>
#include <KrisLibrary/robotics/NewtonEuler.h>
#include <Interface/SimulationGUI.h>
#include <unsupported/Eigen/CXX11/Tensor>
#include <KrisLibrary/meshing/TriMeshTopology.h>
#include <KrisLibrary/math3d/geometry3d.h>
#include "KrisLibrary/math3d/AABB3D.h"
#include "KrisLibrary/math3d/LocalCoordinates3D.h"
#include <KrisLibrary/geometry/CollisionMesh.h>
#include <KrisLibrary/geometry/PQP/src/PQP.h>
#include "Modeling/Paths.h"
#include <fstream>
#include "Spline.h"
struct LinkInfo {
LinkInfo(){LinkIndex = -1;}
LinkInfo(int LinkIndex_){ LinkIndex = LinkIndex_; }
void AddLocalConact(Vector3 local_contact){ LocalContacts.push_back(local_contact); }
void AvgContactUpdate(){
switch (LocalContacts.size()){
case 0: throw std::invalid_argument( "LocalContacts should have been initialized!" );
break;
default:{
Vector3 SumLocalContacts(0.0, 0.0, 0.0);
for (int i = 0; i < LocalContacts.size(); i++){
SumLocalContacts.x = SumLocalContacts.x + LocalContacts[i].x;
SumLocalContacts.y = SumLocalContacts.y + LocalContacts[i].y;
SumLocalContacts.z = SumLocalContacts.z + LocalContacts[i].z;
}
AvgLocalContact.x = SumLocalContacts.x/LocalContacts.size();
AvgLocalContact.y = SumLocalContacts.y/LocalContacts.size();
AvgLocalContact.z = SumLocalContacts.z/LocalContacts.size();
}
break;
}
}
int LinkIndex;
std::vector<Vector3> LocalContacts;
Vector3 AvgLocalContact;
};
struct SDFInfo{
SDFInfo(){
Envi_x_min = 0; Envi_x_max = 0;
Envi_y_min = 0; Envi_y_max = 0;
Envi_z_min = 0; Envi_z_max = 0;
Envi_x_unit = 0; Envi_y_unit = 0; Envi_z_unit = 0;
Envi_x_length = 0; Envi_y_length = 0; Envi_z_length = 0;
GridNo = 0;
}
SDFInfo(const Eigen::Tensor<double, 3>& _SDFTensor, const std::vector<double> &_SDFSpecs){
SDFTensor = _SDFTensor;
Envi_x_min = _SDFSpecs[0]; Envi_x_max = _SDFSpecs[1];
Envi_y_min = _SDFSpecs[2]; Envi_y_max = _SDFSpecs[3];
Envi_z_min = _SDFSpecs[4]; Envi_z_max = _SDFSpecs[5];
Envi_x_unit = _SDFSpecs[6]; Envi_y_unit = _SDFSpecs[7]; Envi_z_unit = _SDFSpecs[8];
Envi_x_length = _SDFSpecs[9]; Envi_y_length = _SDFSpecs[10]; Envi_z_length = _SDFSpecs[11];
GridNo = (int)_SDFSpecs[12];
}
double SignedDistance(const Vector3 &Point) const{
double x_FloatIndex = (Point.x - Envi_x_min)/Envi_x_unit * 1.0;
double y_FloatIndex = (Point.y - Envi_y_min)/Envi_y_unit * 1.0;
double z_FloatIndex = (Point.z - Envi_z_min)/Envi_z_unit * 1.0;
int x_leftindex = std::floor(x_FloatIndex);
int y_leftindex = std::floor(y_FloatIndex);
int z_leftindex = std::floor(z_FloatIndex);
if(x_leftindex<0){
x_leftindex = 0;
} else {
if(x_leftindex>GridNo-2) {
x_leftindex = GridNo-2;
}
}
if(y_leftindex<0) {
y_leftindex = 0;
} else {
if(y_leftindex>GridNo-2) {
y_leftindex = GridNo-2;
}
}
if(z_leftindex<0) {
z_leftindex = 0;
} else {
if(z_leftindex>GridNo-2) {
z_leftindex = GridNo-2;
}
}
int x_rightindex = x_leftindex + 1;
int y_rightindex = y_leftindex + 1;
int z_rightindex = z_leftindex + 1;
double valA = SDFTensor(x_leftindex, y_leftindex, z_leftindex);
double valB = SDFTensor(x_rightindex, y_leftindex, z_leftindex);
double valC = SDFTensor(x_rightindex, y_rightindex, z_leftindex);
double valD = SDFTensor(x_leftindex, y_rightindex, z_leftindex);
double valE = SDFTensor(x_leftindex, y_leftindex, z_rightindex);
double valF = SDFTensor(x_rightindex, y_leftindex, z_rightindex);
double valG = SDFTensor(x_rightindex, y_rightindex, z_rightindex);
double valH = SDFTensor(x_leftindex, y_rightindex, z_rightindex);
// Since this is a tri-linear interpolation, there are three ways to do the interpolation
// Type1:
// Along x-direction
double valMAB = (x_FloatIndex - x_leftindex*1.0) * (valB - valA) + valA;
double valMDC = (x_FloatIndex - x_leftindex*1.0) * (valC - valD) + valD;
double valMEF = (x_FloatIndex - x_leftindex*1.0) * (valF - valE) + valE;
double valMHG = (x_FloatIndex - x_leftindex*1.0) * (valG - valH) + valH;
// Along y-drection
double valMABDC = (y_FloatIndex - y_leftindex*1.0) * (valMDC - valMAB) + valMAB;
double valMEFGH = (y_FloatIndex - y_leftindex*1.0) * (valMHG - valMEF) + valMEF;
// Along z-direction
double valMABCDEFHG = (z_FloatIndex - z_leftindex*1.0) * (valMEFGH - valMABDC) + valMABDC;
// // Type2:
// // Along y-drection
// double valMAD = (y_FloatIndex - y_leftindex*1.0) * (valD - valA) + valA;
// double valMBC = (y_FloatIndex - y_leftindex*1.0) * (valC - valB) + valB;
// double valMEH = (y_FloatIndex - y_leftindex*1.0) * (valH - valE) + valE;
// double valMFG = (y_FloatIndex - y_leftindex*1.0) * (valG - valF) + valF;
//
// //Along x-direction
// double valMADBC = (x_FloatIndex - x_leftindex * 1.0) * (valMBC - valMAD) + valMAD;
// double valMEHFG = (x_FloatIndex - x_leftindex * 1.0) * (valMFG - valMEH) + valMEH;
//
// //Along z-direction
// double valMADBCEHFG = (z_FloatIndex - z_leftindex*1.0) * (valMEHFG - valMADBC) + valMADBC;
return valMABCDEFHG;
}
Vector3 SignedDistanceNormal(const Vector3 &Point) const {
// This function is used to calculate the (1 x 3) Jacobian matrix given the current Position
// This function is used to compute the distance from a 3D point to the environment terrain
// The first job is to figure out the nearest neighbours of the Points
double x_FloatIndex = (Point.x - Envi_x_min)/Envi_x_unit * 1.0;
double y_FloatIndex = (Point.y - Envi_y_min)/Envi_y_unit * 1.0;
double z_FloatIndex = (Point.z - Envi_z_min)/Envi_z_unit * 1.0;
int x_leftindex = std::floor(x_FloatIndex);
int y_leftindex = std::floor(y_FloatIndex);
int z_leftindex = std::floor(z_FloatIndex);
if(x_leftindex<0) {
x_leftindex = 0;
} else {
if(x_leftindex>GridNo-2) {
x_leftindex = GridNo-2;
}
}
if(y_leftindex<0) {
y_leftindex = 0;
} else {
if(y_leftindex>GridNo-2) {
y_leftindex = GridNo-2;
}
}
if(z_leftindex<0) {
z_leftindex = 0;
} else {
if(z_leftindex>GridNo-2) {
z_leftindex = GridNo-2;
}
}
int x_rightindex = x_leftindex + 1;
int y_rightindex = y_leftindex + 1;
int z_rightindex = z_leftindex + 1;
double valA = SDFTensor(x_leftindex, y_leftindex, z_leftindex);
double valB = SDFTensor(x_rightindex, y_leftindex, z_leftindex);
double valC = SDFTensor(x_rightindex, y_rightindex, z_leftindex);
double valD = SDFTensor(x_leftindex, y_rightindex, z_leftindex);
double valE = SDFTensor(x_leftindex, y_leftindex, z_rightindex);
double valF = SDFTensor(x_rightindex, y_leftindex, z_rightindex);
double valG = SDFTensor(x_rightindex, y_rightindex, z_rightindex);
double valH = SDFTensor(x_leftindex, y_rightindex, z_rightindex);
// Since this is a tri-linear interpolation, there are three ways to do the interpolation
/*
Jacobian matrix in the x-direction
*/
// Cut the point with a plane orthgonal to z axis
double valMAE = (z_FloatIndex - z_leftindex*1.0) * (valE - valA) + valA;
double valMBF = (z_FloatIndex - z_leftindex*1.0) * (valF - valB) + valB;
double valMDH = (z_FloatIndex - z_leftindex*1.0) * (valH - valD) + valD;
double valMCG = (z_FloatIndex - z_leftindex*1.0) * (valG - valC) + valC;
// Cut the point with a plane orthgonal to y axis
double valMAEDH = (y_FloatIndex - y_leftindex*1.0) * (valMDH - valMAE) + valMAE;
double valMBFCG = (y_FloatIndex - y_leftindex*1.0) * (valMCG - valMBF) + valMBF;
// The values at the edge give the jacobian to x
double JacDistTo_x = (valMBFCG - valMAEDH)/Envi_x_unit;
/*
Jacobian matrix in the y-direction
*/
double valMABEF = (x_FloatIndex - x_leftindex*1.0) * (valMBF - valMAE) + valMAE;
double valMDHCG = (x_FloatIndex - x_leftindex*1.0) * (valMCG - valMDH) + valMDH;
double JacDistTo_y = (valMDHCG - valMABEF)/Envi_y_unit;
/*
Jacobian matrix in the z-direction
*/
// Cut the point with a plane orthgonal to x axis
double valMAB = (x_FloatIndex - x_leftindex*1.0) * (valB - valA) + valA;
double valMDC = (x_FloatIndex - x_leftindex*1.0) * (valC - valD) + valD;
double valMEF = (x_FloatIndex - x_leftindex*1.0) * (valF - valE) + valE;
double valMHG = (x_FloatIndex - x_leftindex*1.0) * (valG - valH) + valH;
// Cut the point with a plane orthgonal to y axis
double valMABDC = (y_FloatIndex - y_leftindex*1.0) * (valMDC - valMAB) + valMAB;
double valMEFHG = (y_FloatIndex - y_leftindex*1.0) * (valMHG - valMEF) + valMHG;
// The values at the edge give the jacobian to z
double JacDistTo_z = (valMEFHG - valMABDC)/Envi_z_unit;
Vector3 RawNormal(JacDistTo_x, JacDistTo_y, JacDistTo_z);
RawNormal.setNormalized(RawNormal);
return RawNormal;
}
Eigen::Tensor<double, 3> SDFTensor;
double Envi_x_min, Envi_x_max;
double Envi_y_min, Envi_y_max;
double Envi_z_min, Envi_z_max;
double Envi_x_unit, Envi_y_unit, Envi_z_unit;
double Envi_x_length, Envi_y_length, Envi_z_length;
int GridNo;
};
struct ContactStatusInfo{
ContactStatusInfo(){ LinkIndex = -1;}
ContactStatusInfo(const int & link_index){ LinkIndex = link_index; }
void AddLocalConactStatus(const int & _contactstatus){ LocalContactStatus.push_back(_contactstatus); }
void StatusSwitch(const int & Val){
for(int i = 0; i<LocalContactStatus.size(); i++)
LocalContactStatus[i] = Val;
}
int LinkIndex;
std::vector<int> LocalContactStatus;
};
struct PolarPoint {
// This struct expresses a SO(3) point using Polar Coordinates with Radius and Direction
PolarPoint(){
Radius = -1.0;
Position.setZero();
Direction.setZero();
};
PolarPoint(double Radius_, const Vector3 & Position_) {
// Constructor
Radius = Radius_;
Position = Position_;
Direction = Position;
double PositionLength = Position.norm();
Direction.x = Direction.x/PositionLength;
Direction.y = Direction.y/PositionLength;
Direction.z = Direction.z/PositionLength;
}
double Radius;
Vector3 Position;
Vector3 Direction;
};
struct DataRecorderInfo{
DataRecorderInfo(){
PlanStageIndex = -1;
LinkNo = -1;
FailureMetric = 0.0;
};
void setPlanStageIndexNLinkNo(const int & _PlanStageIndex, const int & _LinkNo){
PlanStageIndex = _PlanStageIndex;
LinkNo = _LinkNo;
}
void setRCSData( const std::vector<Vector3> & _ReachableContacts,
const std::vector<Vector3> & _CollisionFreeContacts,
const std::vector<Vector3> & _SupportiveContacts){
ReachableContacts = _ReachableContacts;
CollisionFreeContacts = _CollisionFreeContacts;
SupportiveContacts = _SupportiveContacts;
}
void setCCSData( const std::vector<Vector3> & _CandidateContacts,
const std::vector<Vector3> & _CandidateContactWeights,
const std::vector<Vector3> & _SelectedContacts){
CandidateContacts = _CandidateContacts;
CandidateContactWeights = _CandidateContactWeights;
SelectedContacts = _SelectedContacts;
}
void setPathWaypoints(const std::vector<Vector3> & _PathWaypoints){ PathWaypoints = _PathWaypoints; }
void setTrajs(const LinearPath & _PlannedConfigTraj, const LinearPath & _EndEffectorTraj){
PlannedConfigTraj = _PlannedConfigTraj;
EndEffectorTraj = _EndEffectorTraj;
}
void Vector3Writer(const std::vector<Vector3> & ContactPoints, const std::string & ContactPointFileName){
if(ContactPoints.size() ==0) return;
int NumberOfContactPoints = ContactPoints.size();
std::vector<double> FlatContactPoints(3 * NumberOfContactPoints);
int FlatContactPointIndex = 0;
for (int i = 0; i < NumberOfContactPoints; i++){
FlatContactPoints[FlatContactPointIndex] = ContactPoints[i].x;
FlatContactPointIndex++;
FlatContactPoints[FlatContactPointIndex] = ContactPoints[i].y;
FlatContactPointIndex++;
FlatContactPoints[FlatContactPointIndex] = ContactPoints[i].z;
FlatContactPointIndex++;
}
FILE * FlatContactPointsFile = NULL;
string ContactPointFile = ContactPointFileName + ".bin";
const char *ContactPointFile_Name = ContactPointFile.c_str();
FlatContactPointsFile = fopen(ContactPointFile_Name, "wb");
fwrite(&FlatContactPoints[0], sizeof(double), FlatContactPoints.size(), FlatContactPointsFile);
fclose(FlatContactPointsFile);
return;
}
void UpdateWithRecoveryReferenceInfo(const LinearPath & PlannedConfigTraj_, const LinearPath & EndEffectorTraj_, double FailureMetric_){
PlannedConfigTraj = PlannedConfigTraj_;
EndEffectorTraj = EndEffectorTraj_;
FailureMetric = FailureMetric_;
}
void Write2File(const string & CurrentCasePath){
// This function will only be called if planning is successful!
const string InnerPath = CurrentCasePath + std::to_string(PlanStageIndex) + "_" + std::to_string(LinkNo) + "_";
Vector3Writer(ReachableContacts, InnerPath + "ReachableContacts");
Vector3Writer(CollisionFreeContacts, InnerPath + "CollisionFreeContacts");
Vector3Writer(SupportiveContacts, InnerPath + "SupportiveContacts");
Vector3Writer(CandidateContacts, InnerPath + "CandidateContacts");
Vector3Writer(CandidateContactWeights,InnerPath + "CandidateContactWeights");
Vector3Writer(SelectedContacts, InnerPath + "SelectedContacts");
Vector3Writer(PathWaypoints, InnerPath + "PathWaypoints");
// Failure Metric for strategy selection
const string FailureMetricFileName = InnerPath + "FailureMetric.txt";
std::ofstream FailureMetricFile (FailureMetricFileName);
FailureMetricFile << FailureMetric;
FailureMetricFile.close();
// Write these two trajectories into files.
std::ofstream PlannedConfigTrajFile;
const string PlannedConfigTrajName = InnerPath + "PlannedConfigTraj.path";
PlannedConfigTrajFile.open (PlannedConfigTrajName.c_str());
PlannedConfigTraj.Save(PlannedConfigTrajFile);
PlannedConfigTrajFile.close();
std::ofstream EndEffectorTrajFile;
const string EndEffectorTrajName = InnerPath + "EndEffectorTraj.path";
EndEffectorTrajFile.open(EndEffectorTrajName.c_str());
EndEffectorTraj.Save(EndEffectorTrajFile);
EndEffectorTrajFile.close();
}
std::vector<Vector3> ReachableContacts;
std::vector<Vector3> CollisionFreeContacts;
std::vector<Vector3> SupportiveContacts;
std::vector<Vector3> CandidateContacts;
std::vector<Vector3> CandidateContactWeights;
std::vector<Vector3> SelectedContacts;
std::vector<Vector3> PathWaypoints;
LinearPath PlannedConfigTraj;
LinearPath EndEffectorTraj;
double FailureMetric;
int PlanStageIndex;
int LinkNo;
};
struct ReachabilityMap {
// This struct is used to save the reachability map
ReachabilityMap(){
RadiusMin = -1.0;
RadiusMax = -1.0;
LayerSize = -1;
RadiusUnit = -1.0;
PointSize = -1;
};
ReachabilityMap(double RadiusMin_, double RadiusMax_, int LayerSize_){
RadiusMin = RadiusMin_;
RadiusMax = RadiusMax_;
LayerSize = LayerSize_;
RadiusUnit = (RadiusMax - RadiusMin)/(1.0 * LayerSize - 1.0);
PointSize = -1;
}
std::vector<Vector3> ReachablePointsFinder(const Robot & SimRobot, int SwingLinkInfoIndex, const SDFInfo & SDFInfoObj) const{
const double DisTol = 0.01; // 1cm as a distance tolerance.
double Radius = EndEffectorChainRadius[SwingLinkInfoIndex];
double PivotalLinkIndex = EndEffectorPivotalIndex[SwingLinkInfoIndex];
Vector3 RefPoint;
SimRobot.GetWorldPosition(Vector3(0.0, 0.0, 0.0), PivotalLinkIndex, RefPoint);
std::vector<Vector3> ReachablePoints;
ReachablePoints.reserve(PointSize);
int LayerIndex = 0;
double LayerRadius = RadiusMin;
if(Radius>RadiusMax){
LayerIndex = LayerSize-1;
} else{
while (LayerRadius<Radius){
LayerRadius+=RadiusUnit;
LayerIndex++;
}
LayerRadius-=RadiusUnit;
}
for (int i = 0; i < LayerIndex; i++){
std::vector<PolarPoint> PolarPointLayer = PolarPointLayers.find(i)->second;
for (int j = 0; j < PolarPointLayer.size(); j++){
Vector3 PolarPointPos = PolarPointLayer[j].Position + RefPoint;
double CurrentDist = SDFInfoObj.SignedDistance(PolarPointPos);
if((CurrentDist>0.0)&&(CurrentDist<DisTol)){
ReachablePoints.push_back(PolarPointPos);
}
}
}
return ReachablePoints;
}
std::vector<Vector3> ContactFreePointsFinder(double radius, const std::vector<Vector3> & ReachablePoints,
const std::vector<std::pair<Vector3, double>> & ContactFreeInfo) const{
// This function can only be called after ReachablePointsFinder() to reduce the extra point further.
std::vector<Vector3> ContactFreePoints;
ContactFreePoints.reserve(ReachablePoints.size());
int ContactFreeNo = 0;
for (int i = 0; i < ReachablePoints.size(); i++){
Vector3 ReachablePoint = ReachablePoints[i];
bool ContactFreeFlag = true;
int ContactFreeInfoIndex = 0;
while (ContactFreeInfoIndex<ContactFreeInfo.size()){
Vector3 RefPoint = ContactFreeInfo[ContactFreeInfoIndex].first;
double Radius = ContactFreeInfo[ContactFreeInfoIndex].second;
Vector3 PosDiff = ReachablePoint - RefPoint;
double PosDiffDis = PosDiff.norm();
if(PosDiffDis<=(Radius + radius)){
ContactFreeFlag = false;
break;
}
ContactFreeInfoIndex++;
}
if(ContactFreeFlag){
ContactFreePoints.push_back(ReachablePoints[i]);
ContactFreeNo++;
}
}
return ContactFreePoints;
};
std::map<int, std::vector<PolarPoint>> PolarPointLayers;
std::vector<double> EndEffectorChainRadius; // Radius from end effector to pivital joint
std::vector<double> EndEffectorGeometryRadius; // End effector's geometrical radius
std::vector<int> EndEffectorLinkIndex; // End effector link index
std::vector<int> EndEffectorPivotalIndex;
std::map<int, std::vector<int>> EndEffectorChainIndices; // This map saves intermediate joint from End Effector Joint to Pivotal Joint.
std::map<int, int> EndEffectorIndexCheck;
std::vector<int> Link34ToPivotal;
std::vector<int> Link27ToPivotal;
double RadiusMin;
double RadiusMax ;
int LayerSize;
double RadiusUnit;
int PointSize;
};
struct SimPara{
SimPara(){
PushDuration = -1.0;
DetectionWait = -1.0;
TimeStep = -1.0;
InitDuration = -1.0;
TotalDuration = -1.0;
ForwardDurationSeed = -1.0;
PhaseRatio = -1.0;
ReductionRatio = -1.0;
ContactSelectionCoeff = 1.25;
ImpulseForceValue = -1.0;
ImpulseForceDirection.setZero();
FailureTime = -1.0;
SelfCollisionTol = -1.0;
TouchDownTol = -1.0;
};
SimPara(const std::vector<double> & SimParaVec) {
assert (SimParaVec.size() == 11);
PushDuration = SimParaVec[0];
DetectionWait = SimParaVec[1];
TimeStep = SimParaVec[2];
InitDuration = SimParaVec[3];
TotalDuration = SimParaVec[4];
ForwardDurationSeed = SimParaVec[5];
PhaseRatio = SimParaVec[6]; // This ratio determines the boundary between acceleration and deceleration.
ReductionRatio = SimParaVec[7];
ContactSelectionCoeff = SimParaVec[8];
SelfCollisionTol = SimParaVec[9];
TouchDownTol = SimParaVec[10];
}
void CurrentCasePathUpdate(const string & CurrentCasePath_){
CurrentCasePath = CurrentCasePath_;
string fedge_aFile = CurrentCasePath + "EdgeATraj.txt";
// const char *fedge_aFile_Name = fedge_aFile.c_str();
string fedge_bFile = CurrentCasePath + "EdgeBTraj.txt";
// const char *fedge_bFile_Name = fedge_bFile.c_str();
string fEdgeCOMFile = CurrentCasePath + "EdgeCOMTraj.txt";
// const char *fEdgeCOMFile_Name = fEdgeCOMFile.c_str();
string fEdgexTrajFile = CurrentCasePath + "EdgexTraj.txt";
// const char *fEdgexTrajFile_Name = fEdgexTrajFile.c_str();
string fEdgeyTrajFile = CurrentCasePath + "EdgeyTraj.txt";
// const char *fEdgeyTrajFile_Name = fEdgeyTrajFile.c_str();
string fEdgezTrajFile = CurrentCasePath + "EdgezTraj.txt";
// const char *fEdgezTrajFile_Name = fEdgezTrajFile.c_str();
string fVertexTrajFile = CurrentCasePath + "EdgeVertexTraj.txt";
EdgeFileNames.clear();
EdgeFileNames.push_back(fedge_aFile);
EdgeFileNames.push_back(fedge_bFile);
EdgeFileNames.push_back(fEdgeCOMFile);
EdgeFileNames.push_back(fEdgexTrajFile);
EdgeFileNames.push_back(fEdgeyTrajFile);
EdgeFileNames.push_back(fEdgezTrajFile);
EdgeFileNames.push_back(fVertexTrajFile);
FailureStateTrajStr = CurrentCasePath + "FailureStateTraj.path";
// const char *FailureStateTrajStr_Name = FailureStateTrajStr.c_str();
CtrlStateTrajStr = CurrentCasePath + "CtrlStateTraj.path";
// const char *CtrlStateTrajStr_Name = CtrlStateTrajStr.c_str();
PlanStateTrajStr = CurrentCasePath + "PlanStateTraj.path";
// const char *PlanStateTrajStr_Name = PlanStateTrajStr.c_str();
CtrlPosTrajStr = CurrentCasePath + "CtrlPosTraj.txt";
FailurePosTrajStr = CurrentCasePath + "FailurePosTraj.txt";
CtrlVelTrajStr = CurrentCasePath + "CtrlVelTraj.txt";
FailureVelTrajStr = CurrentCasePath + "FailureVelTraj.txt";
}
void setImpulseForce(double ImpulseForceValue_, Vector3 ImpulseForceDirection_){ ImpulseForceValue = ImpulseForceValue_; ImpulseForceDirection = ImpulseForceDirection_;}
void getImpulseForce(double & ImpulseForceValue_, Vector3 & ImpulseForceDirection_ ) const { ImpulseForceValue_ = ImpulseForceValue; ImpulseForceDirection_ = ImpulseForceDirection; }
string getCurrentCasePath() const{ return CurrentCasePath; }
void setPlanStageIndex(const int & _PlanStageIndex) {PlanStageIndex = _PlanStageIndex; }
int getPlanStageIndex() const{ return PlanStageIndex; }
void setSimTime(const double & _SimTime) { SimTime = _SimTime; }
double getSimTime() const{ return SimTime; }
void setInitContactPos(const Vector3 & InitContactPos_){ InitContactPos = InitContactPos_; }
Vector3 getInitContactPos() const{ return InitContactPos; }
void setInitContactDirection(const Vector3 & InitContactDirection_) { InitContactDirection = InitContactDirection_; }
Vector3 getInitContactDirection() const{return InitContactDirection; }
void setGoalContactPos(const Vector3 & GoalContactPos_) { GoalContactPos = GoalContactPos_; }
Vector3 getGoalContactPos() const{ return GoalContactPos; }
void setGoalContactDirection(const Vector3 & GoalContactDirection_) { GoalContactDirection = GoalContactDirection_; }
Vector3 getGoalContactDirection() const{ return GoalContactDirection; };
void setSwingLinkInfoIndex(const int & _SwingLinkInfoIndex) { SwingLinkInfoIndex = _SwingLinkInfoIndex; }
int getSwingLinkInfoIndex() const{ return SwingLinkInfoIndex;}
double getContactSelectionCoeff() const{ return ContactSelectionCoeff; }
void setOneHandAlreadyFlag(const bool & OneHandAlreadyFlag_) { OneHandAlreadyFlag = OneHandAlreadyFlag_; }
bool getOneHandAlreadyFlag() const { return OneHandAlreadyFlag; }
void setPlanEndEffectorIndex( const int & PlanEndEffectorIndex_) { PlanEndEffectorIndex = PlanEndEffectorIndex_; }
int getPlanEndEffectorIndex() const{ return PlanEndEffectorIndex; }
void setFixedContactStatusInfo(const std::vector<ContactStatusInfo> & _FixedContactStatusInfo){ FixedContactStatusInfo =_FixedContactStatusInfo;}
std::vector<ContactStatusInfo> getFixedContactStatusInfo() const { return FixedContactStatusInfo; }
double getSelfCollisionTol() const { return SelfCollisionTol; }
double getTouchDownTol() const { return TouchDownTol; }
// void setTransPathFeasiFlag(const bool & _TransPathFeasiFlag){ TransPathFeasiFlag = _TransPathFeasiFlag; }
// bool getTransPathFeasiFlag() const{ return TransPathFeasiFlag; }
// void setCurrentContactPos(const Vector3 & _CurrentContactPos) {CurrentContactPos = _CurrentContactPos; }
// Vector3 getCurrentContactPos() const{ return CurrentContactPos; }
// void setTrajConfigOptFlag(const bool & _TrajConfigOptFlag){ TrajConfigOptFlag = _TrajConfigOptFlag;}
// bool getTrajConfigOptFlag() const{return TrajConfigOptFlag;}
double PushDuration;
double DetectionWait;
double TimeStep;
double InitDuration;
double TotalDuration;
double ForwardDurationSeed;
double PhaseRatio; // This ratio determines the boundary between acceleration and deceleration.
double ReductionRatio;
double ContactSelectionCoeff;
double SelfCollisionTol; // 1.0cm
double TouchDownTol; // 1.0cm
double ImpulseForceValue;
Vector3 ImpulseForceDirection;
string CurrentCasePath;
std::vector<string> EdgeFileNames;
string FailureStateTrajStr, CtrlStateTrajStr, PlanStateTrajStr;
string CtrlPosTrajStr, FailurePosTrajStr;
string CtrlVelTrajStr, FailureVelTrajStr;
double FailureTime;
int PlanStageIndex;
double SimTime;
int SwingLinkInfoIndex;
bool OneHandAlreadyFlag;
int PlanEndEffectorIndex; // This PlanEndEffectorIndex saves successful end effector for push recovery.
// Vector3 CurrentContactPos;
// bool TrajConfigOptFlag;
DataRecorderInfo DataRecorderObj;
Vector3 InitContactPos, InitContactDirection;
Vector3 GoalContactPos, GoalContactDirection;
std::vector<ContactStatusInfo> FixedContactStatusInfo;
// Vector3 EndEffectorInitxDir, EndEffectorInityDir; // For alignment purpose
};
struct SelfCollisionInfo: public ScaledLocalCoordinates3D{
SelfCollisionInfo(){
SelfLinkGeoFlag = false;
};
SelfCollisionInfo(const Robot & SimRobot, const std::map<int, std::vector<int>> & EndEffectorChainIndices, const std::vector<int> & SelfCollisionFreeLink){
for (int i = 5; i < SimRobot.q.size(); i++){
Box3D Box3D_i = SimRobot.geometry[i]->GetBB();
Frame3D LinkTransforms_i = SimRobot.links[i].T_World;
BoundingBoxes.push_back(Box3D_i);
Vector3 Extremity_i;
RigidTransform Transformation_i;
BoxInfoUpdate(Box3D_i, Extremity_i, Transformation_i);
BoundingBoxExtremities.push_back(Extremity_i);
BoundingBoxTransforms.push_back(Transformation_i);
}
for (int i = 0; i < EndEffectorChainIndices.size(); i++){
std::vector<int> EndEffectorChainIndex = EndEffectorChainIndices.at(i);
for (int j = 5; j < SimRobot.q.size(); j++){
if(std::find(EndEffectorChainIndex.begin(), EndEffectorChainIndex.end(), j) == EndEffectorChainIndex.end()){
if(std::find(SelfCollisionFreeLink.begin(), SelfCollisionFreeLink.end(), j) == SelfCollisionFreeLink.end()){
SelfCollisionLinkMap[i].push_back(j-5);
}
}
}
}
SelfLinkGeoFlag = true;
};
void SelfCollisionBoundingBoxesUpdate(const Robot& SimRobot){
for (int i = 5; i < SimRobot.q.size(); i++){
Box3D Box3D_i = SimRobot.geometry[i]->GetBB();
BoundingBoxes[i-5] = Box3D_i;
Vector3 Extremity_i;
RigidTransform Transformation_i;
BoxInfoUpdate(Box3D_i, Extremity_i, Transformation_i);
BoundingBoxExtremities[i-5] = Extremity_i;
BoundingBoxTransforms[i-5] = Transformation_i;
}
}
void BBVerticesWriter() const {
for (int i = 0; i < BoundingBoxes.size(); i++){
std::vector<Vector3> BoundingBoxVertices = BBVertices(i);
string BBName = "BB" + to_string(i);
Vector3Writer(BoundingBoxVertices, BBName);
}
}
void BoxInfoUpdate(const Box3D & Box, Vector3 & Extremity_, RigidTransform & Transformation_){
// This function is used to update the bounding box information.
double x_scale = Box.dims.x;
double y_scale = Box.dims.y;
double z_scale = Box.dims.z;
// Get rid of the fact that the axes have been scaled
Vector3 xbasis = Box.xbasis;
Vector3 ybasis = Box.ybasis;
Vector3 zbasis = Box.zbasis;
Vector3 xbasis_, ybasis_, zbasis_;
xbasis_.setNormalized(xbasis);
ybasis_.setNormalized(ybasis);
zbasis_.setNormalized(zbasis);
Vector3 origin = Box.origin;
double x_mag = xbasis.norm();
double y_mag = ybasis.norm();
double z_mag = zbasis.norm();
double x_scale_act = x_scale * x_mag;
double y_scale_act = y_scale * y_mag;
double z_scale_act = z_scale * z_mag;
Vector3 Extremity(x_scale_act, y_scale_act, z_scale_act);
Extremity_ = Extremity;
RigidTransform Transformation(xbasis_, ybasis_, zbasis_, origin);
Transformation_ = Transformation;
}
std::vector<Vector3> BBVertices(int BBIndex) const{
std::vector<Vector3> Vertices(8);
// This function calculates the vertices for current bounding box.
Box3D CurBB = BoundingBoxes[BBIndex];
double x_scale = CurBB.dims.x;
double y_scale = CurBB.dims.y;
double z_scale = CurBB.dims.z;
Vector3 p0(0.0, 0.0, 0.0);
Vector3 p1(x_scale, 0.0, 0.0);
Vector3 p2(0.0, y_scale, 0.0);
Vector3 p3(x_scale, y_scale, 0.0);
Vector3 pz(0.0, 0.0, z_scale);
Vector3 p4 = p0 + pz;
Vector3 p5 = p1 + pz;
Vector3 p6 = p2 + pz;
Vector3 p7 = p3 + pz;
Vector3 p0_, p1_, p2_, p3_, p4_, p5_, p6_, p7_;
Matrix4 basis;
CurBB.getBasis(basis);
basis.mulPoint(p0, p0_);
basis.mulPoint(p1, p1_);
basis.mulPoint(p2, p2_);
basis.mulPoint(p3, p3_);
basis.mulPoint(p4, p4_);
basis.mulPoint(p5, p5_);
basis.mulPoint(p6, p6_);
basis.mulPoint(p7, p7_);
Vertices[0] = p0_;
Vertices[1] = p1_;
Vertices[2] = p2_;
Vertices[3] = p3_;
Vertices[4] = p4_;
Vertices[5] = p5_;
Vertices[6] = p6_;
Vertices[7] = p7_;
return Vertices;
}
std::vector<double> LinearSpace(double a, double b, std::size_t N) const {
double h = (b - a) / static_cast<double>(N-1);
std::vector<double> xs(N);
std::vector<double>::iterator x;
double val;
for (x = xs.begin(), val = a; x != xs.end(); ++x, val += h) {
*x = val;
}
return xs;
}
std::vector<Vector3> TwoPointLine(const Vector3 & p1, const Vector3 & p2) const{
int point_number = 100;
std::vector<double> line_x = LinearSpace(p1.x, p2.x, point_number);
std::vector<double> line_y = LinearSpace(p1.y, p2.y, point_number);
std::vector<double> line_z = LinearSpace(p1.z, p2.z, point_number);
std::vector<Vector3> LinePoints;
Vector3 TempPoint;
for (int i = 0; i < point_number; i++){
TempPoint.x = line_x[i];
TempPoint.y = line_y[i];
TempPoint.z = line_z[i];
LinePoints.push_back(TempPoint);
}
return LinePoints;
}
double Box3DsignedDistance(int BoxIndex, const Point3D & GlobalPoint) const{
Box3D Box = BoundingBoxes[BoxIndex];
Vector3 LocalPoint;
BoundingBoxTransforms[BoxIndex].mulInverse(GlobalPoint, LocalPoint);
Vector3 Extremity = BoundingBoxExtremities[BoxIndex];
bool Inside = true;
Vector3 LocalNearestPoint;
// Comparison from three dimensions
// x dimension
if(LocalPoint.x < 0) {
LocalNearestPoint.x = 0.0;
Inside = false;
} else {
if(LocalPoint.x > Extremity.x) {
LocalNearestPoint.x = Extremity.x;
Inside = false;
} else {
LocalNearestPoint.x = LocalPoint.x;
}
}
// y dimension
if(LocalPoint.y < 0) {
LocalNearestPoint.y = 0.0;
Inside = false;
} else {
if(LocalPoint.y > Extremity.y) {
LocalNearestPoint.y = Extremity.y;
Inside = false;
} else {
LocalNearestPoint.y = LocalPoint.y;
}
}
// z dimension
if(LocalPoint.z < 0) {
LocalNearestPoint.z = 0.0;
Inside = false;
} else {
if(LocalPoint.z > Extremity.z) {
LocalNearestPoint.z = Extremity.z;
Inside = false;
} else {
LocalNearestPoint.z = LocalPoint.z;
}
}
Vector3 GlobalNearestPoint;
BoundingBoxTransforms[BoxIndex].mulPoint(LocalNearestPoint, GlobalNearestPoint);
Vector3 PointDiff = GlobalNearestPoint - GlobalPoint;
if(!Inside) return PointDiff.norm();
else {
double dmin = Inf;
double leftbound = LocalPoint.x;
double rightbound = Extremity.x - LocalPoint.x;
dmin = min(dmin, min(leftbound, rightbound));
leftbound = LocalPoint.y;
rightbound = Extremity.y - LocalPoint.y;
dmin = min(dmin, min(leftbound, rightbound));
leftbound = LocalPoint.z;
rightbound = Extremity.z - LocalPoint.z;
dmin = min(dmin, min(leftbound, rightbound));
return -dmin;
}
}
void Vector3Writer(const std::vector<Vector3> & ContactPoints, const std::string &ContactPointFileName) const{
if(ContactPoints.size()==0){
std::cerr<< " ContactPoints has zero element!\n" << endl;
}
int NumberOfContactPoints = ContactPoints.size();
std::vector<double> FlatContactPoints(3 * NumberOfContactPoints);
int FlatContactPointIndex = 0;
for (int i = 0; i < NumberOfContactPoints; i++){
FlatContactPoints[FlatContactPointIndex] = ContactPoints[i].x;
FlatContactPointIndex++;
FlatContactPoints[FlatContactPointIndex] = ContactPoints[i].y;
FlatContactPointIndex++;
FlatContactPoints[FlatContactPointIndex] = ContactPoints[i].z;
FlatContactPointIndex++;
}
FILE * FlatContactPointsFile = NULL;
string ContactPointFile = ContactPointFileName + ".bin";
const char *ContactPointFile_Name = ContactPointFile.c_str();
FlatContactPointsFile = fopen(ContactPointFile_Name, "wb");
fwrite(&FlatContactPoints[0], sizeof(double), FlatContactPoints.size(), FlatContactPointsFile);
fclose(FlatContactPointsFile);
return;
}
void getSingleLinkDistNGrad(const int & LinkCountIndex, const Vector3 & GlobalPoint, double & Dist, Vector3 & DistGrad) const{
const int GridNo = 100;
double dx = BoundingBoxes[LinkCountIndex].dims.x/(1.0 * GridNo);
double dy = BoundingBoxes[LinkCountIndex].dims.y/(1.0 * GridNo);
double dz = BoundingBoxes[LinkCountIndex].dims.z/(1.0 * GridNo);
Dist = Box3DsignedDistance(LinkCountIndex, GlobalPoint);
Vector3 GlobalPointx = GlobalPoint;
GlobalPointx.x += dx;
double Distx = Box3DsignedDistance(LinkCountIndex, GlobalPointx);
Vector3 GlobalPointy = GlobalPoint;
GlobalPointy.y += dy;
double Disty = Box3DsignedDistance(LinkCountIndex, GlobalPointy);
Vector3 GlobalPointz = GlobalPoint;
GlobalPointz.z += dz;
double Distz = Box3DsignedDistance(LinkCountIndex, GlobalPointz);
DistGrad.x = (Distx - Dist)/dx;
DistGrad.y = (Disty - Dist)/dy;
DistGrad.z = (Distz - Dist)/dz;
DistGrad.getNormalized(DistGrad);
}
double getSelfCollisionDist(const int & LinkIndex, const Vector3 & GlobalPoint) const{
std::vector<int> SelfCollisionLinkIndices = SelfCollisionLinkMap.at(LinkIndex);
const int ActLinkNo = SelfCollisionLinkIndices.size();
std::vector<double> DistVec;
DistVec.reserve(ActLinkNo);
for (int i = 0; i < ActLinkNo; i++){
int SelfCollisionLinkIndex = SelfCollisionLinkIndices[i];
double Dist_i = Box3DsignedDistance(i, GlobalPoint);
DistVec.push_back(Dist_i);
}
double Dist = *std::min_element(DistVec.begin(), DistVec.end());
return Dist;
}
void getSelfCollisionDistNGrad(const int & LinkIndex, const Vector3 & GlobalPoint, double & Dist, Vector3 & Grad) const{
// This function is used to calculate robot's self-collision distance given a point.
std::vector<int> SelfCollisionLinkIndices = SelfCollisionLinkMap.at(LinkIndex);
const int ActLinkNo = SelfCollisionLinkIndices.size();
std::vector<double> DistVec;
DistVec.reserve(ActLinkNo);
std::vector<Vector3> GradVec;
GradVec.reserve(ActLinkNo);
std::vector<double> DistWeights;
DistWeights.reserve(ActLinkNo);
double Dist_i;
Vector3 Grad_i;
for (int i = 0; i < ActLinkNo; i++){
int SelfLinkIndex = SelfCollisionLinkIndices[i];
getSingleLinkDistNGrad(SelfLinkIndex, GlobalPoint, Dist_i, Grad_i);
DistVec.push_back(Dist_i);
GradVec.push_back(Grad_i);
}
Dist = *std::min_element(DistVec.begin(), DistVec.end());
double Scale = abs(Dist);
for (int i = 0; i < ActLinkNo; i++){
DistWeights.push_back(exp(-1.0 * DistVec[i]/Scale));
}
// Set its value to be zero!
Grad.x = 0.0;
Grad.y = 0.0;
Grad.z = 0.0;
for (int i = 0; i < ActLinkNo; i++)
Grad+=DistWeights[i] * GradVec[i];
Grad.getNormalized(Grad);
}
bool SelfLinkGeoFlag;
std::vector<Box3D> BoundingBoxes;
std::vector<Vector3> BoundingBoxExtremities; // Local Extremities
std::vector<RigidTransform> BoundingBoxTransforms; // Local Transformation
std::map<int, std::vector<int>> SelfCollisionLinkMap; // This map saves intermediate joint from End Effector Joint to Pivotal Joint.
};
struct RecoveryReferenceInfo{
RecoveryReferenceInfo(){
ReadyFlag = false;
TouchDownFlag = false;
OneHandAlreadyFlag = false;
ControlReferenceType = -1;
SwingLinkInfoIndex = -1; // Used for RobotLinkInfo
ContactStatusInfoIndex = -1;
WaitTime = -1.0;
FailureMetric = -1.0;
GoalContactPos.setZero();
GoalContactGrad.setZero();
}
void setFailureMetric(const double & _FailureMetric){ FailureMetric = _FailureMetric; }
double getFailureMetric() const{ return FailureMetric; }
void setSwingLinkInfoIndex(const int & _SwingLinkInfoIndex) {SwingLinkInfoIndex = _SwingLinkInfoIndex;}
int getSwingLinkInfoIndex() const{ return SwingLinkInfoIndex; }
bool getReadyFlag() const{ return ReadyFlag;}
void setReadyFlag(const bool & _ReadyFlag ){ ReadyFlag = _ReadyFlag; }
void setTouchDownFlag(const bool & _TouchDownFlag){ TouchDownFlag=_TouchDownFlag; }
bool getTouchDownFlag(){ return TouchDownFlag; }
void setOneHandAlreadyFlag(bool Value) {OneHandAlreadyFlag = Value;}
bool getOneHandAlreadyFlag() const { return OneHandAlreadyFlag; };
int getControlReferenceType() const{ return ControlReferenceType; }
void setControlReferenceType(const int &_ControlReferenceType) { ControlReferenceType = _ControlReferenceType; }
void setGoalContactPosNGrad(const Vector3 & _GoalContactPos, const Vector3 & _GoalContactGrad){
GoalContactPos = _GoalContactPos;
GoalContactGrad = _GoalContactGrad;
}
Vector3 getGoalContactPos() const{ return GoalContactPos; }
Vector3 getGoalContactGrad() const{ return GoalContactGrad;}
void SetInitContactStatus(const std::vector<ContactStatusInfo> &_InitContactStatus){ InitContactStatus = _InitContactStatus; }
std::vector<ContactStatusInfo> getInitContactStatus() const { return InitContactStatus;}
void SetGoalContactStatus(const std::vector<ContactStatusInfo> & _GoalContactStatus) { GoalContactStatus = _GoalContactStatus;}
std::vector<ContactStatusInfo> getGoalContactStatus() const { return GoalContactStatus;}
void TrajectoryUpdate(const std::vector<double> & timeTraj, const std::vector<Config> & configTraj, const std::vector<Config> & velocityTraj, const std::vector<Vector3> & endeffectorTraj){
TimeTraj = timeTraj;
ConfigTraj = configTraj;
PlannedConfigTraj = LinearPath(timeTraj, configTraj);
PlannedVelocityTraj = LinearPath(timeTraj, velocityTraj);
std::vector<Vector> endeffectorPath;
for (Vector3 EndEffectorPos: endeffectorTraj){
Vector EndEffectorPosVec;
EndEffectorPosVec.resize(3);
EndEffectorPosVec[0] = EndEffectorPos[0];
EndEffectorPosVec[1] = EndEffectorPos[1];
EndEffectorPosVec[2] = EndEffectorPos[2];
endeffectorPath.push_back(EndEffectorPosVec);
}
EndEffectorTraj = LinearPath(timeTraj, endeffectorPath);
}
void setWaitTime(const double & _WaitTime) { WaitTime = _WaitTime; }
double getWaitTime() const { return WaitTime; }
void setTouchDownConfig(const std::vector<double> _TouchDownConfig){ TouchDownConfig = _TouchDownConfig; }
std::vector<double> getTouchDownConfig() const { return TouchDownConfig;}
bool ReadyFlag;
bool TouchDownFlag;
bool OneHandAlreadyFlag;
int ControlReferenceType;
int SwingLinkInfoIndex;
int ContactStatusInfoIndex;
double WaitTime;
double FailureMetric;
Vector3 GoalContactPos;
Vector3 GoalContactGrad;
std::vector<double> TouchDownConfig;
LinearPath PlannedConfigTraj;
LinearPath PlannedVelocityTraj;
LinearPath EndEffectorTraj;
std::vector<QuaternionRotation> OrientationQuat;
std::vector<double> TimeTraj;
std::vector<Config> ConfigTraj;
std::vector<ContactStatusInfo> InitContactStatus;
std::vector<ContactStatusInfo> GoalContactStatus;
};
struct FacetInfo{
FacetInfo(){
FacetValidFlag = false;
};
void setFacetValidFlag(const bool & _FacetValidFlag){FacetValidFlag = _FacetValidFlag;}
bool getFacetValidFlag(){ return FacetValidFlag;}
void setFacetEdges(const std::vector<std::pair<Vector3, Vector3>> & _FacetEdges) { FacetEdges = _FacetEdges; }
void setFacetNorm(const Vector3& _FacetNorm){ FacetNorm = _FacetNorm;}
double ProjPoint2EdgeDist(const Vector3& _Point){
std::vector<double> ProjPoint2Edge_vec(EdgeNorms.size());
Vector3 Vertex2Point = _Point - FacetEdges[0].first;
double Point2Facet = Vertex2Point.dot(FacetNorm);
Vector3 Facet2Point = Point2Facet * FacetNorm;
for (int i = 0; i < EdgeNorms.size(); i++){
Vertex2Point = _Point - FacetEdges[i].first;
Vector3 Vertex2ProjPoint = Vertex2Point - Facet2Point;
double ProjPoint2Edge_i = Vertex2ProjPoint.dot(EdgeNorms[i]);
ProjPoint2Edge_vec[i] = ProjPoint2Edge_i;
}
return *min_element(ProjPoint2Edge_vec.begin(), ProjPoint2Edge_vec.end());
}
std::vector<double> ProjPoint2EdgeDistVec(const Vector3& _Point){
std::vector<double> ProjPoint2Edge_vec(EdgeNorms.size());
Vector3 Vertex2Point = _Point - FacetEdges[0].first;
double Point2Facet = Vertex2Point.dot(FacetNorm);
Vector3 Facet2Point = Point2Facet * FacetNorm;
for (int i = 0; i < EdgeNorms.size(); i++){
Vertex2Point = _Point - FacetEdges[i].first;
Vector3 Vertex2ProjPoint = Vertex2Point - Facet2Point;
double ProjPoint2Edge_i = Vertex2ProjPoint.dot(EdgeNorms[i]);
ProjPoint2Edge_vec[i] = ProjPoint2Edge_i;
}
return ProjPoint2Edge_vec;
}
void EdgesUpdate(){
Edges.reserve(EdgeNorms.size());
EdgesDirection.reserve(EdgeNorms.size());
for (int i = 0; i < EdgeNorms.size(); i++){
Vector3 Edge_i = FacetEdges[i].second - FacetEdges[i].first;
Edges.push_back(Edge_i);
Vector3 Edge_i_normalized;
Edge_i.getNormalized(Edge_i_normalized);
EdgesDirection.push_back(Edge_i_normalized);
}
}
std::vector<std::pair<Vector3, Vector3>> FacetEdges;
std::vector<Vector3> EdgeNorms;
Vector3 FacetNorm;
std::vector<Vector3> Edges;
std::vector<Vector3> EdgesDirection;
bool FacetValidFlag;
};
struct PIPInfo{
// This struct saves the information of the projected inverted pendulum from the CoM to the edge of convex polytope
PIPInfo(){
L = 0.25; // The reference bound range is [0.25, 0.85]
Ldot = 0.0;
theta = 0.0;
thetadot = 0.0;
g = 9.81;
g_angle = 0.0;
speed = -1.0;
onFlag = false;
}
PIPInfo(double _L, double _Ldot, double _theta, double _thetadot, double _g, double _g_angle){
L = _L;
Ldot = _Ldot;
theta = _theta;
thetadot = _thetadot;
g = _g;
g_angle = _g_angle;
}
void setPrimeUnits(const Vector3 & x_prime_unit_,const Vector3 & y_prime_unit_,const Vector3 & z_prime_unit_){
x_prime_unit = x_prime_unit_;
y_prime_unit = y_prime_unit_;
z_prime_unit = z_prime_unit_;
}
void setUnits(const Vector3 & x_unit_,const Vector3 & y_unit_,const Vector3 & z_unit_){
x_unit = x_unit_;
y_unit = y_unit_;
z_unit = z_unit_;
}
void setEdgeAnB(const Vector3 & edge_a_, const Vector3 & edge_b_){
edge_a = edge_a_;
edge_b = edge_b_;
}
void setIntersection(const Vector3 & intersection_){ intersection = intersection_;}
void setSpeed(const double & _speed ) {speed = _speed;}
double getSpeed() const{ return speed;}
double L, Ldot, theta, thetadot;
double g, g_angle;
double speed; // This value indicates the horizontal velocity.
bool onFlag; // Whether the origin is at intersection or not?!
Vector3 x_prime_unit, y_prime_unit, z_prime_unit;
Vector3 x_unit, y_unit, z_unit;
Vector3 edge_a, edge_b; // The Edge points from edge_a to edge_b.
Vector3 intersection; // The point where the COM intersects the edge.
};
struct ContactForm{
ContactForm(){
SwingLinkInfoIndex = -1;
ContactType = -1;
};
ContactForm( const std::vector<ContactStatusInfo> & _ContactStatusInfoObj,
const int & _SwingLinkInfoIndex,
const int & _ContactType): FixedContactStatusInfo(_ContactStatusInfoObj),
SwingLinkInfoIndex(_SwingLinkInfoIndex),
ContactType(_ContactType){};
std::vector<ContactStatusInfo> FixedContactStatusInfo;
int SwingLinkInfoIndex;
int ContactType;
};
struct InvertedPendulumInfo{
InvertedPendulumInfo(){
L = -1.0;
g = -1.0;
Theta = -1.0;
Thetadot = -1.0;
COMPos.setZero();
COMVel.setZero();
edge_a.setZero();
edge_b.setZero();
};
InvertedPendulumInfo( const double & _L,
const double & _g,
const double & _Theta,
const double & _Thetadot,
const Vector3 & _COMPos,
const Vector3 & _COMVel): L(_L),
g(_g),
Theta(_Theta),
Thetadot(_Thetadot),
COMPos(_COMPos),
COMVel(_COMVel){};
void setEdges(const Vector3 & _edge_a, const Vector3 & _edge_b){
edge_a = _edge_a;
edge_b = _edge_b;
}
double L, g;
double Theta;
double Thetadot;
Vector3 COMPos;
Vector3 COMVel;
Vector3 edge_a, edge_b;
};
struct CubicSplineInfo{
CubicSplineInfo(){
ReadyFlag = false;
};
CubicSplineInfo(const std::vector<Vector3> & pVec_, const std::vector<double> & sVec_){
ReadyFlag = false;
CubicSplineInfoUpdate(pVec_, sVec_);
}
void CubicSplineInfoUpdate(const std::vector<Vector3> & pVec_, const std::vector<double> & sVec_){
pVec = pVec_;
sVec = sVec_;
spline_x_y_z_init();
}
void spline_x_y_z_init(){
const int n = pVec.size();
std::vector<double> S = sVec;
std::vector<double> X(n), Y(n), Z(n);
for (int i = 0; i < n; i++){
double s = sVec[i];
X[i] = pVec[i].x;
Y[i] = pVec[i].y;
Z[i] = pVec[i].z;
}
tk::spline s_x, s_y, s_z;
s_x.set_points(S,X);
s_y.set_points(S,Y);
s_z.set_points(S,Z);
spline_x = s_x;
spline_y = s_y;
spline_z = s_z;
}
Vector3 s2Pos(double s) const{
if(s<0.0) s = 0.0;
if(s>1.0) s = 1.0;
Vector3 Pos;
Pos.x = spline_x(s);
Pos.y = spline_y(s);
Pos.z = spline_z(s);
return Pos;
}
bool getReadyFlag() const { return ReadyFlag; }
void setReadyFlag(const bool & ReadyFlag_) { ReadyFlag = ReadyFlag_; }
tk::spline spline_x, spline_y, spline_z;
bool ReadyFlag;
std::vector<Vector3> pVec;
std::vector<double> sVec;
};
struct StagePlanningInfo{
StagePlanningInfo(){};
bool ReadyFlag;
double StageTime;
std::vector<double> UpdatedConfig;
std::vector<double> UpdatedVelocity;
};
#endif
| 38.449367 | 190 | 0.684835 | [
"geometry",
"vector",
"3d"
] |
1293a51e8bdf3030bcf7781271f20944058d55df | 7,159 | h | C | libs/screen_capture_lite/include/internal/SCCommon.h | liaoqingfu/DesktopSharing | a66744d8f1c3009a497b3ff478382894eef25287 | [
"MIT"
] | 1 | 2019-09-17T02:41:14.000Z | 2019-09-17T02:41:14.000Z | libs/screen_capture_lite/include/internal/SCCommon.h | FoxesChen/DesktopSharing | 85df8628dd8842adb1b0f169aae92909604a21f7 | [
"MIT"
] | null | null | null | libs/screen_capture_lite/include/internal/SCCommon.h | FoxesChen/DesktopSharing | 85df8628dd8842adb1b0f169aae92909604a21f7 | [
"MIT"
] | 1 | 2022-01-16T19:42:03.000Z | 2022-01-16T19:42:03.000Z | #pragma once
#include "ScreenCapture.h"
#include <atomic>
#include <thread>
// this is INTERNAL DO NOT USE!
namespace SL {
namespace Screen_Capture {
struct Point {
int x;
int y;
};
struct Monitor {
int Id = INT32_MAX;
int Index = INT32_MAX;
int Adapter = INT32_MAX;
int Height = 0;
int Width = 0;
int OriginalHeight = 0;
int OriginalWidth = 0;
// Offsets are the number of pixels that a monitor can be from the origin. For example, users can shuffle their
// monitors around so this affects their offset.
int OffsetX = 0;
int OffsetY = 0;
int OriginalOffsetX = 0;
int OriginalOffsetY = 0;
char Name[128] = { 0 };
float Scaling = 1.0f;
};
struct Window {
size_t Handle;
Point Position;
Point Size;
// Name will always be lower case. It is converted to lower case internally by the library for comparisons
char Name[128] = { 0 };
};
struct ImageRect {
ImageRect() : ImageRect(0, 0, 0, 0) {}
ImageRect(int l, int t, int r, int b) :left(l), top(t), right(r), bottom(b) {}
int left;
int top;
int right;
int bottom;
bool Contains(const ImageRect &a) const { return left <= a.left && right >= a.right && top <= a.top && bottom >= a.bottom; }
};
struct Image {
ImageRect Bounds;
int BytesToNextRow = 0;
bool isContiguous = false;
// alpha is always unused and might contain garbage
const ImageBGRA *Data = nullptr;
};
inline bool operator==(const ImageRect &a, const ImageRect &b)
{
return b.left == a.left && b.right == a.right && b.top == a.top && b.bottom == a.bottom;
}
int Height(const ImageRect &rect);
int Width(const ImageRect &rect);
const ImageRect &Rect(const Image &img);
template <typename F, typename M, typename W> struct CaptureData {
std::shared_ptr<Timer> FrameTimer;
F OnNewFrame;
F OnFrameChanged;
std::shared_ptr<Timer> MouseTimer;
M OnMouseChanged;
W getThingsToWatch;
};
struct CommonData {
// Used to indicate abnormal error condition
std::atomic<bool> UnexpectedErrorEvent;
// Used to indicate a transition event occurred e.g. PnpStop, PnpStart, mode change, TDR, desktop switch and the application needs to recreate
// the duplication interface
std::atomic<bool> ExpectedErrorEvent;
// Used to signal to threads to exit
std::atomic<bool> TerminateThreadsEvent;
std::atomic<bool> Paused;
};
struct Thread_Data {
CaptureData<ScreenCaptureCallback, MouseCallback, MonitorCallback> ScreenCaptureData;
CaptureData<WindowCaptureCallback, MouseCallback, WindowCallback> WindowCaptureData;
CommonData CommonData_;
};
class BaseFrameProcessor {
public:
std::shared_ptr<Thread_Data> Data;
std::unique_ptr<unsigned char[]> ImageBuffer;
int ImageBufferSize = 0;
bool FirstRun = true;
};
enum DUPL_RETURN { DUPL_RETURN_SUCCESS = 0, DUPL_RETURN_ERROR_EXPECTED = 1, DUPL_RETURN_ERROR_UNEXPECTED = 2 };
Monitor CreateMonitor(int index, int id, int h, int w, int ox, int oy, const std::string &n, float scale);
Monitor CreateMonitor(int index, int id, int adapter, int h, int w, int ox, int oy, const std::string &n, float scale);
SC_LITE_EXTERN bool isMonitorInsideBounds(const std::vector<Monitor> &monitors, const Monitor &monitor);
SC_LITE_EXTERN Image CreateImage(const ImageRect &imgrect, int rowpadding, const ImageBGRA *data);
// this function will copy data from the src into the dst. The only requirement is that src must not be larger than dst, but it can be smaller
// void Copy(const Image& dst, const Image& src);
SC_LITE_EXTERN std::vector<ImageRect> GetDifs(const Image &oldimg, const Image &newimg);
template <class F, class T, class C> void ProcessCapture(const F &data, T &base, const C &mointor,
const unsigned char * startsrc,
int srcrowstride
) {
ImageRect imageract;
imageract.left = 0;
imageract.top = 0;
imageract.bottom = Height(mointor);
imageract.right = Width(mointor);
const auto sizeofimgbgra = static_cast<int>(sizeof(ImageBGRA));
const auto startimgsrc = reinterpret_cast<const ImageBGRA*>(startsrc);
auto dstrowstride = sizeofimgbgra * Width(mointor);
if (data.OnNewFrame) {//each frame we still let the caller know if asked for
auto wholeimg = CreateImage(imageract, srcrowstride, startimgsrc);
wholeimg.isContiguous = dstrowstride == srcrowstride;
data.OnNewFrame(wholeimg, mointor);
}
if (data.OnFrameChanged) {//difs are needed!
if (base.FirstRun) {
// first time through, just send the whole image
auto wholeimg = CreateImage(imageract, srcrowstride, startimgsrc);
wholeimg.isContiguous = dstrowstride == srcrowstride;
data.OnFrameChanged(wholeimg, mointor);
base.FirstRun = false;
}
else {
// user wants difs, lets do it!
auto newimg = CreateImage(imageract, srcrowstride - dstrowstride, startimgsrc);
auto oldimg = CreateImage(imageract, 0, reinterpret_cast<const ImageBGRA*>(base.ImageBuffer.get()));
auto imgdifs = GetDifs(oldimg, newimg);
for (auto &r : imgdifs) {
auto leftoffset = r.left * sizeofimgbgra;
auto thisstartsrc = startsrc + leftoffset + (r.top * srcrowstride);
auto difimg = CreateImage(r, srcrowstride, reinterpret_cast<const ImageBGRA*>(thisstartsrc));
difimg.isContiguous = false;
data.OnFrameChanged(difimg, mointor);
}
}
auto startdst = base.ImageBuffer.get();
if (dstrowstride == srcrowstride) { // no need for multiple calls, there is no padding here
memcpy(startdst, startsrc, dstrowstride * Height(mointor));
}
else {
for (auto i = 0; i < Height(mointor); i++) {
memcpy(startdst + (i * dstrowstride), startsrc + (i * srcrowstride), dstrowstride);
}
}
}
}
} // namespace Screen_Capture
} // namespace SL
| 45.025157 | 154 | 0.563766 | [
"vector"
] |
1294abfa0008a83c23f7251ec03f1c4f1fe9b3dd | 3,721 | h | C | shared/ff_util/include/ff_util/ff_fsm.h | limenutt/astrobee | 9241e67e6692810d6e275abb3165b6d02f4ca5ef | [
"Apache-2.0"
] | 629 | 2017-08-31T23:09:00.000Z | 2022-03-30T11:55:40.000Z | shared/ff_util/include/ff_util/ff_fsm.h | limenutt/astrobee | 9241e67e6692810d6e275abb3165b6d02f4ca5ef | [
"Apache-2.0"
] | 269 | 2018-05-05T12:31:16.000Z | 2022-03-30T22:04:11.000Z | shared/ff_util/include/ff_util/ff_fsm.h | limenutt/astrobee | 9241e67e6692810d6e275abb3165b6d02f4ca5ef | [
"Apache-2.0"
] | 248 | 2017-08-31T23:20:56.000Z | 2022-03-30T22:29:16.000Z | /* Copyright (c) 2017, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
*
* All rights reserved.
*
* The Astrobee platform is 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 FF_UTIL_FF_FSM_H_
#define FF_UTIL_FF_FSM_H_
// C++ includes
#include <functional>
#include <utility>
#include <vector>
#include <map>
namespace ff_util {
class FSM {
public:
typedef int8_t State;
typedef uint32_t Event;
typedef std::function<State(Event const&)> TransitionCallback;
typedef std::function<State(State const&, Event const&)> CatchallCallback;
typedef std::function<void(State const&, Event const&)> UpdateCallback;
// Initialize the FSM with a given initial state
FSM(State const& initial_state,
UpdateCallback callback = nullptr) :
state_(initial_state), callback_(callback) {}
// 1-state transition
void Add(State const& s1,
Event const& mask,
TransitionCallback callback) {
for (size_t i = 0; i < 8 * sizeof(Event); i++) {
if (mask & (1 << i)) {
fsm_[std::make_pair(s1, 1 << i)] = callback;
}
}
}
// 2-state transition
void Add(State const& s1, State const& s2,
Event const& mask,
TransitionCallback callback) {
for (size_t i = 0; i < 8 * sizeof(Event); i++) {
if (mask & (1 << i)) {
fsm_[std::make_pair(s1, 1 << i)] = callback;
fsm_[std::make_pair(s2, 1 << i)] = callback;
}
}
}
// 3-state transition
void Add(State const& s1, State const& s2, State const& s3,
Event const& mask,
TransitionCallback callback) {
for (size_t i = 0; i < 8 * sizeof(Event); i++) {
if (mask & (1 << i)) {
fsm_[std::make_pair(s1, 1 << i)] = callback;
fsm_[std::make_pair(s2, 1 << i)] = callback;
fsm_[std::make_pair(s3, 1 << i)] = callback;
}
}
}
// Catch-all for a single event. Takes priority.
void Add(Event const& mask, CatchallCallback callback) {
for (size_t i = 0; i < 8 * sizeof(Event); i++)
if (mask & (1 << i)) catchall_[1 << i] = callback;
}
// Get the current state
State GetState() {
return state_;
}
// Set the current state
void SetState(State const& state) {
state_ = state;
}
// Update the state machine - we only expect one event here
void Update(Event const& event) {
// Case 1 : A catch-all event occured
if (catchall_.find(event) != catchall_.end()) {
state_ = catchall_[event](state_, event);
if (callback_)
callback_(state_, event);
return;
}
// Case 2: Valid transition in the state machine
std::pair<State, Event> key = std::make_pair(state_, event);
if (fsm_.find(key) != fsm_.end()) {
state_ = fsm_[key](event); // Call the transition function
if (callback_) // Post-update callback
callback_(state_, event);
}
// Case 3: Quietly ignore
}
private:
State state_;
std::map<std::pair<State, Event>, TransitionCallback> fsm_;
std::map<Event, CatchallCallback> catchall_;
UpdateCallback callback_;
};
} // namespace ff_util
#endif // FF_UTIL_FF_FSM_H_
| 30.008065 | 76 | 0.635582 | [
"vector"
] |
1294e4262b3e98dc5c49a313831edf92c75ca2d3 | 4,834 | h | C | folly/experimental/crypto/Blake2xb.h | lrita/folly | a315c6b038935397cddc96653e873a8985b263f6 | [
"Apache-2.0"
] | 1 | 2022-03-09T21:40:42.000Z | 2022-03-09T21:40:42.000Z | folly/experimental/crypto/Blake2xb.h | lrita/folly | a315c6b038935397cddc96653e873a8985b263f6 | [
"Apache-2.0"
] | 1 | 2022-03-28T16:56:01.000Z | 2022-03-28T16:57:07.000Z | folly/experimental/crypto/Blake2xb.h | lrita/folly | a315c6b038935397cddc96653e873a8985b263f6 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <sodium.h>
#include <folly/Range.h>
namespace folly {
namespace crypto {
namespace detail {
struct Blake2xbParam {
uint8_t digestLength; /* 1 */
uint8_t keyLength; /* 2 */
uint8_t fanout; /* 3 */
uint8_t depth; /* 4 */
uint32_t leafLength; /* 8 */
uint32_t nodeOffset; /* 12 */
uint32_t xofLength; /* 16 */
uint8_t nodeDepth; /* 17 */
uint8_t innerLength; /* 18 */
uint8_t reserved[14]; /* 32 */
uint8_t salt[16]; /* 48 */
uint8_t personal[16]; /* 64 */
};
static_assert(sizeof(Blake2xbParam) == 64, "wrong sizeof(Blake2xbParam)");
} // namespace detail
/**
* An implementation of the BLAKE2x XOF (extendable output function)
* hash function using BLAKE2b as the underlying hash. This hash function
* can produce cryptographic hashes of arbitrary length (between 1 and 2^32 - 2
* bytes) from inputs of arbitrary size. Like BLAKE2b, it can be keyed, and can
* accept optional salt and personlization parameters.
*
* Note that if you need to compute hashes between 16 and 64 bytes in length,
* you should use Blake2b instead - it's more efficient and you will have an
* easier time interoperating with other languages, since implementations of
* Blake2b are more common than implementations of Blake2xb. You can generate
* a blake2b hash using the following functions from libsodium:
* - crypto_generichash_blake2b()
* - crypto_generichash_blake2b_salt_personal()
*/
class Blake2xb {
public:
/**
* Minimum output hash size, if it is known in advance.
*/
static constexpr size_t kMinOutputLength = 1;
/**
* Maximum output hash size, if it is known in advance.
*/
static constexpr size_t kMaxOutputLength = 0xfffffffeULL;
/**
* If the amount of output data desired is not known in advance, use this
* constant as the outputLength parameter to init().
*/
static constexpr size_t kUnknownOutputLength = 0;
/**
* Creates a new uninitialized Blake2xb instance. The init() method must
* be called before it can be used.
*/
Blake2xb();
/**
* Shorthand for calling the no-argument constructor followed by
* newInstance.init(outputLength, key, salt, personlization).
*/
explicit Blake2xb(
size_t outputLength,
ByteRange key = {},
ByteRange salt = {},
ByteRange personalization = {})
: Blake2xb() {
init(outputLength, key, salt, personalization);
}
~Blake2xb();
/**
* Initializes the digest object. This must be called after a new instance
* is constructed and before update() is called. It can also be called on
* a previously-used instance to reset its internal state and reuse it for
* a new hash computation.
*/
void init(
size_t outputLength,
ByteRange key = {},
ByteRange salt = {},
ByteRange personalization = {});
/**
* Hashes some more input data.
*/
void update(ByteRange data);
/**
* Computes the final hash and stores it in the given output. The value of
* out.size() MUST equal the outputLength parameter that was given to the
* last init() call, except when the outputLength parameter was
* kUnknownOutputLength.
*
* WARNING: never compare the results of two Blake2xb.finish() calls
* using non-constant time comparison. The recommended way to compare
* cryptographic hashes is with sodium_memcmp() (or some other constant-time
* memory comparison function).
*/
void finish(MutableByteRange out);
/**
* Convenience function, use this if you are hashing a single input buffer,
* the output length is known in advance, and the output data is allocated
* and ready to accept the hash value.
*/
static void hash(
MutableByteRange out,
ByteRange data,
ByteRange key = {},
ByteRange salt = {},
ByteRange personalization = {}) {
Blake2xb d;
d.init(out.size(), key, salt, personalization);
d.update(data);
d.finish(out);
}
private:
static constexpr size_t kUnknownOutputLengthMagic = 0xffffffffULL;
detail::Blake2xbParam param_;
crypto_generichash_blake2b_state state_;
bool outputLengthKnown_;
bool initialized_;
bool finished_;
};
} // namespace crypto
} // namespace folly
| 30.594937 | 79 | 0.697766 | [
"object"
] |
129ad9b5c53f6a42b0baae4d57406c100b9049f3 | 90,484 | c | C | stub_libs/3.1/x86-64/libgtk-x11-2.0.c | mwichmann/lsb-buildenv | 7a7eb64b5960172e0032e7202aeb454e076880fa | [
"BSD-3-Clause"
] | null | null | null | stub_libs/3.1/x86-64/libgtk-x11-2.0.c | mwichmann/lsb-buildenv | 7a7eb64b5960172e0032e7202aeb454e076880fa | [
"BSD-3-Clause"
] | null | null | null | stub_libs/3.1/x86-64/libgtk-x11-2.0.c | mwichmann/lsb-buildenv | 7a7eb64b5960172e0032e7202aeb454e076880fa | [
"BSD-3-Clause"
] | null | null | null | void gtk_about_dialog_get_artists() {} ;
void gtk_about_dialog_get_authors() {} ;
void gtk_about_dialog_get_comments() {} ;
void gtk_about_dialog_get_copyright() {} ;
void gtk_about_dialog_get_documenters() {} ;
void gtk_about_dialog_get_license() {} ;
void gtk_about_dialog_get_logo() {} ;
void gtk_about_dialog_get_logo_icon_name() {} ;
void gtk_about_dialog_get_name() {} ;
void gtk_about_dialog_get_translator_credits() {} ;
void gtk_about_dialog_get_type() {} ;
void gtk_about_dialog_get_version() {} ;
void gtk_about_dialog_get_website() {} ;
void gtk_about_dialog_get_website_label() {} ;
void gtk_about_dialog_new() {} ;
void gtk_about_dialog_set_artists() {} ;
void gtk_about_dialog_set_authors() {} ;
void gtk_about_dialog_set_comments() {} ;
void gtk_about_dialog_set_copyright() {} ;
void gtk_about_dialog_set_documenters() {} ;
void gtk_about_dialog_set_email_hook() {} ;
void gtk_about_dialog_set_license() {} ;
void gtk_about_dialog_set_logo() {} ;
void gtk_about_dialog_set_logo_icon_name() {} ;
void gtk_about_dialog_set_name() {} ;
void gtk_about_dialog_set_translator_credits() {} ;
void gtk_about_dialog_set_url_hook() {} ;
void gtk_about_dialog_set_version() {} ;
void gtk_about_dialog_set_website() {} ;
void gtk_about_dialog_set_website_label() {} ;
void gtk_accel_flags_get_type() {} ;
void gtk_accel_group_activate() {} ;
void gtk_accel_group_connect() {} ;
void gtk_accel_group_connect_by_path() {} ;
void gtk_accel_group_disconnect() {} ;
void gtk_accel_group_disconnect_key() {} ;
void gtk_accel_group_find() {} ;
void gtk_accel_group_from_accel_closure() {} ;
void gtk_accel_group_get_type() {} ;
void gtk_accel_group_lock() {} ;
void gtk_accel_group_new() {} ;
void gtk_accel_group_query() {} ;
void gtk_accel_group_unlock() {} ;
void gtk_accel_groups_activate() {} ;
void gtk_accel_groups_from_object() {} ;
void gtk_accel_label_get_accel_widget() {} ;
void gtk_accel_label_get_accel_width() {} ;
void gtk_accel_label_get_type() {} ;
void gtk_accel_label_new() {} ;
void gtk_accel_label_refetch() {} ;
void gtk_accel_label_set_accel_closure() {} ;
void gtk_accel_label_set_accel_widget() {} ;
void gtk_accel_map_add_entry() {} ;
void gtk_accel_map_add_filter() {} ;
void gtk_accel_map_change_entry() {} ;
void gtk_accel_map_foreach() {} ;
void gtk_accel_map_foreach_unfiltered() {} ;
void gtk_accel_map_get() {} ;
void gtk_accel_map_get_type() {} ;
void gtk_accel_map_load() {} ;
void gtk_accel_map_load_fd() {} ;
void gtk_accel_map_load_scanner() {} ;
void gtk_accel_map_lock_path() {} ;
void gtk_accel_map_lookup_entry() {} ;
void gtk_accel_map_save() {} ;
void gtk_accel_map_save_fd() {} ;
void gtk_accel_map_unlock_path() {} ;
void gtk_accelerator_get_default_mod_mask() {} ;
void gtk_accelerator_get_label() {} ;
void gtk_accelerator_name() {} ;
void gtk_accelerator_parse() {} ;
void gtk_accelerator_set_default_mod_mask() {} ;
void gtk_accelerator_valid() {} ;
void gtk_accessible_connect_widget_destroyed() {} ;
void gtk_accessible_get_type() {} ;
void gtk_action_activate() {} ;
void gtk_action_block_activate_from() {} ;
void gtk_action_connect_accelerator() {} ;
void gtk_action_connect_proxy() {} ;
void gtk_action_create_icon() {} ;
void gtk_action_create_menu_item() {} ;
void gtk_action_create_tool_item() {} ;
void gtk_action_disconnect_accelerator() {} ;
void gtk_action_disconnect_proxy() {} ;
void gtk_action_get_accel_path() {} ;
void gtk_action_get_name() {} ;
void gtk_action_get_proxies() {} ;
void gtk_action_get_sensitive() {} ;
void gtk_action_get_type() {} ;
void gtk_action_get_visible() {} ;
void gtk_action_group_add_action() {} ;
void gtk_action_group_add_action_with_accel() {} ;
void gtk_action_group_add_actions() {} ;
void gtk_action_group_add_actions_full() {} ;
void gtk_action_group_add_radio_actions() {} ;
void gtk_action_group_add_radio_actions_full() {} ;
void gtk_action_group_add_toggle_actions() {} ;
void gtk_action_group_add_toggle_actions_full() {} ;
void gtk_action_group_get_action() {} ;
void gtk_action_group_get_name() {} ;
void gtk_action_group_get_sensitive() {} ;
void gtk_action_group_get_type() {} ;
void gtk_action_group_get_visible() {} ;
void gtk_action_group_list_actions() {} ;
void gtk_action_group_new() {} ;
void gtk_action_group_remove_action() {} ;
void gtk_action_group_set_sensitive() {} ;
void gtk_action_group_set_translate_func() {} ;
void gtk_action_group_set_translation_domain() {} ;
void gtk_action_group_set_visible() {} ;
void gtk_action_group_translate_string() {} ;
void gtk_action_is_sensitive() {} ;
void gtk_action_is_visible() {} ;
void gtk_action_new() {} ;
void gtk_action_set_accel_group() {} ;
void gtk_action_set_accel_path() {} ;
void gtk_action_set_sensitive() {} ;
void gtk_action_set_visible() {} ;
void gtk_action_unblock_activate_from() {} ;
void gtk_adjustment_changed() {} ;
void gtk_adjustment_clamp_page() {} ;
void gtk_adjustment_get_type() {} ;
void gtk_adjustment_get_value() {} ;
void gtk_adjustment_new() {} ;
void gtk_adjustment_set_value() {} ;
void gtk_adjustment_value_changed() {} ;
void gtk_alignment_get_padding() {} ;
void gtk_alignment_get_type() {} ;
void gtk_alignment_new() {} ;
void gtk_alignment_set() {} ;
void gtk_alignment_set_padding() {} ;
void gtk_alternative_dialog_button_order() {} ;
void gtk_anchor_type_get_type() {} ;
void gtk_arg_flags_get_type() {} ;
void gtk_arrow_get_type() {} ;
void gtk_arrow_new() {} ;
void gtk_arrow_set() {} ;
void gtk_arrow_type_get_type() {} ;
void gtk_aspect_frame_get_type() {} ;
void gtk_aspect_frame_new() {} ;
void gtk_aspect_frame_set() {} ;
void gtk_attach_options_get_type() {} ;
void gtk_bin_get_child() {} ;
void gtk_bin_get_type() {} ;
void gtk_binding_entry_add_signal() {} ;
void gtk_binding_entry_add_signall() {} ;
void gtk_binding_entry_clear() {} ;
void gtk_binding_entry_remove() {} ;
void gtk_binding_parse_binding() {} ;
void gtk_binding_set_activate() {} ;
void gtk_binding_set_add_path() {} ;
void gtk_binding_set_by_class() {} ;
void gtk_binding_set_find() {} ;
void gtk_binding_set_new() {} ;
void gtk_bindings_activate() {} ;
void gtk_bindings_activate_event() {} ;
void gtk_border_copy() {} ;
void gtk_border_free() {} ;
void gtk_border_get_type() {} ;
void gtk_box_get_homogeneous() {} ;
void gtk_box_get_spacing() {} ;
void gtk_box_get_type() {} ;
void gtk_box_pack_end() {} ;
void gtk_box_pack_end_defaults() {} ;
void gtk_box_pack_start() {} ;
void gtk_box_pack_start_defaults() {} ;
void gtk_box_query_child_packing() {} ;
void gtk_box_reorder_child() {} ;
void gtk_box_set_child_packing() {} ;
void gtk_box_set_homogeneous() {} ;
void gtk_box_set_spacing() {} ;
void gtk_button_box_get_child_secondary() {} ;
void gtk_button_box_get_layout() {} ;
void gtk_button_box_get_type() {} ;
void gtk_button_box_set_child_secondary() {} ;
void gtk_button_box_set_layout() {} ;
void gtk_button_box_style_get_type() {} ;
void gtk_button_clicked() {} ;
void gtk_button_enter() {} ;
void gtk_button_get_alignment() {} ;
void gtk_button_get_focus_on_click() {} ;
void gtk_button_get_image() {} ;
void gtk_button_get_label() {} ;
void gtk_button_get_relief() {} ;
void gtk_button_get_type() {} ;
void gtk_button_get_use_stock() {} ;
void gtk_button_get_use_underline() {} ;
void gtk_button_leave() {} ;
void gtk_button_new() {} ;
void gtk_button_new_from_stock() {} ;
void gtk_button_new_with_label() {} ;
void gtk_button_new_with_mnemonic() {} ;
void gtk_button_pressed() {} ;
void gtk_button_released() {} ;
void gtk_button_set_alignment() {} ;
void gtk_button_set_focus_on_click() {} ;
void gtk_button_set_image() {} ;
void gtk_button_set_label() {} ;
void gtk_button_set_relief() {} ;
void gtk_button_set_use_stock() {} ;
void gtk_button_set_use_underline() {} ;
void gtk_buttons_type_get_type() {} ;
void gtk_calendar_clear_marks() {} ;
void gtk_calendar_display_options_get_type() {} ;
void gtk_calendar_get_date() {} ;
void gtk_calendar_get_display_options() {} ;
void gtk_calendar_get_type() {} ;
void gtk_calendar_mark_day() {} ;
void gtk_calendar_new() {} ;
void gtk_calendar_select_day() {} ;
void gtk_calendar_select_month() {} ;
void gtk_calendar_set_display_options() {} ;
void gtk_calendar_unmark_day() {} ;
void gtk_cell_editable_editing_done() {} ;
void gtk_cell_editable_get_type() {} ;
void gtk_cell_editable_remove_widget() {} ;
void gtk_cell_editable_start_editing() {} ;
void gtk_cell_layout_add_attribute() {} ;
void gtk_cell_layout_clear() {} ;
void gtk_cell_layout_clear_attributes() {} ;
void gtk_cell_layout_get_type() {} ;
void gtk_cell_layout_pack_end() {} ;
void gtk_cell_layout_pack_start() {} ;
void gtk_cell_layout_reorder() {} ;
void gtk_cell_layout_set_attributes() {} ;
void gtk_cell_layout_set_cell_data_func() {} ;
void gtk_cell_renderer_activate() {} ;
void gtk_cell_renderer_combo_get_type() {} ;
void gtk_cell_renderer_combo_new() {} ;
void gtk_cell_renderer_get_fixed_size() {} ;
void gtk_cell_renderer_get_size() {} ;
void gtk_cell_renderer_get_type() {} ;
void gtk_cell_renderer_mode_get_type() {} ;
void gtk_cell_renderer_pixbuf_get_type() {} ;
void gtk_cell_renderer_pixbuf_new() {} ;
void gtk_cell_renderer_progress_get_type() {} ;
void gtk_cell_renderer_progress_new() {} ;
void gtk_cell_renderer_render() {} ;
void gtk_cell_renderer_set_fixed_size() {} ;
void gtk_cell_renderer_start_editing() {} ;
void gtk_cell_renderer_state_get_type() {} ;
void gtk_cell_renderer_stop_editing() {} ;
void gtk_cell_renderer_text_get_type() {} ;
void gtk_cell_renderer_text_new() {} ;
void gtk_cell_renderer_text_set_fixed_height_from_font() {} ;
void gtk_cell_renderer_toggle_get_active() {} ;
void gtk_cell_renderer_toggle_get_radio() {} ;
void gtk_cell_renderer_toggle_get_type() {} ;
void gtk_cell_renderer_toggle_new() {} ;
void gtk_cell_renderer_toggle_set_active() {} ;
void gtk_cell_renderer_toggle_set_radio() {} ;
void gtk_cell_view_get_cell_renderers() {} ;
void gtk_cell_view_get_displayed_row() {} ;
void gtk_cell_view_get_size_of_row() {} ;
void gtk_cell_view_get_type() {} ;
void gtk_cell_view_new() {} ;
void gtk_cell_view_new_with_markup() {} ;
void gtk_cell_view_new_with_pixbuf() {} ;
void gtk_cell_view_new_with_text() {} ;
void gtk_cell_view_set_background_color() {} ;
void gtk_cell_view_set_displayed_row() {} ;
void gtk_cell_view_set_model() {} ;
void gtk_check_button_get_type() {} ;
void gtk_check_button_new() {} ;
void gtk_check_button_new_with_label() {} ;
void gtk_check_button_new_with_mnemonic() {} ;
void gtk_check_menu_item_get_active() {} ;
void gtk_check_menu_item_get_draw_as_radio() {} ;
void gtk_check_menu_item_get_inconsistent() {} ;
void gtk_check_menu_item_get_type() {} ;
void gtk_check_menu_item_new() {} ;
void gtk_check_menu_item_new_with_label() {} ;
void gtk_check_menu_item_new_with_mnemonic() {} ;
void gtk_check_menu_item_set_active() {} ;
void gtk_check_menu_item_set_draw_as_radio() {} ;
void gtk_check_menu_item_set_inconsistent() {} ;
void gtk_check_menu_item_toggled() {} ;
void gtk_check_version() {} ;
void gtk_clipboard_clear() {} ;
void gtk_clipboard_get() {} ;
void gtk_clipboard_get_display() {} ;
void gtk_clipboard_get_for_display() {} ;
void gtk_clipboard_get_owner() {} ;
void gtk_clipboard_get_type() {} ;
void gtk_clipboard_request_contents() {} ;
void gtk_clipboard_request_image() {} ;
void gtk_clipboard_request_targets() {} ;
void gtk_clipboard_request_text() {} ;
void gtk_clipboard_set_can_store() {} ;
void gtk_clipboard_set_image() {} ;
void gtk_clipboard_set_text() {} ;
void gtk_clipboard_set_with_data() {} ;
void gtk_clipboard_set_with_owner() {} ;
void gtk_clipboard_store() {} ;
void gtk_clipboard_wait_for_contents() {} ;
void gtk_clipboard_wait_for_image() {} ;
void gtk_clipboard_wait_for_targets() {} ;
void gtk_clipboard_wait_for_text() {} ;
void gtk_clipboard_wait_is_image_available() {} ;
void gtk_clipboard_wait_is_target_available() {} ;
void gtk_clipboard_wait_is_text_available() {} ;
void gtk_color_button_get_alpha() {} ;
void gtk_color_button_get_color() {} ;
void gtk_color_button_get_title() {} ;
void gtk_color_button_get_type() {} ;
void gtk_color_button_get_use_alpha() {} ;
void gtk_color_button_new() {} ;
void gtk_color_button_new_with_color() {} ;
void gtk_color_button_set_alpha() {} ;
void gtk_color_button_set_color() {} ;
void gtk_color_button_set_title() {} ;
void gtk_color_button_set_use_alpha() {} ;
void gtk_color_selection_dialog_get_type() {} ;
void gtk_color_selection_dialog_new() {} ;
void gtk_color_selection_get_current_alpha() {} ;
void gtk_color_selection_get_current_color() {} ;
void gtk_color_selection_get_has_opacity_control() {} ;
void gtk_color_selection_get_has_palette() {} ;
void gtk_color_selection_get_previous_alpha() {} ;
void gtk_color_selection_get_previous_color() {} ;
void gtk_color_selection_get_type() {} ;
void gtk_color_selection_is_adjusting() {} ;
void gtk_color_selection_new() {} ;
void gtk_color_selection_palette_from_string() {} ;
void gtk_color_selection_palette_to_string() {} ;
void gtk_color_selection_set_change_palette_with_screen_hook() {} ;
void gtk_color_selection_set_current_alpha() {} ;
void gtk_color_selection_set_current_color() {} ;
void gtk_color_selection_set_has_opacity_control() {} ;
void gtk_color_selection_set_has_palette() {} ;
void gtk_color_selection_set_previous_alpha() {} ;
void gtk_color_selection_set_previous_color() {} ;
void gtk_combo_box_append_text() {} ;
void gtk_combo_box_entry_get_text_column() {} ;
void gtk_combo_box_entry_get_type() {} ;
void gtk_combo_box_entry_new() {} ;
void gtk_combo_box_entry_new_text() {} ;
void gtk_combo_box_entry_new_with_model() {} ;
void gtk_combo_box_entry_set_text_column() {} ;
void gtk_combo_box_get_active() {} ;
void gtk_combo_box_get_active_iter() {} ;
void gtk_combo_box_get_active_text() {} ;
void gtk_combo_box_get_add_tearoffs() {} ;
void gtk_combo_box_get_column_span_column() {} ;
void gtk_combo_box_get_focus_on_click() {} ;
void gtk_combo_box_get_model() {} ;
void gtk_combo_box_get_popup_accessible() {} ;
void gtk_combo_box_get_row_separator_func() {} ;
void gtk_combo_box_get_row_span_column() {} ;
void gtk_combo_box_get_type() {} ;
void gtk_combo_box_get_wrap_width() {} ;
void gtk_combo_box_insert_text() {} ;
void gtk_combo_box_new() {} ;
void gtk_combo_box_new_text() {} ;
void gtk_combo_box_new_with_model() {} ;
void gtk_combo_box_popdown() {} ;
void gtk_combo_box_popup() {} ;
void gtk_combo_box_prepend_text() {} ;
void gtk_combo_box_remove_text() {} ;
void gtk_combo_box_set_active() {} ;
void gtk_combo_box_set_active_iter() {} ;
void gtk_combo_box_set_add_tearoffs() {} ;
void gtk_combo_box_set_column_span_column() {} ;
void gtk_combo_box_set_focus_on_click() {} ;
void gtk_combo_box_set_model() {} ;
void gtk_combo_box_set_row_separator_func() {} ;
void gtk_combo_box_set_row_span_column() {} ;
void gtk_combo_box_set_wrap_width() {} ;
void gtk_container_add() {} ;
void gtk_container_add_with_properties() {} ;
void gtk_container_check_resize() {} ;
void gtk_container_child_get() {} ;
void gtk_container_child_get_property() {} ;
void gtk_container_child_get_valist() {} ;
void gtk_container_child_set() {} ;
void gtk_container_child_set_property() {} ;
void gtk_container_child_set_valist() {} ;
void gtk_container_child_type() {} ;
void gtk_container_class_find_child_property() {} ;
void gtk_container_class_install_child_property() {} ;
void gtk_container_class_list_child_properties() {} ;
void gtk_container_forall() {} ;
void gtk_container_foreach() {} ;
void gtk_container_get_border_width() {} ;
void gtk_container_get_children() {} ;
void gtk_container_get_focus_chain() {} ;
void gtk_container_get_focus_hadjustment() {} ;
void gtk_container_get_focus_vadjustment() {} ;
void gtk_container_get_resize_mode() {} ;
void gtk_container_get_type() {} ;
void gtk_container_propagate_expose() {} ;
void gtk_container_remove() {} ;
void gtk_container_resize_children() {} ;
void gtk_container_set_border_width() {} ;
void gtk_container_set_focus_chain() {} ;
void gtk_container_set_focus_child() {} ;
void gtk_container_set_focus_hadjustment() {} ;
void gtk_container_set_focus_vadjustment() {} ;
void gtk_container_set_reallocate_redraws() {} ;
void gtk_container_set_resize_mode() {} ;
void gtk_container_unset_focus_chain() {} ;
void gtk_corner_type_get_type() {} ;
void gtk_curve_get_type() {} ;
void gtk_curve_get_vector() {} ;
void gtk_curve_new() {} ;
void gtk_curve_reset() {} ;
void gtk_curve_set_curve_type() {} ;
void gtk_curve_set_gamma() {} ;
void gtk_curve_set_range() {} ;
void gtk_curve_set_vector() {} ;
void gtk_curve_type_get_type() {} ;
void gtk_debug_flag_get_type() {} ;
void gtk_delete_type_get_type() {} ;
void gtk_dest_defaults_get_type() {} ;
void gtk_dialog_add_action_widget() {} ;
void gtk_dialog_add_button() {} ;
void gtk_dialog_add_buttons() {} ;
void gtk_dialog_flags_get_type() {} ;
void gtk_dialog_get_has_separator() {} ;
void gtk_dialog_get_type() {} ;
void gtk_dialog_new() {} ;
void gtk_dialog_new_with_buttons() {} ;
void gtk_dialog_response() {} ;
void gtk_dialog_run() {} ;
void gtk_dialog_set_alternative_button_order() {} ;
void gtk_dialog_set_alternative_button_order_from_array() {} ;
void gtk_dialog_set_default_response() {} ;
void gtk_dialog_set_has_separator() {} ;
void gtk_dialog_set_response_sensitive() {} ;
void gtk_direction_type_get_type() {} ;
void gtk_disable_setlocale() {} ;
void gtk_drag_begin() {} ;
void gtk_drag_check_threshold() {} ;
void gtk_drag_dest_add_image_targets() {} ;
void gtk_drag_dest_add_text_targets() {} ;
void gtk_drag_dest_add_uri_targets() {} ;
void gtk_drag_dest_find_target() {} ;
void gtk_drag_dest_get_target_list() {} ;
void gtk_drag_dest_set() {} ;
void gtk_drag_dest_set_proxy() {} ;
void gtk_drag_dest_set_target_list() {} ;
void gtk_drag_dest_unset() {} ;
void gtk_drag_finish() {} ;
void gtk_drag_get_data() {} ;
void gtk_drag_get_source_widget() {} ;
void gtk_drag_highlight() {} ;
void gtk_drag_set_icon_default() {} ;
void gtk_drag_set_icon_pixbuf() {} ;
void gtk_drag_set_icon_pixmap() {} ;
void gtk_drag_set_icon_stock() {} ;
void gtk_drag_set_icon_widget() {} ;
void gtk_drag_source_add_image_targets() {} ;
void gtk_drag_source_add_text_targets() {} ;
void gtk_drag_source_add_uri_targets() {} ;
void gtk_drag_source_get_target_list() {} ;
void gtk_drag_source_set() {} ;
void gtk_drag_source_set_icon() {} ;
void gtk_drag_source_set_icon_pixbuf() {} ;
void gtk_drag_source_set_icon_stock() {} ;
void gtk_drag_source_set_target_list() {} ;
void gtk_drag_source_unset() {} ;
void gtk_drag_unhighlight() {} ;
void gtk_draw_insertion_cursor() {} ;
void gtk_drawing_area_get_type() {} ;
void gtk_drawing_area_new() {} ;
void gtk_editable_copy_clipboard() {} ;
void gtk_editable_cut_clipboard() {} ;
void gtk_editable_delete_selection() {} ;
void gtk_editable_delete_text() {} ;
void gtk_editable_get_chars() {} ;
void gtk_editable_get_editable() {} ;
void gtk_editable_get_position() {} ;
void gtk_editable_get_selection_bounds() {} ;
void gtk_editable_get_type() {} ;
void gtk_editable_insert_text() {} ;
void gtk_editable_paste_clipboard() {} ;
void gtk_editable_select_region() {} ;
void gtk_editable_set_editable() {} ;
void gtk_editable_set_position() {} ;
void gtk_entry_completion_complete() {} ;
void gtk_entry_completion_delete_action() {} ;
void gtk_entry_completion_get_entry() {} ;
void gtk_entry_completion_get_inline_completion() {} ;
void gtk_entry_completion_get_minimum_key_length() {} ;
void gtk_entry_completion_get_model() {} ;
void gtk_entry_completion_get_popup_completion() {} ;
void gtk_entry_completion_get_text_column() {} ;
void gtk_entry_completion_get_type() {} ;
void gtk_entry_completion_insert_action_markup() {} ;
void gtk_entry_completion_insert_action_text() {} ;
void gtk_entry_completion_insert_prefix() {} ;
void gtk_entry_completion_new() {} ;
void gtk_entry_completion_set_inline_completion() {} ;
void gtk_entry_completion_set_match_func() {} ;
void gtk_entry_completion_set_minimum_key_length() {} ;
void gtk_entry_completion_set_model() {} ;
void gtk_entry_completion_set_popup_completion() {} ;
void gtk_entry_completion_set_text_column() {} ;
void gtk_entry_get_activates_default() {} ;
void gtk_entry_get_alignment() {} ;
void gtk_entry_get_completion() {} ;
void gtk_entry_get_has_frame() {} ;
void gtk_entry_get_invisible_char() {} ;
void gtk_entry_get_layout() {} ;
void gtk_entry_get_layout_offsets() {} ;
void gtk_entry_get_max_length() {} ;
void gtk_entry_get_text() {} ;
void gtk_entry_get_type() {} ;
void gtk_entry_get_visibility() {} ;
void gtk_entry_get_width_chars() {} ;
void gtk_entry_layout_index_to_text_index() {} ;
void gtk_entry_new() {} ;
void gtk_entry_set_activates_default() {} ;
void gtk_entry_set_alignment() {} ;
void gtk_entry_set_completion() {} ;
void gtk_entry_set_has_frame() {} ;
void gtk_entry_set_invisible_char() {} ;
void gtk_entry_set_max_length() {} ;
void gtk_entry_set_text() {} ;
void gtk_entry_set_visibility() {} ;
void gtk_entry_set_width_chars() {} ;
void gtk_entry_text_index_to_layout_index() {} ;
void gtk_event_box_get_above_child() {} ;
void gtk_event_box_get_type() {} ;
void gtk_event_box_get_visible_window() {} ;
void gtk_event_box_new() {} ;
void gtk_event_box_set_above_child() {} ;
void gtk_event_box_set_visible_window() {} ;
void gtk_events_pending() {} ;
void gtk_expander_get_expanded() {} ;
void gtk_expander_get_label() {} ;
void gtk_expander_get_label_widget() {} ;
void gtk_expander_get_spacing() {} ;
void gtk_expander_get_type() {} ;
void gtk_expander_get_use_markup() {} ;
void gtk_expander_get_use_underline() {} ;
void gtk_expander_new() {} ;
void gtk_expander_new_with_mnemonic() {} ;
void gtk_expander_set_expanded() {} ;
void gtk_expander_set_label() {} ;
void gtk_expander_set_label_widget() {} ;
void gtk_expander_set_spacing() {} ;
void gtk_expander_set_use_markup() {} ;
void gtk_expander_set_use_underline() {} ;
void gtk_expander_style_get_type() {} ;
void gtk_false() {} ;
void gtk_file_chooser_action_get_type() {} ;
void gtk_file_chooser_add_filter() {} ;
void gtk_file_chooser_add_shortcut_folder() {} ;
void gtk_file_chooser_add_shortcut_folder_uri() {} ;
void gtk_file_chooser_button_get_title() {} ;
void gtk_file_chooser_button_get_type() {} ;
void gtk_file_chooser_button_get_width_chars() {} ;
void gtk_file_chooser_button_new() {} ;
void gtk_file_chooser_button_new_with_backend() {} ;
void gtk_file_chooser_button_new_with_dialog() {} ;
void gtk_file_chooser_button_set_title() {} ;
void gtk_file_chooser_button_set_width_chars() {} ;
void gtk_file_chooser_dialog_get_type() {} ;
void gtk_file_chooser_dialog_new() {} ;
void gtk_file_chooser_dialog_new_with_backend() {} ;
void gtk_file_chooser_error_get_type() {} ;
void gtk_file_chooser_error_quark() {} ;
void gtk_file_chooser_get_action() {} ;
void gtk_file_chooser_get_current_folder() {} ;
void gtk_file_chooser_get_current_folder_uri() {} ;
void gtk_file_chooser_get_extra_widget() {} ;
void gtk_file_chooser_get_filename() {} ;
void gtk_file_chooser_get_filenames() {} ;
void gtk_file_chooser_get_filter() {} ;
void gtk_file_chooser_get_local_only() {} ;
void gtk_file_chooser_get_preview_filename() {} ;
void gtk_file_chooser_get_preview_uri() {} ;
void gtk_file_chooser_get_preview_widget() {} ;
void gtk_file_chooser_get_preview_widget_active() {} ;
void gtk_file_chooser_get_select_multiple() {} ;
void gtk_file_chooser_get_show_hidden() {} ;
void gtk_file_chooser_get_type() {} ;
void gtk_file_chooser_get_uri() {} ;
void gtk_file_chooser_get_uris() {} ;
void gtk_file_chooser_get_use_preview_label() {} ;
void gtk_file_chooser_list_filters() {} ;
void gtk_file_chooser_list_shortcut_folder_uris() {} ;
void gtk_file_chooser_list_shortcut_folders() {} ;
void gtk_file_chooser_remove_filter() {} ;
void gtk_file_chooser_remove_shortcut_folder() {} ;
void gtk_file_chooser_remove_shortcut_folder_uri() {} ;
void gtk_file_chooser_select_all() {} ;
void gtk_file_chooser_select_filename() {} ;
void gtk_file_chooser_select_uri() {} ;
void gtk_file_chooser_set_action() {} ;
void gtk_file_chooser_set_current_folder() {} ;
void gtk_file_chooser_set_current_folder_uri() {} ;
void gtk_file_chooser_set_current_name() {} ;
void gtk_file_chooser_set_extra_widget() {} ;
void gtk_file_chooser_set_filename() {} ;
void gtk_file_chooser_set_filter() {} ;
void gtk_file_chooser_set_local_only() {} ;
void gtk_file_chooser_set_preview_widget() {} ;
void gtk_file_chooser_set_preview_widget_active() {} ;
void gtk_file_chooser_set_select_multiple() {} ;
void gtk_file_chooser_set_show_hidden() {} ;
void gtk_file_chooser_set_uri() {} ;
void gtk_file_chooser_set_use_preview_label() {} ;
void gtk_file_chooser_unselect_all() {} ;
void gtk_file_chooser_unselect_filename() {} ;
void gtk_file_chooser_unselect_uri() {} ;
void gtk_file_chooser_widget_get_type() {} ;
void gtk_file_chooser_widget_new() {} ;
void gtk_file_chooser_widget_new_with_backend() {} ;
void gtk_file_filter_add_custom() {} ;
void gtk_file_filter_add_mime_type() {} ;
void gtk_file_filter_add_pattern() {} ;
void gtk_file_filter_add_pixbuf_formats() {} ;
void gtk_file_filter_filter() {} ;
void gtk_file_filter_flags_get_type() {} ;
void gtk_file_filter_get_name() {} ;
void gtk_file_filter_get_needed() {} ;
void gtk_file_filter_get_type() {} ;
void gtk_file_filter_new() {} ;
void gtk_file_filter_set_name() {} ;
void gtk_file_selection_complete() {} ;
void gtk_file_selection_get_filename() {} ;
void gtk_file_selection_get_select_multiple() {} ;
void gtk_file_selection_get_selections() {} ;
void gtk_file_selection_get_type() {} ;
void gtk_file_selection_hide_fileop_buttons() {} ;
void gtk_file_selection_new() {} ;
void gtk_file_selection_set_filename() {} ;
void gtk_file_selection_set_select_multiple() {} ;
void gtk_file_selection_show_fileop_buttons() {} ;
void gtk_fixed_get_has_window() {} ;
void gtk_fixed_get_type() {} ;
void gtk_fixed_move() {} ;
void gtk_fixed_new() {} ;
void gtk_fixed_put() {} ;
void gtk_fixed_set_has_window() {} ;
void gtk_font_button_get_font_name() {} ;
void gtk_font_button_get_show_size() {} ;
void gtk_font_button_get_show_style() {} ;
void gtk_font_button_get_title() {} ;
void gtk_font_button_get_type() {} ;
void gtk_font_button_get_use_font() {} ;
void gtk_font_button_get_use_size() {} ;
void gtk_font_button_new() {} ;
void gtk_font_button_new_with_font() {} ;
void gtk_font_button_set_font_name() {} ;
void gtk_font_button_set_show_size() {} ;
void gtk_font_button_set_show_style() {} ;
void gtk_font_button_set_title() {} ;
void gtk_font_button_set_use_font() {} ;
void gtk_font_button_set_use_size() {} ;
void gtk_font_selection_dialog_get_font_name() {} ;
void gtk_font_selection_dialog_get_preview_text() {} ;
void gtk_font_selection_dialog_get_type() {} ;
void gtk_font_selection_dialog_new() {} ;
void gtk_font_selection_dialog_set_font_name() {} ;
void gtk_font_selection_dialog_set_preview_text() {} ;
void gtk_font_selection_get_font_name() {} ;
void gtk_font_selection_get_preview_text() {} ;
void gtk_font_selection_get_type() {} ;
void gtk_font_selection_new() {} ;
void gtk_font_selection_set_font_name() {} ;
void gtk_font_selection_set_preview_text() {} ;
void gtk_frame_get_label() {} ;
void gtk_frame_get_label_align() {} ;
void gtk_frame_get_label_widget() {} ;
void gtk_frame_get_shadow_type() {} ;
void gtk_frame_get_type() {} ;
void gtk_frame_new() {} ;
void gtk_frame_set_label() {} ;
void gtk_frame_set_label_align() {} ;
void gtk_frame_set_label_widget() {} ;
void gtk_frame_set_shadow_type() {} ;
void gtk_gamma_curve_get_type() {} ;
void gtk_gamma_curve_new() {} ;
void gtk_gc_get() {} ;
void gtk_gc_release() {} ;
void gtk_get_current_event() {} ;
void gtk_get_current_event_state() {} ;
void gtk_get_current_event_time() {} ;
void gtk_get_default_language() {} ;
void gtk_get_event_widget() {} ;
void gtk_get_option_group() {} ;
void gtk_grab_add() {} ;
void gtk_grab_get_current() {} ;
void gtk_grab_remove() {} ;
void gtk_handle_box_get_handle_position() {} ;
void gtk_handle_box_get_shadow_type() {} ;
void gtk_handle_box_get_snap_edge() {} ;
void gtk_handle_box_get_type() {} ;
void gtk_handle_box_new() {} ;
void gtk_handle_box_set_handle_position() {} ;
void gtk_handle_box_set_shadow_type() {} ;
void gtk_handle_box_set_snap_edge() {} ;
void gtk_hbox_get_type() {} ;
void gtk_hbox_new() {} ;
void gtk_hbutton_box_get_type() {} ;
void gtk_hbutton_box_new() {} ;
void gtk_hpaned_get_type() {} ;
void gtk_hpaned_new() {} ;
void gtk_hruler_get_type() {} ;
void gtk_hruler_new() {} ;
void gtk_hscale_get_type() {} ;
void gtk_hscale_new() {} ;
void gtk_hscale_new_with_range() {} ;
void gtk_hscrollbar_get_type() {} ;
void gtk_hscrollbar_new() {} ;
void gtk_hseparator_get_type() {} ;
void gtk_hseparator_new() {} ;
void gtk_icon_factory_add() {} ;
void gtk_icon_factory_add_default() {} ;
void gtk_icon_factory_get_type() {} ;
void gtk_icon_factory_lookup() {} ;
void gtk_icon_factory_lookup_default() {} ;
void gtk_icon_factory_new() {} ;
void gtk_icon_factory_remove_default() {} ;
void gtk_icon_info_copy() {} ;
void gtk_icon_info_free() {} ;
void gtk_icon_info_get_attach_points() {} ;
void gtk_icon_info_get_base_size() {} ;
void gtk_icon_info_get_builtin_pixbuf() {} ;
void gtk_icon_info_get_display_name() {} ;
void gtk_icon_info_get_embedded_rect() {} ;
void gtk_icon_info_get_filename() {} ;
void gtk_icon_info_get_type() {} ;
void gtk_icon_info_load_icon() {} ;
void gtk_icon_info_set_raw_coordinates() {} ;
void gtk_icon_lookup_flags_get_type() {} ;
void gtk_icon_set_add_source() {} ;
void gtk_icon_set_copy() {} ;
void gtk_icon_set_get_sizes() {} ;
void gtk_icon_set_get_type() {} ;
void gtk_icon_set_new() {} ;
void gtk_icon_set_new_from_pixbuf() {} ;
void gtk_icon_set_ref() {} ;
void gtk_icon_set_render_icon() {} ;
void gtk_icon_set_unref() {} ;
void gtk_icon_size_from_name() {} ;
void gtk_icon_size_get_name() {} ;
void gtk_icon_size_get_type() {} ;
void gtk_icon_size_lookup() {} ;
void gtk_icon_size_lookup_for_settings() {} ;
void gtk_icon_size_register() {} ;
void gtk_icon_size_register_alias() {} ;
void gtk_icon_source_copy() {} ;
void gtk_icon_source_free() {} ;
void gtk_icon_source_get_direction() {} ;
void gtk_icon_source_get_direction_wildcarded() {} ;
void gtk_icon_source_get_filename() {} ;
void gtk_icon_source_get_icon_name() {} ;
void gtk_icon_source_get_pixbuf() {} ;
void gtk_icon_source_get_size() {} ;
void gtk_icon_source_get_size_wildcarded() {} ;
void gtk_icon_source_get_state() {} ;
void gtk_icon_source_get_state_wildcarded() {} ;
void gtk_icon_source_get_type() {} ;
void gtk_icon_source_new() {} ;
void gtk_icon_source_set_direction() {} ;
void gtk_icon_source_set_direction_wildcarded() {} ;
void gtk_icon_source_set_filename() {} ;
void gtk_icon_source_set_icon_name() {} ;
void gtk_icon_source_set_pixbuf() {} ;
void gtk_icon_source_set_size() {} ;
void gtk_icon_source_set_size_wildcarded() {} ;
void gtk_icon_source_set_state() {} ;
void gtk_icon_source_set_state_wildcarded() {} ;
void gtk_icon_theme_add_builtin_icon() {} ;
void gtk_icon_theme_append_search_path() {} ;
void gtk_icon_theme_error_get_type() {} ;
void gtk_icon_theme_error_quark() {} ;
void gtk_icon_theme_get_default() {} ;
void gtk_icon_theme_get_example_icon_name() {} ;
void gtk_icon_theme_get_for_screen() {} ;
void gtk_icon_theme_get_icon_sizes() {} ;
void gtk_icon_theme_get_search_path() {} ;
void gtk_icon_theme_get_type() {} ;
void gtk_icon_theme_has_icon() {} ;
void gtk_icon_theme_list_icons() {} ;
void gtk_icon_theme_load_icon() {} ;
void gtk_icon_theme_lookup_icon() {} ;
void gtk_icon_theme_new() {} ;
void gtk_icon_theme_prepend_search_path() {} ;
void gtk_icon_theme_rescan_if_needed() {} ;
void gtk_icon_theme_set_custom_theme() {} ;
void gtk_icon_theme_set_screen() {} ;
void gtk_icon_theme_set_search_path() {} ;
void gtk_icon_view_get_column_spacing() {} ;
void gtk_icon_view_get_columns() {} ;
void gtk_icon_view_get_item_width() {} ;
void gtk_icon_view_get_margin() {} ;
void gtk_icon_view_get_markup_column() {} ;
void gtk_icon_view_get_model() {} ;
void gtk_icon_view_get_orientation() {} ;
void gtk_icon_view_get_path_at_pos() {} ;
void gtk_icon_view_get_pixbuf_column() {} ;
void gtk_icon_view_get_row_spacing() {} ;
void gtk_icon_view_get_selected_items() {} ;
void gtk_icon_view_get_selection_mode() {} ;
void gtk_icon_view_get_spacing() {} ;
void gtk_icon_view_get_text_column() {} ;
void gtk_icon_view_get_type() {} ;
void gtk_icon_view_item_activated() {} ;
void gtk_icon_view_new() {} ;
void gtk_icon_view_new_with_model() {} ;
void gtk_icon_view_path_is_selected() {} ;
void gtk_icon_view_select_all() {} ;
void gtk_icon_view_select_path() {} ;
void gtk_icon_view_selected_foreach() {} ;
void gtk_icon_view_set_column_spacing() {} ;
void gtk_icon_view_set_columns() {} ;
void gtk_icon_view_set_item_width() {} ;
void gtk_icon_view_set_margin() {} ;
void gtk_icon_view_set_markup_column() {} ;
void gtk_icon_view_set_model() {} ;
void gtk_icon_view_set_orientation() {} ;
void gtk_icon_view_set_pixbuf_column() {} ;
void gtk_icon_view_set_row_spacing() {} ;
void gtk_icon_view_set_selection_mode() {} ;
void gtk_icon_view_set_spacing() {} ;
void gtk_icon_view_set_text_column() {} ;
void gtk_icon_view_unselect_all() {} ;
void gtk_icon_view_unselect_path() {} ;
void gtk_identifier_get_type() {} ;
void gtk_im_context_delete_surrounding() {} ;
void gtk_im_context_filter_keypress() {} ;
void gtk_im_context_focus_in() {} ;
void gtk_im_context_focus_out() {} ;
void gtk_im_context_get_preedit_string() {} ;
void gtk_im_context_get_surrounding() {} ;
void gtk_im_context_get_type() {} ;
void gtk_im_context_reset() {} ;
void gtk_im_context_set_client_window() {} ;
void gtk_im_context_set_cursor_location() {} ;
void gtk_im_context_set_surrounding() {} ;
void gtk_im_context_set_use_preedit() {} ;
void gtk_im_context_simple_add_table() {} ;
void gtk_im_context_simple_get_type() {} ;
void gtk_im_context_simple_new() {} ;
void gtk_im_multicontext_append_menuitems() {} ;
void gtk_im_multicontext_get_type() {} ;
void gtk_im_multicontext_new() {} ;
void gtk_im_preedit_style_get_type() {} ;
void gtk_im_status_style_get_type() {} ;
void gtk_image_get_animation() {} ;
void gtk_image_get_icon_name() {} ;
void gtk_image_get_icon_set() {} ;
void gtk_image_get_image() {} ;
void gtk_image_get_pixbuf() {} ;
void gtk_image_get_pixel_size() {} ;
void gtk_image_get_pixmap() {} ;
void gtk_image_get_stock() {} ;
void gtk_image_get_storage_type() {} ;
void gtk_image_get_type() {} ;
void gtk_image_menu_item_get_image() {} ;
void gtk_image_menu_item_get_type() {} ;
void gtk_image_menu_item_new() {} ;
void gtk_image_menu_item_new_from_stock() {} ;
void gtk_image_menu_item_new_with_label() {} ;
void gtk_image_menu_item_new_with_mnemonic() {} ;
void gtk_image_menu_item_set_image() {} ;
void gtk_image_new() {} ;
void gtk_image_new_from_animation() {} ;
void gtk_image_new_from_file() {} ;
void gtk_image_new_from_icon_name() {} ;
void gtk_image_new_from_icon_set() {} ;
void gtk_image_new_from_image() {} ;
void gtk_image_new_from_pixbuf() {} ;
void gtk_image_new_from_pixmap() {} ;
void gtk_image_new_from_stock() {} ;
void gtk_image_set_from_animation() {} ;
void gtk_image_set_from_file() {} ;
void gtk_image_set_from_icon_name() {} ;
void gtk_image_set_from_icon_set() {} ;
void gtk_image_set_from_image() {} ;
void gtk_image_set_from_pixbuf() {} ;
void gtk_image_set_from_pixmap() {} ;
void gtk_image_set_from_stock() {} ;
void gtk_image_set_pixel_size() {} ;
void gtk_image_type_get_type() {} ;
void gtk_init() {} ;
void gtk_init_add() {} ;
void gtk_init_check() {} ;
void gtk_init_with_args() {} ;
void gtk_input_dialog_get_type() {} ;
void gtk_input_dialog_new() {} ;
void gtk_invisible_get_screen() {} ;
void gtk_invisible_get_type() {} ;
void gtk_invisible_new() {} ;
void gtk_invisible_new_for_screen() {} ;
void gtk_invisible_set_screen() {} ;
void gtk_item_deselect() {} ;
void gtk_item_get_type() {} ;
void gtk_item_select() {} ;
void gtk_item_toggle() {} ;
void gtk_justification_get_type() {} ;
void gtk_key_snooper_install() {} ;
void gtk_key_snooper_remove() {} ;
void gtk_label_get_angle() {} ;
void gtk_label_get_attributes() {} ;
void gtk_label_get_ellipsize() {} ;
void gtk_label_get_justify() {} ;
void gtk_label_get_label() {} ;
void gtk_label_get_layout() {} ;
void gtk_label_get_layout_offsets() {} ;
void gtk_label_get_line_wrap() {} ;
void gtk_label_get_max_width_chars() {} ;
void gtk_label_get_mnemonic_keyval() {} ;
void gtk_label_get_mnemonic_widget() {} ;
void gtk_label_get_selectable() {} ;
void gtk_label_get_selection_bounds() {} ;
void gtk_label_get_single_line_mode() {} ;
void gtk_label_get_text() {} ;
void gtk_label_get_type() {} ;
void gtk_label_get_use_markup() {} ;
void gtk_label_get_use_underline() {} ;
void gtk_label_get_width_chars() {} ;
void gtk_label_new() {} ;
void gtk_label_new_with_mnemonic() {} ;
void gtk_label_select_region() {} ;
void gtk_label_set_angle() {} ;
void gtk_label_set_attributes() {} ;
void gtk_label_set_ellipsize() {} ;
void gtk_label_set_justify() {} ;
void gtk_label_set_label() {} ;
void gtk_label_set_line_wrap() {} ;
void gtk_label_set_markup() {} ;
void gtk_label_set_markup_with_mnemonic() {} ;
void gtk_label_set_max_width_chars() {} ;
void gtk_label_set_mnemonic_widget() {} ;
void gtk_label_set_pattern() {} ;
void gtk_label_set_selectable() {} ;
void gtk_label_set_single_line_mode() {} ;
void gtk_label_set_text() {} ;
void gtk_label_set_text_with_mnemonic() {} ;
void gtk_label_set_use_markup() {} ;
void gtk_label_set_use_underline() {} ;
void gtk_label_set_width_chars() {} ;
void gtk_layout_get_hadjustment() {} ;
void gtk_layout_get_size() {} ;
void gtk_layout_get_type() {} ;
void gtk_layout_get_vadjustment() {} ;
void gtk_layout_move() {} ;
void gtk_layout_new() {} ;
void gtk_layout_put() {} ;
void gtk_layout_set_hadjustment() {} ;
void gtk_layout_set_size() {} ;
void gtk_layout_set_vadjustment() {} ;
void gtk_list_store_append() {} ;
void gtk_list_store_clear() {} ;
void gtk_list_store_get_type() {} ;
void gtk_list_store_insert() {} ;
void gtk_list_store_insert_after() {} ;
void gtk_list_store_insert_before() {} ;
void gtk_list_store_insert_with_values() {} ;
void gtk_list_store_insert_with_valuesv() {} ;
void gtk_list_store_iter_is_valid() {} ;
void gtk_list_store_move_after() {} ;
void gtk_list_store_move_before() {} ;
void gtk_list_store_new() {} ;
void gtk_list_store_newv() {} ;
void gtk_list_store_prepend() {} ;
void gtk_list_store_remove() {} ;
void gtk_list_store_reorder() {} ;
void gtk_list_store_set() {} ;
void gtk_list_store_set_column_types() {} ;
void gtk_list_store_set_valist() {} ;
void gtk_list_store_set_value() {} ;
void gtk_list_store_swap() {} ;
void gtk_main() {} ;
void gtk_main_do_event() {} ;
void gtk_main_iteration() {} ;
void gtk_main_iteration_do() {} ;
void gtk_main_level() {} ;
void gtk_main_quit() {} ;
void gtk_match_type_get_type() {} ;
void gtk_menu_attach() {} ;
void gtk_menu_attach_to_widget() {} ;
void gtk_menu_bar_get_type() {} ;
void gtk_menu_bar_new() {} ;
void gtk_menu_detach() {} ;
void gtk_menu_direction_type_get_type() {} ;
void gtk_menu_get_accel_group() {} ;
void gtk_menu_get_active() {} ;
void gtk_menu_get_attach_widget() {} ;
void gtk_menu_get_for_attach_widget() {} ;
void gtk_menu_get_tearoff_state() {} ;
void gtk_menu_get_title() {} ;
void gtk_menu_get_type() {} ;
void gtk_menu_item_activate() {} ;
void gtk_menu_item_deselect() {} ;
void gtk_menu_item_get_right_justified() {} ;
void gtk_menu_item_get_submenu() {} ;
void gtk_menu_item_get_type() {} ;
void gtk_menu_item_new() {} ;
void gtk_menu_item_new_with_label() {} ;
void gtk_menu_item_new_with_mnemonic() {} ;
void gtk_menu_item_remove_submenu() {} ;
void gtk_menu_item_select() {} ;
void gtk_menu_item_set_accel_path() {} ;
void gtk_menu_item_set_right_justified() {} ;
void gtk_menu_item_set_submenu() {} ;
void gtk_menu_item_toggle_size_allocate() {} ;
void gtk_menu_item_toggle_size_request() {} ;
void gtk_menu_new() {} ;
void gtk_menu_popdown() {} ;
void gtk_menu_popup() {} ;
void gtk_menu_reorder_child() {} ;
void gtk_menu_reposition() {} ;
void gtk_menu_set_accel_group() {} ;
void gtk_menu_set_accel_path() {} ;
void gtk_menu_set_active() {} ;
void gtk_menu_set_monitor() {} ;
void gtk_menu_set_screen() {} ;
void gtk_menu_set_tearoff_state() {} ;
void gtk_menu_set_title() {} ;
void gtk_menu_shell_activate_item() {} ;
void gtk_menu_shell_append() {} ;
void gtk_menu_shell_cancel() {} ;
void gtk_menu_shell_deactivate() {} ;
void gtk_menu_shell_deselect() {} ;
void gtk_menu_shell_get_type() {} ;
void gtk_menu_shell_insert() {} ;
void gtk_menu_shell_prepend() {} ;
void gtk_menu_shell_select_first() {} ;
void gtk_menu_shell_select_item() {} ;
void gtk_menu_tool_button_get_menu() {} ;
void gtk_menu_tool_button_get_type() {} ;
void gtk_menu_tool_button_new() {} ;
void gtk_menu_tool_button_new_from_stock() {} ;
void gtk_menu_tool_button_set_arrow_tooltip() {} ;
void gtk_menu_tool_button_set_menu() {} ;
void gtk_message_dialog_format_secondary_markup() {} ;
void gtk_message_dialog_format_secondary_text() {} ;
void gtk_message_dialog_get_type() {} ;
void gtk_message_dialog_new() {} ;
void gtk_message_dialog_new_with_markup() {} ;
void gtk_message_dialog_set_markup() {} ;
void gtk_message_type_get_type() {} ;
void gtk_metric_type_get_type() {} ;
void gtk_misc_get_alignment() {} ;
void gtk_misc_get_padding() {} ;
void gtk_misc_get_type() {} ;
void gtk_misc_set_alignment() {} ;
void gtk_misc_set_padding() {} ;
void gtk_movement_step_get_type() {} ;
void gtk_notebook_append_page() {} ;
void gtk_notebook_append_page_menu() {} ;
void gtk_notebook_get_current_page() {} ;
void gtk_notebook_get_menu_label() {} ;
void gtk_notebook_get_menu_label_text() {} ;
void gtk_notebook_get_n_pages() {} ;
void gtk_notebook_get_nth_page() {} ;
void gtk_notebook_get_scrollable() {} ;
void gtk_notebook_get_show_border() {} ;
void gtk_notebook_get_show_tabs() {} ;
void gtk_notebook_get_tab_label() {} ;
void gtk_notebook_get_tab_label_text() {} ;
void gtk_notebook_get_tab_pos() {} ;
void gtk_notebook_get_type() {} ;
void gtk_notebook_insert_page() {} ;
void gtk_notebook_insert_page_menu() {} ;
void gtk_notebook_new() {} ;
void gtk_notebook_next_page() {} ;
void gtk_notebook_page_num() {} ;
void gtk_notebook_popup_disable() {} ;
void gtk_notebook_popup_enable() {} ;
void gtk_notebook_prepend_page() {} ;
void gtk_notebook_prepend_page_menu() {} ;
void gtk_notebook_prev_page() {} ;
void gtk_notebook_query_tab_label_packing() {} ;
void gtk_notebook_remove_page() {} ;
void gtk_notebook_reorder_child() {} ;
void gtk_notebook_set_current_page() {} ;
void gtk_notebook_set_menu_label() {} ;
void gtk_notebook_set_menu_label_text() {} ;
void gtk_notebook_set_scrollable() {} ;
void gtk_notebook_set_show_border() {} ;
void gtk_notebook_set_show_tabs() {} ;
void gtk_notebook_set_tab_label() {} ;
void gtk_notebook_set_tab_label_packing() {} ;
void gtk_notebook_set_tab_label_text() {} ;
void gtk_notebook_set_tab_pos() {} ;
void gtk_notebook_tab_get_type() {} ;
void gtk_object_destroy() {} ;
void gtk_object_flags_get_type() {} ;
void gtk_object_get_type() {} ;
void gtk_object_sink() {} ;
void gtk_orientation_get_type() {} ;
void gtk_pack_type_get_type() {} ;
void gtk_paint_arrow() {} ;
void gtk_paint_box() {} ;
void gtk_paint_box_gap() {} ;
void gtk_paint_check() {} ;
void gtk_paint_diamond() {} ;
void gtk_paint_expander() {} ;
void gtk_paint_extension() {} ;
void gtk_paint_flat_box() {} ;
void gtk_paint_focus() {} ;
void gtk_paint_handle() {} ;
void gtk_paint_hline() {} ;
void gtk_paint_layout() {} ;
void gtk_paint_option() {} ;
void gtk_paint_polygon() {} ;
void gtk_paint_resize_grip() {} ;
void gtk_paint_shadow() {} ;
void gtk_paint_shadow_gap() {} ;
void gtk_paint_slider() {} ;
void gtk_paint_tab() {} ;
void gtk_paint_vline() {} ;
void gtk_paned_add1() {} ;
void gtk_paned_add2() {} ;
void gtk_paned_get_child1() {} ;
void gtk_paned_get_child2() {} ;
void gtk_paned_get_position() {} ;
void gtk_paned_get_type() {} ;
void gtk_paned_pack1() {} ;
void gtk_paned_pack2() {} ;
void gtk_paned_set_position() {} ;
void gtk_parse_args() {} ;
void gtk_path_priority_type_get_type() {} ;
void gtk_path_type_get_type() {} ;
void gtk_plug_construct() {} ;
void gtk_plug_construct_for_display() {} ;
void gtk_plug_get_id() {} ;
void gtk_plug_get_type() {} ;
void gtk_plug_new() {} ;
void gtk_plug_new_for_display() {} ;
void gtk_policy_type_get_type() {} ;
void gtk_position_type_get_type() {} ;
void gtk_progress_bar_get_ellipsize() {} ;
void gtk_progress_bar_get_fraction() {} ;
void gtk_progress_bar_get_orientation() {} ;
void gtk_progress_bar_get_pulse_step() {} ;
void gtk_progress_bar_get_text() {} ;
void gtk_progress_bar_get_type() {} ;
void gtk_progress_bar_new() {} ;
void gtk_progress_bar_orientation_get_type() {} ;
void gtk_progress_bar_pulse() {} ;
void gtk_progress_bar_set_ellipsize() {} ;
void gtk_progress_bar_set_fraction() {} ;
void gtk_progress_bar_set_orientation() {} ;
void gtk_progress_bar_set_pulse_step() {} ;
void gtk_progress_bar_set_text() {} ;
void gtk_progress_bar_style_get_type() {} ;
void gtk_propagate_event() {} ;
void gtk_quit_add() {} ;
void gtk_quit_add_destroy() {} ;
void gtk_quit_add_full() {} ;
void gtk_quit_remove() {} ;
void gtk_quit_remove_by_data() {} ;
void gtk_radio_action_get_current_value() {} ;
void gtk_radio_action_get_group() {} ;
void gtk_radio_action_get_type() {} ;
void gtk_radio_action_new() {} ;
void gtk_radio_action_set_group() {} ;
void gtk_radio_button_get_group() {} ;
void gtk_radio_button_get_type() {} ;
void gtk_radio_button_new() {} ;
void gtk_radio_button_new_from_widget() {} ;
void gtk_radio_button_new_with_label() {} ;
void gtk_radio_button_new_with_label_from_widget() {} ;
void gtk_radio_button_new_with_mnemonic() {} ;
void gtk_radio_button_new_with_mnemonic_from_widget() {} ;
void gtk_radio_button_set_group() {} ;
void gtk_radio_menu_item_get_group() {} ;
void gtk_radio_menu_item_get_type() {} ;
void gtk_radio_menu_item_new() {} ;
void gtk_radio_menu_item_new_from_widget() {} ;
void gtk_radio_menu_item_new_with_label() {} ;
void gtk_radio_menu_item_new_with_label_from_widget() {} ;
void gtk_radio_menu_item_new_with_mnemonic() {} ;
void gtk_radio_menu_item_new_with_mnemonic_from_widget() {} ;
void gtk_radio_menu_item_set_group() {} ;
void gtk_radio_tool_button_get_group() {} ;
void gtk_radio_tool_button_get_type() {} ;
void gtk_radio_tool_button_new() {} ;
void gtk_radio_tool_button_new_from_stock() {} ;
void gtk_radio_tool_button_new_from_widget() {} ;
void gtk_radio_tool_button_new_with_stock_from_widget() {} ;
void gtk_radio_tool_button_set_group() {} ;
void gtk_range_get_adjustment() {} ;
void gtk_range_get_inverted() {} ;
void gtk_range_get_type() {} ;
void gtk_range_get_update_policy() {} ;
void gtk_range_get_value() {} ;
void gtk_range_set_adjustment() {} ;
void gtk_range_set_increments() {} ;
void gtk_range_set_inverted() {} ;
void gtk_range_set_range() {} ;
void gtk_range_set_update_policy() {} ;
void gtk_range_set_value() {} ;
void gtk_rc_add_default_file() {} ;
void gtk_rc_find_module_in_path() {} ;
void gtk_rc_find_pixmap_in_path() {} ;
void gtk_rc_flags_get_type() {} ;
void gtk_rc_get_default_files() {} ;
void gtk_rc_get_im_module_file() {} ;
void gtk_rc_get_im_module_path() {} ;
void gtk_rc_get_module_dir() {} ;
void gtk_rc_get_style() {} ;
void gtk_rc_get_style_by_paths() {} ;
void gtk_rc_get_theme_dir() {} ;
void gtk_rc_parse() {} ;
void gtk_rc_parse_color() {} ;
void gtk_rc_parse_priority() {} ;
void gtk_rc_parse_state() {} ;
void gtk_rc_parse_string() {} ;
void gtk_rc_property_parse_border() {} ;
void gtk_rc_property_parse_color() {} ;
void gtk_rc_property_parse_enum() {} ;
void gtk_rc_property_parse_flags() {} ;
void gtk_rc_property_parse_requisition() {} ;
void gtk_rc_reparse_all() {} ;
void gtk_rc_reparse_all_for_settings() {} ;
void gtk_rc_reset_styles() {} ;
void gtk_rc_scanner_new() {} ;
void gtk_rc_set_default_files() {} ;
void gtk_rc_style_copy() {} ;
void gtk_rc_style_get_type() {} ;
void gtk_rc_style_new() {} ;
void gtk_rc_style_ref() {} ;
void gtk_rc_style_unref() {} ;
void gtk_rc_token_type_get_type() {} ;
void gtk_relief_style_get_type() {} ;
void gtk_requisition_copy() {} ;
void gtk_requisition_free() {} ;
void gtk_requisition_get_type() {} ;
void gtk_resize_mode_get_type() {} ;
void gtk_response_type_get_type() {} ;
void gtk_ruler_draw_pos() {} ;
void gtk_ruler_draw_ticks() {} ;
void gtk_ruler_get_metric() {} ;
void gtk_ruler_get_range() {} ;
void gtk_ruler_get_type() {} ;
void gtk_ruler_set_metric() {} ;
void gtk_ruler_set_range() {} ;
void gtk_scale_get_digits() {} ;
void gtk_scale_get_draw_value() {} ;
void gtk_scale_get_layout() {} ;
void gtk_scale_get_layout_offsets() {} ;
void gtk_scale_get_type() {} ;
void gtk_scale_get_value_pos() {} ;
void gtk_scale_set_digits() {} ;
void gtk_scale_set_draw_value() {} ;
void gtk_scale_set_value_pos() {} ;
void gtk_scroll_step_get_type() {} ;
void gtk_scroll_type_get_type() {} ;
void gtk_scrollbar_get_type() {} ;
void gtk_scrolled_window_add_with_viewport() {} ;
void gtk_scrolled_window_get_hadjustment() {} ;
void gtk_scrolled_window_get_placement() {} ;
void gtk_scrolled_window_get_policy() {} ;
void gtk_scrolled_window_get_shadow_type() {} ;
void gtk_scrolled_window_get_type() {} ;
void gtk_scrolled_window_get_vadjustment() {} ;
void gtk_scrolled_window_new() {} ;
void gtk_scrolled_window_set_hadjustment() {} ;
void gtk_scrolled_window_set_placement() {} ;
void gtk_scrolled_window_set_policy() {} ;
void gtk_scrolled_window_set_shadow_type() {} ;
void gtk_scrolled_window_set_vadjustment() {} ;
void gtk_selection_add_target() {} ;
void gtk_selection_add_targets() {} ;
void gtk_selection_clear_targets() {} ;
void gtk_selection_convert() {} ;
void gtk_selection_data_copy() {} ;
void gtk_selection_data_free() {} ;
void gtk_selection_data_get_pixbuf() {} ;
void gtk_selection_data_get_targets() {} ;
void gtk_selection_data_get_text() {} ;
void gtk_selection_data_get_type() {} ;
void gtk_selection_data_get_uris() {} ;
void gtk_selection_data_set() {} ;
void gtk_selection_data_set_pixbuf() {} ;
void gtk_selection_data_set_text() {} ;
void gtk_selection_data_set_uris() {} ;
void gtk_selection_data_targets_include_image() {} ;
void gtk_selection_data_targets_include_text() {} ;
void gtk_selection_mode_get_type() {} ;
void gtk_selection_owner_set() {} ;
void gtk_selection_owner_set_for_display() {} ;
void gtk_selection_remove_all() {} ;
void gtk_separator_get_type() {} ;
void gtk_separator_menu_item_get_type() {} ;
void gtk_separator_menu_item_new() {} ;
void gtk_separator_tool_item_get_draw() {} ;
void gtk_separator_tool_item_get_type() {} ;
void gtk_separator_tool_item_new() {} ;
void gtk_separator_tool_item_set_draw() {} ;
void gtk_set_locale() {} ;
void gtk_settings_get_default() {} ;
void gtk_settings_get_for_screen() {} ;
void gtk_settings_get_type() {} ;
void gtk_settings_install_property() {} ;
void gtk_settings_install_property_parser() {} ;
void gtk_settings_set_double_property() {} ;
void gtk_settings_set_long_property() {} ;
void gtk_settings_set_property_value() {} ;
void gtk_settings_set_string_property() {} ;
void gtk_shadow_type_get_type() {} ;
void gtk_show_about_dialog() {} ;
void gtk_side_type_get_type() {} ;
void gtk_signal_run_type_get_type() {} ;
void gtk_size_group_add_widget() {} ;
void gtk_size_group_get_mode() {} ;
void gtk_size_group_get_type() {} ;
void gtk_size_group_mode_get_type() {} ;
void gtk_size_group_new() {} ;
void gtk_size_group_remove_widget() {} ;
void gtk_size_group_set_mode() {} ;
void gtk_socket_add_id() {} ;
void gtk_socket_get_id() {} ;
void gtk_socket_get_type() {} ;
void gtk_socket_new() {} ;
void gtk_sort_type_get_type() {} ;
void gtk_spin_button_configure() {} ;
void gtk_spin_button_get_adjustment() {} ;
void gtk_spin_button_get_digits() {} ;
void gtk_spin_button_get_increments() {} ;
void gtk_spin_button_get_numeric() {} ;
void gtk_spin_button_get_range() {} ;
void gtk_spin_button_get_snap_to_ticks() {} ;
void gtk_spin_button_get_type() {} ;
void gtk_spin_button_get_update_policy() {} ;
void gtk_spin_button_get_value() {} ;
void gtk_spin_button_get_value_as_int() {} ;
void gtk_spin_button_get_wrap() {} ;
void gtk_spin_button_new() {} ;
void gtk_spin_button_new_with_range() {} ;
void gtk_spin_button_set_adjustment() {} ;
void gtk_spin_button_set_digits() {} ;
void gtk_spin_button_set_increments() {} ;
void gtk_spin_button_set_numeric() {} ;
void gtk_spin_button_set_range() {} ;
void gtk_spin_button_set_snap_to_ticks() {} ;
void gtk_spin_button_set_update_policy() {} ;
void gtk_spin_button_set_value() {} ;
void gtk_spin_button_set_wrap() {} ;
void gtk_spin_button_spin() {} ;
void gtk_spin_button_update() {} ;
void gtk_spin_button_update_policy_get_type() {} ;
void gtk_spin_type_get_type() {} ;
void gtk_state_type_get_type() {} ;
void gtk_statusbar_get_context_id() {} ;
void gtk_statusbar_get_has_resize_grip() {} ;
void gtk_statusbar_get_type() {} ;
void gtk_statusbar_new() {} ;
void gtk_statusbar_pop() {} ;
void gtk_statusbar_push() {} ;
void gtk_statusbar_remove() {} ;
void gtk_statusbar_set_has_resize_grip() {} ;
void gtk_stock_add() {} ;
void gtk_stock_add_static() {} ;
void gtk_stock_item_copy() {} ;
void gtk_stock_item_free() {} ;
void gtk_stock_list_ids() {} ;
void gtk_stock_lookup() {} ;
void gtk_style_apply_default_background() {} ;
void gtk_style_attach() {} ;
void gtk_style_copy() {} ;
void gtk_style_detach() {} ;
void gtk_style_get_type() {} ;
void gtk_style_lookup_icon_set() {} ;
void gtk_style_new() {} ;
void gtk_style_render_icon() {} ;
void gtk_style_set_background() {} ;
void gtk_submenu_direction_get_type() {} ;
void gtk_submenu_placement_get_type() {} ;
void gtk_table_attach() {} ;
void gtk_table_attach_defaults() {} ;
void gtk_table_get_col_spacing() {} ;
void gtk_table_get_default_col_spacing() {} ;
void gtk_table_get_default_row_spacing() {} ;
void gtk_table_get_homogeneous() {} ;
void gtk_table_get_row_spacing() {} ;
void gtk_table_get_type() {} ;
void gtk_table_new() {} ;
void gtk_table_resize() {} ;
void gtk_table_set_col_spacing() {} ;
void gtk_table_set_col_spacings() {} ;
void gtk_table_set_homogeneous() {} ;
void gtk_table_set_row_spacing() {} ;
void gtk_table_set_row_spacings() {} ;
void gtk_target_flags_get_type() {} ;
void gtk_target_list_add() {} ;
void gtk_target_list_add_image_targets() {} ;
void gtk_target_list_add_table() {} ;
void gtk_target_list_add_text_targets() {} ;
void gtk_target_list_add_uri_targets() {} ;
void gtk_target_list_find() {} ;
void gtk_target_list_new() {} ;
void gtk_target_list_ref() {} ;
void gtk_target_list_remove() {} ;
void gtk_target_list_unref() {} ;
void gtk_tearoff_menu_item_get_type() {} ;
void gtk_tearoff_menu_item_new() {} ;
void gtk_text_attributes_copy() {} ;
void gtk_text_attributes_copy_values() {} ;
void gtk_text_attributes_get_type() {} ;
void gtk_text_attributes_new() {} ;
void gtk_text_attributes_ref() {} ;
void gtk_text_attributes_unref() {} ;
void gtk_text_buffer_add_selection_clipboard() {} ;
void gtk_text_buffer_apply_tag() {} ;
void gtk_text_buffer_apply_tag_by_name() {} ;
void gtk_text_buffer_backspace() {} ;
void gtk_text_buffer_begin_user_action() {} ;
void gtk_text_buffer_copy_clipboard() {} ;
void gtk_text_buffer_create_child_anchor() {} ;
void gtk_text_buffer_create_mark() {} ;
void gtk_text_buffer_create_tag() {} ;
void gtk_text_buffer_cut_clipboard() {} ;
void gtk_text_buffer_delete() {} ;
void gtk_text_buffer_delete_interactive() {} ;
void gtk_text_buffer_delete_mark() {} ;
void gtk_text_buffer_delete_mark_by_name() {} ;
void gtk_text_buffer_delete_selection() {} ;
void gtk_text_buffer_end_user_action() {} ;
void gtk_text_buffer_get_bounds() {} ;
void gtk_text_buffer_get_char_count() {} ;
void gtk_text_buffer_get_end_iter() {} ;
void gtk_text_buffer_get_insert() {} ;
void gtk_text_buffer_get_iter_at_child_anchor() {} ;
void gtk_text_buffer_get_iter_at_line() {} ;
void gtk_text_buffer_get_iter_at_line_index() {} ;
void gtk_text_buffer_get_iter_at_line_offset() {} ;
void gtk_text_buffer_get_iter_at_mark() {} ;
void gtk_text_buffer_get_iter_at_offset() {} ;
void gtk_text_buffer_get_line_count() {} ;
void gtk_text_buffer_get_mark() {} ;
void gtk_text_buffer_get_modified() {} ;
void gtk_text_buffer_get_selection_bound() {} ;
void gtk_text_buffer_get_selection_bounds() {} ;
void gtk_text_buffer_get_slice() {} ;
void gtk_text_buffer_get_start_iter() {} ;
void gtk_text_buffer_get_tag_table() {} ;
void gtk_text_buffer_get_text() {} ;
void gtk_text_buffer_get_type() {} ;
void gtk_text_buffer_insert() {} ;
void gtk_text_buffer_insert_at_cursor() {} ;
void gtk_text_buffer_insert_child_anchor() {} ;
void gtk_text_buffer_insert_interactive() {} ;
void gtk_text_buffer_insert_interactive_at_cursor() {} ;
void gtk_text_buffer_insert_pixbuf() {} ;
void gtk_text_buffer_insert_range() {} ;
void gtk_text_buffer_insert_range_interactive() {} ;
void gtk_text_buffer_insert_with_tags() {} ;
void gtk_text_buffer_insert_with_tags_by_name() {} ;
void gtk_text_buffer_move_mark() {} ;
void gtk_text_buffer_move_mark_by_name() {} ;
void gtk_text_buffer_new() {} ;
void gtk_text_buffer_paste_clipboard() {} ;
void gtk_text_buffer_place_cursor() {} ;
void gtk_text_buffer_remove_all_tags() {} ;
void gtk_text_buffer_remove_selection_clipboard() {} ;
void gtk_text_buffer_remove_tag() {} ;
void gtk_text_buffer_remove_tag_by_name() {} ;
void gtk_text_buffer_select_range() {} ;
void gtk_text_buffer_set_modified() {} ;
void gtk_text_buffer_set_text() {} ;
void gtk_text_child_anchor_get_deleted() {} ;
void gtk_text_child_anchor_get_type() {} ;
void gtk_text_child_anchor_get_widgets() {} ;
void gtk_text_child_anchor_new() {} ;
void gtk_text_direction_get_type() {} ;
void gtk_text_iter_backward_char() {} ;
void gtk_text_iter_backward_chars() {} ;
void gtk_text_iter_backward_cursor_position() {} ;
void gtk_text_iter_backward_cursor_positions() {} ;
void gtk_text_iter_backward_find_char() {} ;
void gtk_text_iter_backward_line() {} ;
void gtk_text_iter_backward_lines() {} ;
void gtk_text_iter_backward_search() {} ;
void gtk_text_iter_backward_sentence_start() {} ;
void gtk_text_iter_backward_sentence_starts() {} ;
void gtk_text_iter_backward_to_tag_toggle() {} ;
void gtk_text_iter_backward_visible_cursor_position() {} ;
void gtk_text_iter_backward_visible_cursor_positions() {} ;
void gtk_text_iter_backward_visible_word_start() {} ;
void gtk_text_iter_backward_visible_word_starts() {} ;
void gtk_text_iter_backward_word_start() {} ;
void gtk_text_iter_backward_word_starts() {} ;
void gtk_text_iter_begins_tag() {} ;
void gtk_text_iter_can_insert() {} ;
void gtk_text_iter_compare() {} ;
void gtk_text_iter_copy() {} ;
void gtk_text_iter_editable() {} ;
void gtk_text_iter_ends_line() {} ;
void gtk_text_iter_ends_sentence() {} ;
void gtk_text_iter_ends_tag() {} ;
void gtk_text_iter_ends_word() {} ;
void gtk_text_iter_equal() {} ;
void gtk_text_iter_forward_char() {} ;
void gtk_text_iter_forward_chars() {} ;
void gtk_text_iter_forward_cursor_position() {} ;
void gtk_text_iter_forward_cursor_positions() {} ;
void gtk_text_iter_forward_find_char() {} ;
void gtk_text_iter_forward_line() {} ;
void gtk_text_iter_forward_lines() {} ;
void gtk_text_iter_forward_search() {} ;
void gtk_text_iter_forward_sentence_end() {} ;
void gtk_text_iter_forward_sentence_ends() {} ;
void gtk_text_iter_forward_to_end() {} ;
void gtk_text_iter_forward_to_line_end() {} ;
void gtk_text_iter_forward_to_tag_toggle() {} ;
void gtk_text_iter_forward_visible_cursor_position() {} ;
void gtk_text_iter_forward_visible_cursor_positions() {} ;
void gtk_text_iter_forward_visible_word_end() {} ;
void gtk_text_iter_forward_visible_word_ends() {} ;
void gtk_text_iter_forward_word_end() {} ;
void gtk_text_iter_forward_word_ends() {} ;
void gtk_text_iter_free() {} ;
void gtk_text_iter_get_attributes() {} ;
void gtk_text_iter_get_buffer() {} ;
void gtk_text_iter_get_bytes_in_line() {} ;
void gtk_text_iter_get_char() {} ;
void gtk_text_iter_get_chars_in_line() {} ;
void gtk_text_iter_get_child_anchor() {} ;
void gtk_text_iter_get_language() {} ;
void gtk_text_iter_get_line() {} ;
void gtk_text_iter_get_line_index() {} ;
void gtk_text_iter_get_line_offset() {} ;
void gtk_text_iter_get_marks() {} ;
void gtk_text_iter_get_offset() {} ;
void gtk_text_iter_get_pixbuf() {} ;
void gtk_text_iter_get_slice() {} ;
void gtk_text_iter_get_tags() {} ;
void gtk_text_iter_get_text() {} ;
void gtk_text_iter_get_toggled_tags() {} ;
void gtk_text_iter_get_type() {} ;
void gtk_text_iter_get_visible_line_index() {} ;
void gtk_text_iter_get_visible_line_offset() {} ;
void gtk_text_iter_get_visible_slice() {} ;
void gtk_text_iter_get_visible_text() {} ;
void gtk_text_iter_has_tag() {} ;
void gtk_text_iter_in_range() {} ;
void gtk_text_iter_inside_sentence() {} ;
void gtk_text_iter_inside_word() {} ;
void gtk_text_iter_is_cursor_position() {} ;
void gtk_text_iter_is_end() {} ;
void gtk_text_iter_is_start() {} ;
void gtk_text_iter_order() {} ;
void gtk_text_iter_set_line() {} ;
void gtk_text_iter_set_line_index() {} ;
void gtk_text_iter_set_line_offset() {} ;
void gtk_text_iter_set_offset() {} ;
void gtk_text_iter_set_visible_line_index() {} ;
void gtk_text_iter_set_visible_line_offset() {} ;
void gtk_text_iter_starts_line() {} ;
void gtk_text_iter_starts_sentence() {} ;
void gtk_text_iter_starts_word() {} ;
void gtk_text_iter_toggles_tag() {} ;
void gtk_text_mark_get_buffer() {} ;
void gtk_text_mark_get_deleted() {} ;
void gtk_text_mark_get_left_gravity() {} ;
void gtk_text_mark_get_name() {} ;
void gtk_text_mark_get_type() {} ;
void gtk_text_mark_get_visible() {} ;
void gtk_text_mark_set_visible() {} ;
void gtk_text_search_flags_get_type() {} ;
void gtk_text_tag_event() {} ;
void gtk_text_tag_get_priority() {} ;
void gtk_text_tag_get_type() {} ;
void gtk_text_tag_new() {} ;
void gtk_text_tag_set_priority() {} ;
void gtk_text_tag_table_add() {} ;
void gtk_text_tag_table_foreach() {} ;
void gtk_text_tag_table_get_size() {} ;
void gtk_text_tag_table_get_type() {} ;
void gtk_text_tag_table_lookup() {} ;
void gtk_text_tag_table_new() {} ;
void gtk_text_tag_table_remove() {} ;
void gtk_text_view_add_child_at_anchor() {} ;
void gtk_text_view_add_child_in_window() {} ;
void gtk_text_view_backward_display_line() {} ;
void gtk_text_view_backward_display_line_start() {} ;
void gtk_text_view_buffer_to_window_coords() {} ;
void gtk_text_view_forward_display_line() {} ;
void gtk_text_view_forward_display_line_end() {} ;
void gtk_text_view_get_accepts_tab() {} ;
void gtk_text_view_get_border_window_size() {} ;
void gtk_text_view_get_buffer() {} ;
void gtk_text_view_get_cursor_visible() {} ;
void gtk_text_view_get_default_attributes() {} ;
void gtk_text_view_get_editable() {} ;
void gtk_text_view_get_indent() {} ;
void gtk_text_view_get_iter_at_location() {} ;
void gtk_text_view_get_iter_at_position() {} ;
void gtk_text_view_get_iter_location() {} ;
void gtk_text_view_get_justification() {} ;
void gtk_text_view_get_left_margin() {} ;
void gtk_text_view_get_line_at_y() {} ;
void gtk_text_view_get_line_yrange() {} ;
void gtk_text_view_get_overwrite() {} ;
void gtk_text_view_get_pixels_above_lines() {} ;
void gtk_text_view_get_pixels_below_lines() {} ;
void gtk_text_view_get_pixels_inside_wrap() {} ;
void gtk_text_view_get_right_margin() {} ;
void gtk_text_view_get_tabs() {} ;
void gtk_text_view_get_type() {} ;
void gtk_text_view_get_visible_rect() {} ;
void gtk_text_view_get_window() {} ;
void gtk_text_view_get_window_type() {} ;
void gtk_text_view_get_wrap_mode() {} ;
void gtk_text_view_move_child() {} ;
void gtk_text_view_move_mark_onscreen() {} ;
void gtk_text_view_move_visually() {} ;
void gtk_text_view_new() {} ;
void gtk_text_view_new_with_buffer() {} ;
void gtk_text_view_place_cursor_onscreen() {} ;
void gtk_text_view_scroll_mark_onscreen() {} ;
void gtk_text_view_scroll_to_iter() {} ;
void gtk_text_view_scroll_to_mark() {} ;
void gtk_text_view_set_accepts_tab() {} ;
void gtk_text_view_set_border_window_size() {} ;
void gtk_text_view_set_buffer() {} ;
void gtk_text_view_set_cursor_visible() {} ;
void gtk_text_view_set_editable() {} ;
void gtk_text_view_set_indent() {} ;
void gtk_text_view_set_justification() {} ;
void gtk_text_view_set_left_margin() {} ;
void gtk_text_view_set_overwrite() {} ;
void gtk_text_view_set_pixels_above_lines() {} ;
void gtk_text_view_set_pixels_below_lines() {} ;
void gtk_text_view_set_pixels_inside_wrap() {} ;
void gtk_text_view_set_right_margin() {} ;
void gtk_text_view_set_tabs() {} ;
void gtk_text_view_set_wrap_mode() {} ;
void gtk_text_view_starts_display_line() {} ;
void gtk_text_view_window_to_buffer_coords() {} ;
void gtk_text_window_type_get_type() {} ;
void gtk_toggle_action_get_active() {} ;
void gtk_toggle_action_get_draw_as_radio() {} ;
void gtk_toggle_action_get_type() {} ;
void gtk_toggle_action_new() {} ;
void gtk_toggle_action_set_active() {} ;
void gtk_toggle_action_set_draw_as_radio() {} ;
void gtk_toggle_action_toggled() {} ;
void gtk_toggle_button_get_active() {} ;
void gtk_toggle_button_get_inconsistent() {} ;
void gtk_toggle_button_get_mode() {} ;
void gtk_toggle_button_get_type() {} ;
void gtk_toggle_button_new() {} ;
void gtk_toggle_button_new_with_label() {} ;
void gtk_toggle_button_new_with_mnemonic() {} ;
void gtk_toggle_button_set_active() {} ;
void gtk_toggle_button_set_inconsistent() {} ;
void gtk_toggle_button_set_mode() {} ;
void gtk_toggle_button_toggled() {} ;
void gtk_toggle_tool_button_get_active() {} ;
void gtk_toggle_tool_button_get_type() {} ;
void gtk_toggle_tool_button_new() {} ;
void gtk_toggle_tool_button_new_from_stock() {} ;
void gtk_toggle_tool_button_set_active() {} ;
void gtk_tool_button_get_icon_widget() {} ;
void gtk_tool_button_get_label() {} ;
void gtk_tool_button_get_label_widget() {} ;
void gtk_tool_button_get_stock_id() {} ;
void gtk_tool_button_get_type() {} ;
void gtk_tool_button_get_use_underline() {} ;
void gtk_tool_button_new() {} ;
void gtk_tool_button_new_from_stock() {} ;
void gtk_tool_button_set_icon_widget() {} ;
void gtk_tool_button_set_label() {} ;
void gtk_tool_button_set_label_widget() {} ;
void gtk_tool_button_set_stock_id() {} ;
void gtk_tool_button_set_use_underline() {} ;
void gtk_tool_item_get_expand() {} ;
void gtk_tool_item_get_homogeneous() {} ;
void gtk_tool_item_get_icon_size() {} ;
void gtk_tool_item_get_is_important() {} ;
void gtk_tool_item_get_orientation() {} ;
void gtk_tool_item_get_proxy_menu_item() {} ;
void gtk_tool_item_get_relief_style() {} ;
void gtk_tool_item_get_toolbar_style() {} ;
void gtk_tool_item_get_type() {} ;
void gtk_tool_item_get_use_drag_window() {} ;
void gtk_tool_item_get_visible_horizontal() {} ;
void gtk_tool_item_get_visible_vertical() {} ;
void gtk_tool_item_new() {} ;
void gtk_tool_item_rebuild_menu() {} ;
void gtk_tool_item_retrieve_proxy_menu_item() {} ;
void gtk_tool_item_set_expand() {} ;
void gtk_tool_item_set_homogeneous() {} ;
void gtk_tool_item_set_is_important() {} ;
void gtk_tool_item_set_proxy_menu_item() {} ;
void gtk_tool_item_set_tooltip() {} ;
void gtk_tool_item_set_use_drag_window() {} ;
void gtk_tool_item_set_visible_horizontal() {} ;
void gtk_tool_item_set_visible_vertical() {} ;
void gtk_toolbar_child_type_get_type() {} ;
void gtk_toolbar_get_drop_index() {} ;
void gtk_toolbar_get_icon_size() {} ;
void gtk_toolbar_get_item_index() {} ;
void gtk_toolbar_get_n_items() {} ;
void gtk_toolbar_get_nth_item() {} ;
void gtk_toolbar_get_orientation() {} ;
void gtk_toolbar_get_relief_style() {} ;
void gtk_toolbar_get_show_arrow() {} ;
void gtk_toolbar_get_style() {} ;
void gtk_toolbar_get_tooltips() {} ;
void gtk_toolbar_get_type() {} ;
void gtk_toolbar_insert() {} ;
void gtk_toolbar_new() {} ;
void gtk_toolbar_set_drop_highlight_item() {} ;
void gtk_toolbar_set_orientation() {} ;
void gtk_toolbar_set_show_arrow() {} ;
void gtk_toolbar_set_style() {} ;
void gtk_toolbar_set_tooltips() {} ;
void gtk_toolbar_space_style_get_type() {} ;
void gtk_toolbar_style_get_type() {} ;
void gtk_toolbar_unset_style() {} ;
void gtk_tooltips_data_get() {} ;
void gtk_tooltips_disable() {} ;
void gtk_tooltips_enable() {} ;
void gtk_tooltips_force_window() {} ;
void gtk_tooltips_get_info_from_tip_window() {} ;
void gtk_tooltips_get_type() {} ;
void gtk_tooltips_new() {} ;
void gtk_tooltips_set_tip() {} ;
void gtk_tree_drag_dest_drag_data_received() {} ;
void gtk_tree_drag_dest_get_type() {} ;
void gtk_tree_drag_dest_row_drop_possible() {} ;
void gtk_tree_drag_source_drag_data_delete() {} ;
void gtk_tree_drag_source_drag_data_get() {} ;
void gtk_tree_drag_source_get_type() {} ;
void gtk_tree_drag_source_row_draggable() {} ;
void gtk_tree_get_row_drag_data() {} ;
void gtk_tree_iter_copy() {} ;
void gtk_tree_iter_free() {} ;
void gtk_tree_iter_get_type() {} ;
void gtk_tree_model_filter_clear_cache() {} ;
void gtk_tree_model_filter_convert_child_iter_to_iter() {} ;
void gtk_tree_model_filter_convert_child_path_to_path() {} ;
void gtk_tree_model_filter_convert_iter_to_child_iter() {} ;
void gtk_tree_model_filter_convert_path_to_child_path() {} ;
void gtk_tree_model_filter_get_model() {} ;
void gtk_tree_model_filter_get_type() {} ;
void gtk_tree_model_filter_new() {} ;
void gtk_tree_model_filter_refilter() {} ;
void gtk_tree_model_filter_set_modify_func() {} ;
void gtk_tree_model_filter_set_visible_column() {} ;
void gtk_tree_model_filter_set_visible_func() {} ;
void gtk_tree_model_flags_get_type() {} ;
void gtk_tree_model_foreach() {} ;
void gtk_tree_model_get() {} ;
void gtk_tree_model_get_column_type() {} ;
void gtk_tree_model_get_flags() {} ;
void gtk_tree_model_get_iter() {} ;
void gtk_tree_model_get_iter_first() {} ;
void gtk_tree_model_get_iter_from_string() {} ;
void gtk_tree_model_get_n_columns() {} ;
void gtk_tree_model_get_path() {} ;
void gtk_tree_model_get_string_from_iter() {} ;
void gtk_tree_model_get_type() {} ;
void gtk_tree_model_get_valist() {} ;
void gtk_tree_model_get_value() {} ;
void gtk_tree_model_iter_children() {} ;
void gtk_tree_model_iter_has_child() {} ;
void gtk_tree_model_iter_n_children() {} ;
void gtk_tree_model_iter_next() {} ;
void gtk_tree_model_iter_nth_child() {} ;
void gtk_tree_model_iter_parent() {} ;
void gtk_tree_model_ref_node() {} ;
void gtk_tree_model_row_changed() {} ;
void gtk_tree_model_row_deleted() {} ;
void gtk_tree_model_row_has_child_toggled() {} ;
void gtk_tree_model_row_inserted() {} ;
void gtk_tree_model_rows_reordered() {} ;
void gtk_tree_model_sort_clear_cache() {} ;
void gtk_tree_model_sort_convert_child_iter_to_iter() {} ;
void gtk_tree_model_sort_convert_child_path_to_path() {} ;
void gtk_tree_model_sort_convert_iter_to_child_iter() {} ;
void gtk_tree_model_sort_convert_path_to_child_path() {} ;
void gtk_tree_model_sort_get_model() {} ;
void gtk_tree_model_sort_get_type() {} ;
void gtk_tree_model_sort_iter_is_valid() {} ;
void gtk_tree_model_sort_new_with_model() {} ;
void gtk_tree_model_sort_reset_default_sort_func() {} ;
void gtk_tree_model_unref_node() {} ;
void gtk_tree_path_append_index() {} ;
void gtk_tree_path_compare() {} ;
void gtk_tree_path_copy() {} ;
void gtk_tree_path_down() {} ;
void gtk_tree_path_free() {} ;
void gtk_tree_path_get_depth() {} ;
void gtk_tree_path_get_indices() {} ;
void gtk_tree_path_get_type() {} ;
void gtk_tree_path_is_ancestor() {} ;
void gtk_tree_path_is_descendant() {} ;
void gtk_tree_path_new() {} ;
void gtk_tree_path_new_first() {} ;
void gtk_tree_path_new_from_indices() {} ;
void gtk_tree_path_new_from_string() {} ;
void gtk_tree_path_next() {} ;
void gtk_tree_path_prepend_index() {} ;
void gtk_tree_path_prev() {} ;
void gtk_tree_path_to_string() {} ;
void gtk_tree_path_up() {} ;
void gtk_tree_row_reference_copy() {} ;
void gtk_tree_row_reference_deleted() {} ;
void gtk_tree_row_reference_free() {} ;
void gtk_tree_row_reference_get_path() {} ;
void gtk_tree_row_reference_get_type() {} ;
void gtk_tree_row_reference_inserted() {} ;
void gtk_tree_row_reference_new() {} ;
void gtk_tree_row_reference_new_proxy() {} ;
void gtk_tree_row_reference_reordered() {} ;
void gtk_tree_row_reference_valid() {} ;
void gtk_tree_selection_count_selected_rows() {} ;
void gtk_tree_selection_get_mode() {} ;
void gtk_tree_selection_get_selected() {} ;
void gtk_tree_selection_get_selected_rows() {} ;
void gtk_tree_selection_get_tree_view() {} ;
void gtk_tree_selection_get_type() {} ;
void gtk_tree_selection_get_user_data() {} ;
void gtk_tree_selection_iter_is_selected() {} ;
void gtk_tree_selection_path_is_selected() {} ;
void gtk_tree_selection_select_all() {} ;
void gtk_tree_selection_select_iter() {} ;
void gtk_tree_selection_select_path() {} ;
void gtk_tree_selection_select_range() {} ;
void gtk_tree_selection_selected_foreach() {} ;
void gtk_tree_selection_set_mode() {} ;
void gtk_tree_selection_set_select_function() {} ;
void gtk_tree_selection_unselect_all() {} ;
void gtk_tree_selection_unselect_iter() {} ;
void gtk_tree_selection_unselect_path() {} ;
void gtk_tree_selection_unselect_range() {} ;
void gtk_tree_set_row_drag_data() {} ;
void gtk_tree_sortable_get_sort_column_id() {} ;
void gtk_tree_sortable_get_type() {} ;
void gtk_tree_sortable_has_default_sort_func() {} ;
void gtk_tree_sortable_set_default_sort_func() {} ;
void gtk_tree_sortable_set_sort_column_id() {} ;
void gtk_tree_sortable_set_sort_func() {} ;
void gtk_tree_sortable_sort_column_changed() {} ;
void gtk_tree_store_append() {} ;
void gtk_tree_store_clear() {} ;
void gtk_tree_store_get_type() {} ;
void gtk_tree_store_insert() {} ;
void gtk_tree_store_insert_after() {} ;
void gtk_tree_store_insert_before() {} ;
void gtk_tree_store_is_ancestor() {} ;
void gtk_tree_store_iter_depth() {} ;
void gtk_tree_store_iter_is_valid() {} ;
void gtk_tree_store_move_after() {} ;
void gtk_tree_store_move_before() {} ;
void gtk_tree_store_new() {} ;
void gtk_tree_store_newv() {} ;
void gtk_tree_store_prepend() {} ;
void gtk_tree_store_remove() {} ;
void gtk_tree_store_reorder() {} ;
void gtk_tree_store_set() {} ;
void gtk_tree_store_set_column_types() {} ;
void gtk_tree_store_set_valist() {} ;
void gtk_tree_store_set_value() {} ;
void gtk_tree_store_swap() {} ;
void gtk_tree_view_append_column() {} ;
void gtk_tree_view_collapse_all() {} ;
void gtk_tree_view_collapse_row() {} ;
void gtk_tree_view_column_add_attribute() {} ;
void gtk_tree_view_column_cell_get_position() {} ;
void gtk_tree_view_column_cell_get_size() {} ;
void gtk_tree_view_column_cell_is_visible() {} ;
void gtk_tree_view_column_cell_set_cell_data() {} ;
void gtk_tree_view_column_clear() {} ;
void gtk_tree_view_column_clear_attributes() {} ;
void gtk_tree_view_column_clicked() {} ;
void gtk_tree_view_column_focus_cell() {} ;
void gtk_tree_view_column_get_alignment() {} ;
void gtk_tree_view_column_get_cell_renderers() {} ;
void gtk_tree_view_column_get_clickable() {} ;
void gtk_tree_view_column_get_expand() {} ;
void gtk_tree_view_column_get_fixed_width() {} ;
void gtk_tree_view_column_get_max_width() {} ;
void gtk_tree_view_column_get_min_width() {} ;
void gtk_tree_view_column_get_reorderable() {} ;
void gtk_tree_view_column_get_resizable() {} ;
void gtk_tree_view_column_get_sizing() {} ;
void gtk_tree_view_column_get_sort_column_id() {} ;
void gtk_tree_view_column_get_sort_indicator() {} ;
void gtk_tree_view_column_get_sort_order() {} ;
void gtk_tree_view_column_get_spacing() {} ;
void gtk_tree_view_column_get_title() {} ;
void gtk_tree_view_column_get_type() {} ;
void gtk_tree_view_column_get_visible() {} ;
void gtk_tree_view_column_get_widget() {} ;
void gtk_tree_view_column_get_width() {} ;
void gtk_tree_view_column_new() {} ;
void gtk_tree_view_column_new_with_attributes() {} ;
void gtk_tree_view_column_pack_end() {} ;
void gtk_tree_view_column_pack_start() {} ;
void gtk_tree_view_column_set_alignment() {} ;
void gtk_tree_view_column_set_attributes() {} ;
void gtk_tree_view_column_set_cell_data_func() {} ;
void gtk_tree_view_column_set_clickable() {} ;
void gtk_tree_view_column_set_expand() {} ;
void gtk_tree_view_column_set_fixed_width() {} ;
void gtk_tree_view_column_set_max_width() {} ;
void gtk_tree_view_column_set_min_width() {} ;
void gtk_tree_view_column_set_reorderable() {} ;
void gtk_tree_view_column_set_resizable() {} ;
void gtk_tree_view_column_set_sizing() {} ;
void gtk_tree_view_column_set_sort_column_id() {} ;
void gtk_tree_view_column_set_sort_indicator() {} ;
void gtk_tree_view_column_set_sort_order() {} ;
void gtk_tree_view_column_set_spacing() {} ;
void gtk_tree_view_column_set_title() {} ;
void gtk_tree_view_column_set_visible() {} ;
void gtk_tree_view_column_set_widget() {} ;
void gtk_tree_view_column_sizing_get_type() {} ;
void gtk_tree_view_columns_autosize() {} ;
void gtk_tree_view_create_row_drag_icon() {} ;
void gtk_tree_view_drop_position_get_type() {} ;
void gtk_tree_view_enable_model_drag_dest() {} ;
void gtk_tree_view_enable_model_drag_source() {} ;
void gtk_tree_view_expand_all() {} ;
void gtk_tree_view_expand_row() {} ;
void gtk_tree_view_expand_to_path() {} ;
void gtk_tree_view_get_background_area() {} ;
void gtk_tree_view_get_bin_window() {} ;
void gtk_tree_view_get_cell_area() {} ;
void gtk_tree_view_get_column() {} ;
void gtk_tree_view_get_columns() {} ;
void gtk_tree_view_get_cursor() {} ;
void gtk_tree_view_get_dest_row_at_pos() {} ;
void gtk_tree_view_get_drag_dest_row() {} ;
void gtk_tree_view_get_enable_search() {} ;
void gtk_tree_view_get_expander_column() {} ;
void gtk_tree_view_get_fixed_height_mode() {} ;
void gtk_tree_view_get_hadjustment() {} ;
void gtk_tree_view_get_headers_visible() {} ;
void gtk_tree_view_get_hover_expand() {} ;
void gtk_tree_view_get_hover_selection() {} ;
void gtk_tree_view_get_model() {} ;
void gtk_tree_view_get_path_at_pos() {} ;
void gtk_tree_view_get_reorderable() {} ;
void gtk_tree_view_get_row_separator_func() {} ;
void gtk_tree_view_get_rules_hint() {} ;
void gtk_tree_view_get_search_column() {} ;
void gtk_tree_view_get_search_equal_func() {} ;
void gtk_tree_view_get_selection() {} ;
void gtk_tree_view_get_type() {} ;
void gtk_tree_view_get_vadjustment() {} ;
void gtk_tree_view_get_visible_rect() {} ;
void gtk_tree_view_insert_column() {} ;
void gtk_tree_view_insert_column_with_attributes() {} ;
void gtk_tree_view_insert_column_with_data_func() {} ;
void gtk_tree_view_map_expanded_rows() {} ;
void gtk_tree_view_mode_get_type() {} ;
void gtk_tree_view_move_column_after() {} ;
void gtk_tree_view_new() {} ;
void gtk_tree_view_new_with_model() {} ;
void gtk_tree_view_remove_column() {} ;
void gtk_tree_view_row_activated() {} ;
void gtk_tree_view_row_expanded() {} ;
void gtk_tree_view_scroll_to_cell() {} ;
void gtk_tree_view_scroll_to_point() {} ;
void gtk_tree_view_set_column_drag_function() {} ;
void gtk_tree_view_set_cursor() {} ;
void gtk_tree_view_set_cursor_on_cell() {} ;
void gtk_tree_view_set_destroy_count_func() {} ;
void gtk_tree_view_set_drag_dest_row() {} ;
void gtk_tree_view_set_enable_search() {} ;
void gtk_tree_view_set_expander_column() {} ;
void gtk_tree_view_set_fixed_height_mode() {} ;
void gtk_tree_view_set_hadjustment() {} ;
void gtk_tree_view_set_headers_clickable() {} ;
void gtk_tree_view_set_headers_visible() {} ;
void gtk_tree_view_set_hover_expand() {} ;
void gtk_tree_view_set_hover_selection() {} ;
void gtk_tree_view_set_model() {} ;
void gtk_tree_view_set_reorderable() {} ;
void gtk_tree_view_set_row_separator_func() {} ;
void gtk_tree_view_set_rules_hint() {} ;
void gtk_tree_view_set_search_column() {} ;
void gtk_tree_view_set_search_equal_func() {} ;
void gtk_tree_view_set_vadjustment() {} ;
void gtk_tree_view_tree_to_widget_coords() {} ;
void gtk_tree_view_unset_rows_drag_dest() {} ;
void gtk_tree_view_unset_rows_drag_source() {} ;
void gtk_tree_view_widget_to_tree_coords() {} ;
void gtk_true() {} ;
void gtk_type_class() {} ;
void gtk_ui_manager_add_ui() {} ;
void gtk_ui_manager_add_ui_from_file() {} ;
void gtk_ui_manager_add_ui_from_string() {} ;
void gtk_ui_manager_ensure_update() {} ;
void gtk_ui_manager_get_accel_group() {} ;
void gtk_ui_manager_get_action() {} ;
void gtk_ui_manager_get_action_groups() {} ;
void gtk_ui_manager_get_add_tearoffs() {} ;
void gtk_ui_manager_get_toplevels() {} ;
void gtk_ui_manager_get_type() {} ;
void gtk_ui_manager_get_ui() {} ;
void gtk_ui_manager_get_widget() {} ;
void gtk_ui_manager_insert_action_group() {} ;
void gtk_ui_manager_item_type_get_type() {} ;
void gtk_ui_manager_new() {} ;
void gtk_ui_manager_new_merge_id() {} ;
void gtk_ui_manager_remove_action_group() {} ;
void gtk_ui_manager_remove_ui() {} ;
void gtk_ui_manager_set_add_tearoffs() {} ;
void gtk_update_type_get_type() {} ;
void gtk_vbox_get_type() {} ;
void gtk_vbox_new() {} ;
void gtk_vbutton_box_get_type() {} ;
void gtk_vbutton_box_new() {} ;
void gtk_viewport_get_hadjustment() {} ;
void gtk_viewport_get_shadow_type() {} ;
void gtk_viewport_get_type() {} ;
void gtk_viewport_get_vadjustment() {} ;
void gtk_viewport_new() {} ;
void gtk_viewport_set_hadjustment() {} ;
void gtk_viewport_set_shadow_type() {} ;
void gtk_viewport_set_vadjustment() {} ;
void gtk_visibility_get_type() {} ;
void gtk_vpaned_get_type() {} ;
void gtk_vpaned_new() {} ;
void gtk_vruler_get_type() {} ;
void gtk_vruler_new() {} ;
void gtk_vscale_get_type() {} ;
void gtk_vscale_new() {} ;
void gtk_vscale_new_with_range() {} ;
void gtk_vscrollbar_get_type() {} ;
void gtk_vscrollbar_new() {} ;
void gtk_vseparator_get_type() {} ;
void gtk_vseparator_new() {} ;
void gtk_widget_activate() {} ;
void gtk_widget_add_accelerator() {} ;
void gtk_widget_add_events() {} ;
void gtk_widget_add_mnemonic_label() {} ;
void gtk_widget_can_activate_accel() {} ;
void gtk_widget_child_focus() {} ;
void gtk_widget_child_notify() {} ;
void gtk_widget_class_find_style_property() {} ;
void gtk_widget_class_install_style_property() {} ;
void gtk_widget_class_install_style_property_parser() {} ;
void gtk_widget_class_list_style_properties() {} ;
void gtk_widget_class_path() {} ;
void gtk_widget_create_pango_context() {} ;
void gtk_widget_create_pango_layout() {} ;
void gtk_widget_destroy() {} ;
void gtk_widget_destroyed() {} ;
void gtk_widget_ensure_style() {} ;
void gtk_widget_event() {} ;
void gtk_widget_flags_get_type() {} ;
void gtk_widget_freeze_child_notify() {} ;
void gtk_widget_get_accessible() {} ;
void gtk_widget_get_ancestor() {} ;
void gtk_widget_get_child_requisition() {} ;
void gtk_widget_get_child_visible() {} ;
void gtk_widget_get_clipboard() {} ;
void gtk_widget_get_colormap() {} ;
void gtk_widget_get_composite_name() {} ;
void gtk_widget_get_default_colormap() {} ;
void gtk_widget_get_default_direction() {} ;
void gtk_widget_get_default_style() {} ;
void gtk_widget_get_default_visual() {} ;
void gtk_widget_get_direction() {} ;
void gtk_widget_get_display() {} ;
void gtk_widget_get_events() {} ;
void gtk_widget_get_extension_events() {} ;
void gtk_widget_get_modifier_style() {} ;
void gtk_widget_get_name() {} ;
void gtk_widget_get_no_show_all() {} ;
void gtk_widget_get_pango_context() {} ;
void gtk_widget_get_parent() {} ;
void gtk_widget_get_parent_window() {} ;
void gtk_widget_get_pointer() {} ;
void gtk_widget_get_root_window() {} ;
void gtk_widget_get_screen() {} ;
void gtk_widget_get_settings() {} ;
void gtk_widget_get_size_request() {} ;
void gtk_widget_get_style() {} ;
void gtk_widget_get_toplevel() {} ;
void gtk_widget_get_type() {} ;
void gtk_widget_get_visual() {} ;
void gtk_widget_grab_default() {} ;
void gtk_widget_grab_focus() {} ;
void gtk_widget_has_screen() {} ;
void gtk_widget_help_type_get_type() {} ;
void gtk_widget_hide() {} ;
void gtk_widget_hide_all() {} ;
void gtk_widget_hide_on_delete() {} ;
void gtk_widget_intersect() {} ;
void gtk_widget_is_ancestor() {} ;
void gtk_widget_is_focus() {} ;
void gtk_widget_list_accel_closures() {} ;
void gtk_widget_list_mnemonic_labels() {} ;
void gtk_widget_map() {} ;
void gtk_widget_mnemonic_activate() {} ;
void gtk_widget_modify_base() {} ;
void gtk_widget_modify_bg() {} ;
void gtk_widget_modify_fg() {} ;
void gtk_widget_modify_font() {} ;
void gtk_widget_modify_style() {} ;
void gtk_widget_modify_text() {} ;
void gtk_widget_new() {} ;
void gtk_widget_path() {} ;
void gtk_widget_pop_colormap() {} ;
void gtk_widget_pop_composite_child() {} ;
void gtk_widget_push_colormap() {} ;
void gtk_widget_push_composite_child() {} ;
void gtk_widget_queue_draw() {} ;
void gtk_widget_queue_draw_area() {} ;
void gtk_widget_queue_resize() {} ;
void gtk_widget_queue_resize_no_redraw() {} ;
void gtk_widget_realize() {} ;
void gtk_widget_ref() {} ;
void gtk_widget_region_intersect() {} ;
void gtk_widget_remove_accelerator() {} ;
void gtk_widget_remove_mnemonic_label() {} ;
void gtk_widget_render_icon() {} ;
void gtk_widget_reparent() {} ;
void gtk_widget_reset_rc_styles() {} ;
void gtk_widget_reset_shapes() {} ;
void gtk_widget_send_expose() {} ;
void gtk_widget_set_accel_path() {} ;
void gtk_widget_set_app_paintable() {} ;
void gtk_widget_set_child_visible() {} ;
void gtk_widget_set_colormap() {} ;
void gtk_widget_set_composite_name() {} ;
void gtk_widget_set_default_colormap() {} ;
void gtk_widget_set_default_direction() {} ;
void gtk_widget_set_direction() {} ;
void gtk_widget_set_double_buffered() {} ;
void gtk_widget_set_events() {} ;
void gtk_widget_set_extension_events() {} ;
void gtk_widget_set_name() {} ;
void gtk_widget_set_no_show_all() {} ;
void gtk_widget_set_parent() {} ;
void gtk_widget_set_parent_window() {} ;
void gtk_widget_set_redraw_on_allocate() {} ;
void gtk_widget_set_scroll_adjustments() {} ;
void gtk_widget_set_sensitive() {} ;
void gtk_widget_set_size_request() {} ;
void gtk_widget_set_state() {} ;
void gtk_widget_set_style() {} ;
void gtk_widget_shape_combine_mask() {} ;
void gtk_widget_show() {} ;
void gtk_widget_show_all() {} ;
void gtk_widget_show_now() {} ;
void gtk_widget_size_allocate() {} ;
void gtk_widget_size_request() {} ;
void gtk_widget_style_get() {} ;
void gtk_widget_style_get_property() {} ;
void gtk_widget_style_get_valist() {} ;
void gtk_widget_thaw_child_notify() {} ;
void gtk_widget_translate_coordinates() {} ;
void gtk_widget_unmap() {} ;
void gtk_widget_unparent() {} ;
void gtk_widget_unrealize() {} ;
void gtk_widget_unref() {} ;
void gtk_window_activate_default() {} ;
void gtk_window_activate_focus() {} ;
void gtk_window_activate_key() {} ;
void gtk_window_add_accel_group() {} ;
void gtk_window_add_embedded_xid() {} ;
void gtk_window_add_mnemonic() {} ;
void gtk_window_begin_move_drag() {} ;
void gtk_window_begin_resize_drag() {} ;
void gtk_window_deiconify() {} ;
void gtk_window_fullscreen() {} ;
void gtk_window_get_accept_focus() {} ;
void gtk_window_get_decorated() {} ;
void gtk_window_get_default_icon_list() {} ;
void gtk_window_get_default_size() {} ;
void gtk_window_get_destroy_with_parent() {} ;
void gtk_window_get_focus() {} ;
void gtk_window_get_focus_on_map() {} ;
void gtk_window_get_frame_dimensions() {} ;
void gtk_window_get_gravity() {} ;
void gtk_window_get_has_frame() {} ;
void gtk_window_get_icon() {} ;
void gtk_window_get_icon_list() {} ;
void gtk_window_get_icon_name() {} ;
void gtk_window_get_mnemonic_modifier() {} ;
void gtk_window_get_modal() {} ;
void gtk_window_get_position() {} ;
void gtk_window_get_resizable() {} ;
void gtk_window_get_role() {} ;
void gtk_window_get_screen() {} ;
void gtk_window_get_size() {} ;
void gtk_window_get_skip_pager_hint() {} ;
void gtk_window_get_skip_taskbar_hint() {} ;
void gtk_window_get_title() {} ;
void gtk_window_get_transient_for() {} ;
void gtk_window_get_type() {} ;
void gtk_window_get_type_hint() {} ;
void gtk_window_group_add_window() {} ;
void gtk_window_group_get_type() {} ;
void gtk_window_group_new() {} ;
void gtk_window_group_remove_window() {} ;
void gtk_window_has_toplevel_focus() {} ;
void gtk_window_iconify() {} ;
void gtk_window_is_active() {} ;
void gtk_window_list_toplevels() {} ;
void gtk_window_maximize() {} ;
void gtk_window_mnemonic_activate() {} ;
void gtk_window_move() {} ;
void gtk_window_new() {} ;
void gtk_window_parse_geometry() {} ;
void gtk_window_position_get_type() {} ;
void gtk_window_present() {} ;
void gtk_window_propagate_key_event() {} ;
void gtk_window_remove_accel_group() {} ;
void gtk_window_remove_embedded_xid() {} ;
void gtk_window_remove_mnemonic() {} ;
void gtk_window_reshow_with_initial_size() {} ;
void gtk_window_resize() {} ;
void gtk_window_set_accept_focus() {} ;
void gtk_window_set_auto_startup_notification() {} ;
void gtk_window_set_decorated() {} ;
void gtk_window_set_default() {} ;
void gtk_window_set_default_icon() {} ;
void gtk_window_set_default_icon_from_file() {} ;
void gtk_window_set_default_icon_list() {} ;
void gtk_window_set_default_icon_name() {} ;
void gtk_window_set_default_size() {} ;
void gtk_window_set_destroy_with_parent() {} ;
void gtk_window_set_focus() {} ;
void gtk_window_set_focus_on_map() {} ;
void gtk_window_set_frame_dimensions() {} ;
void gtk_window_set_geometry_hints() {} ;
void gtk_window_set_gravity() {} ;
void gtk_window_set_has_frame() {} ;
void gtk_window_set_icon() {} ;
void gtk_window_set_icon_from_file() {} ;
void gtk_window_set_icon_list() {} ;
void gtk_window_set_icon_name() {} ;
void gtk_window_set_keep_above() {} ;
void gtk_window_set_keep_below() {} ;
void gtk_window_set_mnemonic_modifier() {} ;
void gtk_window_set_modal() {} ;
void gtk_window_set_position() {} ;
void gtk_window_set_resizable() {} ;
void gtk_window_set_role() {} ;
void gtk_window_set_screen() {} ;
void gtk_window_set_skip_pager_hint() {} ;
void gtk_window_set_skip_taskbar_hint() {} ;
void gtk_window_set_title() {} ;
void gtk_window_set_transient_for() {} ;
void gtk_window_set_type_hint() {} ;
void gtk_window_set_wmclass() {} ;
void gtk_window_stick() {} ;
void gtk_window_type_get_type() {} ;
void gtk_window_unfullscreen() {} ;
void gtk_window_unmaximize() {} ;
void gtk_window_unstick() {} ;
void gtk_wrap_mode_get_type() {} ;
__asm__(".globl gtk_binary_age; .pushsection .data; .type gtk_binary_age,@object; .size gtk_binary_age, 4; gtk_binary_age: .long 0; .popsection");
__asm__(".globl gtk_debug_flags; .pushsection .data; .type gtk_debug_flags,@object; .size gtk_debug_flags, 4; gtk_debug_flags: .long 0; .popsection");
__asm__(".globl gtk_interface_age; .pushsection .data; .type gtk_interface_age,@object; .size gtk_interface_age, 4; gtk_interface_age: .long 0; .popsection");
__asm__(".globl gtk_major_version; .pushsection .data; .type gtk_major_version,@object; .size gtk_major_version, 4; gtk_major_version: .long 0; .popsection");
__asm__(".globl gtk_micro_version; .pushsection .data; .type gtk_micro_version,@object; .size gtk_micro_version, 4; gtk_micro_version: .long 0; .popsection");
__asm__(".globl gtk_minor_version; .pushsection .data; .type gtk_minor_version,@object; .size gtk_minor_version, 4; gtk_minor_version: .long 0; .popsection");
| 40.037168 | 158 | 0.773651 | [
"object"
] |
129dd92149437351daf8e4b671cf1bf66461ad45 | 48,407 | c | C | test/ft_printf_tester_save/src/tests.c | saladuit/ft_printf | e56f527e73d93b464999f40326762d9b2fe3fe09 | [
"MIT"
] | null | null | null | test/ft_printf_tester_save/src/tests.c | saladuit/ft_printf | e56f527e73d93b464999f40326762d9b2fe3fe09 | [
"MIT"
] | null | null | null | test/ft_printf_tester_save/src/tests.c | saladuit/ft_printf | e56f527e73d93b464999f40326762d9b2fe3fe09 | [
"MIT"
] | null | null | null | #include "ft_printf_tester.h"
#include "helpers.h"
#include "libftprintf.h"
extern char g_orig_fake_stdout[BUFSIZ];
extern char g_user_fake_stdout[BUFSIZ];
extern char *g_test_params;
extern int g_test_nbr;
extern int already_printed_help;
extern int g_current_test;
extern int g_all_bonus;
int right_cat = 1;
int run_tests(int test_cat)
{
int wstatus;
char *null_str = NULL;
int should_run = 1;
describe("basic test");
PRINTF(("1, 2, 3, -d test, testing, 0.4s sound, 1, 2, 3xp, sound, -*dtest"));
// if no cateogry was specified, then run all of the categories
right_cat = test_cat ? test_cat & (CAT_C | CAT_MANDATORY) : 1;
describe("\n%c basic");
PRINTF(("%c", 'a'));
PRINTF(("%c%c%c*", '\0', '1', 1));
PRINTF(("%c small string", 'a'));
PRINTF(("%c small string", '\0'));
PRINTF(("the char is: %c", 'a'));
PRINTF(("the char is: %c", '\0'));
PRINTF(("n%cs", 'a'));
PRINTF(("%c%c%c%c%c", 'a', 'i', 'u', 'e', 'o'));
PRINTF(("l%cl%cl%cl%cl%c", 'a', 'i', 'u', 'e', 'o'));
PRINTF(("l%cl%cl%cl%cl%c", '\0', '\0', '\0', 'e', '\0'));
right_cat = test_cat ? test_cat & (CAT_S | CAT_MANDATORY) : 1;
describe("\n%s basic");
PRINTF(("%s", ""));
PRINTF(("this is a %s", "test"));
PRINTF(("this is 1 %s with %s %s", "test", "multiple", "strings"));
PRINTF(("%s%s%s%s", "This ", "is", " an ugly ", "test"));
PRINTF(("%s", "This is a rather simple test."));
PRINTF(("%s", "-2"));
PRINTF(("%s", "-24"));
PRINTF(("%s", "-stop"));
PRINTF(("%s", "-0003"));
PRINTF(("%s", "000-0003"));
PRINTF(("%s", "0x42"));
PRINTF(("%s", "0x0000042"));
PRINTF(("some naugty tests: %s", "0000%"));
PRINTF(("some naugty tests: %s", " %"));
PRINTF(("some naugty tests: %s", "%000"));
PRINTF(("%s", null_str));
PRINTF(("%s everywhere", null_str));
PRINTF(("everywhere %s", null_str));
PRINTF(("%s", "h"));
PRINTF(("t%st%s", "a", "u"));
PRINTF(("%s%s%s%s%s%s", "a", "i", "u", "e", "o", "l"));
right_cat = test_cat ? test_cat & (CAT_P | CAT_MANDATORY) : 1;
describe("\n%p basic");
int test = 42;
PRINTF(("%p", &test));
PRINTF(("%p is a virtual memory address", &test));
PRINTF(("The address of the answer is %p", &test));
PRINTF(("The address is %p, so what?", &test));
int *ptr = &test;
PRINTF(("A pointer at %p points to %p", &test, &ptr));
PRINTF(("This %p is a very strange address", (void *)(long int)test));
char *mallocked = malloc(2);
PRINTF(("This %p is an address from the heap", mallocked); free(mallocked);); free(mallocked);
PRINTF_EXPECTED(("%p", NULL), /* expected: */ ("0x0"));
PRINTF_EXPECTED(("The NULL macro represents the %p address", NULL), ("The NULL macro represents the 0x0 address"));
PRINTF(("This %p is even stranger", (void *)-1));
right_cat = test_cat ? test_cat & (CAT_D | CAT_MANDATORY) : 1;
describe("\n%d basic");
PRINTF(("%d", 0));
PRINTF(("%d", 10));
PRINTF(("%d, %d", 10, 20));
PRINTF(("%d%d%d%d", 10, 20, 30, 5));
PRINTF(("%d %d", 2147483647, (int)-2147483648));
PRINTF(("42 - 84 is %d", -42));
PRINTF(("%d C is the lowest temperature in the universe", -273));
PRINTF(("%dxC is the lowest temperature in the universe", -273));
PRINTF(("%dsC is the lowest temperature in the universe", -273));
PRINTF(("%dpC is the lowest temperature in the universe", -273));
right_cat = test_cat ? test_cat & (CAT_I | CAT_MANDATORY) : 1;
describe("\n%i basic");
PRINTF(("%i", 0));
PRINTF(("%i", 10));
PRINTF(("%i, %i", 10, 23));
PRINTF(("%i%i%i%i%i%i%i", 10, 23, -2, 37, 200, -9999, 977779));
PRINTF(("%i %i", 2147483647, (int)-2147483648));
PRINTF(("%iq%i", 21447, -21648));
right_cat = test_cat ? test_cat & (CAT_U | CAT_MANDATORY) : 1;
describe("\n%u basic");
PRINTF(("%u", 42));
PRINTF(("%u", 0));
PRINTF(("%u", 2147483647));
PRINTF(("%u", (unsigned int)2147483648));
PRINTF(("%u", (unsigned int)3147983649));
PRINTF(("%u", (unsigned int)4294967295));
PRINTF(("%u to the power of %u is %u", 2, 32, (unsigned int)4294967295));
PRINTF(("%u%u%u%u", (unsigned int)429896724, 0, 32, (unsigned int)4294967295));
right_cat = test_cat ? test_cat & (CAT_X | CAT_MANDATORY ) : 1;
describe("\n%x basic");
PRINTF(("%x", 0));
PRINTF(("%x", 1));
PRINTF(("%x", 10));
PRINTF(("%x", 16));
PRINTF(("%x", 160));
PRINTF(("%x", 255));
PRINTF(("%x", 256));
PRINTF(("%x", 3735929054u));
PRINTF(("the password is %x", 3735929054u));
PRINTF(("%x is the definitive answer", 66u));
PRINTF(("this is the real number: %x", -1u));
right_cat = test_cat ? test_cat & (CAT_BIG_X | CAT_MANDATORY ): 1;
describe("\n%X basic");
PRINTF(("%X", 0));
PRINTF(("%X", 1));
PRINTF(("%X", 10));
PRINTF(("%X", 16));
PRINTF(("%X", 160));
PRINTF(("%X", 255));
PRINTF(("%X", 256));
PRINTF(("%X", (unsigned int)3735929054));
PRINTF(("the password is %X", (unsigned int)3735929054));
PRINTF(("%X is the definitive answer", (unsigned int)66));
PRINTF(("this is the real number: %X", (unsigned int)-1));
right_cat = test_cat ? test_cat & (CAT_PERCENT | CAT_MANDATORY) : 1;
describe("\n%% basic");
PRINTF(("%%"));
PRINTF(("100%%"));
PRINTF(("%%p is how you print a pointer in printf"));
PRINTF(("the '%%%%' is used to print a %% in printf"));
PRINTF(("%%%%%%%%%%%%%%%%"));
PRINTF(("%%c%%s%%p%%d%%i%%u%%x%%X%%"));
right_cat = test_cat ? test_cat & CAT_MANDATORY : 1;
describe("\nmix");
PRINTF(("%c - %s - %p %d - %i - %u - %x %X %%", 'a', "test", (void *)0xdeadc0de, 20, -20, -1, -1, 200000000));
PRINTF(("%c - %s - %p %d - %i - %u - %x %X %%", '\0', "test", (void *)-1, 20, -20, -1, -1, 200000000));
PRINTF(("%c - %s - %p %d - %i - %u - %x %X %%", 'c', "", (void *)-1, 20, -20, -1, -1, 200000000));
PRINTF(("%i - %s - %p %d - %c - %u - %x %X %%", 20, "", (void *)-1, '\0', -20, -1, -1, 200000000));
PRINTF_EXPECTED(("%c - %s - %p %d - %i - %u - %x %X %%", 'b', null_str, NULL, 20, -20, -1, -1, 200000000),
("b - (null) - 0x0 20 - -20 - 4294967295 - ffffffff BEBC200 %%"));
PRINTF(("%c %s - %p - %d - %i %u - %x - %X %%", '\0', null_str, (void *)0xdeadc0de, 0, (int)-2147483648, -1, -1, 200000000));
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_C && test_cat & CAT_BONUS_1)
: 1;
describe("\n%c and widths");
PRINTF(("%1c", 'a'))
PRINTF(("%1c", '\0'))
PRINTF(("%10c", 'b'))
PRINTF(("%10c", '\0'))
PRINTF(("%2c", 'c'))
PRINTF(("there are 15 spaces between this text and the next char%15c", 'd'))
PRINTF(("%5chis paragraph is indented", 't'))
PRINTF(("%5c now you see", '\0'))
PRINTF(("The number %7c represents luck", '7'))
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_S && test_cat & CAT_BONUS_1)
: 1;
describe("\n%s and widths");
PRINTF(("%1s", "a"));
PRINTF(("%1s", "abc"));
PRINTF(("%7s", "a"));
PRINTF(("%7s", "abc"));
PRINTF(("%1s", "-42"));
PRINTF(("%2s", "-42"));
PRINTF(("%3s", "-42"));
PRINTF(("%4s", "-42"));
PRINTF(("%5s", "-42"));
PRINTF(("%6s", "-42"));
PRINTF(("%1s", null_str));
PRINTF(("%2s", null_str));
PRINTF(("%5s", null_str));
PRINTF(("%6s", null_str));
PRINTF(("%7s", null_str));
PRINTF(("%7s is as easy as %13s", "abc", "123"));
PRINTF(("%13s are the three first letter of the %3s", "a, b and c", "alphabet"));
PRINTF(("%s%13s%42s%3s", "a, b and c", " are letters", " of the", " alphabet"));
PRINTF(("%sc%13sd%42sp%3sx", "a, b and c", " are letters", " of the", " alphabet"));
PRINTF(("%sc%13sd%42sp%3sx", "a, b and c", " are letters", " of the", " alphabet"));
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_P && test_cat & CAT_BONUS_1)
: 1;
describe("\n%p and widths");
char c;
PRINTF(("%1p", &c));
PRINTF(("%30p", &c));
PRINTF(("%12p", (void *)0x7ffe6b8e60c6));
PRINTF(("%13p", (void *)0x7ffe6b8e60c5));
PRINTF(("%14p", (void *)0x7ffe6b8e60c4));
PRINTF(("the address is %12p", (void *)0x7ffe6b8e60c7));
PRINTF(("the address is %13p", (void *)0x7ffe6b8e60c8));
PRINTF(("the address is %14p", (void *)0x7ffe6b8e60c9));
PRINTF_EXPECTED(("the address is %1p", (void *)0), /* expected: */ ("the address is 0x0"));
PRINTF_EXPECTED(("the address is %2p", (void *)0), /* expected: */ ("the address is 0x0"));
PRINTF_EXPECTED(("the address is %3p", (void *)0), /* expected: */ ("the address is 0x0"));
PRINTF_EXPECTED(("the address is %4p", (void *)0), /* expected: */ ("the address is 0x0"));
PRINTF_EXPECTED(("the address is %8p", (void *)0), /* expected: */ ("the address is 0x0"));
PRINTF(("%12p is the address", (void *)0x7ffe6b8e60c7));
PRINTF(("%13p is the address", (void *)0x7ffe6b8e60c8));
PRINTF(("%14p is the address", (void *)0x7ffe6b8e60c9));
PRINTF_EXPECTED(("%1p is the address", (void *)0), /* expected: */ ("0x0 is the address"));
PRINTF_EXPECTED(("%2p is the address", (void *)0), /* expected: */ ("0x0 is the address"));
PRINTF_EXPECTED(("%3p is the address", (void *)0), /* expected: */ ("0x0 is the address"));
PRINTF_EXPECTED(("%4p is the address", (void *)0), /* expected: */ (" 0x0 is the address"));
PRINTF_EXPECTED(("%8p is the address", (void *)0), /* expected: */ (" 0x0 is the address"));
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_D && test_cat & CAT_BONUS_1)
: 1;
describe("\n%d and widths");
PRINTF(("%1d", 0));
PRINTF(("%1d", -4));
PRINTF(("%10d", 42));
PRINTF(("%42d", 42000));
PRINTF(("%20d", -42000));
PRINTF(("wait for it... %50d", 42));
PRINTF(("%20d is how many tests are going to be made", 8000));
PRINTF(("%5d", 2147483647));
PRINTF(("%30d", 2147483647));
PRINTF(("%10d", 2147483647));
PRINTF(("%5d", (int)-2147483648));
PRINTF(("%30d", (int)-2147483648));
PRINTF(("%10d", (int)-2147483648));
PRINTF(("%11d", (int)-2147483648));
PRINTF(("%12d", (int)-2147483648));
PRINTF(("%12d, %20d, %2d, %42d", (int)-2147483648, 3, 30, -1));
PRINTF(("%12d, %d, %2d, %42d", (int)-2147483648, 3, 30, -1));
PRINTF(("%14d%20d%2d%d", (int)-2147483648, 3, 30, -1));
PRINTF(("%14dc%20ds%2dx%du", (int)-2147483648, 3, 30, -1));
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_I && test_cat & CAT_BONUS_1)
: 1;
describe("\n%i and widths");
PRINTF(("%1i", 0));
PRINTF(("%1i", -4));
PRINTF(("%10i", 42));
PRINTF(("%42i", 42000));
PRINTF(("%20i", -42000));
PRINTF(("wait for it... %50i", 42));
PRINTF(("%20i is how many tests are going to be made", 8000));
PRINTF(("%5i", 2147483647));
PRINTF(("%30i", 2147483647));
PRINTF(("%10i", 2147483647));
PRINTF(("%5i", (int)-2147483648));
PRINTF(("%30i", (int)-2147483648));
PRINTF(("%10i", (int)-2147483648));
PRINTF(("%11i", (int)-2147483648));
PRINTF(("%12i", (int)-2147483648));
PRINTF(("%12i, %20i, %2i, %42i", (int)-2147483648, 3, 30, -1));
PRINTF(("%12i, %i, %2i, %42i", (int)-2147483648, 3, 30, -1));
PRINTF(("%14i%20i%2i%i", (int)-2147483648, 3, 30, -1));
PRINTF(("%14ic%20is%2ix%du", (int)-2147483648, 3, 30, -1));
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_U && test_cat & CAT_BONUS_1)
: 1;
describe("\n%u and widths");
PRINTF(("%1u", 0));
PRINTF(("%2u", 1));
PRINTF(("%1u", 1000));
PRINTF(("%4u", 1000));
PRINTF(("%30u", 1000));
PRINTF(("%9u is the biggest unsigned int", (unsigned int)-1));
PRINTF(("%10uis the biggest unsigned int", (unsigned int)-1));
PRINTF(("%11uis the biggest unsigned int", (unsigned int)-1));
PRINTF(("the biggest unsigned int is %9u", (unsigned int)-1));
PRINTF(("the biggest unsigned int is %10u", (unsigned int)-1));
PRINTF(("the biggest unsigned int is %11u", (unsigned int)-1));
PRINTF(("Here are some numbers: %1u%2u%5u%3u%9u and %ui", 11, (unsigned int)-1, 2, 200, 3, 10));
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_X && test_cat & CAT_BONUS_1)
: 1;
describe("\n%x and widths");
PRINTF(("%1x", 0));
PRINTF(("%2x", 1));
PRINTF(("%3x", 10));
PRINTF(("%1x", 16));
PRINTF(("%2x", 160));
PRINTF(("%3x", 255));
PRINTF(("%42x", 256));
PRINTF(("%7x", (unsigned int)3735929054));
PRINTF(("%8x", (unsigned int)3735929054));
PRINTF(("%9x", (unsigned int)3735929054));
PRINTF(("the password is %7x", (unsigned int)3735929054));
PRINTF(("the password is %8x", (unsigned int)3735929054));
PRINTF(("the password is %9x", (unsigned int)3735929054));
PRINTF(("%1x is the definitive answer", (unsigned int)66));
PRINTF(("%2x is the definitive answer", (unsigned int)66));
PRINTF(("%3x is the definitive answer", (unsigned int)66));
PRINTF(("this is the real number: %7x", (unsigned int)-1));
PRINTF(("this is the real number: %8x", (unsigned int)-1));
PRINTF(("this is the real number: %9x", (unsigned int)-1));
PRINTF(("%1x%2x%9x", (unsigned int)-1, 0xf0ca, 123456));
PRINTF(("%1xis doomed%2xpost%9xX args", (unsigned int)-1, 0xf0b1a, 7654321));
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_BIG_X && test_cat & CAT_BONUS_1)
: 1;
describe("\n%X and widths");
PRINTF(("%1X", 0));
PRINTF(("%2X", 1));
PRINTF(("%3X", 10));
PRINTF(("%1X", 16));
PRINTF(("%2X", 160));
PRINTF(("%3X", 255));
PRINTF(("%42X", 256));
PRINTF(("%7X", (unsigned int)3735929054));
PRINTF(("%8X", (unsigned int)3735929054));
PRINTF(("%9X", (unsigned int)3735929054));
PRINTF(("the password is %7X", (unsigned int)3735929054));
PRINTF(("the password is %8X", (unsigned int)3735929054));
PRINTF(("the password is %9X", (unsigned int)3735929054));
PRINTF(("%1X is the definitive answer", (unsigned int)66));
PRINTF(("%2X is the definitive answer", (unsigned int)66));
PRINTF(("%3X is the definitive answer", (unsigned int)66));
PRINTF(("this is the real number: %7X", (unsigned int)-1));
PRINTF(("this is the real number: %8X", (unsigned int)-1));
PRINTF(("this is the real number: %9X", (unsigned int)-1));
PRINTF(("%1X%2X%9X", (unsigned int)-1, 0xf0ca, 123456));
PRINTF(("%1Xis doomed%2Xpost%9Xx args", (unsigned int)-1, 0xf0b1a, 7654321));
describe("\n%s and precisions");
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_S && test_cat & CAT_BONUS_1)
: 1;
PRINTF(("%.s", "hi there"));
PRINTF(("%.0s", "hi there"));
PRINTF(("%.1s", "hi there"));
PRINTF(("%.2s", "hi there"));
PRINTF(("%.3s", "hi there"));
PRINTF(("%.4s", "hi there"));
PRINTF(("%.7s", "hi there"));
PRINTF(("%.8s", "hi there"));
PRINTF(("%.9s", "hi there"));
PRINTF(("%.12s", "hi there"));
PRINTF(("%.s", "-42"));
PRINTF(("%.0s", "-42"));
PRINTF(("%.1s", "-42"));
PRINTF(("%.2s", "-42"));
PRINTF(("%.3s", "-42"));
PRINTF(("%.4s", "-42"));
PRINTF(("%.7s", "-42"));
PRINTF_EXPECTED(("%.1s", null_str), /* expected: */ ("("));
PRINTF_EXPECTED(("%.2s", null_str), /* expected: */ ("(n"));
PRINTF_EXPECTED(("%.5s", null_str), /* expected: */ ("(null"));
PRINTF(("%.6s", null_str));
PRINTF(("%.7s", null_str));
PRINTF(("%.2s, motherfucker", "hi there"));
PRINTF(("This %.3s a triumph ", "wasabi"));
PRINTF(("%.4s making a %.4s here: %.13s", "I'm delighted", "notation", "HUGE SUCCESS!"));
PRINTF(("It's %.4s to over%.50s my%s", "hardware", "state", " satisfaction"));
PRINTF(("%.11s%.6s%.4s", "Aperture", " Scientists", "ce"));
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_D && test_cat & CAT_BONUS_1)
: 1;
describe("\n%d and precisions");
PRINTF(("%.1d", 2))
PRINTF(("%.2d", 3))
PRINTF(("%.4d", 32))
PRINTF(("%.3d", 420000))
PRINTF(("%.0d", 420000))
PRINTF(("%.3d", -1))
PRINTF(("%.3d", -1234))
PRINTF(("%.4d", -1234))
PRINTF(("%.5d", -1234))
PRINTF(("%.5d", (int)-2147483648))
PRINTF(("%.9d", (int)-2147483648))
PRINTF(("%.10d", (int)-2147483648))
PRINTF(("%.11d", (int)-2147483648))
PRINTF(("%.12d", (int)-2147483648))
PRINTF(("%.13d", (int)-2147483648))
PRINTF(("%.5d", 2147483647))
PRINTF(("%.9d", 2147483647))
PRINTF(("%.10d", 2147483647))
PRINTF(("%.11d", 2147483647))
PRINTF(("%.12d", 2147483647))
PRINTF(("%.0d", 2))
PRINTF(("%.0d", 2147483647))
PRINTF(("%.0d", 0))
PRINTF(("%.0d", 10))
PRINTF(("%.d", 10))
PRINTF(("%.d", 0))
PRINTF(("I'm gonna watch %.3d", 7))
PRINTF(("%.3d is the movie I'm gonna watch", 7))
PRINTF(("Then take these %.7d things and get the hell out of here", 2))
PRINTF(("Bla %.2di bla %.5dsbla bla %.dx bla %.d", 127, 42, 1023, 0))
PRINTF(("%.4d%.2d%.20d%.0d%.0d%.d%.d%.d", 127, 0, 1023, 0, (int)-2147483648, 0, 1, (int)-2147483648))
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_I && test_cat & CAT_BONUS_1)
: 1;
describe("\n%i and precisions");
PRINTF(("%.1i", 7))
PRINTF(("%.3i", 7))
PRINTF(("%.2i", 3))
PRINTF(("%.4i", 32))
PRINTF(("%.3i", 420000))
PRINTF(("%.0i", 420000))
PRINTF(("%.3i", -1))
PRINTF(("%.3i", -1234))
PRINTF(("%.4i", -1234))
PRINTF(("%.5i", -1234))
PRINTF(("%.5i", (int)-2147483648))
PRINTF(("%.9i", (int)-2147483648))
PRINTF(("%.10i", (int)-2147483648))
PRINTF(("%.11i", (int)-2147483648))
PRINTF(("%.12i", (int)-2147483648))
PRINTF(("%.13i", (int)-2147483648))
PRINTF(("%.5i", 2147483647))
PRINTF(("%.9i", 2147483647))
PRINTF(("%.10i", 2147483647))
PRINTF(("%.11i", 2147483647))
PRINTF(("%.12i", 2147483647))
PRINTF(("%.0i", 2))
PRINTF(("%.0i", 2147483647))
PRINTF(("%.0i", 0))
PRINTF(("%.0i", 10))
PRINTF(("%.i", 10))
PRINTF(("%.i", 0))
PRINTF(("I'm gonna watch %.3i", 7))
PRINTF(("%.3i is the movie I'm gonna watch", 7))
PRINTF(("Then take these %.7i things and get the hell out of here", 2))
PRINTF(("Bla %.2ii bla %.5isbla bla %.ix bla %.i", 127, 42, 1023, 0))
PRINTF(("%.4i%.2i%.20i%.0i%.0i%.i%.i%.i", 127, 0, 1023, 0, (int)-2147483648, 0, 1, (int)-2147483648))
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_U && test_cat & CAT_BONUS_1)
: 1;
describe("\n%u and precisions");
PRINTF(("%.1u", 1))
PRINTF(("%.2u", 1))
PRINTF(("%.2u", 0))
PRINTF(("%.0u", 0))
PRINTF(("%.u", 0))
PRINTF(("%.2u", 30000))
PRINTF(("%.20u", 30000))
PRINTF(("%.0u", (unsigned int)-1))
PRINTF(("%.5u", (unsigned int)-1))
PRINTF(("%.9u", (unsigned int)-1))
PRINTF(("%.10u", (unsigned int)-1))
PRINTF(("%.11u", (unsigned int)-1))
PRINTF(("%.10uis a big number", (unsigned int)-1))
PRINTF(("%.0uis a big number", (unsigned int)-1))
PRINTF(("%.4us a big number", (unsigned int)-1))
PRINTF(("%.9uxs a big number", (unsigned int)-1))
PRINTF(("%.11ups a big number", (unsigned int)-1))
PRINTF(("the number is %.0u", (unsigned int)-1))
PRINTF(("the number is %.u", (unsigned int)-1))
PRINTF(("the number is %.5u", (unsigned int)-1))
PRINTF(("the number is %.9u", (unsigned int)-1))
PRINTF(("the number is %.10u", (unsigned int)-1))
PRINTF(("the number is %.11u", (unsigned int)-1))
PRINTF(("the number is %.11u", (unsigned int)-1))
PRINTF(("%.0uis a big number", 0))
PRINTF(("%.4us a big number", 0))
PRINTF(("the number is %.0u", 0))
PRINTF(("the number is %.u", 0))
PRINTF(("the number is %.5u", 0))
PRINTF(("%u%.5u%.0u%.u%.9u", 5, 55, 2, 0, 42))
PRINTF(("%us%.5ui%.0uc%.up%.9ux", 5, 55, 2, 0, 42))
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_X && test_cat & CAT_BONUS_1)
: 1;
describe("\n%x and precisions");
PRINTF(("%.1x", 0xa))
PRINTF(("%.4x", 11))
PRINTF(("%.0x", 0))
PRINTF(("%.1x", -1))
PRINTF(("%.10x", -1))
PRINTF(("%.14x", -1))
PRINTF(("%.8x", 0))
PRINTF(("%.2x", 30000))
PRINTF(("%.20x", 30000))
PRINTF(("%.0x", (unsigned int)-1))
PRINTF(("%.5x", (unsigned int)-1))
PRINTF(("%.9x", (unsigned int)-1))
PRINTF(("%.10x", (unsigned int)-1))
PRINTF(("%.11x", (unsigned int)-1))
PRINTF(("%.10xis a big number", (unsigned int)-1))
PRINTF(("%.0xis a big number", (unsigned int)-1))
PRINTF(("%.4xs a big number", (unsigned int)-1))
PRINTF(("%.9xxs a big number", (unsigned int)-1))
PRINTF(("%.11xps a big number", (unsigned int)-1))
PRINTF(("the number is %.0x", (unsigned int)-1))
PRINTF(("the number is %.x", (unsigned int)-1))
PRINTF(("the number is %.5x", (unsigned int)-1))
PRINTF(("the number is %.9x", (unsigned int)-1))
PRINTF(("the number is %.10x", (unsigned int)-1))
PRINTF(("the number is %.11x", (unsigned int)-1))
PRINTF(("the number is %.11x", (unsigned int)-1))
PRINTF(("%.0xis a big number", 0))
PRINTF(("%.4xs a big number", 0))
PRINTF(("the number is %.0x", 0))
PRINTF(("the number is %.x", 0))
PRINTF(("the number is %.5x", 0))
PRINTF(("%x%.5x%.0x%.x%.9x", 5, 55, 2, 0, 42))
PRINTF(("%xs%.5xi%.0xc%.xp%.9xu", 5, 55, 2, 0, 42))
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_BIG_X && test_cat & CAT_BONUS_1)
: 1;
describe("\n%X and precisions");
PRINTF(("%.1X", 0xa))
PRINTF(("%.4X", 11))
PRINTF(("%.0X", 0))
PRINTF(("%.1X", -1))
PRINTF(("%.10X", -1))
PRINTF(("%.14X", -1))
PRINTF(("%.8X", 0))
PRINTF(("%.2X", 30000))
PRINTF(("%.20X", 30000))
PRINTF(("%.0X", (unsigned int)-1))
PRINTF(("%.5X", (unsigned int)-1))
PRINTF(("%.9X", (unsigned int)-1))
PRINTF(("%.10X", (unsigned int)-1))
PRINTF(("%.11X", (unsigned int)-1))
PRINTF(("%.10Xis a big number", (unsigned int)-1))
PRINTF(("%.0Xis a big number", (unsigned int)-1))
PRINTF(("%.4Xs a big number", (unsigned int)-1))
PRINTF(("%.9XXs a big number", (unsigned int)-1))
PRINTF(("%.11Xps a big number", (unsigned int)-1))
PRINTF(("the number is %.0X", (unsigned int)-1))
PRINTF(("the number is %.X", (unsigned int)-1))
PRINTF(("the number is %.5X", (unsigned int)-1))
PRINTF(("the number is %.9X", (unsigned int)-1))
PRINTF(("the number is %.10X", (unsigned int)-1))
PRINTF(("the number is %.11X", (unsigned int)-1))
PRINTF(("the number is %.11X", (unsigned int)-1))
PRINTF(("%.0Xis a big number", 0))
PRINTF(("%.4Xs a big number", 0))
PRINTF(("the number is %.0X", 0))
PRINTF(("the number is %.X", 0))
PRINTF(("the number is %.5X", 0))
PRINTF(("%X%.5X%.0X%.X%.9X", 5, 55, 2, 0, 42))
PRINTF(("%Xs%.5Xi%.0Xc%.Xp%.9Xu", 5, 55, 2, 0, 42))
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_C && test_cat & CAT_BONUS_1)
: 1;
describe("\n%c, widths and -");
// this is literally a negative width '-'
PRINTF(("%-c", 'p'));
PRINTF(("%-1c", 'b'));
PRINTF(("%-5c", 'w'));
PRINTF((" kk daora%-5cblz", 'w'));
PRINTF(("%-20carigatou", 'w'));
PRINTF(("%-c%-c%-4c%-11c", 'a', 'b', 'c', 'd'));
PRINTF(("%-ci%-cp%4cs%-11cx", 'a', 'b', 'c', 'd'));
PRINTF(("%----ci%---cp%4cs%--11cx", 'a', 'b', 'c', 'd'));
PRINTF(("%-c%-c%c*", 0, '1', 1));
PRINTF(("%-2c%-3c%-4c*", 0, 'a', 0));
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_S && test_cat & CAT_BONUS_1)
: 1;
describe("\n%s, widths, precisions and -");
PRINTF(("%-9sScience!", "Aperture"));
PRINTF(("We %-s what we %8s, %-2s we %-20s", "do", "must", "because", "can"));
PRINTF(("%--4s %s %------------------9s of %s of %-5s", "for", "the", "goooood", "aaall", "us"));
PRINTF(("%--4.1s %s %------------------9.3s of %s of %-5.7s", "for", "the", "goooood", "aaall", "us"));
PRINTF(("%--.sp--.su kkkk", "pegadinha po"));
PRINTF(("%-9sScience!", "-42"));
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_P && test_cat & CAT_BONUS_1)
: 1;
describe("\n%p, widths and -");
PRINTF(("that's the way it %-20pis", ""));
PRINTF(("as soon as %-10possible", (void *) -1));
PRINTF(("as soon as %-16peasible", (void *) (((long int)3 << 42) + 15)));
PRINTF(("as soon as %-16peasible", (void *) (((long int)3 << 42) + 15)));
PRINTF(("thats %-psrobably not a good idea", (void *) 13));
PRINTF(("%------21pwhoa wtf is that", (void *) 13));
PRINTF(("%------21p yeah i'm %p running out %--p of ideas", (void *) 13, (void *) 65, (void *) -1));
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_D && test_cat & CAT_BONUS_1)
: 1;
describe("\n%d, widths, precisions and -");
PRINTF(("%-d", 0));
PRINTF(("%-d", 1));
PRINTF(("%-d", 10));
PRINTF(("%-d", -10));
PRINTF(("%-d", 5000));
PRINTF(("%-d", -5000));
PRINTF(("%-d", (int)-2147483648));
PRINTF(("%-d", 2147483647));
PRINTF(("%-1d", 0));
PRINTF(("%-1d", 1));
PRINTF(("%-1d", 10));
PRINTF(("%-1d", -10));
PRINTF(("%-1d", 5000));
PRINTF(("%-1d", -5000));
PRINTF(("%-1d", (int)-2147483648));
PRINTF(("%-1d", 2147483647));
PRINTF(("%-10d", 0));
PRINTF(("%-10d", 1));
PRINTF(("%-10d", 10));
PRINTF(("%-10d", -10));
PRINTF(("%-10d", 5000));
PRINTF(("%-10d", -5000));
PRINTF(("%-10d", (int)-2147483648));
PRINTF(("%-10d", 2147483647));
PRINTF(("%-.d", 0));
PRINTF(("%-.1d", 1));
PRINTF(("%-.2d", 10));
PRINTF(("%-.3d", -10));
PRINTF(("%-.4d", 5000));
PRINTF(("%-.5d", -5000));
PRINTF(("%-.6d", (int)-2147483648));
PRINTF(("%-.7d", 2147483647));
PRINTF(("%-1.8d", 0));
PRINTF(("%-1.9d", 1));
PRINTF(("%-1.10d", 10));
PRINTF(("%-1.0d", -10));
PRINTF(("%-1.6d", 5000));
PRINTF(("%-1.4d", -5000));
PRINTF(("%-1.10d", (int)-2147483648));
PRINTF(("%-1.12d", 2147483647));
PRINTF(("%-10.d", 0));
PRINTF(("%-10.10d", 1));
PRINTF(("%-10.5d", 10));
PRINTF(("%-10.2d", -10));
PRINTF(("%-10.5d", 5000));
PRINTF(("%-10.5d", -5000));
PRINTF(("%-10.15d", (int)-2147483648));
PRINTF(("%-10.5d", 2147483647));
PRINTF(("%-15.d", 0));
PRINTF(("%-15.10d", 1));
PRINTF(("%-15.5d", 10));
PRINTF(("%-15.2d", -10));
PRINTF(("%-15.5d", 5000));
PRINTF(("%-15.5d", -5000));
PRINTF(("%-15.15d", (int)-2147483648));
PRINTF(("%-15.5d", 2147483647));
PRINTF(("%-4.5d%d%4d%-10d-d5%-.3d", 3, 4, 5, 6, 7));
PRINTF(("%-4.5d%d%4d%-10d-d5%-.3d", 300000, 400000, 500000, 600000, 700000));
PRINTF(("%-4.5d%d%4d%-10d-d5%-.3d", -300000, -400000, -500000, -600000, -700000));
PRINTF(("%-4.5d%d%4d%-10d-d5%-.3d", 2147483647, 2141483647, 2141483647, 2141483647, 2141483647));
PRINTF(("%-4.5d%d%4d%-10d-d5%-.3d", (int)-2147483648, (int)-2141483648, (int)-2141483648, (int)-2141483648, (int)-2141483648));
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_I && test_cat & CAT_BONUS_1)
: 1;
describe("\n%i, widths, precisions and -");
PRINTF(("%-i", 0));
PRINTF(("%-i", 1));
PRINTF(("%-i", 10));
PRINTF(("%-i", -10));
PRINTF(("%-i", 5000));
PRINTF(("%-i", -5000));
PRINTF(("%-i", (int)-2147483648));
PRINTF(("%-i", 2147483647));
PRINTF(("%-1i", 0));
PRINTF(("%-1i", 1));
PRINTF(("%-1i", 10));
PRINTF(("%-1i", -10));
PRINTF(("%-1i", 5000));
PRINTF(("%-1i", -5000));
PRINTF(("%-1i", (int)-2147483648));
PRINTF(("%-1i", 2147483647));
PRINTF(("%-10i", 0));
PRINTF(("%-10i", 1));
PRINTF(("%-10i", 10));
PRINTF(("%-10i", -10));
PRINTF(("%-10i", 5000));
PRINTF(("%-10i", -5000));
PRINTF(("%-10i", (int)-2147483648));
PRINTF(("%-10i", 2147483647));
PRINTF(("%-.i", 0));
PRINTF(("%-.1i", 1));
PRINTF(("%-.2i", 10));
PRINTF(("%-.3i", -10));
PRINTF(("%-.4i", 5000));
PRINTF(("%-.5i", -5000));
PRINTF(("%-.6i", (int)-2147483648));
PRINTF(("%-.7i", 2147483647));
PRINTF(("%-1.8i", 0));
PRINTF(("%-1.9i", 1));
PRINTF(("%-1.10i", 10));
PRINTF(("%-1.0i", -10));
PRINTF(("%-1.6i", 5000));
PRINTF(("%-1.4i", -5000));
PRINTF(("%-1.10i", (int)-2147483648));
PRINTF(("%-1.12i", 2147483647));
PRINTF(("%-10.i", 0));
PRINTF(("%-10.10i", 1));
PRINTF(("%-10.5i", 10));
PRINTF(("%-10.2i", -10));
PRINTF(("%-10.5i", 5000));
PRINTF(("%-10.5i", -5000));
PRINTF(("%-10.15i", (int)-2147483648));
PRINTF(("%-10.5i", 2147483647));
PRINTF(("%-15.i", 0));
PRINTF(("%-15.10i", 1));
PRINTF(("%-15.5i", 10));
PRINTF(("%-15.2i", -10));
PRINTF(("%-15.5i", 5000));
PRINTF(("%-15.5i", -5000));
PRINTF(("%-15.15i", (int)-2147483648));
PRINTF(("%-15.5i", 2147483647));
PRINTF(("%-4.5i%i%4i%-10i-i5%-.3i", 3, 4, 5, 6, 7));
PRINTF(("%-4.5i%i%4i%-10i-i5%-.3i", 300000, 400000, 500000, 600000, 700000));
PRINTF(("%-4.5i%i%4i%-10i-i5%-.3i", -300000, -400000, -500000, -600000, -700000));
PRINTF(("%-4.5i%i%4i%-10i-i5%-.3i", 2147483647, 2141483647, 2141483647, 2141483647, 2141483647));
PRINTF(("%-4.5i%i%4i%-10i-i5%-.3i", (int)-2147483648, (int)-2141483648, (int)-2141483648, (int)-2141483648, (int)-2141483648));
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_U && test_cat & CAT_BONUS_1)
: 1;
describe("\n%u, widths, precisions and -");
PRINTF(("%-u", 0));
PRINTF(("%-u", 1));
PRINTF(("%-u", 10));
PRINTF(("%-u", -10));
PRINTF(("%-u", 5000));
PRINTF(("%-u", -5000));
PRINTF(("%-u", (unsigned int)-1));
PRINTF(("%-u", 2147483647));
PRINTF(("%-1u", 0));
PRINTF(("%-1u", 1));
PRINTF(("%-1u", 10));
PRINTF(("%-1u", -10));
PRINTF(("%-1u", 5000));
PRINTF(("%-1u", -5000));
PRINTF(("%-1u", (unsigned int)-1));
PRINTF(("%-1u", 2147483647));
PRINTF(("%-10u", 0));
PRINTF(("%-10u", 1));
PRINTF(("%-10u", 10));
PRINTF(("%-10u", -10));
PRINTF(("%-10u", 5000));
PRINTF(("%-10u", -5000));
PRINTF(("%-10u", -1));
PRINTF(("%-10u", 2147483647));
PRINTF(("%-.u", 0));
PRINTF(("%-.1u", 1));
PRINTF(("%-.2u", 10));
PRINTF(("%-.3u", -10));
PRINTF(("%-.4u", 5000));
PRINTF(("%-.5u", -5000));
PRINTF(("%-.6u", -1));
PRINTF(("%-.7u", 2147483647));
PRINTF(("%-1.8u", 0));
PRINTF(("%-1.9u", 1));
PRINTF(("%-1.10u", 10));
PRINTF(("%-1.0u", -10));
PRINTF(("%-1.6u", 5000));
PRINTF(("%-1.4u", -5000));
PRINTF(("%-1.10u", -1));
PRINTF(("%-1.12u", 2147483647));
PRINTF(("%-10.u", 0));
PRINTF(("%-10.10u", 1));
PRINTF(("%-10.5u", 10));
PRINTF(("%-10.2u", -10));
PRINTF(("%-10.5u", 5000));
PRINTF(("%-10.5u", -5000));
PRINTF(("%-10.15u", -1));
PRINTF(("%-10.5u", 2147483647));
PRINTF(("%-15.u", 0));
PRINTF(("%-15.10u", 1));
PRINTF(("%-15.5u", 10));
PRINTF(("%-15.2u", -10));
PRINTF(("%-15.5u", 5000));
PRINTF(("%-15.5u", -5000));
PRINTF(("%-15.15u", -1));
PRINTF(("%-15.5u", 2147483647));
PRINTF(("%-4.5u%u%4u%-10u-u5%-.3u", 3, 4, 5, 6, 7));
PRINTF(("%-4.5u%u%4u%-10u-u5%-.3u", 300000, 400000, 500000, 600000, 700000));
PRINTF(("%-4.5u%u%4u%-10u-u5%-.3u", -300000, -400000, -500000, -600000, -700000));
PRINTF(("%-4.5u%u%4u%-10u-u5%-.3u", 2147483647, 2141483647, 2141483647, 2141483647, 2141483647));
PRINTF(("%-4.5u%u%4u%-10u-u5%-.3u", -1, -1, -1, -1, -1));
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_X && test_cat & CAT_BONUS_1)
: 1;
describe("\n%x, widths, precisions and -");
PRINTF(("%-x", 0));
PRINTF(("%-x", 1));
PRINTF(("%-x", 10));
PRINTF(("%-x", -10));
PRINTF(("%-x", 5000));
PRINTF(("%-x", -5000));
PRINTF(("%-x", -1));
PRINTF(("%-x", 2147483647));
PRINTF(("%-1x", 0));
PRINTF(("%-1x", 1));
PRINTF(("%-1x", 10));
PRINTF(("%-1x", -10));
PRINTF(("%-1x", 5000));
PRINTF(("%-1x", -5000));
PRINTF(("%-1x", -1));
PRINTF(("%-1x", 2147483647));
PRINTF(("%-10x", 0));
PRINTF(("%-10x", 1));
PRINTF(("%-10x", 10));
PRINTF(("%-10x", -10));
PRINTF(("%-10x", 5000));
PRINTF(("%-10x", -5000));
PRINTF(("%-10x", -1));
PRINTF(("%-10x", 2147483647));
PRINTF(("%-.x", 0));
PRINTF(("%-.1x", 1));
PRINTF(("%-.2x", 10));
PRINTF(("%-.3x", -10));
PRINTF(("%-.4x", 5000));
PRINTF(("%-.5x", -5000));
PRINTF(("%-.6x", -1));
PRINTF(("%-.7x", 2147483647));
PRINTF(("%-1.8x", 0));
PRINTF(("%-1.9x", 1));
PRINTF(("%-1.10x", 10));
PRINTF(("%-1.0x", -10));
PRINTF(("%-1.6x", 5000));
PRINTF(("%-1.4x", -5000));
PRINTF(("%-1.10x", -1));
PRINTF(("%-1.12x", 2147483647));
PRINTF(("%-10.x", 0));
PRINTF(("%-10.10x", 1));
PRINTF(("%-10.5x", 10));
PRINTF(("%-10.2x", -10));
PRINTF(("%-10.5x", 5000));
PRINTF(("%-10.5x", -5000));
PRINTF(("%-10.15x", -1));
PRINTF(("%-10.5x", 2147483647));
PRINTF(("%-15.x", 0));
PRINTF(("%-15.10x", 1));
PRINTF(("%-15.5x", 10));
PRINTF(("%-15.2x", -10));
PRINTF(("%-15.5x", 5000));
PRINTF(("%-15.5x", -5000));
PRINTF(("%-15.15x", -1));
PRINTF(("%-15.5x", 2147483647));
PRINTF(("%-4.5x%x%4x%-10x-x5%-.3x", 3, 4, 5, 6, 7));
PRINTF(("%-4.5x%x%4x%-10x-x5%-.3x", 300000, 400000, 500000, 600000, 700000));
PRINTF(("%-4.5x%x%4x%-10x-x5%-.3x", -300000, -400000, -500000, -600000, -700000));
PRINTF(("%-4.5x%x%4x%-10x-x5%-.3x", 2147483647, 2141483647, 2141483647, 2141483647, 2141483647));
PRINTF(("%-4.5x%x%4x%-10x-x5%-.3x", -1, -1, -1, -1, -1));
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_BIG_X && test_cat & CAT_BONUS_1)
: 1;
describe("\n%X, widths, precisions and -");
PRINTF(("%-X", 0));
PRINTF(("%-X", 1));
PRINTF(("%-X", 10));
PRINTF(("%-X", -10));
PRINTF(("%-X", 5000));
PRINTF(("%-X", -5000));
PRINTF(("%-X", -1));
PRINTF(("%-X", 2147483647));
PRINTF(("%-1X", 0));
PRINTF(("%-1X", 1));
PRINTF(("%-1X", 10));
PRINTF(("%-1X", -10));
PRINTF(("%-1X", 5000));
PRINTF(("%-1X", -5000));
PRINTF(("%-1X", -1));
PRINTF(("%-1X", 2147483647));
PRINTF(("%-10X", 0));
PRINTF(("%-10X", 1));
PRINTF(("%-10X", 10));
PRINTF(("%-10X", -10));
PRINTF(("%-10X", 5000));
PRINTF(("%-10X", -5000));
PRINTF(("%-10X", -1));
PRINTF(("%-10X", 2147483647));
PRINTF(("%-.X", 0));
PRINTF(("%-.1X", 1));
PRINTF(("%-.2X", 10));
PRINTF(("%-.3X", -10));
PRINTF(("%-.4X", 5000));
PRINTF(("%-.5X", -5000));
PRINTF(("%-.6X", -1));
PRINTF(("%-.7X", 2147483647));
PRINTF(("%-1.8X", 0));
PRINTF(("%-1.9X", 1));
PRINTF(("%-1.10X", 10));
PRINTF(("%-1.0X", -10));
PRINTF(("%-1.6X", 5000));
PRINTF(("%-1.4X", -5000));
PRINTF(("%-1.10X", -1));
PRINTF(("%-1.12X", 2147483647));
PRINTF(("%-10.X", 0));
PRINTF(("%-10.10X", 1));
PRINTF(("%-10.5X", 10));
PRINTF(("%-10.2X", -10));
PRINTF(("%-10.5X", 5000));
PRINTF(("%-10.5X", -5000));
PRINTF(("%-10.15X", -1));
PRINTF(("%-10.5X", 2147483647));
PRINTF(("%-15.X", 0));
PRINTF(("%-15.10X", 1));
PRINTF(("%-15.5X", 10));
PRINTF(("%-15.2X", -10));
PRINTF(("%-15.5X", 5000));
PRINTF(("%-15.5X", -5000));
PRINTF(("%-15.15X", -1));
PRINTF(("%-15.5X", 2147483647));
PRINTF(("%-4.5X%X%4X%-10X-X5%-.3X", 3, 4, 5, 6, 7));
PRINTF(("%-4.5X%X%4X%-10X-X5%-.3X", 300000, 400000, 500000, 600000, 700000));
PRINTF(("%-4.5X%X%4X%-10X-X5%-.3X", -300000, -400000, -500000, -600000, -700000));
PRINTF(("%-4.5X%X%4X%-10X-X5%-.3X", 2147483647, 2141483647, 2141483647, 2141483647, 2141483647));
PRINTF(("%-4.5X%X%4X%-10X-X5%-.3X", -1, -1, -1, -1, -1));
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_D && test_cat & CAT_BONUS_1)
: 1;
describe("\n%d, widths, precisions and 0");
PRINTF(("%01d", 0));
PRINTF(("%01d", -4));
PRINTF(("%010d", 42));
PRINTF(("%042d", 42000));
PRINTF(("%020d", -42000));
PRINTF(("wait for it... %050d", 42));
PRINTF(("%020d is how many tests are going to be made", 8000));
PRINTF(("%05d", 2147483647));
PRINTF(("%030d", 2147483647));
PRINTF(("%010d", 2147483647));
PRINTF(("%05d", (int)-2147483648));
PRINTF(("%030d", (int)-2147483648));
PRINTF(("%010d", (int)-2147483648));
PRINTF(("%011d", (int)-2147483648));
PRINTF(("%012d", (int)-2147483648));
PRINTF(("%012d, %20d, %2d, %42d", (int)-2147483648, 3, 30, -1));
PRINTF(("%012d, %d, %2d, %42d", (int)-2147483648, 3, 30, -1));
PRINTF(("%014d%020d%02d%0d", (int)-2147483648, 3, 30, -1));
PRINTF(("%014dc%020ds%02dx%0du", (int)-2147483648, 3, 30, -1));
PRINTF(("%01.d", 0));
PRINTF(("%01.0d", 0));
PRINTF(("%02.0d", 0));
PRINTF(("%03.0d", 0));
PRINTF(("%01.1d", 0));
PRINTF(("%01.2d", 0));
PRINTF(("%01.3d", 0));
PRINTF(("%01.0d", -4));
PRINTF(("%01.1d", -4));
PRINTF(("%01.2d", -4));
PRINTF(("%01.3d", -4));
PRINTF(("%01.0d", 4));
PRINTF(("%01.1d", 4));
PRINTF(("%01.2d", 4));
PRINTF(("%01.3d", 4));
PRINTF(("%010.20d", 42));
PRINTF(("%042.2d", 42000));
PRINTF(("%042.20d", 42000));
PRINTF(("%042.42d", 42000));
PRINTF(("%042.52d", 42000));
PRINTF(("%020.10d", -42000));
PRINTF(("%020.20d", -42000));
PRINTF(("%020.30d", -42000));
PRINTF(("wait for it... %050.50d", 42));
PRINTF(("%020.19d is how many tests are going to be made", 8000));
PRINTF(("%020.20d is how many tests are going to be made", 8000));
PRINTF(("%020.21d is how many tests are going to be made", 8000));
PRINTF(("%05d", 2147483647));
PRINTF(("%030d", 2147483647));
PRINTF(("%09d", 2147483647));
PRINTF(("%010d", 2147483647));
PRINTF(("%011d", 2147483647));
PRINTF(("%05d", (int)-2147483648));
PRINTF(("%030d", (int)-2147483648));
PRINTF(("%010d", (int)-2147483648));
PRINTF(("%011d", (int)-2147483648));
PRINTF(("%012d", (int)-2147483648));
PRINTF(("%012d, %20d, %2d, %000042d", (int)-2147483648, 3, 30, -1));
PRINTF(("%012d, %d, %002d, %42d", (int)-2147483648, 3, 30, -1));
PRINTF(("%0014.2d%020d%0002.d%000.5d", (int)-2147483648, 3, 30, -1));
PRINTF(("%014dc%020ds%02dx%0du", (int)-2147483648, 3, 30, -1));
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_I && test_cat & CAT_BONUS_1)
: 1;
describe("\n%i, widths, precisions and 0");
PRINTF(("%01i", 0));
PRINTF(("%01i", -4));
PRINTF(("%010i", 42));
PRINTF(("%042i", 42000));
PRINTF(("%020i", -42000));
PRINTF(("wait for it... %050i", 42));
PRINTF(("%020i is how many tests are going to be maie", 8000));
PRINTF(("%05i", 2147483647));
PRINTF(("%030i", 2147483647));
PRINTF(("%010i", 2147483647));
PRINTF(("%05i", (int)-2147483648));
PRINTF(("%030i", (int)-2147483648));
PRINTF(("%010i", (int)-2147483648));
PRINTF(("%011i", (int)-2147483648));
PRINTF(("%012i", (int)-2147483648));
PRINTF(("%012i, %20i, %2i, %42i", (int)-2147483648, 3, 30, -1));
PRINTF(("%012i, %i, %2i, %42i", (int)-2147483648, 3, 30, -1));
PRINTF(("%014i%020i%02i%0i", (int)-2147483648, 3, 30, -1));
PRINTF(("%014ic%020is%02ix%0iu", (int)-2147483648, 3, 30, -1));
PRINTF(("%01.i", 0));
PRINTF(("%01.0i", 0));
PRINTF(("%02.0i", 0));
PRINTF(("%03.0i", 0));
PRINTF(("%01.1i", 0));
PRINTF(("%01.2i", 0));
PRINTF(("%01.3i", 0));
PRINTF(("%01.0i", -4));
PRINTF(("%01.1i", -4));
PRINTF(("%01.2i", -4));
PRINTF(("%01.3i", -4));
PRINTF(("%01.0i", 4));
PRINTF(("%01.1i", 4));
PRINTF(("%01.2i", 4));
PRINTF(("%01.3i", 4));
PRINTF(("%010.20i", 42));
PRINTF(("%042.2i", 42000));
PRINTF(("%042.20i", 42000));
PRINTF(("%042.42i", 42000));
PRINTF(("%042.52i", 42000));
PRINTF(("%020.10i", -42000));
PRINTF(("%020.20i", -42000));
PRINTF(("%020.30i", -42000));
PRINTF(("wait for it... %050.50i", 42));
PRINTF(("%020.19i is how many tests are going to be made", 8000));
PRINTF(("%020.20i is how many tests are going to be made", 8000));
PRINTF(("%020.21i is how many tests are going to be made", 8000));
PRINTF(("%05i", 2147483647));
PRINTF(("%030i", 2147483647));
PRINTF(("%09i", 2147483647));
PRINTF(("%010i", 2147483647));
PRINTF(("%011i", 2147483647));
PRINTF(("%05i", (int)-2147483648));
PRINTF(("%030i", (int)-2147483648));
PRINTF(("%010i", (int)-2147483648));
PRINTF(("%011i", (int)-2147483648));
PRINTF(("%012i", (int)-2147483648));
PRINTF(("%012i, %20i, %2i, %000042i", (int)-2147483648, 3, 30, -1));
PRINTF(("%012i, %i, %002i, %42i", (int)-2147483648, 3, 30, -1));
PRINTF(("%0014.2i%020i%0002.i%000.5i", (int)-2147483648, 3, 30, -1));
PRINTF(("%014ic%020is%02ix%0iu", (int)-2147483648, 3, 30, -1));
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_U && test_cat & CAT_BONUS_1)
: 1;
describe("\n%u, widths, precisions and 0");
PRINTF(("%01u", 0));
PRINTF(("%01u", -4));
PRINTF(("%010u", 42));
PRINTF(("%042u", 42000));
PRINTF(("%020u", -42000));
PRINTF(("wait for it... %050u", 42));
PRINTF(("%020u is how many tests are going to be maie", 8000));
PRINTF(("%05u", 2147483647));
PRINTF(("%030u", 2147483647));
PRINTF(("%010u", 2147483647));
PRINTF(("%05u", -1));
PRINTF(("%030u", -1));
PRINTF(("%010u", -1));
PRINTF(("%011u", -1));
PRINTF(("%012u", -1));
PRINTF(("%012u, %20u, %2u, %42u", -1, 3, 30, -1));
PRINTF(("%012u, %u, %2u, %42u", -1, 3, 30, -1));
PRINTF(("%014u%020u%02u%0u", -1, 3, 30, -1));
PRINTF(("%014uc%020us%02ux%0ui", -1, 3, 30, -1));
PRINTF(("%01.u", 0));
PRINTF(("%01.0u", 0));
PRINTF(("%02.0u", 0));
PRINTF(("%03.0u", 0));
PRINTF(("%01.1u", 0));
PRINTF(("%01.2u", 0));
PRINTF(("%01.3u", 0));
PRINTF(("%01.0u", 4));
PRINTF(("%01.1u", 4));
PRINTF(("%01.2u", 4));
PRINTF(("%01.3u", 4));
PRINTF(("%010.20u", 42));
PRINTF(("%042.2u", 42000));
PRINTF(("%042.20u", 42000));
PRINTF(("%042.42u", 42000));
PRINTF(("%042.52u", 42000));
PRINTF(("wait for it... %050.50u", 42));
PRINTF(("%020.19u is how many tests are going to be made", 8000));
PRINTF(("%020.20u is how many tests are going to be made", 8000));
PRINTF(("%020.21u is how many tests are going to be made", 8000));
PRINTF(("%05u", 2147483647));
PRINTF(("%030u", 2147483647));
PRINTF(("%09u", 2147483647));
PRINTF(("%010u", 2147483647));
PRINTF(("%011u", 2147483647));
PRINTF(("%05u", -1));
PRINTF(("%030u", -1));
PRINTF(("%010u", -1));
PRINTF(("%011u", -1));
PRINTF(("%012u", -1));
PRINTF(("%012u, %20u, %2u, %000042u", -1, 3, 30, -1));
PRINTF(("%012u, %u, %002u, %42u", -1, 3, 30, -1));
PRINTF(("%0014.2u%020u%0002.u%000.5u", -1, 3, 30, -1));
PRINTF(("%014uc%020us%02ux%0ui", -1, 3, 30, -1));
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_X && test_cat & CAT_BONUS_1)
: 1;
describe("\n%x, widths, precisions and 0");
PRINTF(("%01x", 0));
PRINTF(("%01x", -4));
PRINTF(("%010x", 42));
PRINTF(("%042x", 42000));
PRINTF(("%020x", -42000));
PRINTF(("wait for it... %050x", 42));
PRINTF(("%020x is how many tests are going to be made", 8000));
PRINTF(("%05x", 2147483647));
PRINTF(("%030x", 2147483647));
PRINTF(("%010x", 2147483647));
PRINTF(("%05x", -1));
PRINTF(("%030x", -1));
PRINTF(("%010x", -1));
PRINTF(("%011x", -1));
PRINTF(("%012x", -1));
PRINTF(("%012x, %20x, %2x, %42x", -1, 3, 30, -1));
PRINTF(("%012x, %x, %2x, %42x", -1, 3, 30, -1));
PRINTF(("%014x%020x%02x%0x", -1, 3, 30, -1));
PRINTF(("%014xc%020xs%02xX%0xi", -1, 3, 30, -1));
PRINTF(("%01.x", 0));
PRINTF(("%01.0x", 0));
PRINTF(("%02.0x", 0));
PRINTF(("%03.0x", 0));
PRINTF(("%01.1x", 0));
PRINTF(("%01.2x", 0));
PRINTF(("%01.3x", 0));
PRINTF(("%01.0x", 4));
PRINTF(("%01.1x", 4));
PRINTF(("%01.2x", 4));
PRINTF(("%01.3x", 4));
PRINTF(("%010.20x", 42));
PRINTF(("%042.2x", 42000));
PRINTF(("%042.20x", 42000));
PRINTF(("%042.42x", 42000));
PRINTF(("%042.52x", 42000));
PRINTF(("wait for it... %050.50x", 42));
PRINTF(("%020.19x is how many tests are going to be made", 8000));
PRINTF(("%020.20x is how many tests are going to be made", 8000));
PRINTF(("%020.21x is how many tests are going to be made", 8000));
PRINTF(("%05x", 2147483647));
PRINTF(("%030x", 2147483647));
PRINTF(("%09x", 2147483647));
PRINTF(("%010x", 2147483647));
PRINTF(("%011x", 2147483647));
PRINTF(("%05x", -1));
PRINTF(("%030x", -1));
PRINTF(("%010x", -1));
PRINTF(("%011x", -1));
PRINTF(("%012x", -1));
PRINTF(("%012x, %20x, %2x, %000042x", -1, 3, 30, -1));
PRINTF(("%012x, %x, %002x, %42x", -1, 3, 30, -1));
PRINTF(("%0014.2x%020x%0002.x%000.5x", -1, 3, 30, -1));
PRINTF(("%014xc%020xs%02xx%0xi", -1, 3, 30, -1));
right_cat = (g_all_bonus & CAT_BONUS_1) ? 1
: test_cat ? (test_cat & CAT_BIG_X && test_cat & CAT_BONUS_1)
: 1;
describe("\n%X, widths, precisions and 0");
PRINTF(("%01X", 0));
PRINTF(("%01X", -4));
PRINTF(("%010X", 42));
PRINTF(("%042X", 42000));
PRINTF(("%020X", -42000));
PRINTF(("wait for it... %050X", 42));
PRINTF(("%020X is how many tests are going to be made", 8000));
PRINTF(("%05X", 2147483647));
PRINTF(("%030X", 2147483647));
PRINTF(("%010X", 2147483647));
PRINTF(("%05X", -1));
PRINTF(("%030X", -1));
PRINTF(("%010X", -1));
PRINTF(("%011X", -1));
PRINTF(("%012X", -1));
PRINTF(("%012X, %20X, %2X, %42X", -1, 3, 30, -1));
PRINTF(("%012X, %X, %2X, %42X", -1, 3, 30, -1));
PRINTF(("%014X%020X%02X%0X", -1, 3, 30, -1));
PRINTF(("%014Xc%020Xs%02XX%0Xi", -1, 3, 30, -1));
PRINTF(("%01.X", 0));
PRINTF(("%01.0X", 0));
PRINTF(("%02.0X", 0));
PRINTF(("%03.0X", 0));
PRINTF(("%01.1X", 0));
PRINTF(("%01.2X", 0));
PRINTF(("%01.3X", 0));
PRINTF(("%01.0X", 4));
PRINTF(("%01.1X", 4));
PRINTF(("%01.3X", 4));
PRINTF(("%010.20X", 42));
PRINTF(("%042.2X", 42000));
PRINTF(("%042.20X", 42000));
PRINTF(("%042.42X", 42000));
PRINTF(("%042.52X", 42000));
PRINTF(("wait for it... %050.50X", 42));
PRINTF(("%020.19X is how many tests are going to be made", 8000));
PRINTF(("%020.20X is how many tests are going to be made", 8000));
PRINTF(("%020.21X is how many tests are going to be made", 8000));
PRINTF(("%05X", 2147483647));
PRINTF(("%030X", 2147483647));
PRINTF(("%09X", 2147483647));
PRINTF(("%010X", 2147483647));
PRINTF(("%011X", 2147483647));
PRINTF(("%05X", -1));
PRINTF(("%030.20X", -1));
PRINTF(("%010.11X", -1));
PRINTF(("%011.11X", -1));
PRINTF(("%012.11X", -1));
PRINTF(("%012X, %20X, %2X, %000042.20X", -1, 3, 30, -1));
PRINTF(("%012X, %X, %002X, %42.5X", -1, 3, 30, -1));
PRINTF(("%0014.2X%020X%0002.X%000.5X", -1, 3, 30, -1));
PRINTF(("%014Xc%020Xs%02.5XX%0.Xi", -1, 3, 30, -1));
right_cat = (g_all_bonus & CAT_BONUS_2) ? 1
: test_cat ? (test_cat & CAT_X && test_cat & CAT_BONUS_2)
: 1;
describe("\n%x and #");
PRINTF(("%#x", 0));
PRINTF(("%#x", -4));
PRINTF(("%#x", 42));
PRINTF(("%#x", 42000));
PRINTF(("%#x", -42000));
PRINTF(("wait for it... %#x", 42));
PRINTF(("%#x is how many tests are going to be made", 8000));
PRINTF(("%#xd", 2147483647));
PRINTF(("%#xp", 2147483647));
PRINTF(("%#xX", 2147483647));
PRINTF(("%#xp", -1));
PRINTF(("%#xd", -1));
PRINTF(("%#xX", -1));
PRINTF(("%#x", -1));
PRINTF(("%#x, %x, %x, %x", -1, 3, 30, -1));
PRINTF(("%#x%#x%#x%#x", -1, 3, 30, -1));
PRINTF(("%#xc%#xs%#xX%#xi", -1, 3, 30, -1));
PRINTF(("--.%#xp", 0));
PRINTF(("--.%#xs", 0));
PRINTF(("%#xc", 4));
PRINTF(("c%#x-i", 42000));
PRINTF(("wait for it... %#xp", 42));
right_cat = (g_all_bonus & CAT_BONUS_2) ? 1
: test_cat ? (test_cat & CAT_BIG_X && test_cat & CAT_BONUS_2)
: 1;
describe("\n%X and #");
PRINTF(("%#X", 0));
PRINTF(("%#X", -4));
PRINTF(("%#X", 42));
PRINTF(("%#X", 42000));
PRINTF(("%#X", -42000));
PRINTF(("wait for it... %#X", 42));
PRINTF(("%#X is how many tests are going to be made", 8000));
PRINTF(("%#Xd", 2147483647));
PRINTF(("%#Xp", 2147483647));
PRINTF(("%#XX", 2147483647));
PRINTF(("%#Xp", -1));
PRINTF(("%#Xd", -1));
PRINTF(("%#XX", -1));
PRINTF(("%#X", -1));
PRINTF(("%#X, %X, %X, %X", -1, 3, 30, -1));
PRINTF(("%#X%#X%#X%#X", -1, 3, 30, -1));
PRINTF(("%#Xc%#Xs%#Xx%#Xi", -1, 3, 30, -1));
PRINTF(("--.%#Xp", 0));
PRINTF(("--.%#Xs", 0));
PRINTF(("%#Xc", 4));
PRINTF(("c%#X-i", 42000));
PRINTF(("wait for it... %#Xp", 42));
right_cat = (g_all_bonus & CAT_BONUS_2) ? 1
: test_cat ? (test_cat & CAT_D && test_cat & CAT_BONUS_2)
: 1;
describe("\n%d and ' '");
PRINTF(("% d", 0));
PRINTF(("% d", 1));
PRINTF(("% d", -1));
PRINTF(("% d", 0));
PRINTF(("% d", 1));
PRINTF(("% d", -1));
PRINTF(("% d", 2147483647));
PRINTF(("% d", (int)-2147483648));
PRINTF(("% d", 2147483647));
PRINTF(("% d", (int)-2147483648));
PRINTF(("% d", 2178647));
PRINTF(("% d", (int)-2144348));
PRINTF(("% d", 2147837));
PRINTF(("% d", (int)-2147486));
PRINTF(("% d this is %d getting% di hard :/", (int)-2147486, -2, 42));
right_cat = (g_all_bonus & CAT_BONUS_2) ? 1
: test_cat ? (test_cat & CAT_I && test_cat & CAT_BONUS_2)
: 1;
describe("\n%i and ' '");
PRINTF(("% i", 0));
PRINTF(("% i", 2));
PRINTF(("% i", -2));
PRINTF(("% i", 0));
PRINTF(("% i", 1));
PRINTF(("% i", -1));
PRINTF(("% i", 2147483647));
PRINTF(("% i", (int)-2147483648));
PRINTF(("% i", 2147483647));
PRINTF(("% i", (int)-2147483648));
PRINTF(("% i", 2178647));
PRINTF(("% i", (int)-2144348));
PRINTF(("% i", 2147837));
PRINTF(("% i", (int)-2147486));
PRINTF(("% i this is %i getting% is hari :/", (int)-2147486, -2, 42));
right_cat = (g_all_bonus & CAT_BONUS_2) ? 1
: test_cat ? (test_cat & CAT_D && test_cat & CAT_BONUS_2)
: 1;
describe("\n%d and +");
PRINTF(("%+d", 0));
PRINTF(("%+d", 1));
PRINTF(("%+d", -1));
PRINTF(("%+d", 24));
PRINTF(("%+d", 42));
PRINTF(("%+d", -42));
PRINTF(("%+d", 2147483647));
PRINTF(("%+d", (int)-2147483648));
PRINTF(("%+++d", 2147483647));
PRINTF(("%++d", (int)-2147483648));
PRINTF(("%+d", 2178647));
PRINTF(("%+d", (int)-2144348));
PRINTF(("%+++d", 2147837));
PRINTF(("%++d", (int)-2147486));
PRINTF(("%++d this is %d getting%+di hard :/", (int)-2147486, -2, 42));
right_cat = (g_all_bonus & CAT_BONUS_2) ? 1
: test_cat ? (test_cat & CAT_I && test_cat & CAT_BONUS_2)
: 1;
describe("\n%d and +");
PRINTF(("%+i", 0));
PRINTF(("%+i", 1));
PRINTF(("%+i", -1));
PRINTF(("%+i", 24));
PRINTF(("%+i", 42));
PRINTF(("%+i", -42));
PRINTF(("%+i", 2147483647));
PRINTF(("%+i", (int)-2147483648));
PRINTF(("%+++i", 2147483647));
PRINTF(("%++i", (int)-2147483648));
PRINTF(("%+i", 2178647));
PRINTF(("%+i", (int)-2144348));
PRINTF(("%+++i", 2147837));
PRINTF(("%++i", (int)-2147486));
PRINTF(("%++i this is %i getting%+ix hard :/", (int)-2147486, -2, 42));
return (0);
}
| 34.306875 | 128 | 0.550437 | [
"3d"
] |
12af09fee4a1d0dd55e2b6f3771eb844299761d6 | 8,595 | h | C | tensorflow/compiler/xla/service/dynamic_dimension_inference.h | MathMachado/tensorflow | 56afda20b15f234c23e8393f7e337e7dd2659c2d | [
"Apache-2.0"
] | 848 | 2019-12-03T00:16:17.000Z | 2022-03-31T22:53:17.000Z | tensorflow/compiler/xla/service/dynamic_dimension_inference.h | MathMachado/tensorflow | 56afda20b15f234c23e8393f7e337e7dd2659c2d | [
"Apache-2.0"
] | 656 | 2019-12-03T00:48:46.000Z | 2022-03-31T18:41:54.000Z | tensorflow/compiler/xla/service/dynamic_dimension_inference.h | MathMachado/tensorflow | 56afda20b15f234c23e8393f7e337e7dd2659c2d | [
"Apache-2.0"
] | 506 | 2019-12-03T00:46:26.000Z | 2022-03-30T10:34:56.000Z | /* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_DYNAMIC_DIMENSION_INFERENCE_H_
#define TENSORFLOW_COMPILER_XLA_SERVICE_DYNAMIC_DIMENSION_INFERENCE_H_
#include <memory>
#include <string>
#include <vector>
#include "absl/container/flat_hash_map.h"
#include "absl/types/span.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_module.h"
#include "tensorflow/compiler/xla/status.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/core/platform/macros.h"
namespace xla {
// DynamicDimensionInference analyzes each HLO instruction in a graph and
// inferences which dimensions are dynamic and which scalar instructions
// represent the runtime real size of those dynamic dimensions.
class DynamicDimensionInference {
public:
static StatusOr<DynamicDimensionInference> Run(HloModule* module);
string ToString() const;
// If the dimension `dim` of instruction `inst` at `index` has a dynamic size,
// returns a scalar HloInstruction that represents the runtime size of that
// dimension. Otherwise returns nullptr.
HloInstruction* GetDynamicSize(HloInstruction* inst, const ShapeIndex& index,
int64 dim) const;
friend class DynamicDimensionInferenceVisitor;
private:
explicit DynamicDimensionInference(HloModule* module);
// DynamicDimension is used as a key in the dynamic key-value mapping. It
// unambiguously represents a dynamic dimension of a instruction at a given
// index.
struct DynamicDimension {
// HloInstruction that holds the dimension.
HloInstruction* inst;
// Subshape of the instruction that holds the dimension.
ShapeIndex index;
// The dimension number of the dynamic dimension at given index of a given
// instruction.
int64 dim;
// Artifacts needed to make this struct able to be used as a `key` in absl
// maps. "friend" keywords are added so these functions can be found through
// ADL.
template <typename H>
friend H AbslHashValue(H h, const DynamicDimension& m) {
return H::combine(std::move(h), m.inst, m.index, m.dim);
}
friend bool operator==(const DynamicDimension& lhs,
const DynamicDimension& rhs) {
return lhs.inst == rhs.inst && lhs.index == rhs.index &&
lhs.dim == rhs.dim;
}
};
// DimensionConstraint is attached to each dynamic dimension and describe the
// constraint of each dimension. This is used to disambiguate the index of
// dynamic dimension for reshapes that "splits" a dimension into two.
//
// As an example, consider the following reshapes:
// [<=3, 3] <- Assume first dimension is dynamic.
// |
// Reshape.1
// |
// [<=9] <- Dimension 9 is dynamic
// |
// Reshape.2
// |
// [3, 3] <- Ambiguous dimension after splitting 9 into [3, 3]
//
// There is no way to know which dimension is dynamic by looking at the second
// reshape locally.
//
// However, if we look at the dynamic dimension 9, since it comes from
// collapsing a major dynamic dimension of 3 (the dynamic size can be 0, 1, 2,
// 3, denoted as i in the diagram below) and a minor static dimension of 3, we
// know it has certain constraints that the reshape can only be one of the 4
// forms:
//
// o: Padded Data
// x: Effective Data
//
// [<=3, 3] to [9]
//
// +---+ +---+ +---+ +---+
// |ooo| |ooo| |ooo| |xxx|
// |ooo| |ooo| |xxx| |xxx|
// |ooo| |xxx| |xxx| |xxx|
// +---+ +---+ +---+ +---+
//
// Reshape Reshape Reshape Reshape
//
// +-----------+ +-----------+ +-----------+ +-----------+
// |ooo|ooo|ooo| or |xxx|ooo|ooo| or |xxx|xxx|ooo| or |xxx|xxx|xxx| stride=1
// +-----------+ +-----------+ +-----------+ +-----------+
// i = 0 i = 1 i = 2 i = 3
//
// On the other hand, if the minor dimension 3 is dynamic and major dimension
// is static, we will have the following form:
//
// [3, <=3] to [9]
//
// +---+ +---+ +---+ +---+
// |ooo| |xoo| |xxo| |xxx|
// |ooo| |xoo| |xxo| |xxx|
// |ooo| |xoo| |xxo| |xxx|
// +---+ +---+ +---+ +---+
//
// Reshape Reshape Reshape Reshape
//
// +-----------+ +-----------+ +-----------+ +-----------+
// |ooo|ooo|ooo| or |xoo|xoo|xoo| or |xxo|xxo|xxo| or |xxo|xxo|xxo| stride=3
// +-----------+ +-----------+ +-----------+ +-----------+
// i = 0 i = 1 i = 2 i = 3
//
// By encoding constraint as a stride of elements we can recover this
// information later when we reshape from [9] to [3, 3]. We know which form
// ([3, i] or [i,3]) we should reshape the [9] into.
//
//
struct DimensionConstraint {
// Stride represents the distance of a newly placed element and the previous
// placed element on this dynamic dimension.
int64 stride;
// multiple_of represents the constraints that
//
// `dynamic_size` % `multiple_of` == 0
int64 multiple_of;
};
using ConstraintMapping =
absl::flat_hash_map<DynamicDimension, DimensionConstraint>;
ConstraintMapping constraint_mapping_;
// Update the dynamic mapping so that we know dimension `dim` of instruction
// `inst` at `index` has a dynamic size, and its runtime size is represented
// by a scalar instruction `size`.
void SetDynamicSize(HloInstruction* inst, const ShapeIndex& index, int64 dim,
HloInstruction* size, DimensionConstraint constraint) {
Shape subshape = ShapeUtil::GetSubshape(inst->shape(), index);
CHECK(!subshape.IsTuple())
<< "Can't set a tuple shape to dynamic dimension";
CHECK(dim < subshape.rank() && dim >= 0)
<< "Asked to set invalid dynamic dimension. Shape: "
<< subshape.ToString() << ", Dimension: " << dim;
DynamicDimension dynamic_dimension{inst, index, dim};
dynamic_mapping_.try_emplace(dynamic_dimension, size);
if (constraint_mapping_.count(dynamic_dimension) != 0) {
CHECK_EQ(constraint_mapping_[dynamic_dimension].stride,
constraint.stride);
}
constraint_mapping_.try_emplace(dynamic_dimension, constraint);
auto iter = per_hlo_dynamic_dimensions_.try_emplace(inst);
iter.first->second.emplace(dynamic_dimension);
}
// Copies the internal mapping from instruction `from` to instruction `to`.
// This is useful when an instruction is replaced by the other during the
// inferencing process.
void CopyMapping(HloInstruction* from, HloInstruction* to);
// AnalyzeDynamicDimensions starts the analysis of the dynamic dimensions in
// module_.
Status AnalyzeDynamicDimensions();
// HloModule being analyzed.
HloModule* module_;
// dynamic_mapping_ holds the result of the analysis. It maps a dynamic
// dimension to a scalar HloInstruction that represents the real dynamic size
// of the dynamic dimension.
using DynamicMapping = absl::flat_hash_map<DynamicDimension, HloInstruction*>;
DynamicMapping dynamic_mapping_;
// A convenient mapping from an hlo to the set of dynamic dimensions that it
// holds.
using PerHloDynamicDimensions =
absl::flat_hash_map<HloInstruction*,
absl::flat_hash_set<DynamicDimension>>;
PerHloDynamicDimensions per_hlo_dynamic_dimensions_;
};
} // namespace xla
#endif // TENSORFLOW_COMPILER_XLA_SERVICE_DYNAMIC_DIMENSION_INFERENCE_H_
| 40.352113 | 80 | 0.619779 | [
"shape",
"vector"
] |
12af285f195888981423d2f66ed3b255310bcd79 | 16,559 | h | C | include/ff_stdio.h | lurk101/Lab-Project-FreeRTOS-FAT | d21f242c1199e5db09dc8d50e191c06c1c16ae5a | [
"MIT"
] | 24 | 2019-12-03T21:50:10.000Z | 2022-03-21T05:10:21.000Z | include/ff_stdio.h | lurk101/Lab-Project-FreeRTOS-FAT | d21f242c1199e5db09dc8d50e191c06c1c16ae5a | [
"MIT"
] | 12 | 2021-02-26T09:22:41.000Z | 2022-03-05T07:17:49.000Z | include/ff_stdio.h | lurk101/Lab-Project-FreeRTOS-FAT | d21f242c1199e5db09dc8d50e191c06c1c16ae5a | [
"MIT"
] | 29 | 2019-12-12T00:42:01.000Z | 2021-12-17T21:24:37.000Z | /*
* FreeRTOS+FAT V2.3.3
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* https://www.FreeRTOS.org
* https://github.com/FreeRTOS
*
*/
/*
* ff_stdio.h
*
* An front-end which make +FAT look like the well-known stdio-functions
*/
#ifndef FF_STDIO_H
#define FF_STDIO_H
#if defined( __WIN32__ )
#include <dir.h>
#endif
/* Standard includes. */
#include <stdio.h>
#include <stdarg.h>
/* FreeRTOS+FAT includes. */
#include "ff_headers.h"
#include "ff_sys.h"
#if ( ffconfigDEV_SUPPORT != 0 )
#include "ff_devices.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* Error return from some functions. */
#define FF_EOF ( -1 )
/* Bits used in the FF_Stat_t structure. */
#define FF_IFDIR 0040000u /* directory */
#define FF_IFCHR 0020000u /* character special */
#define FF_IFBLK 0060000u /* block special */
#define FF_IFREG 0100000u /* regular */
/* Bits used in the FF_FindData_t structure. */
#define FF_FA_NORMAL 0x00
#define FF_FA_RDONLY 0x01
#define FF_FA_HIDDEN 0x02
#define FF_FA_SYSTEM 0x04
#define FF_FA_LABEL 0x08
#define FF_FA_DIREC 0x10
#define FF_FA_ARCH 0x20
/* FreeRTOS+FAT uses three thread local buffers. The first stores errno, the
* second a pointer to the CWD structure (if one is used), and the third the more
* descriptive error code. */
#define stdioERRNO_THREAD_LOCAL_OFFSET ( ffconfigCWD_THREAD_LOCAL_INDEX + 0 )
#define stdioCWD_THREAD_LOCAL_OFFSET ( ffconfigCWD_THREAD_LOCAL_INDEX + 1 )
#define stdioFF_ERROR_THREAD_LOCAL_OFFSET ( ffconfigCWD_THREAD_LOCAL_INDEX + 2 )
/* Structure used with ff_stat(). */
typedef struct FF_STAT
{
uint32_t st_ino; /* First data cluster number. */
uint32_t st_size; /* Size of the object in number of bytes. */
uint16_t st_dev; /* The device on which the file can be found (see ff_sys.c) */
uint16_t st_mode; /* The mode (attribute bits) of this file or directory. */
#if ( ffconfigTIME_SUPPORT == 1 )
uint32_t st_atime;
uint32_t st_mtime;
uint32_t st_ctime;
#endif /* ffconfigTIME_SUPPORT */
} FF_Stat_t;
/* Structure used with ff_findfirst(), ff_findnext(), etc. */
typedef struct
{
/* private */
UBaseType_t
#if ( ffconfigDEV_SUPPORT != 0 )
bIsDeviceDir : 1,
#endif
bEntryPOwner : 1;
struct FF_DIR_HANDLER xDirectoryHandler;
FF_DirEnt_t xDirectoryEntry;
/* Public fields included so FF_DirEnt_t does not need to be public. */
const char * pcFileName;
uint32_t ulFileSize;
uint8_t ucAttributes;
} FF_FindData_t;
/*-----------------------------------------------------------
* Get and set the task's file system errno
* The most up to date API documentation is currently provided on the following URL:
* http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_FAT/Standard_File_System_API.html
*-----------------------------------------------------------*/
/*
* int FF_GetErrno( void );
* void FF_SetErrno( int ff_errno );
*
* _RB_ comments are incorrect and index should use the stdioERRNO_THREAD_LOCAL_OFFSET offset.
*/
/* The errno is stored in a thread local buffer. */
static portINLINE void stdioSET_ERRNO( int iErrno )
{
/* Local storage pointers can only store pointers. This function
* wants to store a signed errno value, which needs a cast. */
/* Cast from an integer to a signed value of a pointer size. */
intptr_t xErrno = ( intptr_t ) iErrno;
/* Cast from a numeric value to a pointer. */
void * pvValue = ( void * ) ( xErrno );
vTaskSetThreadLocalStoragePointer( NULL, ffconfigCWD_THREAD_LOCAL_INDEX, pvValue );
}
static portINLINE int stdioGET_ERRNO( void )
{
void * pvResult;
pvResult = pvTaskGetThreadLocalStoragePointer( ( TaskHandle_t ) NULL, ffconfigCWD_THREAD_LOCAL_INDEX );
/* Cast from a pointer to a number of the same size. */
intptr_t xErrno = ( intptr_t ) pvResult;
/* Cast it to an integer. */
int iValue = ( int ) ( xErrno );
return iValue;
}
#if ( ( configNUM_THREAD_LOCAL_STORAGE_POINTERS - ffconfigCWD_THREAD_LOCAL_INDEX ) < 3 )
#error Please define space for 3 entries
#endif
/*
* Store the FreeRTOS+FAT error code, which provides more detail than errno.
*/
static portINLINE void stdioSET_FF_ERROR( FF_Error_t iFF_ERROR )
{
/* Cast it to an unsigned long. */
uint32_t ulError = ( uint32_t ) iFF_ERROR;
/* Cast it to a number with the size of a pointer. */
uintptr_t uxErrno = ( uintptr_t ) ulError;
/* Cast it to a void pointer. */
void * pvValue = ( void * ) ( uxErrno );
vTaskSetThreadLocalStoragePointer( NULL, stdioFF_ERROR_THREAD_LOCAL_OFFSET, pvValue );
}
/*
* Read back the FreeRTOS+FAT error code, which provides more detail than
* errno.
*/
static portINLINE FF_Error_t stdioGET_FF_ERROR( void )
{
void * pvResult;
pvResult = pvTaskGetThreadLocalStoragePointer( NULL, stdioFF_ERROR_THREAD_LOCAL_OFFSET );
/* Cast it to an integer with the same size as a pointer. */
intptr_t uxErrno = ( intptr_t ) pvResult;
/* Cast it to a int32_t. */
FF_Error_t xError = ( FF_Error_t ) uxErrno;
return xError;
}
/*-----------------------------------------------------------
* Open and close a file
* The most up to date API documentation is currently provided on the following URL:
* http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_FAT/Standard_File_System_API.html
*-----------------------------------------------------------*/
FF_FILE * ff_fopen( const char * pcFile,
const char * pcMode );
int ff_fclose( FF_FILE * pxStream );
/*-----------------------------------------------------------
* Seek and tell
* The most up to date API documentation is currently provided on the following URL:
* http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_FAT/Standard_File_System_API.html
*-----------------------------------------------------------*/
int ff_fseek( FF_FILE * pxStream,
long lOffset,
int iWhence );
void ff_rewind( FF_FILE * pxStream );
long ff_ftell( FF_FILE * pxStream );
int ff_feof( FF_FILE * pxStream );
/*-----------------------------------------------------------
* Read and write
* The most up to date API documentation is currently provided on the following URL:
* http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_FAT/Standard_File_System_API.html
*-----------------------------------------------------------*/
size_t ff_fread( void * pvBuffer,
size_t xSize,
size_t xItems,
FF_FILE * pxStream );
size_t ff_fwrite( const void * pvBuffer,
size_t xSize,
size_t xItems,
FF_FILE * pxStream );
/* Whenever possible, use ellipsis parameter type checking.
* _RB_ Compiler specifics need to be moved to the compiler specific header files. */
#if defined( __GNUC__ )
/* The GNU-C compiler will check if the parameters are correct. */
int ff_fprintf( FF_FILE * pxStream,
const char * pcFormat,
... )
__attribute__( ( format( __printf__, 2, 3 ) ) );
#else
int ff_fprintf( FF_FILE * pxStream,
const char * pcFormat,
... );
#endif
int ff_fgetc( FF_FILE * pxStream );
int ff_fputc( int iChar,
FF_FILE * pxStream );
char * ff_fgets( char * pcBuffer,
size_t xCount,
FF_FILE * pxStream );
/*-----------------------------------------------------------
* Change length of file (truncate)
* File should have been opened in "w" or "a" mode
* The actual length of the file will be made equal to the current writing
* position
* The most up to date API documentation is currently provided on the following URL:
* http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_FAT/Standard_File_System_API.html
*-----------------------------------------------------------*/
int ff_seteof( FF_FILE * pxStream );
/*-----------------------------------------------------------
* Open a file in append/update mode, truncate its length to a given value,
* or write zero's up until the required length, and return a handle to the open
* file. If NULL is returned, ff_errno contains an error code.
* The most up to date API documentation is currently provided on the following URL:
* http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_FAT/Standard_File_System_API.html
*-----------------------------------------------------------*/
FF_FILE * ff_truncate( const char * pcFileName,
long lTruncateSize );
/*-----------------------------------------------------------
* Flush to disk
* The most up to date API documentation is currently provided on the following URL:
* http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_FAT/Standard_File_System_API.html
*-----------------------------------------------------------*/
int ff_fflush( FF_FILE * pxStream );
/*-----------------------------------------------------------
* Create directory, remove and rename files
* The most up to date API documentation is currently provided on the following URL:
* http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_FAT/Standard_File_System_API.html
*-----------------------------------------------------------*/
#if ( ffconfigMKDIR_RECURSIVE == 0 )
int ff_mkdir( const char * pcPath );
#else
/* If the parameter bRecursive is non-zero, the entire path will be checked
* and if necessary, created. */
int ff_mkdir( const char * pcPath,
int bRecursive );
#endif
/*-----------------------------------------------------------
* Create path specified by the pcPath parameter.
* The most up to date API documentation is currently provided on the following URL:
* http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_FAT/Standard_File_System_API.html
*-----------------------------------------------------------*/
int ff_mkpath( const char * pcPath );
/*-----------------------------------------------------------
* Remove the directory specified by the pcDirectory parameter.
* The most up to date API documentation is currently provided on the following URL:
* http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_FAT/Standard_File_System_API.html
*-----------------------------------------------------------*/
int ff_rmdir( const char * pcDirectory );
/*-----------------------------------------------------------
* Delete a directory and, recursively, all of its contents.
* The most up to date API documentation is currently provided on the following URL:
* http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_FAT/Standard_File_System_API.html
*-----------------------------------------------------------*/
#if ( ffconfigUSE_DELTREE != 0 )
/* By default, this function will not be compiled. The function will
* recursively call itself, which is against the FreeRTOS coding standards, so
* IT MUST BE USED WITH CARE.
*
* The cost of each recursion will be roughly:
* Stack : 48 (12 stack words)
* Heap : 112 + ffconfigMAX_FILENAME
* These numbers may change depending on CPU and compiler. */
int ff_deltree( const char * pcPath );
#endif
/*-----------------------------------------------------------
* Remove/delete a file.
* The most up to date API documentation is currently provided on the following URL:
* http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_FAT/Standard_File_System_API.html
*-----------------------------------------------------------*/
int ff_remove( const char * pcPath );
/*-----------------------------------------------------------
* Move a file, also cross-directory but not across a file system.
* The most up to date API documentation is currently provided on the following URL:
* http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_FAT/Standard_File_System_API.html
*-----------------------------------------------------------*/
int ff_rename( const char * pcOldName,
const char * pcNewName,
int bDeleteIfExists );
/*-----------------------------------------------------------
* Get the status of a file.
* The most up to date API documentation is currently provided on the following URL:
* http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_FAT/Standard_File_System_API.html
*-----------------------------------------------------------*/
int ff_stat( const char * pcFileName,
FF_Stat_t * pxStatBuffer );
/* _HT_ Keep this for a while, until the new ff_stat() is wel tested */
int ff_old_stat( const char * pcName,
FF_Stat_t * pxStatBuffer );
/*-----------------------------------------------------------
* Get the length of a file in bytes.
* The most up to date API documentation is currently provided on the following URL:
* http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_FAT/Standard_File_System_API.html
*-----------------------------------------------------------*/
size_t ff_filelength( FF_FILE * pxFile );
/*-----------------------------------------------------------
* Working directory and iterating through directories.
* The most up to date API documentation is currently provided on the following URL:
* http://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_FAT/Standard_File_System_API.html
*-----------------------------------------------------------*/
#if ffconfigHAS_CWD
int ff_chdir( const char * pcDirectoryName );
char * ff_getcwd( char * pcBuffer,
size_t xBufferLength );
#endif
int ff_findfirst( const char * pcDirectory,
FF_FindData_t * pxFindData );
int ff_findnext( FF_FindData_t * pxFindData );
int ff_isdirempty( const char * pcPath );
/* _RB_ What to do regarding documentation for the definitions below here. */
#if ( ffconfig64_NUM_SUPPORT != 0 )
int64_t ff_diskfree( const char * pcPath,
uint32_t * pxSectorCount );
#else
int32_t ff_diskfree( const char * pcPath,
uint32_t * pxSectorCount );
#endif
int ff_finddir( const char * pcPath );
#if ( ffconfigHAS_CWD == 1 )
/* Obtain the CWD used by the current task. */
void ff_free_CWD_space( void );
#endif
typedef enum _EFileAction
{
eFileCreate,
eFileRemove,
eFileChange,
eFileIsDir = 0x80,
} eFileAction_t;
void callFileEvents( const char * apPath,
eFileAction_t aAction );
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* FF_STDIO_H */
| 40.585784 | 111 | 0.57745 | [
"object"
] |
3e1d7aa3e6ba9470b6d4da9e9f93ad7121064d0c | 1,538 | h | C | cpp/src/nnbench/nnbench.h | viscloud/ff | 480eb87c6832b3f0bc72a87771abf801c340cab4 | [
"Apache-2.0"
] | 20 | 2019-06-05T02:32:14.000Z | 2022-01-15T15:35:00.000Z | cpp/src/nnbench/nnbench.h | viscloud/filterforward | 480eb87c6832b3f0bc72a87771abf801c340cab4 | [
"Apache-2.0"
] | null | null | null | cpp/src/nnbench/nnbench.h | viscloud/filterforward | 480eb87c6832b3f0bc72a87771abf801c340cab4 | [
"Apache-2.0"
] | 5 | 2019-06-13T08:56:16.000Z | 2020-08-03T02:48:45.000Z | // Copyright 2016 The FilterForward 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 FILTERFORWARD_UTILS_NNBENCH_H_
#define FILTERFORWARD_UTILS_NNBENCH_H_
#include <memory>
#include <string>
#include <vector>
#include "saf.h"
// A NnBench is a Operator
class NnBench : public Operator {
public:
NnBench(const ModelDesc& model_desc, const Shape& input_shape, int batch_size,
int num_copies);
static std::shared_ptr<NnBench> Create(const FactoryParamsType& params);
virtual std::string GetName() const override;
void SetSource(StreamPtr stream);
using Operator::SetSource;
StreamPtr GetSink();
using Operator::GetSink;
protected:
virtual bool Init() override;
virtual bool OnStop() override;
virtual void Process() override;
private:
size_t batch_size_;
std::string input_layer_;
std::string output_layer_;
std::vector<std::unique_ptr<Model>> models_;
std::vector<std::unique_ptr<Frame>> buf_;
};
#endif // FILTERFORWARD_UTILS_NNBENCH_H_
| 28.481481 | 80 | 0.749025 | [
"shape",
"vector",
"model"
] |
3e211fd5848d636406bc329b19a2ca6e20d7f4e9 | 7,433 | h | C | earth_enterprise/src/common/merge/merge.h | seamusdunlop123/earthenterprise | a2651b1c00dd6230fd5d3d47502d228dbfca0f63 | [
"Apache-2.0"
] | 3 | 2017-12-21T05:40:09.000Z | 2018-05-16T11:18:25.000Z | earth_enterprise/src/common/merge/merge.h | seamusdunlop123/earthenterprise | a2651b1c00dd6230fd5d3d47502d228dbfca0f63 | [
"Apache-2.0"
] | null | null | null | earth_enterprise/src/common/merge/merge.h | seamusdunlop123/earthenterprise | a2651b1c00dd6230fd5d3d47502d228dbfca0f63 | [
"Apache-2.0"
] | 1 | 2020-12-16T09:26:10.000Z | 2020-12-16T09:26:10.000Z | /*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef COMMON_MERGE_MERGE_H__
#define COMMON_MERGE_MERGE_H__
// Merge
//
// Classes for multi-way merge
#include <string>
#include <vector>
#include <queue>
#include <common/base/macros.h>
#include <khSimpleException.h>
#include <khGuard.h>
// MergeSource class - abstract class template, subclassed for
// different types of sources. The "name" parameter is used for
// debugging and error reporting.
//
// The instantiable subclass must define operators for Advance(),
// Current(), and Close(), as well as constructor and destructor. The
// subclass must also provide a ">" (follows) operator.
//
// Current() always presents the current value of the source
// (generates an exception if past end). The first value must be
// available on exit from the constructor. Advance() advances the
// source to the next value, returning true for success and false if
// no more values are available. A value returned by Current() is not
// valid after the next Advance().
template <class ValueType> class MergeSource {
public:
typedef ValueType MergeType;
MergeSource(const std::string &name) : name_(name) {}
virtual ~MergeSource() {}
virtual const ValueType &Current() const = 0;
virtual bool Advance() = 0; // to next position (false = end)
virtual void Close() = 0;
const std::string &name() const { return name_; }
private:
const std::string name_;
DISALLOW_COPY_AND_ASSIGN(MergeSource<ValueType>);
};
// Main multi-way merge class. To use, instantiate a Merge with some
// ValueType, add some sources, and Start. Use Current() to access
// the current ValueType item, and Advance() to process the next merge
// item. Use Close() when done.
//
// Note on multi-threading: because Merge is inherently serial, it
// doesn't make sense to access a Merge from multiple threads. The
// MergeSource objects can, of course, be driven by multiple threads.
// A multi-threaded MergeSource implementation is responsible for its
// own thread coordinatation.
template <class ValueType> class Merge : public MergeSource<ValueType> {
private:
// QueueItem - private internal class to encapsulate priority_queue
// items. The priority_queue and underlying heap algorithms do
// comparisons on the items in the priority queue. Since we want to
// store pointers in the queue, we need to encapsulate the pointers
// so that the comparisons are done on the underlying MergeSource
// objects. Note that copying must be allowed for the STL
// priority_queue to function properly.
class QueueItem {
public:
QueueItem(const khTransferGuard<MergeSource<ValueType> > &item,
uint id) :
item_(item.take()),
id_(id)
{}
inline uint Id(void) const { return id_; }
inline bool operator>(const QueueItem &other) const {
return item_->Current() > other.item_->Current();
}
inline MergeSource<ValueType>& operator*() const { return *item_; }
inline MergeSource<ValueType>* operator->() const { return item_; }
// Delete() is done through an explicit method rather than a
// destructor in order to allow copying of QueueItem.
void Delete() {
delete item_;
item_ = NULL;
}
private:
MergeSource<ValueType> *item_;
uint id_;
};
public:
Merge(const std::string &name)
: MergeSource<ValueType>(name),
started_(false),
next_source_id_(0)
{
}
virtual ~Merge() {
Close();
}
virtual void Close() {
if (!std::uncaught_exception()) {
if (!sources_.empty()) {
notify(NFY_WARN, "Merge::Close: %llu sources not empty in: %s",
static_cast<long long unsigned>(sources_.size()),
MergeSource<ValueType>::name().c_str());
}
}
// Ensure that any MergeSource items left in queue are deleted.
while (!sources_.empty()) {
QueueItem source = sources_.top();
sources_.pop();
source.Delete();
}
}
bool Finished() const { return started_ && sources_.empty(); }
bool Active() const { return started_ && !sources_.empty(); }
// Get name of current source at top of queue (for debug). Returns
// empty string if no sources.
const std::string &CurrentName() {
static const std::string empty;
if (!sources_.empty()) {
return sources_.top()->name();
} else {
return empty;
}
}
// Add a source to the merge. If an add is done after Start(),
// the first item from the new source must be strictly > Current().
void AddSource(const khTransferGuard<MergeSource<ValueType> > &source) {
if (!started_ || (!sources_.empty() && source->Current() > Current())) {
sources_.push(QueueItem(source, next_source_id_++));
} else {
throw khSimpleException("Merge::AddSource: "
"attempted on open merge out of order: ")
<< MergeSource<ValueType>::name();
}
}
// Start the merge
void Start() { // start the merge
if (!started_) {
if (!sources_.empty()) {
started_ = true;
} else {
throw khSimpleException("Merge::Start: no sources for Merge ")
<< MergeSource<ValueType>::name();
}
} else {
throw khSimpleException("Merge::Start: already started: ")
<< MergeSource<ValueType>::name();
}
}
virtual const ValueType &Current() const { // first source on heap
if (Active()) {
return sources_.top()->Current();
} else {
throw khSimpleException("Merge::Current: not started or no open sources: ")
<< MergeSource<ValueType>::name();
}
}
const uint CurrentSourceId() const { // first source on heap
if (Active()) {
return sources_.top().Id();
} else {
throw khSimpleException("Merge::CurrentSourceId: not started or no open sources: ")
<< MergeSource<ValueType>::name();
}
}
// Advance first source and reorder
virtual bool Advance() {
if (Active()) {
QueueItem top = sources_.top();
sources_.pop();
if (top->Advance()) { // if more
sources_.push(top);
} else { // else end of data
top->Close();
top.Delete();
}
return !sources_.empty();
} else {
throw khSimpleException("Merge::Advance: not started or no open sources: ")
<< MergeSource<ValueType>::name();
}
}
private:
bool started_; // true after Start called
uint next_source_id_;
// Min-heap priority queue of sources. Close() or ~Merge() will
// delete any sources left over in the queue.
std::priority_queue<QueueItem,
std::vector<QueueItem>,
std::greater<QueueItem> > sources_;
DISALLOW_COPY_AND_ASSIGN(Merge);
};
#endif // COMMON_MERGE_MERGE_H__
| 33.035556 | 89 | 0.648594 | [
"vector"
] |
3e2cf640214d5d6025959330c2958edc9c10b0b9 | 37,951 | h | C | test/ssc_test/cmod_battery_stateful_test.h | rchintala13/ssc | 3424d9b1bfab50cc11d1895d0893cf1771fd3a5e | [
"BSD-3-Clause"
] | null | null | null | test/ssc_test/cmod_battery_stateful_test.h | rchintala13/ssc | 3424d9b1bfab50cc11d1895d0893cf1771fd3a5e | [
"BSD-3-Clause"
] | null | null | null | test/ssc_test/cmod_battery_stateful_test.h | rchintala13/ssc | 3424d9b1bfab50cc11d1895d0893cf1771fd3a5e | [
"BSD-3-Clause"
] | null | null | null | #ifndef SAM_SIMULATION_CORE_CMOD_BATTERY_STATEFUL_TEST_H
#define SAM_SIMULATION_CORE_CMOD_BATTERY_STATEFUL_TEST_H
#include <gtest/gtest.h>
#include "core.h"
#include "vartab.h"
class CMBatteryStatefulIntegration_cmod_battery_stateful : public ::testing::Test {
public:
ssc_data_t data;
ssc_module_t mod;
std::string params_str;
double m_error_tolerance_hi = 100;
double m_error_tolerance_lo = 0.1;
void CreateModel(double dt_hour = 1.) {
params_str = R"({ "control_mode": 0, "input_current": 1, "chem": 1, "nominal_energy": 10, "nominal_voltage": 500, "qmax_init": 1000.000, "initial_SOC": 50.000, "maximum_SOC": 95.000, "minimum_SOC": 5.000, "dt_hr": 1.000, "leadacid_tn": 0.000, "leadacid_qn": 0.000, "leadacid_q10": 0.000, "leadacid_q20": 0.000, "voltage_choice": 0, "Vnom_default": 3.600, "resistance": 0.000, "Vfull": 4.100, "Vexp": 4.050, "Vnom": 3.400, "Qfull": 2.250, "Qexp": 0.040, "Qnom": 2.000, "C_rate": 0.200, "mass": 507.000, "surface_area": 2.018, "Cp": 1004.000, "h": 20.000, "cap_vs_temp": [ [ -10, 60 ], [ 0, 80 ], [ 25, 1E+2 ], [ 40, 1E+2 ] ], "option": 1, "T_room_init": 20, "cycling_matrix": [ [ 20, 0, 1E+2 ], [ 20, 5E+3, 80 ], [ 20, 1E+4, 60 ], [ 80, 0, 1E+2 ], [ 80, 1E+3, 80 ], [ 80, 2E+3, 60 ] ], "calendar_choice": 1, "calendar_q0": 1.020, "calendar_a": 0.003, "calendar_b": -7280.000, "calendar_c": 930.000, "calendar_matrix": [ [ -3.1E+231 ] ], "loss_choice": 0, "monthly_charge_loss": [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ], "monthly_discharge_loss": [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ], "monthly_idle_loss": [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ], "schedule_loss": [], "replacement_option": 0, "replacement_capacity": 0.000, "replacement_schedule": [], "replacement_schedule_percent": [], "analysis_period": 1, "load_escalation": [0]})";
data = json_to_ssc_data(params_str.c_str());
ssc_data_set_number(data, "dt_hr", dt_hour);
mod = ssc_stateful_module_create("battery_stateful", data);
EXPECT_TRUE(mod);
}
void CreateKokamModel()
{
double dt_hour = 1.0 / 360.0;
params_str = "{ \"control_mode\": 0, \"input_current\" : 0.0, \"chem\" : 1, \"nominal_energy\" : 0.272, \"nominal_voltage\" : 3.6, "
"\"initial_SOC\" :0.66, \"maximum_SOC\" : 100.000, \"minimum_SOC\" : 0.000, \"dt_hr\" : 0.002777, \"leadacid_tn\" : 0.000,"
"\"leadacid_qn\" : 0.000, \"leadacid_q10\" : 0.000, \"leadacid_q20\" : 0.000, \"voltage_choice\" : 0,"
"\"Vnom_default\" : 3.6, \"resistance\" : 0.001155, \"Vfull\" : 4.200, \"Vexp\" : 3.529, \"Vnom\" : 3.35, \"Qfull\" : 75.56,"
"\"Qexp\" : 60.75, \"Qnom\" : 73.58, \"C_rate\" : 0.200, \"mass\" : 1.55417, \"surface_area\" : 0.1548, \"Cp\" : 980,"
"\"h\" : 8.066, \"cap_vs_temp\" : [[ 0, 80.200000000000003 ],[23, 100],[30, 103.09999999999999],[45, 105.40000000000001]], \"T_room_init\" : 23,"
"\"cycling_matrix\" : [[ 20, 0, 107 ],[20, 1000, 101],[20, 2000, 98.5],[20, 3000, 96.3],"
"[80, 0, 107],[80, 1000, 95.6],[80, 2000, 91.1],[80, 3000, 87.3],"
"[100, 0, 107],[100, 1000, 85.1],[100, 2000, 76.3],[100, 3000, 69.1]],"
"\"calendar_choice\" : 1, \"calendar_q0\" : 1.03127097 , \"calendar_a\" : 1.35973301e-03,"
"\"calendar_b\" : -9.93161754e+03, \"calendar_c\" : 1.65896984e+03, \"calendar_matrix\" : [[-3.1E+231]], \"loss_choice\" : 0,"
"\"monthly_charge_loss\" : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ,"
"\"monthly_discharge_loss\" : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ,"
"\"monthly_idle_loss\" : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] , \"schedule_loss\" : [] , \"replacement_option\" : 0,"
"\"replacement_capacity\" : 0.000, \"replacement_schedule\" : [] , \"replacement_schedule_percent\" : [] }";
//, \"last_idx\" : 0, \"I\" : 0
data = json_to_ssc_data(params_str.c_str());
ssc_data_set_number(data, "dt_hr", dt_hour);
mod = ssc_stateful_module_create("battery_stateful", data);
}
void TearDown() override {
ssc_data_free(data);
ssc_module_free(mod);
}
std::vector<double> getCurrentData() {
return { 0.0, 0.0, -72.0, -75.6, -75.60000000000001, -75.6, -75.60000000000002, -71.99999999999999, -75.6, -75.6, -75.60000000000007, -75.6, -75.6, -72.00000000000007, -75.6, -75.6, -75.6, -75.6, -75.6, -72.00000000000007, -75.6, -75.6, -75.6, -75.6, -75.6, -72.00000000000007, -75.6, -75.6, -75.6, -75.6, -75.6, -72.00000000000007, -75.6, -75.6, -75.6, -75.6, -75.6, -72.00000000000007, -75.6, -75.6, -75.59999999999967, -75.6000000000003, -75.59999999999967, -72.00000000000038, -75.59999999999967, -75.6000000000003, -75.59999999999967, -75.6000000000003, -75.59999999999967, -72.00000000000038, -75.59999999999967, -75.6000000000003, -75.59999999999967, -75.6000000000003, -75.59999999999967, -72.00000000000038, -75.59999999999967, -75.6000000000003, -75.59999999999967, -75.6000000000003, -75.59999999999967, -72.00000000000038, -75.59999999999967, -75.6000000000003, -75.59999999999967, -75.6000000000003, -75.59999999999967, -72.00000000000038, -75.59999999999967, -75.6000000000003, -75.59999999999967, -75.6000000000003, -75.59999999999967, -72.00000000000038, -75.59999999999967, -75.6000000000003, -75.59999999999967, -75.6000000000003, -75.59999999999967, -71.99999999999974, -75.6000000000003, -75.6000000000003, -75.6000000000003, -75.59999999999903, -75.6000000000003, -71.99999999999974, -75.6000000000003, -75.6000000000003, -75.6000000000003, -75.59999999999903, -75.6000000000003, -71.99999999999974, -75.6000000000003, -75.6000000000003, -75.6000000000003, -75.59999999999903, -75.6000000000003, -71.99999999999974, -75.6000000000003, -74.4479996395116, -75.3120000171664, -71.71200001716583, -68.11200001716547, -64.80000000000108, -64.7999999999999, -64.51200001716599, -61.19999999999945, -60.9120000171667, -57.600000000000044, -57.31200001716614, -54.28799998283339, -57.02400003433233, -50.68799998283401, -53.71200001716568, -50.4000000000002, -50.112000017166295, -47.087999982833544, -50.112000017166295, -46.51200001716583, -43.48799998283417, -46.51200001716583, -42.912000017166456, -39.887999982833705, -42.912000017166456, -39.5999999999998, -39.5999999999998, -39.31200001716599, -36.28799998283432, -39.31200001716599, -35.71200001716661, -32.68799998283375, -35.71200001716543, -32.68799998283386, -35.71200001716661, -32.112000017166146, -29.087999982834468, -32.11200001716604, -28.79999999999949, -28.800000000000562, -28.79999999999949, -28.800000000000562, -5.0400001373111, -9.023892744153272e-13, -1.652011860642233e-12, -2.55440113505756e-12, -2.55440113505756e-12, -2.55440113505756e-12, 0.0, -2.284394895468722e-12, 0.0, 0.0, 0.0, 0.0, 0.0, -3.730349362740526e-13, 0.0, -3.730349362740526e-13, 0.0, -3.730349362740526e-13, -1.2789769243681803e-12, -1.2789769243681803e-12, -1.2789769243681803e-12, 0.0, -1.007194327939942e-12, 0.0, -1.007194327939942e-12, 0.0, -1.007194327939942e-12, 0.0, -2.5579538487363607e-12, 0.0, 0.0, -2.5579538487363607e-12, 0.0, 0.0, -2.5579538487363607e-12, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.7763568394002505e-15, -1.552535877635819e-12, 0.0, 0.0, -1.7763568394002505e-15, 0.0, -4.778399897986674e-13, -8.020251129892131e-13, -3.7481129311345285e-13, 0.0, -1.552535877635819e-12, 0.0, -1.552535877635819e-12, 0.0, -1.552535877635819e-12, -1.2789769243681803e-12, -1.2789769243681803e-12, -1.2789769243681803e-12, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 29.483998918533324, 75.6, 75.6, 75.60000000000001, 74.19600005149842, 73.40399994850156, 75.6, 75.60000000000002, 75.60000000000004, 75.6, 74.19600005149843, 73.40399994850162, 75.6, 75.6, 75.6, 75.6, 74.19600005149843, 73.40399994850162, 75.6, 75.6, 75.6, 75.6, 74.19600005149843, 73.40399994850162, 75.6, 75.6, 75.6, 75.6, 74.19600005149843, 73.40399994850162, 75.6, 75.6, 75.6, 75.6, 74.19600005149843, 73.40399994850162, 75.6, 75.59999999999987, 75.59999999999991, 75.60000000000005, 74.19600005149836, 73.40399994850169, 75.59999999999991, 75.60000000000005, 75.59999999999991, 75.60000000000005, 74.19600005149836, 73.40399994850169, 75.59999999999991, 75.60000000000005, 75.59999999999991, 75.60000000000005, 74.19600005149836, 73.40399994850169, 75.59999999999991, 75.60000000000005, 75.59999999999991, 75.60000000000005, 74.19600005149836, 73.40399994850169, 75.59999999999991, 75.60000000000005, 75.59999999999991, 75.60000000000005, 74.19600005149836, 73.40399994850169, 75.59999999999991, 75.60000000000005, 75.59999999999991, 75.60000000000005, 74.19600005149836, 73.40399994850169, 75.59999999999991, 75.60000000000005, 75.59999999999991, 75.60000000000005, 74.1960000514981, 73.40399994850155, 75.6000000000003, 75.6000000000003, 75.59999999999981, 75.59999999999953, 74.1960000514985, 73.40399994850155, 75.6000000000003, 75.6000000000003, 75.59999999999981, 75.59999999999953, 74.1960000514985, 73.40399994850155, 75.6000000000003, 75.6000000000003, 75.59999999999981, 75.59999999999953, 74.1960000514985, 73.40399994850155, 75.6000000000003, 75.6000000000003, 75.59999999999981, 75.59999999999953, 74.1960000514985, 73.40399994850155, 75.6000000000003, 75.6000000000003, 75.59999999999981, 75.59999999999953, 74.1960000514985, 73.40399994850155, 75.6000000000003, 75.6000000000003, 75.59999999999981, 75.59999999999953, 74.1960000514985, 73.40399994850155, 75.6000000000003, 75.6000000000003, 75.59999999999981, 75.59999999999953, 74.1960000514985, 73.40399994850155, 75.6000000000003, 75.6000000000003, 75.59999999999981, 75.59999999999953, 74.1960000514985, 73.40399994850155, 75.6000000000003, 75.6000000000003, 75.59999999999981, 75.59999999999953, 74.1960000514985, 73.40399994850155, 75.6000000000003, 75.6000000000003, 75.59999999999981, 75.59999999999953, 74.1960000514985, 73.40399994850155, 75.6000000000003, 75.6000000000003, 75.59999999999981, 75.59999999999953, 74.1960000514985, 73.40399994850155, 75.6000000000003, 75.6000000000003, 75.59999999999981, 75.59999999999953, 74.1960000514985, 73.40399994850155, 75.6000000000003, 75.6000000000003, 75.59999999999981, 75.59999999999953, 74.196000051499, 73.40399994850233, 75.59999999999931, 75.59999999999874, 75.6000000000003, 75.6000000000003, 74.196000051499, 73.40399994850233, 75.59999999999931, 75.59999999999874, 75.6000000000003, 75.6000000000003, 74.196000051499, 73.40399994850233, 75.59999999999931, 75.59999999999874, 75.6000000000003, 75.6000000000003, 74.196000051499, 73.40399994850233, 75.59999999999931, 75.59999999999874, 75.6000000000003, 75.6000000000003, 74.196000051499, 73.40399994850233, 75.59999999999931, 75.59999999999874, 75.6000000000003, 75.6000000000003, 74.196000051499, 73.40399994850233, 75.59999999999931, 75.59999999999874, 75.6000000000003, 75.6000000000003, 74.196000051499, 73.40399994850233, 75.59999999999931, 75.59999999999874, 75.6000000000003, 75.6000000000003, 74.196000051499, 73.40399994850233, 75.59999999999931, 75.59999999999874, 75.6000000000003, 75.6000000000003, 74.196000051499, 73.40399994850233, 75.59999999999931, 75.59999999999874, 75.6000000000003, 75.6000000000003, 74.196000051499, 73.40399994850233, 75.59999999999931, 75.59999999999874, 75.6000000000003, 75.6000000000003, 74.196000051499, 73.40399994850233, 75.59999999999931, 75.59999999999874, 75.6000000000003, 75.6000000000003, 74.196000051499, 73.40399994850233, 75.59999999999931, 75.59999999999874, 75.6000000000003, 75.6000000000003, 74.196000051499, 73.40399994850233, 75.59999999999931, 75.59999999999874, 75.6000000000003, 75.6000000000003, 74.196000051499, 73.40399994850233, 75.59999999999931, 75.59999999999874, 75.6000000000003, 75.6000000000003, 74.196000051499, 73.40399994850233, 75.59999999999931, 75.59999999999874, 75.6000000000003, 75.6000000000003, 74.196000051499, 73.40399994850233, 75.59999999999931, 75.59999999999874, 75.6000000000003, 75.6000000000003, 74.196000051499, 73.40399994850233, 75.59999999999931, 75.59999999999874, 75.6000000000003, 75.6000000000003, 74.196000051499, 73.40399994850233, 75.59999999999931, 75.59999999999874, 75.6000000000003, 75.6000000000003, 74.196000051499, 73.40399994850233, 75.59999999999931, 75.59999999999874, 75.6000000000003, 75.6000000000003, 74.196000051499, 73.40399994850233, 75.59999999999931, 75.59999999999874, 75.89781788400414, 45.81818319746303, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -30.239998197555543, -75.6, -75.60000000000001, -75.60000000000001, -74.16000008583069, -73.4399999141693, -75.6, -75.60000000000002, -75.60000000000005, -75.6, -74.16000008583072, -73.43999991416936, -75.6, -75.6, -75.6, -75.6, -74.16000008583072, -73.43999991416936, -75.6, -75.6, -75.6, -75.6, -74.16000008583072, -73.43999991416936, -75.6, -75.6, -75.6, -75.6, -74.16000008583072, -73.43999991416936, -75.6, -75.6, -75.6, -75.6, -74.16000008583072, -73.43999991416936, -75.6, -75.59999999999987, -75.59999999999992, -75.60000000000005, -74.16000008583065, -73.43999991416942, -75.59999999999992, -75.60000000000005, -75.59999999999992, -75.60000000000005, -74.16000008583065, -73.43999991416942, -75.59999999999992, -75.60000000000005, -75.59999999999992, -75.60000000000005, -74.16000008583065, -73.43999991416942, -75.59999999999992, -75.60000000000005, -75.59999999999992, -75.60000000000005, -74.16000008583065, -73.43999991416942, -75.59999999999992, -75.60000000000005, -75.59999999999992, -75.60000000000005, -74.16000008583065, -73.43999991416942, -75.59999999999992, -75.60000000000005, -75.59999999999992, -75.60000000000005, -74.16000008583065, -73.43999991416942, -75.59999999999992, -75.60000000000005, -75.59999999999992, -75.60000000000005, -74.16000008583039, -73.43999991416928, -75.6000000000003, -75.6000000000003, -75.5999999999998, -75.59999999999954, -74.16000008583077, -73.43999991416928, -75.6000000000003, -75.6000000000003, -75.5999999999998, -75.59999999999954, -74.16000008583077, -73.43999991416928, -75.6000000000003, -75.6000000000003, -75.5999999999998, -75.59999999999954, -74.16000008583077, -73.43999991416928, -75.6000000000003, -75.6000000000003, -75.5999999999998, -75.59999999999954, -74.16000008583077, -73.43999991416928, -75.6000000000003, -75.6000000000003, -75.5999999999998, -75.59999999999954, -74.16000008583077, -73.43999991416928, -75.6000000000003, -75.6000000000003, -75.5999999999998, -75.59999999999954, -74.16000008583077, -73.43999991416928, -75.6000000000003, -75.6000000000003, -75.5999999999998, -75.59999999999954, -74.16000008583077, -73.43999991416928, -75.6000000000003, -75.6000000000003, -75.5999999999998, -75.59999999999954, -74.16000008583077, -73.43999991416928, -75.6000000000003, -75.6000000000003, -75.5999999999998, -75.59999999999954, -74.16000008583077, -73.43999991416928, -75.6000000000003, -75.6000000000003, -75.5999999999998, -75.59999999999954, -74.16000008583077, -73.43999991416928, -75.6000000000003, -75.6000000000003, -75.5999999999998, -75.59999999999954, -74.16000008583077, -73.43999991416928, -75.6000000000003, -75.6000000000003, -75.5999999999998, -75.59999999999954, -74.16000008583077, -73.43999991416928, -75.6000000000003, -75.6000000000003, -75.5999999999998, -75.59999999999954, -74.16000008583129, -73.43999991417004, -75.59999999999928, -75.59999999999877, -75.6000000000003, -75.6000000000003, -74.16000008583129, -73.43999991417004, -75.59999999999928, -75.59999999999877, -75.6000000000003, -75.6000000000003, -74.16000008583129, -73.43999991417004, -75.59999999999928, -75.59999999999877, -75.6000000000003, -75.6000000000003, -74.16000008583129, -73.43999991417004, -75.59999999999928, -75.59999999999877, -75.6000000000003, -75.6000000000003, -74.16000008583129, -73.43999991417004, -75.59999999999928, -75.59999999999877, -75.6000000000003, -75.6000000000003, -74.16000008583129, -73.43999991417004, -75.59999999999928, -75.59999999999877, -75.6000000000003, -75.6000000000003, -74.16000008583129, -73.43999991417004, -75.59999999999928, -75.59999999999877, -75.6000000000003, -75.6000000000003, -74.16000008583129, -73.43999991417004, -75.59999999999928, -75.59999999999877, -75.6000000000003, -75.6000000000003, -74.16000008583129, -73.43999991417004, -75.59999999999928, -75.59999999999877, -75.6000000000003, -75.6000000000003, -74.16000008583129, -73.43999991417004, -75.59999999999928, -75.59999999999877, -75.6000000000003, -75.6000000000003, -74.16000008583129, -73.43999991417004, -75.59999999999928, -75.59999999999877, -75.6000000000003, -75.6000000000003, -74.16000008583129, -73.43999991417004, -75.59999999999928, -75.59999999999877, -75.6000000000003, -75.6000000000003, -74.16000008583129, -73.43999991417004, -75.59999999999928, -75.59999999999877, -75.6000000000003, -75.6000000000003, -74.16000008583129, -73.43999991417004, -75.59999999999928, -75.59999999999877, -75.6000000000003, -74.89846176085473, -74.93353859963587, -71.13600013732871, -68.39999999999918, -66.16800006866418, -64.7999999999999, -62.568000068664894, -61.200000000000614, -61.200000000000614, -56.736000137329015, -56.2319999313345, -55.36800006866376, -54.00000000000108, -51.76800006866546, -50.400000000000205, -50.39999999999863, -48.16800006866423, -46.80000000000092, -46.799999999999336, -46.79999999999995, -44.56800006866433, -43.200000000000664, -40.96800006866505, -39.599999999999795, -39.599999999999795, -39.599999999999795, -37.36800006866479, -38.23199993133552, -37.36800006866479, -33.76800006866392, -34.63199993133526, -33.76800006866551, -32.39999999999964, -32.40000000000026, -32.39999999999964, -30.168000068663666, -28.80000000000097, -28.80000000000036, -28.799999999999386, -28.799999999999386, -26.568000068664382, -25.200000000000102, -25.200000000000102, -25.200000000000102, -25.200000000000102, -25.200000000000102, -22.9680000686651, -23.831999931335822, -22.968000068663514, -21.599999999999845, -21.60000000000082, -21.599999999999234, -19.36800006866484, -20.23199993133654, -19.36800006866423, -17.999999999998977, -20.231999931335565, -19.36800006866423, -15.768000068665557, -16.63199993133567, -17.999999999998977, -18.00000000000056, -15.768000068664943, -16.6319999313347, -15.768000068663971, -14.399999999999693, -14.400000000001281, -14.400000000000666, -14.399999999999693, -14.399999999999693, -14.399999999999693, -12.16800006866469, -13.031999931335415, -14.399999999999693, -12.16800006866469, -10.80000000000041, -13.031999931335415, -12.16800006866469, -10.80000000000041, -10.799999999998825, -10.799999999999436, -10.80000000000041, -10.80000000000041, -10.80000000000041, -10.80000000000041, -10.80000000000041, -8.568000068663817, -9.43199993133516, -10.80000000000041, -8.568000068663817, -9.43199993133516, -8.568000068665405, -7.199999999999539, -9.43199993133516, -8.568000068665405, -7.199999999999539, -1.484726537280375, -8.046896482483135e-13, -1.6697754290362354e-13, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 27.215999279022213, 75.6, 75.6, 75.60000000000001, 74.30400003433229, 73.2959999656677, 75.6, 75.60000000000002, 75.60000000000004, 75.6, 74.30400003433229, 73.29599996566776, 75.6, 75.6, 75.6, 75.6, 74.30400003433229, 73.29599996566776, 75.6, 75.6, 75.6, 75.6, 74.30400003433229, 73.29599996566776, 75.6, 75.6, 75.6, 75.6, 74.30400003433229, 73.29599996566776, 75.6, 75.6, 75.6, 75.6, 74.30400003433229, 73.29599996566776, 75.6, 75.59999999999988, 75.5999999999999, 75.60000000000008, 74.3040000343322, 73.29599996566785, 75.5999999999999, 75.60000000000008, 75.5999999999999, 75.60000000000008, 74.3040000343322, 73.29599996566785, 75.5999999999999, 75.60000000000008, 75.5999999999999, 75.60000000000008, 74.3040000343322, 73.29599996566785, 75.5999999999999, 75.60000000000008, 75.5999999999999, 75.60000000000008, 74.3040000343322, 73.29599996566785, 75.5999999999999, 75.60000000000008, 75.5999999999999, 75.60000000000008, 74.3040000343322, 73.29599996566785, 75.5999999999999, 75.60000000000008, 75.5999999999999, 75.60000000000008, 74.3040000343322, 73.29599996566785, 75.5999999999999, 75.60000000000008, 75.5999999999999, 75.60000000000008, 74.30400003433198, 73.29599996566768, 75.6000000000003, 75.6000000000003, 75.59999999999985, 75.59999999999948, 74.30400003433238, 73.29599996566768, 75.6000000000003, 75.6000000000003, 75.59999999999985, 75.59999999999948, 74.30400003433238, 73.29599996566768, 75.6000000000003, 75.6000000000003, 75.59999999999985, 75.59999999999948, 74.30400003433238, 73.29599996566768, 75.6000000000003, 75.6000000000003, 75.59999999999985, 75.59999999999948, 74.30400003433238, 73.29599996566768, 75.6000000000003, 75.6000000000003, 75.59999999999985, 75.59999999999948, 74.30400003433238, 73.29599996566768, 75.6000000000003, 75.6000000000003, 75.59999999999985, 75.59999999999948, 74.30400003433238, 73.29599996566768, 75.6000000000003, 75.6000000000003, 75.59999999999985, 75.59999999999948, 74.30400003433238, 73.29599996566768, 75.6000000000003, 75.6000000000003, 75.59999999999985, 75.59999999999948, 74.30400003433238, 73.29599996566768, 75.6000000000003, 75.6000000000003, 75.59999999999985, 75.59999999999948, 74.30400003433238, 73.29599996566768, 75.6000000000003, 75.6000000000003, 75.59999999999985, 75.59999999999948, 74.30400003433238, 73.29599996566768, 75.6000000000003, 75.6000000000003, 75.59999999999985, 75.59999999999948, 74.30400003433238, 73.29599996566768, 75.6000000000003, 75.6000000000003, 75.59999999999985, 75.59999999999948, 74.30400003433238, 73.29599996566768, 75.6000000000003, 75.6000000000003, 75.59999999999985, 75.59999999999948, 74.30400003433284, 73.29599996566849, 75.59999999999938, 75.59999999999867, 75.6000000000003, 75.6000000000003, 74.30400003433284, 73.29599996566849, 75.59999999999938, 75.59999999999867, 75.6000000000003, 75.6000000000003, 74.30400003433284, 73.29599996566849, 75.59999999999938, 75.59999999999867, 75.6000000000003, 75.6000000000003, 74.30400003433284, 73.29599996566849, 75.59999999999938, 75.59999999999867, 75.6000000000003, 75.6000000000003, 74.30400003433284, 73.29599996566849, 75.59999999999938, 75.59999999999867, 75.6000000000003, 75.6000000000003, 74.30400003433284, 73.29599996566849, 75.59999999999938, 75.59999999999867, 75.6000000000003, 75.6000000000003, 74.30400003433284, 73.29599996566849, 75.59999999999938, 75.59999999999867, 75.6000000000003, 75.6000000000003, 74.30400003433284, 73.29599996566849, 75.59999999999938, 75.59999999999867, 75.6000000000003, 75.6000000000003, 74.30400003433284, 73.29599996566849, 75.59999999999938, 75.59999999999867, 75.6000000000003, 75.6000000000003, 74.30400003433284, 73.29599996566849, 75.59999999999938, 75.59999999999867, 75.6000000000003, 75.6000000000003, 74.30400003433284, 73.29599996566849, 75.59999999999938, 75.59999999999867, 75.6000000000003, 75.6000000000003, 74.30400003433284, 73.29599996566849, 75.59999999999938, 75.59999999999867, 75.6000000000003, 75.6000000000003, 74.30400003433284, 73.29599996566849, 75.59999999999938, 75.59999999999867, 75.6000000000003, 75.6000000000003, 74.30400003433284, 73.29599996566849, 75.59999999999938, 75.59999999999867, 75.6000000000003, 75.6000000000003, 74.30400003433284, 73.29599996566849, 75.59999999999938, 75.59999999999867, 75.6000000000003, 75.6000000000003, 74.30400003433284, 73.29599996566849, 75.59999999999938, 75.59999999999867, 75.6000000000003, 75.6000000000003, 74.30400003433284, 73.29599996566849, 75.59999999999938, 75.59999999999867, 75.6000000000003, 75.6000000000003, 74.30400003433284, 73.29599996566849, 75.59999999999938, 75.59999999999867, 75.6000000000003, 75.6000000000003, 74.30400003433284, 73.29599996566849, 75.59999999999938, 75.59999999999867, 75.6000000000003, 75.6000000000003, 74.30400003433284, 73.29599996566849, 75.59999999999938, 75.59999999999867, 75.6000000000003, 74.7433216305224, 16.84067909045721, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -58.211998558044435, -75.60000000000001, -75.60000000000001, -75.60000000000002, -72.82800006866455, -74.77199993133544, -75.6, -75.60000000000005, -75.60000000000002, -75.6, -72.82800006866461, -74.77199993133547, -75.6, -75.6, -75.6, -75.6, -72.82800006866461, -74.77199993133547, -75.6, -75.6, -75.6, -75.6, -72.82800006866461, -74.77199993133547, -75.6, -75.6, -75.6, -75.6, -72.82800006866461, -74.77199993133547, -75.6, -75.6, -75.6, -75.6, -72.82800006866461, -74.77199993133547, -75.6, -75.59999999999974, -75.60000000000016, -75.59999999999981, -72.82800006866478, -74.77199993133527, -75.60000000000016, -75.59999999999981, -75.60000000000016, -75.59999999999981, -72.82800006866478, -74.77199993133527, -75.60000000000016, -75.59999999999981, -75.60000000000016, -75.59999999999981, -72.82800006866478, -74.77199993133527, -75.60000000000016, -75.59999999999981, -75.60000000000016, -75.59999999999981, -72.82800006866478, -74.77199993133527, -75.60000000000016, -75.59999999999981, -75.60000000000016, -75.59999999999981, -72.82800006866478, -74.77199993133527, -75.60000000000016, -75.59999999999981, -75.60000000000016, -75.59999999999981, -72.82800006866478, -74.77199993133527, -75.60000000000016, -75.59999999999981, -75.60000000000016, -75.59999999999981, -72.82800006866428, -74.77199993133563, -75.6000000000003, -75.6000000000003, -75.59999999999931, -75.60000000000001, -72.82800006866444, -74.77199993133563, -75.6000000000003, -75.6000000000003, -75.59999999999931, -75.60000000000001, -72.82800006866444, -74.77199993133563, -75.6000000000003, -75.6000000000003, -75.59999999999931, -75.60000000000001, -72.82800006866444, -74.77199993133563, -75.6000000000003, -75.6000000000003, -75.59999999999931, -75.60000000000001, -72.82800006866444, -74.77199993133563, -75.6000000000003, -75.6000000000003, -75.59999999999931, -75.60000000000001, -72.82800006866444, -74.77199993133563, -75.6000000000003, -75.6000000000003, -75.59999999999931, -75.60000000000001, -72.82800006866444, -74.77199993133563, -75.6000000000003, -75.6000000000003, -75.59999999999931, -75.60000000000001, -72.82800006866444, -74.77199993133563, -75.6000000000003, -75.6000000000003, -75.59999999999931, -75.60000000000001, -72.82800006866444, -74.77199993133563, -75.6000000000003, -75.6000000000003, -75.59999999999931, -75.60000000000001, -72.82800006866444, -74.77199993133563, -75.6000000000003, -75.6000000000003, -75.59999999999931, -75.60000000000001, -72.82800006866444, -74.77199993133563, -75.6000000000003, -75.6000000000003, -75.59999999999931, -75.60000000000001, -72.82800006866444, -74.77199993133563, -75.6000000000003, -75.6000000000003, -75.59999999999931, -75.60000000000001, -72.82800006866444, -74.77199993133563, -75.6000000000003, -75.6000000000003, -75.59999999999931, -75.60000000000001, -72.8280000686654, -74.77199993133593, -75.59999999999835, -75.59999999999971, -75.6000000000003, -75.6000000000003, -72.8280000686654, -74.77199993133593, -75.59999999999835, -75.59999999999971, -75.6000000000003, -75.6000000000003, -72.8280000686654, -74.77199993133593, -75.59999999999835, -75.59999999999971, -75.6000000000003, -75.6000000000003, -72.8280000686654, -74.77199993133593, -75.59999999999835, -75.59999999999971, -75.6000000000003, -75.6000000000003, -72.8280000686654, -74.77199993133593, -75.59999999999835, -75.59999999999971, -75.6000000000003, -75.6000000000003, -72.8280000686654, -74.77199993133593, -75.59999999999835, -75.59999999999971, -75.6000000000003, -75.6000000000003, -72.8280000686654, -74.77199993133593, -75.59999999999835, -75.59999999999971, -75.6000000000003, -75.6000000000003, -72.8280000686654, -74.77199993133593, -75.59999999999835, -75.59999999999971, -75.6000000000003, -75.6000000000003, -72.8280000686654, -74.77199993133593, -75.59999999999835, -75.59999999999971, -75.6000000000003, -75.6000000000003, -72.8280000686654, -74.77199993133593, -75.59999999999835, -75.59999999999971, -75.6000000000003, -75.6000000000003, -72.8280000686654, -74.77199993133593, -75.59999999999835, -75.59999999999971, -75.6000000000003, -75.6000000000003, -72.8280000686654, -74.77199993133593, -75.59999999999835, -75.59999999999971, -75.6000000000003, -75.6000000000003, -72.8280000686654, -74.77199993133593, -75.59999999999835, -75.59999999999971, -75.6000000000003, -75.6000000000003, -72.8280000686654, -74.77199993133593, -75.59999999999835, -75.59999999999971, -75.6000000000003, -75.56577846359716, -72.14222229171456, -71.99999999999856, -68.54400003433388, -64.94400003433225, -64.7999999999999, -61.3440000343304, -61.200000000000514, -57.74400003433358, -57.59999999999888, -54.14400003433174, -57.45599996566899, -50.6880000686648, -53.855999965667245, -50.54400003433245, -46.944000034330706, -50.255999965667854, -46.944000034333165, -46.80000000000092, -43.34400003433143, -43.19999999999908, -43.20000000000154, -39.744000034332146, -43.055999965666835, -39.744000034332046, -36.144000034332755, -39.45599996566755, -36.144000034332755, -36.000000000000504, -36.000000000000504, -32.54400003433102, -32.40000000000112, -32.39999999999877, -32.40000000000112, -32.39999999999877, -28.944000034331633, -28.80000000000184, -28.79999999999949, -28.799999999999386, -28.799999999999386, -25.344000034332346, -25.2000000000001, -25.2000000000001, -25.2000000000001, -25.2000000000001, -25.2000000000001, -21.744000034333066, -25.05599996566785, -21.744000034330607, -21.60000000000072, -21.60000000000082, -18.144000034331327, -21.45599996566847, -18.144000034331327, -21.45599996566847, -18.144000034331327, -18.00000000000143, -17.99999999999908, -18.00000000000143, -17.99999999999908, -17.999999999998977, -14.54400003433194, -17.855999965669184, -14.544000034332042, -14.399999999999693, -17.85599996566673, -14.544000034334395, -14.399999999999796, -14.399999999999693, -14.399999999999693, -10.944000034332657, -14.255999965667446, -14.399999999999693, -10.944000034332657, -14.255999965667446, -10.944000034332657, -10.80000000000041, -10.80000000000041, -14.255999965667446, -10.9440000343302, -10.800000000000308, -10.80000000000041, -10.80000000000041, -7.344000034333372, -10.655999965665707, -10.800000000000308, -10.80000000000041, -7.344000034333372, -10.655999965665707, -7.34400003433327, -10.655999965668164, -7.344000034330917, -7.200000000001023, -10.655999965668164, -7.344000034330917, -7.200000000001023, -7.2000000000011255, -7.199999999998671, -3.8880000686637772, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 45.36, 75.6, 75.6, 75.60000000000001, 73.44, 74.16, 75.6, 75.60000000000004, 75.60000000000002, 75.6, 73.44000000000004, 74.16000000000003, 75.6, 75.6, 75.6, 75.6, 73.44000000000004, 74.16000000000003, 75.6, 75.6, 75.6, 75.6, 73.44000000000004, 74.16000000000003, 75.6, 75.6, 75.6, 75.6, 73.44000000000004, 74.16000000000003, 75.6, 75.6, 75.6, 75.6, 73.44000000000004, 74.16000000000003, 75.6, 75.5999999999998, 75.60000000000005, 75.59999999999992, 73.4400000000001, 74.15999999999995, 75.60000000000005, 75.59999999999992, 75.60000000000005, 75.59999999999992, 73.4400000000001, 74.15999999999995, 75.60000000000005, 75.59999999999992, 75.60000000000005, 75.59999999999992, 73.4400000000001, 74.15999999999995, 75.60000000000005, 75.59999999999992, 75.60000000000005, 75.59999999999992, 73.4400000000001, 74.15999999999995, 75.60000000000005, 75.59999999999992, 75.60000000000005, 75.59999999999992, 73.4400000000001, 74.15999999999995, 75.60000000000005, 75.59999999999992, 75.60000000000005, 75.59999999999992, 73.4400000000001, 74.15999999999995, 75.60000000000005, 75.59999999999992, 75.60000000000005, 75.59999999999992, 73.43999999999971, 74.16000000000008, 75.6000000000003, 75.6000000000003, 75.59999999999954, 75.5999999999998, 73.43999999999997, 74.16000000000008, 75.6000000000003, 75.6000000000003, 75.59999999999954, 75.5999999999998, 73.43999999999997, 74.16000000000008, 75.6000000000003, 75.6000000000003, 75.59999999999954, 75.5999999999998, 73.43999999999997, 74.16000000000008, 75.6000000000003, 75.6000000000003, 75.59999999999954, 75.5999999999998, 73.43999999999997, 74.16000000000008, 75.6000000000003, 75.6000000000003, 75.59999999999954, 75.5999999999998, 73.43999999999997, 74.16000000000008, 75.6000000000003, 75.6000000000003, 75.59999999999954, 75.5999999999998, 73.43999999999997, 74.16000000000008, 75.6000000000003, 75.6000000000003, 75.59999999999954, 75.5999999999998, 73.43999999999997, 74.16000000000008, 75.6000000000003, 75.6000000000003, 75.59999999999954, 75.5999999999998, 73.43999999999997, 74.16000000000008, 75.6000000000003, 75.6000000000003, 75.59999999999954, 75.5999999999998, 73.43999999999997, 74.16000000000008, 75.6000000000003, 75.6000000000003, 75.59999999999954, 75.5999999999998, 73.43999999999997, 74.16000000000008, 75.6000000000003, 75.6000000000003, 75.59999999999954, 75.5999999999998, 73.43999999999997, 74.16000000000008, 75.6000000000003, 75.6000000000003, 75.59999999999954, 75.5999999999998, 73.43999999999997, 74.16000000000008, 75.6000000000003, 75.6000000000003, 75.59999999999954, 75.5999999999998, 73.44000000000074, 74.1600000000006, 75.59999999999877, 75.59999999999928, 75.6000000000003, 75.6000000000003, 73.44000000000074, 74.1600000000006, 75.59999999999877, 75.59999999999928, 75.6000000000003, 75.6000000000003, 73.44000000000074, 74.1600000000006, 75.59999999999877, 75.59999999999928, 75.6000000000003, 75.6000000000003, 73.44000000000074, 74.1600000000006, 75.59999999999877, 75.59999999999928, 75.6000000000003, 75.6000000000003, 73.44000000000074, 74.1600000000006, 75.59999999999877, 75.59999999999928, 75.6000000000003, 75.6000000000003, 73.44000000000074, 74.1600000000006, 75.59999999999877, 75.59999999999928, 75.6000000000003, 75.6000000000003, 73.44000000000074, 74.1600000000006, 75.59999999999877, 75.59999999999928, 75.6000000000003, 75.6000000000003, 73.44000000000074, 74.1600000000006, 75.59999999999877, 75.59999999999928, 75.6000000000003, 75.6000000000003, 73.44000000000074, 74.1600000000006, 75.59999999999877, 75.59999999999928, 75.6000000000003, 75.6000000000003, 73.44000000000074, 74.1600000000006, 75.59999999999877, 75.59999999999928, 75.6000000000003, 75.6000000000003, 73.44000000000074, 74.1600000000006, 75.59999999999877, 75.59999999999928, 75.6000000000003, 75.6000000000003, 73.44000000000074, 74.1600000000006, 75.59999999999877, 75.59999999999928, 75.6000000000003, 75.6000000000003, 73.44000000000074, 74.1600000000006, 75.59999999999877, 75.59999999999928, 75.6000000000003, 75.6000000000003, 73.44000000000074, 74.1600000000006, 75.59999999999877, 75.59999999999928, 75.6000000000003, 75.6000000000003, 73.44000000000074, 74.1600000000006, 75.59999999999877, 75.59999999999928, 75.6000000000003, 75.6000000000003, 73.44000000000074, 74.1600000000006, 75.59999999999877, 75.59999999999928, 75.6000000000003, 75.6000000000003, 73.44000000000074, 74.1600000000006, 75.59999999999877, 75.59999999999928, 75.6000000000003, 75.6000000000003, 73.44000000000074, 74.1600000000006, 75.59999999999877, 75.59999999999928, 75.6000000000003, 75.6000000000003, 73.44000000000074, 74.1600000000006, 75.59999999999877, 75.59999999999928, 75.6000000000003, 75.6000000000003, 73.44000000000074, 74.1600000000006, 75.59999999999877, 75.59999999999928, 75.6000000000003, 44.639999999999816, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -29.484000720977782, -75.6, -75.60000000000001, -75.60000000000001, -74.19599996566774, -73.40400003433226, -75.6, -75.60000000000002, -75.60000000000005, -75.6, -74.19599996566775, -73.40400003433231, -75.6, -75.6, -75.6, -75.6, -74.19599996566775, -73.40400003433231, -75.6, -75.6, -75.6, -75.6, -74.19599996566775, -73.40400003433231, -75.6, -75.6, -75.6, -75.6, -74.19599996566775, -73.40400003433231, -75.6, -75.6, -75.6, -75.6, -74.19599996566775, -73.40400003433231, -75.6, -75.59999999999987, -75.59999999999991, -75.60000000000005, -74.19599996566767, -73.40400003433237, -75.59999999999991, -75.60000000000005, -75.59999999999991, -75.60000000000005, -74.19599996566767, -73.40400003433237, -75.59999999999991, -75.60000000000005, -75.59999999999991, -75.60000000000005, -74.19599996566767, -73.40400003433237, -75.59999999999991, -75.60000000000005, -75.59999999999991, -75.60000000000005, -74.19599996566767, -73.40400003433237, -75.59999999999991, -75.60000000000005, -75.59999999999991, -75.60000000000005, -74.19599996566767, -73.40400003433237, -75.59999999999991, -75.60000000000005, -75.59999999999991, -75.60000000000005, -74.19599996566767, -73.40400003433237, -75.59999999999991, -75.60000000000005, -75.59999999999991, -75.60000000000005, -74.19599996566743, -73.40400003433224, -75.6000000000003, -75.6000000000003, -75.59999999999981, -75.59999999999953, -74.19599996566781, -73.40400003433224, -75.6000000000003, -75.6000000000003, -75.59999999999981, -75.59999999999953, -74.19599996566781, -73.40400003433224, -75.6000000000003, -75.6000000000003, -75.59999999999981, -75.59999999999953, -74.19599996566781, -73.40400003433224, -75.6000000000003, -75.6000000000003, -75.59999999999981, -75.59999999999953, -74.19599996566781, -73.40400003433224, -75.6000000000003, -75.6000000000003, -75.59999999999981, -75.59999999999953, -74.19599996566781, -73.40400003433224, -75.6000000000003, -75.6000000000003, -75.59999999999981, -75.59999999999953, -74.19599996566781, -73.40400003433224, -75.6000000000003, -75.6000000000003, -75.59999999999981, -75.59999999999953 };
}
};
#endif //SAM_SIMULATION_CORE_CMOD_BATTERY_STATEFUL_TEST_H
| 592.984375 | 33,672 | 0.768148 | [
"vector"
] |
3e34ea51aab5f98dc611a7046eee4a9dd8dd9745 | 79,763 | c | C | nan.c | DennissimOS/platform_vendor_qcom-opensource_wlan_utils_sigma-dut | 8ffe675635b8b9882cf97a1abbaf7b1619148012 | [
"Unlicense"
] | null | null | null | nan.c | DennissimOS/platform_vendor_qcom-opensource_wlan_utils_sigma-dut | 8ffe675635b8b9882cf97a1abbaf7b1619148012 | [
"Unlicense"
] | null | null | null | nan.c | DennissimOS/platform_vendor_qcom-opensource_wlan_utils_sigma-dut | 8ffe675635b8b9882cf97a1abbaf7b1619148012 | [
"Unlicense"
] | null | null | null | /*
* Sigma Control API DUT (NAN functionality)
* Copyright (c) 2014-2017, Qualcomm Atheros, Inc.
* Copyright (c) 2018, The Linux Foundation
* All Rights Reserved.
* Licensed under the Clear BSD license. See README for more details.
*/
#include "sigma_dut.h"
#include <sys/stat.h>
#include "wpa_ctrl.h"
#include "wpa_helpers.h"
#include "wifi_hal.h"
#include "nan_cert.h"
#if NAN_CERT_VERSION >= 2
pthread_cond_t gCondition;
pthread_mutex_t gMutex;
wifi_handle global_wifi_handle;
wifi_interface_handle global_interface_handle;
static NanSyncStats global_nan_sync_stats;
static int nan_state = 0;
static int event_anyresponse = 0;
static int is_fam = 0;
static uint16_t global_ndp_instance_id = 0;
static uint16_t global_publish_id = 0;
static uint16_t global_subscribe_id = 0;
uint16_t global_header_handle = 0;
uint32_t global_match_handle = 0;
#define DEFAULT_SVC "QNanCluster"
#define MAC_ADDR_ARRAY(a) (a)[0], (a)[1], (a)[2], (a)[3], (a)[4], (a)[5]
#define MAC_ADDR_STR "%02x:%02x:%02x:%02x:%02x:%02x"
#ifndef ETH_ALEN
#define ETH_ALEN 6
#endif
struct sigma_dut *global_dut = NULL;
static char global_nan_mac_addr[ETH_ALEN];
static char global_peer_mac_addr[ETH_ALEN];
static char global_event_resp_buf[1024];
static u8 global_publish_service_name[NAN_MAX_SERVICE_NAME_LEN];
static u32 global_publish_service_name_len = 0;
static u8 global_subscribe_service_name[NAN_MAX_SERVICE_NAME_LEN];
static u32 global_subscribe_service_name_len = 0;
static int nan_further_availability_tx(struct sigma_dut *dut,
struct sigma_conn *conn,
struct sigma_cmd *cmd);
static int nan_further_availability_rx(struct sigma_dut *dut,
struct sigma_conn *conn,
struct sigma_cmd *cmd);
void nan_hex_dump(struct sigma_dut *dut, uint8_t *data, size_t len)
{
char buf[512];
uint16_t index;
uint8_t *ptr;
int pos;
memset(buf, 0, sizeof(buf));
ptr = data;
pos = 0;
for (index = 0; index < len; index++) {
pos += snprintf(&(buf[pos]), sizeof(buf) - pos,
"%02x ", *ptr++);
if (pos > 508)
break;
}
sigma_dut_print(dut, DUT_MSG_INFO, "HEXDUMP len=[%d]", (int) len);
sigma_dut_print(dut, DUT_MSG_INFO, "buf:%s", buf);
}
int nan_parse_hex(unsigned char c)
{
if (c >= '0' && c <= '9')
return c - '0';
if (c >= 'a' && c <= 'f')
return c - 'a' + 10;
if (c >= 'A' && c <= 'F')
return c - 'A' + 10;
return 0;
}
int nan_parse_token(const char *tokenIn, u8 *tokenOut, int *filterLen)
{
int total_len = 0, len = 0;
char *saveptr = NULL;
tokenIn = strtok_r((char *) tokenIn, ":", &saveptr);
while (tokenIn != NULL) {
len = strlen(tokenIn);
if (len == 1 && *tokenIn == '*')
len = 0;
tokenOut[total_len++] = (u8) len;
if (len != 0)
memcpy((u8 *) tokenOut + total_len, tokenIn, len);
total_len += len;
tokenIn = strtok_r(NULL, ":", &saveptr);
}
*filterLen = total_len;
return 0;
}
int nan_parse_mac_address(struct sigma_dut *dut, const char *arg, u8 *addr)
{
if (strlen(arg) != 17) {
sigma_dut_print(dut, DUT_MSG_ERROR, "Invalid mac address %s",
arg);
sigma_dut_print(dut, DUT_MSG_ERROR,
"expected format xx:xx:xx:xx:xx:xx");
return -1;
}
addr[0] = nan_parse_hex(arg[0]) << 4 | nan_parse_hex(arg[1]);
addr[1] = nan_parse_hex(arg[3]) << 4 | nan_parse_hex(arg[4]);
addr[2] = nan_parse_hex(arg[6]) << 4 | nan_parse_hex(arg[7]);
addr[3] = nan_parse_hex(arg[9]) << 4 | nan_parse_hex(arg[10]);
addr[4] = nan_parse_hex(arg[12]) << 4 | nan_parse_hex(arg[13]);
addr[5] = nan_parse_hex(arg[15]) << 4 | nan_parse_hex(arg[16]);
return 0;
}
int nan_parse_mac_address_list(struct sigma_dut *dut, const char *input,
u8 *output, u16 max_addr_allowed)
{
/*
* Reads a list of mac address separated by space. Each MAC address
* should have the format of aa:bb:cc:dd:ee:ff.
*/
char *saveptr;
char *token;
int i = 0;
for (i = 0; i < max_addr_allowed; i++) {
token = strtok_r((i == 0) ? (char *) input : NULL,
" ", &saveptr);
if (token) {
nan_parse_mac_address(dut, token, output);
output += NAN_MAC_ADDR_LEN;
} else
break;
}
sigma_dut_print(dut, DUT_MSG_INFO, "Num MacAddress:%d", i);
return i;
}
int nan_parse_hex_string(struct sigma_dut *dut, const char *input,
u8 *output, int *outputlen)
{
int i = 0;
int j = 0;
for (i = 0; i < (int) strlen(input) && j < *outputlen; i += 2) {
output[j] = nan_parse_hex(input[i]);
if (i + 1 < (int) strlen(input)) {
output[j] = ((output[j] << 4) |
nan_parse_hex(input[i + 1]));
}
j++;
}
*outputlen = j;
sigma_dut_print(dut, DUT_MSG_INFO, "Input:%s inputlen:%d outputlen:%d",
input, (int) strlen(input), (int) *outputlen);
return 0;
}
int wait(struct timespec abstime)
{
struct timeval now;
gettimeofday(&now, NULL);
abstime.tv_sec += now.tv_sec;
if (((abstime.tv_nsec + now.tv_usec * 1000) > 1000 * 1000 * 1000) ||
(abstime.tv_nsec + now.tv_usec * 1000 < 0)) {
abstime.tv_sec += 1;
abstime.tv_nsec += now.tv_usec * 1000;
abstime.tv_nsec -= 1000 * 1000 * 1000;
} else {
abstime.tv_nsec += now.tv_usec * 1000;
}
return pthread_cond_timedwait(&gCondition, &gMutex, &abstime);
}
int nan_cmd_sta_preset_testparameters(struct sigma_dut *dut,
struct sigma_conn *conn,
struct sigma_cmd *cmd)
{
const char *oper_chan = get_param(cmd, "oper_chn");
const char *pmk = get_param(cmd, "PMK");
#if ((NAN_MAJOR_VERSION > 2) || \
(NAN_MAJOR_VERSION == 2 && NAN_MINOR_VERSION >= 1)) && \
NAN_CERT_VERSION >= 5
const char *ndpe = get_param(cmd, "NDPE");
const char *trans_proto = get_param(cmd, "TransProtoType");
const char *ndp_attr = get_param(cmd, "ndpAttr");
#endif
if (oper_chan) {
sigma_dut_print(dut, DUT_MSG_INFO, "Operating Channel: %s",
oper_chan);
dut->sta_channel = atoi(oper_chan);
}
if (pmk) {
int pmk_len;
sigma_dut_print(dut, DUT_MSG_INFO, "%s given string pmk: %s",
__func__, pmk);
memset(dut->nan_pmk, 0, NAN_PMK_INFO_LEN);
dut->nan_pmk_len = 0;
pmk_len = NAN_PMK_INFO_LEN;
nan_parse_hex_string(dut, &pmk[2], &dut->nan_pmk[0], &pmk_len);
dut->nan_pmk_len = pmk_len;
sigma_dut_print(dut, DUT_MSG_INFO, "%s: pmk len = %d",
__func__, dut->nan_pmk_len);
sigma_dut_print(dut, DUT_MSG_INFO, "%s:hex pmk", __func__);
nan_hex_dump(dut, &dut->nan_pmk[0], dut->nan_pmk_len);
}
#if ((NAN_MAJOR_VERSION > 2) || \
(NAN_MAJOR_VERSION == 2 && NAN_MINOR_VERSION >= 1)) && \
NAN_CERT_VERSION >= 5
if (ndpe) {
NanConfigRequest req;
wifi_error ret;
sigma_dut_print(dut, DUT_MSG_DEBUG, "%s: NDPE: %s",
__func__, ndpe);
memset(&req, 0, sizeof(NanConfigRequest));
dut->ndpe = strcasecmp(ndpe, "Enable") == 0;
req.config_ndpe_attr = 1;
req.use_ndpe_attr = dut->ndpe;
ret = nan_config_request(0, global_interface_handle, &req);
if (ret != WIFI_SUCCESS) {
send_resp(dut, conn, SIGMA_ERROR,
"NAN config request failed");
return 0;
}
}
if (trans_proto) {
sigma_dut_print(dut, DUT_MSG_INFO, "%s: Transport protocol: %s",
__func__, trans_proto);
if (strcasecmp(trans_proto, "TCP") == 0) {
dut->trans_proto = TRANSPORT_PROTO_TYPE_TCP;
} else if (strcasecmp(trans_proto, "UDP") == 0) {
dut->trans_proto = TRANSPORT_PROTO_TYPE_UDP;
} else {
sigma_dut_print(dut, DUT_MSG_ERROR,
"%s: Invalid protocol %s, set to TCP",
__func__, trans_proto);
dut->trans_proto = TRANSPORT_PROTO_TYPE_TCP;
}
}
if (dut->ndpe && ndp_attr) {
NanDebugParams cfg_debug;
int ndp_attr_val;
int ret, size;
sigma_dut_print(dut, DUT_MSG_DEBUG, "%s: NDP Attr: %s",
__func__, ndp_attr);
memset(&cfg_debug, 0, sizeof(NanDebugParams));
cfg_debug.cmd = NAN_TEST_MODE_CMD_ENABLE_NDP;
if (strcasecmp(ndp_attr, "Absent") == 0)
ndp_attr_val = NAN_NDP_ATTR_ABSENT;
else
ndp_attr_val = NAN_NDP_ATTR_PRESENT;
memcpy(cfg_debug.debug_cmd_data, &ndp_attr_val, sizeof(int));
size = sizeof(u32) + sizeof(int);
ret = nan_debug_command_config(0, global_interface_handle,
cfg_debug, size);
if (ret != WIFI_SUCCESS) {
send_resp(dut, conn, SIGMA_ERROR,
"NAN config ndpAttr failed");
return 0;
}
}
#endif
send_resp(dut, conn, SIGMA_COMPLETE, NULL);
return 0;
}
void nan_print_further_availability_chan(struct sigma_dut *dut,
u8 num_chans,
NanFurtherAvailabilityChannel *fachan)
{
int idx;
sigma_dut_print(dut, DUT_MSG_INFO,
"********Printing FurtherAvailabilityChan Info******");
sigma_dut_print(dut, DUT_MSG_INFO, "Numchans:%d", num_chans);
for (idx = 0; idx < num_chans; idx++) {
sigma_dut_print(dut, DUT_MSG_INFO,
"[%d]: NanAvailDuration:%d class_val:%02x channel:%d",
idx, fachan->entry_control,
fachan->class_val, fachan->channel);
sigma_dut_print(dut, DUT_MSG_INFO,
"[%d]: mapid:%d Availability bitmap:%08x",
idx, fachan->mapid,
fachan->avail_interval_bitmap);
}
sigma_dut_print(dut, DUT_MSG_INFO,
"*********************Done**********************");
}
int sigma_nan_enable(struct sigma_dut *dut, struct sigma_conn *conn,
struct sigma_cmd *cmd)
{
const char *master_pref = get_param(cmd, "MasterPref");
const char *rand_fac = get_param(cmd, "RandFactor");
const char *hop_count = get_param(cmd, "HopCount");
const char *sdftx_band = get_param(cmd, "SDFTxBand");
const char *oper_chan = get_param(cmd, "oper_chn");
const char *further_avail_ind = get_param(cmd, "FurtherAvailInd");
const char *band = get_param(cmd, "Band");
const char *only_5g = get_param(cmd, "5GOnly");
const char *nan_availability = get_param(cmd, "NANAvailability");
#if ((NAN_MAJOR_VERSION > 2) || \
(NAN_MAJOR_VERSION == 2 && NAN_MINOR_VERSION >= 1)) && \
NAN_CERT_VERSION >= 5
const char *ndpe = get_param(cmd, "NDPE");
#endif
struct timespec abstime;
NanEnableRequest req;
memset(&req, 0, sizeof(NanEnableRequest));
req.cluster_low = 0;
req.cluster_high = 0xFFFF;
req.master_pref = 100;
/* This is a debug hack to beacon in channel 11 */
if (oper_chan) {
req.config_2dot4g_support = 1;
req.support_2dot4g_val = 111;
}
if (master_pref) {
int master_pref_val = strtoul(master_pref, NULL, 0);
req.master_pref = master_pref_val;
}
if (rand_fac) {
int rand_fac_val = strtoul(rand_fac, NULL, 0);
req.config_random_factor_force = 1;
req.random_factor_force_val = rand_fac_val;
}
if (hop_count) {
int hop_count_val = strtoul(hop_count, NULL, 0);
req.config_hop_count_force = 1;
req.hop_count_force_val = hop_count_val;
}
if (sdftx_band) {
if (strcasecmp(sdftx_band, "5G") == 0) {
req.config_2dot4g_support = 1;
req.support_2dot4g_val = 0;
}
}
#if ((NAN_MAJOR_VERSION > 2) || \
(NAN_MAJOR_VERSION == 2 && NAN_MINOR_VERSION >= 1)) && \
NAN_CERT_VERSION >= 5
if (ndpe) {
if (strcasecmp(ndpe, "Enable") == 0) {
dut->ndpe = 1;
req.config_ndpe_attr = 1;
req.use_ndpe_attr = 1;
} else {
dut->ndpe = 0;
req.config_ndpe_attr = 1;
req.use_ndpe_attr = 0;
}
req.config_disc_mac_addr_randomization = 1;
req.disc_mac_addr_rand_interval_sec = 0;
}
#endif
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: Setting dual band 2.4 GHz and 5 GHz by default",
__func__);
/* Enable 2.4 GHz support */
req.config_2dot4g_support = 1;
req.support_2dot4g_val = 1;
req.config_2dot4g_beacons = 1;
req.beacon_2dot4g_val = 1;
req.config_2dot4g_sdf = 1;
req.sdf_2dot4g_val = 1;
/* Enable 5 GHz support */
req.config_support_5g = 1;
req.support_5g_val = 1;
req.config_5g_beacons = 1;
req.beacon_5g_val = 1;
req.config_5g_sdf = 1;
req.sdf_5g_val = 1;
if (band) {
if (strcasecmp(band, "24G") == 0) {
sigma_dut_print(dut, DUT_MSG_INFO,
"Band 2.4 GHz selected, disable 5 GHz");
/* Disable 5G support */
req.config_support_5g = 1;
req.support_5g_val = 0;
req.config_5g_beacons = 1;
req.beacon_5g_val = 0;
req.config_5g_sdf = 1;
req.sdf_5g_val = 0;
}
}
if (further_avail_ind) {
sigma_dut_print(dut, DUT_MSG_INFO, "FAM Test Enabled");
if (strcasecmp(further_avail_ind, "tx") == 0) {
is_fam = 1;
nan_further_availability_tx(dut, conn, cmd);
return 0;
} else if (strcasecmp(further_avail_ind, "rx") == 0) {
nan_further_availability_rx(dut, conn, cmd);
return 0;
}
}
if (only_5g && atoi(only_5g)) {
sigma_dut_print(dut, DUT_MSG_INFO, "5GHz only enabled");
req.config_2dot4g_support = 1;
req.support_2dot4g_val = 1;
req.config_2dot4g_beacons = 1;
req.beacon_2dot4g_val = 0;
req.config_2dot4g_sdf = 1;
req.sdf_2dot4g_val = 1;
}
nan_enable_request(0, global_interface_handle, &req);
if (nan_availability) {
int cmd_len, size;
NanDebugParams cfg_debug;
sigma_dut_print(dut, DUT_MSG_INFO,
"%s given string nan_availability: %s",
__func__, nan_availability);
memset(&cfg_debug, 0, sizeof(NanDebugParams));
cfg_debug.cmd = NAN_TEST_MODE_CMD_NAN_AVAILABILITY;
size = NAN_MAX_DEBUG_MESSAGE_DATA_LEN;
nan_parse_hex_string(dut, &nan_availability[2],
&cfg_debug.debug_cmd_data[0], &size);
sigma_dut_print(dut, DUT_MSG_INFO, "%s:hex nan_availability",
__func__);
nan_hex_dump(dut, &cfg_debug.debug_cmd_data[0], size);
cmd_len = size + sizeof(u32);
nan_debug_command_config(0, global_interface_handle,
cfg_debug, cmd_len);
}
/* To ensure sta_get_events to get the events
* only after joining the NAN cluster. */
abstime.tv_sec = 30;
abstime.tv_nsec = 0;
wait(abstime);
return 0;
}
int sigma_nan_disable(struct sigma_dut *dut, struct sigma_conn *conn,
struct sigma_cmd *cmd)
{
struct timespec abstime;
nan_disable_request(0, global_interface_handle);
abstime.tv_sec = 4;
abstime.tv_nsec = 0;
wait(abstime);
return 0;
}
int sigma_nan_config_enable(struct sigma_dut *dut, struct sigma_conn *conn,
struct sigma_cmd *cmd)
{
const char *master_pref = get_param(cmd, "MasterPref");
const char *rand_fac = get_param(cmd, "RandFactor");
const char *hop_count = get_param(cmd, "HopCount");
wifi_error ret;
struct timespec abstime;
NanConfigRequest req;
memset(&req, 0, sizeof(NanConfigRequest));
req.config_rssi_proximity = 1;
req.rssi_proximity = 70;
if (master_pref) {
int master_pref_val = strtoul(master_pref, NULL, 0);
req.config_master_pref = 1;
req.master_pref = master_pref_val;
}
if (rand_fac) {
int rand_fac_val = strtoul(rand_fac, NULL, 0);
req.config_random_factor_force = 1;
req.random_factor_force_val = rand_fac_val;
}
if (hop_count) {
int hop_count_val = strtoul(hop_count, NULL, 0);
req.config_hop_count_force = 1;
req.hop_count_force_val = hop_count_val;
}
ret = nan_config_request(0, global_interface_handle, &req);
if (ret != WIFI_SUCCESS)
send_resp(dut, conn, SIGMA_ERROR, "NAN config request failed");
abstime.tv_sec = 4;
abstime.tv_nsec = 0;
wait(abstime);
return 0;
}
static int sigma_nan_subscribe_request(struct sigma_dut *dut,
struct sigma_conn *conn,
struct sigma_cmd *cmd)
{
const char *subscribe_type = get_param(cmd, "SubscribeType");
const char *service_name = get_param(cmd, "ServiceName");
const char *disc_range = get_param(cmd, "DiscoveryRange");
const char *rx_match_filter = get_param(cmd, "rxMatchFilter");
const char *tx_match_filter = get_param(cmd, "txMatchFilter");
const char *sdftx_dw = get_param(cmd, "SDFTxDW");
const char *discrange_ltd = get_param(cmd, "DiscRangeLtd");
const char *include_bit = get_param(cmd, "IncludeBit");
const char *mac = get_param(cmd, "MAC");
const char *srf_type = get_param(cmd, "SRFType");
#if NAN_CERT_VERSION >= 3
const char *awake_dw_interval = get_param(cmd, "awakeDWint");
#endif
NanSubscribeRequest req;
NanConfigRequest config_req;
int filter_len_rx = 0, filter_len_tx = 0;
u8 input_rx[NAN_MAX_MATCH_FILTER_LEN];
u8 input_tx[NAN_MAX_MATCH_FILTER_LEN];
wifi_error ret;
memset(&req, 0, sizeof(NanSubscribeRequest));
memset(&config_req, 0, sizeof(NanConfigRequest));
req.ttl = 0;
req.period = 1;
req.subscribe_type = 1;
req.serviceResponseFilter = 1; /* MAC */
req.serviceResponseInclude = 0;
req.ssiRequiredForMatchIndication = 0;
req.subscribe_match_indicator = NAN_MATCH_ALG_MATCH_CONTINUOUS;
req.subscribe_count = 0;
if (global_subscribe_service_name_len &&
service_name &&
strcasecmp((char *) global_subscribe_service_name,
service_name) == 0 &&
global_subscribe_id) {
req.subscribe_id = global_subscribe_id;
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: updating subscribe_id = %d in subscribe request",
__func__, req.subscribe_id);
}
if (subscribe_type) {
if (strcasecmp(subscribe_type, "Active") == 0) {
req.subscribe_type = 1;
} else if (strcasecmp(subscribe_type, "Passive") == 0) {
req.subscribe_type = 0;
} else if (strcasecmp(subscribe_type, "Cancel") == 0) {
NanSubscribeCancelRequest req;
memset(&req, 0, sizeof(NanSubscribeCancelRequest));
ret = nan_subscribe_cancel_request(
0, global_interface_handle, &req);
if (ret != WIFI_SUCCESS) {
send_resp(dut, conn, SIGMA_ERROR,
"NAN subscribe cancel request failed");
}
return 0;
}
}
if (disc_range)
req.rssi_threshold_flag = atoi(disc_range);
if (sdftx_dw)
req.subscribe_count = atoi(sdftx_dw);
/* Check this once again if config can be called here (TBD) */
if (discrange_ltd)
req.rssi_threshold_flag = atoi(discrange_ltd);
if (include_bit) {
int include_bit_val = atoi(include_bit);
req.serviceResponseInclude = include_bit_val;
sigma_dut_print(dut, DUT_MSG_INFO, "Includebit set %d",
req.serviceResponseInclude);
}
if (srf_type) {
int srf_type_val = atoi(srf_type);
if (srf_type_val == 1)
req.serviceResponseFilter = 0; /* Bloom */
else
req.serviceResponseFilter = 1; /* MAC */
req.useServiceResponseFilter = 1;
sigma_dut_print(dut, DUT_MSG_INFO, "srfFilter %d",
req.serviceResponseFilter);
}
if (mac) {
sigma_dut_print(dut, DUT_MSG_INFO, "MAC_ADDR List %s", mac);
req.num_intf_addr_present = nan_parse_mac_address_list(
dut, mac, &req.intf_addr[0][0],
NAN_MAX_SUBSCRIBE_MAX_ADDRESS);
}
memset(input_rx, 0, sizeof(input_rx));
memset(input_tx, 0, sizeof(input_tx));
if (rx_match_filter) {
nan_parse_token(rx_match_filter, input_rx, &filter_len_rx);
sigma_dut_print(dut, DUT_MSG_INFO, "RxFilterLen %d",
filter_len_rx);
}
if (tx_match_filter) {
nan_parse_token(tx_match_filter, input_tx, &filter_len_tx);
sigma_dut_print(dut, DUT_MSG_INFO, "TxFilterLen %d",
filter_len_tx);
}
if (tx_match_filter) {
req.tx_match_filter_len = filter_len_tx;
memcpy(req.tx_match_filter, input_tx, filter_len_tx);
nan_hex_dump(dut, req.tx_match_filter, filter_len_tx);
}
if (rx_match_filter) {
req.rx_match_filter_len = filter_len_rx;
memcpy(req.rx_match_filter, input_rx, filter_len_rx);
nan_hex_dump(dut, req.rx_match_filter, filter_len_rx);
}
if (service_name) {
strlcpy((char *) req.service_name, service_name,
strlen(service_name) + 1);
req.service_name_len = strlen(service_name);
strlcpy((char *) global_subscribe_service_name, service_name,
sizeof(global_subscribe_service_name));
global_subscribe_service_name_len =
strlen((char *) global_subscribe_service_name);
}
#if NAN_CERT_VERSION >= 3
if (awake_dw_interval) {
int input_dw_interval_val = atoi(awake_dw_interval);
int awake_dw_int = 0;
if (input_dw_interval_val > NAN_MAX_ALLOWED_DW_AWAKE_INTERVAL) {
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: input active dw interval = %d overwritting dw interval to Max allowed dw interval 16",
__func__, input_dw_interval_val);
input_dw_interval_val =
NAN_MAX_ALLOWED_DW_AWAKE_INTERVAL;
}
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: input active DW interval = %d",
__func__, input_dw_interval_val);
/*
* Indicates the interval for Sync beacons and SDF's in 2.4 GHz
* or 5 GHz band. Valid values of DW Interval are: 1, 2, 3, 4,
* and 5; 0 is reserved. The SDF includes in OTA when enabled.
* The publish/subscribe period values don't override the device
* level configurations.
* input_dw_interval_val is provided by the user are in the
* format 2^n-1 = 1/2/4/8/16. Internal implementation expects n
* to be passed to indicate the awake_dw_interval.
*/
if (input_dw_interval_val == 1 ||
input_dw_interval_val % 2 == 0) {
while (input_dw_interval_val > 0) {
input_dw_interval_val >>= 1;
awake_dw_int++;
}
}
sigma_dut_print(dut, DUT_MSG_INFO,
"%s:converted active DW interval = %d",
__func__, awake_dw_int);
config_req.config_dw.config_2dot4g_dw_band = 1;
config_req.config_dw.dw_2dot4g_interval_val = awake_dw_int;
config_req.config_dw.config_5g_dw_band = 1;
config_req.config_dw.dw_5g_interval_val = awake_dw_int;
ret = nan_config_request(0, global_interface_handle,
&config_req);
if (ret != WIFI_SUCCESS) {
sigma_dut_print(dut, DUT_MSG_ERROR,
"%s:NAN config request failed",
__func__);
return -2;
}
}
#endif
ret = nan_subscribe_request(0, global_interface_handle, &req);
if (ret != WIFI_SUCCESS) {
send_resp(dut, conn, SIGMA_ERROR,
"NAN subscribe request failed");
}
return 0;
}
static int sigma_ndp_configure_band(struct sigma_dut *dut,
struct sigma_conn *conn,
struct sigma_cmd *cmd,
NdpSupportedBand band_config_val)
{
wifi_error ret;
NanDebugParams cfg_debug;
int size;
memset(&cfg_debug, 0, sizeof(NanDebugParams));
cfg_debug.cmd = NAN_TEST_MODE_CMD_NAN_SUPPORTED_BANDS;
memcpy(cfg_debug.debug_cmd_data, &band_config_val, sizeof(int));
sigma_dut_print(dut, DUT_MSG_INFO, "%s:setting debug cmd=0x%x",
__func__, cfg_debug.cmd);
size = sizeof(u32) + sizeof(int);
ret = nan_debug_command_config(0, global_interface_handle, cfg_debug,
size);
if (ret != WIFI_SUCCESS)
send_resp(dut, conn, SIGMA_ERROR, "Nan config request failed");
return 0;
}
static int sigma_nan_data_request(struct sigma_dut *dut,
struct sigma_conn *conn,
struct sigma_cmd *cmd)
{
const char *ndp_security = get_param(cmd, "DataPathSecurity");
const char *ndp_resp_mac = get_param(cmd, "RespNanMac");
const char *include_immutable = get_param(cmd, "includeimmutable");
const char *avoid_channel = get_param(cmd, "avoidchannel");
const char *invalid_nan_schedule = get_param(cmd, "InvalidNANSchedule");
const char *map_order = get_param(cmd, "maporder");
#if NAN_CERT_VERSION >= 3
const char *qos_config = get_param(cmd, "QoS");
#endif
#if ((NAN_MAJOR_VERSION > 2) || \
(NAN_MAJOR_VERSION == 2 && NAN_MINOR_VERSION >= 1)) && \
NAN_CERT_VERSION >= 5
const char *ndpe_enable = get_param(cmd, "Ndpe");
const char *ndpe_attr = get_param(cmd, "ndpeAttr");
const char *ndp_attr = get_param(cmd, "ndpAttr");
const char *tlv_list = get_param(cmd, "TLVList");
#endif
wifi_error ret;
NanDataPathInitiatorRequest init_req;
NanDebugParams cfg_debug;
int size;
memset(&init_req, 0, sizeof(NanDataPathInitiatorRequest));
if (ndp_security) {
if (strcasecmp(ndp_security, "open") == 0)
init_req.ndp_cfg.security_cfg =
NAN_DP_CONFIG_NO_SECURITY;
else if (strcasecmp(ndp_security, "secure") == 0)
init_req.ndp_cfg.security_cfg = NAN_DP_CONFIG_SECURITY;
}
if (include_immutable) {
int include_immutable_val = 0;
memset(&cfg_debug, 0, sizeof(NanDebugParams));
cfg_debug.cmd = NAN_TEST_MODE_CMD_NDP_INCLUDE_IMMUTABLE;
include_immutable_val = atoi(include_immutable);
memcpy(cfg_debug.debug_cmd_data, &include_immutable_val,
sizeof(int));
size = sizeof(u32) + sizeof(int);
nan_debug_command_config(0, global_interface_handle,
cfg_debug, size);
}
if (avoid_channel) {
int avoid_channel_freq = 0;
memset(&cfg_debug, 0, sizeof(NanDebugParams));
avoid_channel_freq = channel_to_freq(dut, atoi(avoid_channel));
cfg_debug.cmd = NAN_TEST_MODE_CMD_NDP_AVOID_CHANNEL;
memcpy(cfg_debug.debug_cmd_data, &avoid_channel_freq,
sizeof(int));
size = sizeof(u32) + sizeof(int);
nan_debug_command_config(0, global_interface_handle,
cfg_debug, size);
}
if (invalid_nan_schedule) {
int invalid_nan_schedule_type = 0;
memset(&cfg_debug, 0, sizeof(NanDebugParams));
invalid_nan_schedule_type = atoi(invalid_nan_schedule);
cfg_debug.cmd = NAN_TEST_MODE_CMD_NAN_SCHED_TYPE;
memcpy(cfg_debug.debug_cmd_data,
&invalid_nan_schedule_type, sizeof(int));
size = sizeof(u32) + sizeof(int);
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: invalid schedule type: cmd type = %d and command data = %d",
__func__, cfg_debug.cmd,
invalid_nan_schedule_type);
nan_debug_command_config(0, global_interface_handle,
cfg_debug, size);
}
if (map_order) {
int map_order_val = 0;
memset(&cfg_debug, 0, sizeof(NanDebugParams));
cfg_debug.cmd = NAN_TEST_MODE_CMD_NAN_AVAILABILITY_MAP_ORDER;
map_order_val = atoi(map_order);
memcpy(cfg_debug.debug_cmd_data, &map_order_val, sizeof(int));
size = sizeof(u32) + sizeof(int);
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: map order: cmd type = %d and command data = %d",
__func__,
cfg_debug.cmd, map_order_val);
nan_debug_command_config(0, global_interface_handle,
cfg_debug, size);
}
#if NAN_CERT_VERSION >= 3
if (qos_config) {
u32 qos_config_val = 0;
memset(&cfg_debug, 0, sizeof(NanDebugParams));
cfg_debug.cmd = NAN_TEST_MODE_CMD_CONFIG_QOS;
qos_config_val = atoi(qos_config);
memcpy(cfg_debug.debug_cmd_data, &qos_config_val, sizeof(u32));
size = sizeof(u32) + sizeof(u32);
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: qos config: cmd type = %d and command data = %d",
__func__, cfg_debug.cmd, qos_config_val);
nan_debug_command_config(0, global_interface_handle,
cfg_debug, size);
}
#endif
#if ((NAN_MAJOR_VERSION > 2) || \
(NAN_MAJOR_VERSION == 2 && NAN_MINOR_VERSION >= 1)) && \
NAN_CERT_VERSION >= 5
if (ndpe_enable &&
strcasecmp(ndpe_enable, "Enable") == 0)
dut->ndpe = 1;
if (dut->ndpe && ndp_attr) {
NanDebugParams cfg_debug;
int ndp_attr_val;
memset(&cfg_debug, 0, sizeof(NanDebugParams));
cfg_debug.cmd = NAN_TEST_MODE_CMD_ENABLE_NDP;
if (strcasecmp(ndp_attr, "Absent") == 0)
ndp_attr_val = NAN_NDP_ATTR_ABSENT;
else
ndp_attr_val = NAN_NDP_ATTR_PRESENT;
memcpy(cfg_debug.debug_cmd_data, &ndp_attr_val, sizeof(int));
size = sizeof(u32) + sizeof(int);
ret = nan_debug_command_config(0, global_interface_handle,
cfg_debug, size);
if (ret != WIFI_SUCCESS) {
send_resp(dut, conn, SIGMA_ERROR,
"NAN config ndpAttr failed");
return 0;
}
}
if (dut->ndpe && ndpe_attr) {
NanDebugParams cfg_debug;
int ndpe_attr_val;
memset(&cfg_debug, 0, sizeof(NanDebugParams));
cfg_debug.cmd = NAN_TEST_MODE_CMD_DISABLE_NDPE;
if (strcasecmp(ndpe_attr, "Absent") == 0)
ndpe_attr_val = NAN_NDPE_ATTR_ABSENT;
else
ndpe_attr_val = NAN_NDPE_ATTR_PRESENT;
memcpy(cfg_debug.debug_cmd_data, &ndpe_attr_val, sizeof(int));
size = sizeof(u32) + sizeof(int);
ret = nan_debug_command_config(0, global_interface_handle,
cfg_debug, size);
if (ret != WIFI_SUCCESS) {
send_resp(dut, conn, SIGMA_ERROR,
"NAN config ndpeAttr failed");
return 0;
}
}
if (dut->ndpe && dut->device_type == STA_testbed && !tlv_list) {
NanDebugParams cfg_debug;
int implicit_ipv6_val;
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: In test bed mode IPv6 is implicit in data request",
__func__);
memset(&cfg_debug, 0, sizeof(NanDebugParams));
cfg_debug.cmd = NAN_TEST_MODE_CMD_DISABLE_IPV6_LINK_LOCAL;
implicit_ipv6_val = NAN_IPV6_IMPLICIT;
memcpy(cfg_debug.debug_cmd_data, &implicit_ipv6_val,
sizeof(int));
size = sizeof(u32) + sizeof(int);
ret = nan_debug_command_config(0, global_interface_handle,
cfg_debug, size);
if (ret != WIFI_SUCCESS) {
send_resp(dut, conn, SIGMA_ERROR,
"errorCode,NAN config implicit IPv6 failed");
return 0;
}
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: config command for implicit IPv6 sent",
__func__);
}
#endif
/*
* Setting this flag, so that interface for ping6 command
* is set appropriately in traffic_send_ping().
*/
dut->ndp_enable = 1;
/*
* Intended sleep after NAN data interface create
* before the NAN data request
*/
sleep(4);
init_req.requestor_instance_id = global_match_handle;
strlcpy((char *) init_req.ndp_iface, "nan0",
sizeof(init_req.ndp_iface));
if (ndp_resp_mac) {
nan_parse_mac_address(dut, ndp_resp_mac,
init_req.peer_disc_mac_addr);
sigma_dut_print(
dut, DUT_MSG_INFO, "PEER MAC ADDR: " MAC_ADDR_STR,
MAC_ADDR_ARRAY(init_req.peer_disc_mac_addr));
} else {
memcpy(init_req.peer_disc_mac_addr, global_peer_mac_addr,
sizeof(init_req.peer_disc_mac_addr));
}
/* Not requesting the channel and letting FW decide */
if (dut->sta_channel == 0) {
init_req.channel_request_type = NAN_DP_CHANNEL_NOT_REQUESTED;
init_req.channel = 0;
} else {
init_req.channel_request_type = NAN_DP_FORCE_CHANNEL_SETUP;
init_req.channel = channel_to_freq(dut, dut->sta_channel);
}
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: Initiator Request: Channel = %d Channel Request Type = %d",
__func__, init_req.channel,
init_req.channel_request_type);
if (dut->nan_pmk_len == NAN_PMK_INFO_LEN) {
init_req.key_info.key_type = NAN_SECURITY_KEY_INPUT_PMK;
memcpy(&init_req.key_info.body.pmk_info.pmk[0],
&dut->nan_pmk[0], NAN_PMK_INFO_LEN);
init_req.key_info.body.pmk_info.pmk_len = NAN_PMK_INFO_LEN;
sigma_dut_print(dut, DUT_MSG_INFO, "%s: pmk len = %d",
__func__,
init_req.key_info.body.pmk_info.pmk_len);
}
#if ((NAN_MAJOR_VERSION > 2) || \
(NAN_MAJOR_VERSION == 2 && NAN_MINOR_VERSION >= 1)) && \
NAN_CERT_VERSION >= 5
if (dut->ndpe) {
unsigned char nan_mac_addr[ETH_ALEN];
size_t addr_len = 0;
get_hwaddr("nan0", nan_mac_addr);
addr_len = convert_mac_addr_to_ipv6_linklocal(
nan_mac_addr, &init_req.nan_ipv6_intf_addr[0]);
init_req.nan_ipv6_addr_present = 1;
sigma_dut_print(dut, DUT_MSG_DEBUG,
"%s: Initiator Request: IPv6:", __func__);
nan_hex_dump(dut, &init_req.nan_ipv6_intf_addr[0],
NAN_IPV6_ADDR_LEN);
}
#endif
ret = nan_data_request_initiator(0, global_interface_handle, &init_req);
if (ret != WIFI_SUCCESS) {
send_resp(dut, conn, SIGMA_ERROR,
"Unable to initiate nan data request");
return 0;
}
return 0;
}
static int sigma_nan_data_response(struct sigma_dut *dut,
struct sigma_conn *conn,
struct sigma_cmd *cmd)
{
const char *ndl_response = get_param(cmd, "NDLresponse");
const char *m4_response_type = get_param(cmd, "M4ResponseType");
#if ((NAN_MAJOR_VERSION > 2) || \
(NAN_MAJOR_VERSION == 2 && NAN_MINOR_VERSION >= 1)) && \
NAN_CERT_VERSION >= 5
const char *ndpe_attr = get_param(cmd, "ndpeAttr");
const char *ndp_attr = get_param(cmd, "ndpAttr");
#endif
wifi_error ret;
NanDebugParams cfg_debug;
int size;
if (ndl_response) {
int auto_responder_mode_val = 0;
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: ndl_response = (%s) is passed",
__func__, ndl_response);
memset(&cfg_debug, 0, sizeof(NanDebugParams));
cfg_debug.cmd = NAN_TEST_MODE_CMD_AUTO_RESPONDER_MODE;
if (strcasecmp(ndl_response, "Auto") == 0) {
auto_responder_mode_val = NAN_DATA_RESPONDER_MODE_AUTO;
} else if (strcasecmp(ndl_response, "Reject") == 0) {
auto_responder_mode_val =
NAN_DATA_RESPONDER_MODE_REJECT;
} else if (strcasecmp(ndl_response, "Accept") == 0) {
auto_responder_mode_val =
NAN_DATA_RESPONDER_MODE_ACCEPT;
} else if (strcasecmp(ndl_response, "Counter") == 0) {
auto_responder_mode_val =
NAN_DATA_RESPONDER_MODE_COUNTER;
} else {
sigma_dut_print(dut, DUT_MSG_ERROR,
"%s: Invalid ndl_response",
__func__);
return 0;
}
memcpy(cfg_debug.debug_cmd_data, &auto_responder_mode_val,
sizeof(int));
size = sizeof(u32) + sizeof(int);
ret = nan_debug_command_config(0, global_interface_handle,
cfg_debug, size);
if (ret != WIFI_SUCCESS) {
send_resp(dut, conn, SIGMA_ERROR,
"Nan config request failed");
}
}
if (m4_response_type) {
int m4_response_type_val = 0;
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: m4_response_type = (%s) is passed",
__func__, m4_response_type);
memset(&cfg_debug, 0, sizeof(NanDebugParams));
cfg_debug.cmd = NAN_TEST_MODE_CMD_M4_RESPONSE_TYPE;
if (strcasecmp(m4_response_type, "Accept") == 0)
m4_response_type_val = NAN_DATA_PATH_M4_RESPONSE_ACCEPT;
else if (strcasecmp(m4_response_type, "Reject") == 0)
m4_response_type_val = NAN_DATA_PATH_M4_RESPONSE_REJECT;
else if (strcasecmp(m4_response_type, "BadMic") == 0)
m4_response_type_val = NAN_DATA_PATH_M4_RESPONSE_BADMIC;
memcpy(cfg_debug.debug_cmd_data, &m4_response_type_val,
sizeof(int));
size = sizeof(u32) + sizeof(int);
ret = nan_debug_command_config(0, global_interface_handle,
cfg_debug, size);
if (ret != WIFI_SUCCESS) {
send_resp(dut, conn, SIGMA_ERROR,
"Nan config request failed");
}
}
#if ((NAN_MAJOR_VERSION > 2) || \
(NAN_MAJOR_VERSION == 2 && NAN_MINOR_VERSION >= 1)) && \
NAN_CERT_VERSION >= 5
if (dut->ndpe && ndp_attr) {
NanDebugParams cfg_debug;
int ndp_attr_val;
memset(&cfg_debug, 0, sizeof(NanDebugParams));
cfg_debug.cmd = NAN_TEST_MODE_CMD_ENABLE_NDP;
if (strcasecmp(ndp_attr, "Absent") == 0)
ndp_attr_val = NAN_NDP_ATTR_ABSENT;
else
ndp_attr_val = NAN_NDP_ATTR_PRESENT;
memcpy(cfg_debug.debug_cmd_data, &ndp_attr_val, sizeof(int));
size = sizeof(u32) + sizeof(int);
ret = nan_debug_command_config(0, global_interface_handle,
cfg_debug, size);
if (ret != WIFI_SUCCESS) {
send_resp(dut, conn, SIGMA_ERROR,
"NAN config ndpAttr failed");
return 0;
}
}
if (ndpe_attr && dut->ndpe) {
int ndpe_attr_val;
memset(&cfg_debug, 0, sizeof(NanDebugParams));
cfg_debug.cmd = NAN_TEST_MODE_CMD_DISABLE_NDPE;
if (strcasecmp(ndpe_attr, "Absent") == 0)
ndpe_attr_val = NAN_NDPE_ATTR_ABSENT;
else
ndpe_attr_val = NAN_NDPE_ATTR_PRESENT;
memcpy(cfg_debug.debug_cmd_data, &ndpe_attr_val, sizeof(int));
size = sizeof(u32) + sizeof(int);
ret = nan_debug_command_config(0, global_interface_handle,
cfg_debug, size);
if (ret != WIFI_SUCCESS) {
send_resp(dut, conn, SIGMA_ERROR,
"NAN config ndpeAttr failed");
return 0;
}
}
#endif
return 0;
}
static int sigma_nan_data_end(struct sigma_dut *dut, struct sigma_cmd *cmd)
{
const char *nmf_security_config = get_param(cmd, "Security");
NanDataPathEndRequest req;
NanDebugParams cfg_debug;
int size;
memset(&req, 0, sizeof(NanDataPathEndRequest));
memset(&cfg_debug, 0, sizeof(NanDebugParams));
if (nmf_security_config) {
int nmf_security_config_val = 0;
cfg_debug.cmd = NAN_TEST_MODE_CMD_NAN_NMF_CLEAR_CONFIG;
if (strcasecmp(nmf_security_config, "open") == 0)
nmf_security_config_val = NAN_NMF_CLEAR_ENABLE;
else if (strcasecmp(nmf_security_config, "secure") == 0)
nmf_security_config_val = NAN_NMF_CLEAR_DISABLE;
memcpy(cfg_debug.debug_cmd_data,
&nmf_security_config_val, sizeof(int));
size = sizeof(u32) + sizeof(int);
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: nmf_security_config_val -- cmd type = %d and command data = %d",
__func__, cfg_debug.cmd,
nmf_security_config_val);
nan_debug_command_config(0, global_interface_handle,
cfg_debug, size);
}
req.num_ndp_instances = 1;
req.ndp_instance_id[0] = global_ndp_instance_id;
nan_data_end(0, global_interface_handle, &req);
return 0;
}
static int sigma_nan_range_request(struct sigma_dut *dut,
struct sigma_cmd *cmd)
{
const char *dest_mac = get_param(cmd, "destmac");
NanSubscribeRequest req;
memset(&req, 0, sizeof(NanSubscribeRequest));
req.period = 1;
req.subscribe_type = NAN_SUBSCRIBE_TYPE_PASSIVE;
req.serviceResponseFilter = NAN_SRF_ATTR_BLOOM_FILTER;
req.serviceResponseInclude = NAN_SRF_INCLUDE_RESPOND;
req.ssiRequiredForMatchIndication = NAN_SSI_NOT_REQUIRED_IN_MATCH_IND;
req.subscribe_match_indicator = NAN_MATCH_ALG_MATCH_CONTINUOUS;
req.subscribe_count = 0;
strlcpy((char *) req.service_name, DEFAULT_SVC,
NAN_MAX_SERVICE_NAME_LEN);
req.service_name_len = strlen((char *) req.service_name);
req.subscribe_id = global_subscribe_id;
req.sdea_params.ranging_state = 1;
req.sdea_params.range_report = NAN_ENABLE_RANGE_REPORT;
req.range_response_cfg.requestor_instance_id = global_match_handle;
req.range_response_cfg.ranging_response = NAN_RANGE_REQUEST_ACCEPT;
req.ranging_cfg.config_ranging_indications =
NAN_RANGING_INDICATE_CONTINUOUS_MASK;
if (dest_mac) {
nan_parse_mac_address(dut, dest_mac,
req.range_response_cfg.peer_addr);
sigma_dut_print(
dut, DUT_MSG_INFO, "peer mac addr: " MAC_ADDR_STR,
MAC_ADDR_ARRAY(req.range_response_cfg.peer_addr));
}
nan_subscribe_request(0, global_interface_handle, &req);
return 0;
}
static int sigma_nan_cancel_range(struct sigma_dut *dut,
struct sigma_cmd *cmd)
{
const char *dest_mac = get_param(cmd, "destmac");
NanPublishRequest req;
memset(&req, 0, sizeof(NanPublishRequest));
req.ttl = 0;
req.period = 1;
req.publish_match_indicator = 1;
req.publish_type = NAN_PUBLISH_TYPE_UNSOLICITED;
req.tx_type = NAN_TX_TYPE_BROADCAST;
req.publish_count = 0;
strlcpy((char *) req.service_name, DEFAULT_SVC,
NAN_MAX_SERVICE_NAME_LEN);
req.service_name_len = strlen((char *) req.service_name);
req.publish_id = global_publish_id;
req.range_response_cfg.ranging_response = NAN_RANGE_REQUEST_CANCEL;
if (dest_mac) {
nan_parse_mac_address(dut, dest_mac,
req.range_response_cfg.peer_addr);
sigma_dut_print(
dut, DUT_MSG_INFO, "peer mac addr: " MAC_ADDR_STR,
MAC_ADDR_ARRAY(req.range_response_cfg.peer_addr));
}
nan_publish_request(0, global_interface_handle, &req);
return 0;
}
static int sigma_nan_schedule_update(struct sigma_dut *dut,
struct sigma_cmd *cmd)
{
const char *schedule_update_type = get_param(cmd, "type");
const char *channel_availability = get_param(cmd,
"ChannelAvailability");
const char *responder_nmi_mac = get_param(cmd, "ResponderNMI");
NanDebugParams cfg_debug;
int size = 0;
memset(&cfg_debug, 0, sizeof(NanDebugParams));
if (!schedule_update_type)
return 0;
if (strcasecmp(schedule_update_type, "ULWnotify") == 0) {
cfg_debug.cmd = NAN_TEST_MODE_CMD_NAN_SCHED_UPDATE_ULW_NOTIFY;
size = sizeof(u32);
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: Schedule Update cmd type = %d", __func__,
cfg_debug.cmd);
if (channel_availability) {
int channel_availability_val;
channel_availability_val = atoi(channel_availability);
size += sizeof(int);
memcpy(cfg_debug.debug_cmd_data,
&channel_availability_val, sizeof(int));
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: Schedule Update cmd data = %d size = %d",
__func__, channel_availability_val,
size);
}
} else if (strcasecmp(schedule_update_type, "NDLnegotiate") == 0) {
cfg_debug.cmd =
NAN_TEST_MODE_CMD_NAN_SCHED_UPDATE_NDL_NEGOTIATE;
size = sizeof(u32);
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: Schedule Update cmd type = %d", __func__,
cfg_debug.cmd);
if (responder_nmi_mac) {
u8 responder_nmi_mac_addr[NAN_MAC_ADDR_LEN];
nan_parse_mac_address(dut, responder_nmi_mac,
responder_nmi_mac_addr);
size += NAN_MAC_ADDR_LEN;
memcpy(cfg_debug.debug_cmd_data, responder_nmi_mac_addr,
NAN_MAC_ADDR_LEN);
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: RESPONDER NMI MAC: "MAC_ADDR_STR,
__func__,
MAC_ADDR_ARRAY(responder_nmi_mac_addr));
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: Schedule Update: cmd size = %d",
__func__, size);
}
} else if (strcasecmp(schedule_update_type, "NDLnotify") == 0) {
cfg_debug.cmd = NAN_TEST_MODE_CMD_NAN_SCHED_UPDATE_NDL_NOTIFY;
size = sizeof(u32);
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: Schedule Update cmd type = %d", __func__,
cfg_debug.cmd);
}
nan_debug_command_config(0, global_interface_handle, cfg_debug, size);
return 0;
}
int config_post_disc_attr(void)
{
wifi_error ret;
NanConfigRequest configReq;
memset(&configReq, 0, sizeof(NanConfigRequest));
/* Configure Post disc attr */
/* Make these defines and use correct enum */
configReq.num_config_discovery_attr = 1;
configReq.discovery_attr_val[0].type = 4; /* Further Nan discovery */
configReq.discovery_attr_val[0].role = 0;
configReq.discovery_attr_val[0].transmit_freq = 1;
configReq.discovery_attr_val[0].duration = 0;
configReq.discovery_attr_val[0].avail_interval_bitmap = 0x00000008;
ret = nan_config_request(0, global_interface_handle, &configReq);
if (ret != WIFI_SUCCESS) {
sigma_dut_print(global_dut, DUT_MSG_INFO,
"NAN config request failed while configuring post discovery attribute");
}
return 0;
}
int sigma_nan_publish_request(struct sigma_dut *dut, struct sigma_conn *conn,
struct sigma_cmd *cmd)
{
const char *publish_type = get_param(cmd, "PublishType");
const char *service_name = get_param(cmd, "ServiceName");
const char *disc_range = get_param(cmd, "DiscoveryRange");
const char *rx_match_filter = get_param(cmd, "rxMatchFilter");
const char *tx_match_filter = get_param(cmd, "txMatchFilter");
const char *sdftx_dw = get_param(cmd, "SDFTxDW");
const char *discrange_ltd = get_param(cmd, "DiscRangeLtd");
const char *ndp_enable = get_param(cmd, "DataPathFlag");
const char *ndp_type = get_param(cmd, "DataPathType");
const char *data_path_security = get_param(cmd, "datapathsecurity");
const char *range_required = get_param(cmd, "rangerequired");
#if NAN_CERT_VERSION >= 3
const char *awake_dw_interval = get_param(cmd, "awakeDWint");
const char *qos_config = get_param(cmd, "QoS");
#endif
const char *ndpe = get_param(cmd, "NDPE");
const char *trans_proto = get_param(cmd, "TransProtoType");
#if ((NAN_MAJOR_VERSION > 2) || \
(NAN_MAJOR_VERSION == 2 && NAN_MINOR_VERSION >= 1)) && \
NAN_CERT_VERSION >= 5
const char *ndp_attr = get_param(cmd, "ndpAttr");
#endif
NanPublishRequest req;
NanConfigRequest config_req;
int filter_len_rx = 0, filter_len_tx = 0;
u8 input_rx[NAN_MAX_MATCH_FILTER_LEN];
u8 input_tx[NAN_MAX_MATCH_FILTER_LEN];
wifi_error ret;
memset(&req, 0, sizeof(NanPublishRequest));
memset(&config_req, 0, sizeof(NanConfigRequest));
req.ttl = 0;
req.period = 1;
req.publish_match_indicator = 1;
req.publish_type = NAN_PUBLISH_TYPE_UNSOLICITED;
req.tx_type = NAN_TX_TYPE_BROADCAST;
req.publish_count = 0;
req.service_responder_policy = NAN_SERVICE_ACCEPT_POLICY_ALL;
if (global_publish_service_name_len &&
service_name &&
strcasecmp((char *) global_publish_service_name,
service_name) == 0 &&
global_publish_id) {
req.publish_id = global_publish_id;
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: updating publish_id = %d in publish request",
__func__, req.publish_id);
}
if (service_name) {
strlcpy((char *) req.service_name, service_name,
sizeof(req.service_name));
req.service_name_len = strlen((char *) req.service_name);
strlcpy((char *) global_publish_service_name, service_name,
sizeof(global_publish_service_name));
global_publish_service_name_len =
strlen((char *) global_publish_service_name);
}
if (publish_type) {
if (strcasecmp(publish_type, "Solicited") == 0) {
req.publish_type = NAN_PUBLISH_TYPE_SOLICITED;
} else if (strcasecmp(publish_type, "Unsolicited") == 0) {
req.publish_type = NAN_PUBLISH_TYPE_UNSOLICITED;
} else if (strcasecmp(publish_type, "Cancel") == 0) {
NanPublishCancelRequest req;
memset(&req, 0, sizeof(NanPublishCancelRequest));
ret = nan_publish_cancel_request(
0, global_interface_handle, &req);
if (ret != WIFI_SUCCESS) {
send_resp(dut, conn, SIGMA_ERROR,
"Unable to cancel nan publish request");
}
return 0;
}
}
if (disc_range)
req.rssi_threshold_flag = atoi(disc_range);
if (sdftx_dw)
req.publish_count = atoi(sdftx_dw);
if (discrange_ltd)
req.rssi_threshold_flag = atoi(discrange_ltd);
memset(input_rx, 0, sizeof(input_rx));
memset(input_tx, 0, sizeof(input_tx));
if (rx_match_filter) {
nan_parse_token(rx_match_filter, input_rx, &filter_len_rx);
sigma_dut_print(dut, DUT_MSG_INFO, "RxFilterLen %d",
filter_len_rx);
}
if (tx_match_filter) {
nan_parse_token(tx_match_filter, input_tx, &filter_len_tx);
sigma_dut_print(dut, DUT_MSG_INFO, "TxFilterLen %d",
filter_len_tx);
}
if (is_fam == 1) {
config_post_disc_attr();
/*
* 8-bit bitmap which allows the Host to associate this publish
* with a particular Post-NAN Connectivity attribute which has
* been sent down in a NanConfigureRequest/NanEnableRequest
* message. If the DE fails to find a configured Post-NAN
* connectivity attributes referenced by the bitmap, the DE will
* return an error code to the Host. If the Publish is
* configured to use a Post-NAN Connectivity attribute and the
* Host does not refresh the Post-NAN Connectivity attribute the
* Publish will be canceled and the Host will be sent a
* PublishTerminatedIndication message.
*/
req.connmap = 0x10;
}
if (tx_match_filter) {
req.tx_match_filter_len = filter_len_tx;
memcpy(req.tx_match_filter, input_tx, filter_len_tx);
nan_hex_dump(dut, req.tx_match_filter, filter_len_tx);
}
if (rx_match_filter) {
req.rx_match_filter_len = filter_len_rx;
memcpy(req.rx_match_filter, input_rx, filter_len_rx);
nan_hex_dump(dut, req.rx_match_filter, filter_len_rx);
}
if (service_name) {
strlcpy((char *) req.service_name, service_name,
strlen(service_name) + 1);
req.service_name_len = strlen(service_name);
}
if (ndp_enable) {
if (strcasecmp(ndp_enable, "enable") == 0)
req.sdea_params.config_nan_data_path = 1;
else
req.sdea_params.config_nan_data_path = 0;
if (ndp_type)
req.sdea_params.ndp_type = atoi(ndp_type);
if (data_path_security) {
if (strcasecmp(data_path_security, "secure") == 0) {
req.sdea_params.security_cfg =
NAN_DP_CONFIG_SECURITY;
} else if (strcasecmp(data_path_security, "open") ==
0) {
req.sdea_params.security_cfg =
NAN_DP_CONFIG_NO_SECURITY;
}
}
if (dut->nan_pmk_len == NAN_PMK_INFO_LEN) {
req.key_info.key_type = NAN_SECURITY_KEY_INPUT_PMK;
memcpy(&req.key_info.body.pmk_info.pmk[0],
&dut->nan_pmk[0], NAN_PMK_INFO_LEN);
req.key_info.body.pmk_info.pmk_len = NAN_PMK_INFO_LEN;
sigma_dut_print(dut, DUT_MSG_INFO, "%s: pmk len = %d",
__func__, req.key_info.body.pmk_info.pmk_len);
}
}
if (range_required && strcasecmp(range_required, "enable") == 0) {
req.sdea_params.ranging_state = NAN_RANGING_ENABLE;
req.sdea_params.range_report = NAN_ENABLE_RANGE_REPORT;
}
#if NAN_CERT_VERSION >= 3
if (awake_dw_interval) {
int input_dw_interval_val = atoi(awake_dw_interval);
int awake_dw_int = 0;
if (input_dw_interval_val > NAN_MAX_ALLOWED_DW_AWAKE_INTERVAL) {
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: input active dw interval = %d overwritting dw interval to Max allowed dw interval 16",
__func__, input_dw_interval_val);
input_dw_interval_val =
NAN_MAX_ALLOWED_DW_AWAKE_INTERVAL;
}
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: input active DW interval = %d",
__func__, input_dw_interval_val);
/*
* Indicates the interval for Sync beacons and SDF's in 2.4 GHz
* or 5 GHz band. Valid values of DW Interval are: 1, 2, 3, 4,
* and 5; 0 is reserved. The SDF includes in OTA when enabled.
* The publish/subscribe period. values don't override the
* device level configurations.
* input_dw_interval_val is provided by the user are in the
* format 2^n-1 = 1/2/4/8/16. Internal implementation expects n
* to be passed to indicate the awake_dw_interval.
*/
if (input_dw_interval_val == 1 ||
input_dw_interval_val % 2 == 0) {
while (input_dw_interval_val > 0) {
input_dw_interval_val >>= 1;
awake_dw_int++;
}
}
sigma_dut_print(dut, DUT_MSG_INFO,
"%s:converted active DW interval = %d",
__func__, awake_dw_int);
config_req.config_dw.config_2dot4g_dw_band = 1;
config_req.config_dw.dw_2dot4g_interval_val = awake_dw_int;
config_req.config_dw.config_5g_dw_band = 1;
config_req.config_dw.dw_5g_interval_val = awake_dw_int;
ret = nan_config_request(0, global_interface_handle,
&config_req);
if (ret != WIFI_SUCCESS) {
sigma_dut_print(dut, DUT_MSG_ERROR,
"%s:NAN config request failed",
__func__);
return -2;
}
}
if (qos_config)
req.sdea_params.qos_cfg = (NanQosCfgStatus) atoi(qos_config);
#endif
if (ndpe &&
strcasecmp(ndpe, "Enable") == 0)
dut->ndpe = 1;
if (trans_proto) {
if (strcasecmp(trans_proto, "TCP") == 0) {
dut->trans_proto = TRANSPORT_PROTO_TYPE_TCP;
} else if (strcasecmp(trans_proto, "UDP") == 0) {
dut->trans_proto = TRANSPORT_PROTO_TYPE_UDP;
} else {
sigma_dut_print(dut, DUT_MSG_ERROR,
"%s: Invalid protocol %s",
__func__, trans_proto);
return -1;
}
}
#if ((NAN_MAJOR_VERSION > 2) || \
(NAN_MAJOR_VERSION == 2 && NAN_MINOR_VERSION >= 1)) && \
NAN_CERT_VERSION >= 5
if (dut->ndpe && ndp_attr) {
NanDebugParams cfg_debug;
int ndp_attr_val, size;
memset(&cfg_debug, 0, sizeof(NanDebugParams));
cfg_debug.cmd = NAN_TEST_MODE_CMD_ENABLE_NDP;
if (strcasecmp(ndp_attr, "Absent") == 0)
ndp_attr_val = NAN_NDP_ATTR_ABSENT;
else
ndp_attr_val = NAN_NDP_ATTR_PRESENT;
memcpy(cfg_debug.debug_cmd_data, &ndp_attr_val, sizeof(int));
size = sizeof(u32) + sizeof(int);
ret = nan_debug_command_config(0, global_interface_handle,
cfg_debug, size);
if (ret != WIFI_SUCCESS) {
send_resp(dut, conn, SIGMA_ERROR,
"NAN config ndpAttr failed");
return 0;
}
}
if (dut->ndpe) {
unsigned char nan_mac_addr[ETH_ALEN];
size_t addr_len = 0;
NanDebugParams cfg_debug;
NdpIpTransParams ndp_ip_trans_param;
get_hwaddr("nan0", nan_mac_addr);
addr_len = convert_mac_addr_to_ipv6_linklocal(
nan_mac_addr, ndp_ip_trans_param.ipv6_intf_addr);
ndp_ip_trans_param.ipv6_addr_present = 1;
ndp_ip_trans_param.trans_port_present = 1;
ndp_ip_trans_param.transport_port = dut->trans_port;
ndp_ip_trans_param.trans_proto_present = 1;
ndp_ip_trans_param.transport_protocol = dut->trans_proto;
cfg_debug.cmd = NAN_TEST_MODE_CMD_TRANSPORT_IP_PARAM;
memcpy(cfg_debug.debug_cmd_data, &ndp_ip_trans_param,
sizeof(NdpIpTransParams));
nan_debug_command_config(0, global_interface_handle, cfg_debug,
sizeof(u32) +
sizeof(NdpIpTransParams));
}
#endif
ret = nan_publish_request(0, global_interface_handle, &req);
if (ret != WIFI_SUCCESS)
send_resp(dut, conn, SIGMA_ERROR, "Unable to publish");
if (ndp_enable)
dut->ndp_enable = 1;
return 0;
}
static int nan_further_availability_rx(struct sigma_dut *dut,
struct sigma_conn *conn,
struct sigma_cmd *cmd)
{
const char *master_pref = get_param(cmd, "MasterPref");
const char *rand_fac = get_param(cmd, "RandFactor");
const char *hop_count = get_param(cmd, "HopCount");
wifi_error ret;
struct timespec abstime;
NanEnableRequest req;
memset(&req, 0, sizeof(NanEnableRequest));
req.cluster_low = 0;
req.cluster_high = 0xFFFF;
req.master_pref = 30;
if (master_pref)
req.master_pref = strtoul(master_pref, NULL, 0);
if (rand_fac) {
int rand_fac_val = strtoul(rand_fac, NULL, 0);
req.config_random_factor_force = 1;
req.random_factor_force_val = rand_fac_val;
}
if (hop_count) {
int hop_count_val = strtoul(hop_count, NULL, 0);
req.config_hop_count_force = 1;
req.hop_count_force_val = hop_count_val;
}
ret = nan_enable_request(0, global_interface_handle, &req);
if (ret != WIFI_SUCCESS) {
send_resp(dut, conn, SIGMA_ERROR, "Unable to enable nan");
return 0;
}
abstime.tv_sec = 4;
abstime.tv_nsec = 0;
wait(abstime);
return 0;
}
static int nan_further_availability_tx(struct sigma_dut *dut,
struct sigma_conn *conn,
struct sigma_cmd *cmd)
{
const char *master_pref = get_param(cmd, "MasterPref");
const char *rand_fac = get_param(cmd, "RandFactor");
const char *hop_count = get_param(cmd, "HopCount");
wifi_error ret;
NanEnableRequest req;
NanConfigRequest configReq;
memset(&req, 0, sizeof(NanEnableRequest));
req.cluster_low = 0;
req.cluster_high = 0xFFFF;
req.master_pref = 30;
if (master_pref)
req.master_pref = strtoul(master_pref, NULL, 0);
if (rand_fac) {
int rand_fac_val = strtoul(rand_fac, NULL, 0);
req.config_random_factor_force = 1;
req.random_factor_force_val = rand_fac_val;
}
if (hop_count) {
int hop_count_val = strtoul(hop_count, NULL, 0);
req.config_hop_count_force = 1;
req.hop_count_force_val = hop_count_val;
}
ret = nan_enable_request(0, global_interface_handle, &req);
if (ret != WIFI_SUCCESS) {
send_resp(dut, conn, SIGMA_ERROR, "Unable to enable nan");
return 0;
}
/* Start the config of fam */
memset(&configReq, 0, sizeof(NanConfigRequest));
configReq.config_fam = 1;
configReq.fam_val.numchans = 1;
configReq.fam_val.famchan[0].entry_control = 0;
configReq.fam_val.famchan[0].class_val = 81;
configReq.fam_val.famchan[0].channel = 6;
configReq.fam_val.famchan[0].mapid = 0;
configReq.fam_val.famchan[0].avail_interval_bitmap = 0x7ffffffe;
ret = nan_config_request(0, global_interface_handle, &configReq);
if (ret != WIFI_SUCCESS)
send_resp(dut, conn, SIGMA_ERROR, "Nan config request failed");
return 0;
}
int sigma_nan_transmit_followup(struct sigma_dut *dut,
struct sigma_conn *conn,
struct sigma_cmd *cmd)
{
const char *mac = get_param(cmd, "mac");
const char *requestor_id = get_param(cmd, "RemoteInstanceId");
const char *local_id = get_param(cmd, "LocalInstanceId");
const char *service_name = get_param(cmd, "servicename");
wifi_error ret;
NanTransmitFollowupRequest req;
memset(&req, 0, sizeof(NanTransmitFollowupRequest));
req.requestor_instance_id = global_match_handle;
req.addr[0] = 0xFF;
req.addr[1] = 0xFF;
req.addr[2] = 0xFF;
req.addr[3] = 0xFF;
req.addr[4] = 0xFF;
req.addr[5] = 0xFF;
req.priority = NAN_TX_PRIORITY_NORMAL;
req.dw_or_faw = 0;
if (service_name)
req.service_specific_info_len = strlen(service_name);
if (requestor_id) {
/* int requestor_id_val = atoi(requestor_id); */
if (global_match_handle != 0) {
req.requestor_instance_id = global_match_handle;
} else {
u32 requestor_id_val = atoi(requestor_id);
requestor_id_val =
(requestor_id_val << 24) | 0x0000FFFF;
req.requestor_instance_id = requestor_id_val;
}
}
if (local_id) {
/* int local_id_val = atoi(local_id); */
if (global_header_handle != 0)
req.publish_subscribe_id = global_header_handle;
else
req.publish_subscribe_id = atoi(local_id);
}
if (mac == NULL) {
sigma_dut_print(dut, DUT_MSG_ERROR, "Invalid MAC Address");
return -1;
}
nan_parse_mac_address(dut, mac, req.addr);
ret = nan_transmit_followup_request(0, global_interface_handle, &req);
if (ret != WIFI_SUCCESS) {
send_resp(dut, conn, SIGMA_ERROR,
"Unable to complete nan transmit followup");
}
return 0;
}
/* NotifyResponse invoked to notify the status of the Request */
void nan_notify_response(transaction_id id, NanResponseMsg *rsp_data)
{
sigma_dut_print(global_dut, DUT_MSG_INFO,
"%s: status %d response_type %d",
__func__, rsp_data->status, rsp_data->response_type);
if (rsp_data->response_type == NAN_RESPONSE_STATS &&
rsp_data->body.stats_response.stats_type ==
NAN_STATS_ID_DE_TIMING_SYNC) {
NanSyncStats *pSyncStats;
sigma_dut_print(global_dut, DUT_MSG_INFO,
"%s: stats_type %d", __func__,
rsp_data->body.stats_response.stats_type);
pSyncStats = &rsp_data->body.stats_response.data.sync_stats;
memcpy(&global_nan_sync_stats, pSyncStats,
sizeof(NanSyncStats));
pthread_cond_signal(&gCondition);
} else if (rsp_data->response_type == NAN_RESPONSE_PUBLISH) {
sigma_dut_print(global_dut, DUT_MSG_INFO,
"%s: publish_id %d\n",
__func__,
rsp_data->body.publish_response.publish_id);
global_publish_id = rsp_data->body.publish_response.publish_id;
} else if (rsp_data->response_type == NAN_RESPONSE_SUBSCRIBE) {
sigma_dut_print(global_dut, DUT_MSG_INFO,
"%s: subscribe_id %d\n",
__func__,
rsp_data->body.subscribe_response.subscribe_id);
global_subscribe_id =
rsp_data->body.subscribe_response.subscribe_id;
}
}
/* Events Callback */
void nan_event_publish_replied(NanPublishRepliedInd *event)
{
sigma_dut_print(global_dut, DUT_MSG_INFO,
"%s: handle %d " MAC_ADDR_STR " rssi:%d",
__func__, event->requestor_instance_id,
MAC_ADDR_ARRAY(event->addr), event->rssi_value);
event_anyresponse = 1;
snprintf(global_event_resp_buf, sizeof(global_event_resp_buf),
"EventName,Replied,RemoteInstanceID,%d,LocalInstanceID,%d,mac," MAC_ADDR_STR" ",
(event->requestor_instance_id >> 24),
(event->requestor_instance_id & 0xFFFF),
MAC_ADDR_ARRAY(event->addr));
}
/* Events Callback */
void nan_event_publish_terminated(NanPublishTerminatedInd *event)
{
sigma_dut_print(global_dut, DUT_MSG_INFO, "%s: publish_id %d reason %d",
__func__, event->publish_id, event->reason);
}
/* Events Callback */
void nan_event_match(NanMatchInd *event)
{
sigma_dut_print(global_dut, DUT_MSG_INFO,
"%s: Pub/Sub Id %d remote_requestor_id %08x "
MAC_ADDR_STR
" rssi:%d",
__func__,
event->publish_subscribe_id,
event->requestor_instance_id,
MAC_ADDR_ARRAY(event->addr),
event->rssi_value);
event_anyresponse = 1;
global_header_handle = event->publish_subscribe_id;
global_match_handle = event->requestor_instance_id;
memcpy(global_peer_mac_addr, event->addr, sizeof(global_peer_mac_addr));
/* memset(event_resp_buf, 0, sizeof(event_resp_buf)); */
/* global_pub_sub_handle = event->header.handle; */
/* Print the SSI */
sigma_dut_print(global_dut, DUT_MSG_INFO, "Printing SSI:");
nan_hex_dump(global_dut, event->service_specific_info,
event->service_specific_info_len);
snprintf(global_event_resp_buf, sizeof(global_event_resp_buf),
"EventName,DiscoveryResult,RemoteInstanceID,%d,LocalInstanceID,%d,mac,"
MAC_ADDR_STR " ", (event->requestor_instance_id >> 24),
event->publish_subscribe_id, MAC_ADDR_ARRAY(event->addr));
/* Print the match filter */
sigma_dut_print(global_dut, DUT_MSG_INFO, "Printing sdf match filter:");
nan_hex_dump(global_dut, event->sdf_match_filter,
event->sdf_match_filter_len);
/* Print the conn_capability */
sigma_dut_print(global_dut, DUT_MSG_INFO,
"Printing PostConnectivity Capability");
if (event->is_conn_capability_valid) {
sigma_dut_print(global_dut, DUT_MSG_INFO, "Wfd supported:%s",
event->conn_capability.is_wfd_supported ?
"yes" : "no");
sigma_dut_print(global_dut, DUT_MSG_INFO, "Wfds supported:%s",
(event->conn_capability.is_wfds_supported ?
"yes" : "no"));
sigma_dut_print(global_dut, DUT_MSG_INFO, "TDLS supported:%s",
(event->conn_capability.is_tdls_supported ?
"yes" : "no"));
sigma_dut_print(global_dut, DUT_MSG_INFO, "IBSS supported:%s",
(event->conn_capability.is_ibss_supported ?
"yes" : "no"));
sigma_dut_print(global_dut, DUT_MSG_INFO, "Mesh supported:%s",
(event->conn_capability.is_mesh_supported ?
"yes" : "no"));
sigma_dut_print(global_dut, DUT_MSG_INFO, "Infra Field:%d",
event->conn_capability.wlan_infra_field);
} else {
sigma_dut_print(global_dut, DUT_MSG_INFO,
"PostConnectivity Capability not present");
}
/* Print the discovery_attr */
sigma_dut_print(global_dut, DUT_MSG_INFO,
"Printing PostDiscovery Attribute");
if (event->num_rx_discovery_attr) {
int idx;
for (idx = 0; idx < event->num_rx_discovery_attr; idx++) {
sigma_dut_print(global_dut, DUT_MSG_INFO,
"PostDiscovery Attribute - %d", idx);
sigma_dut_print(global_dut, DUT_MSG_INFO,
"Conn Type:%d Device Role:%d"
MAC_ADDR_STR,
event->discovery_attr[idx].type,
event->discovery_attr[idx].role,
MAC_ADDR_ARRAY(event->discovery_attr[idx].addr));
sigma_dut_print(global_dut, DUT_MSG_INFO,
"Duration:%d MapId:%d "
"avail_interval_bitmap:%04x",
event->discovery_attr[idx].duration,
event->discovery_attr[idx].mapid,
event->discovery_attr[idx].avail_interval_bitmap);
sigma_dut_print(global_dut, DUT_MSG_INFO,
"Printing Mesh Id:");
nan_hex_dump(global_dut,
event->discovery_attr[idx].mesh_id,
event->discovery_attr[idx].mesh_id_len);
sigma_dut_print(global_dut, DUT_MSG_INFO,
"Printing Infrastructure Ssid:");
nan_hex_dump(global_dut,
event->discovery_attr[idx].infrastructure_ssid_val,
event->discovery_attr[idx].infrastructure_ssid_len);
}
} else {
sigma_dut_print(global_dut, DUT_MSG_INFO,
"PostDiscovery attribute not present");
}
/* Print the fam */
if (event->num_chans) {
nan_print_further_availability_chan(global_dut,
event->num_chans,
&event->famchan[0]);
} else {
sigma_dut_print(global_dut, DUT_MSG_INFO,
"Further Availability Map not present");
}
if (event->cluster_attribute_len) {
sigma_dut_print(global_dut, DUT_MSG_INFO,
"Printing Cluster Attribute:");
nan_hex_dump(global_dut, event->cluster_attribute,
event->cluster_attribute_len);
} else {
sigma_dut_print(global_dut, DUT_MSG_INFO,
"Cluster Attribute not present");
}
}
/* Events Callback */
void nan_event_match_expired(NanMatchExpiredInd *event)
{
sigma_dut_print(global_dut, DUT_MSG_INFO,
"%s: publish_subscribe_id %d match_handle %08x",
__func__, event->publish_subscribe_id,
event->requestor_instance_id);
}
/* Events Callback */
void nan_event_subscribe_terminated(NanSubscribeTerminatedInd *event)
{
sigma_dut_print(global_dut, DUT_MSG_INFO,
"%s: Subscribe Id %d reason %d",
__func__, event->subscribe_id, event->reason);
}
/* Events Callback */
void nan_event_followup(NanFollowupInd *event)
{
sigma_dut_print(global_dut, DUT_MSG_INFO,
"%s: Publish/Subscribe Id %d match_handle 0x%08x dw_or_faw %d "
MAC_ADDR_STR, __func__, event->publish_subscribe_id,
event->requestor_instance_id, event->dw_or_faw,
MAC_ADDR_ARRAY(event->addr));
global_match_handle = event->requestor_instance_id;
global_header_handle = event->publish_subscribe_id;
sigma_dut_print(global_dut, DUT_MSG_INFO, "%s: Printing SSI", __func__);
nan_hex_dump(global_dut, event->service_specific_info,
event->service_specific_info_len);
event_anyresponse = 1;
snprintf(global_event_resp_buf, sizeof(global_event_resp_buf),
"EventName,FollowUp,RemoteInstanceID,%d,LocalInstanceID,%d,mac,"
MAC_ADDR_STR " ", event->requestor_instance_id >> 24,
event->publish_subscribe_id, MAC_ADDR_ARRAY(event->addr));
}
/* Events Callback */
void nan_event_disceng_event(NanDiscEngEventInd *event)
{
sigma_dut_print(global_dut, DUT_MSG_INFO, "%s: event_type %d",
__func__, event->event_type);
if (event->event_type == NAN_EVENT_ID_JOINED_CLUSTER) {
sigma_dut_print(global_dut, DUT_MSG_INFO, "%s: Joined cluster "
MAC_ADDR_STR,
__func__,
MAC_ADDR_ARRAY(event->data.cluster.addr));
/* To ensure sta_get_events to get the events
* only after joining the NAN cluster. */
pthread_cond_signal(&gCondition);
}
if (event->event_type == NAN_EVENT_ID_STARTED_CLUSTER) {
sigma_dut_print(global_dut, DUT_MSG_INFO,
"%s: Started cluster " MAC_ADDR_STR,
__func__,
MAC_ADDR_ARRAY(event->data.cluster.addr));
}
if (event->event_type == NAN_EVENT_ID_DISC_MAC_ADDR) {
sigma_dut_print(global_dut, DUT_MSG_INFO,
"%s: Discovery Mac Address "
MAC_ADDR_STR,
__func__,
MAC_ADDR_ARRAY(event->data.mac_addr.addr));
memcpy(global_nan_mac_addr, event->data.mac_addr.addr,
sizeof(global_nan_mac_addr));
}
}
/* Events Callback */
void nan_event_disabled(NanDisabledInd *event)
{
sigma_dut_print(global_dut, DUT_MSG_INFO, "%s: reason %d",
__func__, event->reason);
/* pthread_cond_signal(&gCondition); */
}
/* Events callback */
static void ndp_event_data_indication(NanDataPathRequestInd *event)
{
sigma_dut_print(global_dut, DUT_MSG_INFO,
"%s: Service Instance Id: %d Peer Discovery MAC ADDR "
MAC_ADDR_STR
" NDP Instance Id: %d App Info len %d App Info %s",
__func__,
event->service_instance_id,
MAC_ADDR_ARRAY(event->peer_disc_mac_addr),
event->ndp_instance_id,
event->app_info.ndp_app_info_len,
event->app_info.ndp_app_info);
global_ndp_instance_id = event->ndp_instance_id;
}
/* Events callback */
static void ndp_event_data_confirm(NanDataPathConfirmInd *event)
{
char cmd[200];
char ipv6_buf[100];
sigma_dut_print(global_dut, DUT_MSG_INFO,
"Received NDP Confirm Indication");
memset(cmd, 0, sizeof(cmd));
memset(ipv6_buf, 0, sizeof(ipv6_buf));
global_ndp_instance_id = event->ndp_instance_id;
if (event->rsp_code == NAN_DP_REQUEST_ACCEPT) {
if (system("ifconfig nan0 up") != 0) {
sigma_dut_print(global_dut, DUT_MSG_ERROR,
"Failed to set nan interface up");
return;
}
if (system("ip -6 route replace fe80::/64 dev nan0 table local") !=
0) {
sigma_dut_print(global_dut, DUT_MSG_ERROR,
"Failed to run:ip -6 route replace fe80::/64 dev nan0 table local");
}
#if ((NAN_MAJOR_VERSION > 2) || \
(NAN_MAJOR_VERSION == 2 && NAN_MINOR_VERSION >= 1)) && \
NAN_CERT_VERSION >= 5
if (event->nan_ipv6_addr_present)
snprintf(ipv6_buf, sizeof(ipv6_buf),
"fe80::%02x%02x:%02xff:fe%02x:%02x%02x",
event->nan_ipv6_intf_addr[8],
event->nan_ipv6_intf_addr[9],
event->nan_ipv6_intf_addr[10],
event->nan_ipv6_intf_addr[13],
event->nan_ipv6_intf_addr[14],
event->nan_ipv6_intf_addr[15]);
else
#endif
convert_mac_addr_to_ipv6_lladdr(
event->peer_ndi_mac_addr,
ipv6_buf, sizeof(ipv6_buf));
snprintf(cmd, sizeof(cmd),
"ip -6 neighbor replace %s lladdr %02x:%02x:%02x:%02x:%02x:%02x nud permanent dev nan0",
ipv6_buf, event->peer_ndi_mac_addr[0],
event->peer_ndi_mac_addr[1],
event->peer_ndi_mac_addr[2],
event->peer_ndi_mac_addr[3],
event->peer_ndi_mac_addr[4],
event->peer_ndi_mac_addr[5]);
sigma_dut_print(global_dut, DUT_MSG_INFO,
"neighbor replace cmd = %s", cmd);
if (system(cmd) != 0) {
sigma_dut_print(global_dut, DUT_MSG_ERROR,
"Failed to run: ip -6 neighbor replace");
return;
}
}
}
void * my_thread_function(void *ptr)
{
wifi_event_loop(global_wifi_handle);
pthread_exit(0);
return (void *) NULL;
}
static NanCallbackHandler callbackHandler = {
.NotifyResponse = nan_notify_response,
.EventPublishReplied = nan_event_publish_replied,
.EventPublishTerminated = nan_event_publish_terminated,
.EventMatch = nan_event_match,
.EventMatchExpired = nan_event_match_expired,
.EventSubscribeTerminated = nan_event_subscribe_terminated,
.EventFollowup = nan_event_followup,
.EventDiscEngEvent = nan_event_disceng_event,
.EventDisabled = nan_event_disabled,
.EventDataRequest = ndp_event_data_indication,
.EventDataConfirm = ndp_event_data_confirm,
};
void nan_init(struct sigma_dut *dut)
{
pthread_t thread1; /* thread variables */
wifi_error err = wifi_initialize(&global_wifi_handle);
if (err) {
printf("wifi hal initialize failed\n");
return;
}
global_interface_handle = wifi_get_iface_handle(global_wifi_handle,
(char *) "wlan0");
/* create threads 1 */
pthread_create(&thread1, NULL, &my_thread_function, NULL);
pthread_mutex_init(&gMutex, NULL);
pthread_cond_init(&gCondition, NULL);
if (global_interface_handle)
nan_register_handler(global_interface_handle, callbackHandler);
}
void nan_cmd_sta_reset_default(struct sigma_dut *dut, struct sigma_conn *conn,
struct sigma_cmd *cmd)
{
sigma_dut_print(dut, DUT_MSG_INFO, "NAN sta_reset_default");
#ifdef ANDROID
if (dut->nanservicediscoveryinprogress) {
char *argv[5];
pid_t pid;
argv[0] = "am";
argv[1] = "broadcast";
argv[2] = "-a";
argv[3] = "org.codeaurora.nanservicediscovery.close";
argv[4] = NULL;
pid = fork();
if (pid == -1) {
sigma_dut_print(dut, DUT_MSG_ERROR, "fork: %s",
strerror(errno));
} else if (pid == 0) {
execv("/system/bin/am", argv);
sigma_dut_print(dut, DUT_MSG_ERROR, "execv: %s",
strerror(errno));
exit(0);
}
dut->nanservicediscoveryinprogress = 0;
}
#endif /* ANDROID */
if (nan_state == 0) {
nan_init(dut);
nan_state = 1;
}
is_fam = 0;
event_anyresponse = 0;
global_dut = dut;
memset(&dut->nan_pmk[0], 0, NAN_PMK_INFO_LEN);
dut->nan_pmk_len = 0;
dut->sta_channel = 0;
dut->ndpe = 0;
dut->trans_proto = NAN_TRANSPORT_PROTOCOL_DEFAULT;
dut->trans_port = NAN_TRANSPORT_PORT_DEFAULT;
memset(global_event_resp_buf, 0, sizeof(global_event_resp_buf));
memset(&global_nan_sync_stats, 0, sizeof(global_nan_sync_stats));
memset(global_publish_service_name, 0,
sizeof(global_publish_service_name));
global_publish_service_name_len = 0;
global_publish_id = 0;
global_subscribe_id = 0;
sigma_nan_data_end(dut, cmd);
nan_data_interface_delete(0, global_interface_handle, (char *) "nan0");
sigma_nan_disable(dut, conn, cmd);
global_header_handle = 0;
global_match_handle = 0;
}
int nan_cmd_sta_exec_action(struct sigma_dut *dut, struct sigma_conn *conn,
struct sigma_cmd *cmd)
{
const char *program = get_param(cmd, "Prog");
const char *nan_op = get_param(cmd, "NANOp");
const char *method_type = get_param(cmd, "MethodType");
const char *band = get_param(cmd, "band");
const char *disc_mac_addr = get_param(cmd, "DiscoveryMacAddress");
char resp_buf[100];
wifi_error ret;
if (program == NULL)
return -1;
if (strcasecmp(program, "NAN") != 0) {
send_resp(dut, conn, SIGMA_ERROR,
"ErrorCode,Unsupported program");
return 0;
}
if (nan_op) {
#if NAN_CERT_VERSION >= 3
int size = 0;
u32 device_type_val = 0;
NanDebugParams cfg_debug;
memset(&cfg_debug, 0, sizeof(NanDebugParams));
cfg_debug.cmd = NAN_TEST_MODE_CMD_DEVICE_TYPE;
if (dut->device_type == STA_testbed)
device_type_val = NAN_DEVICE_TYPE_TEST_BED;
else if (dut->device_type == STA_dut)
device_type_val = NAN_DEVICE_TYPE_DUT;
memcpy(cfg_debug.debug_cmd_data, &device_type_val, sizeof(u32));
size = sizeof(u32) + sizeof(u32);
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: Device Type: cmd type = %d and command data = %u",
__func__, cfg_debug.cmd, device_type_val);
nan_debug_command_config(0, global_interface_handle,
cfg_debug, size);
#endif
/*
* NANOp has been specified.
* We will build a nan_enable or nan_disable command.
*/
if (strcasecmp(nan_op, "On") == 0) {
if (sigma_nan_enable(dut, conn, cmd) == 0) {
ret = nan_data_interface_create(
0, global_interface_handle,
(char *) "nan0");
if (ret != WIFI_SUCCESS) {
sigma_dut_print(
global_dut, DUT_MSG_ERROR,
"Unable to create NAN data interface");
}
snprintf(resp_buf, sizeof(resp_buf), "mac,"
MAC_ADDR_STR,
MAC_ADDR_ARRAY(global_nan_mac_addr));
send_resp(dut, conn, SIGMA_COMPLETE, resp_buf);
} else {
send_resp(dut, conn, SIGMA_ERROR,
"NAN_ENABLE_FAILED");
return -1;
}
if (band && strcasecmp(band, "24g") == 0) {
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: Setting band to 2G Only",
__func__);
sigma_ndp_configure_band(
dut, conn, cmd,
NAN_DATA_PATH_SUPPORTED_BAND_2G);
} else if (band && dut->sta_channel > 12) {
sigma_ndp_configure_band(
dut, conn, cmd,
NAN_DATA_PATH_SUPPORT_DUAL_BAND);
}
} else if (strcasecmp(nan_op, "Off") == 0) {
nan_data_interface_delete(0,
global_interface_handle, (char *) "nan0");
sigma_nan_disable(dut, conn, cmd);
memset(global_publish_service_name, 0,
sizeof(global_publish_service_name));
global_publish_service_name_len = 0;
global_publish_id = 0;
global_subscribe_id = 0;
global_header_handle = 0;
global_match_handle = 0;
send_resp(dut, conn, SIGMA_COMPLETE, "NULL");
}
}
if (nan_state && nan_op == NULL) {
if (method_type) {
if (strcasecmp(method_type, "Publish") == 0) {
sigma_nan_publish_request(dut, conn, cmd);
send_resp(dut, conn, SIGMA_COMPLETE, "NULL");
}
if (strcasecmp(method_type, "Subscribe") == 0) {
sigma_nan_subscribe_request(dut, conn, cmd);
send_resp(dut, conn, SIGMA_COMPLETE, "NULL");
}
if (strcasecmp(method_type, "Followup") == 0) {
sigma_nan_transmit_followup(dut, conn, cmd);
send_resp(dut, conn, SIGMA_COMPLETE, "NULL");
}
if (strcasecmp(method_type, "DataRequest") == 0) {
sigma_nan_data_request(dut, conn, cmd);
send_resp(dut, conn, SIGMA_COMPLETE, "NULL");
}
if (strcasecmp(method_type, "DataResponse") == 0) {
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: method_type is DataResponse",
__func__);
sigma_nan_data_response(dut, conn, cmd);
send_resp(dut, conn, SIGMA_COMPLETE, "NULL");
}
if (strcasecmp(method_type, "DataEnd") == 0) {
sigma_nan_data_end(dut, cmd);
send_resp(dut, conn, SIGMA_COMPLETE, "NULL");
}
if (strcasecmp(method_type, "rangerequest") == 0) {
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: method_type is rangerequest",
__func__);
sigma_nan_range_request(dut, cmd);
send_resp(dut, conn, SIGMA_COMPLETE, "NULL");
}
if (strcasecmp(method_type, "cancelrange") == 0) {
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: method_type is cancelrange",
__func__);
sigma_nan_cancel_range(dut, cmd);
send_resp(dut, conn, SIGMA_COMPLETE, "NULL");
}
if (strcasecmp(method_type, "SchedUpdate") == 0) {
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: method_type is SchedUpdate",
__func__);
sigma_nan_schedule_update(dut, cmd);
send_resp(dut, conn, SIGMA_COMPLETE, "NULL");
}
} else if (disc_mac_addr &&
strcasecmp(disc_mac_addr, "GET") == 0) {
snprintf(resp_buf, sizeof(resp_buf), "mac,"
MAC_ADDR_STR,
MAC_ADDR_ARRAY(global_nan_mac_addr));
send_resp(dut, conn, SIGMA_COMPLETE, resp_buf);
} else {
sigma_nan_config_enable(dut, conn, cmd);
snprintf(resp_buf, sizeof(resp_buf), "mac,"
MAC_ADDR_STR,
MAC_ADDR_ARRAY(global_nan_mac_addr));
send_resp(dut, conn, SIGMA_COMPLETE, resp_buf);
}
}
return 0;
}
int nan_cmd_sta_get_parameter(struct sigma_dut *dut, struct sigma_conn *conn,
struct sigma_cmd *cmd)
{
const char *program = get_param(cmd, "Program");
const char *parameter = get_param(cmd, "Parameter");
char resp_buf[100];
NanStatsRequest req;
struct timespec abstime;
u64 master_rank;
u8 master_pref;
u8 random_factor;
u8 hop_count;
u32 beacon_transmit_time;
u32 ndp_channel_freq;
u32 ndp_channel_freq2;
#if NAN_CERT_VERSION >= 3
u32 sched_update_channel_freq;
#endif
if (program == NULL) {
sigma_dut_print(dut, DUT_MSG_ERROR, "Invalid Program Name");
return -1;
}
if (strcasecmp(program, "NAN") != 0) {
send_resp(dut, conn, SIGMA_ERROR,
"ErrorCode,Unsupported program");
return 0;
}
if (parameter == NULL) {
sigma_dut_print(dut, DUT_MSG_ERROR, "Invalid Parameter");
return -1;
}
memset(&req, 0, sizeof(NanStatsRequest));
memset(resp_buf, 0, sizeof(resp_buf));
req.stats_type = (NanStatsType) NAN_STATS_ID_DE_TIMING_SYNC;
nan_stats_request(0, global_interface_handle, &req);
/*
* To ensure sta_get_events to get the events
* only after joining the NAN cluster
*/
abstime.tv_sec = 4;
abstime.tv_nsec = 0;
wait(abstime);
master_rank = global_nan_sync_stats.myRank;
master_pref = (global_nan_sync_stats.myRank & 0xFF00000000000000) >> 56;
random_factor = (global_nan_sync_stats.myRank & 0x00FF000000000000) >>
48;
hop_count = global_nan_sync_stats.currAmHopCount;
beacon_transmit_time = global_nan_sync_stats.currAmBTT;
ndp_channel_freq = global_nan_sync_stats.ndpChannelFreq;
ndp_channel_freq2 = global_nan_sync_stats.ndpChannelFreq2;
#if NAN_CERT_VERSION >= 3
sched_update_channel_freq =
global_nan_sync_stats.schedUpdateChannelFreq;
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: NanStatsRequest Master_pref:%02x, Random_factor:%02x, hop_count:%02x beacon_transmit_time:%d ndp_channel_freq:%d ndp_channel_freq2:%d sched_update_channel_freq:%d",
__func__, master_pref, random_factor,
hop_count, beacon_transmit_time,
ndp_channel_freq, ndp_channel_freq2,
sched_update_channel_freq);
#else /* #if NAN_CERT_VERSION >= 3 */
sigma_dut_print(dut, DUT_MSG_INFO,
"%s: NanStatsRequest Master_pref:%02x, Random_factor:%02x, hop_count:%02x beacon_transmit_time:%d ndp_channel_freq:%d ndp_channel_freq2:%d",
__func__, master_pref, random_factor,
hop_count, beacon_transmit_time,
ndp_channel_freq, ndp_channel_freq2);
#endif /* #if NAN_CERT_VERSION >= 3 */
if (strcasecmp(parameter, "MasterPref") == 0) {
snprintf(resp_buf, sizeof(resp_buf), "MasterPref,0x%x",
master_pref);
} else if (strcasecmp(parameter, "MasterRank") == 0) {
snprintf(resp_buf, sizeof(resp_buf), "MasterRank,0x%lx",
master_rank);
} else if (strcasecmp(parameter, "RandFactor") == 0) {
snprintf(resp_buf, sizeof(resp_buf), "RandFactor,0x%x",
random_factor);
} else if (strcasecmp(parameter, "HopCount") == 0) {
snprintf(resp_buf, sizeof(resp_buf), "HopCount,0x%x",
hop_count);
} else if (strcasecmp(parameter, "BeaconTransTime") == 0) {
snprintf(resp_buf, sizeof(resp_buf), "BeaconTransTime 0x%x",
beacon_transmit_time);
} else if (strcasecmp(parameter, "NANStatus") == 0) {
if (nan_state == 1)
snprintf(resp_buf, sizeof(resp_buf), "On");
else
snprintf(resp_buf, sizeof(resp_buf), "Off");
} else if (strcasecmp(parameter, "NDPChannel") == 0) {
if (ndp_channel_freq != 0 && ndp_channel_freq2 != 0) {
snprintf(resp_buf, sizeof(resp_buf),
"ndpchannel,%d,ndpchannel,%d",
freq_to_channel(ndp_channel_freq),
freq_to_channel(ndp_channel_freq2));
} else if (ndp_channel_freq != 0) {
snprintf(resp_buf, sizeof(resp_buf), "ndpchannel,%d",
freq_to_channel(ndp_channel_freq));
} else if (ndp_channel_freq2 != 0) {
snprintf(resp_buf, sizeof(resp_buf), "ndpchannel,%d",
freq_to_channel(ndp_channel_freq2));
} else {
sigma_dut_print(dut, DUT_MSG_ERROR,
"%s: No Negotiated NDP Channels", __func__);
}
#if NAN_CERT_VERSION >= 3
} else if (strcasecmp(parameter, "SchedUpdateChannel") == 0) {
snprintf(resp_buf, sizeof(resp_buf), "schedupdatechannel,%d",
freq_to_channel(sched_update_channel_freq));
#endif
} else {
send_resp(dut, conn, SIGMA_ERROR, "Invalid Parameter");
return 0;
}
send_resp(dut, conn, SIGMA_COMPLETE, resp_buf);
return 0;
}
int nan_cmd_sta_get_events(struct sigma_dut *dut, struct sigma_conn *conn,
struct sigma_cmd *cmd)
{
const char *action = get_param(cmd, "Action");
if (!action)
return 0;
/* Check action for start, stop and get events. */
if (strcasecmp(action, "Start") == 0) {
memset(global_event_resp_buf, 0, sizeof(global_event_resp_buf));
send_resp(dut, conn, SIGMA_COMPLETE, NULL);
} else if (strcasecmp(action, "Stop") == 0) {
event_anyresponse = 0;
memset(global_event_resp_buf, 0, sizeof(global_event_resp_buf));
send_resp(dut, conn, SIGMA_COMPLETE, NULL);
} else if (strcasecmp(action, "Get") == 0) {
if (event_anyresponse == 1) {
send_resp(dut, conn, SIGMA_COMPLETE,
global_event_resp_buf);
} else {
send_resp(dut, conn, SIGMA_COMPLETE, "EventList,NONE");
}
}
return 0;
}
#else /* #if NAN_CERT_VERSION */
int nan_cmd_sta_preset_testparameters(struct sigma_dut *dut,
struct sigma_conn *conn,
struct sigma_cmd *cmd)
{
return 1;
}
int nan_cmd_sta_get_parameter(struct sigma_dut *dut, struct sigma_conn *conn,
struct sigma_cmd *cmd)
{
return 0;
}
void nan_cmd_sta_reset_default(struct sigma_dut *dut, struct sigma_conn *conn,
struct sigma_cmd *cmd)
{
return;
}
int nan_cmd_sta_get_events(struct sigma_dut *dut, struct sigma_conn *conn,
struct sigma_cmd *cmd)
{
return 0;
}
int nan_cmd_sta_exec_action(struct sigma_dut *dut, struct sigma_conn *conn,
struct sigma_cmd *cmd)
{
return 0;
}
#endif /* #if NAN_CERT_VERSION */
| 30.31661 | 172 | 0.71715 | [
"mesh"
] |
3e4df8331327ae22c48fd092f6204e0295c3b5cf | 928 | h | C | src/Pizzeria.h | mateobosco/concurrentes_tp1 | a5f5d2319cb42d40f0deee681ede9c36816030fe | [
"MIT"
] | 1 | 2015-04-26T05:12:35.000Z | 2015-04-26T05:12:35.000Z | src/Pizzeria.h | mateobosco/concurrentes_tp1 | a5f5d2319cb42d40f0deee681ede9c36816030fe | [
"MIT"
] | 2 | 2015-05-06T15:19:53.000Z | 2015-05-06T23:59:51.000Z | src/Pizzeria.h | mateobosco/concurrentes_tp1 | a5f5d2319cb42d40f0deee681ede9c36816030fe | [
"MIT"
] | null | null | null | /*
* Pizzeria.h
*
* Created on: 25/4/2015
* Author: mateo
*/
#ifndef PIZZERIA_H_
#define PIZZERIA_H_
#include <stdlib.h>
#include <vector>
#include "structures/Semaforo.h"
#include "Proceso.h"
#include "GeneradorLlamados.h"
#include "Recepcionista.h"
#include "Cocinero.h"
#include "Horno.h"
#include "Cadete.h"
#include "Supervisora.h"
#include "Caja.h"
class Pizzeria: public Proceso {
public:
Pizzeria();
virtual ~Pizzeria();
void crearGeneradorLlamados();
void crearRecepcionistas(int n);
void crearCocineros(int n);
void crearHornos(int n);
void crearCadetes(int n);
void crearSupervisora(int segundos);
void crearCaja();
void run();
private:
std::vector<int> childs;
Semaforo* semaforoPizzeriaGracefulQuit;
Semaforo* semaforoHornosLibres;
Semaforo* semaforoPedidosPendientes;
Semaforo* semaforoCadetesLibres;
MemoriaCompartida<Caja>* memoriaCompartidaCaja;
};
#endif /* PIZZERIA_H_ */
| 18.196078 | 48 | 0.740302 | [
"vector"
] |
3e5587b007a6339ec4ce6a4bcc39fccc342ae5dc | 4,869 | h | C | src/DewDropPlayer/Engine/IAudioEngine.h | kineticpsychology/Dew-Drop-Project | 1704ac491395800c0b1e54d1d0fd761fc5a71296 | [
"0BSD"
] | null | null | null | src/DewDropPlayer/Engine/IAudioEngine.h | kineticpsychology/Dew-Drop-Project | 1704ac491395800c0b1e54d1d0fd761fc5a71296 | [
"0BSD"
] | null | null | null | src/DewDropPlayer/Engine/IAudioEngine.h | kineticpsychology/Dew-Drop-Project | 1704ac491395800c0b1e54d1d0fd761fc5a71296 | [
"0BSD"
] | null | null | null | /*******************************************************************************
* *
* COPYRIGHT (C) Aug, 2020 | Polash Majumdar *
* *
* This file is part of the Dew Drop Player project. The file content comes *
* "as is" without any warranty of definitive functionality. The author of the *
* code is not to be held liable for any improper functionality, broken code, *
* bug and otherwise unspecified error that might cause damage or might break *
* the application where this code is imported. In accordance with the *
* Zero-Clause BSD licence model of the Dew Drop project, the end-user/adopter *
* of this code is hereby granted the right to use, copy, modify, and/or *
* distribute this code with/without keeping this copyright notice. *
* *
* TL;DR - It's a free world. All of us should give back to the world that we *
* get so much from. I have tried doing my part by making this code *
* free (as in free beer). Have fun. Just don't vandalize the code *
* or morph it into a malicious one. *
* *
*******************************************************************************/
#ifndef _IAUDIOENGINE_H_
#define _IAUDIOENGINE_H_
#ifndef UNICODE
#define UNICODE
#endif
#ifndef _UNICODE
#define _UNICODE
#endif
#include "TagInfo.h"
#include "..\Common\DewCommon.h"
typedef struct _EXTENDEDINFO
{
wchar_t Type[EXINFO_TYP_SIZE];
wchar_t Value[EXINFO_VAL_SIZE];
void Set(LPCWSTR type, LPCWSTR value)
{
StringCchPrintf(Type, EXINFO_TYP_SIZE, type);
StringCchPrintf(Value, EXINFO_VAL_SIZE, value);
return;
}
void SetType(LPCWSTR type)
{
StringCchPrintf(Type, EXINFO_TYP_SIZE, type);
return;
}
void SetValue(LPCWSTR value)
{
StringCchPrintf(Value, EXINFO_VAL_SIZE, value);
return;
}
} EXTENDEDINFO, *LPEXTENDEDINFO;
typedef class IAUDIOENGINE
{
private:
void _GenerateTempSrcFile(); // Use a temp location filename
protected:
wchar_t _wsInternalTemp[MAX_CHAR_PATH];
HWND _hWndNotify = NULL;
LPBYTE _lpEncodedSrcData = NULL;
DWORD _dwSrcDataSize = 0;
BYTE _btStatus = DEWS_MEDIA_NONE;
BYTE _btMediaType = DEWMT_UNKNOWN;
DWORD _dwDuration = 0;
DWORD _dwBitrate = 0;
DWORD _dwSampleRate = 0;
BYTE _btChannels = 0;
DWORD _dwExInfoLength = 0;
LPEXTENDEDINFO _lpExInfo = NULL;
wchar_t _wsSrcFile[MAX_CHAR_PATH];
wchar_t _wsLibrary[MAX_PATH];
TAGINFO _tiTagInfo;
virtual BOOL _StoreRawInputData(LPCWSTR sourceFile);
virtual void _Cleanup();
public:
const BYTE& Status;
const BYTE& MediaType;
const DWORD& Duration;
const DWORD& Bitrate;
const DWORD& SampleRate;
const BYTE& Channels;
const DWORD& ExtendedInfoCount;
const LPEXTENDEDINFO& ExtendedInfo;
const wchar_t* SourceFileName;
const wchar_t* Library;
TAGINFO& Tag;
IAUDIOENGINE();
virtual BYTE Load(HWND notificationWindow, LPCWSTR srcFile) = 0;
virtual BYTE Load(HWND notificationWindow, LPBYTE srcDataBytes, DWORD dataSize) = 0;
virtual BYTE Play() = 0;
virtual BYTE Pause() = 0;
virtual BYTE Resume() = 0;
virtual BYTE Stop() = 0;
virtual BYTE Seek(DWORD dwMS) = 0;
virtual DWORD Tell() = 0;
virtual BYTE SetVolume(WORD wLevel) = 0;
virtual BYTE Unload() = 0;
virtual void SetContainerFormat(BYTE containerFormat);
virtual ~IAUDIOENGINE();
static void GetAudioFormatString(BYTE audioFormatCode, LPWSTR formatCodeString, const DWORD stringLength);
} IAUDIOENGINE, *LPIAUDIOENGINE;
#endif
| 41.262712 | 126 | 0.489012 | [
"model"
] |
3e6bd7966f570d474465f239e173e879b7ca6ecf | 5,071 | h | C | include/breakout/particlegenerator.h | darkoverlordofdata/wrengame | 58a85b1fc4cacafb51780cadb694aa2b71382ec0 | [
"MIT"
] | null | null | null | include/breakout/particlegenerator.h | darkoverlordofdata/wrengame | 58a85b1fc4cacafb51780cadb694aa2b71382ec0 | [
"MIT"
] | null | null | null | include/breakout/particlegenerator.h | darkoverlordofdata/wrengame | 58a85b1fc4cacafb51780cadb694aa2b71382ec0 | [
"MIT"
] | null | null | null | #pragma once
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include "dark.h"
#include "tglm.h"
#define GL3_PROTOTYPES 1
#include <GLES3/gl3.h>
#include "SDL2/SDL.h"
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_mixer.h>
#include <SDL2/SDL_ttf.h>
// Represents a single particle and its state
type (Particle)
{
Vec2 Position;
Vec2 Velocity;
Vec4 Color;
GLfloat Life;
// Particle() : Position(0.0f), Velocity(0.0f), Color(1.0f), Life(0.0f) { }
};
// ParticleGenerator acts as a container for rendering a large number of
// particles by repeatedly spawning and updating particles and killing
// them after a given amount of time.
type (ParticleGenerator)
{
Object* Isa;
Particle* particles;
GLuint amount;
Shader* shader;
Texture2D* texture;
GLuint VAO;
};
/**
* ParticleGenerator
*
* @param shader to use
* @param texture to source from
* @param amount number of particles to generate
*
*/
constructor (ParticleGenerator*,
Shader* shader,
Texture2D* texture,
int amount)
{
this->shader = shader;
this->texture = texture;
this->amount = amount;
init(this);
return this;
}
/**
* Update
*
* @param dt delta time
* @param object GameObject
* @param newParticles count
* @param offset to display from
*
*/
method void Update(
ParticleGenerator* this,
GLfloat dt,
GameObject* object,
GLuint newParticles,
Vec2 offset)
{
// Add new particles
for (GLuint i = 0; i < newParticles; ++i)
{
int unusedParticle = firstUnusedParticle(this);
respawnParticle(this, this->particles[unusedParticle], object, offset);
}
// Update all particles
for (GLuint i = 0; i < this->amount; ++i)
{
this->particles[i].Life -= dt; // reduce life
if (this->particles[i].Life > 0.0f)
{ // particle is alive, thus update
this->particles[i].Position -= this->particles[i].Velocity * dt;
this->particles[i].Color[3] -= dt * 2.5;
}
}
}
/**
* Render all particles
*
*/
method void Draw(ParticleGenerator* this)
{
// Use additive blending to give it a 'glow' effect
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
Use(this->shader);
for (int i=0; i<this->amount; i++)
{
struct Particle particle = this->particles[i];
if (particle.Life > 0.0f)
{
SetArray2(this->shader, "offset", &particle.Position);
SetArray4(this->shader, "color", &particle.Color);
Bind(this->texture);
glBindVertexArray(this->VAO);
glDrawArrays(GL_TRIANGLES, 0, 6);
glBindVertexArray(0);
}
}
// Don't forget to reset to default blending mode
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
/**
* initialize generator
*/
static void init(ParticleGenerator* this)
{
// Set up mesh and attribute properties
GLuint VBO;
GLfloat particle_quad[24] = {
0.0f, 1.0f, 0.0f, 1.0f,
1.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f,
1.0f, 0.0f, 1.0f, 0.0f
};
glGenVertexArrays(1, &this->VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(this->VAO);
// Fill mesh buffer
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(particle_quad), particle_quad, GL_STATIC_DRAW);
// Set mesh attributes
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0);
glBindVertexArray(0);
this->particles = DSmalloc(sizeof(Particle) * this->amount);
}
// Stores the index of the last particle used (for quick access to next dead particle)
GLuint lastUsedParticle = 0;
static GLuint firstUnusedParticle(ParticleGenerator* this)
{
// First search from last used particle, this will usually return almost instantly
for (GLuint i = lastUsedParticle; i < this->amount; ++i){
if (this->particles[i].Life <= 0.0f){
lastUsedParticle = i;
return i;
}
}
// Otherwise, do a linear search
for (GLuint i = 0; i < lastUsedParticle; ++i){
if (this->particles[i].Life <= 0.0f){
lastUsedParticle = i;
return i;
}
}
// All particles are taken, override the first one (note that if it repeatedly hits this case, more particles should be reserved)
lastUsedParticle = 0;
return 0;
}
static void respawnParticle(
ParticleGenerator* this,
struct Particle particle,
GameObject* object,
Vec2 offset)
{
GLfloat random = ((rand() % 100) - 50) / 10.0f;
GLfloat rColor = 0.5 + ((rand() % 100) / 100.0f);
particle.Position = object->Position + random + offset;
particle.Color = (Vec4){ rColor, rColor, rColor, 1.0f };
particle.Life = 1.0f;
particle.Velocity = object->Velocity * 0.1f;
}
/**
* ToString
*/
method char* ToString(const ParticleGenerator* const this)
{
return "ParticleGenerator";
}
| 26.005128 | 133 | 0.623546 | [
"mesh",
"render",
"object"
] |
3e6c743c8a5782209ea9e626c44f021382e38a05 | 18,343 | c | C | src/trusted/validator_x86/ncdis.c | MicrohexHQ/nacl_contracts | 3efab5eecb3cf7ba43f2d61000e65918aa4ba77a | [
"BSD-3-Clause"
] | 6 | 2015-02-06T23:41:01.000Z | 2015-10-21T03:08:51.000Z | src/trusted/validator_x86/ncdis.c | MicrohexHQ/nacl_contracts | 3efab5eecb3cf7ba43f2d61000e65918aa4ba77a | [
"BSD-3-Clause"
] | null | null | null | src/trusted/validator_x86/ncdis.c | MicrohexHQ/nacl_contracts | 3efab5eecb3cf7ba43f2d61000e65918aa4ba77a | [
"BSD-3-Clause"
] | 1 | 2019-10-02T08:41:50.000Z | 2019-10-02T08:41:50.000Z | /*
* Copyright (c) 2011 The Native Client Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/*
* ncdis.c - disassemble using NaCl decoder.
* Mostly for testing.
*/
#ifndef NACL_TRUSTED_BUT_NOT_TCB
#error("This file is not meant for use in the TCB")
#endif
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "native_client/src/shared/gio/gio.h"
#include "native_client/src/shared/utils/types.h"
#include "native_client/src/shared/utils/flags.h"
#include "native_client/src/shared/platform/nacl_log.h"
#include "native_client/src/trusted/validator/ncfileutil.h"
#include "native_client/src/trusted/validator/x86/decoder/nc_inst_state.h"
#include "native_client/src/trusted/validator/x86/decoder/ncopcode_desc.h"
#include "native_client/src/trusted/validator/x86/decoder/nc_decode_tables.h"
#include "native_client/src/trusted/validator/x86/ncval_seg_sfi/ncdecode_verbose.h"
#include "native_client/src/trusted/validator/x86/ncval_seg_sfi/ncvalidate_internaltypes.h"
#include "native_client/src/trusted/validator_x86/nc_read_segment.h"
#include "native_client/src/trusted/validator_x86/ncdis_segments.h"
/* True if we should use the full decoder when decoding. */
/* TODO(karl): When the full_decoder is working for both the x86-32 and
* x86-64 platforms, change to use full decoder for both as default.
*/
static Bool NACL_FLAGS_full_decoder =
#if NACL_TARGET_SUBARCH == 64
TRUE
#else
FALSE
#endif
;
/* True if we should use the validator decoder when decoding. */
static Bool NACL_FLAGS_validator_decoder =
#if NACL_TARGET_SUBARCH == 64
FALSE
#else
TRUE
#endif
;
/* True if we should print internal representations while decoding. */
static Bool NACL_FLAGS_internal = FALSE;
/* The name of the executable that is being run. */
static const char* exec_name = "???";
static void Fatal(const char *fmt, ...) {
FILE* fp = stdout;
va_list ap;
fprintf(fp, "Fatal: ");
va_start(ap, fmt);
vfprintf(fp, fmt, ap);
va_end(ap);
exit(-1);
}
void Info(const char *fmt, ...) {
FILE* fp = stdout;
va_list ap;
fprintf(fp, "Info: ");
va_start(ap, fmt);
vfprintf(fp, fmt, ap);
va_end(ap);
}
static void usage(void) {
fprintf(stderr,
"usage: ncdis [options] [file]\n"
"\n"
"Options are:\n"
"--commands=<file>\n"
"\tAdditional command line arguments are specified in the given\n"
"\tfile ('#' acts as a comment character). Use '-' as its value to\n"
"\tredirect command line arguments from standard input.\n"
"--full_decoder\n"
"\tDisassemble the elf executable using native client's\n"
"\tfull decoder.\n"
"--help\n"
"\tPrint out this usage message\n"
"--hex_text=<file>\n"
"\tDefine code section as sequence of (textual) hexidecimal bytes\n"
"\tdefined in the given file. Lines beginning with '#' will be\n"
"\treated as comments. If the first non-comment line begins with\n"
"\t'@' the following hexidecimal number will be used as the\n"
"\tbeginning (RIP/EIP) instruction address of the code segment.\n"
"\tUse '-' as its value to redirect standard input as the\n"
"\ttext file to process.\n"
"-i=XXXX\n"
"\tXXXX specifies the sequence of hexidecimal digits that define\n"
"\tan instruction to be decoded.\n"
"--internal\n"
"\tFor the iterator model (only), prints out each the decoded\n"
"\tinstruction, followed by the internals for the matched\n"
"\tinstruction.\n"
"--pc=XXX\n"
"\tSet program counter (i.e. RIP or EIP) to XXX.\n"
"--self_document\n"
"\tProcess input hext_text file in such a way, that it also\n"
"\trepresents the output that will be generated by ncdis.\n"
"\tThat is, copy comment lines (i.e. lines beginning with\n"
"\t'#') to stdout. In addition, it assumes that each line\n"
"\tconsists of an '-i' command line argument (and possibly\n"
"\ta '--pc' command line argument, followed by a '#',\n"
"\tfollowed by the corresponding disassembled text. On such\n"
"\tlines, the input is copied up to (and including) the '#'.,\n"
"\tand then the disassembled instruction is printed.\n"
"--validator_decoder\n"
"\tDisassemble the file using the partial instruction decoder used\n"
"\tby the validator.\n"
);
exit(1);
}
/* Converts command line flags to corresponding disassemble flags. */
static NaClDisassembleFlags NaClGetDisassembleFlags(void) {
NaClDisassembleFlags flags = 0;
if (NACL_FLAGS_validator_decoder) {
NaClAddBits(flags, NACL_DISASSEMBLE_FLAG(NaClDisassembleValidatorDecoder));
}
if (NACL_FLAGS_full_decoder) {
NaClAddBits(flags, NACL_DISASSEMBLE_FLAG(NaClDisassembleFull));
}
if (NACL_FLAGS_internal) {
NaClAddBits(flags, NACL_DISASSEMBLE_FLAG(NaClDisassembleAddInternals));
}
return flags;
}
static int AnalyzeSections(ncfile *ncf) {
int badsections = 0;
int ii;
const Elf_Shdr* shdr = ncf->sheaders;
for (ii = 0; ii < ncf->shnum; ii++) {
Info("section %d sh_addr %x offset %x flags %x\n",
ii, (uint32_t)shdr[ii].sh_addr,
(uint32_t)shdr[ii].sh_offset, (uint32_t)shdr[ii].sh_flags);
if ((shdr[ii].sh_flags & SHF_EXECINSTR) != SHF_EXECINSTR)
continue;
Info("parsing section %d\n", ii);
NaClDisassembleSegment(ncf->data + (shdr[ii].sh_addr - ncf->vbase),
shdr[ii].sh_addr, shdr[ii].sh_size,
NaClGetDisassembleFlags());
}
return -badsections;
}
static void AnalyzeCodeSegments(ncfile *ncf, const char *fname) {
if (AnalyzeSections(ncf) < 0) {
fprintf(stderr, "%s: text validate failed\n", fname);
}
}
/* Capture a sequence of bytes defining an instruction (up to a
* MAX_BYTES_PER_X86_INSTRUCTION). This sequence is used to run
* a (debug) test of the disassembler.
*/
static uint8_t FLAGS_decode_instruction[NACL_MAX_BYTES_PER_X86_INSTRUCTION];
/* Define the number of bytes supplied for a debug instruction. */
static int FLAGS_decode_instruction_size = 0;
/* Flag defining the value of the pc to use when decoding an instruction
* through decode_instruction.
*/
static uint32_t FLAGS_decode_pc = 0;
/* Flag defining an input file to use as command line arguments
* (one per input line). When specified, run the disassembler
* on each command line. The empty string "" denotes that no command
* line file was specified. A dash ("-") denotes that standard input
* should be used to get command line arguments.
*/
static char* FLAGS_commands = "";
/* Flag defining the name of a hex text to be used as the code segment. Assumes
* that the pc associated with the code segment is defined by
* FLAGS_decode_pc.
*/
static char* FLAGS_hex_text = "";
/* Flag, when used in combination with the commands flag, will turn
* on input copy rules, making the genrated output contain comments
* and the command line arguments as part of the corresponding
* generated output. For more details on this, see ProcessInputFile
* below.
*/
static Bool FLAGS_self_document = FALSE;
/*
* Store default values of flags on the first call. On subsequent
* calls, resets the flags to the default value.
*
* *WARNING* In order for this to work, this function must be
* called before GrokFlags
*
* NOTE: we only allow the specification of -use_iter at the top-level
* command line..
*/
static void ResetFlags(void) {
int i;
static uint32_t DEFAULT_decode_pc;
static char* DEFAULT_commands;
static Bool DEFAULT_self_document;
static Bool is_first_call = TRUE;
if (is_first_call) {
DEFAULT_decode_pc = FLAGS_decode_pc;
DEFAULT_commands = FLAGS_commands;
DEFAULT_self_document = FLAGS_self_document;
is_first_call = FALSE;
}
FLAGS_decode_pc = DEFAULT_decode_pc;
FLAGS_commands = DEFAULT_commands;
FLAGS_self_document = DEFAULT_self_document;
/* Always clear the decode instruction. */
FLAGS_decode_instruction_size = 0;
for (i = 0; i < NACL_MAX_BYTES_PER_X86_INSTRUCTION; ++i) {
FLAGS_decode_instruction[i] = 0;
}
}
/* Returns true if all characters in the string are zero. */
static Bool IsZero(const char* arg) {
while (*arg) {
if ('0' != *arg) {
return FALSE;
}
++arg;
}
return TRUE;
}
uint8_t HexToByte(const char* hex_value) {
unsigned long value = strtoul(hex_value, NULL, 16);
/* Verify that arg is all zeros when zero is returned. Otherwise,
* assume that the zero value was due to an error.
*/
if (0L == value && !IsZero(hex_value)) {
Fatal("-i option specifies illegal hex value '%s'\n", hex_value);
}
return (uint8_t) value;
}
/* Recognizes flags in argv, processes them, and then removes them.
* Returns the updated value for argc.
*/
int GrokFlags(int argc, const char *argv[]) {
int i;
int new_argc;
char* hex_instruction;
Bool help = FALSE;
if (argc == 0) return 0;
exec_name = argv[0];
new_argc = 1;
for (i = 1; i < argc; ++i) {
const char* arg = argv[i];
if (GrokUint32HexFlag("--pc", arg, &FLAGS_decode_pc) ||
GrokCstringFlag("--commands", arg, &FLAGS_commands) ||
GrokCstringFlag("--hex_text", arg, &FLAGS_hex_text) ||
GrokBoolFlag("--self_document", arg, &FLAGS_self_document) ||
GrokBoolFlag("--internal", arg, &NACL_FLAGS_internal) ||
GrokBoolFlag("--help", arg, &help)) {
if (help) usage();
} else if (GrokBoolFlag("--validator_decoder", arg,
&NACL_FLAGS_validator_decoder)) {
NACL_FLAGS_full_decoder = !NACL_FLAGS_validator_decoder;
} else if (GrokBoolFlag("--full_decoder", arg,
&NACL_FLAGS_full_decoder)) {
NACL_FLAGS_validator_decoder = !NACL_FLAGS_full_decoder;
} else if (GrokCstringFlag("-i", arg, &hex_instruction)) {
int i = 0;
char buffer[3];
char* buf = &(hex_instruction[0]);
buffer[2] = '\0';
while (*buf) {
buffer[i++] = *(buf++);
if (i == 2) {
uint8_t byte = HexToByte(buffer);
FLAGS_decode_instruction[FLAGS_decode_instruction_size++] = byte;
if (FLAGS_decode_instruction_size >
NACL_MAX_BYTES_PER_X86_INSTRUCTION) {
Fatal("-i=%s specifies too long of a hex value\n", hex_instruction);
}
i = 0;
}
}
if (i != 0) {
Fatal("-i=%s doesn't specify a sequence of bytes\n", hex_instruction);
}
} else {
argv[new_argc++] = argv[i];
}
}
return new_argc;
}
/* Process the command line arguments. */
static const char* GrokArgv(int argc, const char* argv[]) {
if (argc != 2) {
Fatal("no filename specified\n");
}
return argv[argc-1];
}
static void ProcessCommandLine(int argc, const char* argv[]);
/* Defines the maximum number of characters allowed on an input line
* of the input text defined by the commands command line option.
*/
#define MAX_INPUT_LINE 4096
/* Defines the characters used as (token) separators to recognize command
* line arguments when processing lines of text in the text file specified
* by the commands command line option.
*/
#define CL_SEPARATORS " \t\n"
/* Copies the text from the input line (which should be command line options),
* up to any trailing comments (i.e. the pound sign).
* input_line - The line of text to process.
* tokens - The extracted text from the input_line.
* max_length - The maximum length of input_line and tokens.
*
* Note: If input_line doesn't end with a null terminator, one is automatically
* inserted.
*/
static void CopyCommandLineTokens(char* input_line,
char* token_text,
size_t max_length) {
size_t i;
for (i = 0; i < max_length; ++i) {
char ch;
if (max_length == i + 1) {
/* Be sure we end the string with a null terminator. */
input_line[i] = '\0';
}
ch = input_line[i];
token_text[i] = ch;
if (ch == '\0') return;
if (ch == '#') {
token_text[i] = '\0';
return;
}
}
}
/* Tokenize the given text to find command line arguments, and
* add them to the given list of command line arguments.
*
* *WARNING* This function will (destructively) modify the
* contents of token_text, by converting command line option
* separator characters into newlines.
*/
static void ExtractTokensAndAddToArgv(
char* token_text,
int* argc,
const char* argv[]) {
/* Note: Assume that each command line argument corresponds to
* non-blank text, which is a HACK, but should be sufficient for
* what we need.
*/
char* token = strtok(token_text, CL_SEPARATORS);
while (token != NULL) {
argv[(*argc)++] = token;
token = strtok(NULL, CL_SEPARATORS);
}
}
/* Print out the contents of text, up to the first occurence of the
* pound sign.
*/
static void PrintUpToPound(const char text[]) {
int i;
struct Gio* g = NaClLogGetGio();
for (i = 0; i < MAX_INPUT_LINE; ++i) {
char ch = text[i];
switch (ch) {
case '#':
gprintf(g, "%c", ch);
return;
case '\0':
return;
default:
gprintf(g, "%c", ch);
break;
}
}
}
/* Reads the given text file and processes the command line options specified
* inside of it. Each line specifies a separate sequence of command line
* arguments to process.
*
* Note:
* (a) The '#' is used as a comment delimiter.
* (b) whitespace lines are ignored.
* (c) If flag --self_document is specified, comment lines and whitespace
* lines will automatically be copied to stdout. In addition, command
* line arguments will be copied to stdout before processing them.
* Further, if the command line arguments are followed by a comment,
* only text up to (and including) the '#' will be copied. This allows
* the input file to contain the (hopefully single lined) output that
* would be generated by the given command line arguments. Therefore,
* if set up correctly, the output of the disassembler (in this case)
* should be the same as the input file (making it easy to use the
* input file as the the corresponding GOLD file to test against).
*/
static void ProcessInputFile(FILE* file) {
char input_line[MAX_INPUT_LINE];
const Bool self_document = FLAGS_self_document;
while (fgets(input_line, MAX_INPUT_LINE, file) != NULL) {
char token_text[MAX_INPUT_LINE];
const char* line_argv[MAX_INPUT_LINE];
int line_argc = 0;
/* Copy the input line (up to the first #) into token_text */
CopyCommandLineTokens(input_line, token_text, MAX_INPUT_LINE);
/* Tokenize the commands to build argv.
* Note: Since each token is separated by a blank,
* and the input is no more than MAX_INPUT_LINE,
* we know (without checking) that line_argc
* will not exceed MAX_INPUT_LINE.
*/
line_argv[line_argc++] = exec_name;
ExtractTokensAndAddToArgv(token_text, &line_argc, line_argv);
/* Process the parsed input line. */
if (1 == line_argc) {
/* No command line arguments. */
if (self_document) {
printf("%s", input_line);
}
} else {
/* Process the tokenized command line. */
if (self_document) {
PrintUpToPound(input_line);
}
ProcessCommandLine(line_argc, line_argv);
}
}
ResetFlags();
}
/* Run the disassembler using the given command line arguments. */
static void ProcessCommandLine(int argc, const char* argv[]) {
int new_argc;
ResetFlags();
new_argc = GrokFlags(argc, argv);
if (FLAGS_decode_instruction_size > 0) {
/* Command line options specify an instruction to decode, run
* the disassembler on the instruction to print out the decoded
* results.
*/
if (new_argc > 1) {
Fatal("unrecognized option '%s'\n", argv[1]);
}
NaClDisassembleSegment(FLAGS_decode_instruction, FLAGS_decode_pc,
FLAGS_decode_instruction_size,
NaClGetDisassembleFlags());
} else if (0 != strcmp(FLAGS_hex_text, "")) {
uint8_t bytes[MAX_INPUT_LINE];
size_t num_bytes;
NaClPcAddress pc;
if (0 == strcmp(FLAGS_hex_text, "-")) {
num_bytes = NaClReadHexTextWithPc(stdin, &pc, bytes, MAX_INPUT_LINE);
NaClDisassembleSegment(bytes, pc, (NaClMemorySize) num_bytes,
NaClGetDisassembleFlags());
} else {
FILE* input = fopen(FLAGS_hex_text, "r");
if (NULL == input) {
Fatal("Can't open hex text file: %s\n", FLAGS_hex_text);
}
num_bytes = NaClReadHexTextWithPc(input, &pc, bytes, MAX_INPUT_LINE);
fclose(input);
NaClDisassembleSegment(bytes, pc, (NaClMemorySize) num_bytes,
NaClGetDisassembleFlags());
}
} else if (0 != strcmp(FLAGS_commands, "")) {
/* Use the given input file to find command line arguments,
* and process.
*/
if (0 == strcmp(FLAGS_commands, "-")) {
ProcessInputFile(stdin);
} else {
FILE* input = fopen(FLAGS_commands, "r");
if (NULL == input) {
Fatal("Can't open commands file: %s\n", FLAGS_commands);
}
ProcessInputFile(input);
fclose(input);
}
} else {
/* Command line should specify an executable to disassemble.
* Read the file and disassemble it.
*/
ncfile *ncf;
const char* filename = GrokArgv(new_argc, argv);
Info("processing %s", filename);
ncf = nc_loadfile_depending(filename, NULL);
if (ncf == NULL) {
Fatal("nc_loadfile(%s): %s\n", filename, strerror(errno));
}
AnalyzeCodeSegments(ncf, filename);
nc_freefile(ncf);
}
}
int main(int argc, const char *argv[]) {
struct GioFile gout_file;
struct Gio* gout = (struct Gio*) &gout_file;
if (!GioFileRefCtor(&gout_file, stdout)) {
fprintf(stderr, "Unable to create gio file for stdout!\n");
return 1;
}
NaClLogModuleInitExtended(LOG_INFO, gout);
ProcessCommandLine(argc, argv);
NaClLogModuleFini();
GioFileDtor(gout);
return 0;
}
| 33.780847 | 91 | 0.659325 | [
"model"
] |
3e6f4119c57564d68d031532fadd6dd3fccfe60c | 530 | h | C | parquetfile/compressor.h | Apsalar/parquet-writer | c7d04ceaafad7f391ffedb3bb5474c1b0ffbc0aa | [
"Apache-2.0"
] | 10 | 2017-06-05T12:50:55.000Z | 2022-01-28T10:15:25.000Z | parquetfile/compressor.h | Apsalar/parquet-writer | c7d04ceaafad7f391ffedb3bb5474c1b0ffbc0aa | [
"Apache-2.0"
] | 1 | 2018-11-12T11:56:01.000Z | 2018-11-12T11:56:01.000Z | parquetfile/compressor.h | Apsalar/parquet-writer | c7d04ceaafad7f391ffedb3bb5474c1b0ffbc0aa | [
"Apache-2.0"
] | 6 | 2017-06-05T12:50:43.000Z | 2019-12-09T09:23:10.000Z | //
// Parquet Compression Utility
//
// Copyright (c) 2016 Apsalar Inc.
// All rights reserved.
//
#pragma once
#include <string>
#include <vector>
#include "parquet_types.h"
namespace parquet_file {
class Compressor
{
public:
Compressor(parquet::CompressionCodec::type i_compression_codec);
void compress(std::string & in, std::string & out);
private:
parquet::CompressionCodec::type m_compression_codec;
std::string m_tmp;
};
} // end namespace parquet_file
// Local Variables:
// mode: C++
// End:
| 15.588235 | 68 | 0.696226 | [
"vector"
] |
3e7bbe566a35179ec3ab7fc73bac7f2a68f3410b | 1,355 | h | C | Pods/FXDanmaku/FXDanmaku/FXDanmakuItemData.h | lieonCX/Live | cfb81f9a57578ba8781dc1ccd7487bcf1d194e1e | [
"MIT"
] | 3 | 2017-08-16T14:51:12.000Z | 2017-09-14T02:44:59.000Z | Pods/FXDanmaku/FXDanmaku/FXDanmakuItemData.h | LieonShelly/Live | cfb81f9a57578ba8781dc1ccd7487bcf1d194e1e | [
"MIT"
] | null | null | null | Pods/FXDanmaku/FXDanmaku/FXDanmakuItemData.h | LieonShelly/Live | cfb81f9a57578ba8781dc1ccd7487bcf1d194e1e | [
"MIT"
] | 1 | 2017-11-11T06:12:06.000Z | 2017-11-11T06:12:06.000Z | //
// FXDanmakuItemData.h
// FXDanmakuDemo
//
// Created by ShawnFoo on 2017/1/2.
// Copyright © 2017年 ShawnFoo. All rights reserved.
//
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSUInteger, FXDataPriority) {
FXDataPriorityNormal,
FXDataPriorityHigh
};
NS_ASSUME_NONNULL_BEGIN
/**
FXDanmakuItemData plays an important role to FXDanmakuItem as the view model. FXDanmakuItemData should supply FXDanmakuItem with any datas item requires. One kind of FXDanmakuItemData should only be used by a specified FXDanmakuItem via itemReuseIdentifier property.
*/
@interface FXDanmakuItemData : NSObject
/**
The reuse identifier of DanmakuItem that will display this data.
*/
@property (nonatomic, readonly, copy) NSString *itemReuseIdentifier;
/**
High Priority data will be displayed first since it will be inserted to queue before normal priority data;
*/
@property (nonatomic, assign) FXDataPriority priority;
// Note: Identifier can't be nil or empty string!
+ (nullable instancetype)dataWithItemReuseIdentifier:(NSString *)identifier;
+ (nullable instancetype)highPriorityDataWithItemReuseIdentifier:(NSString *)identifier;
- (nullable instancetype)initWithItemReuseIdentifier:(NSString *)identifier priority:(FXDataPriority)priority NS_DESIGNATED_INITIALIZER;
- (instancetype)init NS_UNAVAILABLE;
@end
NS_ASSUME_NONNULL_END
| 30.795455 | 267 | 0.79631 | [
"model"
] |
3e7f7317dfc28e9bd98370ed95498b0a6f9ff780 | 1,081 | c | C | kungfu/skill/xiaoli-feidao/fei.c | zhangyifei/mud | b2090bbd2a8d3d82b86148d794a7ca59cd2429f3 | [
"MIT"
] | 69 | 2018-03-08T18:24:44.000Z | 2022-02-24T13:43:53.000Z | kungfu/skill/xiaoli-feidao/fei.c | zhangyifei/mud | b2090bbd2a8d3d82b86148d794a7ca59cd2429f3 | [
"MIT"
] | 3 | 2019-04-24T12:21:19.000Z | 2021-03-28T23:34:58.000Z | kungfu/skill/xiaoli-feidao/fei.c | zhangyifei/mud | b2090bbd2a8d3d82b86148d794a7ca59cd2429f3 | [
"MIT"
] | 33 | 2017-12-23T05:06:58.000Z | 2021-08-16T02:42:59.000Z | // shan.c
#include <ansi.h>
inherit F_SSERVER;
int perform(object me, object target)
{
int skill;
// int n, i;
// string pmsg;
string msg;
object weapon;
if (! target) target = offensive_target(me);
if (! target || ! me->is_fighting(target))
return notify_fail("小李飞刀只能在战斗中对对手使用。\n");
if (! objectp(weapon = me->query_temp("handing")) ||
(string)weapon->query("skill_type") != "throwing")
return notify_fail("你现在手中并没有拿着飞刀。\n");
if ((skill = me->query_skill("xiaoli-feidao", 1)) < 100)
return notify_fail("你的小李飞刀不够娴熟。\n");
if ((int)me->query("neili") < 100)
return notify_fail("你内力不够了。\n");
me->add("neili", -50);
weapon->add_amount(-1);
msg= HIW "忽然间只见$N" HIW "手中寒光一闪,正是小李飞刀,例无虚发!\n\n"
NOR + HIR "一股鲜血从$n" HIR "咽喉中喷出……\n" NOR;
message_combatd(msg, me, target);
me->start_busy(random(5));
target->die(me);
me->reset_action();
return 1;
}
| 25.139535 | 64 | 0.526364 | [
"object"
] |
3e8d2cf313335111db359669bf1a7a92b2bd0861 | 391 | h | C | memecity.game/Game/Components/InventoryComponent.h | TvanBronswijk/memecity | f0410fb72d5484a642be90964defb87654ebd66b | [
"MIT"
] | null | null | null | memecity.game/Game/Components/InventoryComponent.h | TvanBronswijk/memecity | f0410fb72d5484a642be90964defb87654ebd66b | [
"MIT"
] | 4 | 2018-10-01T09:44:02.000Z | 2018-12-10T12:08:39.000Z | memecity.game/Game/Components/InventoryComponent.h | TvanBronswijk/memecity | f0410fb72d5484a642be90964defb87654ebd66b | [
"MIT"
] | null | null | null | #ifndef _INVENTORYCOMPONENT_H
#define _INVENTORYCOMPONENT_H
#include <ECS.h>
#include "ItemComponent.h"
#include <vector>
struct InventoryComponent : public memecity::engine::ecs::Component
{
std::vector<const memecity::engine::ecs::Entity*> items;
int selected = 0;
InventoryComponent(memecity::engine::ecs::Entity& entity) : memecity::engine::ecs::Component(entity) {};
};
#endif;
| 23 | 105 | 0.749361 | [
"vector"
] |
3e9c0f2644fefd2aa6a0148f947febb38add9df9 | 8,395 | c | C | LIB/CDE/C/Rename_Narr.c | edwardcrichton/BToolkit | 1b927def38d143c1295edf0e0c98ad162d605e4a | [
"BSD-2-Clause"
] | 30 | 2015-04-28T13:12:25.000Z | 2022-03-29T17:05:04.000Z | LIB/CDE/C/Rename_Narr.c | edwardcrichton/BToolkit | 1b927def38d143c1295edf0e0c98ad162d605e4a | [
"BSD-2-Clause"
] | null | null | null | LIB/CDE/C/Rename_Narr.c | edwardcrichton/BToolkit | 1b927def38d143c1295edf0e0c98ad162d605e4a | [
"BSD-2-Clause"
] | 5 | 2016-08-28T20:58:01.000Z | 2021-09-27T18:10:57.000Z | /*Copyright (c) 1985-2012, B-Core (UK) Ltd
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include "Rename_Narr.h"
#include <stdio.h>
#include <sys/types.h>
#include <netinet/in.h>
extern FILE *dump_file;
#define convert_arr_htonl(a,i,n) \
j = i; \
k = 0; \
while ( k < n ) { \
a [ j ] = htonl ( a [ j ] ); \
j++; \
k++; \
}
#define convert_arr_ntohl(a,i,n) \
j = i; \
k = 0; \
while ( k < n ) { \
a [ j ] = ntohl ( a [ j ] ); \
j++; \
k++; \
}
#define write_fm(a,b) fwrite(&a,sizeof(int),b,dump_file)
void
Rename_SAV_NARR()
{
write_fm(Rename_Narray[1],Rename_NarrP2);
}
void
Rename_SAVN_NARR()
{
int j, k;
convert_arr_htonl(Rename_Narray,1,Rename_NarrP2);
write_fm(Rename_Narray[1],Rename_NarrP2);
convert_arr_ntohl(Rename_Narray,1,Rename_NarrP2);
}
#define read_fm(a,b) fread(&a,sizeof(int),b,dump_file)
void
Rename_RST_NARR()
{
read_fm(Rename_Narray[1],Rename_NarrP2);
}
void
Rename_RSTN_NARR()
{
int j, k;
read_fm(Rename_Narray[1],Rename_NarrP2);
convert_arr_ntohl(Rename_Narray,1,Rename_NarrP2);
}
void
#ifdef _BT_ANSIC
Rename_SWP_NARR( int ii, int jj )
#else
Rename_SWP_NARR( ii, jj )
int ii, jj;
#endif
{
int i;
i=Rename_Narray[ii];
Rename_Narray[ii]=Rename_Narray[jj];
Rename_Narray[jj]=i;
}
void
#ifdef _BT_ANSIC
Rename_MAX_IDX_NARR( int *vv, int ii, int jj )
#else
Rename_MAX_IDX_NARR( vv, ii, jj )
int* vv;
int ii, jj;
#endif
{
int x,t,k;
x=ii;
t=0;
k=ii;
while( x<=jj ){
if( Rename_Narray[x]>=t ){
t=Rename_Narray[x];
k=x;
};
x=x+1;
};
*(vv)=k;
}
void
#ifdef _BT_ANSIC
Rename_MIN_IDX_NARR( int *vv, int ii, int jj )
#else
Rename_MIN_IDX_NARR( vv, ii, jj )
int* vv;
int ii, jj;
#endif
{
int x,t,k;
x=ii;
k=ii;
t=Rename_NarrP1;
while( x<=jj ){
if( Rename_Narray[x]<=t ){
t=Rename_Narray[x];
k=x;
};
x=x+1;
};
*(vv)=k;
}
void
#ifdef _BT_ANSIC
Rename_SCH_LO_EQL_NARR( int *bb, int *ii, int jj, int kk, int vv )
#else
Rename_SCH_LO_EQL_NARR( bb, ii, jj, kk, vv )
int *bb;
int *ii;
int jj, kk, vv;
#endif
{
int r,y;
r=jj;
y=kk+1;
while( y!=r ){
if( Rename_Narray[r] == vv ){
y=r;
} else{
r=r+1;
};
}
*(bb)=((r!=kk+1)!=0);
*(ii)=r;
}
void
#ifdef _BT_ANSIC
Rename_SCH_LO_NEQ_NARR( int *bb, int *ii, int jj, int kk, int vv )
#else
Rename_SCH_LO_NEQ_NARR( bb, ii, jj, kk, vv )
int *bb;
int *ii;
int jj, kk, vv;
#endif
{
int r,y;
r=jj;
y=kk+1;
while( y!=r ){
if( Rename_Narray[r] != vv ){
y=r;
} else{
r=r+1;
};
}
*(bb)=((r!=kk+1)!=0);
*(ii)=r;
}
void
#ifdef _BT_ANSIC
Rename_SCH_LO_GEQ_NARR( int *bb, int *ii, int jj, int kk, int vv )
#else
Rename_SCH_LO_GEQ_NARR( bb, ii, jj, kk, vv )
int *bb;
int *ii;
int jj, kk, vv;
#endif
{
int r,y;
r=jj;
y=kk+1;
while( y!=r ){
if( Rename_Narray[r] >= vv ){
y=r;
} else{
r=r+1;
};
}
*(bb)=((r!=kk+1)!=0);
*(ii)=r;
}
void
#ifdef _BT_ANSIC
Rename_SCH_LO_GTR_NARR( int *bb, int *ii, int jj, int kk, int vv )
#else
Rename_SCH_LO_GTR_NARR( bb, ii, jj, kk, vv )
int *bb;
int *ii;
int jj, kk, vv;
#endif
{
int r,y;
r=jj;
y=kk+1;
while( y!=r ){
if( Rename_Narray[r] > vv ){
y=r;
} else{
r=r+1;
};
}
*(bb)=((r!=kk+1)!=0);
*(ii)=r;
}
void
#ifdef _BT_ANSIC
Rename_SCH_LO_LEQ_NARR( int *bb, int *ii, int jj, int kk, int vv )
#else
Rename_SCH_LO_LEQ_NARR( bb, ii, jj, kk, vv )
int *bb;
int *ii;
int jj, kk, vv;
#endif
{
int r,y;
r=jj;
y=kk+1;
while( y!=r ){
if( Rename_Narray[r] <= vv ){
y=r;
} else{
r=r+1;
};
}
*(bb)=((r!=kk+1)!=0);
*(ii)=r;
}
void
#ifdef _BT_ANSIC
Rename_SCH_LO_SMR_NARR( int *bb, int *ii, int jj, int kk, int vv )
#else
Rename_SCH_LO_SMR_NARR( bb, ii, jj, kk, vv )
int *bb;
int *ii;
int jj, kk, vv;
#endif
{
int r,y;
r=jj;
y=kk+1;
while( y!=r ){
if( Rename_Narray[r] < vv ){
y=r;
} else{
r=r+1;
};
}
*(bb)=((r!=kk+1)!=0);
*(ii)=r;
}
void
#ifdef _BT_ANSIC
Rename_SCH_HI_EQL_NARR( int *bb, int *ii, int jj, int kk, int vv )
#else
Rename_SCH_HI_EQL_NARR( bb, ii, jj, kk, vv )
int *bb;
int *ii;
int jj, kk, vv;
#endif
{
int r,y;
r=kk;
y=jj-1;
while( y!=r ){
if( Rename_Narray[r] == vv ){
y=r;
} else{
r=r-1;
};
}
*(bb)=((r!=jj-1)!=0);
*(ii)=r;
}
void
#ifdef _BT_ANSIC
Rename_SCH_HI_NEQ_NARR( int *bb, int *ii, int jj, int kk, int vv )
#else
Rename_SCH_HI_NEQ_NARR( bb, ii, jj, kk, vv )
int *bb;
int *ii;
int jj, kk, vv;
#endif
{
int r,y;
r=kk;
y=jj-1;
while( y!=r ){
if( Rename_Narray[r] != vv ){
y=r;
} else{
r=r-1;
};
}
*(bb)=((r!=jj-1)!=0);
*(ii)=r;
}
void
#ifdef _BT_ANSIC
Rename_SCH_HI_GEQ_NARR( int *bb, int *ii, int jj, int kk, int vv )
#else
Rename_SCH_HI_GEQ_NARR( bb, ii, jj, kk, vv )
int *bb;
int *ii;
int jj, kk, vv;
#endif
{
int r,y;
r=kk;
y=jj-1;
while( y!=r ){
if( Rename_Narray[r] >= vv ){
y=r;
} else{
r=r-1;
};
}
*(bb)=((r!=jj-1)!=0);
*(ii)=r;
}
void
#ifdef _BT_ANSIC
Rename_SCH_HI_GTR_NARR( int *bb, int *ii, int jj, int kk, int vv )
#else
Rename_SCH_HI_GTR_NARR( bb, ii, jj, kk, vv )
int *bb;
int *ii;
int jj, kk, vv;
#endif
{
int r,y;
r=kk;
y=jj-1;
while( y!=r ){
if( Rename_Narray[r] > vv ){
y=r;
} else{
r=r-1;
};
}
*(bb)=((r!=jj-1)!=0);
*(ii)=r;
}
void
#ifdef _BT_ANSIC
Rename_SCH_HI_LEQ_NARR( int *bb, int *ii, int jj, int kk, int vv )
#else
Rename_SCH_HI_LEQ_NARR( bb, ii, jj, kk, vv )
int *bb;
int *ii;
int jj, kk, vv;
#endif
{
int r,y;
r=kk;
y=jj-1;
while( y!=r ){
if( Rename_Narray[r] <= vv ){
y=r;
} else{
r=r-1;
};
}
*(bb)=((r!=jj-1)!=0);
*(ii)=r;
}
void
#ifdef _BT_ANSIC
Rename_SCH_HI_SMR_NARR( int *bb, int *ii, int jj, int kk, int vv )
#else
Rename_SCH_HI_SMR_NARR( bb, ii, jj, kk, vv )
int *bb;
int *ii;
int jj, kk, vv;
#endif
{
int r,y;
r=kk;
y=jj-1;
while( y!=r ){
if( Rename_Narray[r] < vv ){
y=r;
} else{
r=r-1;
};
}
*(bb)=((r!=jj-1)!=0);
*(ii)=r;
}
void
#ifdef _BT_ANSIC
Rename_SRT_ASC_NARR( int ii, int jj )
#else
Rename_SRT_ASC_NARR( ii, jj )
int ii, jj;
#endif
{
int i,v,b,r;
i=ii;
while( i<jj ){
Rename_VAL_NARR(&v,i+1);
Rename_SCH_LO_GTR_NARR(&b,&r,ii,i,v);
if( b==1 ){
Rename_RHT_NARR(r,i,1);
Rename_STO_NARR(r,v);
};
i=i+1;
};
}
void
#ifdef _BT_ANSIC
Rename_SRT_DSC_NARR( int ii, int jj )
#else
Rename_SRT_DSC_NARR( ii, jj )
int ii, jj;
#endif
{
int i,v,b,r;
i=ii;
while( i<jj ){
Rename_VAL_NARR(&v,i+1);
Rename_SCH_LO_SMR_NARR(&b,&r,ii,i,v);
if( b==1 ){
Rename_RHT_NARR(r,i,1);
Rename_STO_NARR(r,v);
};
i=i+1;
};
}
void
#ifdef _BT_ANSIC
Rename_REV_NARR( int ii, int jj )
#else
Rename_REV_NARR( ii, jj )
int ii, jj;
#endif
{
int i,j;
i=ii;
j=jj;
while( i<j ){
Rename_SWP_NARR(i,j);
i=i+1;
j=j-1;
};
}
void
#ifdef _BT_ANSIC
Rename_RHT_NARR( int ii, int jj, int nn )
#else
Rename_RHT_NARR( ii, jj, nn )
int ii, jj, nn;
#endif
{
int k,n;
n=jj-ii+1;
k=0;
while( k<n ){
if( jj+nn-k<=Rename_NarrP2 ){
Rename_Narray[jj+nn-k]=Rename_Narray[jj-k];
}
k=k+1;
};
}
void
#ifdef _BT_ANSIC
Rename_LFT_NARR( int ii, int jj, int nn )
#else
Rename_LFT_NARR( ii, jj, nn )
int ii, jj, nn;
#endif
{
int k,n;
n=jj-ii+1;
k=0;
while( k<n ){
if( ii-nn+k>=1 ){
Rename_Narray[ii-nn+k]=Rename_Narray[ii+k];
}
k=k+1;
};
}
| 15.208333 | 75 | 0.613818 | [
"object"
] |
3eaca9605c9d39067009975e8cc3780a6058b9ac | 97,041 | c | C | broadband/lib/src/xcal-device-library.c | rdkcmf/rdk-xupnp | 089497d8984905992dabec459c62b35102a283ca | [
"Apache-2.0"
] | null | null | null | broadband/lib/src/xcal-device-library.c | rdkcmf/rdk-xupnp | 089497d8984905992dabec459c62b35102a283ca | [
"Apache-2.0"
] | null | null | null | broadband/lib/src/xcal-device-library.c | rdkcmf/rdk-xupnp | 089497d8984905992dabec459c62b35102a283ca | [
"Apache-2.0"
] | 1 | 2018-08-16T19:12:44.000Z | 2018-08-16T19:12:44.000Z | /*
* If not stated otherwise in this file or this component's Licenses.txt file the
* following copyright and licenses apply:
*
* Copyright 2018 RDK Management
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <glib.h>
#include <sys/types.h>
#include <libsoup/soup.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <stdbool.h>
#include "xdevice-library-private.h"
#include "syscfg/syscfg.h"
#include <glib/gprintf.h>
#include <glib/gstdio.h>
#include <arpa/inet.h>
#include <platform_hal.h>
#include "rdk_safeclib.h"
#include "secure_wrapper.h"
#ifndef INET6_ADDRSTRLEN
#define INET6_ADDRSTRLEN 46
#endif
#define MAXSIZE 256
#ifndef BOOL
#define BOOL unsigned char
#endif
#define ISOLATION_IF "brlan10"
#define PRIVATE_LAN_BRIDGE "brlan0"
#define WIFI_IF "brlan0:0"
#define UDN_IF "erouter0"
#define PARTNER_ID "partnerId"
#define RECEIVER_ID "deviceId"
#define BCAST_PORT 50755
#define LOG_FILE "/rdklogs/logs/xdevice.log"
#define DEVICE_XML_PATH "/etc/xupnp/"
#define DEVICE_XML_FILE "BasicDevice.xml"
#define BROADBAND_DEVICE_XML_FILE "X1BroadbandGateway.xml"
#define MAX_FILE_LENGTH 256
#define MAX_OUTVALUE 256
#define RUIURLSIZE 2048
#define URLSIZE 512
#define DEVICE_KEY_PATH "/tmp/"
#define DEVICE_KEY_FILE "icebergwedge_y"
#define DEVICE_CERT_PATH "/tmp/"
#define DEVICE_CERT_FILE "icebergwedge_t"
#define LINK_LOCAL_ADDR "169.254"
#ifndef F_OK
#define F_OK 0
#endif
#ifndef BOOL
#define BOOL unsigned char
#endif
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#ifndef RETURN_OK
#define RETURN_OK 0
#endif
#ifndef RETURN_ERR
#define RETURN_ERR -1
#endif
typedef enum serviceListCb {
SERIAL_NUMBER,
IPV6_PREFIX,
TUNE_READY,
} serviceListCb;
#define DEVICE_PROPERTY_FILE "/etc/device.properties"
#define AUTH_SERVER_URL "http://localhost:50050/authService/getDeviceId"
#define DEVICE_NAME_FILE "/opt/hn_service_settings.conf"
#define HST_RAWOFFSET (-11 * 60 * 60 * 1000)
#define AKST_RAWOFFSET (-9 * 60 * 60 * 1000)
#define PST_RAWOFFSET (-8 * 60 * 60 * 1000)
#define MST_RAWOFFSET (-7 * 60 * 60 * 1000)
#define CST_RAWOFFSET (-6 * 60 * 60 * 1000)
#define EST_RAWOFFSET (-5 * 60 * 60 * 1000)
gboolean ipv6Enabled = FALSE;
char ipAddressBuffer[INET6_ADDRSTRLEN] = {0};
char stbipAddressBuffer[INET6_ADDRSTRLEN] = {0};
#if 0
static struct TZStruct {
char *inputTZ;
char *javaTZ;
int rawOffset;
gboolean usesDST;
} tzStruct[] = {
{"HST11", "US/Hawaii", HST_RAWOFFSET, 1},
{"HST11HDT,M3.2.0,M11.1.0", "US/Hawaii", HST_RAWOFFSET, 1},
{"AKST", "US/Alaska", AKST_RAWOFFSET, 1},
{"AKST09AKDT", "US/Alaska", AKST_RAWOFFSET, 1},
{"PST08", "US/Pacific", PST_RAWOFFSET, 1},
{"PST08PDT,M3.2.0,M11.1.0", "US/Pacific", PST_RAWOFFSET, 1},
{"MST07", "US/Mountain", MST_RAWOFFSET, 1},
{"MST07MDT,M3.2.0,M11.1.0", "US/Mountain", MST_RAWOFFSET, 1},
{"CST06", "US/Central", CST_RAWOFFSET, 1},
{"CST06CDT,M3.2.0,M11.1.0", "US/Central", CST_RAWOFFSET, 1},
{"EST05", "US/Eastern", EST_RAWOFFSET, 1},
{"EST05EDT,M3.2.0,M11.1.0", "US/Eastern", EST_RAWOFFSET, 1}
};
#endif
#define COMCAST_PARTNET_KEY "comcast"
#define COX_PARTNET_KEY "cox"
ConfSettings *devConf;
#define ARRAY_COUNT(array) (sizeof(array)/sizeof(array[0]))
#if 0
static STRING_MAP partnerNameMap[] = {
{COMCAST_PARTNET_KEY, "comcast"},
{COX_PARTNET_KEY , "cox"},
};
static STRING_MAP friendlyNameMap[] = {
{COMCAST_PARTNET_KEY, "XFINITY"},
{COX_PARTNET_KEY , "Contour"},
};
static STRING_MAP productNameMap[] = {
{COMCAST_PARTNET_KEY, "xfinity"},
{COX_PARTNET_KEY , "contour"},
};
static STRING_MAP serviceNameMap[] = {
{COMCAST_PARTNET_KEY, "Comcast XFINITY Guide"},
{COX_PARTNET_KEY , "Cox Contour Guide"},
};
static STRING_MAP serviceDescriptionMap[] = {
{COMCAST_PARTNET_KEY, "Comcast XFINITY Guide application"},
{COX_PARTNET_KEY , "Cox Contour Guide application"},
};
static STRING_MAP gatewayNameMap[] = {
{COMCAST_PARTNET_KEY, "Comcast Gateway"},
{COX_PARTNET_KEY , "Cox Gateway"},
};
#endif
xupnpEventCallback eventCallback;
void xupnpEventCallback_register(xupnpEventCallback callback_func)
{
eventCallback=callback_func;
}
int check_rfc()
{
errno_t rc = -1;
int ind = -1;
char temp[24] = {0};
if (!syscfg_get(NULL, "Refactor", temp, sizeof(temp)) )
{
if(temp != NULL)
{
rc = strcmp_s("true",strlen("true"),temp,&ind);
ERR_CHK(rc);
if((!ind) && (rc == EOK))
{
g_message("New Device Refactoring rfc_enabled");
return 1;
}
}
}
else
{
g_message("check_rfc: Failed Unable to find the RFC parameter");
}
return 0;
}
BOOL getAccountId(char *outValue)
{
char temp[24] = {0};
int rc;
errno_t rc1 = -1;
rc = syscfg_get(NULL, "AccountID", temp, sizeof(temp));
if(!rc)
{
if (check_null(outValue))
{
rc1 = strcpy_s(outValue,MAX_OUTVALUE,temp);
if(rc1 == EOK)
{
return TRUE;
}
else
{
ERR_CHK(rc1);
}
}
}
else
{
g_message("getAccountId: Unable to get the Account Id");
}
return FALSE;
}
gboolean getserialnum(GString* serial_num)
{
gboolean result = FALSE;
if ( platform_hal_PandMDBInit() == 0)
{
g_message("getserialnum: hal PandMDB initiated successfully");
if ( platform_hal_GetSerialNumber(serial_num->str) == 0)
{
g_message("getserialnum: serialNumber from hal:%s", serial_num->str);
result = TRUE;
}
else
{
g_error("getserialnum: Unable to get SerialNumber");
}
}
else
{
g_message("getserialnum: Failed to initiate hal DB to fetch SerialNumber");
}
return result;
}
void xupnp_logger (const gchar *log_domain, GLogLevelFlags log_level,
const gchar *message, gpointer user_data)
{
GTimeVal timeval;
char *timestr;
g_get_current_time(&timeval);
if (logoutfile == NULL)
{
// Fall back to console output if unable to open file
g_print (" g_time_val_to_iso8601(&timeval): %s\n", message);
return;
}
timestr = g_time_val_to_iso8601(&timeval);
g_fprintf (logoutfile, "%s : %s\n", timestr, message);
g_free(timestr);
fflush(logoutfile);
}
/**
* @brief This function is used to get partner ID.
*
* @return Returns partner ID.
* @ingroup XUPNP_XCALDEV_FUNC
*/
#if 0
static char *getPartnerID()
{
return partner_id->str;
}
#endif
#ifndef BROADBAND_SUPPORT
#if 0
/**
* @brief This function is used to get the IP address based on IPv6 or IPv4 is enabled.
*
* @param[in] ifname Name of the network interface.
* @param[out] ipAddressBuffer Character buffer to hold the IP address.
* @param[in] ipv6Enabled Flag to check whether IPV6 is enabled
*
* @return Returns an integer value '1' if successfully gets the IP address else returns '0'.
* @ingroup XUPNP_XCALDEV_FUNC
*/
static char *getPartnerName()
{
return getStrValueFromMap(getPartnerID(), ARRAY_COUNT(partnerNameMap),
partnerNameMap);
}
/**
* @brief This function is used to get the IP address based on IPv6 or IPv4 is enabled.
*
* @param[in] ifname Name of the network interface.
* @param[out] ipAddressBuffer Character buffer to hold the IP address.
* @param[in] ipv6Enabled Flag to check whether IPV6 is enabled
*
* @return Returns an integer value '1' if successfully gets the IP address else returns '0'.
* @ingroup XUPNP_XCALDEV_FUNC
*/
static char *getFriendlyName()
{
return getStrValueFromMap(getPartnerID(), ARRAY_COUNT(friendlyNameMap),
friendlyNameMap);
}
/**
* @brief This function is used to get the IP address based on IPv6 or IPv4 is enabled.
*
* @param[in] ifname Name of the network interface.
* @param[out] ipAddressBuffer Character buffer to hold the IP address.
* @param[in] ipv6Enabled Flag to check whether IPV6 is enabled
*
* @return Returns an integer value '1' if successfully gets the IP address else returns '0'.
* @ingroup XUPNP_XCALDEV_FUNC
*/
static char *getProductName()
{
return getStrValueFromMap(getPartnerID(), ARRAY_COUNT(productNameMap),
productNameMap);
}
/**
* @brief This function is used to get the IP address based on IPv6 or IPv4 is enabled.
*
* @param[in] ifname Name of the network interface.
* @param[out] ipAddressBuffer Character buffer to hold the IP address.
* @param[in] ipv6Enabled Flag to check whether IPV6 is enabled
*
* @return Returns an integer value '1' if successfully gets the IP address else returns '0'.
* @ingroup XUPNP_XCALDEV_FUNC
*/
static char *getServiceName()
{
return getStrValueFromMap(getPartnerID(), ARRAY_COUNT(serviceNameMap),
serviceNameMap);
}
/**
* @brief This function is used to get the IP address based on IPv6 or IPv4 is enabled.
*
* @param[in] ifname Name of the network interface.
* @param[out] ipAddressBuffer Character buffer to hold the IP address.
* @param[in] ipv6Enabled Flag to check whether IPV6 is enabled
*
* @return Returns an integer value '1' if successfully gets the IP address else returns '0'.
* @ingroup XUPNP_XCALDEV_FUNC
*/
static char *getServiceDescription()
{
return getStrValueFromMap(getPartnerID(), ARRAY_COUNT(serviceDescriptionMap),
serviceDescriptionMap);
}
/**
* @brief This function is used to get the IP address based on IPv6 or IPv4 is enabled.
*
* @param[in] ifname Name of the network interface.
* @param[out] ipAddressBuffer Character buffer to hold the IP address.
* @param[in] ipv6Enabled Flag to check whether IPV6 is enabled
*
* @return Returns an integer value '1' if successfully gets the IP address else returns '0'.
* @ingroup XUPNP_XCALDEV_FUNC
*/
static char *getGatewayName()
{
return getStrValueFromMap(getPartnerID(), ARRAY_COUNT(gatewayNameMap),
gatewayNameMap);
}
#endif
#endif
/**
* @brief This function is used to retrieve the information from the device file.
*
* @param[in] deviceFile Name of the device configuration file.
*
* @return Returns TRUE if successfully reads the device file else returns FALSE.
* @ingroup XUPNP_XCALDEV_FUNC
*/
gboolean readDevFile(const char *deviceFile)
{
GError *error=NULL;
gboolean result = FALSE;
gchar* devfilebuffer = NULL;
gchar counter=0;
if (deviceFile == NULL)
{
g_message("device properties file not found");
return result;
}
result = g_file_get_contents (deviceFile, &devfilebuffer, NULL, &error);
if (result == FALSE)
{
g_message("No contents in device properties");
}
else
{
/* reset result = FALSE to identify device properties from devicefile contents */
result = FALSE;
gchar **tokens = g_strsplit_set(devfilebuffer,",='\n'", -1);
guint toklength = g_strv_length(tokens);
guint loopvar=0;
for (loopvar=0; loopvar<toklength; loopvar++)
{
if (g_strrstr(g_strstrip(tokens[loopvar]), "DEVICE_TYPE"))
{
if ((loopvar+1) < toklength )
{
counter++;
g_string_assign(recvdevtype, g_strstrip(tokens[loopvar+1]));
}
if (counter == 6)
{
result = TRUE;
break;
}
}
else if(g_strrstr(g_strstrip(tokens[loopvar]), "BUILD_VERSION"))
{
if ((loopvar+1) < toklength )
{
counter++;
g_string_assign(buildversion, g_strstrip(tokens[loopvar+1]));
}
if (counter == 6)
{
result = TRUE;
break;
}
}
else if(g_strrstr(g_strstrip(tokens[loopvar]), "BOX_TYPE"))
{
if ((loopvar+1) < toklength )
{
counter++;
g_string_assign(devicetype, g_strstrip(tokens[loopvar+1]));
}
if (counter == 6)
{
result = TRUE;
break;
}
}
else if(g_strrstr(g_strstrip(tokens[loopvar]), "MODEL_NUM"))
{
if ((loopvar+1) < toklength )
{
counter++;
g_string_assign(devicename, g_strstrip(tokens[loopvar+1]));
}
if (counter == 6)
{
result = TRUE;
break;
}
}
if (g_strrstr(g_strstrip(tokens[loopvar]), "MFG_NAME"))
{
if ((loopvar+1) < toklength )
{
counter++;
g_string_assign(make, g_strstrip(tokens[loopvar+1]));
}
if (counter == 6)
{
result = TRUE;
break;
}
}
else
{
if (g_strrstr(g_strstrip(tokens[loopvar]), "MANUFACTURE"))
{
if ((loopvar+1) < toklength )
{
counter++;
g_string_assign(make, g_strstrip(tokens[loopvar+1]));
}
if (counter == 6)
{
result = TRUE;
break;
}
}
}
}
g_strfreev(tokens);
}
g_string_printf(mocaIface,"%s",ISOLATION_IF);
g_string_printf(wifiIface,"%s",WIFI_IF);
if(result == FALSE)
{
g_message("RECEIVER_DEVICETYPE and BUILD_VERSION not found in %s",deviceFile);
}
if(error)
{
/* g_clear_error() frees the GError *error memory and reset pointer if set in above operation */
g_clear_error(&error);
}
//diagid=1000;
return result;
}
/**
* @brief Supporting function for checking the content of given string is numeric or not.
*
* @param[in] str String for which the contents need to be verified.
*
* @return Returns TRUE if successfully checks the string is numeric else returns FALSE.
* @ingroup XUPNP_XCALDEV_FUNC
*/
gboolean is_num(const gchar *str)
{
unsigned int i=0;
gboolean isnum = TRUE;
for (i = 0; i < strlen(str); i++) {
if (!g_ascii_isdigit(str[i])) {
isnum = FALSE;
break;
}
}
return isnum;
}
/**
* @brief This function is used to get the IP address based on IPv6 or IPv4 is enabled.
*
* @param[in] ifname Name of the network interface.
* @param[out] ipAddressBuffer Character buffer to hold the IP address.
* @param[in] ipv6Enabled Flag to check whether IPV6 is enabled
*
* @return Returns an integer value '1' if successfully gets the IP address else returns '0'.
* @ingroup XUPNP_XCALDEV_FUNC
*/
BOOL check_empty(char *str)
{
if (str[0]) {
return TRUE;
}
return FALSE;
}
BOOL check_null(char *str)
{
if (str) {
return TRUE;
}
return FALSE;
}
/**
* @brief This function is used to get the IP address based on IPv6 or IPv4 is enabled.
*
* @param[in] ifname Name of the network interface.
* @param[out] ipAddressBuffer Character buffer to hold the IP address.
* @param[in] ipv6Enabled Flag to check whether IPV6 is enabled
*
* @return Returns an integer value '1' if successfully gets the IP address else returns '0'.
* @ingroup XUPNP_XCALDEV_FUNC
*/
BOOL getBaseUrl(char *outValue)
{
BOOL result = FALSE;
if ((!check_null((char *)gwyip)) || (!check_null(outValue)) || (!check_null((char *)recv_id))) {
g_message("getBaseUrl : NULL string !");
return result;
}
if (check_empty(gwyip->str) && check_empty(recv_id->str)) {
g_string_printf(url, "http://%s:8080/videoStreamInit?recorderId=%s",
gwyip->str, recv_id->str);
g_message ("The url is now %s.", url->str);
result = TRUE;
}
else
{
g_message("getBaseUrl : Empty url");
}
return result;
}
/**
* @brief This function is used to get the IP address based on IPv6 or IPv4 is enabled.
*
* @param[in] ifname Name of the network interface.
* @param[out] ipAddressBuffer Character buffer to hold the IP address.
* @param[in] ipv6Enabled Flag to check whether IPV6 is enabled
*
* @return Returns an integer value '1' if successfully gets the IP address else returns '0'.
* @ingroup XUPNP_XCALDEV_FUNC
*/
BOOL getFogTsbUrl(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if (!check_null(outValue)) {
g_message("getFogTsbUrl : NULL string !");
return result;
}
if (fogtsburl->str) {
rc = strcpy_s(outValue,MAX_OUTVALUE,fogtsburl->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
} else {
g_message("getFogTsbUrl : No fogtsb url !");
}
return result;
}
/**
* @brief This function is used to get the IP address based on IPv6 or IPv4 is enabled.
*
* @param[in] ifname Name of the network interface.
* @param[out] ipAddressBuffer Character buffer to hold the IP address.
* @param[in] ipv6Enabled Flag to check whether IPV6 is enabled
*
* @return Returns an integer value '1' if successfully gets the IP address else returns '0'.
* @ingroup XUPNP_XCALDEV_FUNC
*/
BOOL getIpv6Prefix(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if (!check_null(outValue)) {
g_message("getIpv6Prefix : NULL string !");
return result;
}
if (parseipv6prefix()) {
rc = strcpy_s(outValue,MAX_OUTVALUE,ipv6prefix->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
} else {
g_message("getIpv6Prefix : No ipv6 prefix !");
}
return result;
}
/**
* @brief This function is used to get the IP address based on IPv6 or IPv4 is enabled.
*
* @param[in] ifname Name of the network interface.
* @param[out] ipAddressBuffer Character buffer to hold the IP address.
* @param[in] ipv6Enabled Flag to check whether IPV6 is enabled
*
* @return Returns an integer value '1' if successfully gets the IP address else returns '0'.
* @ingroup XUPNP_XCALDEV_FUNC
*/
BOOL getDeviceName(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if (!check_null(outValue)) {
g_message("getDeviceName : NULL string !");
return result;
}
if(devicename->str != NULL) {
rc = strcpy_s(outValue,MAX_OUTVALUE,devicename->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
} else {
g_message("getDeviceName : No Device Name !");
}
return result;
}
/**
* @brief This function is used to get the IP address based on IPv6 or IPv4 is enabled.
*
* @param[in] ifname Name of the network interface.
* @param[out] ipAddressBuffer Character buffer to hold the IP address.
* @param[in] ipv6Enabled Flag to check whether IPV6 is enabled
*
* @return Returns an integer value '1' if successfully gets the IP address else returns '0'.
* @ingroup XUPNP_XCALDEV_FUNC
*/
BOOL getDeviceType(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if ((!check_null((char *)devicetype)) || (!check_null(outValue))) {
g_message("getDeviceType : NULL string !");
return result;
}
if (check_empty(devicetype->str)) {
rc = strcpy_s(outValue,MAX_OUTVALUE,devicetype->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
}
else
{
g_message("getDeviceType : Empty device type");
}
return result;
}
/**
* @brief This function is used to get the IP address based on IPv6 or IPv4 is enabled.
*
* @param[in] ifname Name of the network interface.
* @param[out] ipAddressBuffer Character buffer to hold the IP address.
* @param[in] ipv6Enabled Flag to check whether IPV6 is enabled
*
* @return Returns an integer value '1' if successfully gets the IP address else returns '0'.
* @ingroup XUPNP_XCALDEV_FUNC
*/
BOOL getBcastMacAddress(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if (!check_null(outValue)) {
g_message("getBcastMacAddress : NULL string !");
return result;
}
if (devConf->bcastIf != NULL ) {
const gchar *bcastmac = (gchar *)getmacaddress(devConf->bcastIf);
if (bcastmac) {
g_message("Broadcast MAC address in interface: %s %s ", devConf->bcastIf,
bcastmac);
} else {
g_message("failed to retrieve macaddress on interface %s ", devConf->bcastIf);
return result;
}
g_string_assign(bcastmacaddress, bcastmac);
g_message("bcast mac address is %s", bcastmacaddress->str);
rc = strcpy_s(outValue,MAX_OUTVALUE,bcastmacaddress->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
}
else
{
g_message("getBcastMacAddress : Empty broadcast interface");
}
return result;
}
/**
* @brief This function is used to get the IP address based on IPv6 or IPv4 is enabled.
*
* @param[in] ifname Name of the network interface.
* @param[out] ipAddressBuffer Character buffer to hold the IP address.
* @param[in] ipv6Enabled Flag to check whether IPV6 is enabled
*
* @return Returns an integer value '1' if successfully gets the IP address else returns '0'.
* @ingroup XUPNP_XCALDEV_FUNC
*/
BOOL getGatewayStbIp(char *outValue)
{
BOOL result = FALSE;
if ((!check_null((char *)gwystbip)) || (!check_null(outValue))) {
g_message("getGatewayStbIp : NULL string !");
return result;
}
#ifndef CLIENT_XCAL_SERVER
errno_t rc = -1;
if (check_empty(gwystbip->str)) {
rc = strcpy_s(outValue,MAX_OUTVALUE,gwystbip->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
}
#endif
return result;
}
/**
* @brief This function is used to get the IP address based on IPv6 or IPv4 is enabled.
*
* @param[in] ifname Name of the network interface.
* @param[out] ipAddressBuffer Character buffer to hold the IP address.
* @param[in] ipv6Enabled Flag to check whether IPV6 is enabled
*
* @return Returns an integer value '1' if successfully gets the IP address else returns '0'.
* @ingroup XUPNP_XCALDEV_FUNC
*/
BOOL getGatewayIpv6(char *outValue)
{
BOOL result = FALSE;
if ((!check_null((char *)gwyipv6)) || (!check_null(outValue))) {
g_message("getGatewayIpv6 : NULL string !");
return result;
}
#ifndef CLIENT_XCAL_SERVER
errno_t rc = -1;
if (check_empty(gwyipv6->str)) {
rc = strcpy_s(outValue,MAX_OUTVALUE,gwyipv6->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
}
#endif
return result;
}
/**
* @brief This function is used to get the IP address based on IPv6 or IPv4 is enabled.
*
* @param[in] ifname Name of the network interface.
* @param[out] ipAddressBuffer Character buffer to hold the IP address.
* @param[in] ipv6Enabled Flag to check whether IPV6 is enabled
*
* @return Returns an integer value '1' if successfully gets the IP address else returns '0'.
* @ingroup XUPNP_XCALDEV_FUNC
*/
BOOL getGatewayIp(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if ((!check_null((char *)gwyip)) || (!check_null(outValue))) {
g_message("getGatewayIp : NULL string !");
return result;
}
if (check_empty(gwyip->str)) {
rc = strcpy_s(outValue,MAX_OUTVALUE,gwyip->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
}
else
{
g_message("getGatewayIp : Empty gateway ip");
}
return result;
}
/**
* @brief This function is used to get the IP address based on IPv6 or IPv4 is enabled.
*
* @param[in] ifname Name of the network interface.
* @param[out] ipAddressBuffer Character buffer to hold the IP address.
* @param[in] ipv6Enabled Flag to check whether IPV6 is enabled
*
* @return Returns an integer value '1' if successfully gets the IP address else returns '0'.
* @ingroup XUPNP_XCALDEV_FUNC
*/
BOOL getRecvDevType(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if ((!check_null((char *)recvdevtype)) || (!check_null(outValue))) {
g_message("getRecvDevType : NULL string !");
return result;
}
if (check_empty(recvdevtype->str)) {
rc = strcpy_s(outValue,MAX_OUTVALUE,recvdevtype->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
}
else
{
g_message("getRecvDevType : Empty receiver device type");
}
return result;
}
BOOL getBuildVersion(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if ((!check_null((char *)buildversion)) || (!check_null(outValue))) {
g_message("getBuildVersion : NULL string !");
return result;
}
if (check_empty(buildversion->str)) {
rc = strcpy_s(outValue,MAX_OUTVALUE,buildversion->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
}
else
{
g_message("getBuildVersion : Empty Build version");
}
return result;
}
BOOL getHostMacAddress(char *outValue)
{
BOOL result = FALSE;
if (!(check_null((char *)hostmacaddress)) || (!check_null(outValue))) {
g_message("getHostMacAddress : NULL string !");
return result;
}
#ifndef CLIENT_XCAL_SERVER
errno_t rc = -1;
if (devConf->hostMacIf != NULL) {
const gchar *hostmac = (gchar *)getmacaddress(devConf->hostMacIf);
if (hostmac) {
g_message("MAC address in interface: %s %s ", devConf->hostMacIf, hostmac);
} else {
g_message("failed to retrieve macaddress on interface %s ",
devConf->hostMacIf);
}
g_string_assign(hostmacaddress, hostmac);
g_message("Host mac address is %s", hostmacaddress->str);
rc = strcpy_s(outValue,MAX_OUTVALUE,hostmacaddress->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
}
#endif
return result;
}
BOOL getDnsConfig(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if (!check_null(outValue)) {
g_message("getDnsConfig : NULL string !");
return result;
}
if (parsednsconfig()) {
rc = strcpy_s(outValue,MAX_OUTVALUE,dnsconfig->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
} else {
g_message("getDnsConfig : no dns config !");
}
return result;
}
BOOL getSystemsIds(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if ((!check_null((char *)systemids)) || (!check_null(outValue))) {
g_message("getSystemsIds : NULL string !");
return result;
}
if (check_empty(systemids->str)) {
rc = strcpy_s(outValue,MAX_OUTVALUE,systemids->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
}
else
{
g_message("getSystemsIds : empty system ids");
}
return result;
}
gboolean gettimezone(void)
{
GError *error=NULL;
gboolean result = FALSE;
gchar* dsgproxyfile = NULL;
if (devConf->dsgFile == NULL)
{
g_warning("dsg file name not found in config");
return result;
}
result = g_file_get_contents (devConf->dsgFile, &dsgproxyfile, NULL, &error);
/* Coverity Fix for CID: 124792: Forward NULL */
if (result == FALSE) {
g_warning("Problem in reading dsgproxyfile file %s",
error ? error->message : "NULL");
}
else
{
/* reset result = FALSE to identify timezone from dsgproxyfile contents */
result = FALSE;
gchar **tokens = g_strsplit_set(dsgproxyfile,",=", -1);
guint toklength = g_strv_length(tokens);
guint loopvar=0;
for (loopvar=0; loopvar<toklength; loopvar++)
{
//g_print("Token is %s\n",g_strstrip(tokens[loopvar]));
if (g_strrstr(g_strstrip(tokens[loopvar]), "DSGPROXY_HOST_TIME_ZONE"))
{
if ((loopvar+1) < toklength )
{
g_string_assign(dsgtimezone, g_strstrip(tokens[loopvar+1]));
}
result = TRUE;
break;
}
}
g_strfreev(tokens);
}
//diagid=1000;
if(error)
{
/* g_clear_error() frees the GError *error memory and reset pointer if set in above operation */
g_clear_error(&error);
}
return result;
}
BOOL getIpSubnet(char *outValue)
{
BOOL result = FALSE;
int ret = 0;
if (!check_null(outValue)) {
g_message("getIpSubnet : NULL string !");
return result;
}
FILE *fp = NULL;
if(!(fp = v_secure_popen("r", "ip -4 route show dev "PRIVATE_LAN_BRIDGE " | grep -v "LINK_LOCAL_ADDR " | grep src | awk '{print $1}'")))
{
return result;
}
while(fgets(outValue, sizeof(MAX_OUTVALUE), fp)!=NULL)
{
size_t len = strlen(outValue);
if (len > 0 && outValue[len-1] == '\n') {
outValue[len-1] = '\0';
}
}
ret = v_secure_pclose(fp);
if(ret != 0)
{
g_message("Error in closing pipe ! : %d \n", ret);
}
else {
result = TRUE;
}
return result;
}
BOOL getTimeZone(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if ((!check_null((char *)dsgtimezone)) || (!check_null(outValue))) {
g_message("getTimeZone : NULL string !");
return result;
}
if (check_empty(dsgtimezone->str)) {
rc = strcpy_s(outValue,MAX_OUTVALUE, dsgtimezone->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
}
else
{
g_message("getTimeZone : Empty timezone");
}
return result;
}
BOOL getRawOffSet(int *outValue)
{
*outValue = rawOffset;
return TRUE;
}
BOOL getDstSavings(int *outValue)
{
*outValue = dstSavings;
return TRUE;
}
BOOL getUsesDayLightTime(BOOL *outValue)
{
*outValue = usesDaylightTime;
return TRUE;
}
BOOL getIsGateway(BOOL *outValue)
{
*outValue = devConf->allowGwy;
return TRUE;
}
BOOL getHosts(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if (!check_null(outValue)) {
g_message("getHosts : NULL string !");
return result;
}
if (check_empty(etchosts->str)) {
rc = strcpy_s(outValue,RUIURLSIZE,etchosts->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
} else {
g_message("getHosts : No Hosts Data available !");
}
return result;
}
BOOL getRequiresTRM(BOOL *outValue)
{
*outValue = requirestrm;
return TRUE;
}
BOOL getBcastPort(int *outValue)
{
*outValue = devConf->bcastPort;
return TRUE;
}
BOOL getBcastIp(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if ((!check_null((char *)gwyip)) || (!check_null(outValue))) {
g_message("getBcastIp : NULL string !");
return result;
}
if (check_empty(gwyip->str)) {
rc = strcpy_s(outValue,MAX_OUTVALUE,gwyip->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
}
else
{
g_message("getBcastIp : Empty Broadcast Ip");
}
return result;
}
BOOL getBcastIf(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if (!check_null(outValue)) {
g_message("getBcastIf : NULL string !");
return result;
}
if(check_empty(devConf->bcastIf)) {
rc = strcpy_s(outValue, MAXSIZE, devConf->bcastIf);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
}
else
g_message("getBcastIf : No Bcast Interface found !");
return result;
}
/**
* @brief Supporting function for checking the given string is alphanumeric.
*
* @param[in] str String to be verified.
*
* @return Returns TRUE if successfully checks the string is alphanumeric else returns FALSE.
* @ingroup XUPNP_XCALDEV_FUNC
*/
gboolean is_alphanum(const gchar *str)
{
unsigned int i=0;
gboolean isalphanum = TRUE;
for (i = 0; i < strlen(str); i++) {
if (!g_ascii_isalnum(str[i])) {
isalphanum = FALSE;
break;
}
}
return isalphanum;
}
BOOL getRUIUrl(char *outValue)
{
return TRUE;
}
BOOL getSerialNum(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if (!check_null(outValue)) {
g_message("getSerialNum : NULL string !");
return result;
}
if(check_empty(serial_num->str)) {
rc = strcpy_s(outValue,MAX_OUTVALUE,serial_num->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
} else {
g_message("getSerialNum : No Serial Number Available !");
}
return result;
}
BOOL getPartnerId(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if (!check_null(outValue)) {
g_message("getPartnerId : NULL string !");
return result;
} else {
if (check_null((char *)partner_id) && check_empty(partner_id->str)) {
rc = strcpy_s(outValue,MAX_OUTVALUE,partner_id->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
}
else
{
g_message("getPartnerId : No partnerId available");
}
}
return result;
}
BOOL getDevKeyPath(char *outValue)
{
BOOL result = FALSE;
if ((!check_null(devConf->devKeyPath)) || (!check_null(outValue))) {
g_message("getDevKeyPath: NULL string !");
return result;
}
if (check_empty(devConf->devKeyPath)) {
strncpy(outValue,devConf->devKeyPath, MAX_FILE_LENGTH);
result = TRUE;
} else
g_message("getDevKeyPath : config has empty key path !");
return result;
}
BOOL getDevKeyFile(char *outValue)
{
BOOL result = FALSE;
if ((!check_null(devConf->devKeyFile)) || (!check_null(outValue))) {
g_message("getDevKeyFile : NULL string !");
return result;
}
if (check_empty(devConf->devKeyFile)) {
strncpy(outValue,devConf->devKeyFile, MAX_FILE_LENGTH);
result = TRUE;
} else
g_message("getDevKeyFile : config has empty key file !");
return result;
}
BOOL getDevCertPath(char *outValue)
{
BOOL result = FALSE;
if ((!check_null(devConf->devCertPath)) || (!check_null(outValue))) {
g_message("getDevCertPath: NULL string !");
return result;
}
if (check_empty(devConf->devCertPath)) {
strncpy(outValue,devConf->devCertPath, MAX_FILE_LENGTH);
result = TRUE;
} else
g_message("getDevCertPath: config has empty path!");
return result;
}
BOOL getDevCertFile(char *outValue)
{
BOOL result = FALSE;
if ((!check_null(devConf->devCertFile)) || (!check_null(outValue))) {
g_message("getDevCertFile: NULL string !");
return result;
}
if (check_empty(devConf->devCertFile)) {
strncpy(outValue,devConf->devCertFile, MAX_FILE_LENGTH);
result = TRUE;
} else
g_message("getDevCertFile: config has empty file !");
return result;
}
BOOL getUidfromRecvId()
{
BOOL result = FALSE;
guint loopvar = 0;
gchar **tokens = g_strsplit_set(eroutermacaddress->str, "':''\n'", -1);
guint toklength = g_strv_length(tokens);
while (loopvar < toklength)
{
g_string_printf(recv_id, "ebf5a0a0-1dd1-11b2-a90f-%s%s%s%s%s%s", g_strstrip(tokens[loopvar]), g_strstrip(tokens[loopvar + 1]),g_strstrip(tokens[loopvar + 2]),g_strstrip(tokens[loopvar + 3]),g_strstrip(tokens[loopvar + 4]),g_strstrip(tokens[loopvar + 5]));
g_message("getUidfromRecvId: recvId: %s", recv_id->str);
result = TRUE;
break;
}
g_strfreev(tokens);
return result;
}
BOOL getUUID(char *outValue)
{
BOOL result = FALSE;
if (!check_null(outValue)) {
g_message("getUUID : NULL string !");
return result;
}
if (getUidfromRecvId()){
if( (check_empty(recv_id->str))) {
sprintf(outValue, "uuid:%s", recv_id->str);
result = TRUE;
}
else
{
g_message("getUUID : empty recvId");
}
}
else
{
g_message("getUUID : could not get UUID");
}
return result;
}
BOOL getReceiverId(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if (!check_null(outValue)) {
g_message("getReceiverId : NULL string !");
return result;
}
if(getUidfromRecvId())
{
if (check_null((char *)recv_id) && check_empty(recv_id->str)) {
rc = strcpy_s(outValue,MAX_OUTVALUE,recv_id->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
}
else
{
g_message("getReceiverId : empty recvId");
}
}
else
{
g_message("getUUID : could not get UUID");
}
return result;
}
BOOL getTrmUrl(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if (!check_null(outValue)) {
g_message("getTrmUrl : NULL string !");
return result;
}
if (check_empty(trmurl->str)) {
rc = strcpy_s(outValue,MAX_OUTVALUE,trmurl->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
} else {
g_message("getTrmUrl : No trmurl found");
}
return result;
}
BOOL getTuneReady()
{
return tune_ready;
}
BOOL getPlaybackUrl(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if (!check_null(playbackurl->str)){
g_message("getPlaybackUrl: NULL string !");
return result;
}
if (check_empty(playbackurl->str))
{
rc = strcpy_s(outValue,URLSIZE, playbackurl->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
}
else
{
g_message("getPlaybackUrl: Empty plabackurl");
}
return result;
}
BOOL getVideoBasedUrl(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if (!check_null(outValue)) {
g_message("getVideoBasedUrl : NULL string !");
return result;
}
if (check_empty(videobaseurl->str)) {
rc = strcpy_s(outValue,MAX_OUTVALUE, videobaseurl->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
} else {
g_message("getVideoBasedUrl : No VideoBasedUrl found");
}
return result;
}
BOOL getIsuseGliDiagEnabled()
{
return devConf->useGliDiag;
}
BOOL getDstOffset(int *outValue)
{
*outValue = dstOffset;
return TRUE;
}
BOOL getDisableTuneReadyStatus()
{
return devConf->disableTuneReady;
}
#ifndef CLIENT_XCAL_SERVER
BOOL getCVPIp(char *outValue)
{
errno_t rc = -1;
if (!check_null(outValue)) {
g_message("getCVPIp : NULL string !");
return FALSE;
}
ipAddressBuffer[0] = '\0';
int result = getipaddress(devConf->cvpIf, ipAddressBuffer, FALSE);
if (!result) {
fprintf(stderr, "Could not locate the ipaddress of CVP2 interface %s\n",
devConf->cvpIf);
return FALSE;
}
g_message("ipaddress of the CVP2 interface %s", ipAddressBuffer);
rc = strcpy_s(outValue,MAX_OUTVALUE,ipAddressBuffer);
if(rc == EOK)
{
return TRUE;
}
else
{
ERR_CHK(rc);
return FALSE;
}
}
BOOL getCVPIf(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1
if (!check_null(outValue)) {
g_message("getCVPIf : NULL string !");
return result;
}
if (check_empty(devConf->cvpIf)) {
rc = strcpy_s(outValue, MAXSIZE, devConf->cvpIf);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
}
else
{
g_message("getCVPIf : Failed to get the CVP Interface");
}
return result;
}
BOOL getCVPPort(int *outValue)
{
BOOL result = FALSE;
if (!check_null(outValue)) {
g_message("getCVPPort : NULL string !");
return result;
}
else
{
*outValue = devConf->cvpPort;
result = TRUE;
}
return result;
}
BOOL getCVPXmlFile(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if (!check_null(outValue)) {
g_message("getCVPXmlFile : NULL string !");
return result;
}
if (check_empty(devConf->cvpXmlFile)) {
rc = strcpy_s(outValue, MAXSIZE, devConf->cvpXmlFile);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
}
else
{
g_message("getCVPXmlFile : Failed to get the CVP XmlFile");
}
return result;
}
#endif
BOOL getRouteDataGateway(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if (!check_null(outValue)) {
g_message("getRouteDataGateway : NULL string !");
return result;
}
if(check_empty(dataGatewayIPaddress->str)) {
rc = strcpy_s(outValue,MAX_OUTVALUE,dataGatewayIPaddress->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
} else
g_message("getRouteDataGateway : error getting route data!");
return result;
}
BOOL getLogFile(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if (!check_null(outValue)) {
g_message("getLogFile : NULL string !");
return result;
}
if (check_empty(devConf->logFile)) {
rc = strcpy_s(outValue,MAX_OUTVALUE,devConf->logFile);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
} else
g_message("getLogFile : Config doesnt have a log file !");
return result;
}
BOOL getEstbMacAddr(char *outValue)
{
BOOL result = FALSE;
#ifndef CLIENT_XCAL_SERVER
errno_t rc = -1;
if ((!check_null(devConf->hostMacIf)) || (!check_null(outValue))) {
g_message("getEstbMacAddr : NULL string !");
return result;
}
if (!check_empty(hostmacaddress->str)) {
const gchar *hostmac = (gchar *)getmacaddress(devConf->hostMacIf);
if (hostmac) {
g_message("MAC address in interface: %s %s ", devConf->hostMacIf, hostmac);
g_string_assign(hostmacaddress,hostmac);
result = TRUE;
} else {
g_message("failed to retrieve macaddress on interface %s ",
devConf->hostMacIf);
return result;
}
}
rc = strcpy_s(outValue,MAX_OUTVALUE, hostmacaddress->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
g_message("Host mac address is %s", hostmacaddress->str);
#endif
return result;
}
BOOL getDevXmlPath(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if ((!check_null(devConf->devXmlPath)) || (!check_null(outValue))) {
g_message("getDevXmlPath : NULL string !");
return result;
}
if (check_empty(devConf->devXmlPath)) {
rc = strcpy_s(outValue,MAX_OUTVALUE,devConf->devXmlPath);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
} else
g_message("getDevXmlPath : config has empty xml path !");
return result;
}
BOOL getDevXmlFile(char *outValue, int refactor)
{
BOOL result = FALSE;
if ((!check_null(devConf->devXmlFile)) || (!check_null(outValue))) {
g_message("getDevXmlFile : NULL string !");
return result;
}
if(!refactor)
{
if (check_empty(devConf->devXmlFile)) {
sprintf(outValue, "%s/%s", devConf->devXmlPath, devConf->devXmlFile);
result = TRUE;
} else
g_message("getDevXmlFile : config has empty xml file !");
}
else
{
sprintf(outValue, "%s/%s", devConf->devXmlPath,BROADBAND_DEVICE_XML_FILE);
g_message("getDevXmlFile : refactor = %s",outValue);
result = TRUE;
}
return result;
}
BOOL checkCVP2Enabled()
{
return devConf->enableCVP2;
}
BOOL getModelNumber(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if ((!check_null(devicename->str)) || (!check_null(outValue))) {
g_message("getModelNumber : NULL string !");
return result;
}
if (check_empty(devicename->str)) {
rc = strcpy_s(outValue,MAX_OUTVALUE,devicename->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
} else
g_message("getModelNumber : config has empty modelnumber file !");
return result;
}
BOOL getMake(char *outValue)
{
BOOL result = FALSE;
errno_t rc = -1;
if ((!check_null(make->str)) || (!check_null(outValue))) {
g_message("getMake : NULL string !");
return result;
}
if (check_empty(make->str)) {
rc = strcpy_s(outValue,MAX_OUTVALUE,make->str);
if(rc == EOK)
{
result = TRUE;
}
else
{
ERR_CHK(rc);
}
} else
g_message("getMake : config has empty device make file !");
return result;
}
BOOL xdeviceInit(char *devConfFile, char *devLogFile)
{
syscfg_init(); // to get values from syscfg.db
url = g_string_new(NULL);
trmurl = g_string_new(NULL);
trmurlCVP2 = g_string_new(NULL);
playbackurl = g_string_new(NULL);
fogtsburl = g_string_new(NULL);
playbackurlCVP2 = g_string_new(NULL);
videobaseurl = g_string_new("null");
gwyip = g_string_new(NULL);
gwyipv6 = g_string_new(NULL);
gwystbip = g_string_new(NULL);
ipv6prefix = g_string_new(NULL);
gwyipCVP2 = g_string_new(NULL);
dnsconfig = g_string_new(NULL);
systemids = g_string_new(NULL);
dsgtimezone = g_string_new(NULL);
etchosts = g_string_new(NULL);
serial_num = g_string_new(NULL);
channelmap_id = dac_id = plant_id = vodserver_id = 0;
isgateway = FALSE;
requirestrm = FALSE;
service_ready = FALSE;
tune_ready = FALSE;
ruiurl = g_string_new(NULL);
inDevProfile = g_string_new(NULL);
uiFilter = g_string_new(NULL);
recv_id = g_string_new(NULL);
partner_id = g_string_new(NULL);
hostmacaddress = g_string_new(NULL);
bcastmacaddress = g_string_new(NULL);
eroutermacaddress = g_string_new(NULL);
devicename = g_string_new(NULL);
buildversion = g_string_new(NULL);
recvdevtype = g_string_new(NULL);
devicetype = g_string_new(NULL);
mocaIface = g_string_new(NULL);
wifiIface = g_string_new(NULL);
make = g_string_new(NULL);
dataGatewayIPaddress = g_string_new(NULL);
if (! check_null(devConfFile)) {
#ifndef CLIENT_XCAL_SERVER
g_message("No Configuration file please use /usr/bin/xcal-device /etc/xdevice.conf");
exit(1);
#endif
}
#ifndef CLIENT_XCAL_SERVER
if(readconffile(devConfFile)==FALSE)
{
g_message("readconffile returned FALSE");
devConf = g_new0(ConfSettings, 1);
}
#else
devConf = g_new0(ConfSettings, 1);
#endif
#ifdef CLIENT_XCAL_SERVER
if (! (devConf->bcastPort))
devConf->bcastPort = BCAST_PORT;
if (! (devConf->devPropertyFile))
devConf->devPropertyFile = g_strdup(DEVICE_PROPERTY_FILE);
if (! (devConf->authServerUrl))
devConf->authServerUrl = g_strdup(AUTH_SERVER_URL);
if (! (devConf->deviceNameFile))
devConf->deviceNameFile = g_strdup(DEVICE_NAME_FILE);
if (! (devConf->logFile))
devConf->logFile = g_strdup(LOG_FILE);
if (! (devConf->devXmlPath))
devConf->devXmlPath = g_strdup(DEVICE_XML_PATH);
if (! (devConf->devXmlFile))
devConf->devXmlFile = g_strdup(DEVICE_XML_FILE);
if (! (devConf->devKeyFile))
devConf->devKeyFile = g_strdup(DEVICE_KEY_FILE);
if (! (devConf->devKeyPath))
devConf->devKeyPath = g_strdup(DEVICE_KEY_PATH);
if (! (devConf->devCertFile))
devConf->devCertFile = g_strdup(DEVICE_CERT_FILE);
if (! (devConf->devCertPath))
devConf->devCertPath = g_strdup(DEVICE_CERT_PATH);
devConf->allowGwy = FALSE;
devConf->useIARM = TRUE;
devConf->useGliDiag=TRUE;
#endif
if (check_null(devLogFile)) {
logoutfile = g_fopen (devLogFile, "a");
}
else if (devConf->logFile) {
logoutfile = g_fopen (devConf->logFile, "a");
}
else {
g_message("xupnp not handling the logging");
}
if (logoutfile) {
g_log_set_handler(G_LOG_DOMAIN, G_LOG_LEVEL_INFO | G_LOG_LEVEL_MESSAGE | \
G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_ERROR, xupnp_logger,
NULL);
g_log_set_handler("libsoup", G_LOG_LEVEL_INFO | G_LOG_LEVEL_MESSAGE | \
G_LOG_LEVEL_WARNING | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_ERROR, xupnp_logger,
NULL);
}
g_message("Starting xdevice service");
if (devConf->devPropertyFile != NULL) {
if (readDevFile(devConf->devPropertyFile) == TRUE) {
g_message("Receiver Type : %s Build Version : %s Device Type: %s moca %s wifi %s ",
recvdevtype->str, buildversion->str, devicetype->str, mocaIface->str,
wifiIface->str);
} else {
g_message(" ERROR in getting Receiver Type : %s Build Version : %s ",
recvdevtype->str, buildversion->str);
g_message("Receiver Type : %s Build Version : %s Device Type: %s moca %s wifi %s ",
recvdevtype->str, buildversion->str, devicetype->str, mocaIface->str,
wifiIface->str);
}
}
#ifndef CLIENT_XCAL_SERVER
int result;
if ( access(devConf->ipv6FileLocation, F_OK ) != -1 )
result = getipaddress(devConf->bcastIf, ipAddressBuffer, TRUE);
if (!result) {
fprintf(stderr,
"In Ipv6 Could not locate the link local ipv6 address of the broadcast interface %s\n",
devConf->bcastIf);
g_critical("In Ipv6 Could not locate the link local ipv6 address of the broadcast interface %s\n",
devConf->bcastIf);
exit(1);
}
g_string_assign(gwyipv6, ipAddressBuffer);
ipAddressBuffer[0] = '\0';
result = getipaddress(devConf->bcastIf, ipAddressBuffer, FALSE);
if (!result) {
fprintf(stderr,
"Could not locate the link local v4 ipaddress of the broadcast interface %s\n",
devConf->bcastIf);
g_critical("Could not locate the link local v4 ipaddress of the broadcast interface %s\n",
devConf->bcastIf);
exit(1);
} else
g_message("ipaddress of the interface %s", ipAddressBuffer);
#else
ipAddressBuffer[0] = '\0';
int result = getipaddress(mocaIface->str, ipAddressBuffer, FALSE);
if (!result) {
g_message("Could not locate the ipaddress of the broadcast moca isolation interface %s",
mocaIface->str);
result = getipaddress(wifiIface->str, ipAddressBuffer, FALSE);
if (!result) {
g_message("Could not locate the ipaddress of the wifi broadcast interface %s",
wifiIface->str);
g_critical("Could not locate the link local v4 ipaddress of the broadcast interface %s\n",
wifiIface->str);
exit(1);
} else {
devConf->bcastIf = g_strdup(wifiIface->str);
}
} else {
devConf->bcastIf = g_strdup(mocaIface->str);
}
g_message("Starting xdevice service on interface %s ipAddressBuffer= %s", devConf->bcastIf,ipAddressBuffer);
#endif
g_message("Broadcast Network interface: %s", devConf->bcastIf);
g_message("Dev XML File Name: %s", devConf->devXmlFile);
g_string_assign(gwyip, ipAddressBuffer);
//Init IARM Events
#if defined(USE_XUPNP_IARM_BUS)
gboolean iarminit = XUPnP_IARM_Init();
if (iarminit == true) {
//g_print("IARM init success");
g_message("XUPNP IARM init success");
#ifndef CLIENT_XCAL_SERVER
getSystemValues();
#endif
} else {
//g_print("IARM init failure");
g_critical("XUPNP IARM init failed");
}
#endif //#if defined(USE_XUPNP_IARM_BUS)
#ifndef CLIENT_XCAL_SERVER
if (devConf->hostMacIf != NULL) {
const gchar *hostmac = (gchar *)getmacaddress(devConf->hostMacIf);
if (hostmac) {
g_message("MAC address in interface: %s %s \n", devConf->hostMacIf, hostmac);
} else {
g_message("failed to retrieve macaddress on interface %s ",
devConf->hostMacIf);
}
g_string_assign(hostmacaddress, hostmac);
g_message("Host mac address is %s", hostmacaddress->str);
}
#endif
if (devConf->bcastIf != NULL ) {
const gchar *bcastmac = (gchar *)getmacaddress(devConf->bcastIf);
if (bcastmac) {
g_message("Broadcast MAC address in interface: %s %s ", devConf->bcastIf,
bcastmac);
} else {
g_message("failed to retrieve macaddress on interface %s ", devConf->bcastIf);
}
g_string_assign(bcastmacaddress, bcastmac);
g_message("bcast mac address is %s", bcastmacaddress->str);
}
const gchar *eroutermac = (gchar *)getmacaddress(UDN_IF);
if(eroutermac)
{
g_message("Erouter0 MAC address in interface: %s %s",UDN_IF,
eroutermac);
}
else
{
g_message("failed to retrieve macaddress on interface %s ", devConf->bcastIf);
}
g_string_assign(eroutermacaddress,eroutermac);
g_message("erouter0 mac address is %s",eroutermacaddress->str);
if(devicename->str != NULL)
{
g_message("Device Name : %s ", devicename->str);
}
else
{
g_message(" ERROR in getting Device Name ");
}
#ifndef CLIENT_XCAL_SERVER
if (devConf->enableTRM == FALSE) {
requirestrm = FALSE;
g_string_printf(trmurl, NULL);
} else {
requirestrm = TRUE;
g_string_printf(trmurl, "ws://%s:9988", ipAddressBuffer);
}
#endif
if (devConf->allowGwy == FALSE) {
isgateway = FALSE;
}
#ifndef CLIENT_XCAL_SERVER
g_string_printf(playbackurl,
"http://%s:8080/hnStreamStart?deviceId=%s&DTCP1HOST=%s&DTCP1PORT=5000",
ipAddressBuffer, recv_id->str, ipAddressBuffer);
if (getDnsConfig(dnsconfig->str) == TRUE) {
g_print("Contents of dnsconfig is %s\n", dnsconfig->str);
}
if (updatesystemids() == TRUE) {
g_message("System ids are %s", systemids->str);
} else {
g_warning("Error in finding system ids\n");
}
#if defined(USE_XUPNP_IARM_BUS)
if ((strlen(g_strstrip(serial_num->str)) < 6)
|| (is_alphanum(serial_num->str) == FALSE)) {
g_message("Serial Number not yet received.\n");
}
g_message("Received Serial Number:%s", serial_num->str);
#else
if (getserialnum(serial_num) == TRUE) {
g_message("Serial Number is %s", serial_num->str);
}
#endif
#else
if (getserialnum(serial_num) == TRUE) {
g_message("Serial Number is %s", serial_num->str);
}
#endif
#ifndef CLIENT_XCAL_SERVER
if (getetchosts() == TRUE) {
g_message("EtcHosts Content is %s", etchosts->str);
} else {
g_message("Error in getting etc hosts");
}
#else
#endif
#ifndef CLIENT_XCAL_SERVER
if (devConf->disableTuneReady == FALSE) {
if (FALSE == tune_ready) {
g_message("XUPnP: Tune Ready Not Yet Received.\n");
}
} else {
g_message("Tune Ready check is disabled - Setting tune_ready to TRUE");
tune_ready = TRUE;
}
if ((devConf->allowGwy == TRUE) && (ipv6Enabled == TRUE)
&& (devConf->ipv6PrefixFile != NULL)) {
if (access(devConf->ipv6PrefixFile, F_OK ) == -1 ) {
g_message("IPv6 Prefix File Not Yet Created.");
}
if (getIpv6Prefix(ipv6prefix->str) == FALSE) {
g_message(" V6 prefix is not yet updated in file %s ",
devConf->ipv6PrefixFile);
}
g_message("IPv6 prefix : %s ", ipv6prefix->str);
} else {
g_message("Box is in IPV4 or ipv6 prefix is empty or Not a gateway ipv6enabled = %d ipv6PrefixFile = %s allowGwy = %d ",
ipv6Enabled, devConf->ipv6PrefixFile, devConf->allowGwy);
}
if (devConf->hostMacIf != NULL) {
result = getipaddress(devConf->hostMacIf, stbipAddressBuffer, ipv6Enabled);
if (!result) {
g_message("Could not locate the ipaddress of the host mac interface %s\n",
devConf->hostMacIf);
} else
g_message("ipaddress of the interface %s\n", stbipAddressBuffer);
g_string_assign(gwystbip, stbipAddressBuffer);
}
#endif
return TRUE;
}
/**
* @brief This function is used to get the Receiver Id & Partner Id.
*
* When box in warehouse mode, the box does not have the receiver Id so the box need to be put the
* broadcast MAC address as receiver Id.
*
* @param[in] id The Device ID node for which the value need to be retrieved. It is also used for
* getting Partner Id.
*
* @return Returns Value of the Device Id on success else NULL.
* @ingroup XUPNP_XCALDEV_FUNC
*/
GString *getID( const gchar *id )
{
gboolean isDevIdPresent = FALSE;
gshort counter =
0; // to limit the logging if the user doesnt activate for long time
SoupSession *session = soup_session_sync_new();
GString *jsonData = g_string_new(NULL);
GString *value = g_string_new(NULL);
// if (IARM_BUS_SYS_MODE_WAREHOUSE == sysModeParam)
SoupMessage *msg = soup_message_new ("GET", devConf->authServerUrl);
if (msg != NULL) {
soup_session_send_message (session, msg);
if (SOUP_STATUS_IS_SUCCESSFUL(msg->status_code)) {
if ((msg->response_body->data[0] == '\0') && (counter < MAX_DEBUG_MESSAGE)) {
counter ++;
g_message("No Json string found in Auth url %s \n" ,
msg->response_body->data);
} else {
g_string_assign(jsonData, msg->response_body->data);
gchar **tokens = g_strsplit_set(jsonData->str, "{}:,\"", -1);
guint tokLength = g_strv_length(tokens);
guint loopvar = 0;
for (loopvar = 0; loopvar < tokLength; loopvar++) {
if (g_strrstr(g_strstrip(tokens[loopvar]), id)) {
//"deviceId": "T00xxxxxxx" so omit 3 tokens ":" fromDeviceId
if ((loopvar + 3) < tokLength ) {
g_string_assign(value, g_strstrip(tokens[loopvar + 3]));
if (value->str[0] != '\0') {
isDevIdPresent = TRUE;
break;
}
}
}
}
if (!isDevIdPresent) {
if (g_strrstr(id, PARTNER_ID)) {
g_message("%s not found in Json string in Auth url %s \n ", id, jsonData->str);
return value;
}
if (counter < MAX_DEBUG_MESSAGE ) {
counter++;
g_message("%s not found in Json string in Auth url %s \n ", id, jsonData->str);
}
} else {
g_message("Successfully fetched %s %s \n ", id, value->str);
//g_free(tokens);
//#########
//break;
//#########
}
g_strfreev(tokens);
}
} else {
if (g_strrstr(id, PARTNER_ID)) {
g_message("Partner ID lib soup error %d while fetching the Auth url %s \n ",
msg->status_code, devConf->authServerUrl);
return value;
}
if (counter < MAX_DEBUG_MESSAGE) {
g_message("lib soup error %d while fetching the Auth url %s \n ",
msg->status_code, devConf->authServerUrl);
counter ++;
}
}
g_object_unref(msg);
} else {
g_message("The Auth url %s can't be processed", devConf->authServerUrl);
}
g_string_free(jsonData, TRUE);
soup_session_abort (session);
return value;
}
/**
* @brief This function is used to update the system Ids such as channelMapId, controllerId, plantId
* and vodServerId.
*
* @return Returns TRUE if successfully updates the system ids, else returns FALSE.
* @ingroup XUPNP_XCALDEV_FUNC
*/
gboolean updatesystemids(void)
{
if (devConf->useGliDiag == TRUE) {
g_string_printf(systemids,
"channelMapId:%lu;controllerId:%lu;plantId:%lu;vodServerId:%lu",
channelmap_id, dac_id, plant_id, vodserver_id);
return TRUE;
} else {
/* Coverity Fix CID: 124887 : UnInitialised variable*/
gchar *diagfile = NULL;
unsigned long diagid = 0;
gboolean result = FALSE;
GError *error = NULL;
if (devConf->diagFile == NULL) {
g_warning("diag file name not found in config");
return result;
}
result = g_file_get_contents (devConf->diagFile, &diagfile, NULL, &error);
if (result == FALSE) {
g_string_assign(systemids,
"channelMapId:0;controllerId:0;plantId:0;vodServerId:0");
} else {
diagid = getidfromdiagfile("channelMapId", diagfile);
g_string_printf(systemids, "channelMapId:%lu;", diagid);
diagid = getidfromdiagfile("controllerId", diagfile);
g_string_append_printf(systemids, "controllerId:%lu;", diagid);
diagid = getidfromdiagfile("plantId", diagfile);
g_string_append_printf(systemids, "plantId:%lu;", diagid);
diagid = getidfromdiagfile("vodServerId", diagfile);
g_string_append_printf(systemids, "vodServerId:%lu", diagid);
}
if (error) {
/* g_clear_error() frees the GError *error memory and reset pointer if set in above operation */
g_clear_error(&error);
}
return result;
}
}
/**
* @brief This function is used to get the device name from /devicename/devicename file.
*
* @return Returns TRUE if successfully gets the device name string else returns FALSE.
* @ingroup XUPNP_XCALDEV_FUNC
*/
gboolean parsedevicename(void)
{
GError *error = NULL;
gboolean result = FALSE;
gchar *devicenamefile = NULL;
guint loopvar = 0;
gboolean devicenamematch = FALSE;
if (devConf->deviceNameFile == NULL) {
g_warning("device name file name not found in config");
return result;
}
result = g_file_get_contents (devConf->deviceNameFile, &devicenamefile, NULL,
&error);
/* Coverity Fix for CID: 125452 : Forward NULL */
if (result == FALSE) {
g_warning("Problem in reading /devicename/devicename file %s", error ? error->message : "NULL");
} else {
gchar **tokens = g_strsplit_set(devicenamefile, "'=''\n''\0'", -1);
guint toklength = g_strv_length(tokens);
while (loopvar < toklength) {
if (g_strrstr(g_strstrip(tokens[loopvar]), "deviceName")) {
result = TRUE;
g_string_printf(devicename, "%s", g_strstrip(tokens[loopvar + 1]));
g_message("device name = %s", devicename->str);
devicenamematch = TRUE;
break;
}
loopvar++;
}
g_strfreev(tokens);
if (devicenamematch == FALSE) {
g_message("No Matching devicename in file %s", devicenamefile);
}
}
if (error) {
/* g_clear_error() frees the GError *error memory and reset pointer if set in above operation */
g_clear_error(&error);
}
g_free(devicenamefile);
return result;
}
/**
* @brief This function is used to retrieve the IPv6 prefix information from dibblers file.
*
* @return Returns TRUE if successfully gets the ipv6 prefix value else returns FALSE.
* @ingroup XUPNP_XCALDEV_FUNC
*/
gboolean parseipv6prefix(void)
{
GError *error = NULL;
gboolean result = FALSE;
gchar *prefixfile = NULL;
guint loopvar = 0;
guint prefixloopvar = 0;
gboolean ifacematch = FALSE;
gboolean prefixmatch = FALSE;
gchar **prefixtokens;
if (devConf->ipv6PrefixFile == NULL) {
g_warning("ipv6PrefixFile file name not found in config");
return result;
}
result = g_file_get_contents (devConf->ipv6PrefixFile, &prefixfile, NULL,
&error);
/* Coverity Fix for CID: 124926 : Forward NULL */
if (result == FALSE) {
g_warning("Problem in reading /prefix/prefix file %s", error ? error->message : "NULL");
} else {
gchar **tokens = g_strsplit_set(prefixfile, "'\n''\0'", -1);
guint toklength = g_strv_length(tokens);
while (loopvar < toklength) {
if (ifacematch == FALSE) {
if ((g_strrstr(g_strstrip(tokens[loopvar]), "ifacename"))
&& (g_strrstr(g_strstrip(tokens[loopvar]), devConf->hostMacIf))) {
ifacematch = TRUE;
}
} else {
if (g_strrstr(g_strstrip(tokens[loopvar]), "AddrPrefix")) {
prefixtokens = g_strsplit_set(tokens[loopvar], "'<''>''='", -1);
guint prefixtoklength = g_strv_length(prefixtokens);
while (prefixloopvar < prefixtoklength) {
if (g_strrstr(g_strstrip(prefixtokens[prefixloopvar]), "/AddrPrefix")) {
prefixmatch = TRUE;
result = TRUE;
g_string_printf(ipv6prefix, "%s", prefixtokens[prefixloopvar - 1]);
g_message("ipv6 prefix format in the file %s",
prefixtokens[prefixloopvar - 1]);
break;
}
prefixloopvar++;
}
g_strfreev(prefixtokens);
}
if (prefixmatch == TRUE)
break;
}
loopvar++;
}
g_strfreev(tokens);
if (prefixmatch == FALSE) {
result = FALSE;
g_message("No Matching ipv6 prefix in file %s", prefixfile);
}
}
if (error) {
/* g_clear_error() frees the GError *error memory and reset pointer if set in above operation */
g_clear_error(&error);
}
g_free(prefixfile);
return result;
}
/*
* isVidiPathEnabled()
* If /opt/vidiPathEnabled does not exist, indicates VidiPath is NOT enabled.
* If /opt/vidiPathEnabled exists, VidiPath is enabled.
*/
#define VIDIPATH_FLAG "/opt/vidiPathEnabled"
#ifndef CLIENT_XCAL_SERVER
static int isVidiPathEnabled()
{
if (access(VIDIPATH_FLAG, F_OK) == 0)
return 1; //vidipath enabled
return 0; //vidipath not enabled
}
#endif
/**
* @brief This function is used to retrieve the data from the device configuration file
*
* @param[in] configfile Device configuration file name.
*
* @return Returns TRUE if successfully reads the configuration else returns FALSE.
* @ingroup XUPNP_XCALDEV_FUNC
*/
gboolean readconffile(const char *configfile)
{
GKeyFile *keyfile = NULL;
GKeyFileFlags flags;
GError *error = NULL;
/* Create a new GKeyFile object and a bitwise list of flags. */
keyfile = g_key_file_new ();
flags = G_KEY_FILE_KEEP_COMMENTS | G_KEY_FILE_KEEP_TRANSLATIONS;
/* Load the GKeyFile from keyfile.conf or return. */
if (!g_key_file_load_from_file (keyfile, configfile, flags, &error)) {
if (error) {
g_error ("%s\n", error->message);
/* g_clear_error() frees the GError *error memory and reset pointer if set in above operation */
g_clear_error(&error);
}
if (keyfile) {
g_key_file_free(keyfile);
}
return FALSE;
}
//g_message("Starting with Settings %s\n", g_key_file_to_data(keyfile, NULL,
// NULL));
devConf = g_new0(ConfSettings, 1);
/*
# Names of all network interfaces used for publishing
[Network]
BCastIf=eth1
BCastPort=50755
StreamIf=eth1
TrmIf=eth1
GwIf=eth1
CvpIf=eth1
CvpPort=50753
HostMacIf=wan
*/
/* Read in data from the key file from the group "Network". */
devConf->bcastIf = g_key_file_get_string (keyfile, "Network",
"BCastIf", NULL);
devConf->bcastPort = g_key_file_get_integer (keyfile, "Network",
"BCastPort", NULL);
#ifndef CLIENT_XCAL_SERVER
devConf->streamIf = g_key_file_get_string (keyfile, "Network",
"StreamIf", NULL);
devConf->trmIf = g_key_file_get_string (keyfile, "Network",
"TrmIf", NULL);
devConf->gwIf = g_key_file_get_string (keyfile, "Network", "GwIf",
NULL);
devConf->cvpIf = g_key_file_get_string (keyfile, "Network",
"CvpIf", NULL);
devConf->cvpPort = g_key_file_get_integer (keyfile, "Network",
"CvpPort", NULL);
devConf->hostMacIf = g_key_file_get_string (keyfile, "Network",
"HostMacIf", NULL);
#endif
/*
# Paths and names of all input data files
[DataFiles]
OemFile=//etc//udhcpc.vendor_specific
DnsFile=//etc//resolv.dnsmasq
DsgFile=//tmp//dsgproxy_slp_attributes.txt
DiagFile=//tmp//mnt/diska3//persistent//usr//1112//703e//diagnostics.json
HostsFile=//etc//hosts
WbFile=/opt/www/whitebox/wbdevice.dat
DevXmlPath=/opt/xupnp/
DevXmlFile=BasicDevice.xml
LogFile=/opt/logs/xdevice.log
AuthServerUrl=http://localhost:50050/device/generateAuthToken
DevPropertyFile=/etc/device.properties
Ipv6FileLocation=/tmp/stb_ipv6
Ipv6PrefixFile=/tmp/stb_ipv6
DeviceNameFile=/opt/hn_service_settings.conf
*/
/* Read in data from the key file from the group "DataFiles". */
#ifndef CLIENT_XCAL_SERVER
devConf->oemFile = g_key_file_get_string (keyfile, "DataFiles",
"OemFile", NULL);
devConf->dnsFile = g_key_file_get_string (keyfile, "DataFiles",
"DnsFile", NULL);
devConf->dsgFile = g_key_file_get_string (keyfile, "DataFiles",
"DsgFile", NULL);
devConf->diagFile = g_key_file_get_string (keyfile, "DataFiles",
"DiagFile", NULL);
devConf->wbFile = g_key_file_get_string (keyfile, "DataFiles",
"WbFile", NULL);
devConf->devXmlPath = g_key_file_get_string (keyfile, "DataFiles",
"DevXmlPath", NULL);
devConf->devXmlFile = g_key_file_get_string (keyfile, "DataFiles",
"DevXmlFile", NULL);
devConf->cvpXmlFile = g_key_file_get_string (keyfile, "DataFiles",
"CvpXmlFile", NULL);
devConf->logFile = g_key_file_get_string (keyfile, "DataFiles",
"LogFile", NULL);
devConf->ipv6FileLocation = g_key_file_get_string (keyfile,
"DataFiles", "Ipv6FileLocation", NULL);
devConf->ipv6PrefixFile = g_key_file_get_string (keyfile, "DataFiles",
"Ipv6PrefixFile", NULL);
devConf->devCertFile = g_key_file_get_string (keyfile, "DataFiles",
"DevCertFile", NULL);
devConf->devKeyFile = g_key_file_get_string (keyfile, "DataFiles",
"DevKeyFile", NULL);
devConf->devCertPath = g_key_file_get_string (keyfile, "DataFiles",
"DevCertPath", NULL);
devConf->devKeyPath = g_key_file_get_string (keyfile, "DataFiles",
"DevKeyPath", NULL);
#endif
devConf->deviceNameFile = g_key_file_get_string (keyfile, "DataFiles",
"DeviceNameFile", NULL);
devConf->authServerUrl = g_key_file_get_string (keyfile,
"DataFiles", "AuthServerUrl", NULL);
devConf->devPropertyFile = g_key_file_get_string (keyfile,
"DataFiles", "DevPropertyFile", NULL);
/*
# Enable/Disable feature flags
[Flags]
EnableCVP2=false
UseIARM=true
AllowGwy=true
EnableTRM=true
UseGliDiag=true
DisableTuneReady=true
enableHostMacPblsh=true
wareHouseMode=true
rmfCrshSupp=false
*/
devConf->useIARM = g_key_file_get_boolean (keyfile, "Flags",
"UseIARM", NULL);
devConf->allowGwy = g_key_file_get_boolean (keyfile, "Flags",
"AllowGwy", NULL);
#ifndef CLIENT_XCAL_SERVER
devConf->enableCVP2 = isVidiPathEnabled();
devConf->ruiPath = g_key_file_get_string (keyfile, "Rui", "RuiPath" , NULL);
if (devConf->ruiPath == NULL ) { //only use overrides if ruiPath is not present
devConf->uriOverride = g_key_file_get_string (keyfile, "Rui", "uriOverride",
NULL);
} else {
devConf->uriOverride = NULL;
}
devConf->enableTRM = g_key_file_get_boolean (keyfile, "Flags",
"EnableTRM", NULL);
devConf->useGliDiag = g_key_file_get_boolean (keyfile, "Flags",
"UseGliDiag", NULL);
devConf->disableTuneReady = g_key_file_get_boolean (keyfile,
"Flags", "DisableTuneReady", NULL);
devConf->enableHostMacPblsh = g_key_file_get_boolean (keyfile,
"Flags", "EnableHostMacPblsh", NULL);
devConf->rmfCrshSupp = g_key_file_get_boolean (keyfile, "Flags",
"rmfCrshSupp", NULL);
devConf->wareHouseMode = g_key_file_get_boolean (keyfile, "Flags",
"wareHouseMode", NULL);
#endif
g_key_file_free(keyfile);
#ifndef CLIENT_XCAL_SERVER
if ((devConf->bcastIf == NULL) || (devConf->bcastPort == 0)
|| (devConf->devXmlPath == NULL) ||
(devConf->devXmlFile == NULL) || (devConf->wbFile == NULL)) {
g_warning("Invalid or no values found for mandatory parameters\n");
return FALSE;
}
#endif
return TRUE;
}
/*-----------------------------
* Initialize ipAddressBufferCVP2 with ip address at devConf->cvp2If
*/
#if 0
static void initIpAddressBufferCVP2( char *ipAddressBufferCVP2)
{
int result = getipaddress(devConf->cvpIf, ipAddressBufferCVP2, FALSE);
if (!result)
{
fprintf(stderr,"Could not locate the ipaddress of CVP2 interface %s\n", devConf->cvpIf);
}
g_message("ipaddress of the CVP2 interface %s\n", ipAddressBufferCVP2);
g_string_assign(gwyipCVP2, ipAddressBufferCVP2);
}
#endif
/*-----------------------------
* Returns pointer to string of eSTBMAC without ':' chars
* Uses global hostmacaddress GString for address value
* Returned string must be g_string_free() if not NULL
*/
/**
* @brief This function is used to get the MAC address of the eSTB. It uses global hostmacaddress
* GString to get the address value.
*
* @return Returned string must be g_string_free() if not NULL.
* @ingroup XUPNP_XCALDEV_FUNC
*/
GString* get_eSTBMAC(void)
{
if (hostmacaddress != NULL && hostmacaddress->len == 17)//length of address with ':' chars
{
GString* addr = g_string_new(NULL);
int i = 0;
for (i = 0; i < hostmacaddress->len; ++i)
{
if (i != 2 && i != 5 && i != 8 && i != 11 && i != 14 )//positions of ':' char
{
addr = g_string_append_c(addr,(hostmacaddress->str)[i]);
}
}
return g_string_ascii_up(addr);
}
return NULL;
}
#if 0
/*-----------------------------
* Creates a XML escaped string from input
*/
static void xmlescape(gchar *instr, GString *outstr)
{
for (; *instr; instr++)
{
switch (*instr)
{
case '&':
g_string_append_printf(outstr,"%s","&");
break;
case '\"':
g_string_append_printf(outstr,"%s","&guot;");
break;
case '\'':
g_string_append_printf(outstr,"%s","'");
break;
case '<':
g_string_append_printf(outstr,"%s","<");
break;
case '>':
g_string_append_printf(outstr,"%s",">");
break;
default:
g_string_append_printf(outstr,"%c",*instr);
break;
}
}
}
/*-----------------------------
* Creates a URI escaped string from input using RFC 2396 reserved chars
* The output matches what javascript encodeURIComponent() generates
*/
static void uriescape(unsigned char *instr, GString *outstr)
{
int i;
char unreserved[256] = {0}; //array of unreserved chars or 0 flag
for (i = 0; i < 256; ++i) //init unreserved chars
{
unreserved[i] = isalnum(i) || i == '-' || i == '_' || i == '.' || i == '!' || i == '~'
|| i == '*' || i == '\'' || i == '(' || i == ')'
? i : 0;
}
for (; *instr; instr++) //escape the input string to the output string
{
if (unreserved[*instr]) //if defined as unreserved
g_string_append_printf(outstr,"%c",*instr);
else
g_string_append_printf(outstr,"%%%02X",*instr);
}
}
/*-----------------------------
* Creates the escaped rui <uri> element value
*/
static GString *get_uri_value()
{
//create a unique udn value
//struct timeval now;
//int rc = gettimeofday(&now,NULL);
GTimeVal timeval;
g_get_current_time(&timeval);
double t = timeval.tv_sec + (timeval.tv_usec /
1000000.0); //number of seconds and microsecs since epoch
char udnvalue[25];
snprintf(udnvalue, 25, "%s%f", "CVP-", t);
//get current ip address for CVP2
char ipAddressBufferCVP2[INET6_ADDRSTRLEN];
initIpAddressBufferCVP2(ipAddressBufferCVP2);
//init uri parameters with current ip address
g_string_printf(trmurlCVP2, "ws://%s:9988", ipAddressBufferCVP2);
g_string_printf(playbackurlCVP2,
"http://%s:8080/hnStreamStart?deviceId=%s&DTCP1HOST=%s&DTCP1PORT=5000",
ipAddressBufferCVP2, recv_id->str, ipAddressBufferCVP2);
//initialize urivalue from xdevice.conf if present
gchar *urilink;
if (devConf->uriOverride != NULL)
urilink = devConf->uriOverride;
else
urilink = "http://syndeo.xcal.tv/app/x2rui/rui.html";
//g_print("before g_strconcat urilink: %s\n",urilink);
//parse the systemids
//systemids-str must have the following format
//channelMapId:%lu;controllerId:%lu;plantId:%lu;vodServerId:%lu
g_print("systemids->str: %s\n", systemids->str);
GString *channelMapId = NULL;
char *pId = "channelMapId:";
char *pChannelMapId = strstr(systemids->str, pId);
if (pChannelMapId != NULL) {
pChannelMapId += strlen(pId);
size_t len = strcspn(pChannelMapId, ";");
channelMapId = g_string_new_len(pChannelMapId, len);
}
if (channelMapId == NULL)
channelMapId = g_string_new("0");
GString *controllerId = NULL;
pId = "controllerId:";
char *pControllerId = strstr(systemids->str, pId);
if (pControllerId != NULL) {
pControllerId += strlen(pId);
size_t len = strcspn(pControllerId, ";");
controllerId = g_string_new_len(pControllerId, len);
}
if (controllerId == NULL)
controllerId = g_string_new("0");
GString *plantId = NULL;
pId = "plantId:";
char *pPlantId = strstr(systemids->str, pId);
if (pPlantId != NULL) {
pPlantId += strlen(pId);
size_t len = strcspn(pPlantId, ";");
plantId = g_string_new_len(pPlantId, len);
}
if (plantId == NULL)
plantId = g_string_new("0");
GString *vodServerId = NULL;
pId = "vodServerId:";
char *pVodServerId = strstr(systemids->str, pId);
if (pVodServerId != NULL) {
pVodServerId += strlen(pId);
size_t len = strcspn(pVodServerId, ";");
vodServerId = g_string_new_len(pVodServerId, len);
}
if (vodServerId == NULL)
vodServerId = g_string_new("0");
GString *eSTBMAC = get_eSTBMAC();
if (eSTBMAC == NULL) {
eSTBMAC = g_string_new("UNKNOWN");
}
gchar *gw_value = g_strconcat(
"{"
"\"deviceType\":\"DMS\","
"\"friendlyName\":\"" , getGatewayName(), "\","
"\"receiverID\":\"" , recv_id->str, "\","
"\"udn\":\"" , udnvalue, "\","
"\"gatewayIP\":\"" , gwyipCVP2->str, "\","
"\"baseURL\":\"" , playbackurlCVP2->str, "\","
"\"trmURL\":\"" , trmurlCVP2->str, "\","
"\"channelMapId\":\"" , channelMapId->str, "\","
"\"controllerId\":\"" , controllerId->str, "\","
"\"plantId\":\"" , plantId->str, "\","
"\"vodServerId\":\"" , vodServerId->str, "\","
"\"eSTBMAC\":\"" , eSTBMAC->str, "\""
"}", NULL );
g_string_free(eSTBMAC, TRUE);
g_string_free(channelMapId, TRUE);
g_string_free(controllerId, TRUE);
g_string_free(plantId, TRUE);
g_string_free(vodServerId, TRUE);
//gchar *gw_value = "a&b\"c\'d<e>f;g/h?i:j@k&l=m+n$o,p{}q'r_s-t.u!v~x*y(z)"; //test string with reserved chars
//g_print("gw_value string before escape = %s\n",gw_value);
GString *gwescapededstr = g_string_sized_new(strlen(gw_value) *
3);//x3, big enough for all of the chars to be escaped
uriescape(gw_value, gwescapededstr);
g_free(gw_value);
//g_print("gw_value string after URI escape = %s\n",gwescapededstr->str);
gchar *uri = g_strconcat( urilink, "?partner=", getPartnerID(), "&gw=",
gwescapededstr->str, NULL );
g_string_free(gwescapededstr, TRUE);
GString *xmlescapedstr = g_string_sized_new(strlen(uri) *
2);//x2 should be big enough
xmlescape(uri, xmlescapedstr);
g_free(uri);
//g_print("uri string after XML escape = %s\n",xmlescapedstr->str);
return xmlescapedstr;
}
#endif
/**
* @brief This function is used to get the hosts IP information from hosts configuration file "/etc/hosts".
*
* @return Returns TRUE if successfully gets the hosts else returns FALSE.
* @ingroup XUPNP_XCALDEV_FUNC
*/
gboolean getetchosts(void)
{
GError *error = NULL;
gboolean result = FALSE;
gchar *etchostsfile = NULL;
gchar *hostsFile;
if ( ipv6Enabled == TRUE )
hostsFile = g_strdup("//etc//xi-xconf-hosts.list");
else
hostsFile = g_strdup("//etc//hosts");
result = g_file_get_contents (hostsFile, &etchostsfile, NULL, &error);
/* Coverity Fix for CID: 125218 : Forward NULL*/
if (result == FALSE) {
g_warning("Problem in reading %s file %s", hostsFile, error ? error->message : "NULL");
} else {
gchar **tokens = g_strsplit_set(etchostsfile, "\n\0", -1);
//etchosts->str = g_strjoinv(";", tokens);
guint toklength = g_strv_length(tokens);
guint loopvar = 0;
if ((toklength > 0) && (strlen(g_strstrip(tokens[0])) > 0) &&
(g_strrstr(g_strstrip(tokens[0]), "127.0.0.1") == NULL)) {
g_string_printf(etchosts, "%s", gwyip->str);
g_string_append_printf(etchosts, "%s", " ");
g_string_append_printf(etchosts, "%s;", g_strstrip(tokens[0]));
} else {
g_string_assign(etchosts, "");
}
for (loopvar = 1; loopvar < toklength; loopvar++) {
//g_print("Token is %s\n",g_strstrip(tokens[loopvar]));
//Do not send localhost 127.0.0.1 mapping
if (g_strrstr(g_strstrip(tokens[loopvar]), "127.0.0.1") == NULL) {
if (strlen(g_strstrip(tokens[loopvar])) > 0) {
g_string_append_printf(etchosts, "%s", gwyip->str);
g_string_append_printf(etchosts, "%s", " ");
g_string_append_printf(etchosts, "%s;", g_strstrip(tokens[loopvar]));
}
}
}
g_strfreev(tokens);
}
//diagid=1000;
//g_print("Etc Hosts contents are %s", etchosts->str);
g_free(hostsFile);
if (error) {
/* g_clear_error() frees the GError *error memory and reset pointer if set in above operation */
g_clear_error(&error);
}
return result;
}
/**
* @brief This function is used to get the serial number of the device from the vendor specific file.
*
* @param[out] serial_num Manufacturer serial number
*
* @return Returns TRUE if successfully gets the serial number else, returns FALSE.
* @ingroup XUPNP_XCALDEV_FUNC
*/
gboolean parseserialnum(GString *serial_num)
{
#ifndef CLIENT_XCAL_SERVER
GError *error = NULL;
gboolean result = FALSE;
gchar *udhcpcvendorfile = NULL;
result = g_file_get_contents ("//etc//udhcpc.vendor_specific",
&udhcpcvendorfile, NULL, &error);
if (result == FALSE) {
g_warning("Problem in reading /etc/udhcpcvendorfile file %s", error->message);
} else {
/* reset result = FALSE to identify serial number from udhcpcvendorfile contents */
result = FALSE;
gchar **tokens = g_strsplit_set(udhcpcvendorfile, " \n\t\b\0", -1);
guint toklength = g_strv_length(tokens);
guint loopvar = 0;
for (loopvar = 0; loopvar < toklength; loopvar++) {
//g_print("Token is %s\n",g_strstrip(tokens[loopvar]));
if (g_strrstr(g_strstrip(tokens[loopvar]), "SUBOPTION4")) {
if ((loopvar + 1) < toklength ) {
g_string_assign(serial_num, g_strstrip(tokens[loopvar + 2]));
}
result = TRUE;
break;
}
}
g_strfreev(tokens);
}
//diagid=1000;
if (error) {
/* g_clear_error() frees the GError *error memory and reset pointer if set in above operation */
g_clear_error(&error);
}
return result;
#else
/* bool bRet;
IARM_Bus_MFRLib_GetSerializedData_Param_t param;
IARM_Result_t iarmRet = IARM_RESULT_IPCCORE_FAIL;
memset(¶m, 0, sizeof(param));
param.type = mfrSERIALIZED_TYPE_SERIALNUMBER;
iarmRet = IARM_Bus_Call(IARM_BUS_MFRLIB_NAME,
IARM_BUS_MFRLIB_API_GetSerializedData, ¶m, sizeof(param));
if (iarmRet == IARM_RESULT_SUCCESS) {
if (param.buffer && param.bufLen) {
g_message( " serialized data %s \n", param.buffer );
g_string_assign(serial_num, param.buffer);
bRet = true;
} else {
g_message( " serialized data is empty \n" );
bRet = false;
}
} else {
bRet = false;
g_message( "IARM CALL failed for mfrtype \n");
}
return bRet;*/
#endif
return TRUE;
}
/**
* @brief This function is used to get the system Id information from the diagnostic file.
*
* @param[in] diagparam Parameter for which value(system Id) need to be retrieved from the diagnostic file.
* @param[in] diagfilecontents The diagnostic filename
*
* @return Returns value of the system Id.
* @ingroup XUPNP_XCALDEV_FUNC
*/
unsigned long getidfromdiagfile(const gchar *diagparam,
const gchar *diagfilecontents)
{
unsigned long diagid = 0;
gchar **tokens = g_strsplit_set(diagfilecontents, ":,{}", -1);
guint toklength = g_strv_length(tokens);
guint loopvar = 0;
for (loopvar = 0; loopvar < toklength; loopvar++) {
if (g_strrstr(g_strstrip(tokens[loopvar]), diagparam)) {
if ((loopvar + 1) < toklength )
diagid = strtoul(tokens[loopvar + 1], NULL, 10);
}
}
g_strfreev(tokens);
return diagid;
}
/**
* @brief This function is used to get the DNS value from DNS mask configuration file.
*
* @return Returns TRUE if successfully gets the DNS configuration, else returns FALSE.
* @ingroup XUPNP_XCALDEV_FUNC
*/
gboolean parsednsconfig(void)
{
GError *error = NULL;
gboolean result = FALSE;
gchar *dnsconfigfile = NULL;
GString *strdnsconfig = g_string_new(NULL);
if (devConf->dnsFile == NULL) {
g_warning("dnsconfig file name not found in config");
return result;
}
result = g_file_get_contents (devConf->dnsFile, &dnsconfigfile, NULL, &error);
/* Coverity Fix for CID: 125036 : Forward NULL */
if (result == FALSE) {
g_warning("Problem in reading dnsconfig file %s", error ? error->message : "NULL");
} else {
gchar **tokens = g_strsplit_set(dnsconfigfile, "\n\0", -1);
//etchosts->str = g_strjoinv(";", tokens);
guint toklength = g_strv_length(tokens);
guint loopvar = 0;
gboolean firsttok = TRUE;
for (loopvar = 0; loopvar < toklength; loopvar++) {
if ((strlen(g_strstrip(tokens[loopvar])) > 0)) {
// g_message("Token is %s\n",g_strstrip(tokens[loopvar]));
if (firsttok == FALSE) {
g_string_append_printf(strdnsconfig, "%s;", g_strstrip(tokens[loopvar]));
} else {
g_string_printf(strdnsconfig, "%s;", g_strstrip(tokens[loopvar]));
firsttok = FALSE;
}
}
}
g_string_assign(dnsconfig, strdnsconfig->str);
g_string_free(strdnsconfig, TRUE);
g_message("DNS Config is %s", dnsconfig->str);
g_strfreev(tokens);
}
if (error) {
/* g_clear_error() frees the GError *error memory and reset pointer if set in above operation */
g_clear_error(&error);
}
return result;
}
/**
* @brief This function is used to get the mac address of the target device.
*
* @param[in] ifname Name of the network interface.
*
* @return Returns the mac address of the interface given.
* @ingroup XUPNP_XCALDEV_FUNC
*/
gchar *getmacaddress(const gchar *ifname)
{
errno_t rc = -1;
int fd;
struct ifreq ifr;
unsigned char *mac;
GString *data = g_string_new(NULL);
fd = socket(AF_INET, SOCK_DGRAM, 0);
ifr.ifr_addr.sa_family = AF_INET;
rc = strcpy_s(ifr.ifr_name,IFNAMSIZ - 1,ifname);
ERR_CHK(rc);
ioctl(fd, SIOCGIFHWADDR, &ifr);
close(fd);
mac = (unsigned char *)ifr.ifr_hwaddr.sa_data;
//display mac address
//g_print("Mac : %.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n" , mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
g_string_printf(data, "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x", mac[0], mac[1], mac[2],
mac[3], mac[4], mac[5]);
return data->str;
}
/**
* @brief This function is used to get the IP address based on IPv6 or IPv4 is enabled.
*
* @param[in] ifname Name of the network interface.
* @param[out] ipAddressBuffer Character buffer to hold the IP address.
* @param[in] ipv6Enabled Flag to check whether IPV6 is enabled
*
* @return Returns an integer value '1' if successfully gets the IP address else returns '0'.
* @ingroup XUPNP_XCALDEV_FUNC
*/
int getipaddress(const char *ifname, char *ipAddressBuffer,
gboolean ipv6Enabled)
{
struct ifaddrs *ifAddrStruct = NULL;
struct ifaddrs *ifa = NULL;
void *tmpAddrPtr = NULL;
getifaddrs(&ifAddrStruct);
errno_t rc = -1;
int ind = -1;
//char addressBuffer[INET_ADDRSTRLEN] = NULL;
int found = 0;
for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == NULL) continue;
if (ipv6Enabled == TRUE) {
// check it is IP6
// is a valid IP6 Address
rc = strcmp_s(ifa->ifa_name,strlen(ifa->ifa_name),ifname,&ind);
ERR_CHK(rc);
if(((!ind) && (rc == EOK)) && (ifa ->ifa_addr->sa_family == AF_INET6))
{
tmpAddrPtr = &((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
inet_ntop(AF_INET6, tmpAddrPtr, ipAddressBuffer, INET6_ADDRSTRLEN);
//if (strcmp(ifa->ifa_name,"eth0")==0trcmp0(g_strstrip(devConf->mocaMacIf),ifname) == 0)
if (((g_strcmp0(g_strstrip(devConf->bcastIf), ifname) == 0)
&& (IN6_IS_ADDR_LINKLOCAL(tmpAddrPtr)))
|| ((!(IN6_IS_ADDR_LINKLOCAL(tmpAddrPtr)))
&& (g_strcmp0(g_strstrip(devConf->hostMacIf), ifname) == 0))) {
found = 1;
break;
}
}
} else {
if (ifa ->ifa_addr->sa_family == AF_INET) { // check it is IP4
// is a valid IP4 Address
tmpAddrPtr = &((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
inet_ntop(AF_INET, tmpAddrPtr, ipAddressBuffer, INET_ADDRSTRLEN);
//if (strcmp(ifa->ifa_name,"eth0")==0)
rc = strcmp_s(ifa->ifa_name,strlen(ifa->ifa_name),ifname,&ind);
ERR_CHK(rc);
if((!ind) && (rc == EOK))
{
found = 1;
break;
}
}
}
}
if (ifAddrStruct != NULL) freeifaddrs(ifAddrStruct);
return found;
}
| 31.837598 | 263 | 0.580569 | [
"object"
] |
3eb1e4c15ea5d27e3a8e6a131828e5441292cb02 | 6,248 | c | C | vendor/ltfat/libltfat/modules/libltfat/src/idgtreal_fb.c | sevagh/Music-Separation-TF | 1e21d3802b7df8f6c25778bca6a6c576f805fc4a | [
"MIT"
] | 4 | 2021-03-02T15:47:59.000Z | 2021-04-26T02:46:00.000Z | vendor/ltfat/libltfat/modules/libltfat/src/idgtreal_fb.c | sevagh/Music-Separation-TF | 1e21d3802b7df8f6c25778bca6a6c576f805fc4a | [
"MIT"
] | null | null | null | vendor/ltfat/libltfat/modules/libltfat/src/idgtreal_fb.c | sevagh/Music-Separation-TF | 1e21d3802b7df8f6c25778bca6a6c576f805fc4a | [
"MIT"
] | 1 | 2021-03-19T03:21:41.000Z | 2021-03-19T03:21:41.000Z | #include "ltfat.h"
#include "ltfat/types.h"
#include "ltfat/macros.h"
#include "ltfat/thirdparty/fftw3.h"
struct LTFAT_NAME(idgtreal_fb_plan)
{
ltfat_int a;
ltfat_int M;
ltfat_int gl;
ltfat_phaseconvention ptype;
LTFAT_COMPLEX* cbuf;
LTFAT_REAL* crbuf;
LTFAT_REAL* gw;
LTFAT_REAL* ff;
LTFAT_NAME(ifftreal_plan)* p_small;
int do_overwriteoutarray;
};
/* ------------------- IDGTREAL ---------------------- */
#define THE_SUM_REAL { \
memcpy(cbuf,cin+n*M2+w*M2*N, M2*sizeof*cbuf); \
LTFAT_NAME(ifftreal_execute)(p->p_small); \
LTFAT_NAME_REAL(circshift)(crbuf,M,p->ptype==LTFAT_TIMEINV?glh:-n*a+glh,ff); \
LTFAT_NAME_REAL(periodize_array)(ff,M,gl,ff); \
for (ltfat_int ii=0; ii<gl; ii++) \
ff[ii] *= gw[ii]; \
}
LTFAT_API int
LTFAT_NAME(idgtreal_fb)(const LTFAT_COMPLEX* cin, const LTFAT_REAL* g,
ltfat_int L, ltfat_int gl, ltfat_int W,
ltfat_int a, ltfat_int M,
const ltfat_phaseconvention ptype, LTFAT_REAL* f)
{
LTFAT_NAME(idgtreal_fb_plan)* plan = NULL;
int status = LTFATERR_SUCCESS;
CHECKSTATUS(
LTFAT_NAME(idgtreal_fb_init)(g, gl, a, M, ptype, FFTW_ESTIMATE, &plan));
CHECKSTATUS(
LTFAT_NAME(idgtreal_fb_execute)(plan, cin, L, W, f));
error:
if (plan) LTFAT_NAME(idgtreal_fb_done)(&plan);
return status;
}
LTFAT_API int
LTFAT_NAME(idgtreal_fb_set_overwriteoutarray)(
LTFAT_NAME(idgtreal_fb_plan)* p, int do_overwriteoutarray)
{
int status = LTFATERR_FAILED;
CHECKNULL(p);
p->do_overwriteoutarray = do_overwriteoutarray;
error:
return status;
}
LTFAT_API int
LTFAT_NAME(idgtreal_fb_init)(const LTFAT_REAL* g, ltfat_int gl,
ltfat_int a, ltfat_int M, const ltfat_phaseconvention ptype,
unsigned flags, LTFAT_NAME(idgtreal_fb_plan)** pout)
{
ltfat_int M2;
LTFAT_NAME(idgtreal_fb_plan)* p = NULL;
int status = LTFATERR_SUCCESS;
CHECKNULL(g); CHECKNULL(pout);
CHECK(LTFATERR_BADSIZE, gl > 0, "gl (passed %td) must be positive.", gl);
CHECK(LTFATERR_NOTPOSARG, a > 0, "a (passed %td) must be positive.", a);
CHECK(LTFATERR_NOTPOSARG, M > 0, "M (passed %td) must be positive.", M);
CHECK(LTFATERR_CANNOTHAPPEN, ltfat_phaseconvention_is_valid(ptype),
"Invalid ltfat_phaseconvention enum value." );
CHECKMEM(p = LTFAT_NEW(LTFAT_NAME(idgtreal_fb_plan)) );
p->ptype = ptype; p->a = a; p->M = M; p->gl = gl;
p->do_overwriteoutarray = 1;
/* This is a floor operation. */
M2 = M / 2 + 1;
CHECKMEM( p->cbuf = LTFAT_NAME_COMPLEX(malloc)(M2));
CHECKMEM( p->crbuf = LTFAT_NAME_REAL(malloc)(M));
CHECKMEM( p->gw = LTFAT_NAME_REAL(malloc)(gl));
CHECKMEM( p->ff = LTFAT_NAME_REAL(malloc)(gl > M ? gl : M));
CHECKSTATUS(
LTFAT_NAME(ifftreal_init)(M, 1, p->cbuf, p->crbuf, flags, &p->p_small));
LTFAT_NAME_REAL(fftshift)(g, gl, p->gw);
*pout = p;
return status;
error:
if (p) LTFAT_NAME(idgtreal_fb_done)(&p);
return status;
}
LTFAT_API int
LTFAT_NAME(idgtreal_fb_done)(LTFAT_NAME(idgtreal_fb_plan)** p)
{
LTFAT_NAME(idgtreal_fb_plan)* pp;
int status = LTFATERR_SUCCESS;
CHECKNULL(p); CHECKNULL(*p);
pp = *p;
LTFAT_SAFEFREEALL(pp->cbuf, pp->crbuf, pp->ff, pp->gw);
if (pp->p_small) LTFAT_NAME(ifftreal_done)(&pp->p_small);
ltfat_free(pp);
pp = NULL;
error:
return status;
}
LTFAT_API int
LTFAT_NAME(idgtreal_fb_execute)(LTFAT_NAME(idgtreal_fb_plan)* p,
const LTFAT_COMPLEX* cin,
ltfat_int L, ltfat_int W, LTFAT_REAL* f)
{
ltfat_int M2, M, a, gl, N, ep, sp, glh, glh_d_a;
LTFAT_COMPLEX* cbuf;
LTFAT_REAL* crbuf, *gw, *ff;
int status = LTFATERR_SUCCESS;
CHECKNULL(p); CHECKNULL(cin); CHECKNULL(f);
CHECK(LTFATERR_BADTRALEN, L >= p->gl && !(L % p->a) ,
"L (passed %td) must be greater or equal to gl and divisible by a (passed %td).", L, p->a);
CHECK(LTFATERR_NOTPOSARG, W > 0, "W (passed %td) must be positive.", W);
M = p->M;
a = p->a;
gl = p->gl;
N = L / a;
/* This is a floor operation. */
M2 = M / 2 + 1;
/* This is a floor operation. */
glh = gl / 2;
/* This is a ceil operation. */
glh_d_a = (ltfat_int)ceil((glh * 1.0) / (a));
cbuf = p->cbuf;
crbuf = p->crbuf;
gw = p->gw;
ff = p->ff;
if(p->do_overwriteoutarray)
memset(f, 0, L * W * sizeof * f);
for (ltfat_int w = 0; w < W; w++)
{
LTFAT_REAL* fw = f + w * L;
/* ----- Handle the first boundary using periodic boundary conditions. --- */
for (ltfat_int n = 0; n < glh_d_a; n++)
{
THE_SUM_REAL;
sp = ltfat_positiverem(n * a - glh, L);
ep = ltfat_positiverem(n * a - glh + gl - 1, L);
/* % Add the ff vector to f at position sp. */
for (ltfat_int ii = 0; ii < L - sp; ii++)
fw[sp + ii] += ff[ii];
for (ltfat_int ii = 0; ii < ep + 1; ii++)
fw[ii] += ff[L - sp + ii];
}
/* ----- Handle the middle case. --------------------- */
for (ltfat_int n = glh_d_a; n < (L - (gl + 1) / 2) / a + 1; n++)
{
THE_SUM_REAL;
sp = ltfat_positiverem(n * a - glh, L);
ep = ltfat_positiverem(n * a - glh + gl - 1, L);
/* Add the ff vector to f at position sp. */
for (ltfat_int ii = 0; ii < ep - sp + 1; ii++)
fw[ii + sp] += ff[ii];
}
/* Handle the last boundary using periodic boundary conditions. */
for (ltfat_int n = (L - (gl + 1) / 2) / a + 1; n < N; n++)
{
THE_SUM_REAL;
sp = ltfat_positiverem(n * a - glh, L);
ep = ltfat_positiverem(n * a - glh + gl - 1, L);
/* Add the ff vector to f at position sp. */
for (ltfat_int ii = 0; ii < L - sp; ii++)
fw[sp + ii] += ff[ii];
for (ltfat_int ii = 0; ii < ep + 1; ii++)
fw[ii] += ff[L - sp + ii];
}
}
error:
return status;
}
#undef THE_SUM_REAL
| 29.060465 | 101 | 0.56338 | [
"vector"
] |
c41a74196805cc36efec691381620c33644866b0 | 1,855 | h | C | cc/google/fhir_examples/example_utils.h | ymnliu/fhir-examples | 2483bd4e0f1833f03a496688a06cdd92a9a855b6 | [
"Apache-2.0"
] | null | null | null | cc/google/fhir_examples/example_utils.h | ymnliu/fhir-examples | 2483bd4e0f1833f03a496688a06cdd92a9a855b6 | [
"Apache-2.0"
] | null | null | null | cc/google/fhir_examples/example_utils.h | ymnliu/fhir-examples | 2483bd4e0f1833f03a496688a06cdd92a9a855b6 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 <fstream>
#include <iostream>
#include <string>
#include <vector>
#include "absl/strings/str_cat.h"
#include "absl/time/time.h"
#include "google/fhir/r4/json_format.h"
#include "google/fhir/status/statusor.h"
#include "proto/r4/core/resources/patient.pb.h"
namespace fhir_examples {
using ::google::fhir::StatusOr;
using ::google::fhir::r4::JsonFhirStringToProto;
template <typename R>
std::vector<R> ReadNdJsonFile(std::string filename) {
std::ifstream read_stream;
read_stream.open(absl::StrCat(filename));
absl::TimeZone time_zone;
CHECK(absl::LoadTimeZone("America/Los_Angeles", &time_zone));
std::vector<R> result;
std::string line;
while (!read_stream.eof()) {
std::getline(read_stream, line);
if (!line.length()) continue;
StatusOr<R> status_or_proto = JsonFhirStringToProto<R>(line, time_zone);
if (!status_or_proto.ok()) {
std::cout << "Failed to parse a record to "
<< R::descriptor()->full_name() << ": "
<< status_or_proto.status().message() << std::endl;
continue;
}
result.push_back(status_or_proto.ValueOrDie());
std::cout << "Parsed Patient " << result.back().id().value() << std::endl;
}
return result;
}
} // namespace fhir_examples
| 30.409836 | 78 | 0.692722 | [
"vector"
] |
c41ee4f3a0909eee4d889d96aa2a32a7894e6016 | 8,144 | c | C | c.c | alpha123/are | e94c597e00125fff1f0cdd9aa427c6b293fe88e7 | [
"Unlicense"
] | 4 | 2018-07-21T17:46:36.000Z | 2021-01-19T23:50:19.000Z | c.c | alpha123/are | e94c597e00125fff1f0cdd9aa427c6b293fe88e7 | [
"Unlicense"
] | null | null | null | c.c | alpha123/are | e94c597e00125fff1f0cdd9aa427c6b293fe88e7 | [
"Unlicense"
] | null | null | null | /**
* c.c - compile strings to bytecode
*/
#pragma once
#include "a.h"
#include "u.c"
#include "v.c"
#include "qp.c"
/**
* token types:
* - integer literals (I)
* - floating point literals (F)
* - string literals (S)
* - symbol literals (Y)
* - words
* - short word (1 codepoint)
* - punctuation: ()[]{};
*
* There's a trick used here: enum values for the punctuation tokens are
* '()[]{};' - '(' (the lowest UTF-8 value), which means the tokenizer can
* set the token value for those by simply subtracting '(' from the current
* character.
*/
typedef enum{ tLP=0, tRP=1, tSC=19, tLB=51, tRB=53, tLC=83, tRC=85, tW, tSW, tI, tF, tS, tY }TT;
typedef struct{union{I32 i;F64 f;CP c;S s;};TT t;}T;
#define rfn(n,...) USZ n(T *t,USZ z,U8B s[z]){USZ l=0;__VA_ARGS__;R l;}
rfn(rw, t->t=tW;while(l<z&&isalpha(s[l])){++l;}t->s=snew((U32)l,s))
rfn(rsw, t->t=tSW;E e=u8d(z,s,&t->c,&l);assert(e==0))
rfn(ri, t->t=tI;t->i=0;while(isdigit(*s)){t->i*=10;t->i+=*s-'0';++s;++l;})
rfn(rf, t->t=tF;F64 wp=t->i,f=0.0,d=10.0;while(isdigit(*s)){f+=(F64)(*s-'0')/d;d*=10.0;++s;++l;}t->f=wp+f)
rfn(rnum, l=ri(t,z,s);if(s[1]=='.'&&z>2){l+=rf(t,z-2,s+2)+1;})
rfn(ry, l=rw(t,z-1,s+1)+1;t->t=tY)
rfn(rsl, t->t=tS;while(l<z&&s[l]!='}'){++l;}t->s=snew((U32)l-1,s+1);++l)
USZ nt(T *t,USZ z,U8B s[z]) {
USZ l=0;while(isspace(*s)){++l;++s;}
switch(*s) {
C ANY('(',')','[',']',';'):t->t=*s-'(';R l+1;
C '.':R l+ry(t,z,s);
C '{':R l+rsl(t,z,s);
default:R l+CONDE(isdigit(*s),rnum(t,z,s), isalpha(*s),rw(t,z,s), rsw(t,z,s)); }}
typedef enum{
bcPushI, bcPushF, bcPushS, bcMkArray, bcJmp, bcRet, bcCall, bcCallQ, bcCallPower,
bcSwap, bcDrop, bcDup, bcDip, bcKeep, bcPopRP, bcQuot, bcIota, bcIndex, bcShape, bcReshape,
bcNeg, bcNot, bcSgn, bcAdd, bcMul, bcSub, bcDiv, bcMod, bcMin, bcMax, bcEq, bcGt, bcLt, bcGte, bcLte,
bcCat, bcReplicate, bcTake, bcEach, bcReduce
}BCT;
typedef struct{U32 z,l;U8 *b;}BC;
BC *bcnew(USZ iz){BC *b=ca(1,szof(BC));b->z=iz;b->b=ma(iz);R b;}
void bcfree(BC *b){free(b->b);free(b);}
void bcgrw(BC *b){b->b=ra(b->b,b->z+=100);}
#define emit(x) bcemit(b,x)
#define emiti(x) bcemiti(b,x)
#define emitp(x) bcemitp(b,x)
void bcemit(BC *b,U8 w){if(b->l==b->z){bcgrw(b);}b->b[b->l++]=w;}
void bcemiti(BC *b,U32 i){DO(4,emit(0))*(U32 *)(b->b+b->l-4)=i;}
void bcemitf(BC *b,F64 f){DO(8,emit(0))*(F64 *)(b->b+b->l-8)=f;}
void bcemitp(BC *b,UIP p){DO(szof(UIP),emit(0))*(UIP *)(b->b+b->l-szof(UIP))=p;}
#define seti(i,x) (*(U32 *)(b->b+(i))=x)
#define rt() (tl=nt(&t,z-i,s+i))
USZ ct(BC *b,WD **d,USZ z,U8B s[z]);
void ci(BC *b,I32 i){emit(bcPushI);emiti((U32)i);}
void cf(BC *b,F64 f){emit(bcPushF);bcemitf(b,f);}
void cs(BC *b,S s){emit(bcPushS);emitp((UIP)s);}
USZ cr(BC *b,WD **d,USZ z,U8B s[z]) {
T t;USZ i=0,tl;U32 tc=0;
while(i<z){rt();if(t.t==tRP){i+=tl;B;}++tc;i+=ct(b,d,z-i,s+i);}emit(bcMkArray);emiti(tc);R i; }
USZ cq_(BC *b,WD **d,USZ z,U8B s[z],U32 *nq) {
T t;USZ i=0,tl;emit(bcQuot);emiti(0);U32 o=b->l;
while(i<z) {
rt();
if(t.t==tRB){i+=tl;emit(bcRet);B;}
else if(t.t==tSC){i+=tl;++*nq;emit(bcRet);seti(o-szof(U32),b->l-o);i+=cq_(b,d,z-i,s+i,nq);R i;}
else{i+=ct(b,d,z-i,s+i);} }
seti(o-szof(U32),b->l-o);R i; }
USZ cq(BC *b,WD **d,USZ z,U8B s[z]){U32 nq=1;USZ l=cq_(b,d,z,s,&nq);if(nq>1){emit(bcMkArray);emiti(nq);}R l;}
USZ csq(BC *b,WD **d,USZ z,U8B s[z]) {
emit(bcQuot);emiti(0);U32 o=b->l;USZ i=ct(b,d,z,s);emit(bcRet);seti(o-szof(U32),b->l-o);R i; }
void csw(BC *b,CP c){}
USZ cd(BC *b,WD **d,USZ z,U8B s[z]) {
USZ i=0,tl;T t;rt();i+=tl;if(t.t!=tW){puts("invalid word name");R i;}
emit(bcJmp);emiti(0);U32 o=b->l;
*d=Tsetl(*d,t.s,o);while(i<z){rt();i+=ct(b,d,z-i,s+i);if(t.t==tSW&&t.c==0x3B){B;}}
seti(o-szof(U32),b->l-o);R i; }
void cw(BC *b,WD *d,S w) {
U32 j;if(!Tgetkv(d,w,&w,&j)){printf("unknown word %.*s\n",(int)slen(w),w);R;}
emit(bcCall);emiti(j); }
USZ ct(BC *b,WD **d,USZ z,U8B s[z]) {
USZ i=0,tl;T t;rt();i+=tl;
switch(t.t) {
C tI:ci(b,t.i);B;
C tF:cf(b,t.f);B;
C tS:cs(b,t.s);B;
C tLB:i+=cq(b,d,z-tl,s+tl);B;
C tLP:i+=cr(b,d,z-tl,s+tl);B;
C tSC:emit(bcRet);B;
C tSW:switch(t.c) {
C 0x22:emit(bcIndex);B;
C 0x27:i+=csq(b,d,z-tl,s+tl);B;
C 0x2B:emit(bcAdd);B;
C 0x2C:emit(bcCat);B;
C 0x2D:emit(bcSub);B;
C 0xD7:emit(bcMul);B;
C 0xF7:emit(bcDiv);B;
C 0x7C:emit(bcMod);B;
C 0x7E:emit(bcNeg);B;
C 0xA8:emit(bcEach);B;
C 0xAC:emit(bcNot);B;
C 0x3D:emit(bcEq);B;
C 0x2260:emit(bcEq);emit(bcNot);B;
C 0x3E:emit(bcGt);B;
C 0x3C:emit(bcLt);B;
C 0x2265:emit(bcGte);B;
C 0x2264:emit(bcLte);B;
C 0x2F:emit(bcReduce);B;
C 0x3A:i+=cd(b,d,z-tl,s+tl);B;
C 0x3B9:emit(bcIota);B;
C 0x3C1:emit(bcReshape);B;
C 0x3C3:emit(bcShape);B;
C 0x2218:emit(bcCallQ);B;
C 0x2365:emit(bcCallPower);B;
C 0x2B59:emit(bcSgn);B;
C 0x2021:emit(bcDup);B;
C 0x21A7:emit(bcDrop);B;
C 0x296F:emit(bcSwap);B;
C 0x2193:emit(bcDip);emit(bcPopRP);B;
C 0x2B71:emit(bcKeep);B;
C 0x25B3:emit(bcMax);B;
C 0x25BD:emit(bcMin);B;
C 0x2191:emit(bcTake);B;
C 0x3003:emit(bcReplicate);B;
default:csw(b,t.c); }
B;
C tW:cw(b,*d,t.s);B;
}
R i; }
void cmpl(BC *b,WD **d,USZ z,U8B s[z]){for(USZ i=0;i<z;){i+=ct(b,d,z-i,s+i);}}
#define decodei() (*(U32 *)(b->b+i+1))
#define decodef() (*(F64 *)(b->b+i+1))
#define decodep() (*(UIP *)(b->b+i+1))
void dumpbc(BC *b) {
for(USZ i=0;i<b->l;++i) {
printf("%zu\t",i);
switch(b->b[i]) {
C bcPushI:printf("PUSHI %"PRIi32"\n",(I32)decodei());i+=4;B;
C bcPushF:printf("PUSHF %f\n",decodef());i+=8;B;
C bcPushS:printf("PUSHS 0x%"PRIxPTR"\n",decodep());i+=szof(UIP);B;
C bcMkArray:printf("MKARRAY %"PRIu32"\n",decodei());i+=4;B;
C bcQuot:printf("QUOT %"PRIu32"\n",decodei());i+=4;B;
C bcJmp:printf("JMP %"PRIu32"\n",decodei());i+=4;B;
C bcRet:puts("RET");B;
C bcCall:printf("CALL %"PRIu32"\n",decodei());i+=4;B;
C bcCallQ:puts("CALLQ");B;
C bcSwap:puts("SWAP");B;C bcDrop:puts("DROP");B;C bcDup:puts("DUP");B;
C bcDip:puts("DIP");B;C bcPopRP:puts("POPRP");B;
C bcIota:puts("IOTA");B;C bcIndex:puts("INDEX");B;
C bcShape:puts("SHAPE");B;C bcReshape:puts("RESHAPE");B;
C bcNeg:puts("NEG");B;C bcNot:puts("NOT");B;C bcSgn:puts("SGN");B;
C bcAdd:puts("ADD");B;C bcMul:puts("MUL");B;C bcSub:puts("SUB");B;
C bcDiv:puts("DIV");B;C bcMod:puts("MOD");B;
C bcMin:puts("MIN");B;C bcMax:puts("MAX");B;
C bcEq:puts("EQ");B;C bcGt:puts("GT");B;C bcLt:puts("LT");B;
C bcGte:puts("GTE");B;C bcLte:puts("LTE");B;
C bcReplicate:puts("REPLICATE");B;C bcCat:puts("CAT");B;C bcTake:puts("TAKE");B;
C bcEach:puts("EACH");B;C bcReduce:puts("REDUCE");B;
default:puts("?"); }}}
#undef decodei
#undef decodef
#undef decodep
#if AREPL
#include "linenoise.c"
#include "linenoise-utf8.h"
#include "linenoise-utf8.c"
int main(int argc,char**argv) {
char*line;
T t;
linenoiseSetEncodingFunctions(linenoiseUtf8PrevCharLen,linenoiseUtf8NextCharLen,linenoiseUtf8ReadCode);
while((line=linenoise("a> "))) {
USZ z=strlen(line);
for(USZ i=0;i<z;) {
i+=nt(&t,z-i,line+i);
//printf("span %zu\n",i);
switch(t.t) {
C tW: printf("%.*s\n",slen(t.s),t.s);sfree(t.s);B;
C tSW: printf("0x%"PRIx32"\n",t.c); B;
C tI: printf("%"PRIi32"\n",t.i); B;
C tF: printf("%f\n",t.f); B;
C tY: printf(".%.*s\n",slen(t.s),t.s);sfree(t.s);B;
C tS: printf("{%.*s}\n",slen(t.s),t.s);sfree(t.s);B;
default: putchar('('+(char)t.t);putchar('\n'); }}
WD *d=NULL;BC *b=bcnew(256);cmpl(b,&d,z,line);
dumpbc(b);
bcfree(b);
linenoiseFree(line); }
R 0; }
#endif
| 39.726829 | 110 | 0.537574 | [
"shape"
] |
c4217fa119af40ea9364442bc496bd6b7ea905ff | 1,119 | h | C | src/MayaBridge/PointCloudShape/NuiMayaMappableDataIterator.h | hustztz/NatureUserInterfaceStudio | 3cdac6b6ee850c5c8470fa5f1554c7447be0d8af | [
"MIT"
] | 3 | 2016-07-14T13:04:35.000Z | 2017-04-01T09:58:27.000Z | src/MayaBridge/PointCloudShape/NuiMayaMappableDataIterator.h | hustztz/NatureUserInterfaceStudio | 3cdac6b6ee850c5c8470fa5f1554c7447be0d8af | [
"MIT"
] | null | null | null | src/MayaBridge/PointCloudShape/NuiMayaMappableDataIterator.h | hustztz/NatureUserInterfaceStudio | 3cdac6b6ee850c5c8470fa5f1554c7447be0d8af | [
"MIT"
] | 1 | 2021-11-21T15:33:35.000Z | 2021-11-21T15:33:35.000Z | #pragma once
////////////////////////////////////////////////////////////////////////////////
//
// Point iterator for control-point based geometry
//
// This is used by the translate/rotate/scale manipulators to
// determine where to place the manipulator when components are
// selected.
//
// As well deformers use this class to deform points of the shape.
//
////////////////////////////////////////////////////////////////////////////////
#include <maya/MPxGeometryIterator.h>
#include "Shape/NuiCLMappableData.h"
class NuiMayaMappableDataIterator : public MPxGeometryIterator
{
public:
NuiMayaMappableDataIterator( void * userGeometry, MObjectArray & components );
NuiMayaMappableDataIterator( void * userGeometry, MObject & components );
//////////////////////////////////////////////////////////
//
// Overrides
//
//////////////////////////////////////////////////////////
virtual void reset();
virtual MPoint point() const;
virtual void setPoint( const MPoint & ) const;
virtual int iteratorCount() const;
virtual bool hasPoints() const;
public:
NuiCLMappableData* geomPtr;
};
| 28.692308 | 80 | 0.559428 | [
"geometry",
"shape"
] |
c425c3e57f766592cde8cd4d72d0996ba1750876 | 2,475 | h | C | RootFormat/interface/MiniEvent.h | enochnotsocool/TstarAnalysis_in_CMS | 84e695e7fc43188fcabe18468399a5fe4b909efb | [
"MIT"
] | null | null | null | RootFormat/interface/MiniEvent.h | enochnotsocool/TstarAnalysis_in_CMS | 84e695e7fc43188fcabe18468399a5fe4b909efb | [
"MIT"
] | null | null | null | RootFormat/interface/MiniEvent.h | enochnotsocool/TstarAnalysis_in_CMS | 84e695e7fc43188fcabe18468399a5fe4b909efb | [
"MIT"
] | null | null | null | /*******************************************************************************
*
* Filename : MiniEvent.h
* Description : Minimal implementation of event for combine analysis
* Author : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ]
*
*
*******************************************************************************/
#ifndef __MINIEVENT_H__
#define __MINIEVENT_H__
#include <vector>
#ifdef CMSSW
#include "TstarAnalysis/RootFormat/interface/MiniJet.h"
#include "TstarAnalysis/RootFormat/interface/MiniMuon.h"
#include "TstarAnalysis/RootFormat/interface/MiniElectron.h"
#include "TstarAnalysis/RootFormat/interface/ChiSquareResult.h"
#include "TstarAnalysis/RootFormat/interface/HitFitResult.h"
#else
#include "MiniJet.h"
#include "MiniMuon.h"
#include "MiniElectron.h"
#include "ChiSquareResult.h"
#include "HitFitResult.h"
#endif
class MiniEvent
{
public:
MiniEvent();
virtual ~MiniEvent ();
void SetRunNumber( const unsigned );
void SetLumiNumber( const unsigned long long );
void SetEventNumber( const unsigned );
void SetBunchCrossing( const unsigned );
unsigned RunNumber() const ;
unsigned EventNumber() const;
unsigned BunchCrossing() const;
unsigned long long LumiNumber() const;
void SetPileUp( const unsigned );
unsigned PileUp() const;
void SetTotalWeight( const double );
double TotalEventWeight() const;
void SetMet( const double, const double );
double MET() const;
double METPhi() const;
std::vector<MiniJet>& JetList();
std::vector<MiniMuon>& MuonList() ;
std::vector<MiniElectron>& ElectronList();
ChiSquareResult& GetChiSquare();
HitFitResult& GetHitFit();
void AddJet( const MiniJet& );
void AddMuon( const MiniMuon& );
void AddElectron( const MiniElectron& );
void ClearLists();
private:
//----- Event id number -------------------------------------------------------
unsigned _runNumber;
unsigned long long _lumiNumber;
unsigned _eventNumber;
unsigned _bunchCrossingNumber;
unsigned _pileup;
double _totalEventWeight;
double _met;
double _metphi;
//----- LCD dictionary generation doesn't play well with const ----------------
std::vector<MiniJet> _jetList;
std::vector<MiniMuon> _muonList;
std::vector<MiniElectron> _electronList;
ChiSquareResult _chisqresult;
HitFitResult _hitfitresult;
};
#endif // __MINIEVENT_H__
| 28.448276 | 83 | 0.636768 | [
"vector"
] |
c4386e64e0ce3b1810ad27e1b11c38eeec174f1d | 15,440 | h | C | MinGW/include/_mingw.h | pedrofernandesfilho/MinGWMSYSProtable | d28394ab24227be78cbf84d6c04329aea5ed2ffa | [
"MIT"
] | 1 | 2017-08-29T18:48:03.000Z | 2017-08-29T18:48:03.000Z | MinGW/include/_mingw.h | pedrofernandesfilho/MinGWMSYSPortable | d28394ab24227be78cbf84d6c04329aea5ed2ffa | [
"MIT"
] | null | null | null | MinGW/include/_mingw.h | pedrofernandesfilho/MinGWMSYSPortable | d28394ab24227be78cbf84d6c04329aea5ed2ffa | [
"MIT"
] | null | null | null | #ifndef __MINGW_H
/*
* _mingw.h
*
* Mingw specific macros included by ALL include files.
*
* This file is part of the Mingw32 package.
*
* Contributors:
* Created by Mumit Khan <khan@xraylith.wisc.edu>
*
* THIS SOFTWARE IS NOT COPYRIGHTED
*
* This source code is offered for use in the public domain. You may
* use, modify or distribute it freely.
*
* This code is distributed in the hope that it will be useful but
* WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY
* DISCLAIMED. This includes but is not limited to warranties of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
*/
#define __MINGW_H
/* In previous versions, __MINGW32_VERSION was expressed as a dotted
* numeric pair, representing major.minor; unfortunately, this doesn't
* adapt well to the inclusion of a patch-level component, since the
* major.minor.patch dotted triplet representation is not valid as a
* numeric entity. Thus, for this version, we adopt a representation
* which encodes the version as a long integer value, expressing:
*
* __MINGW32_VERSION = 1,000,000 * major + 1,000 * minor + patch
*/
#define __MINGW32_VERSION 3021000L
#define __MINGW32_MAJOR_VERSION 3
#define __MINGW32_MINOR_VERSION 21
#define __MINGW32_PATCHLEVEL 0
#if __GNUC__ >= 3
#ifndef __PCC__
#pragma GCC system_header
#endif
#endif
/* The following are defined by the user (or by the compiler), to specify how
* identifiers are imported from a DLL. All headers should include this first,
* and then use __DECLSPEC_SUPPORTED to choose between the old ``__imp__name''
* style or the __MINGW_IMPORT style for declarations.
*
* __DECLSPEC_SUPPORTED Defined if dllimport attribute is supported.
* __MINGW_IMPORT The attribute definition to specify imported
* variables/functions.
* _CRTIMP As above. For MS compatibility.
* __MINGW32_VERSION Runtime version.
* __MINGW32_MAJOR_VERSION Runtime major version.
* __MINGW32_MINOR_VERSION Runtime minor version.
* __MINGW32_BUILD_DATE Runtime build date.
*
* Macros to enable MinGW features which deviate from standard MSVC
* compatible behaviour; these may be specified directly in user code,
* activated implicitly, (e.g. by specifying _POSIX_C_SOURCE or such),
* or by inclusion in __MINGW_FEATURES__:
*
* __USE_MINGW_ANSI_STDIO Select a more ANSI C99 compatible
* implementation of printf() and friends.
*
* Other macros:
*
* __int64 define to be long long. Using a typedef
* doesn't work for "unsigned __int64"
*
*
* Manifest definitions for flags to control globbing of the command line
* during application start up, (before main() is called). The first pair,
* when assigned as bit flags within _CRT_glob, select the globbing algorithm
* to be used; (the MINGW algorithm overrides MSCVRT, if both are specified).
* Prior to mingwrt-3.21, only the MSVCRT option was supported; this choice
* may produce different results, depending on which particular version of
* MSVCRT.DLL is in use; (in recent versions, it seems to have become
* definitively broken, when globbing within double quotes).
*/
#define __CRT_GLOB_USE_MSVCRT__ 0x0001
/* From mingwrt-3.21 onward, this should be the preferred choice; it will
* produce consistent results, regardless of the MSVCRT.DLL version in use.
*/
#define __CRT_GLOB_USE_MINGW__ 0x0002
/* When the __CRT_GLOB_USE_MINGW__ flag is set, within _CRT_glob, the
* following additional options are also available; they are not enabled
* by default, but the user may elect to enable any combination of them,
* by setting _CRT_glob to the boolean sum (i.e. logical OR combination)
* of __CRT_GLOB_USE_MINGW__ and the desired options.
*
* __CRT_GLOB_USE_SINGLE_QUOTE__ allows use of single (apostrophe)
* quoting characters, analogously to
* POSIX usage, as an alternative to
* double quotes, for collection of
* arguments separated by white space
* into a single logical argument.
*
* __CRT_GLOB_BRACKET_GROUPS__ enable interpretation of bracketed
* character groups as POSIX compatible
* globbing patterns, matching any one
* character which is either included
* in, or excluded from the group.
*
* __CRT_GLOB_CASE_SENSITIVE__ enable case sensitive matching for
* globbing patterns; this is default
* behaviour for POSIX, but because of
* the case insensitive nature of the
* MS-Windows file system, it is more
* appropriate to use case insensitive
* globbing as the MinGW default.
*
*/
#define __CRT_GLOB_USE_SINGLE_QUOTE__ 0x0010
#define __CRT_GLOB_BRACKET_GROUPS__ 0x0020
#define __CRT_GLOB_CASE_SENSITIVE__ 0x0040
/* The MinGW globbing algorithm uses the ASCII DEL control code as a marker
* for globbing characters which were embedded within quoted arguments; (the
* quotes are stripped away BEFORE the argument is globbed; the globbing code
* treats the marked character as immutable, and strips out the DEL markers,
* before storing the resultant argument). The DEL code is mapped to this
* function here; DO NOT change it, without rebuilding the runtime.
*/
#define __CRT_GLOB_ESCAPE_CHAR__ (char)(127)
/* Manifest definitions identifying the flag bits, controlling activation
* of MinGW features, as specified by the user in __MINGW_FEATURES__.
*/
#define __MINGW_ANSI_STDIO__ 0x0000000000000001ULL
/*
* The following three are not yet formally supported; they are
* included here, to document anticipated future usage.
*/
#define __MINGW_LC_EXTENSIONS__ 0x0000000000000050ULL
#define __MINGW_LC_MESSAGES__ 0x0000000000000010ULL
#define __MINGW_LC_ENVVARS__ 0x0000000000000040ULL
/* Try to avoid problems with outdated checks for GCC __attribute__ support.
*/
#undef __attribute__
#if defined (__PCC__)
# undef __DECLSPEC_SUPPORTED
# ifndef __MINGW_IMPORT
# define __MINGW_IMPORT extern
# endif
# ifndef _CRTIMP
# define _CRTIMP
# endif
# ifndef __cdecl
# define __cdecl _Pragma("cdecl")
# endif
# ifndef __stdcall
# define __stdcall _Pragma("stdcall")
# endif
# ifndef __int64
# define __int64 long long
# endif
# ifndef __int32
# define __int32 long
# endif
# ifndef __int16
# define __int16 short
# endif
# ifndef __int8
# define __int8 char
# endif
# ifndef __small
# define __small char
# endif
# ifndef __hyper
# define __hyper long long
# endif
# ifndef __volatile__
# define __volatile__ volatile
# endif
# ifndef __restrict__
# define __restrict__ restrict
# endif
# define NONAMELESSUNION
#elif defined(__GNUC__)
# ifdef __declspec
# ifndef __MINGW_IMPORT
/* Note the extern. This is needed to work around GCC's
limitations in handling dllimport attribute. */
# define __MINGW_IMPORT extern __attribute__ ((__dllimport__))
# endif
# ifndef _CRTIMP
# ifdef __USE_CRTIMP
# define _CRTIMP __attribute__ ((dllimport))
# else
# define _CRTIMP
# endif
# endif
# define __DECLSPEC_SUPPORTED
# else /* __declspec */
# undef __DECLSPEC_SUPPORTED
# undef __MINGW_IMPORT
# ifndef _CRTIMP
# define _CRTIMP
# endif
# endif /* __declspec */
/*
* The next two defines can cause problems if user code adds the
* __cdecl attribute like so:
* void __attribute__ ((__cdecl)) foo(void);
*/
# ifndef __cdecl
# define __cdecl __attribute__ ((__cdecl__))
# endif
# ifndef __stdcall
# define __stdcall __attribute__ ((__stdcall__))
# endif
# ifndef __int64
# define __int64 long long
# endif
# ifndef __int32
# define __int32 long
# endif
# ifndef __int16
# define __int16 short
# endif
# ifndef __int8
# define __int8 char
# endif
# ifndef __small
# define __small char
# endif
# ifndef __hyper
# define __hyper long long
# endif
#else /* ! __GNUC__ && ! __PCC__ */
# ifndef __MINGW_IMPORT
# define __MINGW_IMPORT __declspec(dllimport)
# endif
# ifndef _CRTIMP
# define _CRTIMP __declspec(dllimport)
# endif
# define __DECLSPEC_SUPPORTED
# define __attribute__(x) /* nothing */
#endif
#if defined (__GNUC__) && defined (__GNUC_MINOR__)
#define __MINGW_GNUC_PREREQ(major, minor) \
(__GNUC__ > (major) \
|| (__GNUC__ == (major) && __GNUC_MINOR__ >= (minor)))
#else
#define __MINGW_GNUC_PREREQ(major, minor) 0
#endif
#ifdef __cplusplus
# define _EXTERN_C extern "C"
# define _BEGIN_C_DECLS extern "C" {
# define _END_C_DECLS }
# define __CRT_INLINE inline
#else
# define _EXTERN_C extern
# define _BEGIN_C_DECLS
# define _END_C_DECLS
# if __GNUC_STDC_INLINE__
# define __CRT_INLINE extern inline __attribute__((__gnu_inline__))
# else
# define __CRT_INLINE extern __inline__
# endif
#endif
# ifdef __GNUC__
/* A special form of __CRT_INLINE, to ALWAYS request inlining when
* possible is provided; originally specified as _CRTALIAS, this is
* now deprecated in favour of __CRT_ALIAS, for syntactic consistency
* with __CRT_INLINE itself.
*/
# define _CRTALIAS __CRT_INLINE __attribute__((__always_inline__))
# define __CRT_ALIAS __CRT_INLINE __attribute__((__always_inline__))
# else
# define _CRTALIAS __CRT_INLINE /* deprecated form */
# define __CRT_ALIAS __CRT_INLINE /* preferred form */
# endif
/*
* Each function which is implemented as a __CRT_ALIAS should also be
* accompanied by an externally visible interface. The following pair
* of macros provide a mechanism for implementing this, either as a stub
* redirecting to an alternative external function, or by compilation of
* the normally inlined code into free standing object code; each macro
* provides a way for us to offer arbitrary hints for use by the build
* system, while remaining transparent to the compiler.
*/
#define __JMPSTUB__(__BUILD_HINT__)
#define __LIBIMPL__(__BUILD_HINT__)
#ifdef __cplusplus
# define __UNUSED_PARAM(x)
#else
# ifdef __GNUC__
# define __UNUSED_PARAM(x) x __attribute__ ((__unused__))
# else
# define __UNUSED_PARAM(x) x
# endif
#endif
#ifdef __GNUC__
#define __MINGW_ATTRIB_NORETURN __attribute__ ((__noreturn__))
#define __MINGW_ATTRIB_CONST __attribute__ ((__const__))
#else
#define __MINGW_ATTRIB_NORETURN
#define __MINGW_ATTRIB_CONST
#endif
#if __MINGW_GNUC_PREREQ (3, 0)
#define __MINGW_ATTRIB_MALLOC __attribute__ ((__malloc__))
#define __MINGW_ATTRIB_PURE __attribute__ ((__pure__))
#else
#define __MINGW_ATTRIB_MALLOC
#define __MINGW_ATTRIB_PURE
#endif
/* Attribute `nonnull' was valid as of gcc 3.3. We don't use GCC's
variadiac macro facility, because variadic macros cause syntax
errors with --traditional-cpp. */
#if __MINGW_GNUC_PREREQ (3, 3)
#define __MINGW_ATTRIB_NONNULL(arg) __attribute__ ((__nonnull__ (arg)))
#else
#define __MINGW_ATTRIB_NONNULL(arg)
#endif /* GNUC >= 3.3 */
#if __MINGW_GNUC_PREREQ (3, 1)
#define __MINGW_ATTRIB_DEPRECATED __attribute__ ((__deprecated__))
#else
#define __MINGW_ATTRIB_DEPRECATED
#endif /* GNUC >= 3.1 */
#if __MINGW_GNUC_PREREQ (3, 3)
#define __MINGW_NOTHROW __attribute__ ((__nothrow__))
#else
#define __MINGW_NOTHROW
#endif /* GNUC >= 3.3 */
/* TODO: Mark (almost) all CRT functions as __MINGW_NOTHROW. This will
allow GCC to optimize away some EH unwind code, at least in DW2 case. */
#ifndef __MSVCRT_VERSION__
/* High byte is the major version, low byte is the minor. */
# define __MSVCRT_VERSION__ 0x0600
#endif
/* Activation of MinGW specific extended features:
*/
#ifndef __USE_MINGW_ANSI_STDIO
/*
* We must check this BEFORE we specifiy any implicit _POSIX_C_SOURCE,
* otherwise we would always implicitly choose __USE_MINGW_ANSI_STDIO;
* if user didn't specify it explicitly...
*/
# if defined __STRICT_ANSI__ || defined _ISOC99_SOURCE \
|| defined _POSIX_SOURCE || defined _POSIX_C_SOURCE \
|| defined _XOPEN_SOURCE || defined _XOPEN_SOURCE_EXTENDED \
|| defined _GNU_SOURCE || defined _BSD_SOURCE \
|| defined _SVID_SOURCE
/*
* but where any of these source code qualifiers are specified,
* then assume ANSI I/O standards are preferred over Microsoft's...
*/
# define __USE_MINGW_ANSI_STDIO 1
# else
/* otherwise use whatever __MINGW_FEATURES__ specifies...
*/
# define __USE_MINGW_ANSI_STDIO (__MINGW_FEATURES__ & __MINGW_ANSI_STDIO__)
# endif
#endif
#ifndef _POSIX_C_SOURCE
/*
* Users may define this, either directly or indirectly, to explicitly
* enable a particular level of visibility for the subset of those POSIX
* features which are supported by MinGW; (notice that this offers no
* guarantee that any particular POSIX feature will be supported).
*/
# if defined _XOPEN_SOURCE
/*
* Specifying this is the preferred method for setting _POSIX_C_SOURCE;
* (POSIX defines an explicit relationship to _XOPEN_SOURCE). Note that
* any such explicit setting will augment the set of features which are
* available to any compilation unit, even if it seeks to be strictly
* ANSI-C compliant.
*/
# if _XOPEN_SOURCE < 500
# define _POSIX_C_SOURCE 1L /* POSIX.1-1990 / SUSv1 */
# elif _XOPEN_SOURCE < 600
# define _POSIX_C_SOURCE 199506L /* POSIX.1-1996 / SUSv2 */
# elif _XOPEN_SOURCE < 700
# define _POSIX_C_SOURCE 200112L /* POSIX.1-2001 / SUSv3 */
# else
# define _POSIX_C_SOURCE 200809L /* POSIX.1-2008 / SUSv4 */
# endif
# elif defined _GNU_SOURCE || defined _BSD_SOURCE || ! defined __STRICT_ANSI__
/*
* No explicit level of support has been specified; implicitly grant
* the most comprehensive level to any compilation unit which requests
* either GNU or BSD feature support, or does not seek to be strictly
* ANSI-C compliant.
*/
# define _POSIX_C_SOURCE 200809L
# elif defined _POSIX_SOURCE
/*
* Now formally deprecated by POSIX, some old code may specify this;
* it will enable a minimal level of POSIX support, in addition to the
* limited feature set enabled for strict ANSI-C conformity.
*/
# define _POSIX_C_SOURCE 1L
# endif
#endif
/* Only Microsoft could attempt to justify this insanity: when building
* a UTF-16LE application -- apparently their understanding of Unicode is
* limited to this -- the C/C++ runtime requires that the user must define
* the _UNICODE macro, while to use the Windows API's UTF-16LE capabilities,
* it is the UNICODE macro, (without the leading underscore), which must be
* defined. The (bogus) explanation appears to be that it is the C standard
* which dictates the requirement for the leading underscore, to avoid any
* possible conflict with a user defined symbol; (bogus because the macro
* must be user defined anyway -- it is not a private symbol -- and in
* any case, the Windows API already reserves the UNICODE symbol as
* a user defined macro, with equivalent intent.
*
* The real explanation, of course, is that this is just another example
* of Microsoft irrationality; in any event, there seems to be no sane
* scenario in which defining one without the other would be required,
* or indeed would not raise potential for internal inconsistency, so we
* ensure that either both are, or neither is defined.
*/
#if defined UNICODE && ! defined _UNICODE
# define _UNICODE UNICODE
#endif
#if defined _UNICODE && ! defined UNICODE
# define UNICODE _UNICODE
#endif
#endif /* __MINGW_H */
| 33.934066 | 79 | 0.736464 | [
"object"
] |
c439626541409ca68e8156da2985899b6eb2083b | 959 | h | C | Pods/Clarifai-Apple-SDK/Clarifai_Apple_SDK.framework/Headers/CAIOutput.h | SaAPro/DoubleProject | 6b75c8b572d73bdea510a1a90e05d02d4093432c | [
"MIT"
] | null | null | null | Pods/Clarifai-Apple-SDK/Clarifai_Apple_SDK.framework/Headers/CAIOutput.h | SaAPro/DoubleProject | 6b75c8b572d73bdea510a1a90e05d02d4093432c | [
"MIT"
] | null | null | null | Pods/Clarifai-Apple-SDK/Clarifai_Apple_SDK.framework/Headers/CAIOutput.h | SaAPro/DoubleProject | 6b75c8b572d73bdea510a1a90e05d02d4093432c | [
"MIT"
] | null | null | null | //
// CAIOutput.h
// Clarifai-Apple-SDK
//
// Copyright © 2017 Clarifai. All rights reserved.
//
#import "CAIDataModel.h"
@class CAIDataAsset;
@class CAIOutputConfiguration;
@class CAIStatus;
NS_SWIFT_NAME(Output)
@interface CAIOutput : CAIDataModel <NSCoding>
/// Output configuration with regards to the Model
@property (nonatomic, strong, nonnull, readonly) CAIOutputConfiguration *configuration;
/// DataAsset associated with the Output
@property (nonatomic, strong, nonnull, readonly) CAIDataAsset *dataAsset;
/// Helps to know what type of DataAsset to expect out of the model.
@property (nonatomic, strong, nonnull, readonly) NSString *type;
/// Extra information about the type.
@property (nonatomic, strong, nonnull, readonly) NSString *typeExtra;
- (nonnull instancetype)initWithDataAsset:(nonnull CAIDataAsset *)dataAsset configuration:(nonnull CAIOutputConfiguration *)configuration NS_SWIFT_NAME(init(dataAsset:configuration:));
@end
| 29.96875 | 184 | 0.778936 | [
"model"
] |
c43c932e61d2d3077cdb9d9fdc45cb688f9285cd | 11,345 | h | C | src/memcpy_gemm_lib.h | google/memcpy-gemm | b84732ec0c1b1de02b8358e60c1ad8fb45befc69 | [
"Apache-2.0"
] | 9 | 2019-12-11T09:51:27.000Z | 2021-10-13T02:33:17.000Z | src/memcpy_gemm_lib.h | google/memcpy-gemm | b84732ec0c1b1de02b8358e60c1ad8fb45befc69 | [
"Apache-2.0"
] | 5 | 2019-12-19T17:37:52.000Z | 2021-07-21T15:39:11.000Z | src/memcpy_gemm_lib.h | google/memcpy-gemm | b84732ec0c1b1de02b8358e60c1ad8fb45befc69 | [
"Apache-2.0"
] | 5 | 2020-01-16T18:53:38.000Z | 2020-11-14T01:13:54.000Z | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 PLATFORMS_GPUS_TESTING_NVIDIA_MEMCPY_GEMM_LIB_H_
#define PLATFORMS_GPUS_TESTING_NVIDIA_MEMCPY_GEMM_LIB_H_
#include <stddef.h>
#include <cstdint>
#include <map>
#include <memory>
#include <string>
#include <thread> // NOLINT(build/c++11)
#include <utility>
#include <vector>
#include "glog/logging.h"
#include "absl/memory/memory.h"
#include "absl/synchronization/notification.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "src/gemm_test_lib.h"
#include "cuda/include/cuda_runtime.h"
namespace platforms_gpus {
namespace memcpy_gemm {
enum DeviceType { CPU, GPU };
typedef std::pair<DeviceType, int> DeviceSpec;
std::string DeviceSpecToString(DeviceSpec dev);
// Allocates the buffer on CPU or GPU.
class BufferPool {
public:
explicit BufferPool(size_t size) : size_(size) {}
// buffer_index == -1 creates an anonymous buffer
char *GetBuffer(DeviceSpec dev, int buffer_index);
~BufferPool();
BufferPool(const BufferPool &) = delete;
BufferPool &operator=(const BufferPool &) = delete;
protected:
size_t size_;
std::map<DeviceSpec, std::vector<char *>> buffers_;
};
// Stores description of the flow.
class Flow {
public:
Flow(DeviceSpec from_dev, char *from_mem, DeviceSpec to_dev, char *to_mem,
size_t buf_size, std::atomic<int> *counter)
: from_dev_(from_dev),
from_mem_(from_mem),
to_dev_(to_dev),
to_mem_(to_mem),
buf_size_(buf_size),
counter_(counter) {}
int from_dev_flow_cnt_ = 0;
int to_dev_flow_cnt_ = 0;
DeviceSpec from_dev_;
char *from_mem_;
DeviceSpec to_dev_;
char *to_mem_;
size_t buf_size_;
std::atomic<int> *counter_;
cudaStream_t stream_;
};
class PulseBarrier {
public:
PulseBarrier(absl::Duration high_time, absl::Duration low_time,
bool sync_flows)
: high_time_(high_time), low_time_(low_time), sync_flows_(sync_flows) {}
// Returns the next high-time end time.
// Doesn't return until low_time has expired in this cycle.
absl::Time HighTimeDeadline() const {
absl::Time now = absl::Now();
absl::Time sync_now = now;
if (sync_flows_) {
// If requested to sync, align everything to the same window.
sync_now = absl::UnixEpoch() +
absl::Floor(now - absl::UnixEpoch(), low_time_ + high_time_);
}
// To ensure sleep precision, back off a bit and busy-poll.
absl::SleepFor(sync_now - now + low_time_ - absl::Milliseconds(20));
auto nanos = absl::ToUnixNanos(sync_now + low_time_);
while (absl::GetCurrentTimeNanos() < nanos) {
}
return sync_now + low_time_ + high_time_;
}
private:
absl::Duration high_time_;
absl::Duration low_time_;
bool sync_flows_;
};
// Tuning parameters for threads handling memcpy flows.
struct FlowThreadParameters {
// Timing parameters for the copy threads.
int64_t wait_ns;
std::string flow_model;
// Control which CUDA API is used to perform the memcpy.
bool use_cudaMemcpyPeerAsync; // NOLINT - suffix matches a CUDA convention.
bool use_cudaMemcpyDefault; // NOLINT - suffix matches a CUDA convention.
bool use_cudaComputeCopy;
bool use_group_by_dest;
// Copy batch_size buffers at a time.
int batch_size;
};
// The CopyThread will exit by setting stop_copying_ (set by the signal
// handler thread).
class CopyThread {
public:
CopyThread() = default;
virtual ~CopyThread() = default;
void StopCopying() { stop_copying_.Notify(); }
// Upon calling start, a new thread will be spawned executing Run().
virtual void Run() = 0;
// Execute the the contents of Run() in a new thread.
void Start();
// Wait until the thread has completed.
void Join();
protected:
std::optional<std::thread> thread_handler_;
absl::Notification stop_copying_;
};
// Copies one flow in one thread.
class CopySingleFlow : public CopyThread {
public:
CopySingleFlow(Flow *flow, const PulseBarrier *pulse_barrier,
const FlowThreadParameters ¶ms)
: flow_(flow),
wait_ns_(params.wait_ns),
batch_size_(params.batch_size),
use_cudaMemcpyPeerAsync_(params.use_cudaMemcpyPeerAsync),
use_cudaMemcpyDefault_(params.use_cudaMemcpyDefault),
use_cudaComputeCopy_(params.use_cudaComputeCopy),
pulse_barrier_(pulse_barrier) {}
protected:
// With sync_flows_ set, repeatedly copies the specified flow for high_time,
// then waits for the next synchronization of the blocking counter.
void Run() override;
private:
Flow *flow_;
int wait_ns_;
int batch_size_;
bool use_cudaMemcpyPeerAsync_;
bool use_cudaMemcpyDefault_;
bool use_cudaComputeCopy_;
const PulseBarrier *pulse_barrier_;
};
// Copy multiple flows in one thread, where each flow waits for its prior
// invocation to complete, but otherwise does not wait for other flows.
class EventPollThread : public CopyThread {
public:
EventPollThread(std::vector<Flow *> flows, const FlowThreadParameters ¶ms)
: flows_(std::move(flows)),
use_cudaMemcpyPeerAsync_(params.use_cudaMemcpyPeerAsync),
use_cudaMemcpyDefault_(params.use_cudaMemcpyDefault),
use_cudaComputeCopy_(params.use_cudaComputeCopy) {}
protected:
void Run() override;
private:
const std::vector<Flow *> flows_;
const bool use_cudaMemcpyPeerAsync_;
const bool use_cudaMemcpyDefault_;
const bool use_cudaComputeCopy_;
};
// Each GPU and its associated in/out flows is managed by one thread.
// All flows on the given GPU are synchronized between each copy.
class PerGpuThread : public CopyThread {
public:
PerGpuThread(absl::string_view name_prefix, const PulseBarrier *pulse_barrier,
std::vector<Flow *> flows, const FlowThreadParameters ¶ms)
: flows_(std::move(flows)),
group_by_dest_(params.use_group_by_dest),
batch_size_(params.batch_size),
use_cudaMemcpyPeerAsync_(params.use_cudaMemcpyPeerAsync),
use_cudaMemcpyDefault_(params.use_cudaMemcpyDefault),
use_cudaComputeCopy_(params.use_cudaComputeCopy),
name_prefix_(name_prefix),
pulse_barrier_(pulse_barrier) {}
std::string NamePrefix() { return name_prefix_; }
protected:
void Run() override;
private:
const std::vector<Flow *> flows_;
const bool group_by_dest_;
const int batch_size_;
const bool use_cudaMemcpyPeerAsync_;
const bool use_cudaMemcpyDefault_;
const bool use_cudaComputeCopy_;
const std::string name_prefix_;
const PulseBarrier *pulse_barrier_;
};
class BaseComputeStream : public CopyThread {
public:
using CopyThread::CopyThread;
double AccumulatedTime() { return accum_time_; }
int Loops() { return loops_; }
protected:
void AddAccumulatedTime(double time) { accum_time_ += time; }
void AddLoop() { loops_++; }
private:
double accum_time_ = 0;
int loops_ = 0;
};
// Creates cublasGemmEx compute stream using synchronization with CopyThread.
// This class uses mix-precision HostContext and GpuContext.
class GemmExComputeStream : public BaseComputeStream {
public:
// The HostContext should outlive the GemmExComputeStream
GemmExComputeStream(platforms_gpus::gemm_test::GpuContext *gpu_context,
const PulseBarrier *pulse_barrier,
int outstanding_operations_in_flight)
: gpu_context_(gpu_context),
pulse_barrier_(pulse_barrier),
outstanding_operations_in_flight_(outstanding_operations_in_flight) {}
protected:
void Run() override {
bool printWarning = false;
while (!stop_copying_.HasBeenNotified()) {
const absl::Time deadline = pulse_barrier_->HighTimeDeadline();
absl::Time start_time = absl::Now();
absl::Time last_time = start_time;
absl::Time end_time;
do {
for (int i = 0; i < outstanding_operations_in_flight_; i++) {
gpu_context_->LaunchKernel();
AddLoop();
}
gpu_context_->StreamSynchronize();
end_time = absl::Now();
if (!printWarning && outstanding_operations_in_flight_ == 1 &&
(end_time - last_time) < absl::Microseconds(20)) {
printWarning = true;
LOG(WARNING) << "Kernel execute time too short, may not accurate !!!";
}
last_time = end_time;
// The end condition ends up getting slightly smeared as the kernel
// isn't scheduled perfectly. Cancellation isn't sent though to the GPU,
// which would require special GPU kernel support, since it's not
// provided by the NVidia runtime.
} while (!stop_copying_.HasBeenNotified() && end_time < deadline);
AddAccumulatedTime(absl::ToDoubleSeconds(end_time - start_time));
VLOG(2) << "pulse high for " << (end_time - start_time);
}
}
private:
platforms_gpus::gemm_test::GpuContext *gpu_context_;
const PulseBarrier *pulse_barrier_;
const int outstanding_operations_in_flight_;
};
// Creates GemmExComputeAutoTuneStream compute stream using synchronization with
// CopyThread. This class is used to find the best algorithm of GEMM gpu
// context.
class GemmExComputeAutoTuneStream : public BaseComputeStream {
public:
GemmExComputeAutoTuneStream(
platforms_gpus::gemm_test::GpuContext *gpu_context)
: gpu_context_(gpu_context) {}
void Run() override { gpu_context_->AutoTuning(); }
private:
platforms_gpus::gemm_test::GpuContext *gpu_context_;
};
std::vector<std::unique_ptr<platforms_gpus::gemm_test::GpuContext>>
CreateGpuContexts(platforms_gpus::gemm_test::HostContext *host_ctx,
absl::Span<const int64_t> gpu_list);
void GemmAutoTune(
std::vector<std::unique_ptr<platforms_gpus::gemm_test::GpuContext>>
&gpu_ctxs);
// factory method to create a thread that wraps a multi_gemm task
// The HostContext should outlive the created CopyThread.
std::unique_ptr<CopyThread> CreateGemmThread(
platforms_gpus::gemm_test::GpuContext *gpu_context,
memcpy_gemm::PulseBarrier *pulse_barrier,
int outstanding_operations_in_flight);
// Makes compute threads for the provided gpu_list initialized according to
// Host Context, with one thread per GPU managing the GEMM operations on that
// GPU.
std::vector<std::unique_ptr<CopyThread>> MakeComputeThreads(
std::vector<std::unique_ptr<platforms_gpus::gemm_test::GpuContext>>
&gpu_ctxs,
PulseBarrier *pulse_barrier, int outstanding_operations_in_flight);
// Makes memcpy threads for the provided flows and params
std::vector<std::unique_ptr<CopyThread>> MakeMemcpyThreads(
const FlowThreadParameters ¶ms,
std::vector<std::unique_ptr<Flow>> &flows, PulseBarrier *pulse_barrier);
} // namespace memcpy_gemm
} // namespace platforms_gpus
#endif // PLATFORMS_GPUS_TESTING_NVIDIA_MEMCPY_GEMM_LIB_H_
| 33.075802 | 80 | 0.722785 | [
"vector"
] |
c44441cc57f6be9b23e674c6065cd6a74f8ec264 | 5,422 | c | C | external/uwp/cairo/cairo/boilerplate/cairo-boilerplate-egl.c | Greentwip/anura | ab3723d6efffc42b0fc3adbddbdf03ac600ed827 | [
"CC0-1.0"
] | null | null | null | external/uwp/cairo/cairo/boilerplate/cairo-boilerplate-egl.c | Greentwip/anura | ab3723d6efffc42b0fc3adbddbdf03ac600ed827 | [
"CC0-1.0"
] | null | null | null | external/uwp/cairo/cairo/boilerplate/cairo-boilerplate-egl.c | Greentwip/anura | ab3723d6efffc42b0fc3adbddbdf03ac600ed827 | [
"CC0-1.0"
] | null | null | null | /* Cairo - a vector graphics library with display and print output
*
* Copyright © 2009 Chris Wilson
*
* This library is free software; you can redistribute it and/or
* modify it either under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation
* (the "LGPL") or, at your option, under the terms of the Mozilla
* Public License Version 1.1 (the "MPL"). If you do not alter this
* notice, a recipient may use your version of this file under either
* the MPL or the LGPL.
*
* You should have received a copy of the LGPL along with this library
* in the file COPYING-LGPL-2.1; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA
* You should have received a copy of the MPL along with this library
* in the file COPYING-MPL-1.1
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (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.mozilla.org/MPL/
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
* OF ANY KIND, either express or implied. See the LGPL or the MPL for
* the specific language governing rights and limitations.
*
* The Original Code is the cairo graphics library.
*
* The Initial Developer of the Original Code is Chris Wilson.
*/
#include "cairo-boilerplate-private.h"
#include <cairo-gl.h>
#if CAIRO_HAS_GLESV3_SURFACE
#include <GLES3/gl3.h>
#include <EGL/eglext.h>
#elif CAIRO_HAS_GLESV2_SURFACE
#include <GLES2/gl2.h>
#elif CAIRO_HAS_GL_SURFACE
#include <GL/gl.h>
#endif
static const cairo_user_data_key_t gl_closure_key;
typedef struct _egl_target_closure {
EGLDisplay dpy;
EGLContext ctx;
cairo_device_t *device;
cairo_surface_t *surface;
} egl_target_closure_t;
static void
_cairo_boilerplate_egl_cleanup (void *closure)
{
egl_target_closure_t *gltc = closure;
cairo_device_finish (gltc->device);
cairo_device_destroy (gltc->device);
eglDestroyContext (gltc->dpy, gltc->ctx);
eglMakeCurrent (gltc->dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
eglTerminate (gltc->dpy);
free (gltc);
}
static cairo_surface_t *
_cairo_boilerplate_egl_create_surface (const char *name,
cairo_content_t content,
double width,
double height,
double max_width,
double max_height,
cairo_boilerplate_mode_t mode,
void **closure)
{
egl_target_closure_t *gltc;
cairo_surface_t *surface;
int major, minor;
EGLConfig config;
EGLint numConfigs;
EGLint config_attribs[] = {
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
#if CAIRO_HAS_GLESV3_SURFACE
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT_KHR,
#elif CAIRO_HAS_GLESV2_SURFACE
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
#elif CAIRO_HAS_GL_SURFACE
EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT,
#endif
EGL_NONE
};
const EGLint ctx_attribs[] = {
#if CAIRO_HAS_GLESV3_SURFACE
EGL_CONTEXT_CLIENT_VERSION, 3,
#elif CAIRO_HAS_GLESV2_SURFACE
EGL_CONTEXT_CLIENT_VERSION, 2,
#endif
EGL_NONE
};
gltc = xcalloc (1, sizeof (egl_target_closure_t));
*closure = gltc;
gltc->dpy = eglGetDisplay (EGL_DEFAULT_DISPLAY);
if (! eglInitialize (gltc->dpy, &major, &minor)) {
free (gltc);
return NULL;
}
eglChooseConfig (gltc->dpy, config_attribs, &config, 1, &numConfigs);
#if CAIRO_HAS_GLESV3_SURFACE && CAIRO_HAS_GLESV2_SURFACE
if (numConfigs == 0) {
/* retry with ES2_BIT */
config_attribs[11] = ES2_BIT; /* FIXME: Ick */
eglChooseConfig (gltc->dpy, config_attribs, &config, 1, &numConfigs);
}
#endif
if (numConfigs == 0) {
free (gltc);
return NULL;
}
#if CAIRO_HAS_GLESV3_SURFACE || CAIRO_HAS_GLESV2_SURFACE
eglBindAPI (EGL_OPENGL_ES_API);
#elif CAIRO_HAS_GL_SURFACE
eglBindAPI (EGL_OPENGL_API);
#endif
gltc->ctx = eglCreateContext (gltc->dpy, config, EGL_NO_CONTEXT,
ctx_attribs);
if (gltc->ctx == EGL_NO_CONTEXT) {
eglTerminate (gltc->dpy);
free (gltc);
return NULL;
}
gltc->device = cairo_egl_device_create (gltc->dpy, gltc->ctx);
if (mode == CAIRO_BOILERPLATE_MODE_PERF)
cairo_gl_device_set_thread_aware(gltc->device, FALSE);
if (width < 1)
width = 1;
if (height < 1)
height = 1;
gltc->surface = surface = cairo_gl_surface_create (gltc->device,
content,
ceil (width),
ceil (height));
if (cairo_surface_status (surface))
_cairo_boilerplate_egl_cleanup (gltc);
return surface;
}
static void
_cairo_boilerplate_egl_synchronize (void *closure)
{
egl_target_closure_t *gltc = closure;
if (cairo_device_acquire (gltc->device))
return;
glFinish ();
cairo_device_release (gltc->device);
}
static const cairo_boilerplate_target_t targets[] = {
{
"egl", "gl", NULL, NULL,
CAIRO_SURFACE_TYPE_GL, CAIRO_CONTENT_COLOR_ALPHA, 1,
"cairo_egl_device_create",
_cairo_boilerplate_egl_create_surface,
cairo_surface_create_similar,
NULL, NULL,
_cairo_boilerplate_get_image_surface,
cairo_surface_write_to_png,
_cairo_boilerplate_egl_cleanup,
_cairo_boilerplate_egl_synchronize,
NULL,
TRUE, FALSE, FALSE
}
};
CAIRO_BOILERPLATE (egl, targets)
| 27.805128 | 79 | 0.716156 | [
"vector"
] |
c44b1d3346afbcf21380b81a94f0cf486608f73c | 592 | h | C | jadette/src/Primitives.h | j-oel/jadette-treehouse | d7f89063e3a82d37665d10984f399c09a6a83904 | [
"CC-BY-4.0"
] | 1 | 2021-11-15T09:28:16.000Z | 2021-11-15T09:28:16.000Z | jadette/src/Primitives.h | j-oel/jadette-treehouse | d7f89063e3a82d37665d10984f399c09a6a83904 | [
"CC-BY-4.0"
] | null | null | null | jadette/src/Primitives.h | j-oel/jadette-treehouse | d7f89063e3a82d37665d10984f399c09a6a83904 | [
"CC-BY-4.0"
] | null | null | null | // SPDX-License-Identifier: GPL-3.0-only
// This file is part of Jadette.
// Copyright (C) 2020-2021 Joel Jansson
// Distributed under GNU General Public License v3.0
// See gpl-3.0.txt or <https://www.gnu.org/licenses/>
#pragma once
#include "Mesh.h"
// A unit cube centered in origo.
class Cube : public Mesh
{
public:
Cube(ID3D12Device& device, ID3D12GraphicsCommandList& command_list);
private:
};
// A unit plane centered in origo, through y = 0, facing upwards.
class Plane : public Mesh
{
public:
Plane(ID3D12Device& device, ID3D12GraphicsCommandList& command_list);
};
| 21.142857 | 73 | 0.724662 | [
"mesh"
] |
c455838f1260ff1e339d5bbd5088f37643286358 | 57,318 | h | C | classpath-0.98/include/jvmti.h | nmldiegues/jvm-stm | d422d78ba8efc99409ecb49efdb4edf4884658df | [
"Apache-2.0"
] | 2 | 2015-09-08T15:40:04.000Z | 2017-02-09T15:19:33.000Z | classpath-0.98/include/jvmti.h | nmldiegues/jvm-stm | d422d78ba8efc99409ecb49efdb4edf4884658df | [
"Apache-2.0"
] | 2 | 2021-04-07T00:18:48.000Z | 2021-04-07T00:20:08.000Z | classpath-0.98/include/jvmti.h | nmldiegues/jvm-stm | d422d78ba8efc99409ecb49efdb4edf4884658df | [
"Apache-2.0"
] | 1 | 2017-10-26T23:20:32.000Z | 2017-10-26T23:20:32.000Z | /* jvmti.h - Java Virtual Machine Tool Interface
Copyright (C) 2006 Free Software Foundation
This file is part of GNU Classpath.
GNU Classpath 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 Classpath 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 Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
/* Note: this file must be compilable by the C compiler (for now,
assuming GNU C is ok). This means you must never use `//'
comments, and all C++-specific code must be conditional on
__cplusplus. */
#ifndef _CLASSPATH_JVMTI_H
#define _CLASSPATH_JVMTI_H
#include <jni.h>
#include "jvmti_md.h"
/* The VM might define JVMTI base types */
#ifndef _CLASSPATH_VM_JVMTI_TYPES_DEFINED
typedef jobject jthread;
typedef jobject jthreadGroup;
typedef jlong jlocation;
typedef struct _Jv_rawMonitorID *jrawMonitorID;
#endif /* !_CLASSPATH_VM_JVMTI_TYPES_DEFINED */
/* JVMTI Version */
#define JVMTI_VERSION_1_0 0x30010000
#define JVMTI_VERSION (JVMTI_VERSION_1_0 + 38) /* Spec version is 1.0.38 */
#ifdef __cplusplus
extern "C"
{
#endif
/* These functions might be defined in libraries which we load; the
JVMTI implementation calls them at the appropriate times. */
extern JNIEXPORT jint JNICALL Agent_OnLoad (JavaVM *vm, char *options,
void *reserved);
extern JNIEXPORT void JNICALL Agent_OnUnload (JavaVM *vm);
#ifdef __cplusplus
}
#endif
/* Forward declarations */
typedef struct _jvmtiAddrLocationMap jvmtiAddrLocationMap;
#ifdef __cplusplus
typedef struct _Jv_JVMTIEnv jvmtiEnv;
#else
typedef const struct _Jv_jvmtiEnv *jvmtiEnv;
#endif
/*
* Error constants
*/
typedef enum
{
/* Universal Errors */
JVMTI_ERROR_NONE = 0,
JVMTI_ERROR_NULL_POINTER = 100,
JVMTI_ERROR_OUT_OF_MEMORY = 110,
JVMTI_ERROR_ACCESS_DENIED = 111,
JVMTI_ERROR_WRONG_PHASE = 112,
JVMTI_ERROR_INTERNAL = 113,
JVMTI_ERROR_UNATTACHED_THREAD = 115,
JVMTI_ERROR_INVALID_ENVIRONMENT = 116,
/* Function-specific Required Errors */
JVMTI_ERROR_INVALID_PRIORITY = 12,
JVMTI_ERROR_THREAD_NOT_SUSPENDED = 13,
JVMTI_ERROR_THREAD_SUSPENDED = 14,
JVMTI_ERROR_THREAD_NOT_ALIVE = 15,
JVMTI_ERROR_CLASS_NOT_PREPARED = 22,
JVMTI_ERROR_NO_MORE_FRAMES = 31,
JVMTI_ERROR_OPAQUE_FRAME = 32,
JVMTI_ERROR_DUPLICATE = 40,
JVMTI_ERROR_NOT_FOUND = 41,
JVMTI_ERROR_NOT_MONITOR_OWNER = 51,
JVMTI_ERROR_INTERRUPT = 52,
JVMTI_ERROR_UNMODIFIABLE_CLASS = 79,
JVMTI_ERROR_NOT_AVAILABLE = 98,
JVMTI_ERROR_ABSENT_INFORMATION = 101,
JVMTI_ERROR_INVALID_EVENT_TYPE = 102,
JVMTI_ERROR_NATIVE_METHOD = 104,
/* Function-specific Agent Errors */
JVMTI_ERROR_INVALID_THREAD = 10,
JVMTI_ERROR_INVALID_THREAD_GROUP = 11,
JVMTI_ERROR_INVALID_OBJECT = 20,
JVMTI_ERROR_INVALID_CLASS = 21,
JVMTI_ERROR_INVALID_METHODID = 23,
JVMTI_ERROR_INVALID_LOCATION = 24,
JVMTI_ERROR_INVALID_FIELDID = 25,
JVMTI_ERROR_TYPE_MISMATCH = 34,
JVMTI_ERROR_INVALID_SLOT = 35,
JVMTI_ERROR_INVALID_MONITOR = 50,
JVMTI_ERROR_INVALID_CLASS_FORMAT = 60,
JVMTI_ERROR_CIRCULAR_CLASS_DEFINITION = 61,
JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_ADDED = 63,
JVMTI_ERROR_UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED = 64,
JVMTI_ERROR_INVALID_TYPESTATE = 65,
JVMTI_ERROR_FAILS_VERIFICATION = 62,
JVMTI_ERROR_UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED = 66,
JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_DELETED = 67,
JVMTI_ERROR_UNSUPPORTED_VERSION = 68,
JVMTI_ERROR_NAMES_DONT_MATCH = 69,
JVMTI_ERROR_UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED = 70,
JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED = 71,
JVMTI_ERROR_MUST_POSSESS_CAPABILITY = 99,
JVMTI_ERROR_ILLEGAL_ARGUMENT = 103
} jvmtiError;
/*
* Enumeration Definitions
*/
typedef enum
{
JVMTI_DISABLE = 0,
JVMTI_ENABLE = 1
} jvmtiEventMode;
typedef enum
{
JVMTI_HEAP_OBJECT_TAGGED = 1,
JVMTI_HEAP_OBJECT_UNTAGGED = 2,
JVMTI_HEAP_OBJECT_EITHER = 3
} jvmtiHeapObjectFilter;
typedef enum
{
JVMTI_HEAP_ROOT_JNI_GLOBAL = 1,
JVMTI_HEAP_ROOT_SYSTEM_CLASS = 2,
JVMTI_HEAP_ROOT_MONITOR = 3,
JVMTI_HEAP_ROOT_STACK_LOCAL = 4,
JVMTI_HEAP_ROOT_JNI_LOCAL = 5,
JVMTI_HEAP_ROOT_THREAD = 6,
JVMTI_HEAP_ROOT_OTHER = 7
} jvmtiHeapRootKind;
typedef enum
{
JVMTI_ITERATION_ABORT = 0,
JVMTI_ITERATION_CONTINUE = 1,
JVMTI_ITERATION_IGNORE = 2
} jvmtiIterationControl;
typedef enum
{
JVMTI_JLOCATION_OTHER = 0,
JVMTI_JLOCATION_JVMBCI = 1,
JVMTI_JLOCATION_MACHINEPC = 2
} jvmtiJlocationFormat;
typedef enum
{
JVMTI_REFERENCE_CLASS = 1,
JVMTI_REFERENCE_FIELD = 2,
JVMTI_REFERENCE_ARRAY_ELEMENT = 3,
JVMTI_REFERENCE_CLASS_LOADER = 4,
JVMTI_REFERENCE_SIGNERS = 5,
JVMTI_REFERENCE_PROTECTION_DOMAIN = 6,
JVMTI_REFERENCE_INTERFACE = 7,
JVMTI_REFERENCE_STATIC_FIELD = 8,
JVMTI_REFERENCE_CONSTANT_POOL = 9
} jvmtiObjectReferenceKind;
typedef enum
{
JVMTI_KIND_IN = 91,
JVMTI_KIND_IN_PTR = 92,
JVMTI_KIND_IN_BUF = 93,
JVMTI_KIND_ALLOC_BUF = 94,
JVMTI_KIND_ALLOC_ALLOC_BUF = 95,
JVMTI_KIND_OUT = 96,
JVMTI_KIND_OUT_BUF = 97
} jvmtiParamKind;
typedef enum
{
JVMTI_TYPE_JBYTE = 101,
JVMTI_TYPE_JCHAR = 102,
JVMTI_TYPE_JSHORT = 103,
JVMTI_TYPE_JINT = 104,
JVMTI_TYPE_JLONG = 105,
JVMTI_TYPE_JFLOAT = 106,
JVMTI_TYPE_JDOUBLE = 107,
JVMTI_TYPE_JBOOLEAN = 108,
JVMTI_TYPE_JOBJECT = 109,
JVMTI_TYPE_JTHREAD = 110,
JVMTI_TYPE_JCLASS = 111,
JVMTI_TYPE_JVALUE = 112,
JVMTI_TYPE_JFIELDID = 113,
JVMTI_TYPE_JMETHODID = 114,
JVMTI_TYPE_CCHAR = 115,
JVMTI_TYPE_CVOID = 116,
JVMTI_TYPE_JNIENV = 117
} jvmtiParamTypes;
typedef enum
{
JVMTI_PHASE_ONLOAD = 1,
JVMTI_PHASE_PRIMORDIAL = 2,
JVMTI_PHASE_LIVE = 4,
JVMTI_PHASE_START = 6,
JVMTI_PHASE_DEAD = 8
} jvmtiPhase;
typedef enum
{
JVMTI_TIMER_USER_CPU = 30,
JVMTI_TIMER_TOTAL_CPU = 31,
JVMTI_TIMER_ELAPSED = 32
} jvmtiTimerKind;
typedef enum
{
JVMTI_VERBOSE_OTHER = 0,
JVMTI_VERBOSE_GC = 1,
JVMTI_VERBOSE_CLASS = 2,
JVMTI_VERBOSE_JNI = 4
} jvmtiVerboseFlag;
/* Version information */
#define JVMTI_VERSION_INTERFACE_JNI 0x00000000
#define JVMTI_VERSION_INTERFACE_JVMTI 0x30000000
#define JVMTI_VERSION_MASK_INTERFACE_TYPE 0x70000000
#define JVMTI_VERSION_MASK_MAJOR 0x0FFF0000
#define JVMTI_VERSION_MASK_MINOR 0x0000FF00
#define JVMTI_VERSION_MASK_MICRO 0x000000FF
#define JVMTI_VERSION_SHIFT_MAJOR 16
#define JVMTI_VERSION_SHIFT_MINOR 8
#define JVMTI_VERSION_SHIFT_MICRO 0
/*
* Events and event callbacks
*/
typedef enum
{
JVMTI_EVENT_VM_INIT = 50,
JVMTI_EVENT_VM_DEATH = 51,
JVMTI_EVENT_THREAD_START = 52,
JVMTI_EVENT_THREAD_END = 53,
JVMTI_EVENT_CLASS_FILE_LOAD_HOOK = 54,
JVMTI_EVENT_CLASS_LOAD = 55,
JVMTI_EVENT_CLASS_PREPARE = 56,
JVMTI_EVENT_VM_START = 57,
JVMTI_EVENT_EXCEPTION = 58,
JVMTI_EVENT_EXCEPTION_CATCH = 59,
JVMTI_EVENT_SINGLE_STEP = 60,
JVMTI_EVENT_FRAME_POP = 61,
JVMTI_EVENT_BREAKPOINT = 62,
JVMTI_EVENT_FIELD_ACCESS = 63,
JVMTI_EVENT_FIELD_MODIFICATION = 64,
JVMTI_EVENT_METHOD_ENTRY = 65,
JVMTI_EVENT_METHOD_EXIT = 66,
JVMTI_EVENT_NATIVE_METHOD_BIND = 67,
JVMTI_EVENT_COMPILED_METHOD_LOAD = 68,
JVMTI_EVENT_COMPILED_METHOD_UNLOAD = 69,
JVMTI_EVENT_DYNAMIC_CODE_GENERATED = 70,
JVMTI_EVENT_DATA_DUMP_REQUEST = 71,
JVMTI_EVENT_MONITOR_WAIT = 73,
JVMTI_EVENT_MONITOR_WAITED = 74,
JVMTI_EVENT_MONITOR_CONTENDED_ENTER = 75,
JVMTI_EVENT_MONITOR_CONTENDED_ENTERED = 76,
JVMTI_EVENT_GARBAGE_COLLECTION_START = 81,
JVMTI_EVENT_GARBAGE_COLLECTION_FINISH = 82,
JVMTI_EVENT_OBJECT_FREE = 83,
JVMTI_EVENT_VM_OBJECT_ALLOC = 84
} jvmtiEvent;
typedef void *jvmtiEventReserved;
typedef void (JNICALL *jvmtiEventSingleStep)
(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jmethodID method,
jlocation location);
typedef void (JNICALL *jvmtiEventBreakpoint)
(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jmethodID method,
jlocation location);
typedef void (JNICALL *jvmtiEventFieldAccess)
(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jmethodID method,
jlocation location, jclass field_klass, jobject object, jfieldID field);
typedef void (JNICALL *jvmtiEventFieldModification)
(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jmethodID method,
jlocation location, jclass field_klass, jobject object, jfieldID field,
char signature_type, jvalue new_value);
typedef void (JNICALL *jvmtiEventFramePop)
(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jmethodID method,
jboolean was_popped_by_exception);
typedef void (JNICALL *jvmtiEventMethodEntry)
(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jmethodID method);
typedef void (JNICALL *jvmtiEventMethodExit)
(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jmethodID method,
jboolean was_popped_by_exception, jvalue return_value);
typedef void (JNICALL *jvmtiEventNativeMethodBind)
(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jmethodID method,
void *address, void **new_address_ptr);
typedef void (JNICALL *jvmtiEventException)
(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jmethodID method,
jlocation location, jobject exception, jmethodID catch_method,
jlocation catch_location);
typedef void (JNICALL *jvmtiEventExceptionCatch)
(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jmethodID method,
jlocation location, jobject exception);
typedef void (JNICALL *jvmtiEventThreadStart)
(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread);
typedef void (JNICALL *jvmtiEventThreadEnd)
(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread);
typedef void (JNICALL *jvmtiEventClassLoad)
(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jclass klass);
typedef void (JNICALL *jvmtiEventClassPrepare)
(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thraed, jclass klass);
typedef void (JNICALL *jvmtiEventClassFileLoadHook)
(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jclass class_being_redefined,
jobject loader, const char *name, jobject protection_domain,
jint class_data_len, const unsigned char *class_data,
jint *new_class_data_len, unsigned char **new_class_data);
typedef void (JNICALL *jvmtiEventVMStart)
(jvmtiEnv *jvmti_env, JNIEnv *jni_env);
typedef void (JNICALL *jvmtiEventVMInit)
(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread);
typedef void (JNICALL *jvmtiEventVMDeath)
(jvmtiEnv *jvmti_env, JNIEnv *jni_env);
typedef void (JNICALL *jvmtiEventCompiledMethodLoad)
(jvmtiEnv *jvmti_env, jmethodID method, jint code_size,
const void *code_addr, jint map_length, const jvmtiAddrLocationMap *map,
const void *compile_info);
typedef void (JNICALL *jvmtiEventCompiledMethodUnload)
(jvmtiEnv *jvmti_env, jmethodID method, const void *code_addr);
typedef void (JNICALL *jvmtiEventDynamicCodeGenerated)
(jvmtiEnv *jvmti_env, const char *name, const void *address, jint length);
typedef void (JNICALL *jvmtiEventDataDumpRequest)
(jvmtiEnv *jvmti_env);
typedef void (JNICALL *jvmtiEventMonitorContendedEnter)
(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jobject object);
typedef void (JNICALL *jvmtiEventMonitorContendedEntered)
(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jobject object);
typedef void (JNICALL *jvmtiEventMonitorWait)
(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jobject object,
jlong timeout);
typedef void (JNICALL *jvmtiEventMonitorWaited)
(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jobject object,
jboolean timed_out);
typedef void (JNICALL *jvmtiEventVMObjectAlloc)
(jvmtiEnv *jvmti_env, JNIEnv *jni_env, jthread thread, jobject object,
jclass object_klass, jlong size);
typedef void (JNICALL *jvmtiEventObjectFree)
(jvmtiEnv *jvmti_env, jlong tag);
typedef void (JNICALL *jvmtiEventGarbageCollectionStart)
(jvmtiEnv *jvmti_env);
typedef void (JNICALL *jvmtiEventGarbageCollectionFinish)
(jvmtiEnv *jvmti_env);
typedef struct
{
jvmtiEventVMInit VMInit;
jvmtiEventVMDeath VMDeath;
jvmtiEventThreadStart ThreadStart;
jvmtiEventThreadEnd ThreadEnd;
jvmtiEventClassFileLoadHook ClassFileLoadHook;
jvmtiEventClassLoad ClassLoad;
jvmtiEventClassPrepare ClassPrepare;
jvmtiEventVMStart VMStart;
jvmtiEventException Exception;
jvmtiEventExceptionCatch ExceptionCatch;
jvmtiEventSingleStep SingleStep;
jvmtiEventFramePop FramePop;
jvmtiEventBreakpoint Breakpoint;
jvmtiEventFieldAccess FieldAccess;
jvmtiEventFieldModification FieldModification;
jvmtiEventMethodEntry MethodEntry;
jvmtiEventMethodExit MethodExit;
jvmtiEventNativeMethodBind NativeMethodBind;
jvmtiEventCompiledMethodLoad CompiledMethodLoad;
jvmtiEventCompiledMethodUnload CompiledMethodUnload;
jvmtiEventDynamicCodeGenerated DynamicCodeGenerated;
jvmtiEventDataDumpRequest DataDumpRequest;
jvmtiEventReserved reserved72;
jvmtiEventMonitorWait MonitorWait;
jvmtiEventMonitorWaited MonitorWaited;
jvmtiEventMonitorContendedEnter MonitorContendedEnter;
jvmtiEventMonitorContendedEntered MonitorContendedEntered;
jvmtiEventReserved reserved77;
jvmtiEventReserved reserved78;
jvmtiEventReserved reserved79;
jvmtiEventReserved reserved80;
jvmtiEventGarbageCollectionStart GarbageCollectionStart;
jvmtiEventGarbageCollectionFinish GarbageCollectionFinish;
jvmtiEventObjectFree ObjectFree;
jvmtiEventVMObjectAlloc VMObjectAlloc;
} jvmtiEventCallbacks;
/*
* Function and Structure Type Definitions
*/
struct _jvmtiAddrLocationMap
{
const void *start_address;
jlocation location;
};
typedef struct
{
unsigned int can_tag_objects : 1;
unsigned int can_generate_field_modification_events : 1;
unsigned int can_generate_field_access_events : 1;
unsigned int can_get_bytecodes : 1;
unsigned int can_get_synthetic_attribute : 1;
unsigned int can_get_owned_monitor_info : 1;
unsigned int can_get_current_contended_monitor : 1;
unsigned int can_get_monitor_info : 1;
unsigned int can_pop_frame : 1;
unsigned int can_redefine_classes : 1;
unsigned int can_signal_thread : 1;
unsigned int can_get_source_file_name : 1;
unsigned int can_get_line_numbers : 1;
unsigned int can_get_source_debug_extension : 1;
unsigned int can_access_local_variables : 1;
unsigned int can_maintain_original_method_order : 1;
unsigned int can_generate_single_step_events : 1;
unsigned int can_generate_exception_events : 1;
unsigned int can_generate_frame_pop_events : 1;
unsigned int can_generate_breakpoint_events : 1;
unsigned int can_suspend : 1;
unsigned int can_redefine_any_class : 1;
unsigned int can_get_current_thread_cpu_time : 1;
unsigned int can_get_thread_cpu_time : 1;
unsigned int can_generate_method_entry_events : 1;
unsigned int can_generate_method_exit_events : 1;
unsigned int can_generate_all_class_hook_events : 1;
unsigned int can_generate_compiled_method_load_events : 1;
unsigned int can_generate_monitor_events : 1;
unsigned int can_generate_vm_object_alloc_events : 1;
unsigned int can_generate_native_method_bind_events : 1;
unsigned int can_generate_garbage_collection_events : 1;
unsigned int can_generate_object_free_events : 1;
unsigned int : 15;
unsigned int : 16;
unsigned int : 16;
unsigned int : 16;
unsigned int : 16;
unsigned int : 16;
} jvmtiCapabilities;
typedef struct
{
jclass klass;
jint class_byte_count;
const unsigned char *class_bytes;
} jvmtiClassDefinition;
typedef struct
{
char *name;
jvmtiParamKind kind;
jvmtiParamTypes base_type;
jboolean null_ok;
} jvmtiParamInfo;
typedef struct
{
jint extension_event_index;
char *id;
char *short_description;
jint param_count;
jvmtiParamInfo* params;
} jvmtiExtensionEventInfo;
typedef jvmtiError (JNICALL *jvmtiExtensionFunction)
(jvmtiEnv *jvmti_enf, ...);
typedef struct
{
jvmtiExtensionFunction func;
char *id;
char *short_description;
jint param_count;
jvmtiParamInfo *params;
jint error_count;
jvmtiError *errors;
} jvmtiExtensionFunctionInfo;
typedef struct
{
jmethodID method;
jlocation location;
} jvmtiFrameInfo;
typedef struct
{
jlocation start_location;
jint line_number;
} jvmtiLineNumberEntry;
typedef struct
{
jlocation start_location;
jint length;
char *name;
char *signature;
char *generic_signature;
jint slot;
} jvmtiLocalVariableEntry;
typedef struct
{
jthread owner;
jint entry_count;
jint waiter_count;
jthread *waiters;
jint notify_waiter_count;
jthread *notify_waiters;
} jvmtiMonitorUsage;
typedef struct
{
jthread thread;
jint state;
jvmtiFrameInfo *frame_buffer;
jint frame_count;
} jvmtiStackInfo;
typedef struct
{
jthreadGroup parent;
char *name;
jint max_priority;
jboolean is_daemon;
} jvmtiThreadGroupInfo;
typedef struct
{
char *name;
jint priority;
jboolean is_daemon;
jthreadGroup thread_group;
jobject context_class_loader;
} jvmtiThreadInfo;
typedef struct
{
jlong max_value;
jboolean may_skip_forward;
jboolean may_skip_backward;
jvmtiTimerKind kind;
jlong reserved1;
jlong reserved2;
} jvmtiTimerInfo;
typedef void (JNICALL *jvmtiExtensionEvent)
(jvmtiEnv *jvmti_env, ...);
typedef jvmtiIterationControl (JNICALL *jvmtiHeapObjectCallback)
(jlong class_tag, jlong size, jlong *tag_ptr, void *user_data);
typedef jvmtiIterationControl (JNICALL *jvmtiHeapRootCallback)
(jvmtiHeapRootKind root_kind, jlong class_tag, jlong size, jlong *tag_ptr,
void *user_data);
typedef jvmtiIterationControl (JNICALL *jvmtiObjectReferenceCallback)
(jvmtiObjectReferenceKind reference_kind, jlong class_tag, jlong size,
jlong *tag_ptr, jlong referrer_tag, jint referrer_index, void *user_data);
typedef jvmtiIterationControl (JNICALL *jvmtiStackReferenceCallback)
(jvmtiHeapRootKind root_kind, jlong class_tag, jlong size, jlong *tag_ptr,
jlong thread_tag, jint depth, jmethodID method, jint slot, void *user_data);
typedef void (JNICALL *jvmtiStartFunction)
(jvmtiEnv *env, JNIEnv *jni_env, void *arg);
/*
* JVM Tool Interface Base Types
*/
typedef struct JNINativeInterface_ jniNativeInterface;
struct _Jv_jvmtiEnv
{
void *reserved1;
jvmtiError (JNICALL *SetEventNotificationMode) (jvmtiEnv *env,
jvmtiEventMode mode,
jvmtiEvent event_type,
jthread event_thread, ...);
void *reserved3;
jvmtiError (JNICALL *GetAllThreads) (jvmtiEnv *env,
jint *threads_count_ptr,
jthread **threads_ptr);
jvmtiError (JNICALL *SuspendThread) (jvmtiEnv *env,
jthread thread);
jvmtiError (JNICALL *ResumeThread) (jvmtiEnv *env,
jthread thread);
jvmtiError (JNICALL *StopThread) (jvmtiEnv *env,
jthread thread,
jobject exception);
jvmtiError (JNICALL *InterruptThread) (jvmtiEnv *env,
jthread thread);
jvmtiError (JNICALL *GetThreadInfo) (jvmtiEnv *env,
jthread thread,
jvmtiThreadInfo *info_ptr);
jvmtiError (JNICALL *GetOwnedMonitorInfo) (jvmtiEnv *env,
jthread thread,
jint *owned_monitor_count_ptr,
jobject **owned_monitors_ptr);
jvmtiError (JNICALL *GetCurrentContendedMonitor) (jvmtiEnv *env,
jthread thread,
jobject *monitor_ptr);
jvmtiError (JNICALL *RunAgentThread) (jvmtiEnv *env,
jthread thread,
jvmtiStartFunction proc,
const void *arg,
jint priority);
jvmtiError (JNICALL *GetTopThreadGroups) (jvmtiEnv *env,
jint *group_count_ptr,
jthreadGroup **groups_ptr);
jvmtiError (JNICALL *GetThreadGroupInfo) (jvmtiEnv *env,
jthreadGroup group,
jvmtiThreadGroupInfo *info_ptr);
jvmtiError (JNICALL *GetThreadGroupChildren) (jvmtiEnv *env,
jthreadGroup group,
jint *thread_count_ptr,
jthread **threads_ptr,
jint *group_count_ptr,
jthreadGroup **groups_ptr);
jvmtiError (JNICALL *GetFrameCount) (jvmtiEnv *env,
jthread thread,
jint *count_ptr);
jvmtiError (JNICALL *GetThreadState) (jvmtiEnv *env,
jthread thread,
jint *thread_state_ptr);
void *reserved18;
jvmtiError (JNICALL *GetFrameLocation) (jvmtiEnv *env,
jthread thread,
jint depth,
jmethodID *method_ptr,
jlocation *location_ptr);
jvmtiError (JNICALL *NotifyPopFrame) (jvmtiEnv *env,
jthread thread,
jint depth);
jvmtiError (JNICALL *GetLocalObject) (jvmtiEnv *env,
jthread thread,
jint depth,
jint slot,
jobject *value_ptr);
jvmtiError (JNICALL *GetLocalInt) (jvmtiEnv *env,
jthread thread,
jint depth,
jint slot,
jint *value_ptr);
jvmtiError (JNICALL *GetLocalLong) (jvmtiEnv *env,
jthread thread,
jint depth,
jint slot,
jlong *value_ptr);
jvmtiError (JNICALL *GetLocalFloat) (jvmtiEnv *env,
jthread thread,
jint depth,
jint slot,
jfloat *value_ptr);
jvmtiError (JNICALL *GetLocalDouble) (jvmtiEnv *env,
jthread thread,
jint depth,
jint slot,
jdouble *value_ptr);
jvmtiError (JNICALL *SetLocalObject) (jvmtiEnv *env,
jthread thread,
jint depth,
jint slot,
jobject value);
jvmtiError (JNICALL *SetLocalInt) (jvmtiEnv *env,
jthread thread,
jint depth,
jint slot,
jint value);
jvmtiError (JNICALL *SetLocalLong) (jvmtiEnv *env,
jthread thread,
jint depth,
jint slot,
jlong value);
jvmtiError (JNICALL *SetLocalFloat) (jvmtiEnv *env,
jthread thread,
jint depth,
jint slot,
jfloat value);
jvmtiError (JNICALL *SetLocalDouble) (jvmtiEnv *env,
jthread thread,
jint depth,
jint slot,
jdouble value);
jvmtiError (JNICALL *CreateRawMonitor) (jvmtiEnv *env,
const char *name,
jrawMonitorID *monitor_ptr);
jvmtiError (JNICALL *DestroyRawMonitor) (jvmtiEnv *env,
jrawMonitorID monitor);
jvmtiError (JNICALL *RawMonitorEnter) (jvmtiEnv *env,
jrawMonitorID monitor);
jvmtiError (JNICALL *RawMonitorExit) (jvmtiEnv *env,
jrawMonitorID monitor);
jvmtiError (JNICALL *RawMonitorWait) (jvmtiEnv *env,
jrawMonitorID monitor,
jlong millis);
jvmtiError (JNICALL *RawMonitorNotify) (jvmtiEnv *env,
jrawMonitorID monitor);
jvmtiError (JNICALL *RawMonitorNotifyAll) (jvmtiEnv *env,
jrawMonitorID monitor);
jvmtiError (JNICALL *SetBreakpoint) (jvmtiEnv *env,
jmethodID method,
jlocation location);
jvmtiError (JNICALL *ClearBreakpoint) (jvmtiEnv *env,
jmethodID method,
jlocation location);
void *reserved40;
jvmtiError (JNICALL *SetFieldAccessWatch) (jvmtiEnv *env,
jclass klass,
jfieldID field);
jvmtiError (JNICALL *ClearFieldAccessWatch) (jvmtiEnv *env,
jclass klass,
jfieldID field);
jvmtiError (JNICALL *SetFieldModificationWatch) (jvmtiEnv *env,
jclass klass,
jfieldID field);
jvmtiError (JNICALL *ClearFieldModificationWatch) (jvmtiEnv *env,
jclass klass,
jfieldID field);
void *reserved45;
jvmtiError (JNICALL *Allocate) (jvmtiEnv *env,
jlong size,
unsigned char **mem_ptr);
jvmtiError (JNICALL *Deallocate) (jvmtiEnv *env,
unsigned char *mem);
jvmtiError (JNICALL *GetClassSignature) (jvmtiEnv *env,
jclass klass,
char **signature_ptr,
char **generic_ptr);
jvmtiError (JNICALL *GetClassStatus) (jvmtiEnv *env,
jclass klass,
jint *status_ptr);
jvmtiError (JNICALL *GetSourceFileName) (jvmtiEnv *env,
jclass klass,
char **source_name_ptr);
jvmtiError (JNICALL *GetClassModifiers) (jvmtiEnv *env,
jclass klass,
jint *modifiers_ptr);
jvmtiError (JNICALL *GetClassMethods) (jvmtiEnv *env,
jclass klass,
jint *method_count_ptr,
jmethodID **methods_ptr);
jvmtiError (JNICALL *GetClassFields) (jvmtiEnv *env,
jclass klass,
jint *field_count_ptr,
jfieldID **fields_ptr);
jvmtiError (JNICALL *GetImplementedInterfaces) (jvmtiEnv *env,
jclass klass,
jint *interface_count_ptr,
jclass **interfaces_ptr);
jvmtiError (JNICALL *IsInterface) (jvmtiEnv *env,
jclass klass,
jboolean *is_interface_ptr);
jvmtiError (JNICALL *IsArrayClass) (jvmtiEnv *env,
jclass klass,
jboolean *is_array_class_ptr);
jvmtiError (JNICALL *GetClassLoader) (jvmtiEnv *env,
jclass klass,
jobject *classloader_ptr);
jvmtiError (JNICALL *GetObjectHashCode) (jvmtiEnv *env,
jobject object,
jint *hash_code_ptr);
jvmtiError (JNICALL *GetObjectMonitorUsage) (jvmtiEnv *env,
jobject object,
jvmtiMonitorUsage *info_ptr);
jvmtiError (JNICALL *GetFieldName) (jvmtiEnv *env,
jclass klass,
jfieldID field,
char **name_ptr,
char **signature_ptr,
char **generic_ptr);
jvmtiError (JNICALL *GetFieldDeclaringClass) (jvmtiEnv *env,
jclass klass,
jfieldID field,
jclass *declaring_class_ptr);
jvmtiError (JNICALL *GetFieldModifiers) (jvmtiEnv *env,
jclass klass,
jfieldID field,
jint *modifiers_ptr);
jvmtiError (JNICALL *IsFieldSynthetic) (jvmtiEnv *env,
jclass klass,
jfieldID field,
jboolean *is_synthetic_ptr);
jvmtiError (JNICALL *GetMethodName) (jvmtiEnv *env,
jmethodID method,
char **name_ptr,
char **signature_ptr,
char **generic_ptr);
jvmtiError (JNICALL *GetMethodDeclaringClass) (jvmtiEnv *env,
jmethodID method,
jclass *declaring_class_ptr);
jvmtiError (JNICALL *GetMethodModifiers) (jvmtiEnv *env,
jmethodID method,
jint *modifiers_ptr);
void *reserved67;
jvmtiError (JNICALL *GetMaxLocals) (jvmtiEnv *env,
jmethodID method,
jint *max_ptr);
jvmtiError (JNICALL *GetArgumentsSize) (jvmtiEnv *env,
jmethodID method,
jint *size_ptr);
jvmtiError (JNICALL *GetLineNumberTable) (jvmtiEnv *env,
jmethodID method,
jint *entry_count_ptr,
jvmtiLineNumberEntry **table_ptr);
jvmtiError (JNICALL *GetMethodLocation) (jvmtiEnv *env,
jmethodID method,
jlocation *start_location_ptr,
jlocation *end_location_ptr);
jvmtiError (JNICALL *GetLocalVariableTable) (jvmtiEnv *env,
jmethodID method,
jint *entry_count_ptr,
jvmtiLocalVariableEntry **table_ptr);
void *reserved73;
void *reserved74;
jvmtiError (JNICALL *GetBytecodes) (jvmtiEnv *env,
jmethodID method,
jint *bytecode_count_ptr,
unsigned char **bytecodes_ptr);
jvmtiError (JNICALL *IsMethodNative) (jvmtiEnv *env,
jmethodID method,
jboolean *is_native_ptr);
jvmtiError (JNICALL *IsMethodSynthetic) (jvmtiEnv *env,
jmethodID method,
jboolean *is_synthetic_ptr);
jvmtiError (JNICALL *GetLoadedClasses) (jvmtiEnv *env,
jint *class_count_ptr,
jclass **classes_ptr);
jvmtiError (JNICALL *GetClassLoaderClasses) (jvmtiEnv *env,
jobject initiating_loader,
jint *class_count_ptr,
jclass **classes_ptr);
jvmtiError (JNICALL *PopFrame) (jvmtiEnv *env,
jthread thread);
void *reserved81;
void *reserved82;
void *reserved83;
void *reserved84;
void *reserved85;
void *reserved86;
jvmtiError (JNICALL *RedefineClasses) (jvmtiEnv *env,
jint class_count,
const jvmtiClassDefinition* class_definitions);
jvmtiError (JNICALL *GetVersionNumber) (jvmtiEnv *env,
jint *version_ptr);
jvmtiError (JNICALL *GetCapabilities) (jvmtiEnv *env,
jvmtiCapabilities *capabilities_ptr);
jvmtiError (JNICALL *GetSourceDebugExtension) (jvmtiEnv *env,
jclass klass,
char **source_debug_extension_ptr);
jvmtiError (JNICALL *IsMethodObsolete) (jvmtiEnv *env,
jmethodID method,
jboolean *is_obsolete_ptr);
jvmtiError (JNICALL *SuspendThreadList) (jvmtiEnv *env,
jint request_count,
const jthread *request_list,
jvmtiError *results);
jvmtiError (JNICALL *ResumeThreadList) (jvmtiEnv *env,
jint request_count,
const jthread *request_list,
jvmtiError *results);
void *reserved94;
void *reserved95;
void *reserved96;
void *reserved97;
void *reserved98;
void *reserved99;
jvmtiError (JNICALL *GetAllStackTraces) (jvmtiEnv *env,
jint max_frame_count,
jvmtiStackInfo **stack_info_ptr,
jint *thread_count_ptr);
jvmtiError (JNICALL *GetThreadListStackTraces) (jvmtiEnv *env,
jint thread_count,
const jthread *thread_list,
jint max_frame_count,
jvmtiStackInfo **stack_info_ptr);
jvmtiError (JNICALL *GetThreadLocalStorage) (jvmtiEnv *env,
jthread thread,
void **data_ptr);
jvmtiError (JNICALL *SetThreadLocalStorage) (jvmtiEnv *env,
jthread thread,
const void *data);
jvmtiError (JNICALL *GetStackTrace) (jvmtiEnv *env,
jthread thread,
jint start_depth,
jint max_frame_count,
jvmtiFrameInfo *frame_buffer,
jint *count_ptr);
void *reserved105;
jvmtiError (JNICALL *GetTag) (jvmtiEnv *env,
jobject object,
jlong *tag_ptr);
jvmtiError (JNICALL *SetTag) (jvmtiEnv *env,
jobject object,
jlong tag);
jvmtiError (JNICALL *ForceGarbageCollection) (jvmtiEnv *env);
jvmtiError (JNICALL *IterateOverObjectsReachableFromObject) (jvmtiEnv *env,
jobject object,
jvmtiObjectReferenceCallback object_reference_callback,
void *user_data);
jvmtiError (JNICALL *IterateOverReachableObjects) (jvmtiEnv *env,
jvmtiHeapRootCallback heap_root_callback,
jvmtiStackReferenceCallback stack_ref_callback,
jvmtiObjectReferenceCallback object_ref_callback,
void *user_data);
jvmtiError (JNICALL *IterateOverHeap) (jvmtiEnv *env,
jvmtiHeapObjectFilter object_filter,
jvmtiHeapObjectCallback heap_object_callback,
void *user_data);
jvmtiError (JNICALL *IterateOverInstanceOfClass) (jvmtiEnv *env,
jclass klass,
jvmtiHeapObjectFilter object_filter,
jvmtiHeapObjectCallback heap_object_callback,
void *user_data);
void *reserved113;
jvmtiError (JNICALL *GetObjectsWithTags) (jvmtiEnv *env,
jint tag_count,
const jlong *tags,
jint *count_ptr,
jobject **object_result_ptr,
jlong **tag_result_ptr);
void *reserved115;
void *reserved116;
void *reserved117;
void *reserved118;
void *reserved119;
jvmtiError (JNICALL *SetJNIFunctionTable) (jvmtiEnv *env,
const jniNativeInterface *function_table);
jvmtiError (JNICALL *GetJNIFunctionTable) (jvmtiEnv *env,
jniNativeInterface **function_table_ptr);
jvmtiError (JNICALL *SetEventCallbacks) (jvmtiEnv *env,
const jvmtiEventCallbacks *callbacks,
jint size_of_callbacks);
jvmtiError (JNICALL *GenerateEvents) (jvmtiEnv *env,
jvmtiEvent event_type);
jvmtiError (JNICALL *GetExtensionFunctions) (jvmtiEnv *env,
jint *extension_count_ptr,
jvmtiExtensionFunctionInfo **extensions);
jvmtiError (JNICALL *GetExtensionEvents) (jvmtiEnv *env,
jint *extension_count_ptr,
jvmtiExtensionEventInfo **extensions);
jvmtiError (JNICALL *SetExtensionEventCallback) (jvmtiEnv *env,
jint extension_event_index,
jvmtiExtensionEvent callback);
jvmtiError (JNICALL *DisposeEnvironment) (jvmtiEnv *env);
jvmtiError (JNICALL *GetErrorName) (jvmtiEnv *env,
jvmtiError error,
char **name_ptr);
jvmtiError (JNICALL *GetJLocationFormat) (jvmtiEnv *env,
jvmtiJlocationFormat *format_ptr);
jvmtiError (JNICALL *GetSystemProperties) (jvmtiEnv *env,
jint *count_ptr,
char ***property_ptr);
jvmtiError (JNICALL *GetSystemProperty) (jvmtiEnv *env,
const char *property,
char **value_ptr);
jvmtiError (JNICALL *SetSystemProperty) (jvmtiEnv *env,
const char *property,
const char *value);
jvmtiError (JNICALL *GetPhase) (jvmtiEnv *env,
jvmtiPhase *phase_ptr);
jvmtiError (JNICALL *GetCurrentThreadCpuTimerInfo) (jvmtiEnv *env,
jvmtiTimerInfo *info_ptr);
jvmtiError (JNICALL *GetCurrentThreadCpuTime) (jvmtiEnv *env,
jlong *nanos_ptr);
jvmtiError (JNICALL *GetThreadCpuTimerInfo) (jvmtiEnv *env,
jvmtiTimerInfo *info_ptr);
jvmtiError (JNICALL *GetThreadCpuTime) (jvmtiEnv *env,
jthread thread,
jlong *nanos_ptr);
jvmtiError (JNICALL *GetTimerInfo) (jvmtiEnv *env,
jvmtiTimerInfo *info_ptr);
jvmtiError (JNICALL *GetTime) (jvmtiEnv *env,
jlong *nanos_ptr);
jvmtiError (JNICALL *GetPotentialCapabilities) (jvmtiEnv *env,
jvmtiCapabilities *capabilities_ptr);
void *reserved141;
jvmtiError (JNICALL *AddCapabilities) (jvmtiEnv *env,
const jvmtiCapabilities *capabilities_ptr);
jvmtiError (JNICALL *RelinquishCapabilities) (jvmtiEnv *env,
const jvmtiCapabilities *capabilities_ptr);
jvmtiError (JNICALL *GetAvailableProcessors) (jvmtiEnv *env,
jint *processor_count_ptr);
void *reserved145;
void *reserved146;
jvmtiError (JNICALL *GetEnvironmentLocalStorage) (jvmtiEnv *env,
void **data_ptr);
jvmtiError (JNICALL *SetEnvironmentLocalStorage) (jvmtiEnv *env,
const void *data);
jvmtiError (JNICALL *AddToBootstrapClassLoaderSearch) (jvmtiEnv *env,
const char *segment);
jvmtiError (JNICALL *SetVerboseFlag) (jvmtiEnv *env,
jvmtiVerboseFlag flag,
jboolean value);
void *reserved151;
void *reserved152;
void *reserved153;
jvmtiError (JNICALL *GetObjectSize) (jvmtiEnv *env,
jobject object,
jlong *size_ptr);
};
#ifdef __cplusplus
class _Jv_JVMTIEnv
{
public:
/* Method table */
struct _Jv_jvmtiEnv *p;
#ifdef _CLASSPATH_JVMTIENV_CONTENTS
_CLASSPATH_JVMTIENV_CONTENTS
#endif
jvmtiError SetEventNotificationMode (jvmtiEventMode mode,
jvmtiEvent event_type,
jthread event_thread, ...)
{
va_list args;
va_start (args, event_thread);
jvmtiError result = p->SetEventNotificationMode (this, mode, event_type,
event_thread, args);
va_end (args);
return result;
}
jvmtiError GetAllThreads (jint *threads_count_ptr, jthread **threads_ptr)
{ return p->GetAllThreads (this, threads_count_ptr, threads_ptr); }
jvmtiError SuspendThread (jthread thread)
{ return p->SuspendThread (this, thread); }
jvmtiError ResumeThread (jthread thread)
{ return p->ResumeThread (this, thread); }
jvmtiError StopThread (jthread thread, jobject exception)
{ return p->StopThread (this, thread, exception); }
jvmtiError InterruptThread (jthread thread)
{ return p->InterruptThread (this, thread); }
jvmtiError GetThreadInfo (jthread thread, jvmtiThreadInfo *info_ptr)
{ return p->GetThreadInfo (this, thread, info_ptr); }
jvmtiError GetOwnedMonitorInfo (jthread thread,
jint *owned_monitor_count_ptr,
jobject **owned_monitors_ptr)
{
return p->GetOwnedMonitorInfo (this, thread, owned_monitor_count_ptr,
owned_monitors_ptr);
}
jvmtiError GetCurrentContendedMonitor (jthread thread, jobject *monitor_ptr)
{ return p->GetCurrentContendedMonitor (this, thread, monitor_ptr); }
jvmtiError RunAgentThread (jthread thread, jvmtiStartFunction proc,
const void *arg, jint priority)
{ return p->RunAgentThread (this, thread, proc, arg, priority); }
jvmtiError GetTopThreadGroups (jint *group_count_ptr,
jthreadGroup **groups_ptr)
{ return p->GetTopThreadGroups (this, group_count_ptr, groups_ptr); }
jvmtiError GetThreadGroupInfo (jthreadGroup group,
jvmtiThreadGroupInfo *info_ptr)
{ return p->GetThreadGroupInfo (this, group, info_ptr); }
jvmtiError GetThreadGroupChildren (jthreadGroup group,
jint *thread_count_ptr,
jthread **threads_ptr,
jint *group_count_ptr,
jthreadGroup **groups_ptr)
{
return p->GetThreadGroupChildren (this, group, thread_count_ptr,
threads_ptr, group_count_ptr,
groups_ptr);
}
jvmtiError GetFrameCount (jthread thread, jint *count_ptr)
{ return p->GetFrameCount (this, thread, count_ptr); }
jvmtiError GetThreadState (jthread thread, jint *thread_state_ptr)
{ return p->GetThreadState (this, thread, thread_state_ptr); }
jvmtiError GetFrameLocation (jthread thread, jint depth,
jmethodID *method_ptr, jlocation *location_ptr)
{
return p->GetFrameLocation (this, thread, depth, method_ptr,
location_ptr);
}
jvmtiError NotifyPopFrame (jthread thread, jint depth)
{ return p->NotifyPopFrame (this, thread, depth); }
jvmtiError GetLocalObject (jthread thread, jint depth, jint slot,
jobject *value_ptr)
{ return p->GetLocalObject (this, thread, depth, slot, value_ptr); }
jvmtiError GetLocalInt (jthread thread, jint depth, jint slot,
jint *value_ptr)
{ return p->GetLocalInt (this, thread, depth, slot, value_ptr); }
jvmtiError GetLocalLong (jthread thread, jint depth, jint slot,
jlong *value_ptr)
{ return p->GetLocalLong (this, thread, depth, slot, value_ptr); }
jvmtiError GetLocalFloat (jthread thread, jint depth, jint slot,
jfloat *value_ptr)
{ return p->GetLocalFloat (this, thread, depth, slot, value_ptr); }
jvmtiError GetLocalDouble (jthread thread, jint depth, jint slot,
jdouble *value_ptr)
{ return p->GetLocalDouble (this, thread, depth, slot, value_ptr); }
jvmtiError SetLocalObject (jthread thread, jint depth, jint slot,
jobject value)
{ return p->SetLocalObject (this, thread, depth, slot, value); }
jvmtiError SetLocalInt (jthread thread, jint depth, jint slot,
jint value)
{ return p->SetLocalInt (this, thread, depth, slot, value); }
jvmtiError SetLocalLong (jthread thread, jint depth, jint slot,
jlong value)
{ return p->SetLocalLong (this, thread, depth, slot, value); }
jvmtiError SetLocalFloat (jthread thread, jint depth, jint slot,
jfloat value)
{ return p->SetLocalFloat (this, thread, depth, slot, value); }
jvmtiError SetLocalDouble (jthread thread, jint depth, jint slot,
jdouble value)
{ return p->SetLocalDouble (this, thread, depth, slot, value); }
jvmtiError CreateRawMonitor (const char *name, jrawMonitorID *monitor_ptr)
{ return p->CreateRawMonitor (this, name, monitor_ptr); }
jvmtiError DestroyRawMonitor (jrawMonitorID monitor)
{ return p->DestroyRawMonitor (this, monitor); }
jvmtiError RawMonitorEnter (jrawMonitorID monitor)
{ return p->RawMonitorEnter (this, monitor); }
jvmtiError RawMonitorExit (jrawMonitorID monitor)
{ return p->RawMonitorExit (this, monitor); }
jvmtiError RawMonitorWait (jrawMonitorID monitor, jlong millis)
{ return p->RawMonitorWait (this, monitor, millis); }
jvmtiError RawMonitorNotify (jrawMonitorID monitor)
{ return p->RawMonitorNotify (this, monitor); }
jvmtiError RawMonitorNotifyAll (jrawMonitorID monitor)
{ return p->RawMonitorNotifyAll (this, monitor); }
jvmtiError SetBreakpoint (jmethodID method, jlocation location)
{ return p->SetBreakpoint (this, method, location); }
jvmtiError ClearBreakpoint (jmethodID method, jlocation location)
{ return p->ClearBreakpoint (this, method, location); }
jvmtiError SetFieldAccessWatch (jclass klass, jfieldID field)
{ return p->SetFieldAccessWatch (this, klass, field); }
jvmtiError ClearFieldAccessWatch (jclass klass, jfieldID field)
{ return p->ClearFieldAccessWatch (this, klass, field); }
jvmtiError SetFieldModificationWatch (jclass klass, jfieldID field)
{ return p->SetFieldModificationWatch (this, klass, field); }
jvmtiError ClearFieldModificationWatch (jclass klass, jfieldID field)
{ return p->ClearFieldModificationWatch (this, klass, field); }
jvmtiError Allocate (jlong size, unsigned char **mem_ptr)
{ return p->Allocate (this, size, mem_ptr); }
jvmtiError Deallocate (unsigned char *mem)
{ return p->Deallocate (this, mem); }
jvmtiError GetClassSignature (jclass klass, char **signature_ptr,
char **generic_ptr)
{ return p->GetClassSignature (this, klass, signature_ptr, generic_ptr); }
jvmtiError GetClassStatus (jclass klass, jint *status_ptr)
{ return p->GetClassStatus (this, klass, status_ptr); }
jvmtiError GetSourceFileName (jclass klass, char **source_name_ptr)
{ return p->GetSourceFileName (this, klass, source_name_ptr); }
jvmtiError GetClassModifiers (jclass klass, jint *modifiers_ptr)
{ return p->GetClassModifiers (this, klass, modifiers_ptr); }
jvmtiError GetClassMethods (jclass klass, jint *method_count_ptr,
jmethodID **methods_ptr)
{ return p->GetClassMethods (this, klass, method_count_ptr, methods_ptr); }
jvmtiError GetClassFields (jclass klass, jint *field_count_ptr,
jfieldID **fields_ptr)
{ return p->GetClassFields (this, klass, field_count_ptr, fields_ptr); }
jvmtiError GetImplementedInterfaces (jclass klass,
jint *interface_count_ptr,
jclass **interfaces_ptr)
{
return p->GetImplementedInterfaces (this, klass, interface_count_ptr,
interfaces_ptr);
}
jvmtiError IsInterface (jclass klass, jboolean *is_interface_ptr)
{ return p->IsInterface (this, klass, is_interface_ptr); }
jvmtiError IsArrayClass (jclass klass, jboolean *is_array_class_ptr)
{ return p->IsArrayClass (this, klass, is_array_class_ptr); }
jvmtiError GetClassLoader (jclass klass, jobject *classloader_ptr)
{ return p->GetClassLoader (this, klass, classloader_ptr); }
jvmtiError GetObjectHashCode (jobject object, jint *hash_code_ptr)
{ return p->GetObjectHashCode (this, object, hash_code_ptr); }
jvmtiError GetObjectMonitorUsage (jobject object,
jvmtiMonitorUsage *info_ptr)
{ return p->GetObjectMonitorUsage (this, object, info_ptr); }
jvmtiError GetFieldName (jclass klass, jfieldID field, char **name_ptr,
char **signature_ptr, char **generic_ptr)
{
return p->GetFieldName (this, klass, field, name_ptr,
signature_ptr, generic_ptr);
}
jvmtiError GetFieldDeclaringClass (jclass klass, jfieldID field,
jclass *declaring_class_ptr)
{
return p->GetFieldDeclaringClass (this, klass, field,
declaring_class_ptr);
}
jvmtiError GetFieldModifiers (jclass klass, jfieldID field,
jint *modifiers_ptr)
{ return p->GetFieldModifiers (this, klass, field, modifiers_ptr); }
jvmtiError IsFieldSynthetic (jclass klass, jfieldID field,
jboolean *is_synthetic_ptr)
{ return p->IsFieldSynthetic (this, klass, field, is_synthetic_ptr); }
jvmtiError GetMethodName (jmethodID method, char **name_ptr,
char **signature_ptr, char **generic_ptr)
{
return p->GetMethodName (this, method, name_ptr, signature_ptr,
generic_ptr);
}
jvmtiError GetMethodDeclaringClass (jmethodID method,
jclass *declaring_class_ptr)
{ return p->GetMethodDeclaringClass (this, method, declaring_class_ptr); }
jvmtiError GetMethodModifiers (jmethodID method, jint *modifiers_ptr)
{ return p->GetMethodModifiers (this, method, modifiers_ptr); }
jvmtiError GetMaxLocals (jmethodID method, jint *max_ptr)
{ return p->GetMaxLocals (this, method, max_ptr); }
jvmtiError GetArgumentsSize (jmethodID method, jint *size_ptr)
{ return p->GetArgumentsSize (this, method, size_ptr); }
jvmtiError GetLineNumberTable (jmethodID method, jint *entry_count_ptr,
jvmtiLineNumberEntry **table_ptr)
{ return p->GetLineNumberTable (this, method, entry_count_ptr, table_ptr); }
jvmtiError GetMethodLocation (jmethodID method,
jlocation *start_location_ptr,
jlocation *end_location_ptr)
{
return p->GetMethodLocation (this, method, start_location_ptr,
end_location_ptr);
}
jvmtiError GetLocalVariableTable (jmethodID method, jint *entry_count_ptr,
jvmtiLocalVariableEntry **table_ptr)
{
return p->GetLocalVariableTable (this, method, entry_count_ptr,
table_ptr);
}
jvmtiError GetBytecodes (jmethodID method, jint *bytecode_count_ptr,
unsigned char **bytecodes_ptr)
{
return p->GetBytecodes (this, method, bytecode_count_ptr,
bytecodes_ptr);
}
jvmtiError IsMethodNative (jmethodID method, jboolean *is_native_ptr)
{ return p->IsMethodNative (this, method, is_native_ptr); }
jvmtiError IsMethodSynthetic (jmethodID method, jboolean *is_synthetic_ptr)
{ return p->IsMethodSynthetic (this, method, is_synthetic_ptr); }
jvmtiError GetLoadedClasses (jint *class_count_ptr, jclass **classes_ptr)
{ return p->GetLoadedClasses (this, class_count_ptr, classes_ptr); }
jvmtiError GetClassLoaderClasses (jobject initiating_loader,
jint *class_count_ptr,
jclass **classes_ptr)
{
return p->GetClassLoaderClasses (this, initiating_loader,
class_count_ptr, classes_ptr);
}
jvmtiError PopFrame (jthread thread)
{ return p->PopFrame (this, thread); }
jvmtiError RedefineClasses (jint class_count,
const jvmtiClassDefinition* class_definitions)
{ return p->RedefineClasses (this, class_count, class_definitions); }
jvmtiError GetVersionNumber (jint *version_ptr)
{ return p->GetVersionNumber (this, version_ptr); }
jvmtiError GetCapabilities (jvmtiCapabilities *capabilities_ptr)
{ return p->GetCapabilities (this, capabilities_ptr); }
jvmtiError GetSourceDebugExtension (jclass klass,
char **source_debug_extension_ptr)
{
return p->GetSourceDebugExtension (this, klass,
source_debug_extension_ptr);
}
jvmtiError IsMethodObsolete (jmethodID method, jboolean *is_obsolete_ptr)
{ return p->IsMethodObsolete (this, method, is_obsolete_ptr); }
jvmtiError SuspendThreadList (jint request_count,
const jthread *request_list,
jvmtiError *results)
{ return p->SuspendThreadList (this, request_count, request_list, results); }
jvmtiError ResumeThreadList (jint request_count,
const jthread *request_list,
jvmtiError *results)
{ return p->ResumeThreadList (this, request_count, request_list, results); }
jvmtiError GetAllStackTraces (jint max_frame_count,
jvmtiStackInfo **stack_info_ptr,
jint *thread_count_ptr)
{
return p->GetAllStackTraces (this, max_frame_count, stack_info_ptr,
thread_count_ptr);
}
jvmtiError GetThreadListStackTraces (jint thread_count,
const jthread *thread_list,
jint max_frame_count,
jvmtiStackInfo **stack_info_ptr)
{
return p->GetThreadListStackTraces (this, thread_count, thread_list,
max_frame_count, stack_info_ptr);
}
jvmtiError GetThreadLocalStorage (jthread thread, void **data_ptr)
{ return p->GetThreadLocalStorage (this, thread, data_ptr); }
jvmtiError SetThreadLocalStorage (jthread thread, const void *data)
{ return p->SetThreadLocalStorage (this, thread, data); }
jvmtiError GetStackTrace (jthread thread, jint start_depth,
jint max_frame_count,
jvmtiFrameInfo *frame_buffer, jint *count_ptr)
{
return p->GetStackTrace (this, thread, start_depth, max_frame_count,
frame_buffer, count_ptr);
}
jvmtiError GetTag (jobject object, jlong *tag_ptr)
{ return p->GetTag (this, object, tag_ptr); }
jvmtiError SetTag (jobject object, jlong tag)
{ return p->SetTag (this, object, tag); }
jvmtiError ForceGarbageCollection (void)
{ return p->ForceGarbageCollection (this); }
jvmtiError IterateOverObjectsReachableFromObject (jobject object,
jvmtiObjectReferenceCallback object_reference_callback,
void *user_data)
{
return p->IterateOverObjectsReachableFromObject (this, object,
object_reference_callback,
user_data);
}
jvmtiError IterateOverReachableObjects (jvmtiHeapRootCallback heap_root_callback,
jvmtiStackReferenceCallback stack_ref_callback,
jvmtiObjectReferenceCallback object_ref_callback,
void *user_data)
{
return p->IterateOverReachableObjects (this, heap_root_callback,
stack_ref_callback,
object_ref_callback,
user_data);
}
jvmtiError IterateOverHeap (jvmtiHeapObjectFilter object_filter,
jvmtiHeapObjectCallback heap_object_callback,
void *user_data)
{
return p->IterateOverHeap (this, object_filter, heap_object_callback,
user_data);
}
jvmtiError IterateOverInstanceOfClass (jclass klass,
jvmtiHeapObjectFilter object_filter,
jvmtiHeapObjectCallback heap_object_callback,
void *user_data)
{
return p->IterateOverInstanceOfClass (this, klass, object_filter,
heap_object_callback, user_data);
}
jvmtiError GetObjectsWithTags (jint tag_count, const jlong *tags,
jint *count_ptr, jobject **object_result_ptr,
jlong **tag_result_ptr)
{
return p->GetObjectsWithTags (this, tag_count, tags, count_ptr,
object_result_ptr, tag_result_ptr);
}
jvmtiError SetJNIFunctionTable (const jniNativeInterface *function_table)
{ return p->SetJNIFunctionTable (this, function_table); }
jvmtiError GetJNIFunctionTable (jniNativeInterface **function_table_ptr)
{ return p->GetJNIFunctionTable (this, function_table_ptr); }
jvmtiError SetEventCallbacks (const jvmtiEventCallbacks *callbacks,
jint size_of_callbacks)
{ return p->SetEventCallbacks (this, callbacks, size_of_callbacks); }
jvmtiError GenerateEvents (jvmtiEvent event_type)
{ return p->GenerateEvents (this, event_type); }
jvmtiError GetExtensionFunctions (jint *extension_count_ptr,
jvmtiExtensionFunctionInfo **extensions)
{ return p->GetExtensionFunctions (this, extension_count_ptr, extensions); }
jvmtiError GetExtensionEvents (jint *extension_count_ptr,
jvmtiExtensionEventInfo **extensions)
{ return p->GetExtensionEvents (this, extension_count_ptr, extensions); }
jvmtiError SetExtensionEventCallback (jint extension_event_index,
jvmtiExtensionEvent callback)
{
return p->SetExtensionEventCallback (this, extension_event_index,
callback);
}
jvmtiError DisposeEnvironment (void)
{ return p->DisposeEnvironment (this); }
jvmtiError GetErrorName (jvmtiError error, char **name_ptr)
{ return p->GetErrorName (this, error, name_ptr); }
jvmtiError GetJLocationFormat (jvmtiJlocationFormat *format_ptr)
{ return p->GetJLocationFormat (this, format_ptr); }
jvmtiError GetSystemProperties (jint *count_ptr, char ***property_ptr)
{ return p->GetSystemProperties (this, count_ptr, property_ptr); }
jvmtiError GetSystemProperty (const char *property, char **value_ptr)
{ return p->GetSystemProperty (this, property, value_ptr); }
jvmtiError SetSystemProperty (const char *property, const char *value)
{ return p->SetSystemProperty (this, property, value); }
jvmtiError GetPhase (jvmtiPhase *phase_ptr)
{ return p->GetPhase (this, phase_ptr); }
jvmtiError GetCurrentThreadCpuTimerInfo (jvmtiTimerInfo *info_ptr)
{ return p->GetCurrentThreadCpuTimerInfo (this, info_ptr); }
jvmtiError GetCurrentThreadCpuTime (jlong *nanos_ptr)
{ return p->GetCurrentThreadCpuTime (this, nanos_ptr); }
jvmtiError GetThreadCpuTimerInfo (jvmtiTimerInfo *info_ptr)
{ return p->GetThreadCpuTimerInfo (this, info_ptr); }
jvmtiError GetThreadCpuTime (jthread thread, jlong *nanos_ptr)
{ return p->GetThreadCpuTime (this, thread, nanos_ptr); }
jvmtiError GetTimerInfo (jvmtiTimerInfo *info_ptr)
{ return p->GetTimerInfo (this, info_ptr); }
jvmtiError GetTime (jlong *nanos_ptr)
{return p->GetTime (this, nanos_ptr); }
jvmtiError GetPotentialCapabilities (jvmtiCapabilities *capabilities_ptr)
{ return p->GetPotentialCapabilities (this, capabilities_ptr); }
jvmtiError AddCapabilities (const jvmtiCapabilities *capabilities_ptr)
{ return p->AddCapabilities (this, capabilities_ptr); }
jvmtiError RelinquishCapabilities (const jvmtiCapabilities *capabilities_ptr)
{ return p->RelinquishCapabilities (this, capabilities_ptr); }
jvmtiError GetAvailableProcessors (jint *processor_count_ptr)
{ return p->GetAvailableProcessors (this, processor_count_ptr); }
jvmtiError GetEnvironmentLocalStorage (void **data_ptr)
{ return p->GetEnvironmentLocalStorage (this, data_ptr); }
jvmtiError SetEnvironmentLocalStorage (const void *data)
{ return p->SetEnvironmentLocalStorage (this, data); }
jvmtiError AddToBootstrapClassLoaderSearch (const char *segment)
{ return p->AddToBootstrapClassLoaderSearch (this, segment); }
jvmtiError SetVerboseFlag (jvmtiVerboseFlag flag, jboolean value)
{ return p->SetVerboseFlag (this, flag, value); }
jvmtiError GetObjectSize (jobject object, jlong *size_ptr)
{ return p->GetObjectSize (this, object, size_ptr); }
};
#endif /* __cplusplus */
/*
* Miscellaneous flags, constants, etc
*/
/* Class status flags */
#define JVMTI_CLASS_STATUS_VERIFIED 1
#define JVMTI_CLASS_STATUS_PREPARED 2
#define JVMTI_CLASS_STATUS_INITIALIZED 4
#define JVMTI_CLASS_STATUS_ERROR 8
#define JVMTI_CLASS_STATUS_ARRAY 16
#define JVMTI_CLASS_STATUS_PRIMITIVE 32
/* Thread state flags */
#define JVMTI_THREAD_STATE_ALIVE 0x0001
#define JVMTI_THREAD_STATE_TERMINATED 0x0002
#define JVMTI_THREAD_STATE_RUNNABLE 0x0004
#define JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER 0x0400
#define JVMTI_THREAD_STATE_WAITING 0x0080
#define JVMTI_THREAD_STATE_WAITING_INDEFINITELY 0x0010
#define JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT 0x0020
#define JVMTI_THREAD_STATE_SLEEPING 0x0040
#define JVMTI_THREAD_STATE_IN_OBJECT_WAIT 0x0100
#define JVMTI_THREAD_STATE_PARKED 0x0200
#define JVMTI_THREAD_STATE_SUSPENDED 0x100000
#define JVMTI_THREAD_STATE_INTERRUPTED 0x200000
#define JVMTI_THREAD_STATE_IN_NATIVE 0x400000
#define JVMTI_THREAD_STATE_VENDOR_1 0x10000000
#define JVMTI_THREAD_STATE_VENDOR_2 0x20000000
#define JVMTI_THREAD_STATE_VENDOR_3 0x40000000
/* java.lang.Thread.State conversion masks */
#define JVMTI_JAVA_LANG_THREAD_STATE_MASK \
(JVMTI_THREAD_STATE_TERMINATED \
| JVMTI_THREAD_STATE_ALIVE \
| JVMTI_THREAD_STATE_RUNNABLE \
| JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER \
| JVMTI_THREAD_STATE_WAITING \
| JVMTI_THREAD_STATE_WAITING_INDEFINITELY \
| JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT)
#define JVMTI_JAVA_LANG_THREAD_STATE_NEW 0
#define JVMTI_JAVA_LANG_THREAD_STATE_TERMINATED JVMTI_THREAD_STATE_TERMINATED
#define JVMTI_JAVA_LANG_THREAD_STATE_RUNNABLE \
(JVMTI_THREAD_STATE_ALIVE \
| JVMTI_THREAD_STATE_RUNNABLE)
#define JVMTI_JAVA_LANG_THREAD_STATE_BLOCKED \
(JVMTI_THREAD_STATE_ALIVE \
| JVMTI_THREAD_STATE_BLOCKED_ON_MONITOR_ENTER)
#define JVMTI_JAVA_LANG_THREAD_STATE_WAITING \
(JVMTI_THREAD_STATE_ALIVE \
| JVMTI_THREAD_STATE_WAITING \
| JVMTI_THREAD_STATE_WAITING_INDEFINITELY)
#define JVMTI_JAVA_LANG_THREAD_STATE_TIMED_WAITING \
(JVMTI_THREAD_STATE_ALIVE \
| JVMTI_THREAD_STATE_WAITING \
| JVMTI_THREAD_STATE_WAITING_WITH_TIMEOUT)
/* Thread priorities */
#define JVMTI_THREAD_MIN_PRIORITY 1
#define JVMTI_THREAD_NORM_PRIORITY 5
#define JVMTI_THREAD_MAX_PRIORITY 10
/* Keep c-font-lock-extra-types in order: JNI followed by JVMTI,
all in alphabetical order */
/* Local Variables: */
/* c-font-lock-extra-types: ("\\sw+_t"
"JNIEnv" "JNINativeMethod" "JavaVM" "JavaVMOption" "jarray"
"jboolean" "jbooleanArray" "jbyte" "jbyteArray" "jchar" "jcharArray"
"jclass" "jdouble" "jdoubleArray" "jfieldID" "jfloat" "jfloatArray"
"jint" "jintArray" "jlong" "jlongArray" "jmethodID" "jobject" "jstring" "jthrowable"
"jvalue" "jweak"
"jvmtiEnv" "jvmtiError"
"jthread" "jthreadGroup" "jlocation" "jrawMonitorID") */
/* End: */
#endif /* !_CLASSPATH_JVMTI_H */
| 31.493407 | 87 | 0.741495 | [
"object"
] |
c4565d53832d00c025f59ce1133e07c67229bc44 | 4,014 | h | C | include/DeprecatedGUI/CGuiSkin.h | JiPRA/openlierox | 1d9a490cb3b214c7f6dad3a7d582b54373b5b9dc | [
"CECILL-B"
] | 192 | 2015-02-13T14:53:59.000Z | 2022-03-29T11:18:58.000Z | include/DeprecatedGUI/CGuiSkin.h | JiPRA/openlierox | 1d9a490cb3b214c7f6dad3a7d582b54373b5b9dc | [
"CECILL-B"
] | 48 | 2015-01-06T22:00:53.000Z | 2022-01-15T18:22:46.000Z | include/DeprecatedGUI/CGuiSkin.h | JiPRA/openlierox | 1d9a490cb3b214c7f6dad3a7d582b54373b5b9dc | [
"CECILL-B"
] | 51 | 2015-01-16T00:55:16.000Z | 2022-02-05T03:09:30.000Z | /////////////////////////////////////////
//
// OpenLieroX
//
// code under LGPL, based on JasonBs work,
// enhanced by Dark Charlie and Albert Zeyer
//
//
/////////////////////////////////////////
#ifndef __CGUISKIN_H__DEPRECATED_GUI__
#define __CGUISKIN_H__DEPRECATED_GUI__
#include <string>
#include <map>
#include <vector>
#include <list>
#include "CScriptableVars.h"
namespace DeprecatedGUI {
class CWidget;
class CGuiLayoutBase;
class CGuiSkinnedLayout;
class CGuiSkin // Singletone
{
public:
static CGuiSkin & Init(); // Called automatically
static void DeInit(); // Should be called from main()
static CGuiSkinnedLayout * GetLayout( const std::string & filename ); // Get GUI layout from cache or create it from disk
static void ClearLayouts();
// has to be a vector because the order is important in the WidgetCreator
typedef std::vector< std::pair< std::string, ScriptVarType_t > > paramListVector_t;
// WidgetCreator will create widget and add it to specified CGuiLayout (and init it a bit after that if necessary).
typedef CWidget * ( * WidgetCreator_t ) ( const std::vector< ScriptVar_t > & params, CGuiLayoutBase * layout, int id, int x, int y, int w, int h );
// Allows registering params with daisy-chaining
class WidgetRegisterHelper
{
friend class CGuiSkin;
paramListVector_t & m_params; // Reference to CGuiSkin.m_vars
WidgetRegisterHelper( paramListVector_t & params ):
m_params( params ) {};
public:
operator bool () { return true; }; // To be able to write static expressions
WidgetRegisterHelper & operator() ( const std::string & c, ScriptVarType_t vt )
{ m_params.push_back( std::pair< std::string, ScriptVarType_t >(c, vt) ); return *this; };
};
static WidgetRegisterHelper RegisterWidget( const std::string & name, WidgetCreator_t creator )
{
Init();
m_instance->m_widgets[name] = std::pair< paramListVector_t, WidgetCreator_t > ( paramListVector_t(), creator );
return WidgetRegisterHelper( m_instance->m_widgets[name].first );
};
static std::string DumpWidgets(); // For debug output
// Helper class for callback info thst should be inserted into widget
class CallbackHandler
{
std::vector< std::pair< ScriptCallback_t, std::string > > m_callbacks;
CWidget * m_source;
public:
void Init( const std::string & param, CWidget * source );
void Call();
CallbackHandler(): m_source(NULL) { };
CallbackHandler( const std::string & param, CWidget * source ) { Init( param, source ); };
};
// Update will be called on each frame with following params
static void RegisterUpdateCallback( ScriptCallback_t update, const std::string & param, CWidget * source );
// Remove widget from update list ( called from widget destructor )
static void DeRegisterUpdateCallback( CWidget * source );
// Called on each frame
static void ProcessUpdateCallbacks();
// INIT_WIDGET is special event for Widget::ProcessGuiSkinEvent() which is called
// after widget added to CGuiLayout - some widgets (textbox and combobox) require this.
// SHOW_WIDGET is special event for Widget::ProcessGuiSkinEvent() which is called
// when the dialog is shown - dialogs are cached into memory and may be shown or hidden.
// No need for HIDE_WIDGET yet.
enum { SHOW_WIDGET = -4 }; // Removed INIT_WIDGET because of more intelligent WidgetCreator_t
private:
friend class WidgetRegisterHelper;
// Should be private, please use CGuiSkin::Vars() and other member functions to have access to them
static CGuiSkin * m_instance;
std::map< std::string, CGuiSkinnedLayout * > m_guis; // All loaded in-game GUI layouts
std::map< std::string, std::pair< paramListVector_t, WidgetCreator_t > > m_widgets; // All widget classes
struct UpdateList_t
{
UpdateList_t( CWidget * s, ScriptCallback_t u, const std::string & p ):
source( s ), update( u ), param( p ) { };
CWidget * source;
ScriptCallback_t update;
std::string param;
};
std::list< UpdateList_t > m_updateCallbacks;
};
} // namespace DeprecatedGUI
#endif
| 33.731092 | 148 | 0.716492 | [
"vector"
] |
c460cd76b666632b015b7b9248714da896a3dc97 | 13,929 | c | C | tools/shptools/shp2sdo.c | woodbri/imaptools.com | 44fcb71843ab1353aec04e2b7544094d2e1c3575 | [
"MIT"
] | 1 | 2020-02-12T16:20:09.000Z | 2020-02-12T16:20:09.000Z | tools/shptools/shp2sdo.c | ysoriano-kore/imaptools.com | 44fcb71843ab1353aec04e2b7544094d2e1c3575 | [
"MIT"
] | null | null | null | tools/shptools/shp2sdo.c | ysoriano-kore/imaptools.com | 44fcb71843ab1353aec04e2b7544094d2e1c3575 | [
"MIT"
] | 4 | 2020-01-20T19:39:50.000Z | 2021-11-22T09:12:43.000Z | /*********************************************************************
*
* $Id: shp2sdo.c,v 1.1 2006/09/28 15:26:15 woodbri Exp $
*
* shp2sdo
* Copyright 2006, Stephen Woodbridge, All rights Reserved
* Redistribition without written permission strictly prohibited
*
**********************************************************************
*
* shp2sdo.c
*
* $Log: shp2sdo.c,v $
* Revision 1.1 2006/09/28 15:26:15 woodbri
* Adding shp2sdo.c
*
*
* 2006-09-26 sew, created from shpcpy.c
*
**********************************************************************
*
* Utility to convert shapefiles into Oracle sdo loader files
*
**********************************************************************/
#define USE_GETOPT_LONG 1
#ifdef USE_GETOPT_LONG
#define _GNU_SOURCE
#include <getopt.h>
#else
#include <unistd.h>
#endif
#include <assert.h>
#include <errno.h>
#include <ctype.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#ifdef DEBIAN_LIBSHP
#include <shapefil.h>
#else
#include <libshp/shapefil.h>
#endif
// Debug print out
#define DBGOUT(s) (s)
//#define DBGOUT(s)
extern int DEBUG;
int DEBUG = 0;
void Usage()
{
printf("Usage: shp2sdo [-o] <shapefile> <tablename> -g <geometry column>\n"
" -i <id column> -n <start_id> -p -d\n"
" -x (xmin,xmax) -y (ymin,ymax) -s <srid>\n"
" or\n"
" shp2sdo -r <shapefile> <outlayer> -c <ordcount> -n <start_gid> -a -d\n"
" -x (xmin,xmax) -y (ymin,ymax)\n"
" shapefile - name of input shape file\n"
" (Do not include suffix .shp .dbf or .shx)\n"
" tablename - spatial table name\n"
" if not specified: same as input file name\n"
" Generic options:\n"
" -o - Convert to object/relational format (default)\n"
" -r - Convert to the relational format\n"
" -d - store data in the control file\n"
" if not specified: keep data in separate files\n"
" -x - bounds for the X dimension\n"
" -y - bounds for the Y dimension\n"
" -v - verbose output\n"
" -h or -? - print this message\n"
" Options valid for the object model only:\n"
" -g geom_col - Name of the column used for the SDO_GEOMETRY object\n"
" if not specified: GEOMETRY\n"
" -i id_column - Name of the column used for numbering the geometries\n"
" if not specified, no key column will be generated\n"
" if specified without name, use ID\n"
" -n start_id - Start number for IDs\n"
" if not specified, start at 1\n"
" -p - Store points in the SDO_ORDINATES array\n"
" if not specified, store in SDO_POINT\n"
" -s - Load SRID field in geometry and metadata\n"
" if not specified, SRID field is NULL\n"
" -t - Load tolerance fields (x and y) in metadata\n"
" if not specified, tolerance fields are 0.00000005\n"
" -8 - Write control file in 8i format\n"
" if not specified, file written in 9i format\n"
" -f - Write geometry data with 10 digits of precision\n"
" if not specified, 6 digits of precision is used\n"
" Options valid for the relational model only:\n"
" -c ordcount - Number of ordinates in _SDOGOEM table\n"
" if not specified: 16 ordinates\n"
" -n start_gid - Start number for GIDs\n"
" if not specified, start at 1\n"
" -a - attributes go in _SDOGEOM table\n"
" if not specified, attributes are in separate table\n");
exit(0);
}
char *strtoupper(char *str)
{
char *s = strdup(str);
int i;
for (i=0; i<strlen(s); i++)
s[i] = toupper(s[i]);
return s;
}
int main( int argc, char ** argv )
{
FILE *SQL;
FILE *CTL;
FILE *DAT;
DBFHandle dIN;
SHPHandle sIN;
SHPObject *sobj;
DBFFieldType fType;
char *fin;
char *table;
char fldname[12];
char fsql[256];
char fctl[256];
char fdat[256];
int c;
int nEnt, sType, fw, fd;
int i, j, rec, n;
double zX[2] = {0.0, 0.0};
double zY[2] = {0.0, 0.0};
double sMin[4];
double sMax[4];
#ifdef USE_GETOPT_LONG
static struct option long_options[] = {
{"help", 0, 0, 'h'},
{0, 0, 0, 0}
};
#endif
int odatactl = 0;
int mode = 'o';
int verbose = 0;
int start_id = 1;
int oraformat = 9;
int percision = 6;
int ordcount = 16;
int start_gid = 1;
long tm;
char *xextents = NULL;
char *yextents = NULL;
char *geom_col = "GEOMETRY";
char *id_column = NULL;
char *sdo_ordinates = "SDO_POINT";
char *srid = "NULL";
char *attributes = NULL;
double tolerance = 0.00000005;
double xmin = -180.0;
double xmax = 180.0;
double ymin = -90.0;
double ymax = 90.0;
while (1) {
int option_index = 0;
/*
c = getopt_long( argc, argv, "ordx:y:vhg:i:n:p:s:t:8fc:a:",
long_options, &option_index);
*/
c = getopt( argc, argv, "ordx:y:vhg:i:n:p:s:t:8fc:a:");
/* Detect the end of options. */
if (c == -1)
break;
switch (c) {
case 'o':
mode = 'o';
break;
case 'r':
mode = 'r';
break;
case 'd':
odatactl = 1;
break;
case 'x':
xextents = optarg;
break;
case 'y':
yextents = optarg;
break;
case 'v':
verbose += 1;
break;
case '?':
case 'h':
Usage();
break;
case 'g':
geom_col = optarg;
break;
case 'i':
id_column = optarg;
break;
case 'n':
start_id = strtol(optarg, NULL, 10);
break;
case 'p':
sdo_ordinates = optarg;
break;
case 's':
srid = optarg;
break;
case 't':
tolerance = strtod(optarg, NULL);
break;
case '8':
oraformat = 8;
break;
case 'f':
percision = 10;
break;
case 'c':
ordcount = strtol(optarg, NULL, 10);
break;
case 'a':
start_gid = strtol(optarg, NULL, 10);
break;
default:
Usage();
}
}
if ((argc - optind) != 2) Usage();
fin = argv[optind];
table = argv[optind+1];
/* do some sanity checking of arguments */
if (mode == 'r') {
printf("Sorry relational format is not currently supported\n");
exit(1);
}
if (xextents) {
if (sscanf(xextents, "(%f,%f)", &xmin, &xmax) == EOF) {
printf("Error parsing parameter -x '%s' as (%%f,%%f)\n", xextents);
exit(1);
}
}
if (yextents) {
if (sscanf(yextents, "(%f,%f)", &ymin, &ymax) == EOF) {
printf("Error parsing parameter -y '%s' as (%%f,%%f)\n", xextents);
exit(1);
}
}
if (!(dIN = DBFOpen(fin, "rb"))) {
printf("Failed to open dbf %s for read\n", fin);
exit(1);
}
if (!(sIN = SHPOpen(fin, "rb"))) {
printf("Failed to open shp %s for read\n", fin);
exit(1);
}
SHPGetInfo(sIN, &nEnt, &sType, sMin, sMax);
if (sType%10 != 1 && sType%10 != 3) {
printf("Only point and arc type shapefiles are currently supported!\n");
exit(1);
}
strcpy(fsql, table);
strcat(fsql, ".sql");
if (!(SQL = fopen(fsql, "wb"))) {
printf("Failed to create %s for write\n", fsql);
exit(1);
}
strcpy(fctl, table);
strcat(fctl, ".ctl");
if (!(CTL = fopen(fctl, "wb"))) {
printf("Failed to create %s for write\n", fctl);
exit(1);
}
strcpy(fdat, table);
strcat(fdat, ".dat");
if (!(DAT = fopen(fdat, "wb"))) {
printf("Failed to create %s for write\n", fdat);
exit(1);
}
/* this return a strdup of the input string, so free it */
table = strtoupper(table);
/* write the .sql and .ctl file */
fprintf(CTL, "LOAD DATA\n");
fprintf(CTL, " INFILE %s\n", fdat);
fprintf(CTL, " TRUNCATE\n");
fprintf(CTL, " CONTINUEIF NEXT(1:1) = '#'\n");
fprintf(CTL, " INTO TABLE %s\n", table);
fprintf(CTL, " FIELDS TERMINATED BY '|'\n");
fprintf(CTL, " TRAILING NULLCOLS (\n");
fprintf(SQL, "-- %s\n", fsql);
fprintf(SQL, "--\n");
fprintf(SQL, "-- This script creates the spatial table.\n");
fprintf(SQL, "--\n");
fprintf(SQL, "-- Execute this script before attempting to use SQL*Loader\n");
fprintf(SQL, "-- to load the %s file\n", fctl);
fprintf(SQL, "--\n");
fprintf(SQL, "-- This script will also populate the USER_SDO_GEOM_METADATA table.\n");
fprintf(SQL, "-- Loading the .ctl file will populate %s table.\n", table);
fprintf(SQL, "--\n");
fprintf(SQL, "-- To load the .ctl file, run SQL*Loader as follows\n");
fprintf(SQL, "-- substituting appropriate values\n");
fprintf(SQL, "-- sqlldr username/password %s\n", fctl);
fprintf(SQL, "--\n");
fprintf(SQL, "-- After the data is loaded in the %s table, you should\n", table);
fprintf(SQL, "-- migrate polygon data and create the spatial index\n");
fprintf(SQL, "--\n");
tm = time(NULL);
fprintf(SQL, "-- CreationDate : %s\n", ctime(&tm));
fprintf(SQL, "-- Copyright 2006, Where2getit, Inc.\n");
fprintf(SQL, "-- Copyright 2006, Stephen Woodbridge\n");
fprintf(SQL, "-- All rights reserved\n");
fprintf(SQL, "--\n");
fprintf(SQL, "DROP TABLE %s;\n\n", table);
fprintf(SQL, "CREATE TABLE %s (\n", table);
for (i=0; i<DBFGetFieldCount(dIN); i++) {
fType = DBFGetFieldInfo(dIN, i, fldname, &fw, &fd);
if (fType == FTInteger) {
fprintf(CTL, " %s,\n", fldname);
fprintf(SQL, " %s \tNUMBER,\n", fldname);
} else if (fType == FTString) {
fprintf(CTL, " %-15s NULLIF %s = BLANKS,\n", fldname, fldname);
fprintf(SQL, " %s \tVARCHAR2(%d),\n", fldname, fw);
} else if (fType == FTDouble) {
fprintf(CTL, " %s,\n", fldname);
fprintf(SQL, " %s \tFLOAT,\n", fldname);
} else {
printf("Invalid or unknown column type in shapefile (%s).\n", fldname);
exit(1);
}
}
fprintf(CTL, " %s COLUMN OBJECT\n", geom_col);
fprintf(CTL, " (\n");
fprintf(CTL, " SDO_GTYPE INTEGER EXTERNAL,\n");
fprintf(CTL, " SDO_SRID INTEGER EXTERNAL,\n");
if (sType%10 == 1) { /* point objects here */
fprintf(CTL, " SDO_POINT COLUMN OBJECT\n");
fprintf(CTL, " (X FLOAT EXTERNAL,\n");
fprintf(CTL, " Y FLOAT EXTERNAL)\n");
}
else if (sType%10 == 3) { /* line/arc objects here */
fprintf(CTL, " SDO_ELEM_INFO VARRAY TERMINATED BY '|/'\n");
fprintf(CTL, " (X FLOAT EXTERNAL),\n");
fprintf(CTL, " SDO_ORDINATES VARRAY TERMINATED BY '|/'\n");
fprintf(CTL, " (X FLOAT EXTERNAL)\n");
}
fprintf(CTL, " )\n");
fprintf(CTL, ")\n");
fprintf(SQL, " %s \tMDSYS.SDO_GEOMETRY);\n\n", geom_col);
fprintf(SQL, "DELETE FROM USER_SDO_GEOM_METADATA\n");
fprintf(SQL, " WHERE TABLE_NAME = '%s' AND COLUMN_NAME = '%s' ;\n\n", table, geom_col);
fprintf(SQL, "INSERT INTO USER_SDO_GEOM_METADATA (TABLE_NAME, COLUMN_NAME, DIMINFO, SRID)\n");
fprintf(SQL, " VALUES ('%s', '%s',\n", table, geom_col);
fprintf(SQL, " MDSYS.SDO_DIM_ARRAY\n");
fprintf(SQL, " (MDSYS.SDO_DIM_ELEMENT('X', %.9f, %.9f, %.9f),\n", xmin, xmax, tolerance);
fprintf(SQL, " MDSYS.SDO_DIM_ELEMENT('Y', %.9f, %.9f, %.9f)\n", ymin, ymax, tolerance);
fprintf(SQL, " ),\n");
fprintf(SQL, " %s);\n", srid);
fprintf(SQL, "COMMIT;\n");
for (i=0; i<nEnt; i++) {
rec = i;
fprintf(DAT, " ");
for (j=0; j<DBFGetFieldCount(dIN); j++) {
fType = DBFGetFieldInfo(dIN, j, NULL, &fw, NULL);
switch (fType) {
case FTString:
if (strlen(DBFReadStringAttribute( dIN, rec, j)) == 0)
fprintf(DAT, "%*s", fw, DBFReadStringAttribute( dIN, rec, j));
else
fprintf(DAT, "%s", DBFReadStringAttribute( dIN, rec, j));
break;
case FTInteger:
fprintf(DAT, "%d", DBFReadIntegerAttribute(dIN, rec, j));
break;
case FTDouble:
fprintf(DAT, "%.9f", DBFReadDoubleAttribute( dIN, rec, j));
break;
}
fprintf(DAT, "|");
}
/* write the shape data here */
sobj = SHPReadObject(sIN, rec);
if (sType%10 == 1) {
if (sobj->nSHPType < 1 || sobj->nVertices < 1)
fprintf(DAT, " 2001|%s|%.9f|%.9f|", srid, 0.0, 0.0);
else
fprintf(DAT, " 2001|%s|%.9f|%.9f|", srid, sobj->padfX[0], sobj->padfY[0]);
} else if (sType%10 == 3) {
if (!(sobj->nSHPType < 1 || sobj->nVertices < 1)) {
fprintf(DAT, "\n#2002|%s|\n", srid);
fprintf(DAT, "#1|2|1|/");
for (j=0; j<sobj->nVertices; j++) {
if (j%2 == 0) fprintf(DAT, "\n#");
fprintf(DAT, "%.*f|%.*f|", percision, sobj->padfX[j],
percision, sobj->padfY[j]);
}
fprintf(DAT, "/");
}
}
SHPDestroyObject(sobj);
fprintf(DAT, "\n");
}
free(table);
DBFClose(dIN);
SHPClose(sIN);
fclose(SQL);
fclose(CTL);
fclose(DAT);
}
| 31.80137 | 96 | 0.504343 | [
"geometry",
"object",
"shape",
"model"
] |
c46450c6d38f92760a167e01f8da2e51730845e5 | 2,799 | c | C | platforms/portable/vec_math/vec_sqr_c32.c | vnerozin/cimlib | c8f44c30dcb240e183dedd2e26b0aff59801ee63 | [
"MIT"
] | 3 | 2017-03-17T11:54:27.000Z | 2021-07-11T11:59:38.000Z | platforms/portable/vec_math/vec_sqr_c32.c | vnerozin/cimlib | c8f44c30dcb240e183dedd2e26b0aff59801ee63 | [
"MIT"
] | null | null | null | platforms/portable/vec_math/vec_sqr_c32.c | vnerozin/cimlib | c8f44c30dcb240e183dedd2e26b0aff59801ee63 | [
"MIT"
] | null | null | null | /*******************************************************************************
* Copyright (c) 2017 Vasiliy Nerozin
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MIT license. See LICENSE.md for details.
******************************************************************************/
/* -----------------------------------------------------------------------------
* Includes
* ---------------------------------------------------------------------------*/
#include "cimlib.h" /* Library header */
/* -----------------------------------------------------------------------------
* Exported functions
* ---------------------------------------------------------------------------*/
/*******************************************************************************
* This function calculates square of each element of vector, 32 bit complex.
*
* @param[out] pY Pointer to output vector, 32 bit unsigned.
* @param[in] len Vector length.
* @param[in] radix Radix.
* @param[in] pX Pointer to input vector, 32 bit complex.
******************************************************************************/
void vec_sqr_c32(uint32_t *pY, int len, int radix, const cint32_t *pX)
{
int n;
uint64_t tmp;
for (n = 0; n < len; n++) {
tmp = (uint64_t)((int64_t)pX[n].re * pX[n].re);
tmp += (uint64_t)((int64_t)pX[n].im * pX[n].im);
pY[n] = (uint32_t)(tmp >> radix);
}
}
#if (CIMLIB_BUILD_TEST == 1)
/* Simplify macroses for fixed radix */
#define RADIX (23)
#define CONST(X) CIMLIB_CONST_U32(X, RADIX)
#define CONST_CPLX(RE, IM) CIMLIB_CONST_C32(RE, IM, RADIX)
/*******************************************************************************
* This function tests 'vec_sqr_c32' function. Returns 'true' if validation
* is successfully done, 'false' - otherwise.
******************************************************************************/
bool test_vec_sqr_c32(void)
{
uint32_t y[4];
static cint32_t x[4] = {
CONST_CPLX( 9.9996948242E-01, 9.9996948242E-01),
CONST_CPLX( 1.2496948242E-01, -1.2496948242E-01),
CONST_CPLX( 9.9996948242E-01, -1.0000000000E+00),
CONST_CPLX( 3.7658691406E-02, -1.3186645508E-01)
};
static uint32_t res[4] = {
CONST( 1.9998779297E+00),
CONST( 3.1234741211E-02),
CONST( 1.9999389648E+00),
CONST( 1.8806934357E-02)
};
bool flOk = true;
/* Call 'vec_sqr_c32' function */
vec_sqr_c32(y, 4, RADIX, x);
/* Check the correctness of the result */
TEST_LIBS_CHECK_RES_REAL(y, res, 4, flOk);
return flOk;
}
#endif /* (CIMLIB_BUILD_TEST == 1) */
| 35.884615 | 82 | 0.430511 | [
"vector"
] |
c46b40efdfbf670fdd78a902049cf0e0efdd7795 | 2,063 | h | C | Source/SoundplaneOSCOutput.h | afofo/soundplane | 2f41fe74b5c68047af98ea6bced5ee32f8de7f54 | [
"MIT"
] | null | null | null | Source/SoundplaneOSCOutput.h | afofo/soundplane | 2f41fe74b5c68047af98ea6bced5ee32f8de7f54 | [
"MIT"
] | null | null | null | Source/SoundplaneOSCOutput.h | afofo/soundplane | 2f41fe74b5c68047af98ea6bced5ee32f8de7f54 | [
"MIT"
] | null | null | null |
// Part of the Soundplane client software by Madrona Labs.
// Copyright (c) 2013 Madrona Labs LLC. http://www.madronalabs.com
// Distributed under the MIT license: http://madrona-labs.mit-license.org/
#ifndef __SOUNDPLANE_OSC_OUTPUT_H_
#define __SOUNDPLANE_OSC_OUTPUT_H_
#include <vector>
#include <list>
#include <tr1/memory>
#include "MLDebug.h"
#include "MLTime.h"
#include "SoundplaneDataListener.h"
#include "SoundplaneModelA.h"
#include "TouchTracker.h"
#include "JuceHeader.h"
#include "OscOutboundPacketStream.h"
#include "UdpSocket.h"
extern const char* kDefaultHostnameString;
const int kDefaultUDPPort = 3123;
const int kDefaultUDPReceivePort = 3124;
const int kUDPOutputBufferSize = 4096;
class OSCVoice
{
public:
OSCVoice();
~OSCVoice();
float startX;
float startY;
float x;
float y;
float z;
float z1;
float note;
VoiceState mState;
};
class SoundplaneOSCOutput :
public SoundplaneDataListener
{
public:
SoundplaneOSCOutput();
~SoundplaneOSCOutput();
void initialize();
void connect(const char* name, int port);
int getKymaMode();
void setKymaMode(bool m);
// SoundplaneDataListener
void processSoundplaneMessage(const SoundplaneDataMessage* msg);
void modelStateChanged();
void setDataFreq(float f) { mDataFreq = f; }
void setActive(bool v);
void setMaxTouches(int t) { mMaxTouches = clamp(t, 0, kSoundplaneMaxTouches); }
void setSerialNumber(int s) { mSerialNumber = s; }
void notify(int connected);
void doInfrequentTasks();
private:
int mMaxTouches;
OSCVoice mOSCVoices[kSoundplaneMaxTouches];
SoundplaneDataMessage mMessagesByZone[kSoundplaneAMaxZones];
float mDataFreq;
UInt64 mCurrFrameStartTime;
UInt64 mLastFrameStartTime;
bool mTimeToSendNewFrame;
UdpTransmitSocket* mpUDPSocket;
char* mpOSCBuf;
osc::int32 mFrameId;
int mSerialNumber;
UInt64 lastInfrequentTaskTime;
bool mKymaMode;
bool mGotNoteChangesThisFrame;
bool mGotMatrixThisFrame;
SoundplaneDataMessage mMatrixMessage;
};
#endif // __SOUNDPLANE_OSC_OUTPUT_H_
| 21.715789 | 80 | 0.755696 | [
"vector"
] |
c47c31698adb84ddb520b3d3f6497ff7c4af1ab6 | 2,780 | h | C | ios/chrome/browser/ui/main/browser_view_wrangler.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ios/chrome/browser/ui/main/browser_view_wrangler.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ios/chrome/browser/ui/main/browser_view_wrangler.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef IOS_CHROME_BROWSER_UI_MAIN_BROWSER_VIEW_WRANGLER_H_
#define IOS_CHROME_BROWSER_UI_MAIN_BROWSER_VIEW_WRANGLER_H_
#import <UIKit/UIKit.h>
#include "ios/chrome/app/application_mode.h"
#import "ios/chrome/browser/ui/main/browser_interface_provider.h"
@protocol ApplicationCommands;
@protocol BrowsingDataCommands;
class ChromeBrowserState;
namespace {
// Preference key used to store which profile is current.
NSString* kIncognitoCurrentKey = @"IncognitoActive";
} // namespace
// Wrangler (a class in need of further refactoring) for handling the creation
// and ownership of BrowserViewController instances and their associated
// TabModels, and a few related methods.
@interface BrowserViewWrangler : NSObject <BrowserInterfaceProvider>
// Initialize a new instance of this class using |browserState| as the primary
// browser state for the tab models and BVCs, and setting
// |WebStateListObserving|, if not nil, as the webStateListObsever for any
// WebStateLists that are created. |applicationCommandEndpoint| is the object
// that methods in the ApplicationCommands protocol should be dispatched to by
// any BVCs that are created. |storageSwitcher| is used to manage changing any
// storage associated with the interfaces when the current interface changes;
// this is handled in the implementation of -setCurrentInterface:.
- (instancetype)initWithBrowserState:(ChromeBrowserState*)browserState
applicationCommandEndpoint:
(id<ApplicationCommands>)applicationCommandEndpoint
browsingDataCommandEndpoint:
(id<BrowsingDataCommands>)browsingDataCommandEndpoint
NS_DESIGNATED_INITIALIZER;
- (instancetype)init NS_UNAVAILABLE;
// Window ID. Only used in multiwindow. Temporary solution for session
// restoration in multiwindow.
// TODO(crbug.com/1069762): remove this.
@property(nonatomic, assign) NSUInteger windowID;
// Creates the main Browser used by the receiver, using the browser state
// and tab model observer it was configured with. The main interface is then
// created; until this method is called, the main and incognito interfaces will
// be nil. This should be done before the main interface is accessed, usually
// immediately after initialization.
- (void)createMainBrowser;
// Destroy and rebuild the incognito Browser.
- (void)destroyAndRebuildIncognitoBrowser;
// Called before the instance is deallocated.
- (void)shutdown;
// Switch all global states for the given mode (normal or incognito).
- (void)switchGlobalStateToMode:(ApplicationMode)mode;
@end
#endif // IOS_CHROME_BROWSER_UI_MAIN_BROWSER_VIEW_WRANGLER_H_
| 39.714286 | 79 | 0.792806 | [
"object",
"model"
] |
c47c5b64b10d2c574fcab3820064ed2f9919acd7 | 3,927 | h | C | StRoot/StDbLib/StDbXmlReader.h | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | 2 | 2018-12-24T19:37:00.000Z | 2022-02-28T06:57:20.000Z | StRoot/StDbLib/StDbXmlReader.h | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | StRoot/StDbLib/StDbXmlReader.h | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | /***************************************************************************
*
* $Id: StDbXmlReader.h,v 1.10 2016/05/25 20:17:51 dmitry Exp $
*
* Author: R. Jeff Porter
***************************************************************************
*
* Description: implement typeAcceptor for READING XML files of DB-tables
*
***************************************************************************
*
* $Log: StDbXmlReader.h,v $
* Revision 1.10 2016/05/25 20:17:51 dmitry
* coverity - uninit ctor
*
* Revision 1.9 2004/01/15 00:02:25 fisyak
* Replace ostringstream => StString, add option for alpha
*
* Revision 1.8 2003/09/16 22:44:18 porter
* got rid of all ostrstream objects; replaced with StString+string.
* modified rules.make and added file stdb_streams.h for standalone compilation
*
* Revision 1.7 2003/09/02 17:57:50 perev
* gcc 3.2 updates + WarnOff
*
* Revision 1.6 2001/10/24 04:05:20 porter
* added long long type to I/O and got rid of obsolete dataIndex table
*
* Revision 1.5 2001/02/09 23:06:25 porter
* replaced ostrstream into a buffer with ostrstream creating the
* buffer. The former somehow clashed on Solaris with CC5 iostream (current .dev)
*
* Revision 1.4 2000/01/10 20:37:55 porter
* expanded functionality based on planned additions or feedback from Online work.
* update includes:
* 1. basis for real transaction model with roll-back
* 2. limited SQL access via the manager for run-log & tagDb
* 3. balance obtained between enumerated & string access to databases
* 4. 3-levels of diagnostic output: Quiet, Normal, Verbose
* 5. restructured Node model for better XML support
*
* Revision 1.3 1999/12/03 17:03:24 porter
* added multi-row support for the Xml reader & writer
*
* Revision 1.2 1999/09/30 02:06:12 porter
* add StDbTime to better handle timestamps, modify SQL content (mysqlAccessor)
* allow multiple rows (StDbTable), & Added the comment sections at top of
* each header and src file
*
**************************************************************************/
#ifndef STDBXmlReader_HH
#define STDBXmlReader_HH
#include <stdlib.h>
#include <string.h>
#include "typeAcceptor.hh"
#include "stdb_streams.h"
class dbTable;
class elem;
class accessor;
class StDbXmlReader : public typeAcceptor {
protected:
char* loca[20024];//!
dbTable* tab = 0;//!
int maxlines = 0;
void buildDbTable();
void buildStruct();
void fillElements(accessor* a);
elem* findElement(char* name);
public:
StDbXmlReader();
// StDbXmlReader(ofstream& ofs){ os=&ofs;};
virtual ~StDbXmlReader();
void readTable(ifstream &is);
virtual void pass(char* name, short& i, int& len) ;
virtual void pass(char* name, int& i, int& len);
virtual void pass(char* name, long& i, int& len);
virtual void pass(char* name, unsigned short& i, int& len) ;
virtual void pass(char* name, unsigned int& i, int& len) ;
virtual void pass(char* name, unsigned long& i, int& len) ;
virtual void pass(char* name, long long& i, int& len) ;
virtual void pass(char* name, float& i, int& len);
virtual void pass(char* name, double& i, int& len);
virtual void pass(char* name, char*& i, int& len);
virtual void pass(char* name, unsigned char& i, int& len) ;
virtual void pass(char* name, unsigned char*& i, int& len) ;
virtual void pass(char* name, short*& i, int& len) ;
virtual void pass(char* name, int*& i, int& len);
virtual void pass(char* name, long*& i, int& len);
virtual void pass(char* name, unsigned short*& i, int& len) ;
virtual void pass(char* name, unsigned int*& i, int& len) ;
virtual void pass(char* name, unsigned long*& i, int& len) ;
virtual void pass(char* name, long long*& i, int& len) ;
virtual void pass(char* name, float*& i, int& len);
virtual void pass(char* name, double*& i, int& len);
//ClassDef(StDbXmlReader,1)
};
#endif
| 32.725 | 82 | 0.633308 | [
"model"
] |
c47e39d1f32541820326e31379ccd275ff6670f7 | 4,583 | h | C | interface/src/scripting/TestScriptingInterface.h | amantley/blendshapes | 3f5820266762f9962d9bb5bd91912272005e4f02 | [
"Apache-2.0"
] | null | null | null | interface/src/scripting/TestScriptingInterface.h | amantley/blendshapes | 3f5820266762f9962d9bb5bd91912272005e4f02 | [
"Apache-2.0"
] | null | null | null | interface/src/scripting/TestScriptingInterface.h | amantley/blendshapes | 3f5820266762f9962d9bb5bd91912272005e4f02 | [
"Apache-2.0"
] | null | null | null | //
// Created by Bradley Austin Davis on 2016/12/12
// Copyright 2013-2016 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#pragma once
#ifndef hifi_TestScriptingInterface_h
#define hifi_TestScriptingInterface_h
#include <functional>
#include <QtCore/QObject>
class QScriptValue;
class TestScriptingInterface : public QObject {
Q_OBJECT
public:
void setTestResultsLocation(const QString path) { _testResultsLocation = path; }
const QString& getTestResultsLocation() { return _testResultsLocation; };
public slots:
static TestScriptingInterface* getInstance();
/**jsdoc
* Exits the application
* @function Test.quit
*/
void quit();
/**jsdoc
* Waits for all texture transfers to be complete
* @function Test.waitForTextureIdle
*/
void waitForTextureIdle();
/**jsdoc
* Waits for all pending downloads to be complete
* @function Test.waitForDownloadIdle
*/
void waitForDownloadIdle();
/**jsdoc
* Waits for all file parsing operations to be complete
* @function Test.waitForProcessingIdle
*/
void waitForProcessingIdle();
/**jsdoc
* Waits for all pending downloads, parsing and texture transfers to be complete
* @function Test.waitIdle
*/
void waitIdle();
/**jsdoc
* Waits for establishment of connection to server
* @function Test.waitForConnection
* @param {int} maxWaitMs [default=10000] - Number of milliseconds to wait
*/
bool waitForConnection(qint64 maxWaitMs = 10000);
/**jsdoc
* Waits a specific number of milliseconds
* @function Test.wait
* @param {int} milliseconds - Number of milliseconds to wait
*/
void wait(int milliseconds);
/**jsdoc
* Waits for all pending downloads, parsing and texture transfers to be complete
* @function Test.loadTestScene
* @param {string} sceneFile - URL of scene to load
*/
bool loadTestScene(QString sceneFile);
/**jsdoc
* Clears all caches
* @function Test.clear
*/
void clear();
/**jsdoc
* Start recording Chrome compatible tracing events
* logRules can be used to specify a set of logging category rules to limit what gets captured
* @function Test.startTracing
* @param {string} logrules [defaultValue=""] - See implementation for explanation
*/
bool startTracing(QString logrules = "");
/**jsdoc
* Stop recording Chrome compatible tracing events and serialize recorded events to a file
* Using a filename with a .gz extension will automatically compress the output file
* @function Test.stopTracing
* @param {string} filename - Name of file to save to
* @returns {bool} True if successful.
*/
bool stopTracing(QString filename);
/**jsdoc
* Starts a specific trace event
* @function Test.startTraceEvent
* @param {string} name - Name of event
*/
void startTraceEvent(QString name);
/**jsdoc
* Stop a specific name event
* Using a filename with a .gz extension will automatically compress the output file
* @function Test.endTraceEvent
* @param {string} filename - Name of event
*/
void endTraceEvent(QString name);
/**jsdoc
* Write detailed timing stats of next physics stepSimulation() to filename
* @function Test.savePhysicsSimulationStats
* @param {string} filename - Name of file to save to
*/
void savePhysicsSimulationStats(QString filename);
/**jsdoc
* Profiles a specific function
* @function Test.savePhysicsSimulationStats
* @param {string} name - Name used to reference the function
* @param {function} function - Function to profile
*/
Q_INVOKABLE void profileRange(const QString& name, QScriptValue function);
/**jsdoc
* Clear all caches (menu command Reload Content)
* @function Test.clearCaches
*/
void clearCaches();
/**jsdoc
* Save a JSON object to a file in the test results location
* @function Test.saveObject
* @param {string} name - Name of the object
* @param {string} filename - Name of file to save to
*/
void saveObject(QVariant v, const QString& filename);
/**jsdoc
* Maximizes the window
* @function Test.showMaximized
*/
void showMaximized();
private:
bool waitForCondition(qint64 maxWaitMs, std::function<bool()> condition);
QString _testResultsLocation;
};
#endif // hifi_TestScriptingInterface_h
| 29.006329 | 97 | 0.687323 | [
"object"
] |
c4809e1627c0c15a713e8ad8e088a9b94bfc7150 | 104,283 | c | C | resources/Wireshark/WiresharkDissectorFoo/epan/dissectors/packet-zbee-nwk-gp.c | joshis1/C_Programming | 4a8003321251448a167bfca0b595c5eeab88608d | [
"MIT"
] | 2 | 2020-09-11T05:51:42.000Z | 2020-12-31T11:42:02.000Z | resources/Wireshark/WiresharkDissectorFoo/epan/dissectors/packet-zbee-nwk-gp.c | joshis1/C_Programming | 4a8003321251448a167bfca0b595c5eeab88608d | [
"MIT"
] | null | null | null | resources/Wireshark/WiresharkDissectorFoo/epan/dissectors/packet-zbee-nwk-gp.c | joshis1/C_Programming | 4a8003321251448a167bfca0b595c5eeab88608d | [
"MIT"
] | null | null | null | /* packet-zbee-nwk-gp.c
* Dissector routines for the ZigBee Green Power profile (GP)
* Copyright 2013 DSR Corporation, http://dsr-wireless.com/
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <gerald@wireshark.org>
* Copyright 1998 Gerald Combs
*
* Used Owen Kirby's packet-zbee-aps module as a template. Based
* on ZigBee Cluster Library Specification document 075123r02ZB
*
* SPDX-License-Identifier: GPL-2.0-or-later
*/
/* Include files. */
#include "config.h"
#include <epan/packet.h>
#include <epan/exceptions.h>
#include <epan/expert.h>
#include <epan/prefs.h>
#include <epan/uat.h>
#include <wsutil/bits_ctz.h>
#include <wsutil/pint.h>
#include "packet-zbee.h"
#include "packet-zbee-nwk.h"
#include "packet-zbee-security.h"
#include "packet-zbee-aps.h"
#include "packet-zbee-zcl.h"
void proto_register_zbee_nwk_gp(void);
void proto_reg_handoff_zbee_nwk_gp(void);
/**************************/
/* Defines. */
/**************************/
/* ZigBee NWK GP FCF frame types. */
#define ZBEE_NWK_GP_FCF_DATA 0x00
#define ZBEE_NWK_GP_FCF_MAINTENANCE 0x01
/* ZigBee NWK GP FCF fields. */
#define ZBEE_NWK_GP_FCF_AUTO_COMMISSIONING 0x40
#define ZBEE_NWK_GP_FCF_CONTROL_EXTENSION 0x80
#define ZBEE_NWK_GP_FCF_FRAME_TYPE 0x03
#define ZBEE_NWK_GP_FCF_VERSION 0x3C
/* Extended NWK Frame Control field. */
#define ZBEE_NWK_GP_FCF_EXT_APP_ID 0x07 /* 0 - 2 b. */
#define ZBEE_NWK_GP_FCF_EXT_SECURITY_LEVEL 0x18 /* 3 - 4 b. */
#define ZBEE_NWK_GP_FCF_EXT_SECURITY_KEY 0x20 /* 5 b. */
#define ZBEE_NWK_GP_FCF_EXT_RX_AFTER_TX 0x40 /* 6 b. */
#define ZBEE_NWK_GP_FCF_EXT_DIRECTION 0x80 /* 7 b. */
/* Definitions for application IDs. */
#define ZBEE_NWK_GP_APP_ID_DEFAULT 0x00
#define ZBEE_NWK_GP_APP_ID_LPED 0x01
#define ZBEE_NWK_GP_APP_ID_ZGP 0x02
/* Definitions for GP directions. */
#define ZBEE_NWK_GP_FC_EXT_DIRECTION_DEFAULT 0x00
#define ZBEE_NWK_GP_FC_EXT_DIRECTION_FROM_ZGPD 0x00
#define ZBEE_NWK_GP_FC_EXT_DIRECTION_FROM_ZGPP 0x01
/* Definitions for ZGPD Source IDs. */
#define ZBEE_NWK_GP_ZGPD_SRCID_ALL 0xFFFFFFFF
#define ZBEE_NWK_GP_ZGPD_SRCID_UNKNOWN 0x00000000
/* Security level values. */
#define ZBEE_NWK_GP_SECURITY_LEVEL_NO 0x00
#define ZBEE_NWK_GP_SECURITY_LEVEL_1LSB 0x01
#define ZBEE_NWK_GP_SECURITY_LEVEL_FULL 0x02
#define ZBEE_NWK_GP_SECURITY_LEVEL_FULLENCR 0x03
/* GP Security key types. */
#define ZBEE_NWK_GP_SECURITY_KEY_TYPE_NO_KEY 0x00
#define ZBEE_NWK_GP_SECURITY_KEY_TYPE_ZB_NWK_KEY 0x01
#define ZBEE_NWK_GP_SECURITY_KEY_TYPE_GPD_GROUP_KEY 0x02
#define ZBEE_NWK_GP_SECURITY_KEY_TYPE_NWK_KEY_DERIVED_GPD_KEY_GROUP_KEY 0x03
#define ZBEE_NWK_GP_SECURITY_KEY_TYPE_PRECONFIGURED_INDIVIDUAL_GPD_KEY 0x04
#define ZBEE_NWK_GP_SECURITY_KEY_TYPE_DERIVED_INDIVIDUAL_GPD_KEY 0x07
typedef struct {
/* FCF Data. */
guint8 frame_type;
gboolean nwk_frame_control_extension;
/* Ext FCF Data. */
guint8 application_id;
guint8 security_level;
guint8 direction;
/* Src ID. */
guint32 source_id;
/* GPD Endpoint */
guint8 endpoint;
/* Security Frame Counter. */
guint32 security_frame_counter;
/* MIC. */
guint8 mic_size;
guint32 mic;
/* Application Payload. */
guint8 payload_len;
} zbee_nwk_green_power_packet;
/* Definitions for GP Commissioning command opt field (bitmask). */
#define ZBEE_NWK_GP_CMD_COMMISSIONING_OPT_MAC_SEQ 0x01
#define ZBEE_NWK_GP_CMD_COMMISSIONING_OPT_RX_ON_CAP 0x02
#define ZBEE_NWK_GP_CMD_COMMISSIONING_OPT_APPLICATION_INFO 0x04
#define ZBEE_NWK_GP_CMD_COMMISSIONING_OPT_PAN_ID_REQ 0x10
#define ZBEE_NWK_GP_CMD_COMMISSIONING_OPT_GP_SEC_KEY_REQ 0x20
#define ZBEE_NWK_GP_CMD_COMMISSIONING_OPT_FIXED_LOCATION 0x40
#define ZBEE_NWK_GP_CMD_COMMISSIONING_OPT_EXT_OPTIONS 0x80
/* Definitions for GP Commissioning command ext_opt field (bitmask). */
#define ZBEE_NWK_GP_CMD_COMMISSIONING_EXT_OPT_SEC_LEVEL_CAP 0x03
#define ZBEE_NWK_GP_CMD_COMMISSIONING_EXT_OPT_KEY_TYPE 0x1C
#define ZBEE_NWK_GP_CMD_COMMISSIONING_EXT_OPT_GPD_KEY_PRESENT 0x20
#define ZBEE_NWK_GP_CMD_COMMISSIONING_EXT_OPT_GPD_KEY_ENCR 0x40
#define ZBEE_NWK_GP_CMD_COMMISSIONING_EXT_OPT_OUT_COUNTER 0x80
/* Definitions for GP Commissioning command application information field (bitmask). */
#define ZBEE_NWK_GP_CMD_COMMISSIONING_APPLI_INFO_MIP 0x01
#define ZBEE_NWK_GP_CMD_COMMISSIONING_APPLI_INFO_MMIP 0x02
#define ZBEE_NWK_GP_CMD_COMMISSIONING_APPLI_INFO_GCLP 0x04
#define ZBEE_NWK_GP_CMD_COMMISSIONING_APPLI_INFO_CRP 0x08
/* Definitions for GP Commissioning command Number of server ClusterIDs (bitmask) */
#define ZBEE_NWK_GP_CMD_COMMISSIONING_CLID_LIST_LEN_SRV 0x0F
#define ZBEE_NWK_GP_CMD_COMMISSIONING_CLID_LIST_LEN_CLI 0xF0
/* Definitions for GP Decommissioning command opt field (bitmask). */
#define ZBEE_NWK_GP_CMD_COMMISSIONING_REP_OPT_PAN_ID_PRESENT 0x01
#define ZBEE_NWK_GP_CMD_COMMISSIONING_REP_OPT_SEC_KEY_PRESENT 0x02
#define ZBEE_NWK_GP_CMD_COMMISSIONING_REP_OPT_KEY_ENCR 0x04
#define ZBEE_NWK_GP_CMD_COMMISSIONING_REP_OPT_SEC_LEVEL 0x18
#define ZBEE_NWK_GP_CMD_COMMISSIONING_REP_OPT_KEY_TYPE 0xE0
/* Definition for GP read attributes command opt field (bitmask). */
#define ZBEE_NWK_GP_CMD_READ_ATTRIBUTE_OPT_MULTI_RECORD 0x01
#define ZBEE_NWK_GP_CMD_READ_ATTRIBUTE_OPT_MAN_FIELD_PRESENT 0x02
/* Definitions for GP Channel Request command. */
#define ZBEE_NWK_GP_CMD_CHANNEL_REQUEST_1ST 0x0F
#define ZBEE_NWK_GP_CMD_CHANNEL_REQUEST_2ND 0xF0
/* GP Channel Configuration command. */
#define ZBEE_NWK_GP_CMD_CHANNEL_CONFIGURATION_OPERATION_CH 0x0F
/* GP GENERIC IDS. */
#define GPD_DEVICE_ID_GENERIC_GP_SIMPLE_GENERIC_1STATE_SWITCH 0x00
#define GPD_DEVICE_ID_GENERIC_GP_SIMPLE_GENERIC_2STATE_SWITCH 0x01
#define GPD_DEVICE_ID_GENERIC_GP_ON_OFF_SWITCH 0x02
#define GPD_DEVICE_ID_GENERIC_GP_LEVEL_CONTROL_SWITCH 0x03
#define GPD_DEVICE_ID_GENERIC_GP_SIMPLE_SENSOR 0x04
#define GPD_DEVICE_ID_GENERIC_GP_ADVANCED_GENERIC_1STATE_SWITCH 0x05
#define GPD_DEVICE_ID_GENERIC_GP_ADVANCED_GENERIC_2STATE_SWITCH 0x06
/* GP LIGHTING IDS. */
#define GPD_DEVICE_ID_LIGHTING_GP_COLOR_DIMMER_SWITCH 0x10
#define GPD_DEVICE_ID_LIGHTING_GP_LIGHT_SENSOR 0x11
#define GPD_DEVICE_ID_LIGHTING_GP_OCCUPANCY_SENSOR 0x12
/* GP CLOSURES IDS. */
#define GPD_DEVICE_ID_CLOSURES_GP_DOOR_LOCK_CONTROLLER 0x20
/* HVAC IDS. */
#define GPD_DEVICE_ID_HVAC_GP_TEMPERATURE_SENSOR 0x30
#define GPD_DEVICE_ID_HVAC_GP_PRESSURE_SENSOR 0x31
#define GPD_DEVICE_ID_HVAC_GP_FLOW_SENSOR 0x32
#define GPD_DEVICE_ID_HVAC_GP_INDOOR_ENVIRONMENT_SENSOR 0x33
/* Manufacturer specific device. */
#define GPD_DEVICE_ID_MANUFACTURER_SPECIFIC 0xFE
/* GPD manufacturers. */
#define ZBEE_NWK_GP_MANUF_ID_GREENPEAK 0x10D0
/* GPD devices by GreenPeak. */
#define ZBEE_NWK_GP_MANUF_GREENPEAK_IZDS 0x0000
#define ZBEE_NWK_GP_MANUF_GREENPEAK_IZDWS 0x0001
#define ZBEE_NWK_GP_MANUF_GREENPEAK_IZLS 0x0002
#define ZBEE_NWK_GP_MANUF_GREENPEAK_IZRHS 0x0003
/*********************/
/* Global variables. */
/*********************/
/* GP proto handle. */
static int proto_zbee_nwk_gp = -1;
/* GP NWK FC. */
static int hf_zbee_nwk_gp_auto_commissioning = -1;
static int hf_zbee_nwk_gp_fc_ext = -1;
static int hf_zbee_nwk_gp_fcf = -1;
static int hf_zbee_nwk_gp_frame_type = -1;
static int hf_zbee_nwk_gp_proto_version = -1;
/* GP NWK FC extension. */
static int hf_zbee_nwk_gp_fc_ext_field = -1;
static int hf_zbee_nwk_gp_fc_ext_app_id = -1;
static int hf_zbee_nwk_gp_fc_ext_direction = -1;
static int hf_zbee_nwk_gp_fc_ext_rx_after_tx = -1;
static int hf_zbee_nwk_gp_fc_ext_sec_key = -1;
static int hf_zbee_nwk_gp_fc_ext_sec_level = -1;
/* ZGPD Src ID. */
static int hf_zbee_nwk_gp_zgpd_src_id = -1;
/* ZGPD Endpoint */
static int hf_zbee_nwk_gp_zgpd_endpoint = -1;
/* Security frame counter. */
static int hf_zbee_nwk_gp_security_frame_counter = -1;
/* Security MIC. */
static int hf_zbee_nwk_gp_security_mic_2b = -1;
static int hf_zbee_nwk_gp_security_mic_4b = -1;
/* Payload subframe. */
static int hf_zbee_nwk_gp_command_id = -1;
/* Commissioning. */
static int hf_zbee_nwk_gp_cmd_comm_device_id = -1;
static int hf_zbee_nwk_gp_cmd_comm_ext_opt = -1;
static int hf_zbee_nwk_gp_cmd_comm_ext_opt_gpd_key_encr = -1;
static int hf_zbee_nwk_gp_cmd_comm_ext_opt_gpd_key_present = -1;
static int hf_zbee_nwk_gp_cmd_comm_ext_opt_key_type = -1;
static int hf_zbee_nwk_gp_cmd_comm_ext_opt_outgoing_counter = -1;
static int hf_zbee_nwk_gp_cmd_comm_ext_opt_sec_level_cap = -1;
static int hf_zbee_nwk_gp_cmd_comm_security_key = -1;
static int hf_zbee_nwk_gp_cmd_comm_gpd_sec_key_mic = -1;
static int hf_zbee_nwk_gp_cmd_comm_opt_ext_opt = -1;
static int hf_zbee_nwk_gp_cmd_comm_opt = -1;
static int hf_zbee_nwk_gp_cmd_comm_opt_fixed_location = -1;
static int hf_zbee_nwk_gp_cmd_comm_opt_mac_sec_num_cap = -1;
static int hf_zbee_nwk_gp_cmd_comm_opt_appli_info_present = -1;
static int hf_zbee_nwk_gp_cmd_comm_opt_panid_req = -1;
static int hf_zbee_nwk_gp_cmd_comm_opt_rx_on_cap = -1;
static int hf_zbee_nwk_gp_cmd_comm_opt_sec_key_req = -1;
static int hf_zbee_nwk_gp_cmd_comm_outgoing_counter = -1;
static int hf_zbee_nwk_gp_cmd_comm_manufacturer_greenpeak_dev_id = -1;
static int hf_zbee_nwk_gp_cmd_comm_manufacturer_dev_id = -1;
static int hf_zbee_nwk_gp_cmd_comm_manufacturer_id = -1;
static int hf_zbee_nwk_gp_cmd_comm_appli_info = -1;
static int hf_zbee_nwk_gp_cmd_comm_appli_info_crp = -1;
static int hf_zbee_nwk_gp_cmd_comm_appli_info_gclp = -1;
static int hf_zbee_nwk_gp_cmd_comm_appli_info_mip = -1;
static int hf_zbee_nwk_gp_cmd_comm_appli_info_mmip = -1;
static int hf_zbee_nwk_gp_cmd_comm_gpd_cmd_num = -1;
static int hf_zbee_nwk_gp_cmd_comm_gpd_cmd_id_list = -1;
static int hf_zbee_nwk_gp_cmd_comm_length_of_clid_list = -1;
static int hf_zbee_nwk_gp_cmd_comm_length_of_clid_list_server = -1;
static int hf_zbee_nwk_gp_cmd_comm_length_of_clid_list_client = -1;
static int hf_zbee_nwk_cmd_comm_clid_list_server = -1;
static int hf_zbee_nwk_cmd_comm_clid_list_client = -1;
static int hf_zbee_nwk_cmd_comm_cluster_id = -1;
/* Commissioning reply. */
static int hf_zbee_nwk_gp_cmd_comm_rep_opt = -1;
static int hf_zbee_nwk_gp_cmd_comm_rep_opt_key_encr = -1;
static int hf_zbee_nwk_gp_cmd_comm_rep_opt_panid_present = -1;
static int hf_zbee_nwk_gp_cmd_comm_rep_opt_sec_key_present = -1;
static int hf_zbee_nwk_gp_cmd_comm_rep_opt_sec_level = -1;
static int hf_zbee_nwk_gp_cmd_comm_rep_opt_sec_type = -1;
static int hf_zbee_nwk_gp_cmd_comm_rep_pan_id = -1;
static int hf_zbee_nwk_gp_cmd_comm_rep_frame_counter = -1;
/* Read attribute and read attribute response. */
static int hf_zbee_nwk_gp_cmd_read_att_opt_multi_rec = -1;
static int hf_zbee_nwk_gp_cmd_read_att_opt_man_field_present = -1;
static int hf_zbee_nwk_gp_cmd_read_att_opt = -1;
static int hf_zbee_nwk_gp_cmd_read_att_record_len = -1;
/* Common to commands returning data */
static int hf_zbee_nwk_gp_zcl_attr_status = -1;
static int hf_zbee_nwk_gp_zcl_attr_data_type = -1;
static int hf_zbee_nwk_gp_zcl_attr_cluster_id = -1;
/* Common to all manufacturer specific commands */
static int hf_zbee_zcl_gp_cmd_ms_manufacturer_code = -1;
/* Channel request. */
static int hf_zbee_nwk_gp_cmd_channel_request_toggling_behaviour = -1;
static int hf_zbee_nwk_gp_cmd_channel_request_toggling_behaviour_1st = -1;
static int hf_zbee_nwk_gp_cmd_channel_request_toggling_behaviour_2nd = -1;
/* Channel Configuration command. */
static int hf_zbee_nwk_gp_cmd_operational_channel = -1;
static int hf_zbee_nwk_gp_cmd_channel_configuration = -1;
/* Move Color command. */
static int hf_zbee_nwk_gp_cmd_move_color_ratex = -1;
static int hf_zbee_nwk_gp_cmd_move_color_ratey = -1;
/* Move Up/Down command. */
static int hf_zbee_nwk_gp_cmd_move_up_down_rate = -1;
/* Step Color command. */
static int hf_zbee_nwk_gp_cmd_step_color_stepx = -1;
static int hf_zbee_nwk_gp_cmd_step_color_stepy = -1;
static int hf_zbee_nwk_gp_cmd_step_color_transition_time = -1;
/* Step Up/Down command. */
static int hf_zbee_nwk_gp_cmd_step_up_down_step_size = -1;
static int hf_zbee_nwk_gp_cmd_step_up_down_transition_time = -1;
static expert_field ei_zbee_nwk_gp_no_payload = EI_INIT;
static expert_field ei_zbee_nwk_gp_inval_residual_data = EI_INIT;
static expert_field ei_zbee_nwk_gp_com_rep_no_out_cnt = EI_INIT;
/* Proto tree elements. */
static gint ett_zbee_nwk = -1;
static gint ett_zbee_nwk_cmd = -1;
static gint ett_zbee_nwk_cmd_cinfo = -1;
static gint ett_zbee_nwk_cmd_appli_info = -1;
static gint ett_zbee_nwk_cmd_options = -1;
static gint ett_zbee_nwk_fcf = -1;
static gint ett_zbee_nwk_fcf_ext = -1;
static gint ett_zbee_nwk_clu_rec = -1;
static gint ett_zbee_nwk_att_rec = -1;
static gint ett_zbee_nwk_cmd_comm_gpd_cmd_id_list = -1;
static gint ett_zbee_nwk_cmd_comm_length_of_clid_list = -1;
static gint ett_zbee_nwk_cmd_comm_clid_list_server = -1;
static gint ett_zbee_nwk_cmd_comm_clid_list_client = -1;
/* Common. */
static GSList *zbee_gp_keyring = NULL;
static guint num_uat_key_records = 0;
typedef struct {
gchar *string;
guint8 byte_order;
gchar *label;
guint8 key[ZBEE_SEC_CONST_KEYSIZE];
} uat_key_record_t;
static const guint8 empty_key[ZBEE_SEC_CONST_KEYSIZE] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
static uat_key_record_t *gp_uat_key_records = NULL;
static uat_t *zbee_gp_sec_key_table_uat;
/* UAT. */
UAT_CSTRING_CB_DEF(gp_uat_key_records, string, uat_key_record_t)
UAT_VS_DEF(gp_uat_key_records, byte_order, uat_key_record_t, guint8, 0, "Normal")
UAT_CSTRING_CB_DEF(gp_uat_key_records, label, uat_key_record_t)
/****************/
/* Field names. */
/****************/
/* Byte order. */
static const value_string byte_order_vals[] = {
{ 0, "Normal"},
{ 1, "Reverse"},
{ 0, NULL }
};
/* Application ID names. */
static const value_string zbee_nwk_gp_app_id_names[] = {
{ ZBEE_NWK_GP_APP_ID_LPED, "LPED" },
{ ZBEE_NWK_GP_APP_ID_ZGP, "ZGP" },
{ 0, NULL }
};
/* Green Power commands. */
/* Abbreviations:
* GPDF commands sent:
* From GPD w/o payload: "F "
* From GPD w payload: "FP"
* To GPD: "T "
*/
#define zbee_nwk_gp_cmd_names_VALUE_STRING_LIST(XXX) \
XXX( /*F */ ZB_GP_CMD_ID_IDENTIFY , 0x00, "Identify" ) \
XXX( /*F */ ZB_GP_CMD_ID_SCENE0 , 0x10, "Scene 0" ) \
XXX( /*F */ ZB_GP_CMD_ID_SCENE1 , 0x11, "Scene 1" ) \
XXX( /*F */ ZB_GP_CMD_ID_SCENE2 , 0x12, "Scene 2" ) \
XXX( /*F */ ZB_GP_CMD_ID_SCENE3 , 0x13, "Scene 3" ) \
XXX( /*F */ ZB_GP_CMD_ID_SCENE4 , 0x14, "Scene 4" ) \
XXX( /*F */ ZB_GP_CMD_ID_SCENE5 , 0x15, "Scene 5" ) \
XXX( /*F */ ZB_GP_CMD_ID_SCENE6 , 0x16, "Scene 6" ) \
XXX( /*F */ ZB_GP_CMD_ID_SCENE7 , 0x17, "Scene 7" ) \
XXX( /*F */ ZB_GP_CMD_ID_SCENE8 , 0x18, "Scene 8" ) \
XXX( /*F */ ZB_GP_CMD_ID_SCENE9 , 0x19, "Scene 9" ) \
XXX( /*F */ ZB_GP_CMD_ID_SCENE10 , 0x1A, "Scene 10" ) \
XXX( /*F */ ZB_GP_CMD_ID_SCENE11 , 0x1B, "Scene 11" ) \
XXX( /*F */ ZB_GP_CMD_ID_SCENE12 , 0x1C, "Scene 12" ) \
XXX( /*F */ ZB_GP_CMD_ID_SCENE13 , 0x1D, "Scene 13" ) \
XXX( /*F */ ZB_GP_CMD_ID_SCENE14 , 0x1E, "Scene 14" ) \
XXX( /*F */ ZB_GP_CMD_ID_SCENE15 , 0x1F, "Scene 15" ) \
XXX( /*F */ ZB_GP_CMD_ID_OFF , 0x20, "Off" ) \
XXX( /*F */ ZB_GP_CMD_ID_ON , 0x21, "On" ) \
XXX( /*F */ ZB_GP_CMD_ID_TOGGLE , 0x22, "Toggle" ) \
XXX( /*F */ ZB_GP_CMD_ID_RELEASE , 0x23, "Release" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_MOVE_UP , 0x30, "Move Up" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_MOVE_DOWN , 0x31, "Move Down" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_STEP_UP , 0x32, "Step Up" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_STEP_DOWN , 0x33, "Step Down" ) \
XXX( /*F */ ZB_GP_CMD_ID_LEVEL_CONTROL_STOP , 0x34, "Level Control/Stop" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_MOVE_UP_WITH_ON_OFF , 0x35, "Move Up (with On/Off)" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_MOVE_DOWN_WITH_ON_OFF , 0x36, "Move Down (with On/Off)" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_STEP_UP_WITH_ON_OFF , 0x37, "Step Up (with On/Off)" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_STEP_DOWN_WITH_ON_OFF , 0x38, "Step Down (with On/Off)" ) \
XXX( /*F */ ZB_GP_CMD_ID_MOVE_HUE_STOP , 0x40, "Move Hue Stop" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_MOVE_HUE_UP , 0x41, "Move Hue Up" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_MOVE_HUE_DOWN , 0x42, "Move Hue Down" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_STEP_HUE_UP , 0x43, "Step Hue Up" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_STEP_HUW_DOWN , 0x44, "Step Hue Down" ) \
XXX( /*F */ ZB_GP_CMD_ID_MOVE_SATURATION_STOP , 0x45, "Move Saturation Stop" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_MOVE_SATURATION_UP , 0x46, "Move Saturation Up" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_MOVE_SATURATION_DOWN , 0x47, "Move Saturation Down" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_STEP_SATURATION_UP , 0x48, "Step Saturation Up" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_STEP_SATURATION_DOWN , 0x49, "Step Saturation Down" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_MOVE_COLOR , 0x4A, "Move Color" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_STEP_COLOR , 0x4B, "Step Color" ) \
XXX( /*F */ ZB_GP_CMD_ID_LOCK_DOOR , 0x50, "Lock Door" ) \
XXX( /*F */ ZB_GP_CMD_ID_UNLOCK_DOOR , 0x51, "Unlock Door" ) \
XXX( /*F */ ZB_GP_CMD_ID_PRESS11 , 0x60, "Press 1 of 1" ) \
XXX( /*F */ ZB_GP_CMD_ID_RELEASE11 , 0x61, "Release 1 of 1" ) \
XXX( /*F */ ZB_GP_CMD_ID_PRESS12 , 0x62, "Press 1 of 2" ) \
XXX( /*F */ ZB_GP_CMD_ID_RELEASE12 , 0x63, "Release 1 of 2" ) \
XXX( /*F */ ZB_GP_CMD_ID_PRESS22 , 0x64, "Press 2 of 2" ) \
XXX( /*F */ ZB_GP_CMD_ID_RELEASE22 , 0x65, "Release 2 of 2" ) \
XXX( /*F */ ZB_GP_CMD_ID_SHORT_PRESS11 , 0x66, "Short press 1 of 1" ) \
XXX( /*F */ ZB_GP_CMD_ID_SHORT_PRESS12 , 0x67, "Short press 1 of 2" ) \
XXX( /*F */ ZB_GP_CMD_ID_SHORT_PRESS22 , 0x68, "Short press 2 of 2" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_ATTRIBUTE_REPORTING , 0xA0, "Attribute reporting" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_MANUFACTURE_SPECIFIC_ATTR_REPORTING , 0xA1, "Manufacturer-specific attribute reporting" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_MULTI_CLUSTER_REPORTING , 0xA2, "Multi-cluster reporting" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_MANUFACTURER_SPECIFIC_MCLUSTER_REPORTING , 0xA3, "Manufacturer-specific multi-cluster reporting" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_REQUEST_ATTRIBUTES , 0xA4, "Request Attributes" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_READ_ATTRIBUTES_RESPONSE , 0xA5, "Read Attributes Response" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_ANY_SENSOR_COMMAND_A0_A3 , 0xAF, "Any GPD sensor command (0xA0 - 0xA3)" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_COMMISSIONING , 0xE0, "Commissioning" ) \
XXX( /*F */ ZB_GP_CMD_ID_DECOMMISSIONING , 0xE1, "Decommissioning" ) \
XXX( /*F */ ZB_GP_CMD_ID_SUCCESS , 0xE2, "Success" ) \
XXX( /*FP*/ ZB_GP_CMD_ID_CHANNEL_REQUEST , 0xE3, "Channel Request" ) \
XXX( /*T */ ZB_GP_CMD_ID_COMMISSIONING_REPLY , 0xF0, "Commissioning Reply" ) \
XXX( /*T */ ZB_GP_CMD_ID_WRITE_ATTRIBUTES , 0xF1, "Write Attributes" ) \
XXX( /*T */ ZB_GP_CMD_ID_READ_ATTRIBUTES , 0xF2, "Read Attributes" ) \
XXX( /*T */ ZB_GP_CMD_ID_CHANNEL_CONFIGURATION , 0xF3, "Channel Configuration" )
VALUE_STRING_ENUM(zbee_nwk_gp_cmd_names);
VALUE_STRING_ARRAY(zbee_nwk_gp_cmd_names);
value_string_ext zbee_nwk_gp_cmd_names_ext = VALUE_STRING_EXT_INIT(zbee_nwk_gp_cmd_names);
/* Green Power devices. */
const value_string zbee_nwk_gp_device_ids_names[] = {
/* GP GENERIC */
{ GPD_DEVICE_ID_GENERIC_GP_SIMPLE_GENERIC_1STATE_SWITCH, "Generic: GP Simple Generic 1-state Switch" },
{ GPD_DEVICE_ID_GENERIC_GP_SIMPLE_GENERIC_2STATE_SWITCH, "Generic: GP Simple Generic 2-state Switch" },
{ GPD_DEVICE_ID_GENERIC_GP_ON_OFF_SWITCH, "Generic: GP On/Off Switch" },
{ GPD_DEVICE_ID_GENERIC_GP_LEVEL_CONTROL_SWITCH, "Generic: GP Level Control Switch" },
{ GPD_DEVICE_ID_GENERIC_GP_SIMPLE_SENSOR, "Generic: GP Simple Sensor" },
{ GPD_DEVICE_ID_GENERIC_GP_ADVANCED_GENERIC_1STATE_SWITCH, "Generic: GP Advanced Generic 1-state Switch" },
{ GPD_DEVICE_ID_GENERIC_GP_ADVANCED_GENERIC_2STATE_SWITCH, "Generic: GP Advanced Generic 2-state Switch" },
/* GP LIGHTING */
{ GPD_DEVICE_ID_LIGHTING_GP_COLOR_DIMMER_SWITCH, "Lighting: GP Color Dimmer Switch" },
{ GPD_DEVICE_ID_LIGHTING_GP_LIGHT_SENSOR, "Lighting: GP Light Sensor" },
{ GPD_DEVICE_ID_LIGHTING_GP_OCCUPANCY_SENSOR, "Lighting: GP Occupancy Sensor" },
/* GP CLOSURES */
{ GPD_DEVICE_ID_CLOSURES_GP_DOOR_LOCK_CONTROLLER, "Closures: GP Door Lock Controller" },
/* HVAC */
{ GPD_DEVICE_ID_HVAC_GP_TEMPERATURE_SENSOR, "HVAC: GP Temperature Sensor" },
{ GPD_DEVICE_ID_HVAC_GP_PRESSURE_SENSOR, "HVAC: GP Pressure Sensor" },
{ GPD_DEVICE_ID_HVAC_GP_FLOW_SENSOR, "HVAC: GP Flow Sensor" },
{ GPD_DEVICE_ID_HVAC_GP_INDOOR_ENVIRONMENT_SENSOR, "HVAC: GP Indoor Environment Sensor" },
/* CUSTOM */
{ GPD_DEVICE_ID_MANUFACTURER_SPECIFIC, "Manufacturer Specific" },
{ 0, NULL }
};
static value_string_ext zbee_nwk_gp_device_ids_names_ext = VALUE_STRING_EXT_INIT(zbee_nwk_gp_device_ids_names);
/* GP directions. */
static const value_string zbee_nwk_gp_directions[] = {
{ ZBEE_NWK_GP_FC_EXT_DIRECTION_FROM_ZGPD, "From ZGPD" },
{ ZBEE_NWK_GP_FC_EXT_DIRECTION_FROM_ZGPP, "From ZGPP" },
{ 0, NULL }
};
/* Frame types for Green Power profile. */
static const value_string zbee_nwk_gp_frame_types[] = {
{ ZBEE_NWK_GP_FCF_DATA, "Data" },
{ ZBEE_NWK_GP_FCF_MAINTENANCE, "Maintenance" },
{ 0, NULL }
};
/* GreenPeak Green Power devices. */
static const value_string zbee_nwk_gp_manufacturer_greenpeak_dev_names[] = {
{ ZBEE_NWK_GP_MANUF_GREENPEAK_IZDS, "IAS Zone Door Sensor" },
{ ZBEE_NWK_GP_MANUF_GREENPEAK_IZDWS, "IAS Zone Door/Window Sensor" },
{ ZBEE_NWK_GP_MANUF_GREENPEAK_IZLS, "IAS Zone Leakage Sensor" },
{ ZBEE_NWK_GP_MANUF_GREENPEAK_IZRHS, "IAS Zone Relative Humidity Sensor" },
{ 0, NULL }
};
/* GP Src ID names. */
static const value_string zbee_nwk_gp_src_id_names[] = {
{ ZBEE_NWK_GP_ZGPD_SRCID_ALL, "All" },
{ ZBEE_NWK_GP_ZGPD_SRCID_UNKNOWN, "Unspecified" },
{ 0, NULL }
};
/* GP security key type names. */
static const value_string zbee_nwk_gp_src_sec_keys_type_names[] = {
{ ZBEE_NWK_GP_SECURITY_KEY_TYPE_DERIVED_INDIVIDUAL_GPD_KEY, "Derived individual GPD key" },
{ ZBEE_NWK_GP_SECURITY_KEY_TYPE_GPD_GROUP_KEY, "GPD group key" },
{ ZBEE_NWK_GP_SECURITY_KEY_TYPE_NO_KEY, "No key" },
{ ZBEE_NWK_GP_SECURITY_KEY_TYPE_NWK_KEY_DERIVED_GPD_KEY_GROUP_KEY, "NWK key derived GPD group key" },
{ ZBEE_NWK_GP_SECURITY_KEY_TYPE_PRECONFIGURED_INDIVIDUAL_GPD_KEY, "Individual, out of the box GPD key" },
{ ZBEE_NWK_GP_SECURITY_KEY_TYPE_ZB_NWK_KEY, "ZigBee NWK key" },
{ 0, NULL }
};
/* GP security levels. */
static const value_string zbee_nwk_gp_src_sec_levels_names[] = {
{ ZBEE_NWK_GP_SECURITY_LEVEL_1LSB, "1 LSB of frame counter and short MIC only" },
{ ZBEE_NWK_GP_SECURITY_LEVEL_FULL, "Full frame counter and full MIC only" },
{ ZBEE_NWK_GP_SECURITY_LEVEL_FULLENCR, "Encryption with full frame counter and full MIC" },
{ ZBEE_NWK_GP_SECURITY_LEVEL_NO, "No security" },
{ 0, NULL }
};
/*************************/
/* Function definitions. */
/*************************/
/* UAT record copy callback. */
static void *
uat_key_record_copy_cb(void *n, const void *o, size_t siz _U_)
{
uat_key_record_t *new_key = (uat_key_record_t *)n;
const uat_key_record_t *old_key = (const uat_key_record_t *)o;
new_key->string = g_strdup(old_key->string);
new_key->label = g_strdup(old_key->label);
return new_key;
}
/* UAT record free callback. */
static void
uat_key_record_free_cb(void *r)
{
uat_key_record_t *key = (uat_key_record_t *)r;
g_free(key->string);
g_free(key->label);
}
/**
*Parses a key string from left to right into a buffer with increasing (normal byte order) or decreasing (reverse
*
*@param key_str pointer to the string
*@param key_buf destination buffer in memory
*@param byte_order byte order
*/
static gboolean
zbee_gp_security_parse_key(const gchar *key_str, guint8 *key_buf, gboolean byte_order)
{
gboolean string_mode = FALSE;
gchar temp;
int i, j;
memset(key_buf, 0, ZBEE_SEC_CONST_KEYSIZE);
if (key_str == NULL) {
return FALSE;
}
if ((temp = *key_str++) == '"') {
string_mode = TRUE;
temp = *key_str++;
}
j = byte_order ? ZBEE_SEC_CONST_KEYSIZE - 1 : 0;
for (i = ZBEE_SEC_CONST_KEYSIZE - 1; i >= 0; i--) {
if (string_mode) {
if (g_ascii_isprint(temp)) {
key_buf[j] = temp;
temp = *key_str++;
} else {
return FALSE;
}
} else {
if ((temp == ':') || (temp == '-') || (temp == ' ')) {
temp = *(key_str++);
}
if (g_ascii_isxdigit(temp)) {
key_buf[j] = g_ascii_xdigit_value(temp) << 4;
} else {
return FALSE;
}
temp = *(key_str++);
if (g_ascii_isxdigit(temp)) {
key_buf[j] |= g_ascii_xdigit_value(temp);
} else {
return FALSE;
}
temp = *(key_str++);
}
if (byte_order) {
j--;
} else {
j++;
}
}
return TRUE;
}
/* UAT record update callback. */
static gboolean
uat_key_record_update_cb(void *r, char **err)
{
uat_key_record_t *rec = (uat_key_record_t *)r;
if (rec->string == NULL) {
*err = g_strdup("Key can't be blank.");
return FALSE;
} else {
g_strstrip(rec->string);
if (rec->string[0] != 0) {
*err = NULL;
if (!zbee_gp_security_parse_key(rec->string, rec->key, rec->byte_order)) {
*err = g_strdup_printf("Expecting %d hexadecimal bytes or a %d character double-quoted string",
ZBEE_SEC_CONST_KEYSIZE, ZBEE_SEC_CONST_KEYSIZE);
return FALSE;
}
} else {
*err = g_strdup("Key can't be blank.");
return FALSE;
}
}
return TRUE;
}
static void uat_key_record_post_update_cb(void) {
guint i;
for (i = 0; i < num_uat_key_records; i++) {
if (memcmp(gp_uat_key_records[i].key, empty_key, ZBEE_SEC_CONST_KEYSIZE) == 0) {
/* key was not loaded from string yet */
zbee_gp_security_parse_key(gp_uat_key_records[i].string, gp_uat_key_records[i].key,
gp_uat_key_records[i].byte_order);
}
}
}
/**
*Fills in ZigBee GP security nonce from the provided packet structure.
*
*@param packet ZigBee NWK packet.
*@param nonce nonce buffer.
*/
static void
zbee_gp_make_nonce(zbee_nwk_green_power_packet *packet, gchar *nonce)
{
memset(nonce, 0, ZBEE_SEC_CONST_NONCE_LEN);
if (packet->direction == ZBEE_NWK_GP_FC_EXT_DIRECTION_FROM_ZGPD) {
phtole32(nonce, packet->source_id);
}
phtole32(nonce+4, packet->source_id);
phtole32(nonce+8, packet->security_frame_counter);
if ((packet->application_id == ZBEE_NWK_GP_APP_ID_ZGP) && (packet->direction !=
ZBEE_NWK_GP_FC_EXT_DIRECTION_FROM_ZGPD)) {
nonce[12] = (gchar)0xa3;
} else {
nonce[12] = (gchar)0x05;
}
/* TODO: implement if application_id == ZB_ZGP_APP_ID_0000. */
/* TODO: implement if application_id != ZB_ZGP_APP_ID_0000. */
}
/**
*Creates a nonce and decrypts secured ZigBee GP payload.
*
*@param packet ZigBee NWK packet.
*@param enc_buffer encoded payload buffer.
*@param offset payload offset.
*@param dec_buffer decoded payload buffer.
*@param payload_len payload length.
*@param mic_len MIC length.
*@param key key.
*/
static gboolean
zbee_gp_decrypt_payload(zbee_nwk_green_power_packet *packet, const gchar *enc_buffer, const gchar offset, guint8
*dec_buffer, guint payload_len, guint mic_len, guint8 *key)
{
guint8 *key_buffer = key;
guint8 nonce[ZBEE_SEC_CONST_NONCE_LEN];
zbee_gp_make_nonce(packet, nonce);
if (zbee_sec_ccm_decrypt(key_buffer, nonce, enc_buffer, enc_buffer + offset, dec_buffer, offset, payload_len,
mic_len)) {
return TRUE;
}
return FALSE;
}
/**
*Dissector for ZigBee Green Power commissioning.
*
*@param tvb pointer to buffer containing raw packet.
*@param pinfo pointer to packet information fields.
*@param tree pointer to data tree Wireshark uses to display packet.
*@param packet packet data.
*@param offset current payload offset.
*@return payload processed offset.
*/
static guint
dissect_zbee_nwk_gp_cmd_commissioning(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
zbee_nwk_green_power_packet *packet, guint offset)
{
guint8 comm_options;
guint8 comm_ext_options = 0;
guint8 appli_info_options = 0;
guint16 manufacturer_id = 0;
guint8 i;
guint8 gpd_cmd_num = 0;
proto_item *gpd_cmd_list;
proto_tree *gpd_cmd_list_tree;
guint8 length_of_clid_list_bm;
guint8 server_clid_num;
guint8 client_clid_num;
proto_item *server_clid_list, *client_clid_list;
proto_tree *server_clid_list_tree, *client_clid_list_tree;
void *enc_buffer;
guint8 *enc_buffer_withA;
guint8 *dec_buffer;
gboolean gp_decrypted;
GSList *GSList_i;
tvbuff_t *payload_tvb;
static const int * options[] = {
&hf_zbee_nwk_gp_cmd_comm_opt_mac_sec_num_cap,
&hf_zbee_nwk_gp_cmd_comm_opt_rx_on_cap,
&hf_zbee_nwk_gp_cmd_comm_opt_appli_info_present,
&hf_zbee_nwk_gp_cmd_comm_opt_panid_req,
&hf_zbee_nwk_gp_cmd_comm_opt_sec_key_req,
&hf_zbee_nwk_gp_cmd_comm_opt_fixed_location,
&hf_zbee_nwk_gp_cmd_comm_opt_ext_opt,
NULL
};
static const int * ext_options[] = {
&hf_zbee_nwk_gp_cmd_comm_ext_opt_sec_level_cap,
&hf_zbee_nwk_gp_cmd_comm_ext_opt_key_type,
&hf_zbee_nwk_gp_cmd_comm_ext_opt_gpd_key_present,
&hf_zbee_nwk_gp_cmd_comm_ext_opt_gpd_key_encr,
&hf_zbee_nwk_gp_cmd_comm_ext_opt_outgoing_counter,
NULL
};
static const int * appli_info[] = {
&hf_zbee_nwk_gp_cmd_comm_appli_info_mip,
&hf_zbee_nwk_gp_cmd_comm_appli_info_mmip,
&hf_zbee_nwk_gp_cmd_comm_appli_info_gclp,
&hf_zbee_nwk_gp_cmd_comm_appli_info_crp,
NULL
};
static const int * length_of_clid_list[] = {
&hf_zbee_nwk_gp_cmd_comm_length_of_clid_list_server,
&hf_zbee_nwk_gp_cmd_comm_length_of_clid_list_client,
NULL
};
/* Get Device ID and display it. */
proto_tree_add_item(tree, hf_zbee_nwk_gp_cmd_comm_device_id, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset += 1;
/* Get Options Field, build subtree and display the results. */
comm_options = tvb_get_guint8(tvb, offset);
proto_tree_add_bitmask(tree, tvb, offset, hf_zbee_nwk_gp_cmd_comm_opt, ett_zbee_nwk_cmd_options, options, ENC_NA);
offset += 1;
if (comm_options & ZBEE_NWK_GP_CMD_COMMISSIONING_OPT_EXT_OPTIONS) {
/* Get extended Options Field, build subtree and display the results. */
comm_ext_options = tvb_get_guint8(tvb, offset);
proto_tree_add_bitmask(tree, tvb, offset, hf_zbee_nwk_gp_cmd_comm_ext_opt, ett_zbee_nwk_cmd_options, ext_options, ENC_NA);
offset += 1;
if (comm_ext_options & ZBEE_NWK_GP_CMD_COMMISSIONING_EXT_OPT_GPD_KEY_PRESENT) {
/* Get security key and display it. */
proto_tree_add_item(tree, hf_zbee_nwk_gp_cmd_comm_security_key, tvb, offset, ZBEE_SEC_CONST_KEYSIZE, ENC_NA);
offset += ZBEE_SEC_CONST_KEYSIZE;
/* Key is encrypted */
if (comm_ext_options & ZBEE_NWK_GP_CMD_COMMISSIONING_EXT_OPT_GPD_KEY_ENCR) {
/* Get Security MIC and display it. */
proto_tree_add_item(tree, hf_zbee_nwk_gp_cmd_comm_gpd_sec_key_mic, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset += 4;
if (packet != NULL)
{
/* Decrypt the security key */
dec_buffer = (guint8 *)wmem_alloc(pinfo->pool, ZBEE_SEC_CONST_KEYSIZE);
enc_buffer_withA = (guint8 *)wmem_alloc(pinfo->pool, 4 + ZBEE_SEC_CONST_KEYSIZE + 4); /* CCM* a (this is SrcID) + encKey + MIC */
enc_buffer = tvb_memdup(wmem_packet_scope(), tvb, offset - ZBEE_SEC_CONST_KEYSIZE - 4, ZBEE_SEC_CONST_KEYSIZE + 4);
phtole32(enc_buffer_withA, packet->source_id);
memcpy(enc_buffer_withA+4, enc_buffer, ZBEE_SEC_CONST_KEYSIZE + 4);
gp_decrypted = FALSE;
for (GSList_i = zbee_gp_keyring; GSList_i && !gp_decrypted; GSList_i = g_slist_next(GSList_i)) {
packet->security_frame_counter = packet->source_id; /* for Nonce creation*/
gp_decrypted = zbee_gp_decrypt_payload(packet, enc_buffer_withA, 4
, dec_buffer, ZBEE_SEC_CONST_KEYSIZE, 4, ((key_record_t *)(GSList_i->data))->key);
}
if (gp_decrypted) {
key_record_t key_record;
key_record.frame_num = 0;
key_record.label = NULL;
memcpy(key_record.key, dec_buffer, ZBEE_SEC_CONST_KEYSIZE);
zbee_gp_keyring = g_slist_prepend(zbee_gp_keyring, g_memdup(&key_record, sizeof(key_record_t)));
payload_tvb = tvb_new_child_real_data(tvb, dec_buffer, ZBEE_SEC_CONST_KEYSIZE, ZBEE_SEC_CONST_KEYSIZE);
add_new_data_source(pinfo, payload_tvb, "Decrypted security key");
}
}
}
else
{
key_record_t key_record;
void *key;
key_record.frame_num = 0;
key_record.label = NULL;
key = tvb_memdup(wmem_packet_scope(), tvb, offset - ZBEE_SEC_CONST_KEYSIZE, ZBEE_SEC_CONST_KEYSIZE);
memcpy(key_record.key, key, ZBEE_SEC_CONST_KEYSIZE);
zbee_gp_keyring = g_slist_prepend(zbee_gp_keyring, g_memdup(&key_record, sizeof(key_record_t)));
}
}
if (comm_ext_options & ZBEE_NWK_GP_CMD_COMMISSIONING_EXT_OPT_OUT_COUNTER) {
/* Get GPD Outgoing Frame Counter and display it. */
proto_tree_add_item(tree, hf_zbee_nwk_gp_cmd_comm_outgoing_counter, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset += 4;
}
}
/* Display manufacturer specific data. */
if (comm_options & ZBEE_NWK_GP_CMD_COMMISSIONING_OPT_APPLICATION_INFO) {
/* Display application information. */
appli_info_options = tvb_get_guint8(tvb, offset);
proto_tree_add_bitmask(tree, tvb, offset, hf_zbee_nwk_gp_cmd_comm_appli_info, ett_zbee_nwk_cmd_appli_info, appli_info, ENC_NA);
offset += 1;
if (appli_info_options & ZBEE_NWK_GP_CMD_COMMISSIONING_APPLI_INFO_MIP) {
/* Get Manufacturer ID. */
manufacturer_id = tvb_get_letohs(tvb, offset);
proto_tree_add_item(tree, hf_zbee_nwk_gp_cmd_comm_manufacturer_id, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
}
if (appli_info_options & ZBEE_NWK_GP_CMD_COMMISSIONING_APPLI_INFO_MMIP) {
/* Get Manufacturer Device ID. */
switch (manufacturer_id) {
case ZBEE_NWK_GP_MANUF_ID_GREENPEAK:
proto_tree_add_item(tree, hf_zbee_nwk_gp_cmd_comm_manufacturer_greenpeak_dev_id, tvb, offset, 2,
ENC_LITTLE_ENDIAN);
offset += 2;
break;
default:
proto_tree_add_item(tree, hf_zbee_nwk_gp_cmd_comm_manufacturer_dev_id, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
break;
}
}
if (appli_info_options & ZBEE_NWK_GP_CMD_COMMISSIONING_APPLI_INFO_GCLP) {
/* Get and display number of GPD commands */
gpd_cmd_num = tvb_get_guint8(tvb, offset);
proto_tree_add_item(tree, hf_zbee_nwk_gp_cmd_comm_gpd_cmd_num, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset += 1;
/* Display GPD command list */
if (gpd_cmd_num > 0) {
gpd_cmd_list = proto_tree_add_item(tree, hf_zbee_nwk_gp_cmd_comm_gpd_cmd_id_list,
tvb, offset, gpd_cmd_num, ENC_NA);
gpd_cmd_list_tree = proto_item_add_subtree(gpd_cmd_list, ett_zbee_nwk_cmd_comm_gpd_cmd_id_list);
for (i = 0; i < gpd_cmd_num; i++, offset++) {
/* Display command id */
proto_tree_add_item(gpd_cmd_list_tree, hf_zbee_nwk_gp_command_id,
tvb, offset, 1, ENC_LITTLE_ENDIAN);
}
}
}
if (appli_info_options & ZBEE_NWK_GP_CMD_COMMISSIONING_APPLI_INFO_CRP) {
/* Get and display Cluster List */
length_of_clid_list_bm = tvb_get_guint8(tvb, offset);
server_clid_num = (length_of_clid_list_bm & ZBEE_NWK_GP_CMD_COMMISSIONING_CLID_LIST_LEN_SRV) >>
ws_ctz(ZBEE_NWK_GP_CMD_COMMISSIONING_CLID_LIST_LEN_SRV);
client_clid_num = (length_of_clid_list_bm & ZBEE_NWK_GP_CMD_COMMISSIONING_CLID_LIST_LEN_CLI ) >>
ws_ctz(ZBEE_NWK_GP_CMD_COMMISSIONING_CLID_LIST_LEN_CLI);
proto_tree_add_bitmask(tree, tvb, offset, hf_zbee_nwk_gp_cmd_comm_length_of_clid_list,
ett_zbee_nwk_cmd_comm_length_of_clid_list, length_of_clid_list, ENC_NA);
offset += 1;
if (server_clid_num > 0) {
/* Display server cluster list */
server_clid_list = proto_tree_add_item(tree, hf_zbee_nwk_cmd_comm_clid_list_server,
tvb, offset, 2*server_clid_num, ENC_NA);
server_clid_list_tree = proto_item_add_subtree(server_clid_list, ett_zbee_nwk_cmd_comm_clid_list_server);
/* Retrieve server clusters */
for (i = 0; i < server_clid_num; i++, offset += 2) {
proto_tree_add_item(server_clid_list_tree, hf_zbee_nwk_cmd_comm_cluster_id,
tvb, offset, 2, ENC_LITTLE_ENDIAN);
}
}
if (client_clid_num > 0) {
/* Display client cluster list */
client_clid_list = proto_tree_add_item(tree, hf_zbee_nwk_cmd_comm_clid_list_client,
tvb, offset, 2*client_clid_num, ENC_NA);
client_clid_list_tree = proto_item_add_subtree(client_clid_list, ett_zbee_nwk_cmd_comm_clid_list_client);
/* Retrieve client clusters */
for (i = 0; i < client_clid_num; i++, offset += 2) {
proto_tree_add_item(client_clid_list_tree, hf_zbee_nwk_cmd_comm_cluster_id,
tvb, offset, 2, ENC_LITTLE_ENDIAN);
}
}
}
}
return offset;
} /* dissect_zbee_nwk_gp_cmd_commissioning */
/**
*Dissector for ZigBee Green Power channel request.
*
*@param tvb pointer to buffer containing raw packet.
*@param pinfo pointer to packet information fields.
*@param tree pointer to data tree Wireshark uses to display packet.
*@param packet packet data.
*@param offset current payload offset.
*@return payload processed offset.
*/
static guint
dissect_zbee_nwk_gp_cmd_channel_request(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree,
zbee_nwk_green_power_packet *packet _U_, guint offset)
{
static const int * channels[] = {
&hf_zbee_nwk_gp_cmd_channel_request_toggling_behaviour_1st,
&hf_zbee_nwk_gp_cmd_channel_request_toggling_behaviour_2nd,
NULL
};
/* Get Command Options Field, build subtree and display the results. */
proto_tree_add_bitmask(tree, tvb, offset, hf_zbee_nwk_gp_cmd_channel_request_toggling_behaviour, ett_zbee_nwk_cmd_options, channels, ENC_NA);
offset += 1;
return offset;
} /* dissect_zbee_nwk_gp_cmd_channel_request */
/**
*Dissector for ZigBee Green Power channel configuration.
*
*@param tvb pointer to buffer containing raw packet.
*@param pinfo pointer to packet information fields.
*@param tree pointer to data tree Wireshark uses to display packet.
*@param packet packet data.
*@param offset current payload offset.
*@return payload processed offset.
*/
static guint
dissect_zbee_nwk_gp_cmd_channel_configuration(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree,
zbee_nwk_green_power_packet *packet _U_, guint offset)
{
static const int * channels[] = {
&hf_zbee_nwk_gp_cmd_channel_configuration,
NULL
};
/* Get Command Options Field, build subtree and display the results. */
proto_tree_add_bitmask(tree, tvb, offset, hf_zbee_nwk_gp_cmd_operational_channel, ett_zbee_nwk_cmd_options, channels, ENC_NA);
offset += 1;
return offset;
} /* dissect_zbee_nwk_gp_cmd_channel_configuration */
/**
*Dissector for ZigBee Green Power commands attrib reporting.
*
*@param tvb pointer to buffer containing raw packet.
*@param pinfo pointer to packet information fields.
*@param tree pointer to data tree Wireshark uses to display packet.
*@param packet packet data.
*@param offset current payload offset.
*@param mfr_code manufacturer code.
*@return payload processed offset.
*/
static guint
dissect_zbee_nwk_gp_cmd_attr_reporting(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree,
zbee_nwk_green_power_packet *packet _U_, guint offset, guint16 mfr_code)
{
guint16 cluster_id;
proto_tree *field_tree;
/* Get cluster ID and add it into the tree. */
cluster_id = tvb_get_letohs(tvb, offset);
proto_tree_add_item(tree, hf_zbee_nwk_gp_zcl_attr_cluster_id, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
/* Create subtree and parse ZCL Write Attribute Payload. */
field_tree = proto_tree_add_subtree_format(tree, tvb, offset, 2, ett_zbee_nwk_cmd_options, NULL,
"Attribute reporting command for cluster: 0x%04X", cluster_id);
dissect_zcl_report_attr(tvb, pinfo, field_tree, &offset, cluster_id, mfr_code, ZBEE_ZCL_FCF_TO_CLIENT);
return offset;
} /* dissect_zbee_nwk_gp_cmd_attr_reporting */
/**
* Dissector for ZigBee Green Power manufacturer specific attribute reporting.
*
*@param tvb pointer to buffer containing raw packet.
*@param pinfo pointer to packet information fields.
*@param tree pointer to data tree Wireshark uses to display packet.
*@param packet packet data.
*@param offset current payload offset.
*@return payload processed offset.
*/
static guint
dissect_zbee_nwk_gp_cmd_MS_attr_reporting(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree,
zbee_nwk_green_power_packet *packet _U_, guint offset)
{
guint16 mfr_code;
/*dissect manufacturer ID*/
proto_tree_add_item(tree, hf_zbee_zcl_gp_cmd_ms_manufacturer_code, tvb, offset, 2, ENC_LITTLE_ENDIAN);
mfr_code = tvb_get_letohs(tvb, offset);
offset += 2;
offset = dissect_zbee_nwk_gp_cmd_attr_reporting(tvb, pinfo, tree, packet, offset, mfr_code);
return offset;
}/*dissect_zbee_nwk_gp_cmd_MS_attr_reporting*/
/**
*Dissector for ZigBee Green Power commissioning reply.
*
*@param tvb pointer to buffer containing raw packet.
*@param pinfo pointer to packet information fields.
*@param tree pointer to data tree Wireshark uses to display packet.
*@param packet packet data.
*@param offset current payload offset.
*@return payload processed offset.
*/
static guint
dissect_zbee_nwk_gp_cmd_commissioning_reply(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree,
zbee_nwk_green_power_packet *packet, guint offset)
{
guint8 cr_options;
guint8 cr_sec_level;
void *enc_buffer;
guint8 *enc_buffer_withA;
guint8 *dec_buffer;
gboolean gp_decrypted;
GSList *GSList_i;
tvbuff_t *payload_tvb;
static const int * options[] = {
&hf_zbee_nwk_gp_cmd_comm_rep_opt_panid_present,
&hf_zbee_nwk_gp_cmd_comm_rep_opt_sec_key_present,
&hf_zbee_nwk_gp_cmd_comm_rep_opt_key_encr,
&hf_zbee_nwk_gp_cmd_comm_rep_opt_sec_level,
&hf_zbee_nwk_gp_cmd_comm_rep_opt_sec_type,
NULL
};
/* Get Options Field, build subtree and display the results. */
cr_options = tvb_get_guint8(tvb, offset);
proto_tree_add_bitmask(tree, tvb, offset, hf_zbee_nwk_gp_cmd_comm_rep_opt, ett_zbee_nwk_cmd_options, options, ENC_NA);
offset += 1;
/* Parse and display security Pan ID value. */
if (cr_options & ZBEE_NWK_GP_CMD_COMMISSIONING_REP_OPT_PAN_ID_PRESENT) {
proto_tree_add_item(tree, hf_zbee_nwk_gp_cmd_comm_rep_pan_id, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
}
cr_sec_level = (cr_options & ZBEE_NWK_GP_CMD_COMMISSIONING_REP_OPT_SEC_LEVEL) >>
ws_ctz(ZBEE_NWK_GP_CMD_COMMISSIONING_REP_OPT_SEC_LEVEL);
/* Parse and display security key. */
if (cr_options & ZBEE_NWK_GP_CMD_COMMISSIONING_REP_OPT_SEC_KEY_PRESENT) {
proto_tree_add_item(tree, hf_zbee_nwk_gp_cmd_comm_security_key, tvb, offset, ZBEE_SEC_CONST_KEYSIZE, ENC_NA);
offset += ZBEE_SEC_CONST_KEYSIZE;
/* Key is present clear, add to the key ring */
if (!(cr_options & ZBEE_NWK_GP_CMD_COMMISSIONING_REP_OPT_KEY_ENCR)) {
key_record_t key_record;
void *key;
key_record.frame_num = 0;
key_record.label = NULL;
key = tvb_memdup(wmem_packet_scope(), tvb, offset - ZBEE_SEC_CONST_KEYSIZE, ZBEE_SEC_CONST_KEYSIZE);
memcpy(key_record.key, key, ZBEE_SEC_CONST_KEYSIZE);
zbee_gp_keyring = g_slist_prepend(zbee_gp_keyring, g_memdup(&key_record, sizeof(key_record_t)));
}
}
/* Parse and display security MIC. */
if ((cr_options & ZBEE_NWK_GP_CMD_COMMISSIONING_REP_OPT_KEY_ENCR) &&
(cr_options & ZBEE_NWK_GP_CMD_COMMISSIONING_REP_OPT_SEC_KEY_PRESENT)) {
proto_tree_add_item(tree, hf_zbee_nwk_gp_cmd_comm_gpd_sec_key_mic, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset += 4;
}
/* Parse and display Frame Counter and decrypt key */
if ((cr_options & ZBEE_NWK_GP_CMD_COMMISSIONING_REP_OPT_KEY_ENCR) &&
(cr_options & ZBEE_NWK_GP_CMD_COMMISSIONING_REP_OPT_SEC_KEY_PRESENT) &&
((cr_sec_level == ZBEE_NWK_GP_SECURITY_LEVEL_FULL) ||
(cr_sec_level == ZBEE_NWK_GP_SECURITY_LEVEL_FULLENCR))) {
if (offset + 4 <= tvb_captured_length(tvb)){
proto_tree_add_item(tree, hf_zbee_nwk_gp_cmd_comm_rep_frame_counter, tvb, offset, 4, ENC_LITTLE_ENDIAN);
offset += 4;
if (packet != NULL)
{
/* decrypt the security key*/
dec_buffer = (guint8 *)wmem_alloc(pinfo->pool, ZBEE_SEC_CONST_KEYSIZE);
enc_buffer_withA = (guint8 *)wmem_alloc(pinfo->pool, 4 + ZBEE_SEC_CONST_KEYSIZE + 4); /* CCM* a (this is SrcID) + encKey + MIC */
enc_buffer = tvb_memdup(wmem_packet_scope(), tvb, offset - ZBEE_SEC_CONST_KEYSIZE - 4 - 4, ZBEE_SEC_CONST_KEYSIZE + 4);
phtole32(enc_buffer_withA, packet->source_id); /* enc_buffer_withA = CCM* a (srcID) | enc_buffer */
memcpy(enc_buffer_withA+4, enc_buffer, ZBEE_SEC_CONST_KEYSIZE + 4);
gp_decrypted = FALSE;
for (GSList_i = zbee_gp_keyring; GSList_i && !gp_decrypted; GSList_i = g_slist_next(GSList_i)) {
packet->security_frame_counter = tvb_get_guint32(tvb, offset - 4, ENC_LITTLE_ENDIAN); /*for Nonce creation */
gp_decrypted = zbee_gp_decrypt_payload(packet, enc_buffer_withA, 4
, dec_buffer, ZBEE_SEC_CONST_KEYSIZE, 4, ((key_record_t *)(GSList_i->data))->key);
}
if (gp_decrypted) {
key_record_t key_record;
key_record.frame_num = 0;
key_record.label = NULL;
memcpy(key_record.key, dec_buffer, ZBEE_SEC_CONST_KEYSIZE);
zbee_gp_keyring = g_slist_prepend(zbee_gp_keyring, g_memdup(&key_record, sizeof(key_record_t)));
payload_tvb = tvb_new_child_real_data(tvb, dec_buffer, ZBEE_SEC_CONST_KEYSIZE, ZBEE_SEC_CONST_KEYSIZE);
add_new_data_source(pinfo, payload_tvb, "Decrypted security key");
}
}
}
else{
/* This field is new in 2016 specification, older implementation may exist without it */
proto_tree_add_expert(tree, pinfo, &ei_zbee_nwk_gp_com_rep_no_out_cnt, tvb, 0, -1);
}
}
return offset;
} /* dissect_zbee_nwk_gp_cmd_commissioning_reply */
/**
* Dissector for ZigBee Green Power read attributes and request attributes commands.
*
*@param tvb pointer to buffer containing raw packet.
*@param pinfo pointer to packet information fields.
*@param tree pointer to data tree Wireshark uses to display packet.
*@param packet packet data.
*@param offset current payload offset.
*@return payload processed offset.
*/
static guint
dissect_zbee_nwk_gp_cmd_read_attributes(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree,
zbee_nwk_green_power_packet *packet _U_, guint offset)
{
guint8 cr_options = 0;
proto_tree *subtree = NULL;
guint16 cluster_id;
guint16 mfr_code = ZBEE_MFG_CODE_NONE;
guint8 record_list_len;
guint tvb_len;
guint8 i;
static const int * options[] = {
&hf_zbee_nwk_gp_cmd_read_att_opt_multi_rec,
&hf_zbee_nwk_gp_cmd_read_att_opt_man_field_present,
NULL
};
/* Get Options Field, build subtree and display the results. */
cr_options = tvb_get_guint8(tvb, offset);
proto_tree_add_bitmask(tree, tvb, offset, hf_zbee_nwk_gp_cmd_read_att_opt, ett_zbee_nwk_cmd_options, options, ENC_NA);
offset += 1;
/* Parse and display manufacturer ID value. */
if (cr_options & ZBEE_NWK_GP_CMD_READ_ATTRIBUTE_OPT_MAN_FIELD_PRESENT) {
proto_tree_add_item(tree, hf_zbee_zcl_gp_cmd_ms_manufacturer_code, tvb, offset, 2, ENC_LITTLE_ENDIAN);
mfr_code = tvb_get_letohs(tvb, offset);
offset += 2;
}
tvb_len = tvb_captured_length(tvb);
while (offset < tvb_len)
{
/* Create subtree and parse attributes list. */
subtree = proto_tree_add_subtree_format(tree, tvb, offset, -1, ett_zbee_nwk_clu_rec, NULL, "Cluster Record Request");
/* Get cluster ID and add it into the subtree. */
cluster_id = tvb_get_letohs(tvb, offset);
proto_tree_add_item(subtree, hf_zbee_nwk_gp_zcl_attr_cluster_id, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
/* Get length of record list (number of attributes * 2). */
record_list_len = tvb_get_guint8(tvb, offset);
proto_tree_add_item(subtree, hf_zbee_nwk_gp_cmd_read_att_record_len, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset += 1;
for(i=0 ; i<record_list_len ; i+=2)
{
/* Dissect the attribute identifier */
dissect_zcl_attr_id(tvb, subtree, &offset, cluster_id, mfr_code, ZBEE_ZCL_FCF_TO_CLIENT);
}
}
return offset;
} /* dissect_zbee_nwk_gp_cmd_read_attributes */
/**
* Dissector for ZigBee Green Power write attributes commands.
*
*@param tvb pointer to buffer containing raw packet.
*@param pinfo pointer to packet information fields.
*@param tree pointer to data tree Wireshark uses to display packet.
*@param packet packet data.
*@param offset current payload offset.
*@return payload processed offset.
*/
static guint
dissect_zbee_nwk_gp_cmd_write_attributes(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree,
zbee_nwk_green_power_packet *packet _U_, guint offset)
{
guint8 cr_options = 0;
proto_tree *subtree = NULL;
proto_tree *att_tree = NULL;
guint16 mfr_code = ZBEE_MFG_CODE_NONE;
guint16 cluster_id;
guint8 record_list_len;
guint tvb_len;
guint16 attr_id;
guint end_byte;
//guint8 i;
static const int * options[] = {
&hf_zbee_nwk_gp_cmd_read_att_opt_multi_rec,
&hf_zbee_nwk_gp_cmd_read_att_opt_man_field_present,
NULL
};
/* Get Options Field, build subtree and display the results. */
cr_options = tvb_get_guint8(tvb, offset);
proto_tree_add_bitmask(tree, tvb, offset, hf_zbee_nwk_gp_cmd_read_att_opt, ett_zbee_nwk_cmd_options, options, ENC_NA);
offset += 1;
/* Parse and display manufacturer ID value. */
if (cr_options & ZBEE_NWK_GP_CMD_READ_ATTRIBUTE_OPT_MAN_FIELD_PRESENT) {
proto_tree_add_item(tree, hf_zbee_zcl_gp_cmd_ms_manufacturer_code, tvb, offset, 2, ENC_LITTLE_ENDIAN);
mfr_code = tvb_get_letohs(tvb, offset);
offset += 2;
}
tvb_len = tvb_captured_length(tvb);
while (offset < tvb_len)
{
/* Create subtree and parse attributes list. */
subtree = proto_tree_add_subtree_format(tree, tvb, offset, -1, ett_zbee_nwk_clu_rec, NULL, "Write Cluster Record");
/* Get cluster ID and add it into the subtree. */
cluster_id = tvb_get_letohs(tvb, offset);
proto_tree_add_item(subtree, hf_zbee_nwk_gp_zcl_attr_cluster_id, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
/* Get length of record list. */
record_list_len = tvb_get_guint8(tvb, offset);
proto_tree_add_item(subtree, hf_zbee_nwk_gp_cmd_read_att_record_len, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset += 1;
end_byte = offset + record_list_len;
while ( offset < end_byte)
{
/* Create subtree for attribute status field */
att_tree = proto_tree_add_subtree_format(subtree, tvb, offset, 0, ett_zbee_nwk_att_rec, NULL, "Write Attribute record");
/* Dissect the attribute identifier */
attr_id = tvb_get_letohs(tvb, offset);
dissect_zcl_attr_id(tvb, att_tree, &offset, cluster_id, mfr_code, ZBEE_ZCL_FCF_TO_CLIENT);
/* Dissect the attribute data type and data */
dissect_zcl_attr_data_type_val(tvb, att_tree, &offset, attr_id, cluster_id, mfr_code, ZBEE_ZCL_FCF_TO_CLIENT);
}
}
return offset;
} /* dissect_zbee_nwk_gp_cmd_write_attributes */
/**
* Dissector for ZigBee Green Power read attribute response command.
*
*@param tvb pointer to buffer containing raw packet.
*@param pinfo pointer to packet information fields.
*@param tree pointer to data tree Wireshark uses to display packet.
*@param packet packet data.
*@param offset current payload offset.
*@return payload processed offset.
*/
static guint
dissect_zbee_nwk_gp_cmd_read_attributes_response(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree,
zbee_nwk_green_power_packet *packet _U_, guint offset)
{
guint8 cr_options;
proto_tree *subtree = NULL;
proto_tree *att_tree = NULL;
guint16 cluster_id;
guint16 attr_id;
guint16 mfr_code = ZBEE_MFG_CODE_NONE;
guint8 record_list_len;
guint tvb_len;
guint end_byte;
static const int * options[] = {
&hf_zbee_nwk_gp_cmd_read_att_opt_multi_rec,
&hf_zbee_nwk_gp_cmd_read_att_opt_man_field_present,
NULL
};
/* Get Options Field, build subtree and display the results. */
cr_options = tvb_get_guint8(tvb, offset);
proto_tree_add_bitmask(tree, tvb, offset, hf_zbee_nwk_gp_cmd_read_att_opt, ett_zbee_nwk_cmd_options, options, ENC_NA);
offset += 1;
/* Parse and display manufacturer ID value. */
if (cr_options & ZBEE_NWK_GP_CMD_READ_ATTRIBUTE_OPT_MAN_FIELD_PRESENT) {
proto_tree_add_item(tree, hf_zbee_zcl_gp_cmd_ms_manufacturer_code, tvb, offset, 2, ENC_LITTLE_ENDIAN);
mfr_code = tvb_get_letohs(tvb, offset);
offset += 2;
}
tvb_len = tvb_captured_length(tvb);
while (offset < tvb_len)
{
/* Create subtree and parse attributes list. */
subtree = proto_tree_add_subtree_format(tree, tvb, offset,0, ett_zbee_nwk_clu_rec, NULL, "Cluster record");
/* Get cluster ID and add it into the subtree. */
cluster_id = tvb_get_letohs(tvb, offset);
proto_tree_add_item(subtree, hf_zbee_nwk_gp_zcl_attr_cluster_id, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
/* Get length of record list in bytes. */
record_list_len = tvb_get_guint8(tvb, offset);
proto_tree_add_item(subtree, hf_zbee_nwk_gp_cmd_read_att_record_len, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset += 1;
end_byte = offset + record_list_len;
while ( offset < end_byte)
{
/* Create subtree for attribute status field */
/* TODO ett_ could be an array to permit not to unroll all always */
att_tree = proto_tree_add_subtree_format(subtree, tvb, offset, 0, ett_zbee_nwk_att_rec, NULL, "Read Attribute record");
/* Dissect the attribute identifier */
attr_id = tvb_get_letohs(tvb, offset);
dissect_zcl_attr_id(tvb, att_tree, &offset, cluster_id, mfr_code, ZBEE_ZCL_FCF_TO_CLIENT);
/* Dissect the status and optionally the data type and value */
if (dissect_zcl_attr_uint8(tvb, att_tree, &offset, &hf_zbee_nwk_gp_zcl_attr_status)
== ZBEE_ZCL_STAT_SUCCESS)
{
/* Dissect the attribute data type and data */
dissect_zcl_attr_data_type_val(tvb, att_tree, &offset, attr_id, cluster_id, mfr_code, ZBEE_ZCL_FCF_TO_CLIENT);
}
else
{
/* Data type field is always present (not like in ZCL read attribute response command) */
dissect_zcl_attr_data(tvb, att_tree, &offset,
dissect_zcl_attr_uint8(tvb, att_tree, &offset, &hf_zbee_nwk_gp_zcl_attr_data_type), ZBEE_ZCL_FCF_TO_CLIENT );
}
}
}
return offset;
} /* dissect_zbee_nwk_gp_cmd_read_attributes_response */
/**
*Dissector for ZigBee Green Power multi-cluster reporting command.
*
*@param tvb pointer to buffer containing raw packet.
*@param pinfo pointer to packet information fields.
*@param tree pointer to data tree Wireshark uses to display packet.
*@param packet packet data.
*@param offset current payload offset.
*@param mfr_code manufacturer code.
*@return payload processed offset.
*/
static guint
dissect_zbee_nwk_gp_cmd_multi_cluster_reporting(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree,
zbee_nwk_green_power_packet *packet _U_, guint offset, guint16 mfr_code)
{
proto_tree *subtree = NULL;
guint16 cluster_id;
guint16 attr_id;
guint tvb_len;
tvb_len = tvb_captured_length(tvb);
while (offset < tvb_len)
{
/* Create subtree and parse attributes list. */
subtree = proto_tree_add_subtree_format(tree, tvb, offset, 0, ett_zbee_nwk_clu_rec, NULL, "Cluster record"); //TODO for cluster %% blabla
/* Get cluster ID and add it into the subtree. */
cluster_id = tvb_get_letohs(tvb, offset);
proto_tree_add_item(subtree, hf_zbee_nwk_gp_zcl_attr_cluster_id, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
/* Dissect the attribute identifier */
attr_id = tvb_get_letohs(tvb, offset);
dissect_zcl_attr_id(tvb, subtree, &offset, cluster_id, mfr_code, ZBEE_ZCL_FCF_TO_CLIENT);
/* Dissect the attribute data type and data */
dissect_zcl_attr_data_type_val(tvb, subtree, &offset, attr_id, cluster_id, mfr_code, ZBEE_ZCL_FCF_TO_CLIENT);
// TODO how to dissect when data type is different from expected one for this attribute ? this shouldn't happen
}
return offset;
} /* dissect_zbee_nwk_gp_cmd_multi_cluster_reporting */
/**
*Dissector for ZigBee Green Power commands manufacturer specific attrib reporting.
*
*@param tvb pointer to buffer containing raw packet.
*@param pinfo pointer to packet information fields.
*@param tree pointer to data tree Wireshark uses to display packet.
*@param packet packet data.
*@param offset current payload offset.
*@return payload processed offset.
*/
static guint
dissect_zbee_nwk_gp_cmd_MS_multi_cluster_reporting(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree,
zbee_nwk_green_power_packet *packet _U_, guint offset)
{
guint16 mfr_code;
/*dissect manufacturer ID*/
proto_tree_add_item(tree, hf_zbee_zcl_gp_cmd_ms_manufacturer_code, tvb, offset, 2, ENC_LITTLE_ENDIAN);
mfr_code = tvb_get_letohs(tvb, offset);
offset += 2;
offset = dissect_zbee_nwk_gp_cmd_multi_cluster_reporting(tvb, pinfo, tree, packet, offset, mfr_code);
return offset;
}/*dissect_zbee_nwk_gp_cmd_MS_multi_cluster_reporting*/
/**
*Dissector for ZigBee Green Power Move Color.
*
*@param tvb pointer to buffer containing raw packet.
*@param pinfo pointer to packet information fields.
*@param tree pointer to data tree Wireshark uses to display packet.
*@param packet packet data.
*@param offset current payload offset.
*@return payload processed offset.
*/
static guint
dissect_zbee_nwk_gp_cmd_move_color(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree,
zbee_nwk_green_power_packet *packet _U_, guint offset)
{
proto_tree_add_item(tree, hf_zbee_nwk_gp_cmd_move_color_ratex, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
proto_tree_add_item(tree, hf_zbee_nwk_gp_cmd_move_color_ratey, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
return offset;
} /* dissect_zbee_nwk_gp_cmd_move_color */
/**
*Dissector for ZigBee Green Power Move Up/Down.
*
*@param tvb pointer to buffer containing raw packet.
*@param pinfo pointer to packet information fields.
*@param tree pointer to data tree Wireshark uses to display packet.
*@param packet packet data.
*@param offset current payload offset.
*@return payload processed offset.
*/
static guint
dissect_zbee_nwk_gp_cmd_move_up_down(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree,
zbee_nwk_green_power_packet *packet _U_, guint offset)
{
proto_tree_add_item(tree, hf_zbee_nwk_gp_cmd_move_up_down_rate, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset += 1;
return offset;
} /* dissect_zbee_nwk_gp_cmd_move_up_down */
/**
*Dissector for ZigBee Green Power Step Color.
*
*@param tvb pointer to buffer containing raw packet.
*@param pinfo pointer to packet information fields.
*@param tree pointer to data tree Wireshark uses to display packet.
*@param packet packet data.
*@param offset current payload offset.
*@return payload processed offset.
*/
static guint
dissect_zbee_nwk_gp_cmd_step_color(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree,
zbee_nwk_green_power_packet *packet _U_, guint offset)
{
proto_tree_add_item(tree, hf_zbee_nwk_gp_cmd_step_color_stepx, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
proto_tree_add_item(tree, hf_zbee_nwk_gp_cmd_step_color_stepy, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
/* Optional time field. */
if (tvb_reported_length(tvb) - offset >= 2) {
proto_tree_add_item(tree, hf_zbee_nwk_gp_cmd_step_color_transition_time, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
}
return offset;
} /* dissect_zbee_nwk_gp_cmd_step_color */
/**
*Dissector for ZigBee Green Power Step Up/Down.
*
*@param tvb pointer to buffer containing raw packet.
*@param pinfo pointer to packet information fields.
*@param tree pointer to data tree Wireshark uses to display packet.
*@param packet packet data.
*@param offset current payload offset.
*@return payload processed offset.
*/
static guint
dissect_zbee_nwk_gp_cmd_step_up_down(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree,
zbee_nwk_green_power_packet *packet _U_, guint offset)
{
proto_tree_add_item(tree, hf_zbee_nwk_gp_cmd_step_up_down_step_size, tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset += 1;
proto_tree_add_item(tree, hf_zbee_nwk_gp_cmd_step_up_down_transition_time, tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
return offset;
} /* dissect_zbee_nwk_gp_cmd_step_up_down */
/**
*Dissector for ZigBee Green Power commands.
*
*@param tvb pointer to buffer containing raw packet.
*@param pinfo pointer to packet information fields.
*@param tree pointer to data tree Wireshark uses to display packet.
*@param data raw packet private data.
*@return payload processed offset
*/
static int
dissect_zbee_nwk_gp_cmd(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
{
guint offset = 0;
guint8 cmd_id = tvb_get_guint8(tvb, offset);
proto_item *cmd_root;
proto_tree *cmd_tree;
zbee_nwk_green_power_packet *packet = (zbee_nwk_green_power_packet *)data;
/* Create a subtree for the command. */
cmd_tree = proto_tree_add_subtree_format(tree, tvb, offset, -1, ett_zbee_nwk_cmd, &cmd_root,
"Command Frame: %s", val_to_str_ext_const(cmd_id,
&zbee_nwk_gp_cmd_names_ext,
"Unknown Command Frame"));
/* Add the command ID. */
proto_tree_add_uint(cmd_tree, hf_zbee_nwk_gp_command_id, tvb, offset, 1, cmd_id);
offset += 1;
/* Add the command name to the info column. */
col_set_str(pinfo->cinfo, COL_INFO, val_to_str_ext_const(cmd_id, &zbee_nwk_gp_cmd_names_ext, "Unknown command"));
/* Handle the command for one of the following devices:
* - Door Lock Controller (IDs: 0x50 - 0x51);
* - GP Flow Sensor (IDs: 0xE0, 0xA0 - 0xA3);
* - GP Temperature Sensor (IDs: 0xE0, 0xA0 - 0xA3); */
switch(cmd_id) {
/* Payloadless GPDF commands sent by GPD. */
case ZB_GP_CMD_ID_IDENTIFY:
case ZB_GP_CMD_ID_SCENE0:
case ZB_GP_CMD_ID_SCENE1:
case ZB_GP_CMD_ID_SCENE2:
case ZB_GP_CMD_ID_SCENE3:
case ZB_GP_CMD_ID_SCENE4:
case ZB_GP_CMD_ID_SCENE5:
case ZB_GP_CMD_ID_SCENE6:
case ZB_GP_CMD_ID_SCENE7:
case ZB_GP_CMD_ID_SCENE8:
case ZB_GP_CMD_ID_SCENE9:
case ZB_GP_CMD_ID_SCENE10:
case ZB_GP_CMD_ID_SCENE11:
case ZB_GP_CMD_ID_SCENE12:
case ZB_GP_CMD_ID_SCENE13:
case ZB_GP_CMD_ID_SCENE14:
case ZB_GP_CMD_ID_SCENE15:
case ZB_GP_CMD_ID_OFF:
case ZB_GP_CMD_ID_ON:
case ZB_GP_CMD_ID_TOGGLE:
case ZB_GP_CMD_ID_RELEASE:
case ZB_GP_CMD_ID_LEVEL_CONTROL_STOP:
case ZB_GP_CMD_ID_MOVE_HUE_STOP:
case ZB_GP_CMD_ID_MOVE_SATURATION_STOP:
case ZB_GP_CMD_ID_LOCK_DOOR:
case ZB_GP_CMD_ID_UNLOCK_DOOR:
case ZB_GP_CMD_ID_PRESS11:
case ZB_GP_CMD_ID_RELEASE11:
case ZB_GP_CMD_ID_PRESS12:
case ZB_GP_CMD_ID_RELEASE12:
case ZB_GP_CMD_ID_PRESS22:
case ZB_GP_CMD_ID_RELEASE22:
case ZB_GP_CMD_ID_SHORT_PRESS11:
case ZB_GP_CMD_ID_SHORT_PRESS12:
case ZB_GP_CMD_ID_SHORT_PRESS22:
case ZB_GP_CMD_ID_DECOMMISSIONING:
case ZB_GP_CMD_ID_SUCCESS:
break;
/* GPDF commands with payload sent by GPD. */
case ZB_GP_CMD_ID_MOVE_UP:
case ZB_GP_CMD_ID_MOVE_DOWN:
case ZB_GP_CMD_ID_MOVE_UP_WITH_ON_OFF:
case ZB_GP_CMD_ID_MOVE_DOWN_WITH_ON_OFF:
case ZB_GP_CMD_ID_MOVE_HUE_UP:
case ZB_GP_CMD_ID_MOVE_HUE_DOWN:
case ZB_GP_CMD_ID_MOVE_SATURATION_UP:
case ZB_GP_CMD_ID_MOVE_SATURATION_DOWN:
offset = dissect_zbee_nwk_gp_cmd_move_up_down(tvb, pinfo, cmd_tree, packet, offset);
break;
case ZB_GP_CMD_ID_STEP_UP:
case ZB_GP_CMD_ID_STEP_DOWN:
case ZB_GP_CMD_ID_STEP_UP_WITH_ON_OFF:
case ZB_GP_CMD_ID_STEP_DOWN_WITH_ON_OFF:
case ZB_GP_CMD_ID_STEP_HUE_UP:
case ZB_GP_CMD_ID_STEP_HUW_DOWN:
case ZB_GP_CMD_ID_STEP_SATURATION_UP:
case ZB_GP_CMD_ID_STEP_SATURATION_DOWN:
offset = dissect_zbee_nwk_gp_cmd_step_up_down(tvb, pinfo, cmd_tree, packet, offset);
break;
case ZB_GP_CMD_ID_MOVE_COLOR:
offset = dissect_zbee_nwk_gp_cmd_move_color(tvb, pinfo, cmd_tree, packet, offset);
break;
case ZB_GP_CMD_ID_STEP_COLOR:
offset = dissect_zbee_nwk_gp_cmd_step_color(tvb, pinfo, cmd_tree, packet, offset);
break;
case ZB_GP_CMD_ID_ATTRIBUTE_REPORTING:
offset = dissect_zbee_nwk_gp_cmd_attr_reporting(tvb, pinfo, cmd_tree, packet, offset, ZBEE_MFG_CODE_NONE);
break;
case ZB_GP_CMD_ID_MANUFACTURE_SPECIFIC_ATTR_REPORTING:
offset = dissect_zbee_nwk_gp_cmd_MS_attr_reporting(tvb, pinfo, cmd_tree, packet, offset);
break;
case ZB_GP_CMD_ID_MULTI_CLUSTER_REPORTING:
offset = dissect_zbee_nwk_gp_cmd_multi_cluster_reporting(tvb, pinfo, cmd_tree, packet, offset, ZBEE_MFG_CODE_NONE);
break;
case ZB_GP_CMD_ID_MANUFACTURER_SPECIFIC_MCLUSTER_REPORTING:
offset = dissect_zbee_nwk_gp_cmd_MS_multi_cluster_reporting(tvb, pinfo, cmd_tree, packet, offset);
break;
case ZB_GP_CMD_ID_READ_ATTRIBUTES_RESPONSE:
offset = dissect_zbee_nwk_gp_cmd_read_attributes_response(tvb, pinfo, cmd_tree, packet, offset);
break;
case ZB_GP_CMD_ID_ANY_SENSOR_COMMAND_A0_A3:
/* TODO: implement it. */
break;
case ZB_GP_CMD_ID_COMMISSIONING:
offset = dissect_zbee_nwk_gp_cmd_commissioning(tvb, pinfo, cmd_tree, packet, offset);
break;
case ZB_GP_CMD_ID_CHANNEL_REQUEST:
offset = dissect_zbee_nwk_gp_cmd_channel_request(tvb, pinfo, cmd_tree, packet, offset);
break;
case ZB_GP_CMD_ID_REQUEST_ATTRIBUTES:
/* GPDF commands sent to GPD. */
case ZB_GP_CMD_ID_READ_ATTRIBUTES:
offset = dissect_zbee_nwk_gp_cmd_read_attributes(tvb, pinfo, cmd_tree, packet, offset);
break;
case ZB_GP_CMD_ID_COMMISSIONING_REPLY:
offset = dissect_zbee_nwk_gp_cmd_commissioning_reply(tvb, pinfo, cmd_tree, packet, offset);
break;
case ZB_GP_CMD_ID_WRITE_ATTRIBUTES:
offset = dissect_zbee_nwk_gp_cmd_write_attributes(tvb, pinfo, cmd_tree, packet, offset);
break;
case ZB_GP_CMD_ID_CHANNEL_CONFIGURATION:
offset = dissect_zbee_nwk_gp_cmd_channel_configuration(tvb, pinfo, cmd_tree, packet, offset);
break;
}
if (offset < tvb_reported_length(tvb)) {
/* There are leftover bytes! */
proto_tree *root;
tvbuff_t *leftover_tvb = tvb_new_subset_remaining(tvb, offset);
/* Correct the length of the command tree. */
root = proto_tree_get_root(tree);
proto_item_set_len(cmd_root, offset);
/* Dump the tail. */
call_data_dissector(leftover_tvb, pinfo, root);
}
return offset;
} /* dissect_zbee_nwk_gp_cmd */
/**
*ZigBee NWK packet dissection routine for Green Power profile.
*
*@param tvb pointer to buffer containing raw packet.
*@param pinfo pointer to packet information fields.
*@param tree pointer to data tree Wireshark uses to display packet.
*@param data raw packet private data.
*/
static int
dissect_zbee_nwk_gp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
{
gboolean gp_decrypted;
GSList *GSList_i;
guint offset = 0;
guint8 *dec_buffer;
guint8 *enc_buffer;
guint8 fcf;
proto_tree *nwk_tree;
proto_item *proto_root;
proto_item *ti = NULL;
tvbuff_t *payload_tvb;
zbee_nwk_green_power_packet packet;
static const int * fields[] = {
&hf_zbee_nwk_gp_frame_type,
&hf_zbee_nwk_gp_proto_version,
&hf_zbee_nwk_gp_auto_commissioning,
&hf_zbee_nwk_gp_fc_ext,
NULL
};
static const int * ext_fields[] = {
&hf_zbee_nwk_gp_fc_ext_app_id,
&hf_zbee_nwk_gp_fc_ext_sec_level,
&hf_zbee_nwk_gp_fc_ext_sec_key,
&hf_zbee_nwk_gp_fc_ext_rx_after_tx,
&hf_zbee_nwk_gp_fc_ext_direction,
NULL
};
memset(&packet, 0, sizeof(packet));
/* Add ourself to the protocol column, clear the info column and create the protocol tree. */
col_set_str(pinfo->cinfo, COL_PROTOCOL, "ZigBee Green Power");
col_clear(pinfo->cinfo, COL_INFO);
proto_root = proto_tree_add_protocol_format(tree, proto_zbee_nwk_gp, tvb, offset, tvb_captured_length(tvb),
"ZGP stub NWK header");
nwk_tree = proto_item_add_subtree(proto_root, ett_zbee_nwk);
enc_buffer = (guint8 *)tvb_memdup(wmem_packet_scope(), tvb, 0, tvb_captured_length(tvb));
/* Get and parse the FCF. */
fcf = tvb_get_guint8(tvb, offset);
packet.frame_type = zbee_get_bit_field(fcf, ZBEE_NWK_GP_FCF_FRAME_TYPE);
packet.nwk_frame_control_extension = zbee_get_bit_field(fcf, ZBEE_NWK_GP_FCF_CONTROL_EXTENSION);
/* Display the FCF. */
ti = proto_tree_add_bitmask(nwk_tree, tvb, offset, hf_zbee_nwk_gp_fcf, ett_zbee_nwk_fcf, fields, ENC_NA);
proto_item_append_text(ti, " %s", val_to_str(packet.frame_type, zbee_nwk_gp_frame_types, "Unknown Frame Type"));
offset += 1;
/* Add the frame type to the info column and protocol root. */
proto_item_append_text(proto_root, " %s", val_to_str(packet.frame_type, zbee_nwk_gp_frame_types, "Unknown type"));
col_set_str(pinfo->cinfo, COL_INFO, val_to_str_const(packet.frame_type, zbee_nwk_gp_frame_types, "Reserved frame type"));
if (packet.nwk_frame_control_extension) {
/* Display ext FCF. */
fcf = tvb_get_guint8(tvb, offset);
packet.application_id = zbee_get_bit_field(fcf, ZBEE_NWK_GP_FCF_EXT_APP_ID);
packet.security_level = zbee_get_bit_field(fcf, ZBEE_NWK_GP_FCF_EXT_SECURITY_LEVEL);
packet.direction = zbee_get_bit_field(fcf, ZBEE_NWK_GP_FCF_EXT_DIRECTION);
/* Create a subtree for the extended FCF. */
proto_tree_add_bitmask(nwk_tree, tvb, offset, hf_zbee_nwk_gp_fc_ext_field, ett_zbee_nwk_fcf_ext, ext_fields, ENC_NA);
offset += 1;
}
if ((packet.frame_type == ZBEE_NWK_GP_FCF_DATA && !packet.nwk_frame_control_extension) || (packet.frame_type ==
ZBEE_NWK_GP_FCF_DATA && packet.nwk_frame_control_extension && packet.application_id ==
ZBEE_NWK_GP_APP_ID_DEFAULT) || (packet.frame_type == ZBEE_NWK_GP_FCF_MAINTENANCE &&
packet.nwk_frame_control_extension && packet.application_id == ZBEE_NWK_GP_APP_ID_DEFAULT && tvb_get_guint8(tvb,
offset) != ZB_GP_CMD_ID_CHANNEL_CONFIGURATION)) {
/* Display GPD Src ID. */
packet.source_id = tvb_get_letohl(tvb, offset);
proto_tree_add_item(nwk_tree, hf_zbee_nwk_gp_zgpd_src_id, tvb, offset, 4, ENC_LITTLE_ENDIAN);
proto_item_append_text(proto_root, ", GPD Src ID: 0x%08x", packet.source_id);
col_append_fstr(pinfo->cinfo, COL_INFO, ", GPD Src ID: 0x%08x", packet.source_id);
col_clear(pinfo->cinfo, COL_DEF_SRC);
col_append_fstr(pinfo->cinfo, COL_DEF_SRC, "0x%08x", packet.source_id);
offset += 4;
}
if (packet.application_id == ZBEE_NWK_GP_APP_ID_ZGP) {
/* Display GPD endpoint */
packet.endpoint = tvb_get_guint8(tvb, offset);
proto_tree_add_item(nwk_tree, hf_zbee_nwk_gp_zgpd_endpoint, tvb, offset, 1, ENC_LITTLE_ENDIAN);
proto_item_append_text(proto_root, ", Endpoint: %d", packet.endpoint);
col_append_fstr(pinfo->cinfo, COL_INFO, ", Endpoint: %d", packet.endpoint);
offset += 1;
}
/* Display Security Frame Counter. */
packet.mic_size = 0;
if (packet.nwk_frame_control_extension) {
if (packet.application_id == ZBEE_NWK_GP_APP_ID_DEFAULT || packet.application_id == ZBEE_NWK_GP_APP_ID_ZGP
|| packet.application_id == ZBEE_NWK_GP_APP_ID_LPED) {
if (packet.security_level == ZBEE_NWK_GP_SECURITY_LEVEL_1LSB
&& packet.application_id != ZBEE_NWK_GP_APP_ID_LPED) {
packet.mic_size = 2;
} else if (packet.security_level == ZBEE_NWK_GP_SECURITY_LEVEL_FULL || packet.security_level ==
ZBEE_NWK_GP_SECURITY_LEVEL_FULLENCR) {
/* Get Security Frame Counter and display it. */
packet.mic_size = 4;
packet.security_frame_counter = tvb_get_letohl(tvb, offset);
proto_tree_add_item(nwk_tree, hf_zbee_nwk_gp_security_frame_counter, tvb, offset, 4,
ENC_LITTLE_ENDIAN);
offset += 4;
}
}
}
/* Parse application payload. */
packet.payload_len = tvb_reported_length(tvb) - offset - packet.mic_size;
/* Ensure that the payload exists. */
if (packet.payload_len <= 0) {
proto_tree_add_expert(nwk_tree, pinfo, &ei_zbee_nwk_gp_no_payload, tvb, 0, -1);
return offset;
}
/* OK, payload exists. Parse MIC field if needed. */
if (packet.mic_size == 2) {
packet.mic = tvb_get_letohs(tvb, offset + packet.payload_len);
} else if (packet.mic_size == 4) {
packet.mic = tvb_get_letohl(tvb, offset + packet.payload_len);
}
/* Save packet private data. */
data = (void *)&packet;
payload_tvb = tvb_new_subset_length(tvb, offset, packet.payload_len);
if (packet.security_level != ZBEE_NWK_GP_SECURITY_LEVEL_FULLENCR) {
dissect_zbee_nwk_gp_cmd(payload_tvb, pinfo, nwk_tree, data);
}
offset += packet.payload_len;
/* Display MIC field. */
if (packet.mic_size) {
proto_tree_add_uint(nwk_tree, packet.mic_size == 4 ? hf_zbee_nwk_gp_security_mic_4b :
hf_zbee_nwk_gp_security_mic_2b, tvb, offset, packet.mic_size, packet.mic);
offset += packet.mic_size;
}
if ((offset < tvb_captured_length(tvb)) && (packet.security_level != ZBEE_NWK_GP_SECURITY_LEVEL_FULLENCR)) {
proto_tree_add_expert(nwk_tree, pinfo, &ei_zbee_nwk_gp_inval_residual_data, tvb, offset, -1);
return offset;
}
if (packet.security_level == ZBEE_NWK_GP_SECURITY_LEVEL_FULLENCR) {
dec_buffer = (guint8 *)wmem_alloc(pinfo->pool, packet.payload_len);
gp_decrypted = FALSE;
for (GSList_i = zbee_gp_keyring; GSList_i && !gp_decrypted; GSList_i = g_slist_next(GSList_i)) {
gp_decrypted = zbee_gp_decrypt_payload(&packet, enc_buffer, offset - packet.payload_len -
packet.mic_size, dec_buffer, packet.payload_len, packet.mic_size,
((key_record_t *)(GSList_i->data))->key);
}
if (gp_decrypted) {
payload_tvb = tvb_new_child_real_data(tvb, dec_buffer, packet.payload_len, packet.payload_len);
add_new_data_source(pinfo, payload_tvb, "Decrypted GP Payload");
dissect_zbee_nwk_gp_cmd(payload_tvb, pinfo, nwk_tree, data);
} else {
payload_tvb = tvb_new_subset_length_caplen(tvb, offset - packet.payload_len - packet.mic_size, packet.payload_len, -1);
call_data_dissector(payload_tvb, pinfo, tree);
}
}
return tvb_captured_length(tvb);
} /* dissect_zbee_nwk_gp */
/**
*Heuristic interpreter for the ZigBee Green Power dissectors.
*
*@param tvb pointer to buffer containing raw packet.
*@param pinfo pointer to packet information fields.
*@param tree pointer to data tree Wireshark uses to display packet.
*@param data raw packet private data.
*/
static gboolean
dissect_zbee_nwk_heur_gp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data)
{
ieee802154_packet *packet = (ieee802154_packet *)data;
guint8 fcf;
/* We must have the IEEE 802.15.4 headers. */
if (packet == NULL) return FALSE;
/* ZigBee green power never uses 16-bit source addresses. */
if (packet->src_addr_mode == IEEE802154_FCF_ADDR_SHORT) return FALSE;
/* If the frame type and version are not sane, then it's probably not ZGP. */
fcf = tvb_get_guint8(tvb, 0);
if (zbee_get_bit_field(fcf, ZBEE_NWK_GP_FCF_VERSION) != ZBEE_VERSION_GREEN_POWER) return FALSE;
if (!try_val_to_str(zbee_get_bit_field(fcf, ZBEE_NWK_FCF_FRAME_TYPE), zbee_nwk_gp_frame_types)) return FALSE;
/* ZigBee greenpower frames are either sent to broadcast or the extended address. */
if (packet->dst_pan == IEEE802154_BCAST_PAN && packet->dst_addr_mode == IEEE802154_FCF_ADDR_SHORT &&
packet->dst16 == IEEE802154_BCAST_ADDR) {
dissect_zbee_nwk_gp(tvb, pinfo, tree, data);
return TRUE;
}
/* 64-bit destination addressing mode support. */
if (packet->dst_addr_mode == IEEE802154_FCF_ADDR_EXT) {
dissect_zbee_nwk_gp(tvb, pinfo, tree, data);
return TRUE;
}
return FALSE;
} /* dissect_zbee_nwk_heur_gp */
/**
*Init routine for the ZigBee GP profile security.
*
*/
static void
gp_init_zbee_security(void)
{
guint i;
key_record_t key_record;
for (i = 0; gp_uat_key_records && (i < num_uat_key_records); i++) {
key_record.frame_num = 0;
key_record.label = g_strdup(gp_uat_key_records[i].label);
memcpy(key_record.key, gp_uat_key_records[i].key, ZBEE_SEC_CONST_KEYSIZE);
zbee_gp_keyring = g_slist_prepend(zbee_gp_keyring, g_memdup(&key_record, sizeof(key_record_t)));
}
}
static void zbee_free_key_record(gpointer ptr)
{
key_record_t *k;
k = (key_record_t *)ptr;
if (!k)
return;
g_free(k->label);
g_free(k);
}
static void
gp_cleanup_zbee_security(void)
{
if (!zbee_gp_keyring)
return;
g_slist_free_full(zbee_gp_keyring, zbee_free_key_record);
zbee_gp_keyring = NULL;
}
/**
*ZigBee NWK GP protocol registration routine.
*
*/
void
proto_register_zbee_nwk_gp(void)
{
module_t *gp_zbee_prefs;
expert_module_t* expert_zbee_nwk_gp;
static hf_register_info hf[] = {
{ &hf_zbee_nwk_gp_auto_commissioning,
{ "Auto Commissioning", "zbee_nwk_gp.auto_commissioning", FT_BOOLEAN, 8, NULL,
ZBEE_NWK_GP_FCF_AUTO_COMMISSIONING, NULL, HFILL }},
{ &hf_zbee_nwk_gp_fc_ext,
{ "NWK Frame Extension", "zbee_nwk_gp.fc_extension", FT_BOOLEAN, 8, NULL, ZBEE_NWK_GP_FCF_CONTROL_EXTENSION,
NULL, HFILL }},
{ &hf_zbee_nwk_gp_fcf,
{ "Frame Control Field", "zbee_nwk_gp.fcf", FT_UINT8, BASE_HEX, NULL,
0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_frame_type,
{ "Frame Type", "zbee_nwk_gp.frame_type", FT_UINT8, BASE_HEX, VALS(zbee_nwk_gp_frame_types),
ZBEE_NWK_GP_FCF_FRAME_TYPE, NULL, HFILL }},
{ &hf_zbee_nwk_gp_proto_version,
{ "Protocol Version", "zbee_nwk_gp.proto_version", FT_UINT8, BASE_DEC, NULL, ZBEE_NWK_GP_FCF_VERSION, NULL,
HFILL }},
{ &hf_zbee_nwk_gp_fc_ext_field,
{ "Extended NWK Frame Control Field", "zbee_nwk_gp.fc_ext", FT_UINT8, BASE_HEX, NULL,
0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_fc_ext_app_id,
{ "Application ID", "zbee_nwk_gp.fc_ext_app_id", FT_UINT8, BASE_HEX, VALS(zbee_nwk_gp_app_id_names),
ZBEE_NWK_GP_FCF_EXT_APP_ID, NULL, HFILL }},
{ &hf_zbee_nwk_gp_fc_ext_direction,
{ "Direction", "zbee_nwk_gp.fc_ext_direction", FT_UINT8, BASE_HEX, VALS(zbee_nwk_gp_directions),
ZBEE_NWK_GP_FCF_EXT_DIRECTION, NULL, HFILL }},
{ &hf_zbee_nwk_gp_fc_ext_rx_after_tx,
{ "Rx After Tx", "zbee_nwk_gp.fc_ext_rxaftertx", FT_BOOLEAN, 8, NULL, ZBEE_NWK_GP_FCF_EXT_RX_AFTER_TX, NULL,
HFILL }},
{ &hf_zbee_nwk_gp_fc_ext_sec_key,
{ "Security Key", "zbee_nwk_gp.fc_ext_security_key", FT_BOOLEAN, 8, NULL, ZBEE_NWK_GP_FCF_EXT_SECURITY_KEY,
NULL, HFILL }},
{ &hf_zbee_nwk_gp_fc_ext_sec_level,
{ "Security Level", "zbee_nwk_gp.fc_ext_security_level", FT_UINT8, BASE_HEX,
VALS(zbee_nwk_gp_src_sec_levels_names), ZBEE_NWK_GP_FCF_EXT_SECURITY_LEVEL, NULL, HFILL }},
{ &hf_zbee_nwk_gp_zgpd_src_id,
{ "Src ID", "zbee_nwk_gp.source_id", FT_UINT32, BASE_HEX, VALS(zbee_nwk_gp_src_id_names), 0x0, NULL,
HFILL }},
{ &hf_zbee_nwk_gp_zgpd_endpoint,
{ "Endpoint", "zbee_nwk_gp.endpoint", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_security_frame_counter,
{ "Security Frame Counter", "zbee_nwk_gp.security_frame_counter", FT_UINT32, BASE_DEC, NULL, 0x0, NULL,
HFILL }},
{ &hf_zbee_nwk_gp_security_mic_2b,
{ "Security MIC", "zbee_nwk_gp.security_mic2", FT_UINT16, BASE_HEX, NULL, 0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_security_mic_4b,
{ "Security MIC", "zbee_nwk_gp.security_mic4", FT_UINT32, BASE_HEX, NULL, 0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_command_id,
{ "ZGPD Command ID", "zbee_nwk_gp.command_id", FT_UINT8, BASE_HEX | BASE_EXT_STRING, &zbee_nwk_gp_cmd_names_ext, 0x0, NULL,
HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_device_id,
{ "ZGPD Device ID", "zbee_nwk_gp.cmd.comm.dev_id", FT_UINT8, BASE_HEX | BASE_EXT_STRING, &zbee_nwk_gp_device_ids_names_ext,
0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_ext_opt_gpd_key_encr,
{ "GPD Key Encryption", "zbee_nwk_gp.cmd.comm.ext_opt.gpd_key_encr", FT_BOOLEAN, 8, NULL,
ZBEE_NWK_GP_CMD_COMMISSIONING_EXT_OPT_GPD_KEY_ENCR, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_ext_opt_gpd_key_present,
{ "GPD Key Present", "zbee_nwk_gp.cmd.comm.ext_opt.gpd_key_present", FT_BOOLEAN, 8, NULL,
ZBEE_NWK_GP_CMD_COMMISSIONING_EXT_OPT_GPD_KEY_PRESENT, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_ext_opt_key_type,
{ "Key Type", "zbee_nwk_gp.cmd.comm.ext_opt.key_type", FT_UINT8, BASE_HEX,
VALS(zbee_nwk_gp_src_sec_keys_type_names), ZBEE_NWK_GP_CMD_COMMISSIONING_EXT_OPT_KEY_TYPE, NULL,
HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_outgoing_counter,
{ "GPD Outgoing Counter", "zbee_nwk_gp.cmd.comm.out_counter", FT_UINT32, BASE_HEX, NULL, 0x0, NULL,
HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_ext_opt_sec_level_cap,
{ "Security Level Capabilities", "zbee_nwk_gp.cmd.comm.ext_opt.seclevel_cap", FT_UINT8, BASE_HEX, NULL,
ZBEE_NWK_GP_CMD_COMMISSIONING_EXT_OPT_SEC_LEVEL_CAP, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_security_key,
{ "Security Key", "zbee_nwk_gp.cmd.comm.security_key", FT_BYTES, BASE_NONE, NULL, 0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_gpd_sec_key_mic,
{ "GPD Key MIC", "zbee_nwk_gp.cmd.comm.gpd_key_mic", FT_UINT32, BASE_HEX, NULL, 0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_opt_ext_opt,
{ "Extended Option Field", "zbee_nwk_gp.cmd.comm.opt.ext_opt_field", FT_BOOLEAN, 8, NULL,
ZBEE_NWK_GP_CMD_COMMISSIONING_OPT_EXT_OPTIONS, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_opt,
{ "Options Field", "zbee_nwk_gp.cmd.comm.opt", FT_UINT8, BASE_HEX, NULL,
0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_opt_fixed_location,
{ "Fixed Location", "zbee_nwk_gp.cmd.comm.opt.fixed_location", FT_BOOLEAN, 8, NULL,
ZBEE_NWK_GP_CMD_COMMISSIONING_OPT_FIXED_LOCATION, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_opt_mac_sec_num_cap,
{ "MAC Sequence number capability", "zbee_nwk_gp.cmd.comm.opt.mac_seq_num_cap", FT_BOOLEAN, 8, NULL,
ZBEE_NWK_GP_CMD_COMMISSIONING_OPT_MAC_SEQ, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_opt_appli_info_present,
{ "Application information present", "zbee_nwk_gp.cmd.comm.opt.appli_info_present", FT_BOOLEAN, 8, NULL,
ZBEE_NWK_GP_CMD_COMMISSIONING_OPT_APPLICATION_INFO, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_opt_panid_req,
{ "PANId request", "zbee_nwk_gp.cmd.comm.opt.panid_req", FT_BOOLEAN, 8, NULL,
ZBEE_NWK_GP_CMD_COMMISSIONING_OPT_PAN_ID_REQ, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_opt_rx_on_cap,
{ "RxOnCapability", "zbee_nwk_gp.cmd.comm.opt.rxon_cap", FT_BOOLEAN, 8, NULL,
ZBEE_NWK_GP_CMD_COMMISSIONING_OPT_RX_ON_CAP, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_opt_sec_key_req,
{ "GP Security Key Request", "zbee_nwk_gp.cmd.comm.opt.seq_key_req", FT_BOOLEAN, 8, NULL,
ZBEE_NWK_GP_CMD_COMMISSIONING_OPT_GP_SEC_KEY_REQ, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_ext_opt,
{ "Extended Options Field", "zbee_nwk_gp.cmd.comm.ext_opt", FT_UINT8, BASE_HEX, NULL,
0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_ext_opt_outgoing_counter,
{ "GPD Outgoing present", "zbee_nwk_gp.cmd.comm.ext_opt.outgoing_counter", FT_BOOLEAN, 8, NULL,
ZBEE_NWK_GP_CMD_COMMISSIONING_EXT_OPT_OUT_COUNTER, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_manufacturer_greenpeak_dev_id,
{ "Manufacturer Model ID", "zbee_nwk_gp.cmd.comm.manufacturer_model_id", FT_UINT16, BASE_HEX,
VALS(zbee_nwk_gp_manufacturer_greenpeak_dev_names), 0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_manufacturer_dev_id,
{ "Manufacturer Model ID", "zbee_nwk_gp.cmd.comm.manufacturer_model_id", FT_UINT16, BASE_HEX,
NULL, 0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_manufacturer_id,
{ "Manufacturer ID", "zbee_nwk_gp.cmd.comm.manufacturer_id", FT_UINT16, BASE_HEX,
VALS(zbee_mfr_code_names), 0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_appli_info_crp,
{ "Cluster reports present", "zbee_nwk_gp.cmd.comm.appli_info.crp", FT_BOOLEAN, 8, NULL,
ZBEE_NWK_GP_CMD_COMMISSIONING_APPLI_INFO_CRP , NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_appli_info_gclp,
{ "GP commands list present", "zbee_nwk_gp.cmd.comm.appli_info.gclp", FT_BOOLEAN, 8, NULL,
ZBEE_NWK_GP_CMD_COMMISSIONING_APPLI_INFO_GCLP , NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_appli_info,
{ "Application information Field", "zbee_nwk_gp.cmd.comm.appli_info", FT_UINT8, BASE_HEX, NULL,
0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_appli_info_mip,
{ "Manufacturer ID present", "zbee_nwk_gp.cmd.comm.appli_info.mip", FT_BOOLEAN, 8, NULL,
ZBEE_NWK_GP_CMD_COMMISSIONING_APPLI_INFO_MIP , NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_appli_info_mmip,
{ "Manufacturer Model ID present", "zbee_nwk_gp.cmd.comm.appli_info.mmip", FT_BOOLEAN, 8, NULL,
ZBEE_NWK_GP_CMD_COMMISSIONING_APPLI_INFO_MMIP , NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_gpd_cmd_num,
{ "Number of GPD commands", "zbee_nwk_gp.cmd.comm.gpd_cmd_num", FT_UINT8, BASE_DEC, NULL,
0x0 , NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_gpd_cmd_id_list,
{ "GPD CommandID list", "zbee_nwk_gp.cmd.comm.gpd_cmd_id_list", FT_NONE, BASE_NONE, NULL,
0x0 , NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_length_of_clid_list,
{ "Length of ClusterID list", "zbee_nwk_gp.cmd.comm.length_of_clid_list", FT_UINT8, BASE_HEX, NULL,
0x0 , NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_length_of_clid_list_server,
{ "Number of server ClusterIDs", "zbee_nwk_gp.cmd.comm.length_of_clid_list_srv", FT_UINT8, BASE_DEC, NULL,
ZBEE_NWK_GP_CMD_COMMISSIONING_CLID_LIST_LEN_SRV, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_length_of_clid_list_client,
{ "Number of client ClusterIDs", "zbee_nwk_gp.cmd.comm.length_of_clid_list_cli", FT_UINT8, BASE_DEC, NULL,
ZBEE_NWK_GP_CMD_COMMISSIONING_CLID_LIST_LEN_CLI, NULL, HFILL }},
{ &hf_zbee_nwk_cmd_comm_clid_list_server,
{ "Cluster ID List Server", "zbee_nwk_gp.cmd.comm.clid_list_server", FT_NONE, BASE_NONE, NULL,
0x0 , NULL, HFILL }},
{ &hf_zbee_nwk_cmd_comm_clid_list_client,
{ "ClusterID List Client", "zbee_nwk_gp.cmd.comm.clid_list_client", FT_NONE, BASE_NONE, NULL,
0x0 , NULL, HFILL }},
{ &hf_zbee_nwk_cmd_comm_cluster_id,
{ "Cluster ID", "zbee_nwk_gp.cmd.comm.cluster_id", FT_UINT16, BASE_HEX, NULL,
0x0 , NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_rep_opt_key_encr,
{ "GPD Key Encryption", "zbee_nwk_gp.cmd.comm_reply.opt.sec_key_encr", FT_BOOLEAN, 8, NULL,
ZBEE_NWK_GP_CMD_COMMISSIONING_REP_OPT_KEY_ENCR, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_rep_opt,
{ "Options Field", "zbee_nwk_gp.cmd.comm_reply.opt", FT_UINT8, BASE_HEX, NULL,
0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_rep_opt_panid_present,
{ "PANID Present", "zbee_nwk_gp.cmd.comm_reply.opt.pan_id_present", FT_BOOLEAN, 8, NULL,
ZBEE_NWK_GP_CMD_COMMISSIONING_REP_OPT_PAN_ID_PRESENT, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_rep_opt_sec_key_present,
{ "GPD Security Key Present", "zbee_nwk_gp.cmd.comm_reply.opt.sec_key_present", FT_BOOLEAN, 8, NULL,
ZBEE_NWK_GP_CMD_COMMISSIONING_REP_OPT_SEC_KEY_PRESENT, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_rep_opt_sec_level,
{ "Security Level", "zbee_nwk_gp.cmd.comm_reply.opt.sec_level", FT_UINT8, BASE_HEX, NULL,
ZBEE_NWK_GP_CMD_COMMISSIONING_REP_OPT_SEC_LEVEL, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_rep_opt_sec_type,
{ "Key Type", "zbee_nwk_gp.cmd.comm_reply.opt.key_type", FT_UINT8, BASE_HEX, NULL,
ZBEE_NWK_GP_CMD_COMMISSIONING_REP_OPT_KEY_TYPE, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_rep_pan_id,
{ "PAN ID", "zbee_nwk_gp.cmd.comm_reply.pan_id", FT_UINT16, BASE_HEX, NULL, 0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_comm_rep_frame_counter,
{ "Frame Counter", "zbee_nwk_gp.cmd.comm_reply.frame_counter", FT_UINT32, BASE_HEX, NULL, 0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_read_att_opt_multi_rec,
{ "Multi-record", "zbee_nwk_gp.cmd.read_att.opt.multi_record", FT_BOOLEAN, 8, NULL,
ZBEE_NWK_GP_CMD_READ_ATTRIBUTE_OPT_MULTI_RECORD, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_read_att_opt_man_field_present,
{ "Manufacturer field present", "zbee_nwk_gp.cmd.read_att.opt.man_field_present", FT_BOOLEAN, 8, NULL,
ZBEE_NWK_GP_CMD_READ_ATTRIBUTE_OPT_MAN_FIELD_PRESENT, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_read_att_opt,
{ "Option field", "zbee_nwk_gp.cmd.read_att.opt", FT_UINT8, BASE_HEX, NULL,
0x0, NULL, HFILL }},
{ &hf_zbee_zcl_gp_cmd_ms_manufacturer_code,
{ "Manufacturer Code", "zbee_nwk_gp.cmd.manufacturer_code", FT_UINT16, BASE_HEX, VALS(zbee_mfr_code_names),
0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_read_att_record_len,
{ "Length of Record List", "zbee_nwk_gp.cmd.read_att.record_len", FT_UINT8, BASE_DEC, NULL, 0x0,
NULL, HFILL }},
{ &hf_zbee_nwk_gp_zcl_attr_status,
{ "Status", "zbee_nwk_gp.zcl.attr.status", FT_UINT8, BASE_HEX, VALS(zbee_zcl_status_names),
0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_zcl_attr_data_type,
{ "Data Type", "zbee_nwk_gp.zcl.attr.datatype", FT_UINT8, BASE_HEX, VALS(zbee_zcl_short_data_type_names),
0x0, NULL, HFILL } },
{ &hf_zbee_nwk_gp_zcl_attr_cluster_id,
{ "ZigBee Cluster ID", "zbee_nwk_gp.zcl.attr.cluster_id", FT_UINT16, BASE_HEX | BASE_RANGE_STRING, RVALS(zbee_aps_cid_names),
0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_channel_request_toggling_behaviour,
{ "Channel Toggling Behaviour", "zbee_nwk_gp.cmd.ch_req", FT_UINT8, BASE_HEX, NULL,
0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_channel_request_toggling_behaviour_1st,
{ "Rx channel in the next attempt", "zbee_nwk_gp.cmd.ch_req.1st", FT_UINT8, BASE_HEX, NULL,
ZBEE_NWK_GP_CMD_CHANNEL_REQUEST_1ST, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_channel_request_toggling_behaviour_2nd,
{ "Rx channel in the second next attempt", "zbee_nwk_gp.ch_req.2nd", FT_UINT8, BASE_HEX, NULL,
ZBEE_NWK_GP_CMD_CHANNEL_REQUEST_2ND, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_operational_channel,
{ "Operational Channel", "zbee_nwk_gp.cmd.configuration_ch", FT_UINT8, BASE_HEX, NULL,
0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_channel_configuration,
{ "Operation channel", "zbee_nwk_gp.cmd.configuration_ch.operation_ch", FT_UINT8, BASE_HEX, NULL,
ZBEE_NWK_GP_CMD_CHANNEL_CONFIGURATION_OPERATION_CH, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_move_color_ratex,
{ "RateX", "zbee_nwk_gp.cmd.move_color.ratex", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_move_color_ratey,
{ "RateY", "zbee_nwk_gp.cmd.move_color.ratey", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_move_up_down_rate,
{ "Rate", "zbee_nwk_gp.cmd.move_up_down.rate", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_step_color_stepx,
{ "StepX", "zbee_nwk_gp.cmd.step_color.stepx", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_step_color_stepy,
{ "StepY", "zbee_nwk_gp.cmd.step_color.stepy", FT_UINT16, BASE_DEC, NULL, 0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_step_color_transition_time,
{ "Transition Time", "zbee_nwk_gp.cmd.step_color.transition_time", FT_UINT16, BASE_DEC, NULL, 0x0, NULL,
HFILL }},
{ &hf_zbee_nwk_gp_cmd_step_up_down_step_size,
{ "Step Size", "zbee_nwk_gp.cmd.step_up_down.step_size", FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL }},
{ &hf_zbee_nwk_gp_cmd_step_up_down_transition_time,
{ "Transition Time", "zbee_nwk_gp.cmd.step_up_down.transition_time", FT_UINT16, BASE_DEC, NULL, 0x0, NULL,
HFILL }}
};
static ei_register_info ei[] = {
{ &ei_zbee_nwk_gp_no_payload,
{ "zbee_nwk_gp.no_payload", PI_MALFORMED, PI_ERROR,
"Payload is missing", EXPFILL }},
{ &ei_zbee_nwk_gp_inval_residual_data,
{ "zbee_nwk_gp.inval_residual_data", PI_MALFORMED, PI_ERROR,
"Invalid residual data", EXPFILL }},
{ &ei_zbee_nwk_gp_com_rep_no_out_cnt,
{ "zbee_nwk_gp.com_rep_no_out_cnt", PI_DEBUG, PI_WARN,
"Missing outgoing frame counter", EXPFILL }}
};
static gint *ett[] = {
&ett_zbee_nwk,
&ett_zbee_nwk_cmd,
&ett_zbee_nwk_cmd_cinfo,
&ett_zbee_nwk_cmd_appli_info,
&ett_zbee_nwk_cmd_options,
&ett_zbee_nwk_fcf,
&ett_zbee_nwk_fcf_ext,
&ett_zbee_nwk_clu_rec,
&ett_zbee_nwk_att_rec,
&ett_zbee_nwk_cmd_comm_gpd_cmd_id_list,
&ett_zbee_nwk_cmd_comm_length_of_clid_list,
&ett_zbee_nwk_cmd_comm_clid_list_server,
&ett_zbee_nwk_cmd_comm_clid_list_client
};
static uat_field_t key_uat_fields[] = {
UAT_FLD_CSTRING(gp_uat_key_records, string, "Key", "A 16-byte key."),
UAT_FLD_VS(gp_uat_key_records, byte_order, "Byte Order", byte_order_vals, "Byte order of a key."),
UAT_FLD_LSTRING(gp_uat_key_records, label, "Label", "User label for a key."),
UAT_END_FIELDS
};
proto_zbee_nwk_gp = proto_register_protocol("ZigBee Green Power Profile", "ZigBee Green Power",
ZBEE_PROTOABBREV_NWK_GP);
gp_zbee_prefs = prefs_register_protocol(proto_zbee_nwk_gp, NULL);
zbee_gp_sec_key_table_uat = uat_new("ZigBee GP Security Keys", sizeof(uat_key_record_t), "zigbee_gp_keys", TRUE,
&gp_uat_key_records, &num_uat_key_records, UAT_AFFECTS_DISSECTION, NULL, uat_key_record_copy_cb,
uat_key_record_update_cb, uat_key_record_free_cb, uat_key_record_post_update_cb, NULL, key_uat_fields);
prefs_register_uat_preference(gp_zbee_prefs, "gp_key_table", "Pre-configured GP Security Keys",
"Pre-configured GP Security Keys.", zbee_gp_sec_key_table_uat);
register_init_routine(gp_init_zbee_security);
register_cleanup_routine(gp_cleanup_zbee_security);
/* Register the Wireshark protocol. */
proto_register_field_array(proto_zbee_nwk_gp, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
expert_zbee_nwk_gp = expert_register_protocol(proto_zbee_nwk_gp);
expert_register_field_array(expert_zbee_nwk_gp, ei, array_length(ei));
/* Register the dissectors. */
register_dissector(ZBEE_PROTOABBREV_NWK_GP, dissect_zbee_nwk_gp, proto_zbee_nwk_gp);
register_dissector(ZBEE_PROTOABBREV_NWK_GP_CMD, dissect_zbee_nwk_gp_cmd, proto_zbee_nwk_gp);
} /* proto_register_zbee_nwk_gp */
/**
*Registers the ZigBee dissector with Wireshark.
*
*/
void
proto_reg_handoff_zbee_nwk_gp(void)
{
/* Register our dissector with IEEE 802.15.4. */
dissector_add_for_decode_as(IEEE802154_PROTOABBREV_WPAN_PANID, find_dissector(ZBEE_PROTOABBREV_NWK_GP));
heur_dissector_add(IEEE802154_PROTOABBREV_WPAN, dissect_zbee_nwk_heur_gp, "ZigBee Green Power over IEEE 802.15.4", "zbee_nwk_gp_wlan", proto_zbee_nwk_gp, HEURISTIC_ENABLE);
} /* proto_reg_handoff_zbee */
/*
* Editor modelines
*
* Local Variables:
* c-basic-offset: 4
* tab-width: 8
* indent-tabs-mode: nil
* End:
*
* ex: set shiftwidth=4 tabstop=8 expandtab:
* :indentSize=4:tabSize=8:noTabs=true:
*/
| 44.075655 | 176 | 0.682297 | [
"model"
] |
c4821716b3520379dd68428c46a33b172bdfb808 | 2,040 | h | C | hv/test/kvm-unit-tests/lib/x86/apic.h | wtliang110/lk_hv | fbbbb280114c44bf321b8f02301a84e3c469d8a2 | [
"MIT"
] | 4 | 2022-02-24T06:16:42.000Z | 2022-02-24T23:49:29.000Z | hv/test/kvm-unit-tests/lib/x86/apic.h | wtliang110/lk_hv | fbbbb280114c44bf321b8f02301a84e3c469d8a2 | [
"MIT"
] | null | null | null | hv/test/kvm-unit-tests/lib/x86/apic.h | wtliang110/lk_hv | fbbbb280114c44bf321b8f02301a84e3c469d8a2 | [
"MIT"
] | null | null | null | #ifndef _X86_APIC_H_
#define _X86_APIC_H_
#include <stdint.h>
#include "apic-defs.h"
extern u8 id_map[MAX_TEST_CPUS];
extern void *g_apic;
extern void *g_ioapic;
typedef struct {
uint8_t vector;
uint8_t delivery_mode:3;
uint8_t dest_mode:1;
uint8_t delivery_status:1;
uint8_t polarity:1;
uint8_t remote_irr:1;
uint8_t trig_mode:1;
uint8_t mask:1;
uint8_t reserve:7;
uint8_t reserved[4];
uint8_t dest_id;
} ioapic_redir_entry_t;
typedef enum trigger_mode {
TRIGGER_EDGE = 0,
TRIGGER_LEVEL,
TRIGGER_MAX,
} trigger_mode_t;
void mask_pic_interrupts(void);
void eoi(void);
uint8_t apic_get_tpr(void);
void apic_set_tpr(uint8_t tpr);
void ioapic_write_redir(unsigned line, ioapic_redir_entry_t e);
void ioapic_write_reg(unsigned reg, uint32_t value);
ioapic_redir_entry_t ioapic_read_redir(unsigned line);
uint32_t ioapic_read_reg(unsigned reg);
void ioapic_set_redir(unsigned line, unsigned vec,
trigger_mode_t trig_mode);
void set_mask(unsigned line, int mask);
void set_irq_line(unsigned line, int val);
void enable_apic(void);
uint32_t apic_read(unsigned reg);
bool apic_read_bit(unsigned reg, int n);
void apic_write(unsigned reg, uint32_t val);
void apic_icr_write(uint32_t val, uint32_t dest);
uint32_t apic_id(void);
int enable_x2apic(void);
void disable_apic(void);
void reset_apic(void);
void init_apic_map(void);
/* Converts byte-addressable APIC register offset to 4-byte offset. */
static inline u32 apic_reg_index(u32 reg)
{
return reg >> 2;
}
static inline u32 x2apic_msr(u32 reg)
{
return APIC_BASE_MSR + (reg >> 4);
}
static inline bool apic_lvt_entry_supported(int idx)
{
return GET_APIC_MAXLVT(apic_read(APIC_LVR)) >= idx;
}
static inline bool x2apic_reg_reserved(u32 reg)
{
switch (reg) {
case 0x000 ... 0x010:
case 0x040 ... 0x070:
case 0x090:
case 0x0c0:
case 0x0e0:
case 0x290 ... 0x2e0:
case 0x310:
case 0x3a0 ... 0x3d0:
case 0x3f0:
return true;
case APIC_CMCI:
return !apic_lvt_entry_supported(6);
default:
return false;
}
}
#endif
| 20.606061 | 70 | 0.753922 | [
"vector"
] |
c492d74dbdebb468ff159b73e22fc838346c9a35 | 96 | h | C | src/Search/BruteForce.h | S1xe/Way-to-Algorithm | e666edfb000b3eaef8cc1413f71b035ec4141718 | [
"MIT"
] | 101 | 2015-11-19T02:40:01.000Z | 2017-12-01T13:43:06.000Z | src/Search/BruteForce.h | S1xe/Way-to-Algorithm | e666edfb000b3eaef8cc1413f71b035ec4141718 | [
"MIT"
] | 3 | 2019-05-31T14:27:56.000Z | 2021-07-28T04:24:55.000Z | src/Search/BruteForce.h | S1xe/Way-to-Algorithm | e666edfb000b3eaef8cc1413f71b035ec4141718 | [
"MIT"
] | 72 | 2016-01-28T15:20:01.000Z | 2017-12-01T13:43:07.000Z | #pragma once
#include <vector>
std::vector<std::vector<int>> BruteForce(int *s, int n, int m);
| 19.2 | 63 | 0.6875 | [
"vector"
] |
c494baef0886a48eaea61d256923391413df13cf | 1,328 | h | C | Code/GeometryCommand/GeoCommandRotateFeature.h | cy15196/FastCAE | 0870752ec2e590f3ea6479e909ebf6c345ac2523 | [
"BSD-3-Clause"
] | 117 | 2020-03-07T12:07:05.000Z | 2022-03-27T07:35:22.000Z | Code/GeometryCommand/GeoCommandRotateFeature.h | cy15196/FastCAE | 0870752ec2e590f3ea6479e909ebf6c345ac2523 | [
"BSD-3-Clause"
] | 4 | 2020-03-12T15:36:57.000Z | 2022-02-08T02:19:17.000Z | Code/GeometryCommand/GeoCommandRotateFeature.h | cy15196/FastCAE | 0870752ec2e590f3ea6479e909ebf6c345ac2523 | [
"BSD-3-Clause"
] | 76 | 2020-03-16T01:47:46.000Z | 2022-03-21T16:37:07.000Z | #ifndef GEOCOMMANDROTATEFEATURE_H_
#define GEOCOMMANDROTATEFEATURE_H_
#include "GeoCommandBase.h"
#include <QList>
#include <QHash>
#include <QPair>
namespace Geometry
{
class GeometrySet;
}
namespace Command
{
class GEOMETRYCOMMANDAPI CommandRotateFeature : public GeoCommandBase
{
public:
CommandRotateFeature(GUI::MainWindow* m, MainWidget::PreWindow* p);
~CommandRotateFeature() = default;
bool execute() override;
void undo() override;
void redo() override;
void releaseResult() override;
void setBodys(QMultiHash<Geometry::GeometrySet*, int> bodyhash);
void setVector(double* vec);
void setBasicPoint(double* bp);
void setSaveOrigin(bool on);
void setDegree(double d);
void setMethod(int m);
void setEdge(Geometry::GeometrySet* body, int edge);
void setReverse(bool on);
private:
bool generateDir(double* d);
private:
//待删
QList<Geometry::GeometrySet*> _bodys{};
//新加
QMultiHash<Geometry::GeometrySet*, int> _solidHash{};
double _basicPoint[3];
double _degree{ 0.0 };
bool _saveOrigin{ false };
int _method{ 0 };
QPair<Geometry::GeometrySet*, int> _edge{};
double _vector[3];
bool _reverse{ false };
QHash<Geometry::GeometrySet*, Geometry::GeometrySet*> _resultOriginHash{};
bool _releasenew{ false };
bool _releaseEdit{ false };
};
}
#endif | 21.079365 | 76 | 0.724398 | [
"geometry"
] |
c496e83c39182c68a2d6b573d8b2a7e0a2bb50ef | 9,066 | c | C | MultiSource/Benchmarks/MallocBench/gs/zgeneric.c | Nuullll/llvm-test-suite | afbdd0a9ee7770e074708b68b34a6a5312bb0b36 | [
"Apache-2.0"
] | 70 | 2019-01-15T03:03:55.000Z | 2022-03-28T02:16:13.000Z | MultiSource/Benchmarks/MallocBench/gs/zgeneric.c | Nuullll/llvm-test-suite | afbdd0a9ee7770e074708b68b34a6a5312bb0b36 | [
"Apache-2.0"
] | 519 | 2020-09-15T07:40:51.000Z | 2022-03-31T20:51:15.000Z | MultiSource/Benchmarks/MallocBench/gs/zgeneric.c | Nuullll/llvm-test-suite | afbdd0a9ee7770e074708b68b34a6a5312bb0b36 | [
"Apache-2.0"
] | 117 | 2020-06-24T13:11:04.000Z | 2022-03-23T15:44:23.000Z | /* Copyright (C) 1989, 1990 Aladdin Enterprises. All rights reserved.
Distributed by Free Software Foundation, Inc.
This file is part of Ghostscript.
Ghostscript is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY. No author or distributor accepts responsibility
to anyone for the consequences of using it or for whether it serves any
particular purpose or works at all, unless he says so in writing. Refer
to the Ghostscript General Public License for full details.
Everyone is granted permission to copy, modify and redistribute
Ghostscript, but only under the conditions described in the Ghostscript
General Public License. A copy of this license is supposed to have been
given to you along with Ghostscript so you can know your rights and
responsibilities. It should be in a file named COPYING. Among other
things, the copyright notice and this notice must be preserved on all
copies. */
/* zgeneric.c */
/* Array/string/dictionary generic operators for PostScript */
#include "memory_.h"
#include "ghost.h"
#include "errors.h"
#include "oper.h"
#include "dict.h"
#include "estack.h" /* for forall */
#include "store.h"
/* This file implements copy, get, put, getinterval, putinterval, */
/* length, and forall, which apply generically to */
/* arrays, strings, and dictionaries. (Copy also has a special */
/* meaning for copying the top N elements of the stack.) */
/* Forward references */
private int copy_interval(P3(ref *, uint, ref*));
/* copy */
/* Note that this implements copy for arrays and strings, */
/* but not for dictionaries (see zcopy_dict in zdict.c). */
int
zcopy(register ref *op)
{ int code;
switch ( r_type(op) )
{
case t_integer:
{ int count;
if ( (ulong)op->value.intval > op - osbot )
return e_rangecheck;
count = op->value.intval;
if ( op - 1 + count > ostop )
return e_stackoverflow;
memcpy((char *)op, (char *)(op - count), count * sizeof(ref));
push(count - 1);
return 0;
}
case t_array:
case t_packedarray:
case t_string:
code = copy_interval(op, 0, op - 1);
break;
case t_dictionary:
return zcopy_dict(op);
default:
return e_typecheck;
}
if ( code ) return code; /* error */
op->size = op[-1].size;
op[-1] = *op;
r_set_attrs(op - 1, a_subrange);
pop(1);
return 0;
}
/* length */
int
zlength(register ref *op)
{ switch ( r_type(op) )
{
case t_array:
case t_packedarray:
case t_string:
check_read(*op);
make_int(op, op->size);
return 0;
case t_dictionary:
check_dict_read(*op);
make_int(op, dict_length(op));
return 0;
case t_name:
{ /* The PostScript manual doesn't allow length on names, */
/* but the implementations apparently do. */
ref str;
name_string_ref(op, &str);
make_int(op, str.size);
}
return 0;
default:
return e_typecheck;
}
}
/* get */
int
zget(register ref *op)
{ ref *op1 = op - 1;
ref *pvalue;
switch ( r_type(op1) )
{
case t_dictionary:
check_dict_read(*op1);
if ( dict_find(op1, op, &pvalue) <= 0 ) return e_undefined;
break;
case t_array:
case t_packedarray:
check_type(*op, t_integer);
check_read(*op1);
if ( (ulong)(op->value.intval) >= op1->size )
return e_rangecheck;
pvalue = op1->value.refs + (uint)op->value.intval;
break;
case t_string:
check_type(*op, t_integer);
check_read(*op1);
if ( (ulong)(op->value.intval) >= op1->size )
return e_rangecheck;
{ int element = op1->value.bytes[(uint)op->value.intval];
make_int(op1, element);
pop(1);
}
return 0;
default:
return e_typecheck;
}
op[-1] = *pvalue;
pop(1);
return 0;
}
/* put */
int
zput(register ref *op)
{ ref *op1 = op - 1;
ref *op2 = op1 - 1;
switch ( r_type(op2) )
{
case t_dictionary:
check_dict_write(*op2);
{ int code = dict_put(op2, op1, op);
if ( code ) return code; /* error */
}
break;
case t_array:
check_type(*op1, t_integer);
check_write(*op2);
if ( op1->value.intval < 0 || op1->value.intval >= op2->size )
return e_rangecheck;
store_i(op2->value.refs + (uint)op1->value.intval, op);
break;
case t_packedarray: /* packed arrays are read-only */
return e_invalidaccess;
case t_string:
check_type(*op1, t_integer);
check_write(*op2);
if ( op1->value.intval < 0 || op1->value.intval >= op2->size )
return e_rangecheck;
check_type(*op, t_integer);
if ( (ulong)op->value.intval > 0xff )
return e_rangecheck;
op2->value.bytes[(uint)op1->value.intval] = (byte)op->value.intval;
break;
default:
return e_typecheck;
}
pop(3);
return 0;
}
/* getinterval */
int
zgetinterval(register ref *op)
{ ref *op1 = op - 1;
ref *op2 = op1 - 1;
uint index;
uint count;
check_type(*op1, t_integer);
check_type(*op, t_integer);
switch ( r_type(op2) )
{
default: return e_typecheck;
case t_array: case t_packedarray: case t_string: ;
}
check_read(*op2);
if ( (ulong)op1->value.intval > op2->size ) return e_rangecheck;
index = op1->value.intval;
if ( (ulong)op->value.intval > op2->size - index ) return e_rangecheck;
count = op->value.intval;
switch ( r_type(op2) )
{
case t_array:
case t_packedarray: op2->value.refs += index; break;
case t_string: op2->value.bytes += index; break;
}
op2->size = count;
r_set_attrs(op2, a_subrange);
pop(2);
return 0;
}
/* putinterval */
int
zputinterval(register ref *op)
{ ref *opindex = op - 1;
ref *opto = opindex - 1;
int code;
check_type(*opindex, t_integer);
switch ( r_type(opto) )
{
default: return e_typecheck;
case t_packedarray: return e_invalidaccess;
case t_array: case t_string: ;
}
check_write(*opto);
if ( (ulong)opindex->value.intval > opto->size ) return e_rangecheck;
code = copy_interval(opto, (uint)(opindex->value.intval), op);
if ( code >= 0 ) pop(3);
return 0;
}
/* forall */
private int
array_continue(P1(ref *)),
string_continue(P1(ref *)),
dict_continue(P1(ref *));
int
zforall(register ref *op)
{ int (*cproc)(P1(ref *));
ref *obj = op - 1;
uint index;
switch ( r_type(obj) )
{
default:
return e_typecheck;
case t_array:
case t_packedarray:
check_read(*obj);
cproc = array_continue;
index = 0; /* not used */
break;
case t_string:
check_read(*obj);
cproc = string_continue;
index = 0; /* not used */
break;
case t_dictionary:
check_dict_read(*obj);
cproc = dict_continue;
index = dict_first(obj);
break;
}
/* Push a mark, the composite object, the iteration index, */
/* and the procedure, and invoke the continuation operator. */
check_estack(6);
mark_estack(es_for);
*++esp = *obj;
++esp;
make_int(esp, index);
*++esp = *op;
pop(2); op -= 2;
return (*cproc)(op);
}
/* Continuation operator for arrays */
private int
array_continue(register ref *op)
{ ref *obj = esp - 2;
if ( obj->size-- ) /* continue */
{ push(1);
*op = *obj->value.refs;
obj->value.refs++;
push_op_estack(array_continue); /* push continuation */
*++esp = obj[2];
}
else /* done */
{ esp -= 4; /* pop mark, object, index, proc */
}
return o_check_estack;
}
/* Continuation operator for strings */
private int
string_continue(register ref *op)
{ ref *obj = esp - 2;
if ( obj->size-- ) /* continue */
{ push(1);
make_int(op, *obj->value.bytes);
obj->value.bytes++;
push_op_estack(string_continue); /* push continuation */
*++esp = obj[2];
}
else /* done */
{ esp -= 4; /* pop mark, object, index, proc */
}
return o_check_estack;
}
/* Continuation operator for dictionaries */
private int
dict_continue(register ref *op)
{ ref *obj = esp - 2;
int index = (int)esp[-1].value.intval;
push(2); /* make room for key and value */
if ( (index = dict_next(obj, index, op - 1)) >= 0 ) /* continue */
{ esp[-1].value.intval = index;
push_op_estack(dict_continue); /* push continuation */
*++esp = obj[2];
}
else /* done */
{ pop(2); /* undo push */
esp -= 4; /* pop mark, object, index, proc */
}
return o_check_estack;
}
/* ------ Initialization procedure ------ */
void
zgeneric_op_init()
{ static op_def my_defs[] = {
{"1copy", zcopy},
{"2forall", zforall},
{"2get", zget},
{"3getinterval", zgetinterval},
{"1length", zlength},
{"3put", zput},
{"3putinterval", zputinterval},
op_def_end
};
z_op_init(my_defs);
}
/* ------ Shared routines ------ */
/* Copy an interval from one operand to another. */
/* This is used by both putinterval and string/array copy. */
/* One operand is known to be an array or string, */
/* and the starting index is known to be less than or equal to */
/* its length; nothing else has been checked. */
private int
copy_interval(ref *prto, uint index, ref *prfrom)
{ if ( r_type(prfrom) != r_type(prto) ) return e_typecheck;
check_read(*prfrom);
check_write(*prto);
if ( prfrom->size > prto->size - index ) return e_rangecheck;
switch ( r_type(prto) )
{
case t_array:
case t_packedarray:
refcpy(prto->value.refs + index, prfrom->value.refs, prfrom->size);
break;
case t_string:
memcpy(prto->value.bytes + index, prfrom->value.bytes, prfrom->size);
}
return 0;
}
| 24.975207 | 72 | 0.65696 | [
"object"
] |
c49a0bd7fc2f6299c41009cff07ccedfac3e2f6b | 3,282 | h | C | src/plots/Vector/avtVectorFilter.h | visit-dav/vis | c08bc6e538ecd7d30ddc6399ec3022b9e062127e | [
"BSD-3-Clause"
] | 226 | 2018-12-29T01:13:49.000Z | 2022-03-30T19:16:31.000Z | src/plots/Vector/avtVectorFilter.h | visit-dav/vis | c08bc6e538ecd7d30ddc6399ec3022b9e062127e | [
"BSD-3-Clause"
] | 5,100 | 2019-01-14T18:19:25.000Z | 2022-03-31T23:08:36.000Z | src/plots/Vector/avtVectorFilter.h | visit-dav/vis | c08bc6e538ecd7d30ddc6399ec3022b9e062127e | [
"BSD-3-Clause"
] | 84 | 2019-01-24T17:41:50.000Z | 2022-03-10T10:01:46.000Z | // Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers. See the top-level LICENSE file for dates and other
// details. No copyright assignment is required to contribute to VisIt.
// ************************************************************************* //
// avtVectorFilter.h //
// ************************************************************************* //
#ifndef AVT_VECTOR_FILTER_H
#define AVT_VECTOR_FILTER_H
#include <avtDataTreeIterator.h>
class vtkVectorReduceFilter;
class vtkVertexFilter;
// ****************************************************************************
// Class: avtVectorFilter
//
// Purpose:
// A filter that takes in vector data and creates vector glyphs as poly
// data.
//
// Programmer: Hank Childs
// Creation: March 21, 2001
//
// Modifications:
//
// Kathleen Bonnell, Tue Apr 10 11:51:18 PDT 2001
// Renamed ExecuteDomain as ExecuteData.
//
// Hank Childs, Thu Aug 30 17:30:48 PDT 2001
// Added the vertex filter.
//
// Kathleen Bonnell, Mon Aug 9 14:27:08 PDT 2004
// Added magVarName, SetMagVarName and ModifyContract.
//
// Kathleen Bonnell, Tue Oct 12 16:18:37 PDT 2004
// Added keepNodeZone.
//
// Hank Childs, Fri Mar 11 15:00:05 PST 2005
// Instantiate VTK filters on the fly.
//
// Jeremy Meredith, Tue Jul 8 15:15:24 EDT 2008
// Added ability to limit vectors to come from original cell only
// (useful for material-selected vector plots).
//
// Jeremy Meredith, Mon Jul 14 12:40:41 EDT 2008
// Keep track of the approximate number of domains to be plotted.
// This will let us calculate a much closer stride value if the
// user requests a particular number of vectors to be plotted.
//
// Hank Childs, Wed Dec 22 01:27:33 PST 2010
// Add PostExecute method.
//
// Eric Brugger, Tue Aug 19 11:50:28 PDT 2014
// Modified the class to work with avtDataRepresentation.
//
// ****************************************************************************
class avtVectorFilter : public avtDataTreeIterator
{
public:
avtVectorFilter(bool, int);
virtual ~avtVectorFilter();
virtual const char *GetType(void) { return "avtVectorFilter"; };
virtual const char *GetDescription(void)
{ return "Creating vectors"; };
void SetStride(int);
void SetNVectors(int);
void SetLimitToOriginal(bool);
void SetMagVarName(const std::string &);
protected:
bool useStride;
int stride;
int nVectors;
bool origOnly;
bool keepNodeZone;
int approxDomains;
std::string magVarName;
virtual void PreExecute(void);
virtual void PostExecute(void);
virtual avtDataRepresentation *ExecuteData(avtDataRepresentation *);
virtual void UpdateDataObjectInfo(void);
virtual avtContract_p ModifyContract(avtContract_p);
};
#endif
| 33.489796 | 79 | 0.546313 | [
"vector"
] |
c49b6934d6562b521ec0f21118a2d30533503a88 | 32,009 | c | C | src/nrfd/manager.c | vitbaq/knot-hal-source | 0ecf74f88f8ab906ea5ec7727a500da65fea982f | [
"BSD-3-Clause"
] | null | null | null | src/nrfd/manager.c | vitbaq/knot-hal-source | 0ecf74f88f8ab906ea5ec7727a500da65fea982f | [
"BSD-3-Clause"
] | null | null | null | src/nrfd/manager.c | vitbaq/knot-hal-source | 0ecf74f88f8ab906ea5ec7727a500da65fea982f | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2016, CESAR.
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*
*/
#include <stdint.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <glib.h>
#include <gio/gio.h>
#include <json-c/json.h>
#include <sys/socket.h>
#include <sys/un.h>
#include "hal/nrf24.h"
#include "hal/comm.h"
#include "hal/time.h"
#include "nrf24l01_io.h"
#include "hal/linux_log.h"
#include "manager.h"
#define KNOTD_UNIX_ADDRESS "knot"
#define MAC_ADDRESS_SIZE 24
#define BCAST_TIMEOUT 10000
#ifndef MIN
#define MIN(a,b) (((a) < (b)) ? (a) : (b))
#endif
static int mgmtfd;
static guint mgmtwatch;
static guint dbus_id;
static struct in_addr inet_address;
static int tcp_port;
static struct adapter {
struct nrf24_mac mac;
/* File with struct keys */
gchar *file_name;
gboolean powered;
/* Struct with the known peers */
struct {
struct nrf24_mac addr;
guint registration_id;
gchar *alias;
gboolean status;
} known_peers[MAX_PEERS];
guint known_peers_size;
} adapter;
struct peer {
uint64_t mac;
int8_t socket_fd; /* HAL comm socket */
int8_t ksock; /* KNoT raw socket: Unix socket or TCP */
guint kwatch; /* KNoT raw socket watch */
};
static struct peer peers[MAX_PEERS] = {
{.socket_fd = -1},
{.socket_fd = -1},
{.socket_fd = -1},
{.socket_fd = -1},
{.socket_fd = -1}
};
struct beacon {
char *name;
unsigned long last_beacon;
};
static GHashTable *peer_bcast_table;
static uint8_t count_clients;
static GDBusNodeInfo *introspection_data;
/* Introspection data for the service we are exporting */
static const gchar introspection_xml[] =
"<node>"
" <interface name='org.cesar.knot.nrf0.Adapter'>"
" <method name='AddDevice'>"
" <arg type='s' name='mac' direction='in'/>"
" <arg type='s' name='key' direction='in'/>"
" <arg type='s' name='name' direction='in'/>"
" <arg type='b' name='response' direction='out'/>"
" </method>"
" <method name='RemoveDevice'>"
" <arg type='s' name='mac' direction='in'/>"
" <arg type='b' name='response' direction='out'/>"
" </method>"
" <property type='s' name='Address' access='read'/>"
" <property type='s' name='Powered' access='readwrite'/>"
" <method name='GetBroadcastingDevices'>"
" <arg type='s' name='response' direction='out'/>"
" </method>"
" </interface>"
"</node>";
static void beacon_free(void *user_data)
{
struct beacon *peer = user_data;
g_free(peer->name);
g_free(peer);
}
static int write_file(const gchar *addr, const gchar *key, const gchar *name)
{
int array_len;
int i;
int err = -EINVAL;
json_object *jobj, *jobj2;
json_object *obj_keys, *obj_array, *obj_tmp, *obj_mac;
/* Load nodes' info from json file */
jobj = json_object_from_file(adapter.file_name);
if (!jobj)
return -EINVAL;
if (!json_object_object_get_ex(jobj, "keys", &obj_keys))
goto failure;
array_len = json_object_array_length(obj_keys);
/*
* If name and key are NULL it means to remove element
* If only name is NULL, update some element
* Otherwise add some element to file
*/
if (name == NULL && key == NULL) {
jobj2 = json_object_new_object();
obj_array = json_object_new_array();
for (i = 0; i < array_len; i++) {
obj_tmp = json_object_array_get_idx(obj_keys, i);
if (!json_object_object_get_ex(obj_tmp, "mac",
&obj_mac))
goto failure;
/* Parse mac address string into struct nrf24_mac known_peers */
if (g_strcmp0(json_object_get_string(obj_mac), addr)
!= 0)
json_object_array_add(obj_array,
json_object_get(obj_tmp));
}
json_object_object_add(jobj2, "keys", obj_array);
json_object_to_file(adapter.file_name, jobj2);
json_object_put(jobj2);
} else if (name == NULL) {
/* TODO update key of some mac (depends on adding keys to file) */
} else {
obj_tmp = json_object_new_object();
json_object_object_add(obj_tmp, "name",
json_object_new_string(name));
json_object_object_add(obj_tmp, "mac",
json_object_new_string(addr));
json_object_array_add(obj_keys, obj_tmp);
json_object_to_file(adapter.file_name, jobj);
}
err = 0;
failure:
json_object_put(jobj);
return err;
}
static GVariant *handle_device_get_property(GDBusConnection *connection,
const gchar *sender,
const gchar *object_path,
const gchar *interface_name,
const gchar *property_name,
GError **error,
gpointer user_data)
{
GVariant *gvar = NULL;
char str_mac[MAC_ADDRESS_SIZE];
gint dev;
dev = GPOINTER_TO_INT(user_data);
/* TODO implement Alias and Status */
if (g_strcmp0(property_name, "Mac") == 0) {
nrf24_mac2str(&adapter.known_peers[dev].addr, str_mac);
gvar = g_variant_new("s", str_mac);
} else if (g_strcmp0(property_name, "Alias") == 0) {
gvar = g_variant_new("s", adapter.known_peers[dev].alias);
} else if (g_strcmp0(property_name, "Status") == 0) {
gvar = g_variant_new_boolean(adapter.known_peers[dev].status);
} else {
gvar = g_variant_new_string("Unknown property requested");
}
return gvar;
}
static int8_t new_device_object(GDBusConnection *connection, uint32_t free_pos)
{
uint8_t i;
guint registration_id;
GDBusInterfaceInfo *interface;
GDBusPropertyInfo **properties;
gchar object_path[26];
gchar *name[] = {"Mac", "Alias", "Status"};
gchar *signature[] = {"s", "s", "b"};
GDBusInterfaceVTable interface_device_vtable = {
NULL,
handle_device_get_property,
NULL
};
properties = g_new0(GDBusPropertyInfo *, 4);
for (i = 0; i < 3; i++) {
properties[i] = g_new0(GDBusPropertyInfo, 1);
/*
* properties->ref_count is incremented here because when
* registering an object the function only increments
* interface->ref_count. Not doing this leads to the memory
* of properties not being deallocated when we call
* g_dbus_connection_unregister_object.
*/
g_atomic_int_inc(&properties[i]->ref_count);
properties[i]->name = g_strdup(name[i]);
properties[i]->signature = g_strdup(signature[i]);
properties[i]->flags = G_DBUS_PROPERTY_INFO_FLAGS_READABLE;
properties[i]->annotations = NULL;
}
interface = g_new0(GDBusInterfaceInfo, 1);
interface->name = g_strdup("org.cesar.knot.nrf.Device");
interface->methods = NULL;
interface->signals = NULL;
interface->properties = properties;
interface->annotations = NULL;
snprintf(object_path, 26, "/org/cesar/knot/nrf0/mac%d", free_pos);
registration_id = g_dbus_connection_register_object(
connection,
object_path,
interface,
&interface_device_vtable,
GINT_TO_POINTER(free_pos), /* user data */
NULL, /* user data free func */
NULL); /* GError** */
/* Free mem if fail */
if (registration_id <= 0) {
for (i = 0; properties[i] != NULL; i++) {
g_free(properties[i]->name);
g_free(properties[i]->signature);
g_free(properties[i]);
}
g_free(properties);
g_free(interface->name);
g_free(interface);
return -1;
}
adapter.known_peers[free_pos].registration_id = registration_id;
return 0;
}
static gboolean add_known_device(GDBusConnection *connection, const gchar *mac,
const gchar *key, const gchar *name)
{
uint8_t alloc_pos, i;
int32_t free_pos;
gboolean response = FALSE;
struct nrf24_mac new_dev;
if (nrf24_str2mac(mac, &new_dev) < 0)
goto done;
for (i = 0, alloc_pos = 0, free_pos = -1; alloc_pos <
adapter.known_peers_size; i++) {
if (adapter.known_peers[i].addr.address.uint64 ==
new_dev.address.uint64) {
if (write_file(mac, key, NULL) < 0)
hal_log_error("Error writing to file");
response = TRUE;
goto done;
} else if (adapter.known_peers[i].addr.address.uint64 != 0) {
alloc_pos++;
} else if (free_pos < 0) {
/* store available position */
free_pos = i;
}
}
/* If there is no empty space between allocated spaces */
if (free_pos < 0)
free_pos = i;
/* If struct has free space add device to struct */
if (adapter.known_peers_size < MAX_PEERS) {
if (new_device_object(connection, free_pos) < 0)
goto done;
adapter.known_peers[free_pos].addr.address.uint64 =
new_dev.address.uint64;
adapter.known_peers[free_pos].alias = g_strdup(name);
adapter.known_peers[free_pos].status = FALSE;
/* TODO: Set key for this mac */
if (write_file(mac, key, name) < 0)
hal_log_error("Error writing to file");
adapter.known_peers_size++;
response = TRUE;
}
done:
return response;
}
static gboolean remove_known_device(GDBusConnection *connection,
const gchar *mac)
{
uint8_t i;
gboolean response = FALSE;
struct nrf24_mac dev;
if (nrf24_str2mac(mac, &dev) < 0)
return FALSE;
for (i = 0; i < MAX_PEERS; i++) {
if (adapter.known_peers[i].addr.address.uint64 ==
dev.address.uint64) {
if (!g_dbus_connection_unregister_object(connection,
adapter.known_peers[i].registration_id))
break;
/* Remove mac from struct */
adapter.known_peers[i].addr.address.uint64 = 0;
g_free(adapter.known_peers[i].alias);
adapter.known_peers_size--;
if (write_file(mac, NULL, NULL) < 0)
hal_log_error("Error writing to file");
response = TRUE;
break;
}
}
return response;
}
static int peers_to_json(struct json_object *peers_bcast_json)
{
GHashTableIter iter;
gpointer key, value;
struct json_object *jobj;
g_hash_table_iter_init (&iter, peer_bcast_table);
while (g_hash_table_iter_next (&iter, &key, &value)) {
struct beacon *peer = value;
jobj = json_object_new_object();
if (peer == NULL)
continue;
json_object_object_add(jobj, "name",
json_object_new_string(peer->name));
json_object_object_add(jobj, "mac",
json_object_new_string((char *) key));
json_object_object_add(jobj, "last_beacon",
json_object_new_int(peer->last_beacon));
json_object_array_add(peers_bcast_json, jobj);
}
return 0;
}
static void handle_method_call(GDBusConnection *connection,
const gchar *sender,
const gchar *object_path,
const gchar *interface_name,
const gchar *method_name,
GVariant *parameters,
GDBusMethodInvocation *invocation,
gpointer user_data)
{
const gchar *mac;
const gchar *key;
const gchar *name;
gboolean response;
struct json_object *peers_bcast;
if (g_strcmp0(method_name, "AddDevice") == 0) {
g_variant_get(parameters, "(&s&s&s)", &mac, &key,&name);
/* Add or Update mac address */
response = add_known_device(connection, mac, key, name);
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(b)", response));
} else if (g_strcmp0(method_name, "RemoveDevice") == 0) {
g_variant_get(parameters, "(&s)", &mac);
/* Remove device */
response = remove_known_device(connection, mac);
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(b)", response));
} else if (g_strcmp0("GetBroadcastingDevices", method_name) == 0) {
/* FIXME: Temporary solution it will be replaced by signals */
/* Get list of devices that sent presence recently */
peers_bcast = json_object_new_array();
peers_to_json(peers_bcast);
g_dbus_method_invocation_return_value(invocation,
g_variant_new("(s)",
json_object_to_json_string(peers_bcast)));
json_object_put(peers_bcast);
}
}
static GVariant *handle_get_property(GDBusConnection *connection,
const gchar *sender,
const gchar *object_path,
const gchar *interface_name,
const gchar *property_name,
GError **gerr,
gpointer user_data)
{
GVariant *gvar = NULL;
char str_mac[MAC_ADDRESS_SIZE];
if (g_strcmp0(property_name, "Address") == 0) {
nrf24_mac2str(&adapter.mac, str_mac);
gvar = g_variant_new("s", str_mac);
} else if (g_strcmp0(property_name, "Powered") == 0) {
gvar = g_variant_new_boolean(adapter.powered);
} else {
gvar = g_variant_new_string("Unknown property requested");
}
return gvar;
}
static gboolean handle_set_property(GDBusConnection *connection,
const gchar *sender,
const gchar *object_path,
const gchar *interface_name,
const gchar *property_name,
GVariant *value,
GError **gerr,
gpointer user_data)
{
if (g_strcmp0(property_name, "Powered") == 0) {
adapter.powered = g_variant_get_boolean(value);
/* TODO turn adapter on or off */
}
return TRUE;
}
static const GDBusInterfaceVTable interface_vtable = {
handle_method_call,
handle_get_property,
handle_set_property
};
static void on_bus_acquired(GDBusConnection *connection, const gchar *name,
gpointer user_data)
{
uint8_t i, j, k;
guint registration_id;
GDBusInterfaceInfo *interface;
GDBusPropertyInfo **properties;
gchar object_path[26];
gchar *obj_name[] = {"Mac", "Alias", "Status"};
gchar *signature[] = {"s", "s", "b"};
GDBusInterfaceVTable interface_device_vtable = {
NULL,
handle_device_get_property,
NULL
};
registration_id = g_dbus_connection_register_object(connection,
"/org/cesar/knot/nrf0",
introspection_data->interfaces[0],
&interface_vtable,
NULL, /* user_data */
NULL, /* user_data_free_func */
NULL); /* GError** */
g_assert(registration_id > 0);
/* Register on dbus every device already known */
for (j = 0, k = 0; j < adapter.known_peers_size; j++, k++) {
properties = g_new0(GDBusPropertyInfo *, 4);
for (i = 0; i < 3; i++) {
properties[i] = g_new0(GDBusPropertyInfo, 1);
/*
* properties->ref_count is incremented here because
* when registering an object the function only
* increments interface->ref_count. Not doing this leads
* to the memory of properties not being deallocated
* when we call g_dbus_connection_unregister_object.
*/
g_atomic_int_inc(&properties[i]->ref_count);
properties[i]->name = g_strdup(obj_name[i]);
properties[i]->signature = g_strdup(signature[i]);
properties[i]->flags =
G_DBUS_PROPERTY_INFO_FLAGS_READABLE;
properties[i]->annotations = NULL;
}
interface = g_new0(GDBusInterfaceInfo, 1);
interface->name = g_strdup("org.cesar.knot.mac.Device");
interface->methods = NULL;
interface->signals = NULL;
interface->properties = properties;
interface->annotations = NULL;
snprintf(object_path, 26, "/org/cesar/knot/nrf0/mac%d", k);
registration_id = g_dbus_connection_register_object(
connection,
object_path,
interface,
&interface_device_vtable,
GINT_TO_POINTER(k),
NULL, /* user data free func */
NULL); /* GError** */
if (registration_id <= 0) {
for (i = 0; properties[i] != NULL; i++) {
g_free(properties[i]->name);
g_free(properties[i]->signature);
g_free(properties[i]);
}
g_free(properties);
g_free(interface->name);
g_free(interface);
k--;
continue;
}
adapter.known_peers[k].registration_id = registration_id;
}
}
static void on_name_acquired(GDBusConnection *connection, const gchar *name,
gpointer user_data)
{
/* Connection successfully estabilished */
hal_log_info("Connection estabilished");
}
static void on_name_lost(GDBusConnection *connection, const gchar *name,
gpointer user_data)
{
if (!connection) {
/* Connection error */
hal_log_error("Connection failure");
} else {
/* Name not owned */
hal_log_error("Name can't be obtained");
}
g_free(adapter.file_name);
g_dbus_node_info_unref(introspection_data);
exit(EXIT_FAILURE);
}
static guint dbus_init(struct nrf24_mac mac)
{
guint owner_id;
introspection_data = g_dbus_node_info_new_for_xml(introspection_xml,
NULL);
g_assert(introspection_data != NULL);
owner_id = g_bus_own_name(G_BUS_TYPE_SYSTEM,
"org.cesar.knot.nrf",
G_BUS_NAME_OWNER_FLAGS_NONE,
on_bus_acquired, on_name_acquired,
on_name_lost, NULL, NULL);
adapter.mac = mac;
adapter.powered = TRUE;
return owner_id;
}
static void dbus_on_close(guint owner_id)
{
uint8_t i;
for (i = 0; i < MAX_PEERS; i++) {
if (adapter.known_peers[i].addr.address.uint64 != 0)
g_free(adapter.known_peers[i].alias);
}
g_free(adapter.file_name);
g_bus_unown_name(owner_id);
g_dbus_node_info_unref(introspection_data);
}
/* Check if peer is on list of known peers */
static int8_t check_permission(struct nrf24_mac mac)
{
uint8_t i;
for (i = 0; i < MAX_PEERS; i++) {
if (mac.address.uint64 ==
adapter.known_peers[i].addr.address.uint64)
return 0;
}
return -EPERM;
}
/* Get peer position in vector of peers */
static int8_t get_peer(struct nrf24_mac mac)
{
int8_t i;
for (i = 0; i < MAX_PEERS; i++)
if (peers[i].socket_fd != -1 &&
peers[i].mac == mac.address.uint64)
return i;
return -EINVAL;
}
/* Get free position in vector for peers */
static int8_t get_peer_index(void)
{
int8_t i;
for (i = 0; i < MAX_PEERS; i++)
if (peers[i].socket_fd == -1)
return i;
return -EUSERS;
}
static int unix_connect(void)
{
struct sockaddr_un addr;
int sock;
sock = socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0);
if (sock < 0)
return -errno;
/* Represents unix socket from nrfd to knotd */
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strncpy(addr.sun_path + 1, KNOTD_UNIX_ADDRESS,
strlen(KNOTD_UNIX_ADDRESS));
if (connect(sock, (struct sockaddr *) &addr, sizeof(addr)) == -1)
return -errno;
return sock;
}
static int tcp_init(const char *host)
{
struct hostent *hostent; /* Host information */
int err;
hostent = gethostbyname(host);
if (hostent == NULL) {
err = errno;
hal_log_error("gethostbyname(): %s(%d)", strerror(err), err);
return -err;
}
inet_address.s_addr = *((unsigned long *) hostent-> h_addr_list[0]);
return 0;
}
static int tcp_connect(void)
{
struct sockaddr_in server;
int err, sock, enable = 1;
sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0) {
err = errno;
hal_log_error("socket(): %s(%d)", strerror(err), err);
return -err;
}
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_address.s_addr;
server.sin_port = htons(tcp_port);
if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &enable,
sizeof(enable)) == -1) {
err = errno;
hal_log_error("tcp setsockopt(iTCP_NODELAY): %s(%d)",
strerror(err), err);
close(sock);
return -err;
}
err = connect(sock, (struct sockaddr *) &server, sizeof(server));
if (err < 0)
return -errno;
return sock;
}
static void kwatch_io_destroy(gpointer user_data)
{
struct peer *p = (struct peer *) user_data;
hal_comm_close(p->socket_fd);
close(p->ksock);
p->socket_fd = -1;
p->kwatch = 0;
count_clients--;
}
static gboolean kwatch_io_read(GIOChannel *io, GIOCondition cond,
gpointer user_data)
{
struct peer *p = (struct peer *) user_data;
GError *gerr = NULL;
GIOStatus status;
char buffer[128];
size_t rx;
ssize_t tx;
if (cond & (G_IO_ERR | G_IO_HUP | G_IO_NVAL))
return FALSE;
/* Reading data from knotd */
status = g_io_channel_read_chars(io, buffer, sizeof(buffer),
&rx, &gerr);
if (status != G_IO_STATUS_NORMAL) {
hal_log_error("glib read(): %s", gerr->message);
g_error_free(gerr);
return FALSE;
}
/* Send data to thing */
/* TODO: put data in list for transmission */
tx = hal_comm_write(p->socket_fd, buffer, rx);
if (tx < 0)
hal_log_error("hal_comm_write(): %zd", tx);
return TRUE;
}
static int8_t evt_presence(struct mgmt_nrf24_header *mhdr)
{
GIOCondition cond = G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL;
GIOChannel *io;
int8_t position;
uint8_t i;
int sock, nsk;
char mac_str[MAC_ADDRESS_SIZE];
struct beacon *peer;
struct mgmt_evt_nrf24_bcast_presence *evt_pre =
(struct mgmt_evt_nrf24_bcast_presence *) mhdr->payload;
nrf24_mac2str(&evt_pre->mac, mac_str);
peer = g_hash_table_lookup(peer_bcast_table, mac_str);
if (peer != NULL) {
peer->last_beacon = hal_time_ms();
goto done;
}
peer = g_try_new0(struct beacon, 1);
if (peer == NULL)
return -ENOMEM;
/*
* Print every MAC sending presence in order to ease the discover of
* things trying to connect to the gw.
*/
peer->last_beacon = hal_time_ms();
/* Creating a UTF-8 copy of the name */
peer->name = g_utf8_make_valid((const char *) evt_pre->name,
strlen((const char *) evt_pre->name));
if (!peer->name)
peer->name = g_strdup("unknown");
hal_log_info("Thing sending presence. MAC = %s Name = %s",
mac_str, peer->name);
/*
* MAC and device name will be printed only once, but the last presence
* time is updated. Every time a user refresh the list in the webui
* we will discard devices that broadcasted
*/
g_hash_table_insert(peer_bcast_table, g_strdup(mac_str), peer);
done:
/* Check if peer is allowed to connect */
if (check_permission(evt_pre->mac) < 0)
return -EPERM;
if (count_clients >= MAX_PEERS)
return -EUSERS; /* MAX PEERS */
/* Check if this peer is already allocated */
position = get_peer(evt_pre->mac);
/* If this is a new peer */
if (position < 0) {
/* Get free peers position */
position = get_peer_index();
if (position < 0)
return position;
/* Radio socket: nRF24 */
nsk = hal_comm_socket(HAL_COMM_PF_NRF24, HAL_COMM_PROTO_RAW);
if (nsk < 0) {
hal_log_error("hal_comm_socket(nRF24): %s(%d)",
strerror(nsk), nsk);
return nsk;
}
/* Upper layer socket: knotd */
if (inet_address.s_addr)
sock = tcp_connect();
else
sock = unix_connect();
if (sock < 0) {
hal_log_error("connect(): %s(%d)", strerror(sock), sock);
hal_comm_close(nsk);
return sock;
}
peers[position].ksock = sock;
peers[position].socket_fd = nsk;
/* Set mac value for this position */
peers[position].mac =
evt_pre->mac.address.uint64;
/* Watch knotd socket */
io = g_io_channel_unix_new(peers[position].ksock);
g_io_channel_set_flags(io, G_IO_FLAG_NONBLOCK, NULL);
g_io_channel_set_close_on_unref(io, TRUE);
g_io_channel_set_encoding(io, NULL, NULL);
g_io_channel_set_buffered(io, FALSE);
peers[position].kwatch = g_io_add_watch_full(io,
G_PRIORITY_DEFAULT,
cond,
kwatch_io_read,
&peers[position],
kwatch_io_destroy);
g_io_channel_unref(io);
count_clients++;
for (i = 0; i < MAX_PEERS; i++) {
if (evt_pre->mac.address.uint64 ==
adapter.known_peers[i].addr.address.uint64) {
adapter.known_peers[i].status = TRUE;
break;
}
}
/* Remove device when the connection is established */
g_hash_table_remove(peer_bcast_table, mac_str);
}
/* Send Connect */
return hal_comm_connect(peers[position].socket_fd,
&evt_pre->mac.address.uint64);
}
static int8_t evt_disconnected(struct mgmt_nrf24_header *mhdr)
{
char mac_str[MAC_ADDRESS_SIZE];
int8_t position;
struct mgmt_evt_nrf24_disconnected *evt_disc =
(struct mgmt_evt_nrf24_disconnected *) mhdr->payload;
nrf24_mac2str(&evt_disc->mac, mac_str);
hal_log_info("Peer disconnected(%s)", mac_str);
if (count_clients == 0)
return -EINVAL;
position = get_peer(evt_disc->mac);
if (position < 0)
return position;
g_source_remove(peers[position].kwatch);
return 0;
}
/* Read RAW from Clients */
static int8_t clients_read()
{
int8_t i;
uint8_t buffer[256];
int rx, err;
/* No client */
if (count_clients == 0)
return 0;
for (i = 0; i < MAX_PEERS; i++) {
struct peer *p = &peers[i];
if (p->socket_fd == -1)
continue;
rx = hal_comm_read(p->socket_fd, &buffer, sizeof(buffer));
if (rx < 0)
continue;
if (write(p->ksock, buffer, rx) < 0) {
err = errno;
hal_log_error("write to knotd: %s(%d)",
strerror(err), err);
continue;
}
}
return 0;
}
static int8_t mgmt_read(void)
{
uint8_t buffer[256];
struct mgmt_nrf24_header *mhdr = (struct mgmt_nrf24_header *) buffer;
ssize_t rbytes;
rbytes = hal_comm_read(mgmtfd, buffer, sizeof(buffer));
/* mgmt on bad state? */
if (rbytes < 0 && rbytes != -EAGAIN)
return rbytes;
/* Nothing to read? */
if (rbytes == -EAGAIN)
return rbytes;
/* Return/ignore if it is not an event? */
if (!(mhdr->opcode & 0x0200))
return -EPROTO;
switch (mhdr->opcode) {
case MGMT_EVT_NRF24_BCAST_PRESENCE:
evt_presence(mhdr);
break;
case MGMT_EVT_NRF24_BCAST_SETUP:
break;
case MGMT_EVT_NRF24_BCAST_BEACON:
break;
case MGMT_EVT_NRF24_DISCONNECTED:
evt_disconnected(mhdr);
break;
}
return 0;
}
static gboolean read_idle(gpointer user_data)
{
mgmt_read();
clients_read();
return TRUE;
}
static int radio_init(const char *spi, uint8_t channel, uint8_t rfpwr,
const struct nrf24_mac *mac)
{
int err;
err = hal_comm_init("NRF0", mac);
if (err < 0) {
hal_log_error("Cannot init NRF0 radio. (%d)", err);
return err;
}
mgmtfd = hal_comm_socket(HAL_COMM_PF_NRF24, HAL_COMM_PROTO_MGMT);
if (mgmtfd < 0) {
hal_log_error("Cannot create socket for radio (%d)", mgmtfd);
goto done;
}
mgmtwatch = g_idle_add(read_idle, NULL);
hal_log_info("Radio initialized");
return 0;
done:
hal_comm_deinit();
return mgmtfd;
}
static void close_clients(void)
{
int i;
for (i = 0; i < MAX_PEERS; i++) {
if (peers[i].socket_fd != -1)
g_source_remove(peers[i].kwatch);
}
}
static void radio_stop(void)
{
close_clients();
hal_comm_close(mgmtfd);
if (mgmtwatch)
g_source_remove(mgmtwatch);
hal_comm_deinit();
}
static char *load_config(const char *file)
{
char *buffer;
int length;
FILE *fl = fopen(file, "r");
if (fl == NULL) {
hal_log_error("No such file available: %s", file);
return NULL;
}
fseek(fl, 0, SEEK_END);
length = ftell(fl);
fseek(fl, 0, SEEK_SET);
buffer = (char *) malloc((length+1)*sizeof(char));
if (buffer) {
fread(buffer, length, 1, fl);
buffer[length] = '\0';
}
fclose(fl);
return buffer;
}
/* Set TX Power from dBm to values defined at nRF24 datasheet */
static uint8_t dbm_int2rfpwr(int dbm)
{
switch (dbm) {
case 0:
return NRF24_PWR_0DBM;
case -6:
return NRF24_PWR_6DBM;
case -12:
return NRF24_PWR_12DBM;
case -18:
return NRF24_PWR_18DBM;
}
/* Return default value when dBm value is invalid */
return NRF24_PWR_0DBM;
}
static int gen_save_mac(const char *config, const char *file,
struct nrf24_mac *mac)
{
json_object *jobj, *obj_radio, *obj_tmp;
int err = -EINVAL;
jobj = json_tokener_parse(config);
if (jobj == NULL)
return -EINVAL;
if (!json_object_object_get_ex(jobj, "radio", &obj_radio))
goto done;
if (json_object_object_get_ex(obj_radio, "mac", &obj_tmp)) {
char mac_string[MAC_ADDRESS_SIZE];
mac->address.uint64 = 0;
hal_getrandom(mac->address.b, sizeof(*mac));
err = nrf24_mac2str(mac, mac_string);
if (err == -1)
goto done;
json_object_object_add(obj_radio, "mac",
json_object_new_string(mac_string));
json_object_to_file((char *) file, jobj);
}
/* Success */
err = 0;
done:
/* Free mem used in json parse: */
json_object_put(jobj);
return err;
}
/*
* TODO: Get "host", "spi" and "port"
* parameters when/if implemented
* in the json configuration file
*/
static int parse_config(const char *config, int *channel, int *dbm,
struct nrf24_mac *mac)
{
json_object *jobj, *obj_radio, *obj_tmp;
int err = -EINVAL;
jobj = json_tokener_parse(config);
if (jobj == NULL)
return -EINVAL;
if (!json_object_object_get_ex(jobj, "radio", &obj_radio))
goto done;
if (json_object_object_get_ex(obj_radio, "channel", &obj_tmp))
*channel = json_object_get_int(obj_tmp);
if (json_object_object_get_ex(obj_radio, "TxPower", &obj_tmp))
*dbm = json_object_get_int(obj_tmp);
if (json_object_object_get_ex(obj_radio, "mac", &obj_tmp)) {
if (json_object_get_string(obj_tmp) != NULL) {
err =
nrf24_str2mac(json_object_get_string(obj_tmp), mac);
if (err == -1)
goto done;
}
}
/* Success */
err = 0;
done:
/* Free mem used in json parse: */
json_object_put(jobj);
return err;
}
/*
* Reads the keys.json file to create the list of allowed peers.
* If the file does not exist or is in the wrong format, a new one (empty)
* is created.
*/
static int parse_nodes(const char *nodes_file)
{
int array_len;
int i;
int err = -EINVAL;
json_object *jobj;
json_object *obj_keys, *obj_nodes, *obj_tmp;
FILE *fp;
/* Load nodes' info from json file */
jobj = json_object_from_file(nodes_file);
if (!jobj) {
fp = fopen(nodes_file, "w");
if (!fp) {
hal_log_error("Could not create file %s", nodes_file);
goto done;
}
fprintf(fp, "{\"keys\":[]}");
fclose(fp);
err = 0;
goto done;
}
if (!json_object_object_get_ex(jobj, "keys", &obj_keys)){
fp = fopen(nodes_file, "w");
if (!fp){
hal_log_error("Could not write file %s", nodes_file);
goto done;
}
fprintf(fp, "{\"keys\":[]}");
fclose(fp);
err = 0;
goto done;
}
/*
* Gets only up to MAX_PEERS nodes.
*/
array_len = json_object_array_length(obj_keys);
if (array_len > MAX_PEERS) {
hal_log_error("Too many nodes at %s", nodes_file);
array_len = MAX_PEERS;
}
for (i = 0; i < array_len; i++) {
obj_nodes = json_object_array_get_idx(obj_keys, i);
if (!json_object_object_get_ex(obj_nodes, "mac", &obj_tmp))
goto done;
/* Parse mac address string into struct nrf24_mac known_peers */
if (nrf24_str2mac(json_object_get_string(obj_tmp),
&adapter.known_peers[i].addr) < 0)
goto done;
adapter.known_peers_size++;
if (!json_object_object_get_ex(obj_nodes, "name", &obj_tmp))
goto done;
/* Set the name of the peer registered */
adapter.known_peers[i].alias =
g_strdup(json_object_get_string(obj_tmp));
adapter.known_peers[i].status = FALSE;
}
err = 0;
done:
/* Free mem used to parse json */
json_object_put(jobj);
return err;
}
static gboolean check_timeout(gpointer key, gpointer value, gpointer user_data)
{
struct beacon *peer = value;
/* If it returns true the key/value is removed */
if (hal_timeout(hal_time_ms(), peer->last_beacon,
BCAST_TIMEOUT) > 0) {
hal_log_info("Peer %s timedout.", (char *) key);
return TRUE;
}
return FALSE;
}
static gboolean timeout_iterator(gpointer user_data)
{
g_hash_table_foreach_remove(peer_bcast_table, check_timeout, NULL);
return TRUE;
}
int manager_start(const char *file, const char *host, int port,
const char *spi, int channel, int dbm,
const char *nodes_file)
{
int cfg_channel = NRF24_CH_MIN, cfg_dbm = 0;
char *json_str;
struct nrf24_mac mac = {.address.uint64 = 0};
int err = -1;
/* Command line arguments have higher priority */
json_str = load_config(file);
if (json_str == NULL) {
hal_log_error("load_config()");
return err;
}
err = parse_config(json_str, &cfg_channel, &cfg_dbm, &mac);
if (err < 0) {
hal_log_error("parse_config(): %d", err);
free(json_str);
return err;
}
memset(&adapter, 0, sizeof(struct adapter));
/* Parse nodes info from nodes_file and writes it to known_peers */
err = parse_nodes(nodes_file);
if (err < 0) {
hal_log_error("parse_nodes(): %d", err);
free(json_str);
return err;
}
if (mac.address.uint64 == 0)
err = gen_save_mac(json_str, file, &mac);
free(json_str);
adapter.file_name = g_strdup(nodes_file);
adapter.mac = mac;
adapter.powered = TRUE;
if (err < 0) {
hal_log_error("Invalid configuration file(%d): %s", err, file);
return err;
}
/* Validate and set the channel */
if (channel < 0 || channel > 125)
channel = cfg_channel;
/*
* Use TX Power from configuration file if it has not been passed
* through cmd line. -255 means invalid: not informed by user.
*/
if (dbm == -255)
dbm = cfg_dbm;
/* Start server dbus */
dbus_id = dbus_init(mac);
/* TCP development mode: RPi(nrfd) connected to Linux(knotd) */
if (host) {
memset(&inet_address, 0, sizeof(inet_address));
err = tcp_init(host);
if (err < 0)
return err;
tcp_port = port;
}
err = radio_init(spi, channel, dbm_int2rfpwr(dbm),
(const struct nrf24_mac*) &mac);
if (err < 0)
return err;
peer_bcast_table = g_hash_table_new_full(g_str_hash, g_str_equal,
g_free, beacon_free);
g_timeout_add_seconds(5, timeout_iterator, NULL);
return 0;
}
void manager_stop(void)
{
dbus_on_close(dbus_id);
radio_stop();
g_hash_table_destroy(peer_bcast_table);
}
| 24.157736 | 79 | 0.687807 | [
"object",
"vector"
] |
c4a0cd1502be8d61d674c63c5dd107ad4febf45e | 2,223 | h | C | PostLib/ImageSlicer.h | EMinsight/FEBioStudio | d3e6485610d19217550fb94cb22180bc4bda45f9 | [
"MIT"
] | null | null | null | PostLib/ImageSlicer.h | EMinsight/FEBioStudio | d3e6485610d19217550fb94cb22180bc4bda45f9 | [
"MIT"
] | null | null | null | PostLib/ImageSlicer.h | EMinsight/FEBioStudio | d3e6485610d19217550fb94cb22180bc4bda45f9 | [
"MIT"
] | null | null | null | /*This file is part of the FEBio Studio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio-Studio.txt for details.
Copyright (c) 2021 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
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 <ImageLib/3DImage.h>
#include <FSCore/box.h>
#include "GLImageRenderer.h"
#include <ImageLib/RGBAImage.h>
#include "ColorMap.h"
namespace Post {
class CImageModel;
class CImageSlicer : public CGLImageRenderer
{
enum { ORIENTATION, OFFSET, COLOR_MAP };
public:
CImageSlicer(CImageModel* img);
~CImageSlicer();
void Create();
void Update() override;
void Render(CGLContext& rc) override;
int GetOrientation() const;
void SetOrientation(int n);
double GetOffset() const;
void SetOffset(double f);
int GetColorMap() const { return m_Col.GetColorMap(); }
void SetColorMap(int n) { m_Col.SetColorMap(n); }
bool UpdateData(bool bsave = true) override;
private:
void BuildLUT();
void UpdateSlice();
private:
CRGBAImage m_im; // 2D image that will be displayed
int m_LUTC[4][256]; // color lookup table
bool m_reloadTexture;
Post::CColorTexture m_Col;
unsigned int m_texID;
};
}
| 28.5 | 89 | 0.769681 | [
"render"
] |
c4a1a82dfa42e0eed8d69a95c2eb1fb16aecb850 | 26,617 | c | C | wx.c | slakpi/piwx | 0d9f90bec24110491fc1285f6656ba0bded649be | [
"MIT"
] | null | null | null | wx.c | slakpi/piwx | 0d9f90bec24110491fc1285f6656ba0bded649be | [
"MIT"
] | null | null | null | wx.c | slakpi/piwx | 0d9f90bec24110491fc1285f6656ba0bded649be | [
"MIT"
] | null | null | null | /**
* @file wx.c
*/
#include "wx.h"
#include "util.h"
#include "wxtype.h"
#include <ctype.h>
#include <curl/curl.h>
#include <jansson.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
typedef void *yyscan_t;
#include "wx.lexer.h"
#define MAX_DATETIME_LEN 20
/**
* @brief Trims a local airport ID for display.
* @details Non-ICAO airport IDs include numbers and are three characters long,
* e.g. 7S3 or X01. However, AviationWeather.gov expects four-character
* IDs. So, for the US, 7S3 should be "K7S3". If the specified ID has
* a number in it, return a duplicate string that does not have the K.
* If the ID is an ICAO ID, return a duplicate of the original string.
* @param[in] id The airport ID of interest.
* @returns A duplicate of either the original ID or the shortened non-ICAO ID.
*/
static char *trimLocalId(const char *id) {
size_t i, len = strlen(id);
const char *p = id;
if (len < 1) {
return NULL;
}
for (i = 0; i < len; ++i) {
if (isdigit(id[i])) {
p = id + 1;
break;
}
}
return strdup(p);
}
/**
* @struct Response
* @brief Buffer to hold response data from cURL.
*/
typedef struct {
char * str;
size_t len, bufLen;
} Response;
/**
* @brief Initialize a response buffer.
* @param[in] res The response buffer.
*/
static void initResponse(Response *res) {
res->str = (char *)malloc(sizeof(char) * 256);
res->str[0] = 0;
res->len = 0;
res->bufLen = 256;
}
/**
* @brief Appends new data from cURL to a response buffer.
* @details If there is not enough room left in the buffer, the function will
* increase the buffer size by 1.5x.
* @param[in] res Response buffer to receive the new data.
* @param[in] str cURL data.
* @param[in] len Length of the cURL data.
*/
static void appendToResponse(Response *res, const char *str, size_t len) {
size_t newBuf = res->bufLen;
if (!res->str) {
return;
}
while (1) {
if (res->len + len < newBuf) {
if (res->bufLen < newBuf) {
res->str = realloc(res->str, newBuf);
res->bufLen = newBuf;
}
memcpy(res->str + res->len, str, len);
res->len += len;
res->str[res->len] = 0;
return;
}
newBuf = (size_t)(newBuf * 1.5) + 1;
if (newBuf < res->bufLen) {
return;
}
}
}
/**
* @brief Free a response buffer.
* @param[in] res The response buffer to free.
*/
static void freeResponse(Response *res) {
free(res->str);
res->str = NULL;
res->len = 0;
res->bufLen = 0;
}
/**
* @brief Simple ISO-8601 parser.
* @details Assumes UTC and ignores timezone information. Assumes integer
* seconds. Performs basic sanity checks, but does not check if the
* day exceeds the number of days in the specified month.
* @param[in] str The string to parse.
* @param[in] tm Receives the date time.
* @returns TRUE if successful, FALSE otherwise.
*/
static boolean parseUTCDateTime(const char *str, struct tm *tm) {
sscanf(str, "%d-%d-%dT%d:%d:%d", &tm->tm_year, &tm->tm_mon, &tm->tm_mday,
&tm->tm_hour, &tm->tm_min, &tm->tm_sec);
if (tm->tm_year < 1900) {
return FALSE;
}
if (!(tm->tm_mon >= 1 && tm->tm_mon <= 12)) {
return FALSE;
}
if (!(tm->tm_mday >= 1 && tm->tm_mday <= 31)) {
return FALSE;
}
if (!(tm->tm_hour >= 0 && tm->tm_hour <= 23)) {
return FALSE;
}
if (!(tm->tm_min >= 0 && tm->tm_min <= 59)) {
return FALSE;
}
if (!(tm->tm_sec >= 0 && tm->tm_sec <= 59)) {
return FALSE;
}
tm->tm_year -= 1900;
tm->tm_mon -= 1;
tm->tm_isdst = 0;
return TRUE;
}
/**
* @brief cURL data callback for the sunrise/sunset API.
* @param[in] ptr Data received.
* @param[in] size Size of a data item.
* @param[in] nmemb Data items received.
* @param[in] userdata User callback data, i.e. Response object.
* @returns Bytes processed.
*/
static size_t sunriseSunsetCallback(char *ptr, size_t size, size_t nmemb,
void *userdata) {
Response *res = (Response *)userdata;
size_t bytes = size * nmemb;
appendToResponse(res, ptr, bytes);
return bytes;
}
/**
* @brief Queries the sunrise/sunset API.
* @details Note that the function returns the Civil Twilight range rather than
* the Sunrise and Sunset range.
* @param[in] lat Latitude to query.
* @param[in] lon Longitude to query.
* @param[in] date Date to query.
* @param[out] sunrise Sunrise in UTC.
* @param[out] sunset Sunset in UTC.
* @returns TRUE if successful, FALSE otherwise.
*/
static boolean getSunriseSunsetForDay(double lat, double lon, struct tm *date,
time_t *sunrise, time_t *sunset) {
CURL * curlLib;
CURLcode res;
json_t * rootNode, *timesNode, *sunriseNode, *sunsetNode;
json_error_t err;
char tmp[257];
Response json;
struct tm dtSunrise, dtSunset;
boolean ok = FALSE;
*sunrise = 0;
*sunset = 0;
curlLib = curl_easy_init();
if (!curlLib) {
return FALSE;
}
snprintf(tmp, COUNTOF(tmp),
"https://api.sunrise-sunset.org/json?"
"lat=%f&lng=%f&formatted=0&date=%d-%d-%d",
lat, lon, date->tm_year + 1900, date->tm_mon + 1, date->tm_mday);
initResponse(&json);
curl_easy_setopt(curlLib, CURLOPT_URL, tmp);
curl_easy_setopt(curlLib, CURLOPT_WRITEFUNCTION, sunriseSunsetCallback);
curl_easy_setopt(curlLib, CURLOPT_WRITEDATA, &json);
res = curl_easy_perform(curlLib);
curl_easy_cleanup(curlLib);
if (res != CURLE_OK) {
return FALSE;
}
rootNode = json_loads(json.str, 0, &err);
freeResponse(&json);
if (!rootNode) {
return FALSE;
}
timesNode = json_object_get(rootNode, "results");
if (!json_is_object(timesNode)) {
goto cleanup;
}
sunriseNode = json_object_get(timesNode, "civil_twilight_begin");
if (!json_is_string(sunriseNode)) {
goto cleanup;
}
sunsetNode = json_object_get(timesNode, "civil_twilight_end");
if (!json_is_string(sunsetNode)) {
goto cleanup;
}
// Copy the date/time strings into the temporary string buffer with an
// explicit limit on the correct format ("YYYY-MM-DDTHH:MM:SS\0").
strncpy(tmp, json_string_value(sunriseNode), MAX_DATETIME_LEN);
if (!parseUTCDateTime(tmp, &dtSunrise)) {
goto cleanup;
}
strncpy(tmp, json_string_value(sunsetNode), MAX_DATETIME_LEN);
if (!parseUTCDateTime(tmp, &dtSunset)) {
goto cleanup;
}
*sunrise = timegm(&dtSunrise);
*sunset = timegm(&dtSunset);
ok = TRUE;
cleanup:
if (rootNode) {
json_decref(rootNode);
}
return ok;
}
/**
* @brief Checks if the given observation time is night at the given location.
* @details Consider a report issued at 1753L on July 31 in the US Pacific
* Daylight time zone. The UTC date/time is 0053Z on Aug 1, so the
* query will return the sunrise/sunset for Aug 1, not July 31. Using
* the Aug 1 data, 0053Z will be less than the sunrise time and
* @a isNight would indicate night time despite it being day time PDT.
*
* @a isNight checks the previous and next days as necessary to make a
* determination without knowing the station's local time zone.
* @param[in] lat Observation latitude.
* @param[in] lon Observation longitude.
* @param[in] obsTime UTC observation time.
* @returns FALSE if day or there is an error, TRUE if night.
*/
static boolean isNight(double lat, double lon, time_t obsTime) {
time_t t = obsTime;
time_t sr, ss;
struct tm date;
gmtime_r(&t, &date);
if (!getSunriseSunsetForDay(lat, lon, &date, &sr, &ss)) {
return 0;
}
// If the observation time is less than the sunrise date/time, check the
// prior day. Otherwise, check the next day.
if (obsTime < sr) {
if (t < 86400) {
return 0; // Underflow
}
t -= 86400;
} else if (obsTime >= ss) {
if (t + 86400 < t) {
return 0; // Overflow
}
t += 86400;
} else {
return 0; // Between sunrise and sunset; it's day time.
}
gmtime_r(&t, &date);
if (!getSunriseSunsetForDay(lat, lon, &date, &sr, &ss)) {
return 0;
}
// It's night time if greater than sunset on the previous day or less than
// sunrise on the next day.
return (obsTime >= ss || obsTime < sr);
}
/**
* @enum Tag
* @brief METAR XML tag ID.
*/
// clang-format off
typedef enum {
tagInvalid = -1,
tagResponse = 1,
tagData,
tagMETAR,
tagRawText, tagStationId, tagObsTime, tagLat, tagLon, tagTemp,
tagDewpoint, tagWindDir, tagWindSpeed, tagWindGust, tagVis, tagAlt,
tagCategory, tagWxString, tagSkyCond, tagVertVis,
tagSkyCover, tagCloudBase,
tagSCT, tagFEW, tagBKN, tagOVC, tagOVX, tagCLR,
tagSKC, tagCAVOK,
tagVFR, tagMVFR, tagIFR, tagLIFR,
tagFirst = tagResponse,
tagLast = tagLIFR
} Tag;
// clang-format on
// clang-format off
static const Tag tags[] = {
tagResponse,
tagData,
tagMETAR,
tagRawText, tagStationId, tagObsTime, tagLat, tagLon, tagTemp,
tagDewpoint, tagWindDir, tagWindSpeed, tagWindGust, tagVis, tagAlt,
tagCategory, tagWxString, tagSkyCond, tagVertVis,
tagSkyCover, tagCloudBase,
tagSCT, tagFEW, tagBKN, tagOVC, tagOVX, tagCLR,
tagSKC, tagCAVOK,
tagVFR, tagMVFR, tagIFR, tagLIFR,
};
// clang-format on
// clang-format off
static const char *tagNames[] = {
"response",
"data",
"METAR",
"raw_text",
"station_id",
"observation_time",
"latitude",
"longitude",
"temp_c",
"dewpoint_c",
"wind_dir_degrees",
"wind_speed_kt",
"wind_gust_kt",
"visibility_statute_mi",
"altim_in_hg",
"flight_category",
"wx_string",
"sky_condition",
"vert_vis_ft",
"sky_cover",
"cloud_base_ft_agl",
"SCT",
"FEW",
"BKN",
"OVC",
"OVX",
"CLR",
"SKC",
"CAVOK",
"VFR",
"MVFR",
"IFR",
"LIFR",
NULL
};
// clang-format on
/**
* @brief Initialize the tag map.
* @param[in] hash Tag hash map.
*/
static void initHash(xmlHashTablePtr hash) {
for (long i = 0; tagNames[i]; ++i)
xmlHashAddEntry(hash, (xmlChar *)tagNames[i], (void *)tags[i]);
}
/**
* @brief Hash destructor.
* @details Placeholder only, there is nothing to deallocate.
* @param[in] payload Data associated with tag.
* @param[in] name The tag name.
*/
static void hashDealloc(void *payload, xmlChar *name) {}
/**
* @brief Lookup the tag ID for a given tag name.
* @param[in] hash The tag hash map.
* @param[in] tag The tag name.
* @returns The associated tag ID or tagInvalid.
*/
static Tag getTag(xmlHashTablePtr hash, const xmlChar *tag) {
void *p = xmlHashLookup(hash, tag);
if (!p) {
return tagInvalid;
}
return (Tag)p;
}
/**
* @struct METARCallbackData
* @brief User data structure for parsing METAR XML.
*/
typedef struct {
xmlParserCtxtPtr ctxt;
} METARCallbackData;
/**
* @brief cURL data callback for the METAR XAML API.
* @param[in] ptr Data received.
* @param[in] size Size of a data item.
* @param[in] nmemb Data items received.
* @param[in] userdata User callback data, i.e. Response object.
* @returns Bytes processed.
*/
static size_t metarCallback(char *ptr, size_t size, size_t nmemb,
void *userdata) {
METARCallbackData *data = (METARCallbackData *)userdata;
size_t res = nmemb * size;
if (!data->ctxt) {
data->ctxt = xmlCreatePushParserCtxt(NULL, NULL, ptr, nmemb, NULL);
if (!data->ctxt) {
res = 0;
}
} else {
if (xmlParseChunk(data->ctxt, ptr, nmemb, 0) != 0) {
res = 0;
}
}
return res;
}
/**
* @brief Converts category text to a FlightCategory value.
* @param[in] node The flight category node.
* @param[in] hash The tag hash map.
* @returns The flight category or catInvalid.
*/
static FlightCategory getStationFlightCategory(xmlNodePtr node,
xmlHashTablePtr hash) {
Tag tag = getTag(hash, node->content);
switch (tag) {
case tagVFR:
return catVFR;
case tagMVFR:
return catMVFR;
case tagIFR:
return catIFR;
case tagLIFR:
return catLIFR;
default:
return catInvalid;
}
}
/**
* @brief Convert cloud cover text to a CloudCover value.
* @param[in] attr The cloud cover attribute.
* @param[in] hash The tag hash map.
* @returns The cloud cover or skyInvalid.
*/
static CloudCover getLayerCloudCover(xmlAttr *attr, xmlHashTablePtr hash) {
Tag tag = getTag(hash, attr->children->content);
switch (tag) {
case tagSKC:
case tagCLR:
case tagCAVOK:
return skyClear;
case tagSCT:
return skyScattered;
case tagFEW:
return skyFew;
case tagBKN:
return skyBroken;
case tagOVC:
return skyOvercast;
case tagOVX:
return skyOvercastSurface;
default:
return skyInvalid;
}
}
/**
* @brief Adds a cloud layer to the list of layers.
* @param[in] node The sky condition node.
* @param[in] station The station to receive the new layer.
* @param[in] hash The tag hash map.
*/
static void addCloudLayer(xmlNodePtr node, WxStation *station,
xmlHashTablePtr hash) {
xmlAttr * a = node->properties;
SkyCondition *newLayer, *p;
Tag tag;
newLayer = malloc(sizeof(SkyCondition));
memset(newLayer, 0, sizeof(SkyCondition));
// Get the layer information.
while (a) {
tag = getTag(hash, a->name);
switch (tag) {
case tagSkyCover:
newLayer->coverage = getLayerCloudCover(a, hash);
break;
case tagCloudBase:
newLayer->height =
(int)strtol((const char *)a->children->content, NULL, 10);
break;
default:
break;
}
a = a->next;
}
// Add the layer in sorted order.
if (!station->layers) {
station->layers = newLayer;
} else {
p = station->layers;
while (p) {
if (newLayer->height < p->height) {
// Insert the layer before the current layer. If the current layer is
// the start of the list, update the list pointer.
if (p == station->layers) {
station->layers = newLayer;
} else {
p->prev->next = newLayer;
}
p->prev = newLayer;
newLayer->next = p;
break;
} else if (!p->next) {
// There are no more items in the list after this one. Thus, this layer
// has to be placed after the current layer.
p->next = newLayer;
newLayer->prev = p;
break;
}
p = p->next;
}
}
}
/**
* @brief Reads a station METAR group.
* @param[in] node The station node.
* @param[in] hash The tag hash map.
* @param[in] station The station object to receive the METAR information.
*/
static void readStation(xmlNodePtr node, xmlHashTablePtr hash,
WxStation *station) {
Tag tag;
struct tm obs;
xmlNodePtr c = node->children;
while (c) {
if (c->type == XML_TEXT_NODE) {
c = c->next;
continue;
}
tag = getTag(hash, c->name);
switch (tag) {
case tagRawText:
station->raw = strdup((char *)c->children->content);
break;
case tagStationId:
station->id = strdup((char *)c->children->content);
station->localId = trimLocalId(station->id);
break;
case tagObsTime:
parseUTCDateTime((char *)c->children->content, &obs);
station->obsTime = timegm(&obs);
break;
case tagLat:
station->lat = strtod((char *)c->children->content, NULL);
break;
case tagLon:
station->lon = strtod((char *)c->children->content, NULL);
break;
case tagTemp:
station->temp = strtod((char *)c->children->content, NULL);
break;
case tagDewpoint:
station->dewPoint = strtod((char *)c->children->content, NULL);
break;
case tagWindDir:
station->windDir = atoi((char *)c->children->content);
break;
case tagWindSpeed:
station->windSpeed = atoi((char *)c->children->content);
break;
case tagWindGust:
station->windGust = atoi((char *)c->children->content);
break;
case tagVis:
station->visibility = strtod((char *)c->children->content, NULL);
break;
case tagAlt:
station->alt = strtod((char *)c->children->content, NULL);
break;
case tagWxString:
station->wxString = strdup((char *)c->children->content);
break;
case tagCategory:
station->cat = getStationFlightCategory(c->children, hash);
break;
case tagSkyCond:
addCloudLayer(c, station, hash);
break;
case tagVertVis:
station->vertVis = strtod((char *)c->children->content, NULL);
break;
default:
break;
}
c = c->next;
}
}
/**
* @enum Intensity
* @brief Weather intensity value.
*/
typedef enum {
intensityInvalid,
intensityLight,
intensityModerate,
intensityHeavy
} Intensity;
/**
* @brief Classifies the dominant weather phenomenon.
* @details Examines all of the reported weather phenomena and returns the
* dominant, i.e. most impactful, phenomenon.
* @param[in] station The weather station to classify.
*/
static void classifyDominantWeather(WxStation *station) {
yyscan_t scanner;
YY_BUFFER_STATE buf;
int c, h, descriptor;
Intensity intensity;
SkyCondition * s;
// Assume clear skies to start.
station->wx = (station->isNight ? wxClearNight : wxClearDay);
s = station->layers;
h = INT_MAX;
// First, find the most impactful cloud cover.
while (s) {
if (s->coverage < skyScattered && station->wx < wxClearDay) {
station->wx = (station->isNight ? wxClearNight : wxClearDay);
} else if (s->coverage < skyBroken && station->wx < wxScatteredOrFewDay) {
station->wx =
(station->isNight ? wxScatteredOrFewNight : wxScatteredOrFewDay);
} else if (s->coverage < skyOvercast && s->height < h &&
station->wx < wxBrokenDay) {
station->wx = (station->isNight ? wxBrokenNight : wxBrokenDay);
h = s->height;
} else if (station->wx < wxOvercast && s->height < h) {
station->wx = wxOvercast;
h = s->height;
}
s = s->next;
}
// If there are no reported phenomena, just use the sky coverage.
if (!station->wxString) {
return;
}
// Tokenize the weather phenomena string.
wxtype_lex_init(&scanner);
buf = wxtype__scan_string(station->wxString, scanner);
intensity = intensityInvalid;
descriptor = 0;
while ((c = wxtype_lex(scanner)) != 0) {
// If the intensity is invalid and the current token does not specify an
// intensity level, just use moderate intensity, e.g. SH is moderate showers
// versus -SH for light showers.
if (intensity == intensityInvalid && c != ' ' && c != '-' && c != '+') {
intensity = intensityModerate;
}
switch (c) {
case ' ': // Reset token
intensity = intensityInvalid;
descriptor = 0;
break;
case wxVC: // Nothing to do for in vincinity
break;
case '-':
intensity = intensityLight;
break;
case '+':
intensity = intensityHeavy;
break;
case wxMI: // Shallow descriptor
case wxPR: // Partial descriptor
case wxBC: // Patchy descriptor
case wxDR: // Drifting descriptor
case wxBL: // Blowing descriptor
case wxSH: // Showery descriptor
case wxFZ: // Freezing descriptor
descriptor = c;
break;
case wxTS:
// If the currently known phenomenon is a lower priority than
// Thunderstorms, update it with the appropriate light or moderate/heavy
// Thunderstorm classification.
if (intensity < intensityModerate &&
station->wx < wxLightTstormsSqualls) {
station->wx = wxLightTstormsSqualls;
} else if (station->wx < wxTstormsSqualls) {
station->wx = wxTstormsSqualls;
}
break;
case wxBR: // Mist
case wxHZ: // Haze
if (station->wx < wxLightMistHaze) {
station->wx = wxLightMistHaze;
}
break;
case wxDZ: // Drizzle
// Let drizzle fall through. DZ and RA will be categorized as
// rain.
case wxRA: // Rain
if (descriptor != wxFZ) {
if (intensity < intensityModerate && station->wx < wxLightDrizzleRain) {
station->wx = wxLightDrizzleRain;
} else if (station->wx < wxRain) {
station->wx = wxRain;
}
} else {
if (intensity < intensityModerate &&
station->wx < wxLightFreezingRain) {
station->wx = wxLightFreezingRain;
} else if (station->wx < wxFreezingRain) {
station->wx = wxFreezingRain;
}
}
break;
case wxSN: // Snow
case wxSG: // Snow grains
if (intensity == intensityLight && station->wx < wxFlurries) {
station->wx = wxFlurries;
} else if (intensity == intensityModerate && station->wx < wxLightSnow) {
station->wx = wxLightSnow;
} else if (station->wx < wxSnow) {
station->wx = wxSnow;
}
break;
case wxIC: // Ice crystals
case wxPL: // Ice pellets
case wxGR: // Hail
case wxGS: // Small hail
// Reuse the freezing rain category.
if (intensity < intensityModerate && station->wx < wxLightFreezingRain) {
station->wx = wxLightFreezingRain;
} else if (station->wx < wxFreezingRain) {
station->wx = wxLightFreezingRain;
}
break;
case wxFG: // Fog
case wxFU: // Smoke
case wxDU: // Dust
case wxSS: // Sand storm
case wxDS: // Dust storm
if (station->wx < wxObscuration) {
station->wx = wxObscuration;
}
break;
case wxVA: // Volcanic ash
if (station->wx < wxVolcanicAsh) {
station->wx = wxVolcanicAsh;
}
break;
case wxSQ: // Squalls
if (intensity < intensityModerate &&
station->wx < wxLightTstormsSqualls) {
station->wx = wxLightTstormsSqualls;
} else if (station->wx < wxTstormsSqualls) {
station->wx = wxTstormsSqualls;
}
break;
case wxFC: // Funnel cloud
if (station->wx < wxFunnelCloud) {
station->wx = wxFunnelCloud;
}
break;
}
}
wxtype__delete_buffer(buf, scanner);
wxtype_lex_destroy(scanner);
}
/**
* @brief Search the parent's children for a specific tag.
* @param[in] children The parent's children.
* @param[in] tag The tag to find.
* @param[in] hash The hash table to use.
* @returns The first instance of the specified tag or null.
*/
static xmlNodePtr getChildTag(xmlNodePtr children, Tag tag,
xmlHashTablePtr hash) {
xmlNodePtr p = children;
Tag curTag;
while (p) {
curTag = getTag(hash, p->name);
if (curTag == tag) {
return p;
}
p = p->next;
}
return NULL;
}
WxStation *queryWx(const char *stations, int *err) {
CURL * curlLib;
CURLcode res;
char url[4096];
METARCallbackData data;
xmlDocPtr doc = NULL;
xmlNodePtr p;
xmlHashTablePtr hash = NULL;
Tag tag;
WxStation * start = NULL, *cur, *newStation;
int count, len;
boolean ok = FALSE;
*err = 0;
// Build the query string to look for reports within the last hour and a half.
// It is possible some stations lag more than an hour, but typically not more
// than an hour and a half.
strncpy(url,
"https://aviationweather.gov/adds/dataserver_current/httpparam?"
"dataSource=metars&"
"requestType=retrieve&"
"format=xml&"
"hoursBeforeNow=1.5&"
"mostRecentForEachStation=true&"
"stationString=",
COUNTOF(url));
count = COUNTOF(url) - strlen(url);
len = strlen(stations);
// TODO: Eventually this should split the station string into multiple queries
// if it is too long. For now, just abort.
if (len >= count) {
return NULL;
}
strcat(url, stations);
curlLib = curl_easy_init();
if (!curlLib) {
return NULL;
}
data.ctxt = NULL;
curl_easy_setopt(curlLib, CURLOPT_URL, url);
curl_easy_setopt(curlLib, CURLOPT_WRITEFUNCTION, metarCallback);
curl_easy_setopt(curlLib, CURLOPT_WRITEDATA, &data);
res = curl_easy_perform(curlLib);
curl_easy_cleanup(curlLib);
if (data.ctxt) {
xmlParseChunk(data.ctxt, NULL, 0, 1);
doc = data.ctxt->myDoc;
xmlFreeParserCtxt(data.ctxt);
}
if (res != CURLE_OK) {
*err = res;
goto cleanup;
}
hash = xmlHashCreate(tagLast);
initHash(hash);
// Find the response tag.
p = getChildTag(doc->children, tagResponse, hash);
if (!p) {
goto cleanup;
}
// Find the data tag.
p = getChildTag(p->children, tagData, hash);
if (!p) {
goto cleanup;
}
// Scan for METAR groups.
p = p->children;
while (p) {
tag = getTag(hash, p->name);
if (tag != tagMETAR) {
p = p->next;
continue;
}
newStation = (WxStation *)malloc(sizeof(WxStation));
memset(newStation, 0, sizeof(WxStation));
// Add the station to the circular list.
if (!start) {
start = cur = newStation;
cur->next = cur;
cur->prev = cur;
} else {
start->prev = newStation;
cur->next = newStation;
newStation->next = start;
newStation->prev = cur;
cur = newStation;
}
// Read the station and get the night status for classifying weather.
readStation(p, hash, newStation);
newStation->isNight =
isNight(newStation->lat, newStation->lon, newStation->obsTime);
newStation->blinkState = 1;
classifyDominantWeather(newStation);
p = p->next;
}
ok = TRUE;
cleanup:
if (doc) {
xmlFreeDoc(doc);
}
if (hash) {
xmlHashFree(hash, hashDealloc);
}
if (!ok) {
freeStations(start);
start = NULL;
}
return start;
}
void freeStations(WxStation *stations) {
WxStation * p;
SkyCondition *s;
// Break the circular list.
stations->prev->next = NULL;
while (stations) {
p = stations;
stations = stations->next;
free(p->id);
free(p->localId);
free(p->raw);
while (p->layers) {
s = p->layers;
p->layers = p->layers->next;
free(s);
}
free(p);
}
}
| 24.736989 | 80 | 0.60961 | [
"object"
] |
c4a35b65a857252840fdcb4cba817322f90e64f0 | 14,581 | h | C | src/larks.bak/larks.h | SyllogismRXS/opencv-workbench | 2fb5b0d67589642d438f21f1cf58aaa761d15757 | [
"MIT"
] | 7 | 2015-10-05T04:33:31.000Z | 2018-07-20T02:47:36.000Z | src/larks.bak/larks.h | SyllogismRXS/opencv-workbench | 2fb5b0d67589642d438f21f1cf58aaa761d15757 | [
"MIT"
] | null | null | null | src/larks.bak/larks.h | SyllogismRXS/opencv-workbench | 2fb5b0d67589642d438f21f1cf58aaa761d15757 | [
"MIT"
] | 12 | 2015-07-18T16:01:00.000Z | 2021-02-28T11:56:02.000Z | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * 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 Willow Garage, Inc. 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.
*
* $Id$
*
*/
#ifndef LARKS_H_
#define LARKS_H_
#include <iostream>
#include <boost/multi_array.hpp>
//#include <opencv_workbench/recognition_pipeline/algorithms/detector.h>
//#include <opencv_workbench/recognition_pipeline/algorithms/trainable.h>
#include <opencv2/opencv.hpp>
#include <vector>
#include <string>
#include <map>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/split_member.hpp>
//#include <opencv_workbench/recognition_pipeline/algorithms/serialization_support.h>
namespace larks {
//using namespace recognition_pipeline;
using namespace cv;
using namespace std;
using boost::multi_array;
typedef multi_array<Mat, 4> array_type4;
typedef multi_array<Mat, 3> array_type3;
typedef multi_array<Mat, 2> array_type2;
typedef multi_array<Mat, 1> array_type1;
typedef multi_array<double, 3> double_type3;
typedef multi_array<double, 4> double_type4;
typedef multi_array<Point, 3> Point_type3;
typedef multi_array<Point, 4> Point_type4;
typedef multi_array<int,1> int_type1;
class Larkcomputation
{
public:
Larkcomputation(){};
void computeCovariance(const Mat& gray, int wsize, const int dfactor, Mat& sC11, Mat& sC12, Mat& sC22);
void computeLARK(const int rows, const int cols, const int wsize, Mat& sC11, Mat& sC12, Mat& sC22, array_type1& temp);
};
class Saliency
{
public:
Saliency(){};
void ProtoObject(const Mat &SaliencyMap, Mat& thMap);
void computeSaliency(const array_type1& LARK, const int wsize, const int psize, Mat& SaliencyMap);
};
class LARKFeatureTemplates
{
public:
PCA pca;
array_type1 QF;
cv::Mat M;
int cols;
cv::Mat img;
cv::Mat mas;
LARKFeatureTemplates() { };
void computeFeatures(const cv::Mat &whole_gray, const cv::Rect & roi, const cv::Mat & mask, int index, PCA& pca1, int cols1);
float MatrixCosineMeasure(array_type1& QF1, Mat M1, array_type1& QF, Mat& M);
};
class TrainingTemplate
{
public:
TrainingTemplate(){};
void Training(std::vector<LARKFeatureTemplates>& models, array_type2& query_mask, array_type3& QF, double_type3& QF_norm, Mat& labels);
inline PCA get_pca() {return pca;}
int numTemplate;
int numScale;
int numRotation;
int maxComponents;
protected:
PCA pca;
Larkcomputation LARK;
std::vector<LARKFeatureTemplates> models;
};
class LARKs //: public Detector, public Trainable
{
public:
LARKs(ModelStoragePtr model_storage) : Detector(model_storage)
{
std::cout << "test" << std::endl;
factor = 0.25;
dfactor = 4;
blue = Scalar(255, 0,0);
dark_blue = Scalar(125,0,0);
red = Scalar(0,0,255);
dark_red = Scalar(0,0,125);
green = Scalar(0,255,0);
dark_green = Scalar(0,125,0);
purple = Scalar(255,0,255);
dark_purple = Scalar(125,0,125);
black = Scalar(0,0,0);
light_black = Scalar(125,125,125);
yellow = Scalar(0,255,255);
white = Scalar(255,255,255);
use_saliency = true;
x_block = 10;
y_block = 10;
wsize = 5;
AtleastSalient = 0;
binaryfeaturemode = false;
block_table = Mat::zeros(x_block, y_block, CV_8U);
index = 0;
};
~LARKs()
{
};
/**
* \brief Run the object detector. The detection results are stored in
* class member detections_.
*/
virtual void detect();
/**
* Each detector will have an unique name. This returns the detector name.
* @return name of the detector
*/
virtual std::string getName() { return "larks"; }
/**
* Loads pre-trained models for a list of objects.
* @param models list of objects to load
*/
virtual void loadModels(const std::vector<std::string>& models);
/**
* Starts training for a new object category model. It may allocate/initialize
* data structures needed for training a new category.
* @param name
*/
virtual void startTraining(const std::string& name);
/**
* Trains the model on a new data instance.
* @param name The name of the model
* @param data Training data instance
*/
virtual void trainInstance(const std::string& name, const recognition_pipeline::TrainingData& data);
/**
* Saves a trained model.
* @param name model name
*/
virtual void endTraining(const std::string& name);
void Pre_Search(const float factor, const int numTemplate, const int numRotation, const int numScale, array_type3& query_mask, array_type4& QF, double_type4& QF_norm, Mat target, bool binaryfeaturemode, array_type3& TF, Mat scales, Mat block_table, Point_type3& region_index, double Prev_max, int maxComponents, double_type3& maxVals, Mat& labels, int level, int obj, vector<int_type1> & offset_x, vector<int_type1> & offset_y);
void Search(const float factor, const int numTemplate, const int numRotation, const int numScale, array_type3& query_mask, array_type4& QF, double_type4& QF_norm, Mat target, bool binaryfeaturemode, array_type3& TF, Mat scales, Mat block_table, Point_type3& region_index, double Prev_max, int maxComponents, Mat& img2, bool& use_saliency, Mat img1, Mat& RM1, std::string modelname, const float threshold , double_type3& maxVals, int& index_template, int& index_scale, int& index_rotation, int level, int obj, Detection &d);
void getTF(const int wsize, Mat target, Mat sC11, Mat sC12, Mat sC22, bool binaryfeaturemode, const int maxComponents, const int numScale, array_type2& TF, Mat& means, Mat& eigenvectors);
void Multiscale_search(array_type4& QF, double_type4& QF_norm,array_type3& query_mask, const Mat& target, array_type3& RM, const int offset_x, const int offset_y,
const int query_index, const bool binaryfeaturemode,const array_type3& TF, const Mat& scales, const Mat& block_table, Point_type3& region_index, const int maxComponents, float f, double_type3& maxVal, int level, int obj);
void Multiscale_search_withPrevious(array_type4& QF, double_type4& QF_norm,array_type3& query_mask, const Mat& target, array_type3& RM, const int offset_x, const int offset_y, const int query_index, const bool binaryfeaturemode,const array_type3& TF, const Mat& scales, const Mat& block_table,Point_type3& region_index, const int maxComponents,double_type3& maxVal1, float threshold, int level, int obj) ;
void pyramidFeatures(array_type2 TF, array_type3& TFs, array_type3 QF, array_type4& QFs,double_type3 QF_norm, double_type4& QF_norms, array_type2 query_mask, array_type3& query_masks, int level, const int numTemplate);
void GradientImage(const Mat& gray, Mat& GradImage);
TrainingTemplate TT;
vector<string> model_list;
std::vector<LARKFeatureTemplates> models;
//typedef map<string, vector<LARKFeatureTemplates> > ModelsMap;
template<class archive>
void load(archive& ar, const unsigned int version)
{
ar & numTemplates[id];
ar & numScale;
ar & numRotation;
ar & maxComponents;
ar & eigenvectors[id];
ar & means[id];
std::cout << "numTemplate " << numTemplates[id] << std::endl;
QFs[id].resize(boost::extents[numTemplates[id]][numRotation][maxComponents]);
query_masks[id].resize(boost::extents[numTemplates[id]][numRotation]);
QF_norms[id].resize(boost::extents[numTemplates[id]][numRotation][numScale]);
for ( int i = 0; i < numTemplates[id]; ++i)
for ( int j = 0; j < numRotation; ++j)
for ( int m = 0; m < maxComponents; ++m)
{
ar & QFs[id][i][j][m];
}
for ( int i = 0; i < numTemplates[id]; ++i)
for ( int j = 0; j < numRotation; ++j)
for ( int m = 0; m < numScale; ++m)
{
ar & QF_norms[id][i][j][m];
}
for ( int i = 0; i < numTemplates[id]; ++i)
for ( int j = 0; j < numRotation; ++j)
{
ar & query_masks[id][i][j];
}
ar & labels[id];
}
template<class archive>
void save(archive& ar, const unsigned int version) const
{
ar & numTemplate;
ar & numScale;
ar & numRotation;
ar & maxComponents;
ar & eigenvector;
ar & mean;
for (unsigned int i = 0; i < QF.shape()[0]; ++i)
for (unsigned int j = 0; j < QF.shape()[1]; ++j)
for (unsigned int m = 0; m < QF.shape()[2]; ++m)
{
ar & QF[i][j][m];
}
for (unsigned int i = 0; i < QF_norm.shape()[0]; ++i)
for (unsigned int j = 0; j < QF_norm.shape()[1]; ++j)
for (unsigned int m = 0; m < QF_norm.shape()[2]; ++m)
{
ar & QF_norm[i][j][m];
}
for (unsigned int i = 0; i < query_mask.shape()[0]; ++i)
for (unsigned int j = 0; j < query_mask.shape()[1]; ++j)
{
ar & query_mask[i][j];
}
ar & label;
}
// define serialize() using save() and load()
BOOST_SERIALIZATION_SPLIT_MEMBER();
inline void set_num_models(int num_models) { num_models_ = num_models; }
inline void set_models(vector<std::string> models, int num_models) { models_.resize(num_models); models_ = models; }
inline void set_threshold(vector<double> threshold, int num_models) { threshold_.resize(num_models); threshold_ = threshold; }
int id;
Mat eigenvector;
Mat mean;
vector<cv::Mat> eigenvectors, means;
int numTemplate, maxComponents, numScale, coeff, numRotation;
vector<int> numTemplates;
Mat scales;
vector<cv::Mat> labels;
Mat label;
vector<int_type1> offset_x;
vector<int_type1> offset_y;
std::string objname;
std::string name;
float score;
cv::Mat mask;
cv::Rect roi;
int num_models_;
vector<float> Prev_max;
vector<std::string> models_;
vector<double> threshold_;
Larkcomputation LARK;
bool use_saliency, binaryfeaturemode;
int wsize, query_counter;
float factor;
double minVal1, minVal2;
double maxVal1, maxVal2;
Point minLoc1, minLoc2;
Point maxLoc1, maxLoc2;
int x_block;
int y_block;
Mat block_table;
vector<Point> start, end;
Point Prev_Loc;
int dfactor;
int AtleastSalient;
Saliency SalientRegion;
Scalar blue;
Scalar dark_blue;
Scalar red;
Scalar dark_red;
Scalar green;
Scalar dark_green;
Scalar purple;
Scalar dark_purple;
Scalar yellow;
Scalar white;
Scalar black;
Scalar light_black;
vector<Point_type3> region_index;
const char* modelname_;
array_type3 QF, QF1;
vector<array_type3> QFs;
array_type2 query_mask, query_mask1;
vector<array_type2> query_masks;
double_type3 QF_norm, QF_norm1;
vector<double_type3> QF_norms;
vector<array_type4> Py_QFs;
vector<array_type3> Py_query_masks;
vector<double_type4> Py_QF_norms;
cv::PCA pca;
vector<cv::PCA> pcas;
int index;
double_type3 maxVal;
vector<double_type3> maxVals;
vector<int> index_templates, index_scales, index_rotations;
};
#endif
}
| 34.147541 | 533 | 0.587408 | [
"object",
"shape",
"vector",
"model"
] |
c4a69170f856c991ec39d064283bb22a8d1c8fa4 | 2,607 | h | C | NativeLibraries/iOS/HERE_iOS_SDK_Premium_v3.15.2_92/framework/NMAKit.framework/Headers/NMAFTCRRoute.h | KarinBerg/Xamarin.HEREMaps | 87927ba567892528d1251ee83ffaab34fe201899 | [
"MIT"
] | 15 | 2020-07-06T00:42:33.000Z | 2022-02-23T21:55:05.000Z | NativeLibraries/iOS/HERE_iOS_SDK_Premium_v3.15.2_92/framework/NMAKit.framework/Headers/NMAFTCRRoute.h | KarinBerg/Xamarin.HEREMaps | 87927ba567892528d1251ee83ffaab34fe201899 | [
"MIT"
] | 1 | 2021-09-22T05:48:37.000Z | 2021-09-29T20:35:43.000Z | NativeLibraries/iOS/HERE_iOS_SDK_Premium_v3.15.2_92/framework/NMAKit.framework/Headers/NMAFTCRRoute.h | KarinBerg/Xamarin.HEREMaps | 87927ba567892528d1251ee83ffaab34fe201899 | [
"MIT"
] | 3 | 2020-08-09T06:06:40.000Z | 2021-11-14T12:23:32.000Z | /*
* Copyright (c) 2011-2020 HERE Global B.V. and its affiliate(s).
* All rights reserved.
* The use of this software is conditional upon having a separate agreement
* with a HERE company for the use or utilization of this software. In the
* absence of such agreement, the use of the software is not allowed.
*/
#import <Foundation/Foundation.h>
@class NMAGeoCoordinates;
@class NMAGeoBoundingBox;
@class NMAFTCRManeuver;
@class NMAFTCRRouteLink;
/**
* A constant used to indicate the whole route should be used in route leg selection.
*/
FOUNDATION_EXPORT const NSInteger NMAFTCRRouteSublegWhole;
/**
* Represents a distinct fleet telematics custom path connecting two or more waypoints
* `NMAGeoCoordinates`. The `NMAFTCRRoute` consists of a list of maneuvers and route links.
*
* IMPORTANT: Fleet Telematics Custom Route is a Beta feature. The related classes are subject to
* change without notice.
*
* See also `NMAFTCRRouter`.
*/
@interface NMAFTCRRoute : NSObject
/**
* Instances of this class should not be initialized directly.
*/
- (nonnull instancetype)init NS_UNAVAILABLE;
/**
* Instances of this class should not be initialized directly.
*/
+ (nonnull instancetype)new NS_UNAVAILABLE;
/**
* Smallest `NMAGeoBoundingBox` that contains the entire route.
*/
@property (nonatomic, readonly, strong, nullable) NMAGeoBoundingBox *boundingBox;
/**
* The `NSArray` of `NMAGeoCoordinates` represents the geometry of the `NMAFTCRRoute`. The geometry
* is a returned as an array of `NMAGeoCoordinates` that can be used to create a polyline.
*/
@property (nonatomic, readonly, strong, nullable) NSArray<NMAGeoCoordinates *> *geometry;
/**
* Array of all maneuvers that travelers will encounter along the route.
*/
@property (nonatomic, readonly, strong, nullable) NSArray<NMAFTCRManeuver *> *maneuvers;
/**
* Array of all links in the route.
*/
@property (nonatomic, readonly, strong, nullable) NSArray<NMAFTCRRouteLink *> *routeLinks;
/**
* Estimated total travel distance for the route, in meters.
*/
@property (nonatomic, readonly) NSUInteger length;
/**
* Estimated base time to the final destination, considering transport mode but not traffic
* conditions.
*/
@property (nonatomic, readonly) NSUInteger baseTime;
/**
* Estimated total travel time in seconds optionally considering traffic depending on
* the request parameters.
*/
@property (nonatomic, readonly) NSUInteger travelTime;
/**
* Estimated traffic time to the final destination, considering traffic and transport mode.
*/
@property (nonatomic, readonly) NSUInteger trafficTime;
@end
| 29.965517 | 99 | 0.754507 | [
"geometry"
] |
c4a6ae3bbce900998552f5740abb231b5fe9ad7b | 5,246 | h | C | Assets/Chunity/Plugins/iOS/chuck_emit.h | marek-stoj/Chuckings | fcca01afdc759b8d374c5ab3d31d010c1174af04 | [
"Unlicense"
] | null | null | null | Assets/Chunity/Plugins/iOS/chuck_emit.h | marek-stoj/Chuckings | fcca01afdc759b8d374c5ab3d31d010c1174af04 | [
"Unlicense"
] | null | null | null | Assets/Chunity/Plugins/iOS/chuck_emit.h | marek-stoj/Chuckings | fcca01afdc759b8d374c5ab3d31d010c1174af04 | [
"Unlicense"
] | null | null | null | /*----------------------------------------------------------------------------
ChucK Concurrent, On-the-fly Audio Programming Language
Compiler and Virtual Machine
Copyright (c) 2004 Ge Wang and Perry R. Cook. All rights reserved.
http://chuck.stanford.edu/
http://chuck.cs.princeton.edu/
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307
U.S.A.
-----------------------------------------------------------------------------*/
//-----------------------------------------------------------------------------
// file: chuck_emit.h
// desc: chuck instruction emitter
//
// author: Ge Wang (ge@ccrma.stanford.edu | gewang@cs.princeton.edu)
// date: Autumn 2002 - first version
// Autumn 2004 - redesign
//-----------------------------------------------------------------------------
#ifndef __CHUCK_EMIT_H__
#define __CHUCK_EMIT_H__
#include "chuck_def.h"
#include "chuck_oo.h"
#include "chuck_type.h"
#include "chuck_frame.h"
// forward references
struct Chuck_Instr;
struct Chuck_Instr_Goto;
struct Chuck_VM_Code;
struct Chuck_VM_Shred;
//-----------------------------------------------------------------------------
// name: struct Chuck_Code
// desc: ...
//-----------------------------------------------------------------------------
struct Chuck_Code
{
public:
// name
std::string name;
// stack depth
t_CKUINT stack_depth;
// need this
t_CKBOOL need_this;
// frame
Chuck_Frame * frame;
// code
std::vector<Chuck_Instr *> code;
// continue stack
std::vector<Chuck_Instr_Goto *> stack_cont;
// break stack
std::vector<Chuck_Instr_Goto *> stack_break;
// return stack
std::vector<Chuck_Instr_Goto *> stack_return;
// filename this code came from (added 1.3.0.0)
std::string filename;
// constructor
Chuck_Code( )
{
stack_depth = 0;
need_this = FALSE;
frame = new Chuck_Frame;
}
// destructor
~Chuck_Code() { delete frame; frame = NULL; }
};
//-----------------------------------------------------------------------------
// name: struct Chuck_Emitter
// desc: ...
//-----------------------------------------------------------------------------
struct Chuck_Emitter : public Chuck_VM_Object
{
// reference to the type checker environment
Chuck_Env * env;
// current code
Chuck_Code * code;
// current context
Chuck_Context * context;
// expression namespace
Chuck_Namespace * nspc;
// current function definition
Chuck_Func * func;
// code stack
std::vector<Chuck_Code *> stack;
// locals
std::vector<Chuck_Local *> locals;
// dump
t_CKBOOL dump;
// constructor
Chuck_Emitter()
{ env = NULL; code = NULL; context = NULL;
nspc = NULL; func = NULL; dump = FALSE;
should_replace_dac = FALSE; }
// destructor
~Chuck_Emitter()
{ }
// append instruction
void append( Chuck_Instr * instr )
{ assert( code != NULL ); code->code.push_back( instr ); }
// index
t_CKUINT next_index()
{ assert( code != NULL ); return code->code.size(); }
// push scope
void push_scope( )
{ assert( code != NULL ); code->frame->push_scope(); }
// alloc local (ge: added is_obj 2012 april | added 1.3.0.0)
Chuck_Local * alloc_local( t_CKUINT size, const std::string & name,
t_CKBOOL is_ref, t_CKBOOL is_obj, t_CKBOOL is_global )
{ assert( code != NULL ); return code->frame->alloc_local( size, name,
is_ref, is_obj, is_global ); }
// add references to locals on current scope (added 1.3.0.0)
void addref_on_scope();
// pop scope
void pop_scope( );
// default durations
t_CKBOOL find_dur( const std::string & name, t_CKDUR * out );
// post REFACTOR-2017: replace-dac
std::string dac_replacement;
t_CKBOOL should_replace_dac;
};
// allocate the emitter
Chuck_Emitter * emit_engine_init( Chuck_Env * env );
// shutdown and free the emitter
t_CKBOOL emit_engine_shutdown( Chuck_Emitter *& emit );
// emit a program into vm code
Chuck_VM_Code * emit_engine_emit_prog( Chuck_Emitter * emit,
a_Program prog,
te_HowMuch how_much = te_do_all );
// helper function to emit code
Chuck_VM_Code * emit_to_code( Chuck_Code * in,
Chuck_VM_Code * out = NULL,
t_CKBOOL dump = FALSE );
// NOT USED: ...
t_CKBOOL emit_engine_addr_map( Chuck_Emitter * emit, Chuck_VM_Shred * shred );
t_CKBOOL emit_engine_resolve( );
#endif
| 28.824176 | 79 | 0.57663 | [
"vector"
] |
c4ae415f11980d649da7040ffd74c787fc3f2ecb | 1,393 | h | C | source/GameReader.h | nguyenpham/MRXqOpeningBook | a1ee03ed7a9056601418fa9e209c57bfb0ebc465 | [
"MIT"
] | 2 | 2019-02-06T09:27:09.000Z | 2020-10-31T03:18:07.000Z | source/GameReader.h | nguyenpham/MRXqOpeningBook | a1ee03ed7a9056601418fa9e209c57bfb0ebc465 | [
"MIT"
] | null | null | null | source/GameReader.h | nguyenpham/MRXqOpeningBook | a1ee03ed7a9056601418fa9e209c57bfb0ebc465 | [
"MIT"
] | null | null | null | //
// GameReader.hpp
// Opening
//
// Created by Tony Pham on 4/3/18.
// Copyright © 2018 Softgaroo. All rights reserved.
//
#ifndef GameReader_hpp
#define GameReader_hpp
#include <stdio.h>
#include <string>
#include <list>
#include <map>
#include "Opening.h"
class Move;
class OpeningBoard;
namespace opening {
class GameReader {
public:
GameReader(const std::string& path);
bool init(const std::string& path);
static std::string loadFile(const std::string& fileName);
bool nextGame(OpeningBoard& board);
int currentGameIdx() const {
return workingGameIdx - 1;
}
private:
std::map<std::string, std::string> parse(const std::string& gameString) const;
std::map<std::string, std::string> pgn_parse(const std::string& gameString) const;
bool parse(OpeningBoard& board, const std::string& fen, const std::string& moves, const std::string& result);
opening::Move findLegalMove(OpeningBoard& board, PieceType pieceType, int fromCol, int fromRow, int dest);
std::map<std::string, std::string> wxf_parse(const std::string& gameString) const;
// bool wxf_parse(OpeningBoard& board, const std::string& fen, const std::string& moves);
private:
std::vector<std::string> gameStringVector;
int workingGameIdx;
};
}
#endif /* GameReader_hpp */
| 24.875 | 117 | 0.659009 | [
"vector"
] |
0ecd6e9074580cc9007094981b4521f2efe3a563 | 3,002 | c | C | src/util/pixhist3d-plot3.c | lf-/brlcad | f91ea585c1a930a2e97c3f5a8274db8805ebbb46 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | 83 | 2021-03-10T05:54:52.000Z | 2022-03-31T16:33:46.000Z | src/util/pixhist3d-plot3.c | lf-/brlcad | f91ea585c1a930a2e97c3f5a8274db8805ebbb46 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | 13 | 2021-06-24T17:07:48.000Z | 2022-03-31T15:31:33.000Z | src/util/pixhist3d-plot3.c | lf-/brlcad | f91ea585c1a930a2e97c3f5a8274db8805ebbb46 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | 54 | 2021-03-10T07:57:06.000Z | 2022-03-28T23:20:37.000Z | /* P I X H I S T 3 D - P L O T 3 . C
* BRL-CAD
*
* Copyright (c) 1986-2021 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; see the file named COPYING for more
* information.
*/
/** @file util/pixhist3d-plot3.c
*
* RGB color space utilization to unix plot.
*
* Plots a point for each unique RGB value found in a pix file.
* Resolution is 128 steps along each color axis.
*
*/
#include "common.h"
#include <stdlib.h>
#include "bio.h"
#include "bu/app.h"
#include "bu/exit.h"
#include "vmath.h"
#include "bn.h"
#include "bv/plot3.h"
FILE *fp;
unsigned char bin[128][128][16];
struct pix_element {
unsigned char red, green, blue;
};
static const char *Usage = "Usage: pixhist3d-plot3 [file.pix] | plot\n";
int
main(int argc, char **argv)
{
int n, x;
struct pix_element scan[512];
unsigned char bmask;
bu_setprogname(argv[0]);
setmode(fileno(stdin), O_BINARY);
setmode(fileno(stdout), O_BINARY);
if (argc > 1) {
if ((fp = fopen(argv[1], "rb")) == NULL) {
fprintf(stderr, "%s", Usage);
bu_exit(1, "pixhist3d-plot3: can't open \"%s\"\n", argv[1]);
}
} else
fp = stdin;
if (argc > 2 || isatty(fileno(fp))) {
fputs(Usage, stderr);
return 2;
}
/* Initialize plot */
pl_3space(stdout, 0, 0, 0, 128, 128, 128);
pl_color(stdout, 255, 0, 0);
pl_3line(stdout, 0, 0, 0, 127, 0, 0);
pl_color(stdout, 0, 255, 0);
pl_3line(stdout, 0, 0, 0, 0, 127, 0);
pl_color(stdout, 0, 0, 255);
pl_3line(stdout, 0, 0, 0, 0, 0, 127);
pl_color(stdout, 255, 255, 255);
while ((n = fread(&scan[0], sizeof(*scan), 512, fp)) > 0) {
int ridx, bidx, gidx;
if (n > 512)
n = 512;
for (x = 0; x < n; x++) {
ridx = scan[x].red;
if (ridx < 0)
ridx = 0;
if (ridx > 255)
ridx = 255;
gidx = scan[x].green;
if (gidx < 0)
gidx = 0;
if (gidx > 255)
gidx = 255;
bidx = scan[x].blue;
if (bidx < 0)
bidx = 0;
if (bidx > 255)
bidx = 255;
bmask = 1 << ((bidx >> 1) & 7);
if ((bin[ ridx>>1 ][ gidx>>1 ][ bidx>>4 ] & bmask) == 0) {
/* New color: plot it and mark it */
pl_3point(stdout, ridx>>1, gidx>>1, bidx>>1);
bin[ ridx>>1 ][ gidx>>1 ][ bidx>>4 ] |= bmask;
}
}
}
return 0;
}
/*
* Local Variables:
* mode: C
* tab-width: 8
* indent-tabs-mode: t
* c-file-style: "stroustrup"
* End:
* ex: shiftwidth=4 tabstop=8
*/
| 22.402985 | 72 | 0.598601 | [
"cad"
] |
0ecee5ec0b20f5789f69367021002f1174b11a4b | 1,157 | h | C | felicia/core/master/tool/client_list_flag.h | chokobole/felicia | 3b5eeb5f93c59c5364d3932bc407e054977aa1ec | [
"BSD-3-Clause"
] | 17 | 2018-10-28T13:58:01.000Z | 2022-03-22T07:54:12.000Z | felicia/core/master/tool/client_list_flag.h | chokobole/felicia | 3b5eeb5f93c59c5364d3932bc407e054977aa1ec | [
"BSD-3-Clause"
] | 2 | 2018-11-09T04:15:58.000Z | 2018-11-09T06:42:57.000Z | felicia/core/master/tool/client_list_flag.h | chokobole/felicia | 3b5eeb5f93c59c5364d3932bc407e054977aa1ec | [
"BSD-3-Clause"
] | 5 | 2019-10-31T06:50:05.000Z | 2022-03-22T07:54:30.000Z | // Copyright (c) 2019 The Felicia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FELICIA_CORE_MASTER_TOOL_CLIENT_LIST_FLAG_H_
#define FELICIA_CORE_MASTER_TOOL_CLIENT_LIST_FLAG_H_
#include <memory>
#include "third_party/chromium/base/macros.h"
#include "felicia/core/util/command_line_interface/flag.h"
namespace felicia {
class ClientListFlag : public FlagParser::Delegate {
public:
ClientListFlag();
~ClientListFlag();
const BoolFlag* all_flag() const { return all_flag_.get(); }
const Flag<uint32_t>* id_flag() const { return id_flag_.get(); }
bool Parse(FlagParser& parser) override;
bool Validate() const override;
std::vector<std::string> CollectUsages() const override;
std::string Description() const override;
std::vector<NamedHelpType> CollectNamedHelps() const override;
private:
bool all_;
uint32_t id_;
std::unique_ptr<BoolFlag> all_flag_;
std::unique_ptr<Flag<uint32_t>> id_flag_;
DISALLOW_COPY_AND_ASSIGN(ClientListFlag);
};
} // namespace felicia
#endif // FELICIA_CORE_MASTER_TOOL_CLIENT_LIST_FLAG_H_ | 26.906977 | 73 | 0.765774 | [
"vector"
] |
0ed17784c8ddf9d6426914ea6ef4705d08182519 | 2,535 | h | C | src/editor/CELLeditor.h | kstemp/TESviewer | 2905367f0e30c586633831e0312a7902fb645b4e | [
"MIT"
] | null | null | null | src/editor/CELLeditor.h | kstemp/TESviewer | 2905367f0e30c586633831e0312a7902fb645b4e | [
"MIT"
] | null | null | null | src/editor/CELLeditor.h | kstemp/TESviewer | 2905367f0e30c586633831e0312a7902fb645b4e | [
"MIT"
] | null | null | null | #pragma once
#include <algorithm>
#include <qtablewidget.h>
#include "ui_CELLeditor.h"
#include <esm\records\CELL.h>
#include <esm\Util.h>
#include <esm\File.h>
#include <esm\Group.h>
#include "..\editor\REFReditor.h"
#include "..\render\CellRenderer.h"
#include "..\model\CellChildrenModel.h"
class CELLeditor : public QMainWindow {
Q_OBJECT
ESM::Record* cell;
ESM::File& dataFile;
Ui::CELLeditor ui;
CellRenderer* renderer = nullptr;
CellChildrenModel* model;
QDockWidget* dockREFReditor = nullptr;
void onTableWidgetItemDoubleClicked(QTableWidgetItem* item) {
uint32_t formID = item->data(Qt::UserRole).toUInt();
ESM::Record* record = dataFile.findByFormID(formID);
auto editor = new REFReditor(record, dataFile);
QWidget::connect(editor, &REFReditor::changed, this, [this]() {
this->renderer->update();
});
dockREFReditor->setWidget(editor);
}
public:
CELLeditor(ESM::Record* cell, ESM::File& dataFile, QWidget* parent = Q_NULLPTR, std::function<void(int)> onProgress = [](const int) {})
: QMainWindow(parent), cell(cell), dataFile(dataFile) {
ui.setupUi(this);
setWindowTitle(QString::fromStdString("Cell: " + (*cell)["EDID"].string()));
dockREFReditor = new QDockWidget("Reference", this);
dockREFReditor->setAllowedAreas(Qt::RightDockWidgetArea);
addDockWidget(Qt::RightDockWidgetArea, dockREFReditor);
// connect(ui.refTable, &QTableWidget::itemDoubleClicked, this, &CELLeditor::onTableWidgetItemDoubleClicked);
QWidget::connect(ui.actionSetNavmeshMode, &QAction::triggered, this, [=]() {
renderer->drawNavmesh = !renderer->drawNavmesh;
renderer->update();
});
ui.actionEnableLights->setChecked(true);
QWidget::connect(ui.actionEnableLights, &QAction::triggered, this, [=]() {
renderer->doLighting = ui.actionEnableLights->isChecked();
renderer->update();
});
ui.actionDrawMeshes->setChecked(true);
QWidget::connect(ui.actionDrawMeshes, &QAction::triggered, this, [=]() {
renderer->doMeshes = ui.actionDrawMeshes->isChecked();
renderer->update();
});
std::vector<ESM::Group>* cellChildrenTop = ESM::findCellChildrenTopLevel(cell, dataFile);
ESM::Group* cellChildren = ESM::findCellChildren(cell, cellChildrenTop);
ESM::Group* cellTemporaryChildren = ESM::findCellTemporaryChildren(cell, cellChildren);
model = new CellChildrenModel(cellTemporaryChildren, dataFile);
ui.refTable->setModel(model);
renderer = new CellRenderer(cellTemporaryChildren->records, dataFile, this);
setCentralWidget(renderer);
}
}; | 28.483146 | 136 | 0.726233 | [
"render",
"vector",
"model"
] |
0ed4d5e2cf71226bc452e5550391fb0830abbc73 | 3,470 | h | C | qtserver/engine/mesh.h | jimfinnis/stumpy2 | 4011e42b7082f847396816b1b5aee46d7ce93b2b | [
"MIT"
] | null | null | null | qtserver/engine/mesh.h | jimfinnis/stumpy2 | 4011e42b7082f847396816b1b5aee46d7ce93b2b | [
"MIT"
] | 1 | 2016-05-18T12:03:16.000Z | 2016-10-01T19:05:26.000Z | qtserver/engine/mesh.h | jimfinnis/stumpy2 | 4011e42b7082f847396816b1b5aee46d7ce93b2b | [
"MIT"
] | null | null | null | /* -*- C -*- ****************************************************************
*
* Copyright 2010 Broadsword Games.
* All Rights Reserved
*
*
* System :
* Module :
* Object Name : $RCSfile$
* Revision : $Revision$
* Date : $Date$
* Author : $Author$
* Created By : Jim Finnis
* Created : Tue May 4 14:27:17 2010
* Last Modified : <191228.1357>
*
* Description
*
* Notes
*
* History
*
****************************************************************************
*
* Copyright (c) 2010 Broadsword Games.
*
* All Rights Reserved.
*
* This document may not, in whole or in part, be copied, photocopied,
* reproduced, translated, or reduced to any electronic medium or machine
* readable form without prior written consent from Broadsword Games.
*
****************************************************************************/
#ifndef __MESH_H
#define __MESH_H
#include "maths.h"
#include "texture.h"
#include "renderable.h"
/// a wrapper around a Mesh loaded from an X file.
/// Initialise by calling Init(directory,meshname) where meshname is
/// an X file inside the directory. The textures should be in the same
/// directory, and the X file should refer to them without any directory
/// components to their filenames. Render with Render() - the Mesh Effect
/// in the Application structure will be used.
class Mesh : public Renderable
{
public:
/// Given a directory, load a given .x file and a given set of
/// textures from it.
Mesh(const char *dir,const char *name);
/// release the mesh and the textures
virtual ~Mesh();
/// draw me
virtual void render(Matrix *world);
/// used for batch rendering of many identical meshes. This binds
/// the vertex and index buffers of the nth SingleMesh. Assumes there's
/// only one material in it!
void bindBuffersForBatch(int n);
/// used for batch rendering - set the materials for SingleMesh n's first material. Will use
/// the appropriate effect for textured or untextured.
void setMaterialsForBatch(int n);
/// issue a draw command for the nth submesh, assuming that all
/// uniforms have been set and buffers bound. It will assume that
/// there's only one material, the uniforms for which have been set.
void drawForBatch(int n);
void doparsefailed(int e); // public so SingleMesh can see it
protected:
void parseFrame();
void parseMesh();
/// actually loads the data
void reset();
/// actually deletes the data
void lost();
// render textured components - possibly replacing all textures
// with another one
virtual void renderTex(Matrix *world);
// render untextured components
virtual void renderUntex(Matrix *world);
/// these are the actual meshes
// (a Mesh can be made up of several submeshes within the xfile)
struct SingleMesh *mSubMeshes[16]; // struct defined in mesh.cpp
int mNumSubMeshes;
bool hasuntex; // does it have textured materials?
bool hastex; // does it have untextured materials?
bool hasalpha; // true if it has alpha'd textures
const char *mName;
const char *mDir;
};
#endif /* __MESH_H */
| 29.65812 | 97 | 0.582133 | [
"mesh",
"render",
"object"
] |
0ed5d34101e3ec4c2c8a55b5b0afcb39eaf4c506 | 39,527 | c | C | measurer/gdb-7.9/gdb/nat/linux-osdata.c | armoredsoftware/protocol | e3b0c1df8bc1027865caec6d117e5925f71f26d2 | [
"BSD-3-Clause"
] | null | null | null | measurer/gdb-7.9/gdb/nat/linux-osdata.c | armoredsoftware/protocol | e3b0c1df8bc1027865caec6d117e5925f71f26d2 | [
"BSD-3-Clause"
] | null | null | null | measurer/gdb-7.9/gdb/nat/linux-osdata.c | armoredsoftware/protocol | e3b0c1df8bc1027865caec6d117e5925f71f26d2 | [
"BSD-3-Clause"
] | null | null | null | /* Linux-specific functions to retrieve OS data.
Copyright (C) 2009-2015 Free Software Foundation, Inc.
This file is part of GDB.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include "common-defs.h"
#include "linux-osdata.h"
#include <sys/types.h>
#include <sys/sysinfo.h>
#include <ctype.h>
#include <utmp.h>
#include <time.h>
#include <unistd.h>
#include <pwd.h>
#include <grp.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "xml-utils.h"
#include "buffer.h"
#include <dirent.h>
#include <sys/stat.h>
#include "filestuff.h"
#define NAMELEN(dirent) strlen ((dirent)->d_name)
/* Define PID_T to be a fixed size that is at least as large as pid_t,
so that reading pid values embedded in /proc works
consistently. */
typedef long long PID_T;
/* Define TIME_T to be at least as large as time_t, so that reading
time values embedded in /proc works consistently. */
typedef long long TIME_T;
#define MAX_PID_T_STRLEN (sizeof ("-9223372036854775808") - 1)
/* Returns the CPU core that thread PTID is currently running on. */
/* Compute and return the processor core of a given thread. */
int
linux_common_core_of_thread (ptid_t ptid)
{
char filename[sizeof ("/proc//task//stat") + 2 * MAX_PID_T_STRLEN];
FILE *f;
char *content = NULL;
char *p;
char *ts = 0;
int content_read = 0;
int i;
int core;
sprintf (filename, "/proc/%lld/task/%lld/stat",
(PID_T) ptid_get_pid (ptid), (PID_T) ptid_get_lwp (ptid));
f = gdb_fopen_cloexec (filename, "r");
if (!f)
return -1;
for (;;)
{
int n;
content = xrealloc (content, content_read + 1024);
n = fread (content + content_read, 1, 1024, f);
content_read += n;
if (n < 1024)
{
content[content_read] = '\0';
break;
}
}
/* ps command also relies on no trailing fields ever contain ')'. */
p = strrchr (content, ')');
if (p != NULL)
p++;
/* If the first field after program name has index 0, then core number is
the field with index 36. There's no constant for that anywhere. */
if (p != NULL)
p = strtok_r (p, " ", &ts);
for (i = 0; p != NULL && i != 36; ++i)
p = strtok_r (NULL, " ", &ts);
if (p == NULL || sscanf (p, "%d", &core) == 0)
core = -1;
xfree (content);
fclose (f);
return core;
}
/* Finds the command-line of process PID and copies it into COMMAND.
At most MAXLEN characters are copied. If the command-line cannot
be found, PID is copied into command in text-form. */
static void
command_from_pid (char *command, int maxlen, PID_T pid)
{
char *stat_path = xstrprintf ("/proc/%lld/stat", pid);
FILE *fp = gdb_fopen_cloexec (stat_path, "r");
command[0] = '\0';
if (fp)
{
/* sizeof (cmd) should be greater or equal to TASK_COMM_LEN (in
include/linux/sched.h in the Linux kernel sources) plus two
(for the brackets). */
char cmd[18];
PID_T stat_pid;
int items_read = fscanf (fp, "%lld %17s", &stat_pid, cmd);
if (items_read == 2 && pid == stat_pid)
{
cmd[strlen (cmd) - 1] = '\0'; /* Remove trailing parenthesis. */
strncpy (command, cmd + 1, maxlen); /* Ignore leading parenthesis. */
}
fclose (fp);
}
else
{
/* Return the PID if a /proc entry for the process cannot be found. */
snprintf (command, maxlen, "%lld", pid);
}
command[maxlen - 1] = '\0'; /* Ensure string is null-terminated. */
xfree (stat_path);
}
/* Returns the command-line of the process with the given PID. The
returned string needs to be freed using xfree after use. */
static char *
commandline_from_pid (PID_T pid)
{
char *pathname = xstrprintf ("/proc/%lld/cmdline", pid);
char *commandline = NULL;
FILE *f = gdb_fopen_cloexec (pathname, "r");
if (f)
{
size_t len = 0;
while (!feof (f))
{
char buf[1024];
size_t read_bytes = fread (buf, 1, sizeof (buf), f);
if (read_bytes)
{
commandline = (char *) xrealloc (commandline, len + read_bytes + 1);
memcpy (commandline + len, buf, read_bytes);
len += read_bytes;
}
}
fclose (f);
if (commandline)
{
size_t i;
/* Replace null characters with spaces. */
for (i = 0; i < len; ++i)
if (commandline[i] == '\0')
commandline[i] = ' ';
commandline[len] = '\0';
}
else
{
/* Return the command in square brackets if the command-line
is empty. */
commandline = (char *) xmalloc (32);
commandline[0] = '[';
command_from_pid (commandline + 1, 31, pid);
len = strlen (commandline);
if (len < 31)
strcat (commandline, "]");
}
}
xfree (pathname);
return commandline;
}
/* Finds the user name for the user UID and copies it into USER. At
most MAXLEN characters are copied. */
static void
user_from_uid (char *user, int maxlen, uid_t uid)
{
struct passwd *pwentry = getpwuid (uid);
if (pwentry)
{
strncpy (user, pwentry->pw_name, maxlen);
/* Ensure that the user name is null-terminated. */
user[maxlen - 1] = '\0';
}
else
user[0] = '\0';
}
/* Finds the owner of process PID and returns the user id in OWNER.
Returns 0 if the owner was found, -1 otherwise. */
static int
get_process_owner (uid_t *owner, PID_T pid)
{
struct stat statbuf;
char procentry[sizeof ("/proc/") + MAX_PID_T_STRLEN];
sprintf (procentry, "/proc/%lld", pid);
if (stat (procentry, &statbuf) == 0 && S_ISDIR (statbuf.st_mode))
{
*owner = statbuf.st_uid;
return 0;
}
else
return -1;
}
/* Find the CPU cores used by process PID and return them in CORES.
CORES points to an array of NUM_CORES elements. */
static int
get_cores_used_by_process (PID_T pid, int *cores, const int num_cores)
{
char taskdir[sizeof ("/proc/") + MAX_PID_T_STRLEN + sizeof ("/task") - 1];
DIR *dir;
struct dirent *dp;
int task_count = 0;
sprintf (taskdir, "/proc/%lld/task", pid);
dir = opendir (taskdir);
if (dir)
{
while ((dp = readdir (dir)) != NULL)
{
PID_T tid;
int core;
if (!isdigit (dp->d_name[0])
|| NAMELEN (dp) > MAX_PID_T_STRLEN)
continue;
sscanf (dp->d_name, "%lld", &tid);
core = linux_common_core_of_thread (ptid_build ((pid_t) pid,
(pid_t) tid, 0));
if (core >= 0 && core < num_cores)
{
++cores[core];
++task_count;
}
}
closedir (dir);
}
return task_count;
}
static LONGEST
linux_xfer_osdata_processes (gdb_byte *readbuf,
ULONGEST offset, ULONGEST len)
{
/* We make the process list snapshot when the object starts to be read. */
static const char *buf;
static LONGEST len_avail = -1;
static struct buffer buffer;
if (offset == 0)
{
DIR *dirp;
if (len_avail != -1 && len_avail != 0)
buffer_free (&buffer);
len_avail = 0;
buf = NULL;
buffer_init (&buffer);
buffer_grow_str (&buffer, "<osdata type=\"processes\">\n");
dirp = opendir ("/proc");
if (dirp)
{
const int num_cores = sysconf (_SC_NPROCESSORS_ONLN);
struct dirent *dp;
while ((dp = readdir (dirp)) != NULL)
{
PID_T pid;
uid_t owner;
char user[UT_NAMESIZE];
char *command_line;
int *cores;
int task_count;
char *cores_str;
int i;
if (!isdigit (dp->d_name[0])
|| NAMELEN (dp) > MAX_PID_T_STRLEN)
continue;
sscanf (dp->d_name, "%lld", &pid);
command_line = commandline_from_pid (pid);
if (get_process_owner (&owner, pid) == 0)
user_from_uid (user, sizeof (user), owner);
else
strcpy (user, "?");
/* Find CPU cores used by the process. */
cores = (int *) xcalloc (num_cores, sizeof (int));
task_count = get_cores_used_by_process (pid, cores, num_cores);
cores_str = (char *) xcalloc (task_count, sizeof ("4294967295") + 1);
for (i = 0; i < num_cores && task_count > 0; ++i)
if (cores[i])
{
char core_str[sizeof ("4294967295")];
sprintf (core_str, "%d", i);
strcat (cores_str, core_str);
task_count -= cores[i];
if (task_count > 0)
strcat (cores_str, ",");
}
xfree (cores);
buffer_xml_printf (
&buffer,
"<item>"
"<column name=\"pid\">%lld</column>"
"<column name=\"user\">%s</column>"
"<column name=\"command\">%s</column>"
"<column name=\"cores\">%s</column>"
"</item>",
pid,
user,
command_line ? command_line : "",
cores_str);
xfree (command_line);
xfree (cores_str);
}
closedir (dirp);
}
buffer_grow_str0 (&buffer, "</osdata>\n");
buf = buffer_finish (&buffer);
len_avail = strlen (buf);
}
if (offset >= len_avail)
{
/* Done. Get rid of the buffer. */
buffer_free (&buffer);
buf = NULL;
len_avail = 0;
return 0;
}
if (len > len_avail - offset)
len = len_avail - offset;
memcpy (readbuf, buf + offset, len);
return len;
}
/* Auxiliary function used by qsort to sort processes by process
group. Compares two processes with ids PROCESS1 and PROCESS2.
PROCESS1 comes before PROCESS2 if it has a lower process group id.
If they belong to the same process group, PROCESS1 comes before
PROCESS2 if it has a lower process id or is the process group
leader. */
static int
compare_processes (const void *process1, const void *process2)
{
PID_T pid1 = *((PID_T *) process1);
PID_T pid2 = *((PID_T *) process2);
PID_T pgid1 = *((PID_T *) process1 + 1);
PID_T pgid2 = *((PID_T *) process2 + 1);
/* Sort by PGID. */
if (pgid1 < pgid2)
return -1;
else if (pgid1 > pgid2)
return 1;
else
{
/* Process group leaders always come first, else sort by PID. */
if (pid1 == pgid1)
return -1;
else if (pid2 == pgid2)
return 1;
else if (pid1 < pid2)
return -1;
else if (pid1 > pid2)
return 1;
else
return 0;
}
}
/* Collect all process groups from /proc. */
static LONGEST
linux_xfer_osdata_processgroups (gdb_byte *readbuf,
ULONGEST offset, ULONGEST len)
{
/* We make the process list snapshot when the object starts to be read. */
static const char *buf;
static LONGEST len_avail = -1;
static struct buffer buffer;
if (offset == 0)
{
DIR *dirp;
if (len_avail != -1 && len_avail != 0)
buffer_free (&buffer);
len_avail = 0;
buf = NULL;
buffer_init (&buffer);
buffer_grow_str (&buffer, "<osdata type=\"process groups\">\n");
dirp = opendir ("/proc");
if (dirp)
{
struct dirent *dp;
const size_t list_block_size = 512;
PID_T *process_list = (PID_T *) xmalloc (list_block_size * 2 * sizeof (PID_T));
size_t process_count = 0;
size_t i;
/* Build list consisting of PIDs followed by their
associated PGID. */
while ((dp = readdir (dirp)) != NULL)
{
PID_T pid, pgid;
if (!isdigit (dp->d_name[0])
|| NAMELEN (dp) > MAX_PID_T_STRLEN)
continue;
sscanf (dp->d_name, "%lld", &pid);
pgid = getpgid (pid);
if (pgid > 0)
{
process_list[2 * process_count] = pid;
process_list[2 * process_count + 1] = pgid;
++process_count;
/* Increase the size of the list if necessary. */
if (process_count % list_block_size == 0)
process_list = (PID_T *) xrealloc (
process_list,
(process_count + list_block_size)
* 2 * sizeof (PID_T));
}
}
closedir (dirp);
/* Sort the process list. */
qsort (process_list, process_count, 2 * sizeof (PID_T),
compare_processes);
for (i = 0; i < process_count; ++i)
{
PID_T pid = process_list[2 * i];
PID_T pgid = process_list[2 * i + 1];
char leader_command[32];
char *command_line;
command_from_pid (leader_command, sizeof (leader_command), pgid);
command_line = commandline_from_pid (pid);
buffer_xml_printf (
&buffer,
"<item>"
"<column name=\"pgid\">%lld</column>"
"<column name=\"leader command\">%s</column>"
"<column name=\"pid\">%lld</column>"
"<column name=\"command line\">%s</column>"
"</item>",
pgid,
leader_command,
pid,
command_line ? command_line : "");
xfree (command_line);
}
xfree (process_list);
}
buffer_grow_str0 (&buffer, "</osdata>\n");
buf = buffer_finish (&buffer);
len_avail = strlen (buf);
}
if (offset >= len_avail)
{
/* Done. Get rid of the buffer. */
buffer_free (&buffer);
buf = NULL;
len_avail = 0;
return 0;
}
if (len > len_avail - offset)
len = len_avail - offset;
memcpy (readbuf, buf + offset, len);
return len;
}
/* Collect all the threads in /proc by iterating through processes and
then tasks within each process. */
static LONGEST
linux_xfer_osdata_threads (gdb_byte *readbuf,
ULONGEST offset, ULONGEST len)
{
/* We make the process list snapshot when the object starts to be read. */
static const char *buf;
static LONGEST len_avail = -1;
static struct buffer buffer;
if (offset == 0)
{
DIR *dirp;
if (len_avail != -1 && len_avail != 0)
buffer_free (&buffer);
len_avail = 0;
buf = NULL;
buffer_init (&buffer);
buffer_grow_str (&buffer, "<osdata type=\"threads\">\n");
dirp = opendir ("/proc");
if (dirp)
{
struct dirent *dp;
while ((dp = readdir (dirp)) != NULL)
{
struct stat statbuf;
char procentry[sizeof ("/proc/4294967295")];
if (!isdigit (dp->d_name[0])
|| NAMELEN (dp) > sizeof ("4294967295") - 1)
continue;
sprintf (procentry, "/proc/%s", dp->d_name);
if (stat (procentry, &statbuf) == 0
&& S_ISDIR (statbuf.st_mode))
{
DIR *dirp2;
char *pathname;
PID_T pid;
char command[32];
pathname = xstrprintf ("/proc/%s/task", dp->d_name);
pid = atoi (dp->d_name);
command_from_pid (command, sizeof (command), pid);
dirp2 = opendir (pathname);
if (dirp2)
{
struct dirent *dp2;
while ((dp2 = readdir (dirp2)) != NULL)
{
PID_T tid;
int core;
if (!isdigit (dp2->d_name[0])
|| NAMELEN (dp2) > sizeof ("4294967295") - 1)
continue;
tid = atoi (dp2->d_name);
core = linux_common_core_of_thread (ptid_build (pid, tid, 0));
buffer_xml_printf (
&buffer,
"<item>"
"<column name=\"pid\">%lld</column>"
"<column name=\"command\">%s</column>"
"<column name=\"tid\">%lld</column>"
"<column name=\"core\">%d</column>"
"</item>",
pid,
command,
tid,
core);
}
closedir (dirp2);
}
xfree (pathname);
}
}
closedir (dirp);
}
buffer_grow_str0 (&buffer, "</osdata>\n");
buf = buffer_finish (&buffer);
len_avail = strlen (buf);
}
if (offset >= len_avail)
{
/* Done. Get rid of the buffer. */
buffer_free (&buffer);
buf = NULL;
len_avail = 0;
return 0;
}
if (len > len_avail - offset)
len = len_avail - offset;
memcpy (readbuf, buf + offset, len);
return len;
}
/* Collect all the open file descriptors found in /proc and put the details
found about them into READBUF. */
static LONGEST
linux_xfer_osdata_fds (gdb_byte *readbuf,
ULONGEST offset, ULONGEST len)
{
/* We make the process list snapshot when the object starts to be read. */
static const char *buf;
static LONGEST len_avail = -1;
static struct buffer buffer;
if (offset == 0)
{
DIR *dirp;
if (len_avail != -1 && len_avail != 0)
buffer_free (&buffer);
len_avail = 0;
buf = NULL;
buffer_init (&buffer);
buffer_grow_str (&buffer, "<osdata type=\"files\">\n");
dirp = opendir ("/proc");
if (dirp)
{
struct dirent *dp;
while ((dp = readdir (dirp)) != NULL)
{
struct stat statbuf;
char procentry[sizeof ("/proc/4294967295")];
if (!isdigit (dp->d_name[0])
|| NAMELEN (dp) > sizeof ("4294967295") - 1)
continue;
sprintf (procentry, "/proc/%s", dp->d_name);
if (stat (procentry, &statbuf) == 0
&& S_ISDIR (statbuf.st_mode))
{
char *pathname;
DIR *dirp2;
PID_T pid;
char command[32];
pid = atoi (dp->d_name);
command_from_pid (command, sizeof (command), pid);
pathname = xstrprintf ("/proc/%s/fd", dp->d_name);
dirp2 = opendir (pathname);
if (dirp2)
{
struct dirent *dp2;
while ((dp2 = readdir (dirp2)) != NULL)
{
char *fdname;
char buf[1000];
ssize_t rslt;
if (!isdigit (dp2->d_name[0]))
continue;
fdname = xstrprintf ("%s/%s", pathname, dp2->d_name);
rslt = readlink (fdname, buf, sizeof (buf) - 1);
if (rslt >= 0)
buf[rslt] = '\0';
buffer_xml_printf (
&buffer,
"<item>"
"<column name=\"pid\">%s</column>"
"<column name=\"command\">%s</column>"
"<column name=\"file descriptor\">%s</column>"
"<column name=\"name\">%s</column>"
"</item>",
dp->d_name,
command,
dp2->d_name,
(rslt >= 0 ? buf : dp2->d_name));
}
closedir (dirp2);
}
xfree (pathname);
}
}
closedir (dirp);
}
buffer_grow_str0 (&buffer, "</osdata>\n");
buf = buffer_finish (&buffer);
len_avail = strlen (buf);
}
if (offset >= len_avail)
{
/* Done. Get rid of the buffer. */
buffer_free (&buffer);
buf = NULL;
len_avail = 0;
return 0;
}
if (len > len_avail - offset)
len = len_avail - offset;
memcpy (readbuf, buf + offset, len);
return len;
}
/* Returns the socket state STATE in textual form. */
static const char *
format_socket_state (unsigned char state)
{
/* Copied from include/net/tcp_states.h in the Linux kernel sources. */
enum {
TCP_ESTABLISHED = 1,
TCP_SYN_SENT,
TCP_SYN_RECV,
TCP_FIN_WAIT1,
TCP_FIN_WAIT2,
TCP_TIME_WAIT,
TCP_CLOSE,
TCP_CLOSE_WAIT,
TCP_LAST_ACK,
TCP_LISTEN,
TCP_CLOSING
};
switch (state)
{
case TCP_ESTABLISHED:
return "ESTABLISHED";
case TCP_SYN_SENT:
return "SYN_SENT";
case TCP_SYN_RECV:
return "SYN_RECV";
case TCP_FIN_WAIT1:
return "FIN_WAIT1";
case TCP_FIN_WAIT2:
return "FIN_WAIT2";
case TCP_TIME_WAIT:
return "TIME_WAIT";
case TCP_CLOSE:
return "CLOSE";
case TCP_CLOSE_WAIT:
return "CLOSE_WAIT";
case TCP_LAST_ACK:
return "LAST_ACK";
case TCP_LISTEN:
return "LISTEN";
case TCP_CLOSING:
return "CLOSING";
default:
return "(unknown)";
}
}
union socket_addr
{
struct sockaddr sa;
struct sockaddr_in sin;
struct sockaddr_in6 sin6;
};
/* Auxiliary function used by linux_xfer_osdata_isocket. Formats
information for all open internet sockets of type FAMILY on the
system into BUFFER. If TCP is set, only TCP sockets are processed,
otherwise only UDP sockets are processed. */
static void
print_sockets (unsigned short family, int tcp, struct buffer *buffer)
{
const char *proc_file;
FILE *fp;
if (family == AF_INET)
proc_file = tcp ? "/proc/net/tcp" : "/proc/net/udp";
else if (family == AF_INET6)
proc_file = tcp ? "/proc/net/tcp6" : "/proc/net/udp6";
else
return;
fp = gdb_fopen_cloexec (proc_file, "r");
if (fp)
{
char buf[8192];
do
{
if (fgets (buf, sizeof (buf), fp))
{
uid_t uid;
unsigned int local_port, remote_port, state;
char local_address[NI_MAXHOST], remote_address[NI_MAXHOST];
int result;
#if NI_MAXHOST <= 32
#error "local_address and remote_address buffers too small"
#endif
result = sscanf (buf,
"%*d: %32[0-9A-F]:%X %32[0-9A-F]:%X %X %*X:%*X %*X:%*X %*X %d %*d %*u %*s\n",
local_address, &local_port,
remote_address, &remote_port,
&state,
&uid);
if (result == 6)
{
union socket_addr locaddr, remaddr;
size_t addr_size;
char user[UT_NAMESIZE];
char local_service[NI_MAXSERV], remote_service[NI_MAXSERV];
if (family == AF_INET)
{
sscanf (local_address, "%X",
&locaddr.sin.sin_addr.s_addr);
sscanf (remote_address, "%X",
&remaddr.sin.sin_addr.s_addr);
locaddr.sin.sin_port = htons (local_port);
remaddr.sin.sin_port = htons (remote_port);
addr_size = sizeof (struct sockaddr_in);
}
else
{
sscanf (local_address, "%8X%8X%8X%8X",
locaddr.sin6.sin6_addr.s6_addr32,
locaddr.sin6.sin6_addr.s6_addr32 + 1,
locaddr.sin6.sin6_addr.s6_addr32 + 2,
locaddr.sin6.sin6_addr.s6_addr32 + 3);
sscanf (remote_address, "%8X%8X%8X%8X",
remaddr.sin6.sin6_addr.s6_addr32,
remaddr.sin6.sin6_addr.s6_addr32 + 1,
remaddr.sin6.sin6_addr.s6_addr32 + 2,
remaddr.sin6.sin6_addr.s6_addr32 + 3);
locaddr.sin6.sin6_port = htons (local_port);
remaddr.sin6.sin6_port = htons (remote_port);
locaddr.sin6.sin6_flowinfo = 0;
remaddr.sin6.sin6_flowinfo = 0;
locaddr.sin6.sin6_scope_id = 0;
remaddr.sin6.sin6_scope_id = 0;
addr_size = sizeof (struct sockaddr_in6);
}
locaddr.sa.sa_family = remaddr.sa.sa_family = family;
result = getnameinfo (&locaddr.sa, addr_size,
local_address, sizeof (local_address),
local_service, sizeof (local_service),
NI_NUMERICHOST | NI_NUMERICSERV
| (tcp ? 0 : NI_DGRAM));
if (result)
continue;
result = getnameinfo (&remaddr.sa, addr_size,
remote_address,
sizeof (remote_address),
remote_service,
sizeof (remote_service),
NI_NUMERICHOST | NI_NUMERICSERV
| (tcp ? 0 : NI_DGRAM));
if (result)
continue;
user_from_uid (user, sizeof (user), uid);
buffer_xml_printf (
buffer,
"<item>"
"<column name=\"local address\">%s</column>"
"<column name=\"local port\">%s</column>"
"<column name=\"remote address\">%s</column>"
"<column name=\"remote port\">%s</column>"
"<column name=\"state\">%s</column>"
"<column name=\"user\">%s</column>"
"<column name=\"family\">%s</column>"
"<column name=\"protocol\">%s</column>"
"</item>",
local_address,
local_service,
remote_address,
remote_service,
format_socket_state (state),
user,
(family == AF_INET) ? "INET" : "INET6",
tcp ? "STREAM" : "DGRAM");
}
}
}
while (!feof (fp));
fclose (fp);
}
}
/* Collect data about internet sockets and write it into READBUF. */
static LONGEST
linux_xfer_osdata_isockets (gdb_byte *readbuf,
ULONGEST offset, ULONGEST len)
{
static const char *buf;
static LONGEST len_avail = -1;
static struct buffer buffer;
if (offset == 0)
{
if (len_avail != -1 && len_avail != 0)
buffer_free (&buffer);
len_avail = 0;
buf = NULL;
buffer_init (&buffer);
buffer_grow_str (&buffer, "<osdata type=\"I sockets\">\n");
print_sockets (AF_INET, 1, &buffer);
print_sockets (AF_INET, 0, &buffer);
print_sockets (AF_INET6, 1, &buffer);
print_sockets (AF_INET6, 0, &buffer);
buffer_grow_str0 (&buffer, "</osdata>\n");
buf = buffer_finish (&buffer);
len_avail = strlen (buf);
}
if (offset >= len_avail)
{
/* Done. Get rid of the buffer. */
buffer_free (&buffer);
buf = NULL;
len_avail = 0;
return 0;
}
if (len > len_avail - offset)
len = len_avail - offset;
memcpy (readbuf, buf + offset, len);
return len;
}
/* Converts the time SECONDS into textual form and copies it into a
buffer TIME, with at most MAXLEN characters copied. */
static void
time_from_time_t (char *time, int maxlen, TIME_T seconds)
{
if (!seconds)
time[0] = '\0';
else
{
time_t t = (time_t) seconds;
strncpy (time, ctime (&t), maxlen);
time[maxlen - 1] = '\0';
}
}
/* Finds the group name for the group GID and copies it into GROUP.
At most MAXLEN characters are copied. */
static void
group_from_gid (char *group, int maxlen, gid_t gid)
{
struct group *grentry = getgrgid (gid);
if (grentry)
{
strncpy (group, grentry->gr_name, maxlen);
/* Ensure that the group name is null-terminated. */
group[maxlen - 1] = '\0';
}
else
group[0] = '\0';
}
/* Collect data about shared memory recorded in /proc and write it
into READBUF. */
static LONGEST
linux_xfer_osdata_shm (gdb_byte *readbuf,
ULONGEST offset, ULONGEST len)
{
static const char *buf;
static LONGEST len_avail = -1;
static struct buffer buffer;
if (offset == 0)
{
FILE *fp;
if (len_avail != -1 && len_avail != 0)
buffer_free (&buffer);
len_avail = 0;
buf = NULL;
buffer_init (&buffer);
buffer_grow_str (&buffer, "<osdata type=\"shared memory\">\n");
fp = gdb_fopen_cloexec ("/proc/sysvipc/shm", "r");
if (fp)
{
char buf[8192];
do
{
if (fgets (buf, sizeof (buf), fp))
{
key_t key;
uid_t uid, cuid;
gid_t gid, cgid;
PID_T cpid, lpid;
int shmid, size, nattch;
TIME_T atime, dtime, ctime;
unsigned int perms;
int items_read;
items_read = sscanf (buf,
"%d %d %o %d %lld %lld %d %u %u %u %u %lld %lld %lld",
&key, &shmid, &perms, &size,
&cpid, &lpid,
&nattch,
&uid, &gid, &cuid, &cgid,
&atime, &dtime, &ctime);
if (items_read == 14)
{
char user[UT_NAMESIZE], group[UT_NAMESIZE];
char cuser[UT_NAMESIZE], cgroup[UT_NAMESIZE];
char ccmd[32], lcmd[32];
char atime_str[32], dtime_str[32], ctime_str[32];
user_from_uid (user, sizeof (user), uid);
group_from_gid (group, sizeof (group), gid);
user_from_uid (cuser, sizeof (cuser), cuid);
group_from_gid (cgroup, sizeof (cgroup), cgid);
command_from_pid (ccmd, sizeof (ccmd), cpid);
command_from_pid (lcmd, sizeof (lcmd), lpid);
time_from_time_t (atime_str, sizeof (atime_str), atime);
time_from_time_t (dtime_str, sizeof (dtime_str), dtime);
time_from_time_t (ctime_str, sizeof (ctime_str), ctime);
buffer_xml_printf (
&buffer,
"<item>"
"<column name=\"key\">%d</column>"
"<column name=\"shmid\">%d</column>"
"<column name=\"permissions\">%o</column>"
"<column name=\"size\">%d</column>"
"<column name=\"creator command\">%s</column>"
"<column name=\"last op. command\">%s</column>"
"<column name=\"num attached\">%d</column>"
"<column name=\"user\">%s</column>"
"<column name=\"group\">%s</column>"
"<column name=\"creator user\">%s</column>"
"<column name=\"creator group\">%s</column>"
"<column name=\"last shmat() time\">%s</column>"
"<column name=\"last shmdt() time\">%s</column>"
"<column name=\"last shmctl() time\">%s</column>"
"</item>",
key,
shmid,
perms,
size,
ccmd,
lcmd,
nattch,
user,
group,
cuser,
cgroup,
atime_str,
dtime_str,
ctime_str);
}
}
}
while (!feof (fp));
fclose (fp);
}
buffer_grow_str0 (&buffer, "</osdata>\n");
buf = buffer_finish (&buffer);
len_avail = strlen (buf);
}
if (offset >= len_avail)
{
/* Done. Get rid of the buffer. */
buffer_free (&buffer);
buf = NULL;
len_avail = 0;
return 0;
}
if (len > len_avail - offset)
len = len_avail - offset;
memcpy (readbuf, buf + offset, len);
return len;
}
/* Collect data about semaphores recorded in /proc and write it
into READBUF. */
static LONGEST
linux_xfer_osdata_sem (gdb_byte *readbuf,
ULONGEST offset, ULONGEST len)
{
static const char *buf;
static LONGEST len_avail = -1;
static struct buffer buffer;
if (offset == 0)
{
FILE *fp;
if (len_avail != -1 && len_avail != 0)
buffer_free (&buffer);
len_avail = 0;
buf = NULL;
buffer_init (&buffer);
buffer_grow_str (&buffer, "<osdata type=\"semaphores\">\n");
fp = gdb_fopen_cloexec ("/proc/sysvipc/sem", "r");
if (fp)
{
char buf[8192];
do
{
if (fgets (buf, sizeof (buf), fp))
{
key_t key;
uid_t uid, cuid;
gid_t gid, cgid;
unsigned int perms, nsems;
int semid;
TIME_T otime, ctime;
int items_read;
items_read = sscanf (buf,
"%d %d %o %u %d %d %d %d %lld %lld",
&key, &semid, &perms, &nsems,
&uid, &gid, &cuid, &cgid,
&otime, &ctime);
if (items_read == 10)
{
char user[UT_NAMESIZE], group[UT_NAMESIZE];
char cuser[UT_NAMESIZE], cgroup[UT_NAMESIZE];
char otime_str[32], ctime_str[32];
user_from_uid (user, sizeof (user), uid);
group_from_gid (group, sizeof (group), gid);
user_from_uid (cuser, sizeof (cuser), cuid);
group_from_gid (cgroup, sizeof (cgroup), cgid);
time_from_time_t (otime_str, sizeof (otime_str), otime);
time_from_time_t (ctime_str, sizeof (ctime_str), ctime);
buffer_xml_printf (
&buffer,
"<item>"
"<column name=\"key\">%d</column>"
"<column name=\"semid\">%d</column>"
"<column name=\"permissions\">%o</column>"
"<column name=\"num semaphores\">%u</column>"
"<column name=\"user\">%s</column>"
"<column name=\"group\">%s</column>"
"<column name=\"creator user\">%s</column>"
"<column name=\"creator group\">%s</column>"
"<column name=\"last semop() time\">%s</column>"
"<column name=\"last semctl() time\">%s</column>"
"</item>",
key,
semid,
perms,
nsems,
user,
group,
cuser,
cgroup,
otime_str,
ctime_str);
}
}
}
while (!feof (fp));
fclose (fp);
}
buffer_grow_str0 (&buffer, "</osdata>\n");
buf = buffer_finish (&buffer);
len_avail = strlen (buf);
}
if (offset >= len_avail)
{
/* Done. Get rid of the buffer. */
buffer_free (&buffer);
buf = NULL;
len_avail = 0;
return 0;
}
if (len > len_avail - offset)
len = len_avail - offset;
memcpy (readbuf, buf + offset, len);
return len;
}
/* Collect data about message queues recorded in /proc and write it
into READBUF. */
static LONGEST
linux_xfer_osdata_msg (gdb_byte *readbuf,
ULONGEST offset, ULONGEST len)
{
static const char *buf;
static LONGEST len_avail = -1;
static struct buffer buffer;
if (offset == 0)
{
FILE *fp;
if (len_avail != -1 && len_avail != 0)
buffer_free (&buffer);
len_avail = 0;
buf = NULL;
buffer_init (&buffer);
buffer_grow_str (&buffer, "<osdata type=\"message queues\">\n");
fp = gdb_fopen_cloexec ("/proc/sysvipc/msg", "r");
if (fp)
{
char buf[8192];
do
{
if (fgets (buf, sizeof (buf), fp))
{
key_t key;
PID_T lspid, lrpid;
uid_t uid, cuid;
gid_t gid, cgid;
unsigned int perms, cbytes, qnum;
int msqid;
TIME_T stime, rtime, ctime;
int items_read;
items_read = sscanf (buf,
"%d %d %o %u %u %lld %lld %d %d %d %d %lld %lld %lld",
&key, &msqid, &perms, &cbytes, &qnum,
&lspid, &lrpid, &uid, &gid, &cuid, &cgid,
&stime, &rtime, &ctime);
if (items_read == 14)
{
char user[UT_NAMESIZE], group[UT_NAMESIZE];
char cuser[UT_NAMESIZE], cgroup[UT_NAMESIZE];
char lscmd[32], lrcmd[32];
char stime_str[32], rtime_str[32], ctime_str[32];
user_from_uid (user, sizeof (user), uid);
group_from_gid (group, sizeof (group), gid);
user_from_uid (cuser, sizeof (cuser), cuid);
group_from_gid (cgroup, sizeof (cgroup), cgid);
command_from_pid (lscmd, sizeof (lscmd), lspid);
command_from_pid (lrcmd, sizeof (lrcmd), lrpid);
time_from_time_t (stime_str, sizeof (stime_str), stime);
time_from_time_t (rtime_str, sizeof (rtime_str), rtime);
time_from_time_t (ctime_str, sizeof (ctime_str), ctime);
buffer_xml_printf (
&buffer,
"<item>"
"<column name=\"key\">%d</column>"
"<column name=\"msqid\">%d</column>"
"<column name=\"permissions\">%o</column>"
"<column name=\"num used bytes\">%u</column>"
"<column name=\"num messages\">%u</column>"
"<column name=\"last msgsnd() command\">%s</column>"
"<column name=\"last msgrcv() command\">%s</column>"
"<column name=\"user\">%s</column>"
"<column name=\"group\">%s</column>"
"<column name=\"creator user\">%s</column>"
"<column name=\"creator group\">%s</column>"
"<column name=\"last msgsnd() time\">%s</column>"
"<column name=\"last msgrcv() time\">%s</column>"
"<column name=\"last msgctl() time\">%s</column>"
"</item>",
key,
msqid,
perms,
cbytes,
qnum,
lscmd,
lrcmd,
user,
group,
cuser,
cgroup,
stime_str,
rtime_str,
ctime_str);
}
}
}
while (!feof (fp));
fclose (fp);
}
buffer_grow_str0 (&buffer, "</osdata>\n");
buf = buffer_finish (&buffer);
len_avail = strlen (buf);
}
if (offset >= len_avail)
{
/* Done. Get rid of the buffer. */
buffer_free (&buffer);
buf = NULL;
len_avail = 0;
return 0;
}
if (len > len_avail - offset)
len = len_avail - offset;
memcpy (readbuf, buf + offset, len);
return len;
}
/* Collect data about loaded kernel modules and write it into
READBUF. */
static LONGEST
linux_xfer_osdata_modules (gdb_byte *readbuf,
ULONGEST offset, ULONGEST len)
{
static const char *buf;
static LONGEST len_avail = -1;
static struct buffer buffer;
if (offset == 0)
{
FILE *fp;
if (len_avail != -1 && len_avail != 0)
buffer_free (&buffer);
len_avail = 0;
buf = NULL;
buffer_init (&buffer);
buffer_grow_str (&buffer, "<osdata type=\"modules\">\n");
fp = gdb_fopen_cloexec ("/proc/modules", "r");
if (fp)
{
char buf[8192];
do
{
if (fgets (buf, sizeof (buf), fp))
{
char *name, *dependencies, *status, *tmp;
unsigned int size;
unsigned long long address;
int uses;
name = strtok (buf, " ");
if (name == NULL)
continue;
tmp = strtok (NULL, " ");
if (tmp == NULL)
continue;
if (sscanf (tmp, "%u", &size) != 1)
continue;
tmp = strtok (NULL, " ");
if (tmp == NULL)
continue;
if (sscanf (tmp, "%d", &uses) != 1)
continue;
dependencies = strtok (NULL, " ");
if (dependencies == NULL)
continue;
status = strtok (NULL, " ");
if (status == NULL)
continue;
tmp = strtok (NULL, "\n");
if (tmp == NULL)
continue;
if (sscanf (tmp, "%llx", &address) != 1)
continue;
buffer_xml_printf (
&buffer,
"<item>"
"<column name=\"name\">%s</column>"
"<column name=\"size\">%u</column>"
"<column name=\"num uses\">%d</column>"
"<column name=\"dependencies\">%s</column>"
"<column name=\"status\">%s</column>"
"<column name=\"address\">%llx</column>"
"</item>",
name,
size,
uses,
dependencies,
status,
address);
}
}
while (!feof (fp));
fclose (fp);
}
buffer_grow_str0 (&buffer, "</osdata>\n");
buf = buffer_finish (&buffer);
len_avail = strlen (buf);
}
if (offset >= len_avail)
{
/* Done. Get rid of the buffer. */
buffer_free (&buffer);
buf = NULL;
len_avail = 0;
return 0;
}
if (len > len_avail - offset)
len = len_avail - offset;
memcpy (readbuf, buf + offset, len);
return len;
}
struct osdata_type {
char *type;
char *title;
char *description;
LONGEST (*getter) (gdb_byte *readbuf, ULONGEST offset, ULONGEST len);
} osdata_table[] = {
{ "processes", "Processes", "Listing of all processes",
linux_xfer_osdata_processes },
{ "procgroups", "Process groups", "Listing of all process groups",
linux_xfer_osdata_processgroups },
{ "threads", "Threads", "Listing of all threads",
linux_xfer_osdata_threads },
{ "files", "File descriptors", "Listing of all file descriptors",
linux_xfer_osdata_fds },
{ "sockets", "Sockets", "Listing of all internet-domain sockets",
linux_xfer_osdata_isockets },
{ "shm", "Shared-memory regions", "Listing of all shared-memory regions",
linux_xfer_osdata_shm },
{ "semaphores", "Semaphores", "Listing of all semaphores",
linux_xfer_osdata_sem },
{ "msg", "Message queues", "Listing of all message queues",
linux_xfer_osdata_msg },
{ "modules", "Kernel modules", "Listing of all loaded kernel modules",
linux_xfer_osdata_modules },
{ NULL, NULL, NULL }
};
LONGEST
linux_common_xfer_osdata (const char *annex, gdb_byte *readbuf,
ULONGEST offset, ULONGEST len)
{
if (!annex || *annex == '\0')
{
static const char *buf;
static LONGEST len_avail = -1;
static struct buffer buffer;
if (offset == 0)
{
int i;
if (len_avail != -1 && len_avail != 0)
buffer_free (&buffer);
len_avail = 0;
buf = NULL;
buffer_init (&buffer);
buffer_grow_str (&buffer, "<osdata type=\"types\">\n");
for (i = 0; osdata_table[i].type; ++i)
buffer_xml_printf (
&buffer,
"<item>"
"<column name=\"Type\">%s</column>"
"<column name=\"Description\">%s</column>"
"<column name=\"Title\">%s</column>"
"</item>",
osdata_table[i].type,
osdata_table[i].description,
osdata_table[i].title);
buffer_grow_str0 (&buffer, "</osdata>\n");
buf = buffer_finish (&buffer);
len_avail = strlen (buf);
}
if (offset >= len_avail)
{
/* Done. Get rid of the buffer. */
buffer_free (&buffer);
buf = NULL;
len_avail = 0;
return 0;
}
if (len > len_avail - offset)
len = len_avail - offset;
memcpy (readbuf, buf + offset, len);
return len;
}
else
{
int i;
for (i = 0; osdata_table[i].type; ++i)
{
if (strcmp (annex, osdata_table[i].type) == 0)
{
gdb_assert (readbuf);
return (osdata_table[i].getter) (readbuf, offset, len);
}
}
return 0;
}
}
| 24.294407 | 87 | 0.580742 | [
"object"
] |
0ee1e7158d4388e721805dd14203489f27d6d4f8 | 15,857 | c | C | usr/src/cmd/sgs/elfedit/common/elfconst.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/cmd/sgs/elfedit/common/elfconst.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/cmd/sgs/elfedit/common/elfconst.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | 1 | 2020-12-30T00:04:16.000Z | 2020-12-30T00:04:16.000Z | /*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2010 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#include <stdlib.h>
#include <stdio.h>
#include <_elfedit.h>
#include <conv.h>
#include <msg.h>
/*
* This file contains support for mapping well known ELF constants
* to their numeric values. It is a layer on top of the elfedit_atoui()
* routines defined in util.c. The idea is that centralizing all the
* support for such constants will improve consistency between modules,
* allow for sharing of commonly needed items, and make the modules
* simpler.
*/
/*
* elfedit output style, with and without leading -o
*/
static elfedit_atoui_sym_t sym_outstyle[] = {
{ MSG_ORIG(MSG_STR_DEFAULT), ELFEDIT_OUTSTYLE_DEFAULT },
{ MSG_ORIG(MSG_STR_SIMPLE), ELFEDIT_OUTSTYLE_SIMPLE },
{ MSG_ORIG(MSG_STR_NUM), ELFEDIT_OUTSTYLE_NUM },
{ NULL }
};
static elfedit_atoui_sym_t sym_minus_o_outstyle[] = {
{ MSG_ORIG(MSG_STR_MINUS_O_DEFAULT), ELFEDIT_OUTSTYLE_DEFAULT },
{ MSG_ORIG(MSG_STR_MINUS_O_SIMPLE), ELFEDIT_OUTSTYLE_SIMPLE },
{ MSG_ORIG(MSG_STR_MINUS_O_NUM), ELFEDIT_OUTSTYLE_NUM },
{ NULL }
};
/*
* Booleans
*/
static elfedit_atoui_sym_t sym_bool[] = {
{ MSG_ORIG(MSG_STR_T), 1 },
{ MSG_ORIG(MSG_STR_F), 0 },
{ MSG_ORIG(MSG_STR_TRUE), 1 },
{ MSG_ORIG(MSG_STR_FALSE), 0 },
{ MSG_ORIG(MSG_STR_ON), 1 },
{ MSG_ORIG(MSG_STR_OFF), 0 },
{ MSG_ORIG(MSG_STR_YES), 1 },
{ MSG_ORIG(MSG_STR_NO), 0 },
{ MSG_ORIG(MSG_STR_Y), 1 },
{ MSG_ORIG(MSG_STR_N), 0 },
{ NULL }
};
/*
* ELF strings for SHT_STRTAB
*/
static elfedit_atoui_sym_t sym_sht_strtab[] = {
{ MSG_ORIG(MSG_SHT_STRTAB), SHT_STRTAB },
{ MSG_ORIG(MSG_SHT_STRTAB_ALT1), SHT_STRTAB },
{ NULL }
};
/*
* Strings for SHT_SYMTAB
*/
static elfedit_atoui_sym_t sym_sht_symtab[] = {
{ MSG_ORIG(MSG_SHT_SYMTAB), SHT_SYMTAB },
{ MSG_ORIG(MSG_SHT_SYMTAB_ALT1), SHT_SYMTAB },
{ NULL }
};
/*
* Strings for SHT_DYNSYM
*/
static elfedit_atoui_sym_t sym_sht_dynsym[] = {
{ MSG_ORIG(MSG_SHT_DYNSYM), SHT_DYNSYM },
{ MSG_ORIG(MSG_SHT_DYNSYM_ALT1), SHT_DYNSYM },
{ NULL }
};
/*
* Strings for SHT_SUNW_LDYNSYM
*/
static elfedit_atoui_sym_t sym_sht_ldynsym[] = {
{ MSG_ORIG(MSG_SHT_SUNW_LDYNSYM), SHT_SUNW_LDYNSYM },
{ MSG_ORIG(MSG_SHT_SUNW_LDYNSYM_ALT1), SHT_SUNW_LDYNSYM },
{ NULL }
};
/*
* Types of items found in sym_table[]. All items other than STE_STATIC
* pulls strings from libconv, differing in the interface required by
* the libconv iteration function used.
*/
typedef enum {
STE_STATIC = 0, /* Constants are statically defined */
STE_LC = 1, /* Libconv, pull once */
STE_LC_OS = 2, /* From libconv, osabi dependency */
STE_LC_MACH = 3, /* From libconv, mach dependency */
STE_LC_OS_MACH = 4 /* From libconv, osabi/mach dep. */
} ste_type_t;
/*
* Interface of functions called to fill strings from libconv
*/
typedef conv_iter_ret_t (* libconv_iter_func_simple_t)(
Conv_fmt_flags_t, conv_iter_cb_t, void *);
typedef conv_iter_ret_t (* libconv_iter_func_os_t)(conv_iter_osabi_t,
Conv_fmt_flags_t, conv_iter_cb_t, void *);
typedef conv_iter_ret_t (* libconv_iter_func_mach_t)(Half,
Conv_fmt_flags_t, conv_iter_cb_t, void *);
typedef conv_iter_ret_t (* libconv_iter_func_os_mach_t)(conv_iter_osabi_t, Half,
Conv_fmt_flags_t, conv_iter_cb_t, void *);
typedef union {
libconv_iter_func_simple_t simple;
libconv_iter_func_os_t osabi;
libconv_iter_func_mach_t mach;
libconv_iter_func_os_mach_t osabi_mach;
} libconv_iter_func_t;
/*
* State for each type of constant
*/
typedef struct {
ste_type_t ste_type; /* Type of entry */
elfedit_atoui_sym_t *ste_arr; /* NULL, or atoui array */
void *ste_alloc; /* Current memory allocation */
size_t ste_nelts; /* # items in ste_alloc */
libconv_iter_func_t ste_conv_func; /* libconv fill function */
} sym_table_ent_t;
/*
* Array of state for each constant type, including the array of atoui
* pointers, for each constant type, indexed by elfedit_const_t value.
* The number and order of entries in this table must agree with the
* definition of elfedit_const_t in elfedit.h.
*
* note:
* - STE_STATIC items must supply a statically allocated buffer here.
* - The non-STE_STATIC items use libconv strings. These items are
* initialized by init_libconv_strings() at runtime, and are represented
* by a simple { 0 } here. The memory used for these arrays is dynamic,
* and can be released and rebuilt at runtime as necessary to keep up
* with changes in osabi or machine type.
*/
static sym_table_ent_t sym_table[ELFEDIT_CONST_NUM] = {
/* #: ELFEDIT_CONST_xxx */
{ STE_STATIC, sym_outstyle }, /* 0: OUTSTYLE */
{ STE_STATIC, sym_minus_o_outstyle }, /* 1: OUTSTYLE_MO */
{ STE_STATIC, sym_bool }, /* 2: BOOL */
{ STE_STATIC, sym_sht_strtab }, /* 3: SHT_STRTAB */
{ STE_STATIC, sym_sht_symtab }, /* 4: SHT_SYMTAB */
{ STE_STATIC, sym_sht_dynsym }, /* 5: SHT_DYNSYM */
{ STE_STATIC, sym_sht_ldynsym }, /* 6: SHT_LDYNSYM */
{ 0 }, /* 7: SHN */
{ 0 }, /* 8: SHT */
{ 0 }, /* 9: SHT_ALLSYMTAB */
{ 0 }, /* 10: DT */
{ 0 }, /* 11: DF */
{ 0 }, /* 12: DF_P1 */
{ 0 }, /* 13: DF_1 */
{ 0 }, /* 14: DTF_1 */
{ 0 }, /* 15: EI */
{ 0 }, /* 16: ET */
{ 0 }, /* 17: ELFCLASS */
{ 0 }, /* 18: ELFDATA */
{ 0 }, /* 19: EF */
{ 0 }, /* 20: EV */
{ 0 }, /* 21: EM */
{ 0 }, /* 22: ELFOSABI */
{ 0 }, /* 23: EAV osabi version */
{ 0 }, /* 24: PT */
{ 0 }, /* 25: PF */
{ 0 }, /* 26: SHF */
{ 0 }, /* 27: STB */
{ 0 }, /* 28: STT */
{ 0 }, /* 29: STV */
{ 0 }, /* 30: SYMINFO_BT */
{ 0 }, /* 31: SYMINFO_FLG */
{ 0 }, /* 32: CA */
{ 0 }, /* 33: AV */
{ 0 }, /* 34: SF1_SUNW */
};
#if ELFEDIT_CONST_NUM != (ELFEDIT_CONST_SF1_SUNW)
error "ELFEDIT_CONST_NUM has grown. Update sym_table[]"
#endif
/*
* Used to count the number of descriptors that will be needed to hold
* strings from libconv.
*/
/*ARGSUSED*/
static conv_iter_ret_t
libconv_count_cb(const char *str, Conv_elfvalue_t value, void *uvalue)
{
size_t *cnt = (size_t *)uvalue;
(*cnt)++;
return (CONV_ITER_CONT);
}
/*
* Used to fill in the descriptors with strings from libconv.
*/
typedef struct {
size_t cur; /* Index of next descriptor */
size_t cnt; /* # of descriptors */
elfedit_atoui_sym_t *desc; /* descriptors */
} libconv_fill_state_t;
static conv_iter_ret_t
libconv_fill_cb(const char *str, Conv_elfvalue_t value, void *uvalue)
{
libconv_fill_state_t *fill_state = (libconv_fill_state_t *)uvalue;
elfedit_atoui_sym_t *sym = &fill_state->desc[fill_state->cur++];
sym->sym_name = str;
sym->sym_value = value;
return (CONV_ITER_CONT);
}
/*
* Call the iteration function using the correct calling sequence for
* the libconv routine.
*/
static void
libconv_fill_iter(sym_table_ent_t *sym, conv_iter_osabi_t osabi, Half mach,
conv_iter_cb_t func, void *uvalue)
{
switch (sym->ste_type) {
case STE_LC:
(void) (* sym->ste_conv_func.simple)(
CONV_FMT_ALT_CF, func, uvalue);
(void) (* sym->ste_conv_func.simple)(
CONV_FMT_ALT_NF, func, uvalue);
break;
case STE_LC_OS:
(void) (* sym->ste_conv_func.osabi)(osabi,
CONV_FMT_ALT_CF, func, uvalue);
(void) (* sym->ste_conv_func.osabi)(osabi,
CONV_FMT_ALT_NF, func, uvalue);
break;
case STE_LC_MACH:
(void) (* sym->ste_conv_func.mach)(mach,
CONV_FMT_ALT_CF, func, uvalue);
(void) (* sym->ste_conv_func.mach)(mach,
CONV_FMT_ALT_NF, func, uvalue);
break;
case STE_LC_OS_MACH:
(void) (* sym->ste_conv_func.osabi_mach)(osabi, mach,
CONV_FMT_ALT_CF, func, uvalue);
(void) (* sym->ste_conv_func.osabi_mach)(osabi, mach,
CONV_FMT_ALT_NF, func, uvalue);
break;
}
}
/*
* Allocate/Fill an atoui array for the specified constant.
*/
static void
libconv_fill(sym_table_ent_t *sym, conv_iter_osabi_t osabi, Half mach)
{
libconv_fill_state_t fill_state;
/* How many descriptors will we need? */
fill_state.cnt = 1; /* Extra for NULL termination */
libconv_fill_iter(sym, osabi, mach, libconv_count_cb, &fill_state.cnt);
/*
* If there is an existing allocation, and it is not large enough,
* release it.
*/
if ((sym->ste_alloc != NULL) && (fill_state.cnt > sym->ste_nelts)) {
free(sym->ste_alloc);
sym->ste_alloc = NULL;
sym->ste_nelts = 0;
}
/* Allocate memory if don't already have an allocation */
if (sym->ste_alloc == NULL) {
sym->ste_alloc = elfedit_malloc(MSG_INTL(MSG_ALLOC_ELFCONDESC),
fill_state.cnt * sizeof (*fill_state.desc));
sym->ste_nelts = fill_state.cnt;
}
/* Fill the array */
fill_state.desc = sym->ste_alloc;
fill_state.cur = 0;
libconv_fill_iter(sym, osabi, mach, libconv_fill_cb, &fill_state);
/* Add null termination */
fill_state.desc[fill_state.cur].sym_name = NULL;
fill_state.desc[fill_state.cur].sym_value = 0;
/* atoui array for this item is now available */
sym->ste_arr = fill_state.desc;
}
/*
* Should be called on first call to elfedit_const_to_atoui(). Does the
* runtime initialization of sym_table.
*/
static void
init_libconv_strings(conv_iter_osabi_t *osabi, Half *mach)
{
/*
* It is critical that the ste_type and ste_conv_func values
* agree. Since the libconv iteration function signatures can
* change (gain or lose an osabi or mach argument), we want to
* ensure that the compiler will catch such changes.
*
* The compiler will catch an attempt to assign a function of
* the wrong type to ste_conv_func. Using these macros, we ensure
* that the ste_type and function assignment happen as a unit.
*/
#define LC(_ndx, _func) sym_table[_ndx].ste_type = STE_LC; \
sym_table[_ndx].ste_conv_func.simple = _func;
#define LC_OS(_ndx, _func) sym_table[_ndx].ste_type = STE_LC_OS; \
sym_table[_ndx].ste_conv_func.osabi = _func;
#define LC_MACH(_ndx, _func) sym_table[_ndx].ste_type = STE_LC_MACH; \
sym_table[_ndx].ste_conv_func.mach = _func;
#define LC_OS_MACH(_ndx, _func) sym_table[_ndx].ste_type = STE_LC_OS_MACH; \
sym_table[_ndx].ste_conv_func.osabi_mach = _func;
if (!state.file.present) {
/*
* No input file: Supply the maximal set of strings for
* all osabi and mach values understood by libconv.
*/
*osabi = CONV_OSABI_ALL;
*mach = CONV_MACH_ALL;
} else if (state.elf.elfclass == ELFCLASS32) {
*osabi = state.elf.obj_state.s32->os_ehdr->e_ident[EI_OSABI];
*mach = state.elf.obj_state.s32->os_ehdr->e_machine;
} else {
*osabi = state.elf.obj_state.s64->os_ehdr->e_ident[EI_OSABI];
*mach = state.elf.obj_state.s64->os_ehdr->e_machine;
}
/* Set up non- STE_STATIC libconv fill functions */
LC_OS_MACH(ELFEDIT_CONST_SHN, conv_iter_sym_shndx);
LC_OS_MACH(ELFEDIT_CONST_SHT, conv_iter_sec_type);
LC_OS(ELFEDIT_CONST_SHT_ALLSYMTAB, conv_iter_sec_symtab);
LC_OS_MACH(ELFEDIT_CONST_DT, conv_iter_dyn_tag);
LC(ELFEDIT_CONST_DF, conv_iter_dyn_flag);
LC(ELFEDIT_CONST_DF_P1, conv_iter_dyn_posflag1);
LC(ELFEDIT_CONST_DF_1, conv_iter_dyn_flag1);
LC(ELFEDIT_CONST_DTF_1, conv_iter_dyn_feature1);
LC(ELFEDIT_CONST_EI, conv_iter_ehdr_eident);
LC_OS(ELFEDIT_CONST_ET, conv_iter_ehdr_type);
LC(ELFEDIT_CONST_ELFCLASS, conv_iter_ehdr_class);
LC(ELFEDIT_CONST_ELFDATA, conv_iter_ehdr_data);
LC_MACH(ELFEDIT_CONST_EF, conv_iter_ehdr_flags);
LC(ELFEDIT_CONST_EV, conv_iter_ehdr_vers);
LC(ELFEDIT_CONST_EM, conv_iter_ehdr_mach);
LC(ELFEDIT_CONST_ELFOSABI, conv_iter_ehdr_osabi);
LC_OS(ELFEDIT_CONST_EAV, conv_iter_ehdr_abivers);
LC_OS(ELFEDIT_CONST_PT, conv_iter_phdr_type);
LC_OS(ELFEDIT_CONST_PF, conv_iter_phdr_flags);
LC_OS_MACH(ELFEDIT_CONST_SHF, conv_iter_sec_flags);
LC(ELFEDIT_CONST_STB, conv_iter_sym_info_bind);
LC_MACH(ELFEDIT_CONST_STT, conv_iter_sym_info_type);
LC(ELFEDIT_CONST_STV, conv_iter_sym_other_vis);
LC(ELFEDIT_CONST_SYMINFO_BT, conv_iter_syminfo_boundto);
LC(ELFEDIT_CONST_SYMINFO_FLG, conv_iter_syminfo_flags);
LC(ELFEDIT_CONST_CA, conv_iter_cap_tags);
LC_MACH(ELFEDIT_CONST_HW1_SUNW, conv_iter_cap_val_hw1);
LC(ELFEDIT_CONST_SF1_SUNW, conv_iter_cap_val_sf1);
LC_MACH(ELFEDIT_CONST_HW2_SUNW, conv_iter_cap_val_hw2);
#undef LC
#undef LC_OS
#undef LC_MACH
#undef LC_OS_MACH
}
/*
* If the user has changed the osabi or machine type of the object,
* then we need to discard the strings we've loaded from libconv
* that are dependent on these values.
*/
static void
invalidate_libconv_strings(conv_iter_osabi_t *osabi, Half *mach)
{
uchar_t cur_osabi;
Half cur_mach;
sym_table_ent_t *sym;
int osabi_change, mach_change;
int i;
/* Reset the ELF header change notification */
state.elf.elfconst_ehdr_change = 0;
if (state.elf.elfclass == ELFCLASS32) {
cur_osabi = state.elf.obj_state.s32->os_ehdr->e_ident[EI_OSABI];
cur_mach = state.elf.obj_state.s32->os_ehdr->e_machine;
} else {
cur_osabi = state.elf.obj_state.s64->os_ehdr->e_ident[EI_OSABI];
cur_mach = state.elf.obj_state.s64->os_ehdr->e_machine;
}
/* What has changed? */
mach_change = *mach != cur_mach;
osabi_change = *osabi != cur_osabi;
if (!(mach_change || osabi_change))
return;
/*
* Set the ste_arr pointer to NULL for any items that
* depend on the things that have changed. Note that we
* do not release the allocated memory --- it may turn
* out to be large enough to hold the new strings, so we
* keep the allocation and leave that decision to the fill
* routine, which will run the next time those strings are
* needed.
*/
for (i = 0, sym = sym_table;
i < (sizeof (sym_table) / sizeof (sym_table[0])); i++, sym++) {
if (sym->ste_arr == NULL)
continue;
switch (sym->ste_type) {
case STE_LC_OS:
if (osabi_change)
sym->ste_arr = NULL;
break;
case STE_LC_MACH:
if (mach_change)
sym->ste_arr = NULL;
break;
case STE_LC_OS_MACH:
if (osabi_change || mach_change)
sym->ste_arr = NULL;
break;
}
}
*mach = cur_mach;
*osabi = cur_osabi;
}
/*
* Given an elfedit_const_t value, return the array of elfedit_atoui_sym_t
* entries that it represents.
*/
elfedit_atoui_sym_t *
elfedit_const_to_atoui(elfedit_const_t const_type)
{
static int first = 1;
static conv_iter_osabi_t osabi;
static Half mach;
sym_table_ent_t *sym;
if (first) {
init_libconv_strings(&osabi, &mach);
first = 0;
}
if ((const_type < 0) ||
(const_type >= (sizeof (sym_table) / sizeof (sym_table[0]))))
elfedit_msg(ELFEDIT_MSG_ERR, MSG_INTL(MSG_ERR_BADCONST));
sym = &sym_table[const_type];
/*
* If the constant is not STE_STATIC, then we may need to fetch
* the strings from libconv.
*/
if (sym->ste_type != STE_STATIC) {
/*
* If the ELF header has changed since the last
* time we were called, then we need to invalidate any
* strings previously pulled from libconv that have
* an osabi or machine dependency.
*/
if (state.elf.elfconst_ehdr_change)
invalidate_libconv_strings(&osabi, &mach);
/* If we don't already have the strings, get them */
if (sym->ste_arr == NULL)
libconv_fill(sym, osabi, mach);
}
return (sym->ste_arr);
}
| 29.639252 | 80 | 0.705051 | [
"object"
] |
0eed9b475cbb70d88417b623276e25081a73c661 | 75,834 | h | C | SeqAn-1.1/seqan/sequence/sequence_multiple.h | dkj/bowtie | d1f4eb8f9a3f7c8dcfbaadfee4f67c9805e038d6 | [
"Artistic-1.0"
] | 29 | 2016-09-27T15:33:27.000Z | 2021-07-14T03:26:53.000Z | SeqAn-1.1/seqan/sequence/sequence_multiple.h | dkj/bowtie | d1f4eb8f9a3f7c8dcfbaadfee4f67c9805e038d6 | [
"Artistic-1.0"
] | 15 | 2015-11-22T13:12:03.000Z | 2022-01-19T02:18:25.000Z | SeqAn-1.1/seqan/sequence/sequence_multiple.h | dkj/bowtie | d1f4eb8f9a3f7c8dcfbaadfee4f67c9805e038d6 | [
"Artistic-1.0"
] | 9 | 2015-03-30T14:37:26.000Z | 2019-06-20T19:06:07.000Z | /*==========================================================================
SeqAn - The Library for Sequence Analysis
http://www.seqan.de
============================================================================
Copyright (C) 2007
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 3 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.
============================================================================
$Id: sequence_multiple.h,v 1.2 2009/02/19 01:51:23 langmead Exp $
==========================================================================*/
#ifndef SEQAN_HEADER_STRING_SET_H
#define SEQAN_HEADER_STRING_SET_H
namespace SEQAN_NAMESPACE_MAIN
{
//////////////////////////////////////////////////////////////////////////////
// StringSet specs
//////////////////////////////////////////////////////////////////////////////
//struct Generous; // large string-string, large id-string
//struct Tight; // small string-string, small id-string
//struct Optimal?? // small string-string, large id-string
/**
.Spec.Dependent:
..summary:A string set storing references of the strings.
..cat:Sequences
..general:Class.StringSet
..signature:StringSet<TString, Dependent<TSpec> >
..param.TString:The string type.
...type:Class.String
..param.TSpec:The specializing type for the dependent string set.
...remarks:Possible values are $Tight$ or $Generous$
...remarks:$Tight$ is very space efficient whereas $Generous$ provides fast access to the strings in the container via ids.
*/
// Default id holder string set
template<typename TSpec = Generous >
struct Dependent; // holds references of its elements
/**
.Spec.ConcatDirect:
..summary:A string set storing the concatenation of all strings within one string.
..cat:Sequences
..general:Spec.Owner
..signature:StringSet<TString, Owner<ConcatDirect<> > >
..param.TString:The string type.
...type:Class.String
..remarks:The strings are internally stored in a $TString$ object and the character position type is a
a single integer value between 0 and the sum of string lengths minus 1.
..remarks:The position type can be returned or modified by the meta-function @Metafunction.SAValue@ called with the @Class.StringSet@ type.
*/
template < typename TDelimiter = void >
struct ConcatDirect; // contains 1 string (the concatenation of n strings)
//struct Default; // contains n strings in a string
/**
.Spec.Owner:
..summary:A string set storing the strings as members.
..cat:Sequences
..general:Class.StringSet
..signature:StringSet<TString, Owner<> >
..signature:StringSet<TString, Owner<Default> >
..param.TString:The string type.
...type:Class.String
..remarks:The strings are internally stored in a $String<TString>$ object and the character position type is a
@Class.Pair@ $(seqNo,seqOfs)$ where seqNo identifies the string within the stringset and seqOfs identifies the position within this string.
..remarks:The position type can be returned or modified by the meta-function @Metafunction.SAValue@ called with the @Class.StringSet@ type.
*/
template < typename TSpec = Default >
struct Owner; // owns its elements
//////////////////////////////////////////////////////////////////////////////
// Forwards
//////////////////////////////////////////////////////////////////////////////
template < typename TString, typename TSpec = Owner<> >
class StringSet;
template <typename TObject>
struct Concatenator {
typedef TObject Type;
};
template <typename TObject>
struct Concatenator<TObject const> {
typedef typename Concatenator<TObject>::Type const Type;
};
//////////////////////////////////////////////////////////////////////////////
// StringSet limits
//////////////////////////////////////////////////////////////////////////////
template <typename TString>
struct StringSetLimits {
typedef Nothing Type;
};
template <typename TString>
struct StringSetLimits<TString const> {
typedef typename StringSetLimits<TString>::Type const Type;
};
template <typename TString>
struct StringSetPosition {
typedef typename Size<TString>::Type Type;
};
template <typename TString, typename TSpec>
struct StringSetLimits< StringSet<TString, TSpec> > {
typedef typename Size<TString>::Type TSize;
typedef String<TSize> Type;
};
template <typename TString, typename TSpec>
struct StringSetPosition< StringSet<TString, TSpec> > {
typedef typename Size<TString>::Type TSize;
typedef Pair<TSize> Type;
};
//////////////////////////////////////////////////////////////////////////////
// get StringSet limits
//////////////////////////////////////////////////////////////////////////////
/**
.Function.stringSetLimits:
..cat:Sequences
..summary:Retrieves a string of delimiter positions of a @Class.StringSet@ which is needed for local<->global position conversions.
..signature:stringSetLimits(me)
..param.me:A string or string set.
...type:Class.String
...type:Class.StringSet
..returns:A reference to a string.
...remarks:If $me$ is a @Class.StringSet@ then the returned string is of size $length(me)+1$ and contains the ascending (virtual) delimiter positions of the concatenation of all strings in the string set.
...remarks:If $me$ is a @Class.String@, @Tag.Nothing@ is returned.
*/
template <typename TStringSet>
inline typename StringSetLimits<TStringSet>::Type
stringSetLimits(TStringSet &) {
return typename StringSetLimits<TStringSet>::Type();
}
template <typename TString, typename TSpec>
inline typename StringSetLimits< StringSet<TString, TSpec> >::Type &
stringSetLimits(StringSet<TString, TSpec> &stringSet) {
if (!_validStringSetLimits(stringSet))
_refreshStringSetLimits(stringSet);
return stringSet.limits;
}
template <typename TString, typename TSpec>
inline typename StringSetLimits< StringSet<TString, TSpec> const>::Type &
stringSetLimits(StringSet<TString, TSpec> const &stringSet) {
if (!_validStringSetLimits(stringSet))
_refreshStringSetLimits(const_cast< StringSet<TString, TSpec>& >(stringSet));
return stringSet.limits;
}
//////////////////////////////////////////////////////////////////////////////
// accessing local positions
//////////////////////////////////////////////////////////////////////////////
/**
.Function.getSeqNo:
..cat:Sequences
..summary:Returns the sequence number of a position.
..signature:getSeqNo(pos[, limits])
..param.pos:A position.
...type:Class.Pair
..param.limits:The limits string returned by @Function.stringSetLimits@.
..returns:A single integer value that identifies the string within the stringset $pos$ points at.
...remarks:If $limits$ is omitted or @Tag.Nothing@ $getSeqNo$ returns 0.
...remarks:If $pos$ is a local position (of class @Class.Pair@) then $i1$ is returned.
...remarks:If $pos$ is a global position (integer type and $limits$ is a @Class.String@) then $pos$ is converted to a local position and $i1$ is returned.
*/
/**
.Function.getSeqOffset:
..cat:Sequences
..summary:Returns the local sequence offset of a position.
..signature:getSeqOffset(pos[, limits])
..param.pos:A position.
...type:Class.Pair
..param.limits:The limits string returned by @Function.stringSetLimits@.
..returns:A single integer value that identifies the position within the string $pos$ points at.
...remarks:If $limits$ is omitted or @Tag.Nothing@ $getSeqNo$ returns $pos$.
...remarks:If $pos$ is a local position (of class @Class.Pair@) then $i2$ is returned.
...remarks:If $pos$ is a global position (integer type and $limits$ is a @Class.String@) then $pos$ is converted to a local position and $i2$ is returned.
*/
//////////////////////////////////////////////////////////////////////////////
// 1 sequence
//////////////////////////////////////////////////////////////////////////////
template <typename TPosition>
inline TPosition getSeqNo(TPosition const &, Nothing const &) {
return 0;
}
template <typename TPosition>
inline TPosition getSeqOffset(TPosition const &pos, Nothing const &) {
return pos;
}
//____________________________________________________________________________
template <typename TPosition>
inline TPosition getSeqNo(TPosition const &) {
return 0;
}
template <typename TPosition>
inline TPosition getSeqOffset(TPosition const &pos) {
return pos;
}
//////////////////////////////////////////////////////////////////////////////
// n sequences (position type is Pair)
//////////////////////////////////////////////////////////////////////////////
template <typename T1, typename T2, typename TCompression, typename TLimitsString>
inline T1 getSeqNo(Pair<T1, T2, TCompression> const &pos, TLimitsString const &) {
return getValueI1(pos);
}
template <typename T1, typename T2, typename TCompression>
inline T1 getSeqNo(Pair<T1, T2, TCompression> const &pos) {
return getValueI1(pos);
}
//____________________________________________________________________________
template <typename T1, typename T2, typename TCompression, typename TLimitsString>
inline T2 getSeqOffset(Pair<T1, T2, TCompression> const &pos, TLimitsString const &) {
return getValueI2(pos);
}
template <typename T1, typename T2, typename TCompression>
inline T1 getSeqOffset(Pair<T1, T2, TCompression> const &pos) {
return getValueI2(pos);
}
//////////////////////////////////////////////////////////////////////////////
// n sequences (position type is an integral type)
//////////////////////////////////////////////////////////////////////////////
template <typename TPos, typename TLimitsString>
inline TPos getSeqNo(TPos const &pos, TLimitsString const &limits) {
typedef typename Iterator<TLimitsString const, Standard>::Type TIter;
typedef typename Value<TLimitsString>::Type TSize;
TIter _begin = begin(limits, Standard());
TIter _upper = ::std::upper_bound(_begin, end(limits, Standard()), (TSize)pos) - 1;
return difference(_begin, _upper);
}
template <typename TPos, typename TLimitsString>
inline TPos getSeqOffset(TPos const &pos, TLimitsString const &limits) {
typedef typename Iterator<TLimitsString const, Standard>::Type TIter;
typedef typename Value<TLimitsString>::Type TSize;
TIter _begin = begin(limits, Standard());
TIter _upper = ::std::upper_bound(_begin, end(limits, Standard()), (TSize)pos) - 1;
return pos - *_upper;
}
//////////////////////////////////////////////////////////////////////////////
// local -> global conversions
//////////////////////////////////////////////////////////////////////////////
/**
.Function.posGlobalize:
..cat:Sequences
..summary:Converts a local/global to a global position.
..signature:posGlobalize(pos, limits)
..param.pos:A local or global position (pair or integer value).
...type:Class.Pair
..param.limits:The limits string returned by @Function.stringSetLimits@.
..returns:The corresponding global position of $pos$.
...remarks:If $pos$ is an integral type $pos$ is returned.
...remarks:If not, $limits[getSeqNo(pos, limits)] + getSeqOffset(pos, limits)$ is returned.
*/
// any_position and no limits_string -> any_position
template <typename TPosition>
inline TPosition posGlobalize(TPosition const &pos, Nothing const &) {
return pos;
}
// local_position (0,x) and no limits_string -> global_position x
template <typename T1, typename T2, typename TCompression>
inline T2 posGlobalize(Pair<T1, T2, TCompression> const &pos, Nothing const &) {
return getSeqOffset(pos);
}
// any_position and no limits_string -> any_position
template <typename TLimitsString, typename TPosition>
inline TPosition posGlobalize(TPosition const &pos, TLimitsString const &) {
return pos;
}
// local_position and limits_string -> global_position
template <typename TLimitsString, typename T1, typename T2, typename TCompression>
inline typename Value<TLimitsString>::Type
posGlobalize(Pair<T1, T2, TCompression> const &pos, TLimitsString const &limits) {
return limits[getSeqNo(pos, limits)] + getSeqOffset(pos, limits);
}
//////////////////////////////////////////////////////////////////////////////
// global -> local position
//////////////////////////////////////////////////////////////////////////////
/**
.Function.posLocalize:
..cat:Sequences
..summary:Converts a local/global to a local position.
..signature:posLocalize(result, pos, limits)
..param.pos:A local or global position (pair or integer value).
...type:Class.Pair
..param.limits:The limits string returned by @Function.stringSetLimits@.
..param.result:Reference to the resulting corresponding local position of $pos$.
...remarks:If $pos$ is an integral type and $limits$ is omitted or @Tag.Nothing@, $pos$ is returned.
...remarks:If $pos$ is a local position (of class @Class.Pair@) then $pos$ is returned.
...remarks:If $pos$ is a global position (integer type and $limits$ is a @Class.String@) then $pos$ is converted to a local position.
*/
// any_position and no limits_string -> any_position
template <typename TResult, typename TPosition>
inline void posLocalize(TResult &result, TPosition const &pos, Nothing const &) {
result = pos;
}
template <typename T1, typename T2, typename TCompression, typename TPosition>
inline void posLocalize(Pair<T1, T2, TCompression> &result, TPosition const &pos, Nothing const &) {
result.i1 = 0;
result.i2 = pos;
}
// global_position and limits_string -> local_position
template <typename TResult, typename TSize, typename TSpec, typename TPosition>
inline void posLocalize(TResult &result, TPosition const &pos, String<TSize, TSpec> const &limits) {
typedef typename Iterator<String<TSize> const, Standard>::Type TIter;
TIter _begin = begin(limits, Standard());
TIter _upper = ::std::upper_bound(_begin, end(limits, Standard()), (TSize)pos) - 1;
result.i1 = difference(_begin, _upper);
result.i2 = pos - *_upper;
}
// local_position -> local_position
template <typename TResult, typename TSize, typename TSpec, typename T1, typename T2, typename TCompression>
inline void posLocalize(TResult &result, Pair<T1, T2, TCompression> const &pos, String<TSize, TSpec> const &/*limits*/) {
result = pos;
}
//////////////////////////////////////////////////////////////////////////////
// prefix
//////////////////////////////////////////////////////////////////////////////
template < typename TString, typename TSpec, typename TPosition >
inline typename Prefix<TString>::Type
prefix(StringSet< TString, TSpec > &me, TPosition pos)
{
typedef StringSet<TString, TSpec> TStringSet;
typedef typename Size<TStringSet>::Type TSetSize;
typedef typename Size<TString>::Type TStringSize;
typedef Pair<TSetSize, TStringSize, Compressed> TPair;
TPair lPos;
posLocalize(lPos, pos, stringSetLimits(me));
return prefix(me[getSeqNo(lPos)], getSeqOffset(lPos));
}
template < typename TString, typename TSpec, typename TPosition >
inline typename Prefix<TString const>::Type
prefix(StringSet< TString, TSpec > const &me, TPosition pos)
{
typedef StringSet<TString, TSpec> TStringSet;
typedef typename Size<TStringSet>::Type TSetSize;
typedef typename Size<TString>::Type TStringSize;
typedef Pair<TSetSize, TStringSize, Compressed> TPair;
TPair lPos;
posLocalize(lPos, pos, stringSetLimits(me));
return prefix(me[getSeqNo(lPos)], getSeqOffset(lPos));
}
template < typename TString, typename TDelimiter, typename TPosition >
inline typename Infix<TString>::Type
prefix(StringSet< TString, Owner<ConcatDirect<TDelimiter> > > &me, TPosition pos)
{
return infix(me.concat, stringSetLimits(me)[getSeqNo(pos, stringSetLimits(me))], posGlobalize(pos, stringSetLimits(me)));
}
template < typename TString, typename TDelimiter, typename TPosition >
inline typename Infix<TString const>::Type
prefix(StringSet< TString, Owner<ConcatDirect<TDelimiter> > > const &me, TPosition pos)
{
return infix(me.concat, stringSetLimits(me)[getSeqNo(pos, stringSetLimits(me))], posGlobalize(pos, stringSetLimits(me)));
}
//////////////////////////////////////////////////////////////////////////////
// suffix
//////////////////////////////////////////////////////////////////////////////
template < typename TString, typename TSpec, typename TPosition >
inline typename Suffix<TString>::Type
suffix(StringSet< TString, TSpec > &me, TPosition pos)
{
typedef StringSet<TString, TSpec> TStringSet;
typedef typename Size<TStringSet>::Type TSetSize;
typedef typename Size<TString>::Type TStringSize;
typedef Pair<TSetSize, TStringSize, Compressed> TPair;
TPair lPos;
posLocalize(lPos, pos, stringSetLimits(me));
return suffix(me[getSeqNo(lPos)], getSeqOffset(lPos));
}
template < typename TString, typename TSpec, typename TPosition >
inline typename Suffix<TString const>::Type
suffix(StringSet< TString, TSpec > const &me, TPosition pos)
{
typedef StringSet<TString, TSpec> TStringSet;
typedef typename Size<TStringSet>::Type TSetSize;
typedef typename Size<TString>::Type TStringSize;
typedef Pair<TSetSize, TStringSize, Compressed> TPair;
TPair lPos;
posLocalize(lPos, pos, stringSetLimits(me));
return suffix(me[getSeqNo(lPos)], getSeqOffset(lPos));
}
template < typename TString, typename TDelimiter, typename TPosition >
inline typename Infix<TString>::Type
suffix(StringSet< TString, Owner<ConcatDirect<TDelimiter> > > &me, TPosition pos)
{
return infix(me.concat, posGlobalize(pos, stringSetLimits(me)), stringSetLimits(me)[getSeqNo(pos, stringSetLimits(me)) + 1]);
}
template < typename TString, typename TDelimiter, typename TPosition >
inline typename Infix<TString const>::Type
suffix(StringSet< TString, Owner<ConcatDirect<TDelimiter> > > const &me, TPosition pos)
{
return infix(me.concat, posGlobalize(pos, stringSetLimits(me)), stringSetLimits(me)[getSeqNo(pos, stringSetLimits(me)) + 1]);
}
//////////////////////////////////////////////////////////////////////////////
// infixWithLength
//////////////////////////////////////////////////////////////////////////////
template < typename TString, typename TSpec, typename TPosition, typename TSize >
inline typename Infix<TString>::Type
infixWithLength(StringSet< TString, TSpec > &me, TPosition pos, TSize length)
{
typedef StringSet<TString, TSpec> TStringSet;
typedef typename Size<TStringSet>::Type TSetSize;
typedef typename Size<TString>::Type TStringSize;
typedef Pair<TSetSize, TStringSize, Compressed> TPair;
TPair lPos;
posLocalize(lPos, pos, stringSetLimits(me));
return infixWithLength(me[getSeqNo(lPos)], getSeqOffset(lPos), length);
}
template < typename TString, typename TSpec, typename TPosition, typename TSize >
inline typename Infix<TString const>::Type
infixWithLength(StringSet< TString, TSpec > const &me, TPosition pos, TSize length)
{
typedef StringSet<TString, TSpec> TStringSet;
typedef typename Size<TStringSet>::Type TSetSize;
typedef typename Size<TString>::Type TStringSize;
typedef Pair<TSetSize, TStringSize, Compressed> TPair;
TPair lPos;
posLocalize(lPos, pos, stringSetLimits(me));
return infixWithLength(me[getSeqNo(lPos)], getSeqOffset(lPos), length);
}
template < typename TString, typename TDelimiter, typename TPosition, typename TSize >
inline typename Infix<TString>::Type
infixWithLength(StringSet< TString, Owner<ConcatDirect<TDelimiter> > > &me, TPosition pos, TSize length)
{
return infixWithLength(me.concat, posGlobalize(pos, stringSetLimits(me)), length);
}
template < typename TString, typename TDelimiter, typename TPosition, typename TSize >
inline typename Infix<TString const>::Type
infixWithLength(StringSet< TString, Owner<ConcatDirect<TDelimiter> > > const &me, TPosition pos, TSize length)
{
return infixWithLength(me.concat, posGlobalize(pos, stringSetLimits(me)), length);
}
//////////////////////////////////////////////////////////////////////////////
// position arithmetics
//////////////////////////////////////////////////////////////////////////////
// posAtFirstLocal
template <typename TPos, typename TLimitsString>
inline bool posAtFirstLocal(TPos pos, TLimitsString const &limits) {
return getSeqOffset(pos, limits) == 0;
}
template <typename TPos>
inline bool posAtFirstLocal(TPos pos) {
return getSeqOffset(pos) == 0;
}
// posPrev
template <typename TPos>
inline TPos posPrev(TPos pos) {
return pos - 1;
}
template <typename T1, typename T2, typename TCompression>
inline Pair<T1, T2, TCompression> posPrev(Pair<T1, T2, TCompression> const &pos) {
return Pair<T1, T2, TCompression>(getValueI1(pos), getValueI2(pos) - 1);
}
// posNext
template <typename TPos>
inline TPos posNext(TPos pos) {
return pos + 1;
}
template <typename T1, typename T2, typename TCompression>
inline Pair<T1, T2, TCompression>
posNext(Pair<T1, T2, TCompression> const &pos) {
return Pair<T1, T2, TCompression>(getValueI1(pos), getValueI2(pos) + 1);
}
// posAdd
template <typename TPos, typename TDelta>
inline TPos posAdd(TPos pos, TDelta delta) {
return pos + delta;
}
template <typename T1, typename T2, typename TCompression, typename TDelta>
inline Pair<T1, T2, TCompression>
posAdd(Pair<T1, T2, TCompression> const &pos, TDelta delta) {
return Pair<T1, T2, TCompression>(getValueI1(pos), getValueI2(pos) + delta);
}
// posSub
template <typename TA, typename TB>
inline TA posSub(TA a, TB b) {
return a - b;
}
template <
typename TA1, typename TA2, typename TACompression,
typename TB1, typename TB2, typename TBCompression
>
inline TA2
posSub(Pair<TA1, TA2, TACompression> const &a, Pair<TB1, TB2, TBCompression> const &b) {
return getValueI2(a) - getValueI2(b);
}
//////////////////////////////////////////////////////////////////////////////
// position relations
//////////////////////////////////////////////////////////////////////////////
template <typename TPos>
inline bool posLess(TPos const &a, TPos const &b) {
return a < b;
}
template <typename T1, typename T2, typename TCompression>
inline bool posLess(Pair<T1, T2, TCompression> const &a, Pair<T1, T2, TCompression> const &b) {
return
(getValueI1(a) < getValueI1(b)) ||
((getValueI1(a) == getValueI1(b)) && (getValueI2(a) < getValueI2(b)));
}
template <typename TPos>
inline int posCompare(TPos const &a, TPos const &b) {
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
template <typename T1, typename T2, typename TCompression>
inline int posCompare(Pair<T1, T2, TCompression> const &a, Pair<T1, T2, TCompression> const &b) {
if (getValueI1(a) < getValueI1(b)) return -1;
if (getValueI1(a) > getValueI1(b)) return 1;
return posCompare(getValueI2(a), getValueI2(b));
}
//////////////////////////////////////////////////////////////////////////////
template <typename TPos, typename TString>
inline typename Size<TString>::Type
suffixLength(TPos pos, TString const &string) {
return length(string) - pos;
}
template <typename TPos, typename TString, typename TSpec>
inline typename Size<TString>::Type
suffixLength(TPos pos, StringSet<TString, TSpec> const &stringSet) {
return length(stringSet[getSeqNo(pos, stringSetLimits(stringSet))]) - getSeqOffset(pos, stringSetLimits(stringSet));
}
//////////////////////////////////////////////////////////////////////////////
template <typename TString>
inline unsigned
countSequences(TString const &) {
return 1;
}
template <typename TString, typename TSpec>
inline typename Size<StringSet<TString, TSpec> >::Type
countSequences(StringSet<TString, TSpec> const &stringSet) {
return length(stringSet);
}
//////////////////////////////////////////////////////////////////////////////
template <typename TSeqNo, typename TString>
inline typename Size<TString>::Type
sequenceLength(TSeqNo /*seqNo*/, TString const &string) {
return length(string);
}
template <typename TSeqNo, typename TString, typename TSpec>
inline typename Size<StringSet<TString, TSpec> >::Type
sequenceLength(TSeqNo seqNo, StringSet<TString, TSpec> const &stringSet) {
return length(stringSet[seqNo]);
}
//////////////////////////////////////////////////////////////////////////////
// StringSet Container
//////////////////////////////////////////////////////////////////////////////
/**
.Class.StringSet:
..cat:Sequences
..summary:A container class for a set of strings.
..signature:StringSet<TString, TSpec>
..param.TString:The string type.
...type:Class.String
..param.TSpec:The specializing type for the StringSet.
...metafunction:Metafunction.Spec
...default:$Generous$.
..include:sequence.h
*/
//////////////////////////////////////////////////////////////////////////////
// StringSet with individual sequences in a tight string of string pointers and corr. IDs
template <typename TString>
class StringSet<TString, Dependent<Tight> >
{
public:
typedef String<TString*> TStrings;
typedef typename Id<StringSet>::Type TIdType;
typedef String<TIdType> TIds;
typedef typename StringSetLimits<StringSet>::Type TLimits;
typedef typename Concatenator<StringSet>::Type TConcatenator;
//____________________________________________________________________________
TStrings strings;
TIds ids;
TLimits limits;
bool limitsValid; // is true if limits contains the cumulative sum of the sequence lengths
TConcatenator concat;
//____________________________________________________________________________
StringSet():
limitsValid(true)
{
SEQAN_CHECKPOINT
appendValue(limits, 0);
concat.set = this;
}
template <typename TDefault>
StringSet(StringSet<TString, Owner<TDefault> > const& _other) :
limitsValid(true)
{
SEQAN_CHECKPOINT
appendValue(limits, 0);
concat.set = this;
for(unsigned int i = 0; i<length(_other); ++i) appendValue(*this, _other[i]);
}
template <typename TPos>
inline typename Reference<StringSet>::Type
operator [] (TPos pos)
{
SEQAN_CHECKPOINT
return value(*this, pos);
}
template <typename TPos>
inline typename Reference<StringSet const>::Type
operator [] (TPos pos) const
{
return value(*this, pos);
}
};
//////////////////////////////////////////////////////////////////////////////
// StringSet with individual sequences in a string of string pointers
template <typename TString>
class StringSet<TString, Dependent<Generous> >
{
public:
typedef String<TString*> TStrings;
typedef typename Size<StringSet>::Type TSize;
typedef typename StringSetLimits<StringSet>::Type TLimits;
typedef typename Concatenator<StringSet>::Type TConcatenator;
//____________________________________________________________________________
TStrings strings;
TLimits limits;
bool limitsValid; // is true if limits contains the cumulative sum of the sequence lengths
TConcatenator concat;
//____________________________________________________________________________
StringSet():
limitsValid(true)
{
SEQAN_CHECKPOINT
appendValue(limits, 0);
concat.set = this;
}
template <typename TDefault>
StringSet(StringSet<TString, Owner<TDefault> > const& _other) :
limitsValid(true)
{
SEQAN_CHECKPOINT
appendValue(limits, 0);
concat.set = this;
for(unsigned int i = 0; i<length(_other); ++i) appendValue(*this, _other[i]);
}
template <typename TPos>
inline typename Reference<StringSet>::Type
operator [] (TPos pos)
{
return value(*this, pos);
}
template <typename TPos>
inline typename Reference<StringSet const>::Type
operator [] (TPos pos) const
{
return value(*this, pos);
}
};
//////////////////////////////////////////////////////////////////////////////
// StringSet with individual sequences in a string of strings
template < typename TString >
class StringSet< TString, Owner<Default> >
{
public:
typedef String<TString> TStrings;
typedef typename StringSetLimits<StringSet>::Type TLimits;
typedef typename Concatenator<StringSet>::Type TConcatenator;
//____________________________________________________________________________
TStrings strings;
TLimits limits;
bool limitsValid; // is true if limits contains the cumulative sum of the sequence lengths
TConcatenator concat;
//____________________________________________________________________________
StringSet():
limitsValid(true)
{
appendValue(limits, 0);
concat.set = this;
};
//____________________________________________________________________________
template <typename TPos>
inline typename Reference<StringSet>::Type
operator [] (TPos pos)
{
return value(*this, pos);
}
template <typename TPos>
inline typename Reference<StringSet const>::Type
operator [] (TPos pos) const
{
return value(*this, pos);
}
};
//////////////////////////////////////////////////////////////////////////////
// StringSet with directly concatenated sequences
template < typename TString, typename TDelimiter >
class StringSet< TString, Owner<ConcatDirect<TDelimiter> > >
{
public:
typedef typename StringSetLimits<StringSet>::Type TLimits;
typedef typename Concatenator<StringSet>::Type TConcatenator;
//____________________________________________________________________________
TLimits limits;
TConcatenator concat;
//____________________________________________________________________________
StringSet() {
appendValue(limits, 0);
}
//____________________________________________________________________________
template <typename TPos>
inline typename Reference<StringSet>::Type
operator [] (TPos pos)
{
SEQAN_CHECKPOINT
return value(*this, pos);
}
template <typename TPos>
inline typename Reference<StringSet const>::Type
operator [] (TPos pos) const
{
SEQAN_CHECKPOINT
return value(*this, pos);
}
};
//////////////////////////////////////////////////////////////////////////////
// meta functions
template < typename TString, typename TSpec >
struct Value< StringSet< TString, TSpec > > {
typedef TString Type;
};
template < typename TString, typename TSpec >
struct Value< StringSet< TString, TSpec > const> {
typedef TString Type;
};
template < typename TString, typename TSpec >
struct Size< StringSet< TString, TSpec > >:
Size< typename StringSetLimits< StringSet<TString, TSpec> >::Type > {};
template < typename TString, typename TSpec >
struct Prefix< StringSet< TString, TSpec > >:
Prefix< TString > {};
template < typename TString, typename TSpec >
struct Prefix< StringSet< TString, TSpec > const >:
Prefix< TString const > {};
template < typename TString, typename TSpec >
struct Suffix< StringSet< TString, TSpec > >:
Suffix< TString > {};
template < typename TString, typename TSpec >
struct Suffix< StringSet< TString, TSpec > const >:
Suffix< TString const > {};
template < typename TString, typename TSpec >
struct Infix< StringSet< TString, TSpec > >:
Infix< TString > {};
template < typename TString, typename TSpec >
struct Infix< StringSet< TString, TSpec > const >:
Infix< TString const > {};
// direct concatenation
template < typename TString, typename TSpec >
struct Value< StringSet< TString, Owner<ConcatDirect<TSpec> > > >:
Infix<TString> {};
template < typename TString, typename TSpec >
struct GetValue< StringSet< TString, Owner<ConcatDirect<TSpec> > > >:
Infix<TString> {};
template < typename TString, typename TSpec >
struct GetValue< StringSet< TString, Owner<ConcatDirect<TSpec> > > const >:
Infix<TString const> {};
template < typename TString, typename TSpec >
struct Reference< StringSet< TString, Owner<ConcatDirect<TSpec> > > >:
Infix<TString> {};
template < typename TString, typename TSpec >
struct Reference< StringSet< TString, Owner<ConcatDirect<TSpec> > > const >:
Infix<TString const> {};
template <typename TString, typename TSpec>
struct AllowsFastRandomAccess< StringSet< TString, TSpec > >:
AllowsFastRandomAccess<TString> {};
template < typename TString, typename TSpec >
struct Prefix< StringSet< TString, Owner<ConcatDirect<TSpec> > > >:
Infix< TString > {};
template < typename TString, typename TSpec >
struct Prefix< StringSet< TString, Owner<ConcatDirect<TSpec> > > const >:
Infix< TString const > {};
template < typename TString, typename TSpec >
struct Suffix< StringSet< TString, Owner<ConcatDirect<TSpec> > > >:
Infix< TString > {};
template < typename TString, typename TSpec >
struct Suffix< StringSet< TString, Owner<ConcatDirect<TSpec> > > const >:
Infix< TString const > {};
template < typename TString, typename TSpec >
struct Infix< StringSet< TString, Owner<ConcatDirect<TSpec> > > >:
Infix< TString > {};
template < typename TString, typename TSpec >
struct Infix< StringSet< TString, Owner<ConcatDirect<TSpec> > > const >:
Infix< TString const > {};
//////////////////////////////////////////////////////////////////////////////
// validStringSetLimits
template < typename T >
inline bool _validStringSetLimits(T const &) {
return true;
}
template < typename TString, typename TSpec >
inline bool _validStringSetLimits(StringSet< TString, TSpec > const &me) {
return me.limitsValid;
}
template < typename TString, typename TSpec >
inline bool _validStringSetLimits(StringSet< TString, Owner<ConcatDirect<TSpec> > > const &) {
return true;
}
//////////////////////////////////////////////////////////////////////////////
// _refreshStringSetLimits
template < typename T >
inline void _refreshStringSetLimits(T &) {}
template < typename TString, typename TSpec >
inline void _refreshStringSetLimits(StringSet< TString, Owner<ConcatDirect<TSpec> > > &) {}
template < typename TString, typename TSpec >
inline void _refreshStringSetLimits(StringSet< TString, TSpec > &me)
{
typedef StringSet< TString, TSpec > TStringSet;
typedef typename StringSetLimits<TStringSet>::Type TLimits;
typename Value<TLimits>::Type sum = 0;
typename Size<TStringSet>::Type len = length(me);
typename Size<TStringSet>::Type i = 0;
// SEQAN_ASSERT(length(me.limits) == len + 1);
// resize(me.limits, len + 1);
for(; i < len; ++i) {
me.limits[i] = sum;
sum += length(me[i]);
}
me.limits[i] = sum;
me.limitsValid = true;
}
//////////////////////////////////////////////////////////////////////////////
// find the i-th non-zero value of a string me
template < typename TValue, typename TSpec, typename TPos >
inline typename Size< String<TValue, TSpec> >::Type
_findIthNonZeroValue(String<TValue, TSpec> const &me, TPos i)
{
typename Iterator< String<TValue, TSpec> const, Standard >::Type it = begin(me, Standard());
typename Iterator< String<TValue, TSpec> const, Standard >::Type itEnd = end(me, Standard());
for(; it != itEnd; ++it)
if (*it) {
if (i) {
--i;
}
else {
return position(it, me);
}
}
return length(me);
}
//////////////////////////////////////////////////////////////////////////////
// count non-zero values before position i
template < typename TValue, typename TSpec, typename TPos >
inline typename Size< String<TValue, TSpec> >::Type
_countNonZeroValues(String<TValue, TSpec> const &me, TPos i)
{
typename Iterator< String<TValue, TSpec> const, Standard >::Type it = begin(me, Standard());
typename Iterator< String<TValue, TSpec> const, Standard >::Type itEnd = begin(me, Standard()) + i;
typename Size< String<TValue, TSpec> >::Type counter = 0;
for(; it != itEnd; ++it)
if (*it) ++counter;
return counter;
}
//////////////////////////////////////////////////////////////////////////////
// lengthSum
template < typename TString >
inline typename Size<TString>::Type lengthSum(TString const &me) {
return length(me);
}
template < typename TString, typename TSpec >
inline typename Size<TString>::Type lengthSum(StringSet< TString, TSpec > const &me) {
return back(stringSetLimits(me));
}
///.Function.appendValue.param.target.type:Class.StringSet
//////////////////////////////////////////////////////////////////////////////
// appendValue
// Default
template < typename TString, typename TString2, typename TExpand >
inline void appendValue(
StringSet< TString, Owner<Default> > &me,
TString2 const &obj,
Tag<TExpand> const)
{
appendValue(me.strings, obj);
appendValue(me.limits, lengthSum(me) + length(obj));
}
// ConcatDirect
template < typename TString, typename TString2, typename TExpand >
inline void appendValue(
StringSet< TString, Owner<ConcatDirect<void> > > &me,
TString2 const &obj,
Tag<TExpand> const)
{
append(me.concat, obj);
appendValue(me.limits, lengthSum(me) + length(obj));
}
template < typename TString, typename TDelimiter, typename TString2, typename TExpand >
inline void appendValue(
StringSet< TString, Owner<ConcatDirect<TDelimiter> > > &me,
TString2 const &obj,
Tag<TExpand> const)
{
append(me.concat, obj);
appendValue(me.concat, TDelimiter());
appendValue(me.limits, lengthSum(me) + length(obj) + 1);
}
// Generous
template < typename TString, typename TExpand >
inline void appendValue(
StringSet<TString, Dependent<Generous> > &me,
TString const &obj,
Tag<TExpand> const)
{
SEQAN_CHECKPOINT
appendValue(me.strings, const_cast<TString*>(&obj));
appendValue(me.limits, lengthSum(me) + length(obj));
}
// Tight
template < typename TString, typename TExpand >
inline void appendValue(
StringSet<TString, Dependent<Tight> > &me,
TString const &obj,
Tag<TExpand> const)
{
SEQAN_CHECKPOINT
appendValue(me.strings, const_cast<TString*>(&obj));
appendValue(me.ids, length(me.strings) - 1);
appendValue(me.limits, lengthSum(me) + length(obj));
}
/*
inline void append(TString *_objs[], unsigned count) {
for(unsigned i = 0; i < count; ++i)
add(_objs[i]);
}
*/
///.Function.clear.param.object.type:Class.StringSet
//////////////////////////////////////////////////////////////////////////////
// clear
template < typename TString >
inline void clear(StringSet< TString, Owner<Default> > &me)
{
SEQAN_CHECKPOINT
clear(me.strings);
resize(me.limits, 1);
me.limitsValid = true;
}
template < typename TString, typename TDelimiter >
inline void clear(StringSet< TString, Owner<ConcatDirect<TDelimiter> > > &me)
{
SEQAN_CHECKPOINT
clear(me.concat);
resize(me.limits, 1);
}
template < typename TString >
inline void clear(StringSet< TString, Dependent<Generous> > & me)
{
SEQAN_CHECKPOINT
clear(me.strings);
resize(me.limits, 1);
me.limitsValid = true;
}
template < typename TString >
inline void clear(StringSet<TString, Dependent<Tight> >& me)
{
SEQAN_CHECKPOINT
clear(me.strings);
resize(me.limits, 1);
me.limitsValid = true;
clear(me.ids);
}
///.Function.length.param.object.type:Class.StringSet
//////////////////////////////////////////////////////////////////////////////
// length
template < typename TString, typename TSpec >
inline typename Size< StringSet< TString, TSpec > >::Type
length(StringSet< TString, TSpec > const &me) {
return length(me.limits) - 1;
}
template <typename TString>
inline typename Size<StringSet<TString, Dependent<Tight> > >::Type
length(StringSet<TString, Dependent<Tight> > const &me)
{
return length(me.strings);
}
///.Function.resize.param.object.type:Class.StringSet
//////////////////////////////////////////////////////////////////////////////
// resize
template < typename TString, typename TSpec, typename TSize >
inline typename Size< StringSet< TString, TSpec > >::Type
resize(StringSet< TString, TSpec > &me, TSize new_size) {
resize(me.limits, new_size + 1);
me.limitsValid = (new_size == 0);
return resize(me.strings, new_size);
}
template < typename TString, typename TSpec, typename TSize >
inline typename Size< StringSet< TString, Owner<ConcatDirect<TSpec> > > >::Type
resize(StringSet< TString, Owner<ConcatDirect<TSpec> > > &me, TSize new_size) {
return resize(me.limits, new_size + 1) - 1;
}
///.Function.value.param.object.type:Class.StringSet
//////////////////////////////////////////////////////////////////////////////
// value
// Default
template < typename TString, typename TPos >
inline typename Reference< StringSet< TString, Owner<Default> > >::Type
value(StringSet< TString, Owner<Default> > & me, TPos pos)
{
return me.strings[pos];
}
template < typename TString, typename TPos >
inline typename Reference< StringSet< TString, Owner<Default> > const >::Type
value(StringSet< TString, Owner<Default> > const & me, TPos pos)
{
return me.strings[pos];
}
// ConcatDirect
template < typename TString, typename TSpec, typename TPos >
inline typename Infix<TString>::Type
value(StringSet< TString, Owner<ConcatDirect<TSpec> > > & me, TPos pos)
{
return infix(me.concat, me.limits[pos], me.limits[pos + 1]);
}
template < typename TString, typename TSpec, typename TPos >
inline typename Infix<TString const>::Type
value(StringSet< TString, Owner<ConcatDirect<TSpec> > > const & me, TPos pos)
{
return infix(me.concat, me.limits[pos], me.limits[pos + 1]);
}
// Tight
template < typename TString, typename TPos >
inline typename Reference<StringSet< TString, Dependent<Tight> > >::Type
value(StringSet< TString, Dependent<Tight> >& me, TPos pos)
{
SEQAN_CHECKPOINT
if (me.strings[pos])
return *me.strings[pos];
static TString tmp = "";
return tmp;
}
template < typename TString, typename TPos >
inline typename Reference<StringSet< TString, Dependent<Tight> > const >::Type
value(StringSet< TString, Dependent<Tight> >const & me, TPos pos)
{
if (me.strings[pos])
return *me.strings[pos];
static TString tmp = "";
return tmp;
}
// Generous
template < typename TString, typename TPos >
inline typename Reference<StringSet< TString, Dependent<Generous> > >::Type
value(StringSet< TString, Dependent<Generous> >& me, TPos pos)
{
SEQAN_CHECKPOINT
unsigned i = _findIthNonZeroValue(me.strings, pos);
if (i < length(me.strings))
return *me.strings[i];
static TString tmp = "";
return tmp;
}
template < typename TString, typename TPos >
inline typename Reference< StringSet< TString, Dependent<Generous> > const >::Type
value(StringSet< TString, Dependent<Generous> > const & me, TPos pos)
{
SEQAN_CHECKPOINT
unsigned i = _findIthNonZeroValue(me.strings, pos);
if (i < length(me.strings))
return *me.strings[i];
static TString tmp = "";
return tmp;
}
//////////////////////////////////////////////////////////////////////////////
// getValueById
/**
.Function.getValueById:
..cat:Sequences
..summary:Retrieves a string from the StringSet given an id.
..signature:getValueById(me, id)
..param.me:A StringSet.
...type:Class.StringSet
..param.id:An id.
...type:Metafunction.Id
..returns:A reference to a string.
..see:Function.assignValueById
..see:Function.valueById
*/
template <typename TString, typename TSpec, typename TId>
inline typename Reference<StringSet<TString, Owner<TSpec> > >::Type
getValueById(StringSet<TString, Owner<TSpec> >& me,
TId const id)
{
SEQAN_CHECKPOINT
if (id < (TId) length(me)) return value(me, id);
static TString tmp = "";
return tmp;
}
template <typename TString, typename TId>
inline typename Reference<StringSet<TString, Dependent<Generous> > >::Type
getValueById(StringSet<TString, Dependent<Generous> >& me,
TId const id)
{
SEQAN_CHECKPOINT
if (me.strings[id])
return *me.strings[id];
static TString tmp = "";
return tmp;
}
template <typename TString, typename TId>
inline typename Reference<StringSet<TString, Dependent<Tight> > >::Type
getValueById(StringSet<TString, Dependent<Tight> >&me,
TId const id)
{
SEQAN_CHECKPOINT
for(unsigned i = 0; i < length(me.strings); ++i)
if ((TId) me.ids[i] == id)
return value(me, i);
static TString tmp = "";
return tmp;
}
//////////////////////////////////////////////////////////////////////////////
// valueById
/**
.Function.valueById:
..cat:Sequences
..summary:Retrieves a string from the StringSet given an id.
..signature:valueById(me, id)
..param.me:A StringSet.
...type:Class.StringSet
..param.id:An id.
...type:Metafunction.Id
..returns:A reference to a string.
..see:Function.assignValueById
..see:Function.getValueById
*/
template<typename TString, typename TSpec, typename TId>
inline typename Reference<StringSet<TString, TSpec> >::Type
valueById(StringSet<TString, TSpec>& me,
TId const id)
{
SEQAN_CHECKPOINT
return getValueById(me, id);
}
//////////////////////////////////////////////////////////////////////////////
// assignValueById
/**
.Function.assignValueById:
..cat:Sequences
..summary:Adds a new string to the StringSet and returns an id.
..signature:assignValueById(dest, str, [id])
..signature:assignValueById(dest, source, id)
..param.dest:A StringSet.
...type:Class.StringSet
..param.source:A StringSet.
...type:Class.StringSet
..param.str:A new string.
...type:Metafunction.Value
..param.id:An associated id.
...type:Metafunction.Id
..returns:A new id
...type:Metafunction.Id
..see:Function.getValueById
..see:Function.valueById
*/
template<typename TString, typename TSpec, typename TString2>
inline typename Id<StringSet<TString, TSpec> >::Type
assignValueById(StringSet<TString, TSpec>& me,
TString2& obj)
{
SEQAN_CHECKPOINT
appendValue(me, obj);
SEQAN_ASSERT(length(me.limits) == length(me) + 1);
return length(me.strings) - 1;
}
template <typename TString, typename TSpec, typename TId>
inline typename Id<StringSet<TString, Owner<TSpec> > >::Type
assignValueById(StringSet<TString, Owner<TSpec> >& me,
TString& obj,
TId id)
{
SEQAN_CHECKPOINT
if (id >= (TId) length(me.strings)) {
fill(me.strings, id+1, TString());
resize(me.limits, length(me.limits) + 1);
}
assignValue(me, id, obj);
me.limitsValid = false;
return id;
}
template<typename TString, typename TId>
inline typename Id<StringSet<TString, Dependent<Generous> > >::Type
assignValueById(StringSet<TString, Dependent<Generous> >& me,
TString& obj,
TId id)
{
SEQAN_CHECKPOINT
SEQAN_ASSERT(length(me.limits) == length(me) + 1);
if (id >= (TId) length(me.strings)) fill(me.strings, id+1, (TString*) 0);
if ((TString*) me.strings[id] == (TString*) 0)
resize(me.limits, length(me.limits) + 1);
me.strings[id] = &obj;
me.limitsValid = false;
SEQAN_ASSERT(length(me.limits) == length(me) + 1);
return id;
}
//////////////////////////////////////////////////////////////////////////////
template<typename TString, typename TId>
inline typename Id<StringSet<TString, Dependent<Tight> > >::Type
assignValueById(StringSet<TString, Dependent<Tight> >& me,
TString& obj,
TId id)
{
SEQAN_CHECKPOINT
typedef StringSet<TString, Dependent<Tight> > TStringSet;
typedef typename Size<TStringSet>::Type TSize;
for(TSize i = 0; i < length(me.ids); ++i)
if ((TId) me.ids[i] == id) {
me.strings[i] = &obj;
me.limitsValid = false;
return id;
}
appendValue(me.strings, &obj);
appendValue(me.ids, id);
return id;
}
template<typename TString, typename TSpec1, typename TSpec2, typename TId>
inline typename Id<StringSet<TString, TSpec1> >::Type
assignValueById(StringSet<TString, TSpec1>& dest,
StringSet<TString, TSpec2>& source,
TId id)
{
SEQAN_CHECKPOINT
return assignValueById(dest, getValueById(source, id), id);
}
//////////////////////////////////////////////////////////////////////////////
// removeValueById
/**
.Function.removeValueById:
..cat:Sequences
..summary:Removes a string from the StringSet given an id.
..signature:removeValueById(me, id)
..param.me:A StringSet.
...type:Class.StringSet
..param.id:An id.
...type:Metafunction.Id
..returns:void
..see:Function.assignValueById
*/
template<typename TString, typename TSpec, typename TId>
inline void
removeValueById(StringSet<TString, Owner<TSpec> >& me, TId const id)
{
SEQAN_CHECKPOINT
erase(me.strings, id);
resize(me.limits, length(me.limits) - 1);
me.limitsValid = empty(me);
}
template<typename TString, typename TId>
inline void
removeValueById(StringSet<TString, Dependent<Generous> >& me, TId const id)
{
SEQAN_CHECKPOINT
if (me.strings[id] != (TString*) 0) {
resize(me.limits, length(me.limits) - 1);
me.limitsValid = empty(me);
}
me.strings[id] = 0;
while (!empty(me.strings) && !me.strings[length(me.strings) - 1])
resize(me.strings, length(me.strings) - 1);
}
template<typename TString, typename TId>
inline void
removeValueById(StringSet<TString, Dependent<Tight> >& me, TId const id)
{
SEQAN_CHECKPOINT
typedef StringSet<TString, Dependent<Tight> > TStringSet;
typedef typename Size<TStringSet>::Type TSize;
SEQAN_ASSERT(length(me.limits) == length(me) + 1);
for(TSize i = 0; i < length(me.strings); ++i)
if (me.ids[i] == id) {
erase(me.strings, i);
erase(me.ids, i);
resize(me.limits, length(me.limits) - 1);
me.limitsValid = empty(me);
}
SEQAN_ASSERT(length(me.limits) == length(me) + 1);
}
//////////////////////////////////////////////////////////////////////////////
//
/**
.Function.positionToId:
..cat:Sequences
..summary:Retrieves the id of a string in the StringSet given a position.
..signature:positionToId(string_set, pos)
..param.string_set:A StringSet.
...type:Class.StringSet
..param.pos:A position that is transfored into an id.
..returns:An id that corresponds to $pos$ within $string_set$
..see:Function.assignValueById
..see:Function.valueById
*/
template <typename TString, typename TSpec, typename TPos>
inline typename Id<StringSet<TString, Owner<TSpec> > >::Type
positionToId(StringSet<TString, Owner<TSpec> >&,
TPos const pos)
{
SEQAN_CHECKPOINT
return pos;
}
template <typename TString, typename TPos>
inline typename Id<StringSet<TString, Dependent<Generous> > >::Type
positionToId(StringSet<TString, Dependent<Generous> >& me,
TPos const pos)
{
SEQAN_CHECKPOINT
return _findIthNonZeroValue(me.strings,pos);
}
template <typename TString, typename TPos>
inline typename Id<StringSet<TString, Dependent<Generous> > >::Type
positionToId(StringSet<TString, Dependent<Generous> > const& me,
TPos const pos)
{
SEQAN_CHECKPOINT
return _findIthNonZeroValue(me.strings,pos);
}
template <typename TString, typename TPos>
inline typename Id<StringSet<TString, Dependent<Tight> > >::Type
positionToId(StringSet<TString, Dependent<Tight> >&me,
TPos const pos)
{
SEQAN_CHECKPOINT
return me.ids[pos];
}
template <typename TString, typename TPos>
inline typename Id<StringSet<TString, Dependent<Tight> > >::Type
positionToId(StringSet<TString, Dependent<Tight> > const&me,
TPos const pos)
{
SEQAN_CHECKPOINT
return me.ids[pos];
}
/**
.Function.idToPosition:
..cat:Sequences
..summary:Retrieves the position of a string in the StringSet given an id.
..signature:idToPosition(me, id)
..param.me:A StringSet.
...type:Class.StringSet
..param.id:An id.
...type:Metafunction.Id
..returns:A reference to a string.
..see:Function.assignValueById
..see:Function.valueById
*/
template <typename TString, typename TSpec, typename TId>
inline typename Id<StringSet<TString, Owner<TSpec> > >::Type
idToPosition(StringSet<TString, Owner<TSpec> >&,
TId const id)
{
SEQAN_CHECKPOINT
return id;
}
template <typename TString, typename TId>
inline typename Id<StringSet<TString, Dependent<Generous> > >::Type
idToPosition(StringSet<TString, Dependent<Generous> >& me,
TId const id)
{
SEQAN_CHECKPOINT
return _countNonZeroValues(me.strings,id);
}
template <typename TString, typename TId>
inline typename Id<StringSet<TString, Dependent<Tight> > >::Type
idToPosition(StringSet<TString, Dependent<Tight> >&me,
TId const id)
{
SEQAN_CHECKPOINT
for(unsigned i = 0; i < length(me.ids); ++i)
if ((TId) me.ids[i] == id)
return i;
return 0;
}
//////////////////////////////////////////////////////////////////////////////
// subset
/**
.Function.subset:
..cat:Sequences
..summary:Creates a subset of a given StringSet.
..signature:subset(source, dest, id_array [, len])
..param.source:In-parameter:The source StringSet.
...type:Class.StringSet
..param.dest:Out-parameter:The destination StringSet (the subset).
...type:Class.StringSet
..param.id_array:In-parameter:An array of ids. Each id corresponds to a sequence that is supposed to be in the subset.
..param.len:In-parameter:Optional length of the id array.
...remarks:If len is not defined the length function must be valid for this array or string type.
..returns:void
*/
template <typename TString, typename TSpec, typename TDestSpec, typename TIds, typename TLength>
inline void
subset(StringSet<TString, Owner<TSpec> >& source,
StringSet<TString, TDestSpec>& dest,
TIds ids,
TLength len)
{
SEQAN_CHECKPOINT
}
template <typename TString, typename TIds, typename TLength>
inline void
subset(StringSet<TString, Dependent<Generous> >& source,
StringSet<TString, Dependent<Generous> >& dest,
TIds ids,
TLength len)
{
SEQAN_CHECKPOINT
typedef StringSet<TString, Dependent<Generous> > TStringSet;
typedef typename Id<TStringSet>::Type TId;
typedef typename Size<TStringSet>::Type TSize;
clear(dest);
resize(dest.limits, len + 1);
dest.limitsValid = (len == 0);
fill(dest.strings, length(source.strings), (TString*) 0);
for(TSize i = 0; i < len; ++i)
dest.strings[ids[i]] = source.strings[ids[i]];
}
template <typename TString, typename TIds, typename TLength>
inline void
subset(StringSet<TString, Dependent<Tight> >& source,
StringSet<TString, Dependent<Tight> >& dest,
TIds ids,
TLength len)
{
SEQAN_CHECKPOINT
typedef StringSet<TString, Dependent<Tight> > TStringSet;
typedef typename Id<TStringSet>::Type TId;
typedef typename Size<TStringSet>::Type TSize;
clear(dest);
resize(dest.limits, len + 1);
dest.limitsValid = (len == 0);
TLength upperBound = length(source.ids);
for(TSize i=0;i<len;++i) {
TId id = ids[i];
if ((upperBound > id) &&
(source.ids[id] == id)) {
appendValue(dest.strings, source.strings[id]);
appendValue(dest.ids, id);
} else {
typedef String<TId> TIdString;
typedef typename Iterator<TIdString, Rooted>::Type TIter;
TIter it = begin(source.ids);
for(;!atEnd(it);goNext(it)) {
if (*it == id) {
appendValue(dest.strings, source.strings[position(it)]);
appendValue(dest.ids, id);
}
}
}
}
}
template <typename TString, typename TSpec, typename TIds>
inline void
subset(StringSet<TString, TSpec>& source,
StringSet<TString, TSpec>& dest,
TIds ids)
{
SEQAN_CHECKPOINT
subset(source, dest, ids, length(ids));
}
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// ConcatenatorNto1 - a StringSet to String converter
//////////////////////////////////////////////////////////////////////////////
template <typename TStringSet>
struct ConcatenatorNto1 {
TStringSet *set;
ConcatenatorNto1 () {}
ConcatenatorNto1 (TStringSet &_set): set(&_set) {}
//____________________________________________________________________________
// WARNING:
// operator[] conducts a binary search and should be avoided
// you better use StringSet<.., Owner<ConcatDirect<..> > > for random access
// or ConcatenatorNto1's iterators for sequential access
template <typename TPos>
inline typename Reference<ConcatenatorNto1>::Type
operator [] (TPos pos)
{
SEQAN_CHECKPOINT
return value(*this, pos);
}
template <typename TPos>
inline typename Reference<ConcatenatorNto1 const>::Type
operator [] (TPos pos) const
{
SEQAN_CHECKPOINT
return value(*this, pos);
}
};
//____________________________________________________________________________
template <typename TStringSet>
struct Value< ConcatenatorNto1<TStringSet> > {
typedef typename Value< typename Value<TStringSet>::Type >::Type Type;
};
template <typename TStringSet>
struct Value< ConcatenatorNto1<TStringSet> const >:
Value< ConcatenatorNto1<TStringSet> > {};
//____________________________________________________________________________
template <typename TStringSet>
struct Size< ConcatenatorNto1<TStringSet> > {
typedef typename Size< typename Value<TStringSet>::Type >::Type Type;
};
//____________________________________________________________________________
template <typename TStringSet>
struct AllowsFastRandomAccess< ConcatenatorNto1<TStringSet> >
{
typedef False Type;
enum { VALUE = false };
};
//////////////////////////////////////////////////////////////////////////////
// value
template < typename TStringSet, typename TPos >
inline typename Reference< ConcatenatorNto1<TStringSet> >::Type
value(ConcatenatorNto1<TStringSet> &me, TPos globalPos)
{
Pair<unsigned, typename Size< typename Value<TStringSet>::Type >::Type> localPos;
posLocalize(localPos, globalPos, stringSetLimits(*me.set));
return value(value(*me.set, getValueI1(localPos)), getValueI2(localPos));
}
template < typename TStringSet, typename TPos >
inline typename Reference< ConcatenatorNto1<TStringSet> const >::Type
value(ConcatenatorNto1<TStringSet> const &me, TPos globalPos)
{
typedef typename Value<TStringSet>::Type TString;
Pair<unsigned, typename Size<TString>::Type> localPos;
posLocalize(localPos, globalPos, stringSetLimits(*me.set));
return value(value(*(TStringSet const*)me.set, getValueI1(localPos)), getValueI2(localPos));
}
//////////////////////////////////////////////////////////////////////////////
// length
template < typename TStringSet >
inline typename Size< ConcatenatorNto1<TStringSet> >::Type
length(ConcatenatorNto1<TStringSet> const &me) {
return lengthSum(*me.set);
}
//////////////////////////////////////////////////////////////////////////////
// begin
template < typename TStringSet, typename TSpec >
inline typename Iterator< ConcatenatorNto1<TStringSet const>, Tag<TSpec> const >::Type
begin(ConcatenatorNto1<TStringSet const> concat, Tag<TSpec> const)
{
return typename Iterator< ConcatenatorNto1<TStringSet const>, Tag<TSpec> const >::Type (*concat.set);
}
template < typename TStringSet, typename TSpec >
inline typename Iterator< ConcatenatorNto1<TStringSet>, Tag<TSpec> const >::Type
begin(ConcatenatorNto1<TStringSet> concat, Tag<TSpec> const)
{
return typename Iterator< ConcatenatorNto1<TStringSet>, Tag<TSpec> const >::Type (*concat.set);
}
//////////////////////////////////////////////////////////////////////////////
// end
template < typename TStringSet, typename TSpec >
inline typename Iterator< ConcatenatorNto1<TStringSet const>, Tag<TSpec> const >::Type
end(ConcatenatorNto1<TStringSet const> concat, Tag<TSpec> const)
{
return typename Iterator< ConcatenatorNto1<TStringSet>, Tag<TSpec> const >::Type
(*concat.set, length(*concat.set), 0);
}
template < typename TStringSet, typename TSpec >
inline typename Iterator< ConcatenatorNto1<TStringSet>, Tag<TSpec> const >::Type
end(ConcatenatorNto1<TStringSet> concat, Tag<TSpec> const)
{
return typename Iterator< ConcatenatorNto1<TStringSet>, Tag<TSpec> const >::Type
(*concat.set, length(*concat.set), 0);
}
//////////////////////////////////////////////////////////////////////////////
// Concatenator metafunction
template < typename TString, typename TSpec >
struct Concatenator< StringSet<TString, TSpec> > {
typedef ConcatenatorNto1< StringSet<TString, TSpec> > Type;
};
template < typename TString, typename TSpec >
struct Concatenator< StringSet<TString, Owner<ConcatDirect<TSpec> > > > {
typedef TString Type;
};
//////////////////////////////////////////////////////////////////////////////
// concat
template <typename TString>
inline typename Concatenator<TString>::Type &
concat(TString &string) {
return string;
}
template <typename TString, typename TSpec>
inline typename Concatenator< StringSet<TString, TSpec> >::Type &
concat(StringSet<TString, TSpec> &set) {
return set.concat;
}
template <typename TString, typename TSpec>
inline typename Concatenator< StringSet<TString, TSpec> const>::Type &
concat(StringSet<TString, TSpec> const &set) {
return set.concat;
}
//////////////////////////////////////////////////////////////////////////////
// This iterator sequentially iterates through the elements of TStringSet
// as if they were directly concatenated (compare StringSet<.., Owner<ConcatDirect<> > >
//////////////////////////////////////////////////////////////////////////////
template < typename TDelimiter = void >
struct ConcatVirtual;
template < typename TStringSet, typename TSpec >
class Iter< TStringSet, ConcatVirtual<TSpec> >
{
public:
typedef typename Value<TStringSet>::Type TString;
typedef typename Value<TString>::Type TValue;
typedef typename Size<TString>::Type TSize;
//____________________________________________________________________________
public:
typedef typename Iterator<TString, Standard>::Type obj_iterator;
typedef typename Iterator<TString const, Standard>::Type const_obj_iterator;
//////////////////////////////////////////////////////////////////////////////
// STL compatible public iterator interface
typedef Iter iterator;
typedef ::std::bidirectional_iterator_tag iterator_category;
typedef TValue value_type;
typedef TValue & reference;
typedef TValue const & const_reference;
typedef TValue* pointer;
typedef TSize size_type;
typedef typename Difference<TString>::Type difference_type;
//____________________________________________________________________________
TStringSet *host;
unsigned objNo;
obj_iterator _begin, _cur, _end;
//____________________________________________________________________________
inline Iter() {}
inline Iter(TStringSet &_host):
host(&_host)
{
objNo = 0;
_begin = _cur = begin(_host[objNo]);
_end = end(_host[objNo]);
_testEnd();
}
inline Iter(TStringSet &_host, unsigned _objNo, difference_type _offset):
host(&_host)
{
if (_objNo < length(_host)) {
objNo = _objNo;
_begin = _cur = begin(_host[objNo]);
_end = end(_host[objNo]);
goFurther(_cur, _offset);
_testEnd();
} else {
objNo = length(_host) - 1;
_begin = _cur = _end = end(_host[objNo]);
}
}
inline operator obj_iterator() {
return _cur;
}
//____________________________________________________________________________
inline bool _atEndOfSequence() {
if (_cur == _begin && objNo > 0) return true;
if (_cur == _end) return true;
return false;
}
inline void _testBegin() {
while (_cur == _begin && objNo > 0) {
--objNo;
_begin = host->_begin(objNo);
_end = _cur = host->_end(objNo);
}
}
inline void _testEnd() {
while (_cur == _end && objNo < (length(*host) - 1)) {
++objNo;
_begin = _cur = begin((*host)[objNo]);
_end = end((*host)[objNo]);
};
}
inline TSize _tell() const {
typedef Pair<unsigned, TSize> TPair;
return posGlobalize(TPair(objNo, difference(_begin, _cur)), stringSetLimits(*host));
}
};
//////////////////////////////////////////////////////////////////////////////
// ConcatenatorNto1 meta functions
//////////////////////////////////////////////////////////////////////////////
//____________________________________________________________________________
// default concatenator iterators
template <typename TString, typename TSpec >
struct Iterator< ConcatenatorNto1< StringSet<TString, TSpec> >, Standard > {
typedef Iter<StringSet<TString, TSpec>, ConcatVirtual<> > Type;
};
template <typename TString, typename TSpec >
struct Iterator< ConcatenatorNto1< StringSet<TString, TSpec> const >, Standard > {
typedef Iter<StringSet<TString, TSpec> const, ConcatVirtual<> > Type;
};
template <typename TString, typename TSpec >
struct Iterator< ConcatenatorNto1< StringSet<TString, TSpec> >, Rooted > {
typedef Iter<StringSet<TString, TSpec>, ConcatVirtual<> > Type;
};
template <typename TString, typename TSpec >
struct Iterator< ConcatenatorNto1< StringSet<TString, TSpec> const >, Rooted > {
typedef Iter<StringSet<TString, TSpec> const, ConcatVirtual<> > Type;
};
//____________________________________________________________________________
template <typename TStringSet >
struct Iterator< ConcatenatorNto1<TStringSet> const, Standard > {
typedef typename Iterator< ConcatenatorNto1<TStringSet>, Standard >::Type Type;
};
template <typename TStringSet >
struct Iterator< ConcatenatorNto1<TStringSet> const, Rooted > {
typedef typename Iterator< ConcatenatorNto1<TStringSet>, Rooted >::Type Type;
};
//////////////////////////////////////////////////////////////////////////////
// meta functions
//////////////////////////////////////////////////////////////////////////////
template <typename TStringSet, typename TSpec>
struct Value< Iter< TStringSet, ConcatVirtual<TSpec> > >:
Value< typename Value<TStringSet>::Type > {};
template <typename TStringSet, typename TSpec>
struct Value< Iter< TStringSet, ConcatVirtual<TSpec> > const >:
Value< typename Value<TStringSet>::Type > {};
template <typename TStringSet, typename TSpec>
struct GetValue< Iter< TStringSet, ConcatVirtual<TSpec> > >:
GetValue< typename Value<TStringSet>::Type > {};
template <typename TStringSet, typename TSpec>
struct GetValue< Iter< TStringSet, ConcatVirtual<TSpec> > const >:
GetValue< typename Value<TStringSet>::Type > {};
template <typename TStringSet, typename TSpec>
struct Size< Iter< TStringSet, ConcatVirtual<TSpec> > >:
Size< typename Value<TStringSet>::Type > {};
template <typename TStringSet, typename TSpec>
struct Reference< Iter< TStringSet, ConcatVirtual<TSpec> > >:
Reference< typename Value<TStringSet>::Type > {};
template <typename TStringSet, typename TSpec>
struct Reference< Iter< TStringSet, ConcatVirtual<TSpec> > const >:
Reference< typename Value<TStringSet>::Type > {};
//////////////////////////////////////////////////////////////////////////////
// operator *
//////////////////////////////////////////////////////////////////////////////
template <typename TStringSet, typename TSpec>
inline typename Reference< Iter< TStringSet, ConcatVirtual<TSpec> > const>::Type
value(Iter<TStringSet, ConcatVirtual<TSpec> > const & me) {
return *me._cur;
}
template <typename TStringSet, typename TSpec>
inline typename Reference< Iter< TStringSet, ConcatVirtual<TSpec> > >::Type
value(Iter<TStringSet, ConcatVirtual<TSpec> > & me) {
return *me._cur;
}
template <typename TStringSet, typename TSpec>
inline typename Reference< Iter< TStringSet, ConcatVirtual<TSpec> > const>::Type
operator * (Iter<TStringSet, ConcatVirtual<TSpec> > const & me) {
return *me._cur;
}
template <typename TStringSet, typename TSpec>
inline typename Reference< Iter< TStringSet, ConcatVirtual<TSpec> > >::Type
operator * (Iter<TStringSet, ConcatVirtual<TSpec> > & me) {
return *me._cur;
}
//////////////////////////////////////////////////////////////////////////////
// operator ++
//////////////////////////////////////////////////////////////////////////////
template <typename TStringSet, typename TSpec>
inline void
goNext(Iter<TStringSet, ConcatVirtual<TSpec> > & me) {
++me._cur;
me._testEnd();
}
template <typename TStringSet, typename TSpec>
inline Iter<TStringSet, ConcatVirtual<TSpec> > const &
operator ++ (Iter<TStringSet, ConcatVirtual<TSpec> > & me) {
goNext(me);
return me;
}
template <typename TStringSet, typename TSpec>
inline Iter<TStringSet, ConcatVirtual<TSpec> > const &
operator ++ (Iter<TStringSet, ConcatVirtual<TSpec> > & me, int) {
Iter<TStringSet, ConcatVirtual<TSpec> > before = me;
goNext(me);
return before;
}
//////////////////////////////////////////////////////////////////////////////
// operator --
//////////////////////////////////////////////////////////////////////////////
template <typename TStringSet, typename TSpec>
inline void
goPrevious(Iter<TStringSet, ConcatVirtual<TSpec> > & me) {
me._testBegin();
--me._cur;
}
template <typename TStringSet, typename TSpec>
inline Iter<TStringSet, ConcatVirtual<TSpec> > const &
operator -- (Iter<TStringSet, ConcatVirtual<TSpec> > & me) {
goPrevious(me);
return me;
}
template <typename TStringSet, typename TSpec>
inline Iter<TStringSet, ConcatVirtual<TSpec> > const &
operator -- (Iter<TStringSet, ConcatVirtual<TSpec> > & me, int) {
Iter<TStringSet, ConcatVirtual<TSpec> > before = me;
goPrevious(me);
return before;
}
//////////////////////////////////////////////////////////////////////////////
// operator +
//////////////////////////////////////////////////////////////////////////////
template <typename TStringSet, typename TSpec, typename TDelta>
inline Iter<TStringSet, ConcatVirtual<TSpec> >
operator + (Iter<TStringSet, ConcatVirtual<TSpec> > const & me, TDelta delta) {
Pair<unsigned, typename Size< typename Value<TStringSet>::Type >::Type> pos;
posLocalize(pos, me._tell() + delta, stringSetLimits(*me.host));
return Iter<TStringSet, ConcatVirtual<TSpec> > (*me.host, getValueI1(pos), getValueI2(pos));
}
template <typename TStringSet, typename TSpec, typename T1, typename T2, typename TCompression>
inline Iter<TStringSet, ConcatVirtual<TSpec> >
operator + (Iter<TStringSet, ConcatVirtual<TSpec> > const & me, Pair<T1, T2, TCompression> delta) {
Pair<unsigned, typename Size< typename Value<TStringSet>::Type >::Type> pos;
posLocalize(pos, me._tell() + delta, stringSetLimits(*me.host));
return Iter<TStringSet, ConcatVirtual<TSpec> > (*me.host, getValueI1(pos), getValueI2(pos));
}
//////////////////////////////////////////////////////////////////////////////
// operator -
//////////////////////////////////////////////////////////////////////////////
template <typename TSSetL, typename TSpecL, typename TSSetR, typename TSpecR>
typename Difference<Iter<TSSetL, ConcatVirtual<TSpecL> > >::Type
operator - (
Iter<TSSetL, ConcatVirtual<TSpecL> > const &L,
Iter<TSSetR, ConcatVirtual<TSpecR> > const &R)
{
return L._tell() - R._tell();
}
template <typename TStringSet, typename TSpec, typename TDelta>
inline Iter<TStringSet, ConcatVirtual<TSpec> >
operator - (Iter<TStringSet, ConcatVirtual<TSpec> > const & me, TDelta delta) {
Pair<unsigned, typename Size< typename Value<TStringSet>::Type >::Type> pos;
posLocalize(pos, me._tell() - delta, stringSetLimits(*me.host));
return Iter<TStringSet, ConcatVirtual<TSpec> > (*me.host, getValueI1(pos), getValueI2(pos));
}
//////////////////////////////////////////////////////////////////////////////
// operator ==
//////////////////////////////////////////////////////////////////////////////
template <typename TSSetL, typename TSpecL, typename TSSetR, typename TSpecR>
inline bool
operator == (
Iter<TSSetL, ConcatVirtual<TSpecL> > const &L,
Iter<TSSetR, ConcatVirtual<TSpecR> > const &R)
{
SEQAN_ASSERT(L.host == R.host);
return L.objNo == R.objNo && L._cur == R._cur;
}
template <typename TSSetL, typename TSpecL, typename TSSetR, typename TSpecR>
inline bool
operator != (
Iter<TSSetL, ConcatVirtual<TSpecL> > const &L,
Iter<TSSetR, ConcatVirtual<TSpecR> > const &R)
{
SEQAN_ASSERT(L.host == R.host);
return L.objNo != R.objNo || L._cur != R._cur;
}
//////////////////////////////////////////////////////////////////////////////
// operator <
//////////////////////////////////////////////////////////////////////////////
template <typename TSSetL, typename TSpecL, typename TSSetR, typename TSpecR>
inline bool
operator < (
Iter<TSSetL, ConcatVirtual<TSpecL> > const &L,
Iter<TSSetR, ConcatVirtual<TSpecR> > const &R)
{
SEQAN_ASSERT(L.host == R.host);
return L.objNo < R.objNo || (L.objNo == R.objNo && L._cur < R._cur);
}
template <typename TSSetL, typename TSpecL, typename TSSetR, typename TSpecR>
inline bool
operator > (
Iter<TSSetL, ConcatVirtual<TSpecL> > const &L,
Iter<TSSetR, ConcatVirtual<TSpecR> > const &R)
{
SEQAN_ASSERT(L.host == R.host);
return L.objNo > R.objNo || (L.objNo == R.objNo && L._cur > R._cur);
}
//////////////////////////////////////////////////////////////////////////////
// container
//////////////////////////////////////////////////////////////////////////////
template <typename TSSet, typename TSpec>
inline typename Concatenator<TSSet>::Type
container(Iter<TSSet, ConcatVirtual<TSpec> > &me)
{
return concat(*me.host);
}
template <typename TSSet, typename TSpec>
inline typename Concatenator<TSSet>::Type
container(Iter<TSSet, ConcatVirtual<TSpec> > const &me)
{
return concat(*me.host);
}
//////////////////////////////////////////////////////////////////////////////
// atBegin
//////////////////////////////////////////////////////////////////////////////
template <typename TSSet, typename TSpec>
inline bool
atBegin(Iter<TSSet, ConcatVirtual<TSpec> > &me)
{
return me._cur == me._begin && me.objNo == 0;
}
template <typename TSSet, typename TSpec>
inline bool
atBegin(Iter<TSSet, ConcatVirtual<TSpec> > const &me)
{
return me._cur == me._begin && me.objNo == 0;
}
//////////////////////////////////////////////////////////////////////////////
// atEnd
//////////////////////////////////////////////////////////////////////////////
template <typename TSSet, typename TSpec>
inline bool
atEnd(Iter<TSSet, ConcatVirtual<TSpec> > &me)
{
return me._cur == me._end && me.objNo == (length(*me.host) - 1);
}
template <typename TSSet, typename TSpec>
inline bool
atEnd(Iter<TSSet, ConcatVirtual<TSpec> > const &me)
{
return me._cur == me._end && me.objNo == (length(*me.host) - 1);
}
//////////////////////////////////////////////////////////////////////////////
// atEndOfSequence
//////////////////////////////////////////////////////////////////////////////
template <typename TIterator>
inline bool
atEndOfSequence(TIterator const &me)
{
return atEnd(me);
}
template <typename TSSet, typename TSpec>
inline bool
atEndOfSequence(Iter<TSSet, ConcatVirtual<TSpec> > const &me)
{
return me._atEndOfSequence();
}
template <typename TIterator>
inline bool
atEndOfSequence(TIterator &me)
{
return atEndOfSequence(reinterpret_cast<TIterator const &>(me));
}
}
#endif
| 33.158723 | 204 | 0.642364 | [
"object"
] |
0ef5a9d7ed53d5b9e40fd2101dca02fa37789962 | 4,154 | h | C | DataFormats/Provenance/interface/Provenance.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 6 | 2017-09-08T14:12:56.000Z | 2022-03-09T23:57:01.000Z | DataFormats/Provenance/interface/Provenance.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 545 | 2017-09-19T17:10:19.000Z | 2022-03-07T16:55:27.000Z | DataFormats/Provenance/interface/Provenance.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 14 | 2017-10-04T09:47:21.000Z | 2019-10-23T18:04:45.000Z | #ifndef DataFormats_Provenance_Provenance_h
#define DataFormats_Provenance_Provenance_h
/*----------------------------------------------------------------------
Provenance: The full description of a product and how it came into
existence.
----------------------------------------------------------------------*/
#include "DataFormats/Provenance/interface/ParameterSetID.h"
#include "DataFormats/Provenance/interface/Parentage.h"
#include "DataFormats/Provenance/interface/StableProvenance.h"
#include <memory>
#include <iosfwd>
/*
Provenance
definitions:
Product: The EDProduct to which a provenance object is associated
Creator: The EDProducer that made the product.
Parents: The EDProducts used as input by the creator.
*/
namespace edm {
class MergeableRunProductMetadataBase;
class ProductProvenance;
class ProductProvenanceRetriever;
class Provenance {
public:
Provenance();
Provenance(std::shared_ptr<BranchDescription const> const& p, ProductID const& pid);
Provenance(StableProvenance const&);
StableProvenance const& stable() const { return stableProvenance_; }
StableProvenance& stable() { return stableProvenance_; }
BranchDescription const& branchDescription() const { return stable().branchDescription(); }
std::shared_ptr<BranchDescription const> const& constBranchDescriptionPtr() const {
return stable().constBranchDescriptionPtr();
}
ProductProvenance const* productProvenance() const;
bool knownImproperlyMerged() const;
BranchID const& branchID() const { return stable().branchID(); }
std::string const& branchName() const { return stable().branchName(); }
std::string const& className() const { return stable().className(); }
std::string const& moduleLabel() const { return stable().moduleLabel(); }
std::string const& moduleName() const { return stable().moduleName(); }
std::string const& processName() const { return stable().processName(); }
std::string const& productInstanceName() const { return stable().productInstanceName(); }
std::string const& friendlyClassName() const { return stable().friendlyClassName(); }
ProductProvenanceRetriever const* store() const { return store_; }
std::set<std::string> const& branchAliases() const { return stable().branchAliases(); }
// Usually branchID() and originalBranchID() return exactly the same result.
// The return values can differ only in cases where an EDAlias is involved.
// For example, if you "get" a product and then get the Provenance object
// available through the Handle, you will find that branchID() and originalBranchID()
// will return different values if and only if an EDAlias was used to specify
// the desired product and in a previous process the EDAlias was kept and
// the original branch name was dropped. In that case, branchID() returns
// the BranchID of the EDAlias and originalBranchID() returns the BranchID
// of the branch name that was dropped. One reason the original BranchID can
// be useful is that Parentage information is stored using the original BranchIDs.
BranchID const& originalBranchID() const { return stable().originalBranchID(); }
void write(std::ostream& os) const;
void setStore(ProductProvenanceRetriever const* store) { store_ = store; }
ProductID const& productID() const { return stable().productID(); }
void setProductID(ProductID const& pid) { stable().setProductID(pid); }
void setMergeableRunProductMetadata(MergeableRunProductMetadataBase const* mrpm) {
mergeableRunProductMetadata_ = mrpm;
}
void setBranchDescription(std::shared_ptr<BranchDescription const> const& p) { stable().setBranchDescription(p); }
void swap(Provenance&);
private:
StableProvenance stableProvenance_;
ProductProvenanceRetriever const* store_;
MergeableRunProductMetadataBase const* mergeableRunProductMetadata_;
};
inline std::ostream& operator<<(std::ostream& os, Provenance const& p) {
p.write(os);
return os;
}
bool operator==(Provenance const& a, Provenance const& b);
} // namespace edm
#endif
| 39.188679 | 118 | 0.712085 | [
"object"
] |
0ef7ae6c90f1114103b35de9cf3a22bb3921dd1a | 5,684 | h | C | projectionIL/include/whisk_action.h | plasma-umass/openwhisk-cli | 4d0856abba3bc11a42840da0d0c5055f8439f117 | [
"Apache-2.0"
] | null | null | null | projectionIL/include/whisk_action.h | plasma-umass/openwhisk-cli | 4d0856abba3bc11a42840da0d0c5055f8439f117 | [
"Apache-2.0"
] | null | null | null | projectionIL/include/whisk_action.h | plasma-umass/openwhisk-cli | 4d0856abba3bc11a42840da0d0c5055f8439f117 | [
"Apache-2.0"
] | null | null | null | #include <string>
#include <vector>
#include <string.h>
#include "utils.h"
#include "serverless.h"
#ifndef __WHISK_ACTION_H__
#define __WHISK_ACTION_H__
#define WHISK_CLI_PATH "wsk"
#define WHISK_CLI_ARGS "-i"
#define ECHO(x) (std::string("echo \"")+x+"\"")
enum
{
WHISK_FORK_NAME_LENGTH = 10,
WHISK_SEQ_NAME_LENGTH = 10,
WHISK_PROJ_NAME_LENGTH = 10
};
typedef ServerlessAction WhiskAction;
class WhiskSequence : public ServerlessSequence
{
public:
WhiskSequence(std::string name) : ServerlessSequence (name)
{
}
WhiskSequence(std::string name, std::vector<ServerlessAction*> _actions) : ServerlessSequence(name, _actions)
{
}
virtual void print ()
{
fprintf (stdout, "(WhiskSequence %s, %ld, (", getName (), actions.size ());
for (auto action : actions) {
action->print ();
fprintf (stdout, " -> ");
}
fprintf (stdout, "))\n");
}
virtual void generateCommand(std::ostream& os)
{
for (auto action : actions) {
action->generateCommand (os);
}
os << WHISK_CLI_PATH << " " << WHISK_CLI_ARGS << " action update " << getName () << " --sequence ";
if (actions.size () > 0) {
for (int i = 0; i < actions.size () - 1; i++) {
os << actions[i]->getNameForSeq () << ",";
}
os << actions[actions.size () - 1]->getNameForSeq () << std::endl;
}
}
};
class WhiskProjection : public ServerlessProjection
{
public:
WhiskProjection (std::string name, std::string _code) : ServerlessProjection (name, _code)
{
}
virtual void generateCommand(std::ostream& os)
{
char temp[256];
assert (getProjectionTempFile (temp, 256) != -1);
os << ECHO(getProjCode ()) << " > " << temp << "\n";
os << WHISK_CLI_PATH << " " << WHISK_CLI_ARGS << " action update " << getName () << " --projection " << temp << "\n";
}
};
class WhiskFork : public ServerlessFork
{
public:
WhiskFork (std::string name, std::string _innerActionName, std::string _returnName, std::string requiredFields) : ServerlessFork (name, _innerActionName, _returnName, requiredFields)
{
}
WhiskFork (std::string name, ServerlessAction* _innerAction, std::string _returnName, std::string requiredFields) : ServerlessFork (name, _innerAction, _returnName, requiredFields)
{
}
virtual void generateCommand(std::ostream& os)
{
os << WHISK_CLI_PATH << " " << WHISK_CLI_ARGS << " action update " <<
getName() << " --fork " << getInnerActionName() << std::endl;
char temp[256];
assert (getProjectionTempFile (temp, 256) != -1);
char code[2048];
resultProjectionName = "Proj_"+gen_random_str (WHISK_PROJ_NAME_LENGTH);
if (requiredFields != "") {
sprintf (code, R"(. * {\"saved\": {\"%s\": %s}})", returnName.c_str(), requiredFields.c_str ());
} else {
sprintf (code, R"(. * {\"saved\": {\"%s\": .input}})", returnName.c_str());
}
os << ECHO(code) << " > " << temp << std::endl;
os << WHISK_CLI_PATH << " " WHISK_CLI_ARGS << " action update " <<
resultProjectionName << " --projection " << temp << std::endl;
}
};
class WhiskProjForkPair : public ServerlessAction
{
private:
WhiskFork* fork;
WhiskProjection* proj;
public:
WhiskProjForkPair (WhiskProjection* _proj, WhiskFork* _fork):
WhiskAction ("ProjForkPair_" + gen_random_str (WHISK_FORK_NAME_LENGTH)),
fork(_fork), proj(_proj)
{
}
virtual void print ()
{
proj->print ();
fprintf (stdout, " -> ");
fork->print ();
}
virtual void generateCommand(std::ostream& os)
{
proj->generateCommand(os);
fork->generateCommand(os);
}
virtual std::string getNameForSeq () {return proj->getName () + std::string(",") + fork->getName () + "," + fork->getResultProjectionName();}
};
typedef ServerlessApp WhiskApp;
class WhiskDirectBranch : public ServerlessApp
{
private:
std::string target;
WhiskProjection* proj;
public:
WhiskDirectBranch (std::string _target) : target(_target)
{
proj = new WhiskProjection ("Proj_DirectBranch_" +gen_random_str (WHISK_PROJ_NAME_LENGTH),
R"(. * {\"action\":\")" + target+R"(\"})"); //TODO: Wrap correctly in app.
}
virtual void print ()
{
fprintf (stdout, "App (%s)", target.c_str ());
}
virtual void generateCommand (std::ostream& os)
{
proj->generateCommand (os);
//os << WHISK_CLI_PATH << " " << WHISK_CLI_ARGS << " action invoke " << getName () << std::endl;
}
virtual std::string getNameForSeq () {return std::string(proj->getName ());}
};
class WhiskProgram : public ServerlessProgram
{
public:
WhiskProgram (std::string _name) : ServerlessProgram (_name)
{
}
WhiskProgram (std::string _name, std::vector <WhiskSequence*> _basicBlocks) :
ServerlessProgram (_name, std::vector<ServerlessSequence*> (_basicBlocks.begin(), _basicBlocks.end()))
{
}
virtual void generateCommand(std::ostream& os)
{
for (auto block : basicBlocks) {
block->generateCommand (os);
std::cout << std::endl;
}
os << WHISK_CLI_PATH << " " << WHISK_CLI_ARGS << " action update " << getName () << " --program ";
if (basicBlocks.size () > 0) {
for (int i = 0; i < basicBlocks.size () - 1; i++) {
os << basicBlocks[i]->getNameForSeq () << ",";
}
os << basicBlocks[basicBlocks.size () - 1]->getNameForSeq () << std::endl;
}
}
virtual void print ()
{
fprintf (stdout, "(WhiskProgram %s, %ld, (", getName (), basicBlocks.size ());
for (auto block : basicBlocks) {
block->print ();
fprintf (stdout, " -> ");
}
fprintf (stdout, "))\n");
}
};
#endif
| 26.938389 | 184 | 0.6133 | [
"vector"
] |
0ef8663cc07c7dcea63ac55d3578335f57c826c2 | 5,459 | h | C | includes/geos/noding/IntersectionAdder.h | Kikehulk/mposm3-for-windows | 014b2d444232ac00a4e0ea46b2ba072689446324 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2020-07-20T00:06:34.000Z | 2020-10-17T19:46:07.000Z | includes/geos/noding/IntersectionAdder.h | geostonemarten/imposm3-for-windows | 014b2d444232ac00a4e0ea46b2ba072689446324 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | includes/geos/noding/IntersectionAdder.h | geostonemarten/imposm3-for-windows | 014b2d444232ac00a4e0ea46b2ba072689446324 | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2020-10-17T19:45:50.000Z | 2022-01-11T22:20:58.000Z | /**********************************************************************
*
* GEOS - Geometry Engine Open Source
* http://geos.osgeo.org
*
* Copyright (C) 2006 Refractions Research Inc.
*
* This is free software; you can redistribute and/or modify it under
* the terms of the GNU Lesser General Public Licence as published
* by the Free Software Foundation.
* See the COPYING file for more information.
*
**********************************************************************
*
* Last port: noding/IntersectionAdder.java rev. 1.6 (JTS-1.9)
*
**********************************************************************/
#ifndef GEOS_NODING_INTERSECTIONADDER_H
#define GEOS_NODING_INTERSECTIONADDER_H
#include <geos/export.h>
#include <vector>
#include <iostream>
#include <cstdlib> // for abs()
#include <geos/inline.h>
#include <geos/geom/Coordinate.h>
#include <geos/noding/SegmentIntersector.h> // for inheritance
// Forward declarations
namespace geos {
namespace noding {
class SegmentString;
}
namespace algorithm {
class LineIntersector;
}
}
namespace geos {
namespace noding { // geos.noding
/** \brief
* Computes the intersections between two line segments in SegmentString
* and adds them to each string.
*
* The SegmentIntersector is passed to a Noder.
* The NodedSegmentString::addIntersections(algorithm::LineIntersector* li, size_t segmentIndex, size_t geomIndex)
* method is called whenever the Noder
* detects that two SegmentStrings *might* intersect.
* This class is an example of the *Strategy* pattern.
*
*/
class GEOS_DLL IntersectionAdder: public SegmentIntersector {
private:
/**
* These variables keep track of what types of intersections were
* found during ALL edges that have been intersected.
*/
bool hasIntersectionVar;
bool hasProper;
bool hasProperInterior;
bool hasInterior;
// the proper intersection point found
geom::Coordinate properIntersectionPoint;
algorithm::LineIntersector& li;
// bool isSelfIntersection;
// bool intersectionFound;
/**
* A trivial intersection is an apparent self-intersection which
* in fact is simply the point shared by adjacent line segments.
* Note that closed edges require a special check for the point
* shared by the beginning and end segments.
*/
bool isTrivialIntersection(const SegmentString* e0, size_t segIndex0,
const SegmentString* e1, size_t segIndex1);
// Declare type as noncopyable
IntersectionAdder(const IntersectionAdder& other) = delete;
IntersectionAdder& operator=(const IntersectionAdder& rhs) = delete;
public:
int numIntersections;
int numInteriorIntersections;
int numProperIntersections;
// testing only
int numTests;
IntersectionAdder(algorithm::LineIntersector& newLi)
:
hasIntersectionVar(false),
hasProper(false),
hasProperInterior(false),
hasInterior(false),
properIntersectionPoint(),
li(newLi),
numIntersections(0),
numInteriorIntersections(0),
numProperIntersections(0),
numTests(0)
{}
algorithm::LineIntersector&
getLineIntersector()
{
return li;
}
/**
* @return the proper intersection point, or `Coordinate::getNull()`
* if none was found
*/
const geom::Coordinate&
getProperIntersectionPoint()
{
return properIntersectionPoint;
}
bool
hasIntersection()
{
return hasIntersectionVar;
}
/** \brief
* A proper intersection is an intersection which is interior to
* at least two line segments.
*
* Note that a proper intersection is not necessarily in the interior
* of the entire Geometry, since another edge may have an endpoint equal
* to the intersection, which according to SFS semantics can result in
* the point being on the Boundary of the Geometry.
*/
bool
hasProperIntersection()
{
return hasProper;
}
/** \brief
* A proper interior intersection is a proper intersection which is
* *not* contained in the set of boundary nodes set for this SegmentIntersector.
*/
bool
hasProperInteriorIntersection()
{
return hasProperInterior;
}
/** \brief
* An interior intersection is an intersection which is
* in the interior of some segment.
*/
bool
hasInteriorIntersection()
{
return hasInterior;
}
/** \brief
* This method is called by clients of the SegmentIntersector class to
* process intersections for two segments of the SegmentStrings being intersected.
*
* Note that some clients (such as MonotoneChains) may optimize away
* this call for segment pairs which they have determined do not
* intersect (e.g. by an disjoint envelope test).
*/
void processIntersections(
SegmentString* e0, size_t segIndex0,
SegmentString* e1, size_t segIndex1) override;
static bool
isAdjacentSegments(size_t i1, size_t i2)
{
return (i1 > i2 ? i1 - i2 : i2 - i1) == 1;
}
/** \brief
* Always process all intersections.
*
* @return false always
*/
bool
isDone() const override
{
return false;
}
};
} // namespace geos.noding
} // namespace geos
#endif // GEOS_NODING_INTERSECTIONADDER_H
| 26.371981 | 114 | 0.64847 | [
"geometry",
"vector"
] |
0ef97d60ce4494720bc56b9994dd541f078d245b | 11,235 | h | C | qemu/include/hw/qdev-properties.h | hyunjoy/scripts | 01114d3627730d695b5ebe61093c719744432ffa | [
"Apache-2.0"
] | 44 | 2022-03-16T08:32:31.000Z | 2022-03-31T16:02:35.000Z | qemu/include/hw/qdev-properties.h | hyunjoy/scripts | 01114d3627730d695b5ebe61093c719744432ffa | [
"Apache-2.0"
] | 1 | 2022-03-29T02:30:28.000Z | 2022-03-30T03:40:46.000Z | qemu/include/hw/qdev-properties.h | hyunjoy/scripts | 01114d3627730d695b5ebe61093c719744432ffa | [
"Apache-2.0"
] | 18 | 2022-03-19T04:41:04.000Z | 2022-03-31T03:32:12.000Z | #ifndef QEMU_QDEV_PROPERTIES_H
#define QEMU_QDEV_PROPERTIES_H
#include "hw/qdev-core.h"
/**
* Property:
* @set_default: true if the default value should be set from @defval,
* in which case @info->set_default_value must not be NULL
* (if false then no default value is set by the property system
* and the field retains whatever value it was given by instance_init).
* @defval: default value for the property. This is used only if @set_default
* is true.
*/
struct Property {
const char *name;
const PropertyInfo *info;
ptrdiff_t offset;
uint8_t bitnr;
bool set_default;
union {
int64_t i;
uint64_t u;
} defval;
int arrayoffset;
const PropertyInfo *arrayinfo;
int arrayfieldsize;
const char *link_type;
};
struct PropertyInfo {
const char *name;
const char *description;
const QEnumLookup *enum_table;
int (*print)(Object *obj, Property *prop, char *dest, size_t len);
void (*set_default_value)(ObjectProperty *op, const Property *prop);
ObjectProperty *(*create)(ObjectClass *oc, const char *name,
Property *prop);
ObjectPropertyAccessor *get;
ObjectPropertyAccessor *set;
ObjectPropertyRelease *release;
};
/*** qdev-properties.c ***/
extern const PropertyInfo qdev_prop_bit;
extern const PropertyInfo qdev_prop_bit64;
extern const PropertyInfo qdev_prop_bool;
extern const PropertyInfo qdev_prop_enum;
extern const PropertyInfo qdev_prop_uint8;
extern const PropertyInfo qdev_prop_uint16;
extern const PropertyInfo qdev_prop_uint32;
extern const PropertyInfo qdev_prop_int32;
extern const PropertyInfo qdev_prop_uint64;
extern const PropertyInfo qdev_prop_int64;
extern const PropertyInfo qdev_prop_size;
extern const PropertyInfo qdev_prop_string;
extern const PropertyInfo qdev_prop_on_off_auto;
extern const PropertyInfo qdev_prop_size32;
extern const PropertyInfo qdev_prop_arraylen;
extern const PropertyInfo qdev_prop_link;
#define DEFINE_PROP(_name, _state, _field, _prop, _type, ...) { \
.name = (_name), \
.info = &(_prop), \
.offset = offsetof(_state, _field) \
+ type_check(_type, typeof_field(_state, _field)), \
__VA_ARGS__ \
}
#define DEFINE_PROP_SIGNED(_name, _state, _field, _defval, _prop, _type) \
DEFINE_PROP(_name, _state, _field, _prop, _type, \
.set_default = true, \
.defval.i = (_type)_defval)
#define DEFINE_PROP_SIGNED_NODEFAULT(_name, _state, _field, _prop, _type) \
DEFINE_PROP(_name, _state, _field, _prop, _type)
#define DEFINE_PROP_BIT(_name, _state, _field, _bit, _defval) \
DEFINE_PROP(_name, _state, _field, qdev_prop_bit, uint32_t, \
.bitnr = (_bit), \
.set_default = true, \
.defval.u = (bool)_defval)
#define DEFINE_PROP_UNSIGNED(_name, _state, _field, _defval, _prop, _type) \
DEFINE_PROP(_name, _state, _field, _prop, _type, \
.set_default = true, \
.defval.u = (_type)_defval)
#define DEFINE_PROP_UNSIGNED_NODEFAULT(_name, _state, _field, _prop, _type) \
DEFINE_PROP(_name, _state, _field, _prop, _type)
#define DEFINE_PROP_BIT64(_name, _state, _field, _bit, _defval) \
DEFINE_PROP(_name, _state, _field, qdev_prop_bit64, uint64_t, \
.bitnr = (_bit), \
.set_default = true, \
.defval.u = (bool)_defval)
#define DEFINE_PROP_BOOL(_name, _state, _field, _defval) \
DEFINE_PROP(_name, _state, _field, qdev_prop_bool, bool, \
.set_default = true, \
.defval.u = (bool)_defval)
#define PROP_ARRAY_LEN_PREFIX "len-"
/**
* DEFINE_PROP_ARRAY:
* @_name: name of the array
* @_state: name of the device state structure type
* @_field: uint32_t field in @_state to hold the array length
* @_arrayfield: field in @_state (of type '@_arraytype *') which
* will point to the array
* @_arrayprop: PropertyInfo defining what property the array elements have
* @_arraytype: C type of the array elements
*
* Define device properties for a variable-length array _name. A
* static property "len-arrayname" is defined. When the device creator
* sets this property to the desired length of array, further dynamic
* properties "arrayname[0]", "arrayname[1]", ... are defined so the
* device creator can set the array element values. Setting the
* "len-arrayname" property more than once is an error.
*
* When the array length is set, the @_field member of the device
* struct is set to the array length, and @_arrayfield is set to point
* to (zero-initialised) memory allocated for the array. For a zero
* length array, @_field will be set to 0 and @_arrayfield to NULL.
* It is the responsibility of the device deinit code to free the
* @_arrayfield memory.
*/
#define DEFINE_PROP_ARRAY(_name, _state, _field, \
_arrayfield, _arrayprop, _arraytype) \
DEFINE_PROP((PROP_ARRAY_LEN_PREFIX _name), \
_state, _field, qdev_prop_arraylen, uint32_t, \
.set_default = true, \
.defval.u = 0, \
.arrayinfo = &(_arrayprop), \
.arrayfieldsize = sizeof(_arraytype), \
.arrayoffset = offsetof(_state, _arrayfield))
#define DEFINE_PROP_LINK(_name, _state, _field, _type, _ptr_type) \
DEFINE_PROP(_name, _state, _field, qdev_prop_link, _ptr_type, \
.link_type = _type)
#define DEFINE_PROP_UINT8(_n, _s, _f, _d) \
DEFINE_PROP_UNSIGNED(_n, _s, _f, _d, qdev_prop_uint8, uint8_t)
#define DEFINE_PROP_UINT16(_n, _s, _f, _d) \
DEFINE_PROP_UNSIGNED(_n, _s, _f, _d, qdev_prop_uint16, uint16_t)
#define DEFINE_PROP_UINT32(_n, _s, _f, _d) \
DEFINE_PROP_UNSIGNED(_n, _s, _f, _d, qdev_prop_uint32, uint32_t)
#define DEFINE_PROP_INT32(_n, _s, _f, _d) \
DEFINE_PROP_SIGNED(_n, _s, _f, _d, qdev_prop_int32, int32_t)
#define DEFINE_PROP_UINT64(_n, _s, _f, _d) \
DEFINE_PROP_UNSIGNED(_n, _s, _f, _d, qdev_prop_uint64, uint64_t)
#define DEFINE_PROP_INT64(_n, _s, _f, _d) \
DEFINE_PROP_SIGNED(_n, _s, _f, _d, qdev_prop_int64, int64_t)
#define DEFINE_PROP_SIZE(_n, _s, _f, _d) \
DEFINE_PROP_UNSIGNED(_n, _s, _f, _d, qdev_prop_size, uint64_t)
#define DEFINE_PROP_STRING(_n, _s, _f) \
DEFINE_PROP(_n, _s, _f, qdev_prop_string, char*)
#define DEFINE_PROP_ON_OFF_AUTO(_n, _s, _f, _d) \
DEFINE_PROP_SIGNED(_n, _s, _f, _d, qdev_prop_on_off_auto, OnOffAuto)
#define DEFINE_PROP_SIZE32(_n, _s, _f, _d) \
DEFINE_PROP_UNSIGNED(_n, _s, _f, _d, qdev_prop_size32, uint32_t)
#define DEFINE_PROP_END_OF_LIST() \
{}
/*
* Set properties between creation and realization.
*
* Returns: %true on success, %false on error.
*/
bool qdev_prop_set_drive_err(DeviceState *dev, const char *name,
BlockBackend *value, Error **errp);
/*
* Set properties between creation and realization.
* @value must be valid. Each property may be set at most once.
*/
void qdev_prop_set_bit(DeviceState *dev, const char *name, bool value);
void qdev_prop_set_uint8(DeviceState *dev, const char *name, uint8_t value);
void qdev_prop_set_uint16(DeviceState *dev, const char *name, uint16_t value);
void qdev_prop_set_uint32(DeviceState *dev, const char *name, uint32_t value);
void qdev_prop_set_int32(DeviceState *dev, const char *name, int32_t value);
void qdev_prop_set_uint64(DeviceState *dev, const char *name, uint64_t value);
void qdev_prop_set_string(DeviceState *dev, const char *name, const char *value);
void qdev_prop_set_chr(DeviceState *dev, const char *name, Chardev *value);
void qdev_prop_set_netdev(DeviceState *dev, const char *name, NetClientState *value);
void qdev_prop_set_drive(DeviceState *dev, const char *name,
BlockBackend *value);
void qdev_prop_set_macaddr(DeviceState *dev, const char *name,
const uint8_t *value);
void qdev_prop_set_enum(DeviceState *dev, const char *name, int value);
void *object_field_prop_ptr(Object *obj, Property *prop);
void qdev_prop_register_global(GlobalProperty *prop);
const GlobalProperty *qdev_find_global_prop(Object *obj,
const char *name);
int qdev_prop_check_globals(void);
void qdev_prop_set_globals(DeviceState *dev);
void error_set_from_qdev_prop_error(Error **errp, int ret, Object *obj,
const char *name, const char *value);
/**
* qdev_property_add_static:
* @dev: Device to add the property to.
* @prop: The qdev property definition.
*
* Add a static QOM property to @dev for qdev property @prop.
* On error, store error in @errp. Static properties access data in a struct.
* The type of the QOM property is derived from prop->info.
*/
void qdev_property_add_static(DeviceState *dev, Property *prop);
/**
* qdev_alias_all_properties: Create aliases on source for all target properties
* @target: Device which has properties to be aliased
* @source: Object to add alias properties to
*
* Add alias properties to the @source object for all qdev properties on
* the @target DeviceState.
*
* This is useful when @target is an internal implementation object
* owned by @source, and you want to expose all the properties of that
* implementation object as properties on the @source object so that users
* of @source can set them.
*/
void qdev_alias_all_properties(DeviceState *target, Object *source);
/**
* @qdev_prop_set_after_realize:
* @dev: device
* @name: name of property
* @errp: indirect pointer to Error to be set
* Set the Error object to report that an attempt was made to set a property
* on a device after it has already been realized. This is a utility function
* which allows property-setter functions to easily report the error in
* a friendly format identifying both the device and the property.
*/
void qdev_prop_set_after_realize(DeviceState *dev, const char *name,
Error **errp);
/**
* qdev_prop_allow_set_link_before_realize:
*
* Set the #Error object if an attempt is made to set the link after realize.
* This function should be used as the check() argument to
* object_property_add_link().
*/
void qdev_prop_allow_set_link_before_realize(const Object *obj,
const char *name,
Object *val, Error **errp);
#endif
| 43.715953 | 85 | 0.648687 | [
"object"
] |
0efb63e815c61d580d0a63536307d5b3e6c6fcbb | 856 | h | C | mod/storage/trajectory.h | tinysky-glm/AMT-MOD | 6ec12d986871e9d0fd309e7ac65defcbf5d3f110 | [
"BSD-3-Clause"
] | 4 | 2018-11-05T01:35:13.000Z | 2019-03-15T16:54:41.000Z | mod/storage/trajectory.h | tinysky-glm/AMT-MOD | 6ec12d986871e9d0fd309e7ac65defcbf5d3f110 | [
"BSD-3-Clause"
] | null | null | null | mod/storage/trajectory.h | tinysky-glm/AMT-MOD | 6ec12d986871e9d0fd309e7ac65defcbf5d3f110 | [
"BSD-3-Clause"
] | null | null | null | /*!
* \file trajectory.h
* \brief The trajectory of moving object, such as taxi.
*/
#pragma once
#include <string>
#include <vector>
#include "mod/storage/point.h"
namespace mod {
class Trajectory {
public:
Trajectory();
/*
* 根据轨迹文件,构建轨迹类.
*/
explicit Trajectory(const std::string& file);
/*
* 追加新的点到轨迹里
*/
void AddPoint(const Point& point);
/*
* 返回第index个轨迹点,index取值范围[0, point_num())
*/
const Point& point(int index) const {
return points_[index];
}
/*
* 返回所有的轨迹点
*/
const std::vector<Point>& points() const {
return points_;
}
/*
* 返回轨迹包含多少个点。
*/
size_t point_num() const {
return points_.size();
}
protected:
/*
* std::vector是C++的Array容器类, 可参考C++ Reference查找用途.
* http://www.cplusplus.com/reference/
*/
std::vector<Point> points_;
};
} // namespace mod
| 15.563636 | 56 | 0.61215 | [
"object",
"vector"
] |
16081985844cedeebf4b5e64b0fea60c113ce821 | 11,766 | h | C | CircularStatsStorage.h | IvarJonsson/Project-Unknown | 4675b41bbb5e90135c7bf3aded2c2e262b50f351 | [
"BSL-1.0"
] | null | null | null | CircularStatsStorage.h | IvarJonsson/Project-Unknown | 4675b41bbb5e90135c7bf3aded2c2e262b50f351 | [
"BSL-1.0"
] | null | null | null | CircularStatsStorage.h | IvarJonsson/Project-Unknown | 4675b41bbb5e90135c7bf3aded2c2e262b50f351 | [
"BSL-1.0"
] | null | null | null | // Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved.
/******************************************************************************
** CircularStatsStorage.h
** 14/04/10
******************************************************************************/
#ifndef __CIRCULARSTATSSTORAGE_H__
#define __CIRCULARSTATSSTORAGE_H__
#include "RecordingBuffer.h"
#include <CryGame/IGameStatistics.h>
#include <CrySystem/TimeValue.h>
#include "Utility/DoubleLinkedList.h"
#include "ITelemetryCollector.h"
#if defined(_DEBUG)
#define DEBUG_CIRCULAR_STATS 1
#else
#define DEBUG_CIRCULAR_STATS 0
#endif
#if DEBUG_CIRCULAR_STATS
#include "GameMechanismManager/GameMechanismBase.h"
#endif
enum
{
eRBPT_TimelineEntry = eRBPT_Custom,
eRBPT_StatAnyValue,
eRBPT_Free
};
class CCircularBufferStatsStorage : public IStatsStorageFactory
#if DEBUG_CIRCULAR_STATS
,protected CGameMechanismBase
#endif
{
protected:
CRecordingBuffer m_circularBuffer;
int m_totalBytesAlloced;
int m_totalBytesRequested;
int m_peakAlloc;
int m_numDiscards;
int m_refCount;
bool m_serializeLocked;
static void DiscardCallback(SRecording_Packet *ps, float recordedTime, void *inUserData);
virtual ~CCircularBufferStatsStorage();
static CCircularBufferStatsStorage *s_storage; // it wouldn't be too difficult to extend the system to support multiple circular buffers, it would just require all allocations of
// timeline entries to specify which buffer they want to allocate from. for now, have a global buffer for all stats
public:
#if DEBUG_CIRCULAR_STATS
int m_numLegacyEvents;
int m_numCircularEvents;
virtual void Update(float inDt) { DebugUpdate(); }
void DebugUpdate();
#endif
static CCircularBufferStatsStorage *GetDefaultStorage();
static CCircularBufferStatsStorage *GetDefaultStorageNoCheck();
CCircularBufferStatsStorage(size_t inBufferSize);
void AddRef();
void Release();
virtual IStatsContainer *CreateContainer();
bool ContainsPtr(const void *inPtr);
bool IsUsingCircularBuffer() { return m_circularBuffer.capacity()>0; }
void *Alloc(int inSize, uint8 inType);
static void Free(void *inPtr);
bool IsDataTruncated() { return m_numDiscards>0; }
int GetTotalSessionMemoryRequests() { return m_totalBytesRequested; }
int GetBufferCapacity() { return m_circularBuffer.capacity(); }
void ResetUsageCounters();
void LockForSerialization();
void UnlockFromSerialization();
bool IsLockedForSerialization();
};
// an implementation of the IGameStatistics IXMLSerializable interface which can be stored in a circular buffer
// data payload in in subclass
// as entry can be purged at any time, it is not advisable to hold references to these objects
class CCircularBufferTimelineEntry : public CXMLSerializableBase
{
protected:
CTimeValue m_time;
public:
CDoubleLinkedElement m_timelineLink;
CCircularBufferTimelineEntry();
CCircularBufferTimelineEntry(
const CCircularBufferTimelineEntry &inCopyMe);
virtual ~CCircularBufferTimelineEntry();
CCircularBufferTimelineEntry &operator=(const CCircularBufferTimelineEntry &inCopyMe)
{
m_time=inCopyMe.m_time;
return *this;
}
// called from the storage discard callback when the memory is being freed and the object HAS to go
// will assert if references are still held
void ForceRelease();
const CTimeValue &GetTime() const { return m_time; }
void SetTime(const CTimeValue &inTime) { m_time=inTime; }
static CCircularBufferTimelineEntry *EntryFromListElement(const CDoubleLinkedElement *inElement);
// allocations will come from the circular pool and be deleted if purged due to lack of space
// there is potential to allocate from different circular storage pools as required, but in order to ease transition there is a default one set and multiple ones aren't currently supported
void *operator new(size_t inSize) throw() { return CCircularBufferStatsStorage::GetDefaultStorage()->Alloc(inSize,eRBPT_TimelineEntry); }
void *operator new(size_t inSize, CCircularBufferStatsStorage *inStorage) throw() { return inStorage->Alloc(inSize,eRBPT_TimelineEntry); }
void operator delete(void *inPtr) { CCircularBufferStatsStorage::Free(inPtr); }
};
// simple storage for a stat any value
struct SCircularStatAnyValue
{
SStatAnyValue val;
CTimeValue time;
CDoubleLinkedElement link;
SCircularStatAnyValue()
{
}
SCircularStatAnyValue(const SCircularStatAnyValue &inCopyMe)
{
*this=inCopyMe;
}
SCircularStatAnyValue &operator=(const SCircularStatAnyValue &inCopyMe)
{
val=inCopyMe.val;
time=inCopyMe.time;
return *this;
}
void *operator new(size_t inSize, CCircularBufferStatsStorage *inStorage) throw() { return inStorage->Alloc(inSize,eRBPT_StatAnyValue); }
void operator delete(void *inPtr, CCircularBufferStatsStorage *inStorage) { CCircularBufferStatsStorage::Free(inPtr); }
void operator delete(void *inPtr) { CCircularBufferStatsStorage::Free(inPtr); }
static SCircularStatAnyValue *EntryFromListElement(const CDoubleLinkedElement *inElement);
};
// a timeline of events. the type specifies the type of allocation and all events on the time line must be of the same type
class CCircularBufferTimeline
{
#ifndef _RELEASE
friend class CCircularBufferStatsContainer;
#endif
protected:
uint8 m_type; // eRBPT_* enum
public:
CDoubleLinkedList m_list;
CCircularBufferTimeline() :
m_type(eRBPT_Invalid)
{
}
void SetType(
uint8 inType)
{
CRY_ASSERT_MESSAGE(m_type==eRBPT_Invalid || m_type==inType,"Cannot intermix different types of stats on the same event time line");
m_type=inType;
}
uint8 GetType() const
{
return m_type;
}
};
// implementation of a stats container that uses the circular buffer to manage its allocations
class CCircularBufferStatsContainer : public IStatsContainer
{
protected:
CCircularBufferStatsStorage *m_storage;
CCircularBufferTimeline *m_timelines;
SStatAnyValue *m_states;
int m_refCount;
size_t m_numTimelines;
size_t m_numStates;
CCircularBufferTimeline *GetMutableTimeline(size_t inTimelineId);
SStatAnyValue *GetMutableState(size_t inStateId);
inline const char *GetEventName(size_t inEventId);
~CCircularBufferStatsContainer();
public:
CCircularBufferStatsContainer(CCircularBufferStatsStorage *inStorage);
virtual void Init(size_t numEvents, size_t numStates);
virtual void AddRef();
virtual void Release();
virtual void AddEvent(size_t eventID, const CTimeValue& time, const SStatAnyValue& val);
virtual void AddState(size_t stateID, const SStatAnyValue& val);
virtual size_t GetEventTrackLength(size_t eventID) const;
virtual void GetEventInfo(size_t eventID, size_t idx, CTimeValue& outTime, SStatAnyValue& outParam) const;
virtual void GetStateInfo(size_t stateID, SStatAnyValue& outValue) const;
virtual void Clear();
virtual bool IsEmpty() const;
virtual void GetMemoryStatistics(ICrySizer *pSizer);
const CCircularBufferTimeline *GetTimeline(size_t inTimelineId) const;
const SStatAnyValue *GetState(size_t inStateId) const;
bool HasAnyTimelineEvents() const;
#ifndef _RELEASE
void Validate() const;
#endif
};
class CCircularXMLSerializer : public IStatsSerializer, public ITelemetryProducer
{
protected:
enum ESerializeAction
{
k_openTag,
k_closeTag
};
struct SSerializeEntry
{
ESerializeAction action;
CryFixedStringT<64> tagName;
IStatsContainerPtr pContainer;
};
typedef std::vector<SSerializeEntry> TEntries;
enum EState
{
k_notStartedProducing,
k_producing
};
struct SWriteState
{
char *pBuffer;
int bufferSize;
int dataWritten;
bool full;
};
TEntries m_entries;
_smart_ptr<CCircularBufferStatsStorage> m_pStorage;
EState m_state;
int m_containerIterator;
CDoubleLinkedList::const_iterator m_eventIterator;
int m_timelineIterator;
int m_stateIterator;
int m_indentLevel;
char m_indentStr[32]; // max indentation
void SerializeContainerTag(
SWriteState *pIOState,
CCircularBufferStatsContainer *pInCont,
IGameStatistics *pInStats);
void SerializeTimeline(
SWriteState *pIOState,
CCircularBufferStatsContainer *pInCont,
IGameStatistics *pInStats);
void SerializeTimelines(
SWriteState *pIOState,
CCircularBufferStatsContainer *pInCont,
IGameStatistics *pInStats);
void SerializeStates(
SWriteState *pIOState,
CCircularBufferStatsContainer *pInCont,
IGameStatistics *pInStats);
void IncreaseIndentation(
int inDelta);
bool Output(
SWriteState *pIOState,
const char *pInDataToWrite,
int inDataLenToWrite,
bool inDoIndent);
public:
CCircularXMLSerializer(
CCircularBufferStatsStorage *pInStorage);
virtual ~CCircularXMLSerializer();
virtual void VisitNode(
const SNodeLocator& locator,
const char* serializeName,
IStatsContainer& container,
EStatNodeState state);
virtual void LeaveNode(
const SNodeLocator& locator,
const char* serializeName,
IStatsContainer& container,
EStatNodeState state);
virtual EResult ProduceTelemetry(
char *pOutBuffer,
int inMinRequired,
int inBufferSize,
int *pOutWritten);
};
#endif // __CIRCULARSTATSSTORAGE_H__
| 36.314815 | 190 | 0.598079 | [
"object",
"vector"
] |
1611181c504aebc9a6a57cd4f2f7fa8ce9ccb9cd | 5,046 | h | C | 3rd-party/gloox/src/presence.h | ForNeVeR/cthulhu-bot | bee022cf03c17c75d01cbc8c2cdb5c888859fbc0 | [
"MIT"
] | null | null | null | 3rd-party/gloox/src/presence.h | ForNeVeR/cthulhu-bot | bee022cf03c17c75d01cbc8c2cdb5c888859fbc0 | [
"MIT"
] | 1 | 2017-07-22T04:10:51.000Z | 2017-07-22T04:10:51.000Z | 3rd-party/gloox/src/presence.h | ForNeVeR/cthulhu-bot | bee022cf03c17c75d01cbc8c2cdb5c888859fbc0 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2007-2009 by Jakob Schroeter <js@camaya.net>
This file is part of the gloox library. http://camaya.net/gloox
This software is distributed under a license. The full license
agreement can be found in the file LICENSE in this distribution.
This software may not be copied, modified, sold or distributed
other than expressed in the named license agreement.
This software is distributed without any warranty.
*/
#ifndef PRESENCE_H__
#define PRESENCE_H__
#include "stanza.h"
#include <string>
namespace gloox
{
class Capabilities;
class JID;
/**
* @brief An abstraction of a presence stanza.
*
* @author Jakob Schroeter <js@camaya.net>
* @since 1.0
*/
class GLOOX_API Presence : public Stanza
{
friend class ClientBase;
public:
/**
* Describes the different valid presence types.
*/
enum PresenceType
{
Available, /**< The entity is online. */
Chat, /**< The entity is 'available for chat'. */
Away, /**< The entity is away. */
DND, /**< The entity is DND (Do Not Disturb). */
XA, /**< The entity is XA (eXtended Away). */
Unavailable, /**< The entity is offline. */
Probe, /**< This is a presence probe. */
Error, /**< This is a presence error. */
Invalid /**< The stanza is invalid. */
};
/**
* Creates a Presence request.
* @param type The presence type.
* @param to The intended receiver. Use an empty JID to create a broadcast packet.
* @param status An optional status message (e.g. "gone fishing").
* @param priority An optional presence priority. Legal range is between -128 and +127.
* Defaults to 0.
* @param xmllang An optional xml:lang for the status message.
*/
Presence( PresenceType type, const JID& to, const std::string& status = EmptyString,
int priority = 0, const std::string& xmllang = EmptyString );
/**
* Destructor.
*/
virtual ~Presence();
/**
* Returns the presence's type.
* @return The presence's type.
*/
PresenceType subtype() const { return m_subtype; }
/**
* A convenience function returning the stanza's Capabilities, if any. May be 0.
* @return A pointer to a Capabilities object, or 0.
*/
const Capabilities* capabilities() const;
/**
* Returns the presence's type.
* @return The presence's type.
*/
//#warning FIXME return something useful (only 'show' values?) or kill this func
PresenceType presence() const { return m_subtype; }
/**
* Sets the presence type.
* @param type The presence type.
*/
void setPresence( PresenceType type ) { m_subtype = type; }
/**
* Returns the status text of a presence stanza for the given language if available.
* If the requested language is not available, the default status text (without a xml:lang
* attribute) will be returned.
* @param lang The language identifier for the desired language. It must conform to
* section 2.12 of the XML specification and RFC 3066. If empty, the default body
* will be returned, if any.
* @return The status text set by the sender.
*/
const std::string status( const std::string& lang = "default" ) const
{
return findLang( m_stati, m_status, lang );
}
/**
* Adds a (possibly translated) status message.
* @param status The status message.
* @param lang The language identifier for the desired language. It must conform to
* section 2.12 of the XML specification and RFC 3066.
*/
void addStatus( const std::string& status, const std::string& lang = EmptyString )
{
setLang( &m_stati, m_status, status, lang );
}
/**
* Resets the default status message as well as all language-specific ones.
*/
void resetStatus();
/**
* Returns the presence priority in the legal range: -128 to +127.
* @return The priority information contained in the stanza, defaults to 0.
*/
int priority() const { return m_priority; }
/**
* Sets the priority. Legal range: -128 to +127.
* @param priority The priority to set.
*/
void setPriority( int priority );
// reimplemented from Stanza
virtual Tag* tag() const;
private:
#ifdef PRESENCE_TEST
public:
#endif
/**
* Creates a Presence request from the given Tag. The original Tag will be ripped off.
* @param tag The Tag to parse.
*/
Presence( Tag* tag );
PresenceType m_subtype;
StringMap* m_stati;
std::string m_status;
int m_priority;
};
}
#endif // PRESENCE_H__
| 31.148148 | 96 | 0.591756 | [
"object"
] |
1615e0f379c20c5752cfcdc958b77716d01e9116 | 3,908 | h | C | externals/desert/include/DesertManager.h | lefevre-fraser/openmeta-mms | 08f3115e76498df1f8d70641d71f5c52cab4ce5f | [
"MIT"
] | null | null | null | externals/desert/include/DesertManager.h | lefevre-fraser/openmeta-mms | 08f3115e76498df1f8d70641d71f5c52cab4ce5f | [
"MIT"
] | null | null | null | externals/desert/include/DesertManager.h | lefevre-fraser/openmeta-mms | 08f3115e76498df1f8d70641d71f5c52cab4ce5f | [
"MIT"
] | null | null | null | #ifndef DESERTMANAGER_H
#define DESERTMANAGER_H
#include <list>
#include <fstream>
#include <exception>
class Desert_exception : public std::exception
{
public:
Desert_exception() throw();
Desert_exception(const Desert_exception &a) throw() : description(a.description) { }
Desert_exception(const std::string &d) throw() : description(d) { }
Desert_exception(const char *d) throw() : description(d) { }
virtual ~Desert_exception() throw() { }
virtual const char *what() const throw() { return description.c_str(); }
protected:
std::string description;
};
class DesertManager
{
private:
std::string importer;
std::string exporter;
std::string inputModel;
std::list<std::string> outputModels;
std::string desertIfaceFile;
std::string desertIfaceBackFile;
std::string constraints;
bool applyAll;
int cfgCount;
std::ofstream logFile;
public:
DesertManager();
~DesertManager();
/*
* register the executable that generates a DesertIface XML file from an input model file
* param importer is the name of such executable, e.g. scamla2desert.exe
* the usage of importer is: "importer inputModel"
*/
void registerImporter(const std::string &importer);
/*
* register the executable that generates an output file with a given input model file,
* a DesertIfaceBack XML file and a configuration number.
* param exporter is the name of such executable, e.g. desert2scamla.exe
* the usage of exporter is: "exporter inputModel DesertIfaceBack.xml cfgId s"
* the argument s is for silent mode without GUI shown up
*/
void registerExporter(const std::string &exporter);
/*
* execute the importer on the model file with the given name to generate the DesertIface XML file
* param modelFile is the name of the source model file that will be processed by the
* registered importer and exporter.
*/
void importModel(const std::string &modelFile);
/*
* insert the constraint to the set of constraints to be applied to run the deserttool.
* param name is the name of the constraint
* param expr is the expression of the constraint
* param path is the full path of the component which contains this inserted constraint
* the seperator "\" is used in the full path (e.g. com1\com2\com3)
* tip: if the component name is unique, use the name instead of the full path
*/
void addConstraint(const std::string &name, const std::string &expr, const std::string &path);
/*
* apply the constraint to run the deserttool
* param constraint_name is the name of the constraint to be applied
*/
void applyConstraint(const std::string &constraint_name);
/*
* apply the list of constraints to run the deserttool
* param constraints_list is the string of the list of constraints to be applied
* the seperator ":" is used in the list of constraint (e.g. constraint1:constraint2)
*/
void applyConstraints(const std::string &constraints_list);
/*
* apply all the constraints in the constraint set to run the deserttool
*/
void applyAllConstraints();
/*
* generate the DesertIfaceBack xml file from the DesertIface xml file generated from the
* input model file and constraints to be applied,
* return the number of configurations in the output DesertIfaceBack XML file
*/
int runDesert();
/*
* execute the exporter to generate the output model file with the given input model file,
* generated DesertIfaceBack xml file and the specified configuration index.
* param cfgIndex is the index of the configurations in the DesertIfaceBack xml file
*/
void exportModel(int cfgIndex);
/*
* for all the configurations in the DesertIfaceBack xml file, execute the exporter to generate the
* corresponding output model with the same given input model file
*/
void exportAll();
protected:
void log(const std::string &info);
};
#endif | 33.982609 | 100 | 0.727482 | [
"model"
] |
16177f8232c00c177c56cde0d56d3038e9ac58f8 | 43,101 | h | C | mesh.h | alecjacobson/fast_muscles | 92150eaa81a4c1cbd27a76dbe4f10d27dffca3b4 | [
"MIT"
] | 1 | 2021-02-09T08:28:39.000Z | 2021-02-09T08:28:39.000Z | mesh.h | alecjacobson/fast_muscles | 92150eaa81a4c1cbd27a76dbe4f10d27dffca3b4 | [
"MIT"
] | null | null | null | mesh.h | alecjacobson/fast_muscles | 92150eaa81a4c1cbd27a76dbe4f10d27dffca3b4 | [
"MIT"
] | null | null | null | #ifndef MESH
#define MESH
#include <unsupported/Eigen/KroneckerProduct>
#include <json.hpp>
#include <unsupported/Eigen/MatrixFunctions>
#include <iostream>
#include <igl/readDMAT.h>
#include "PreProcessing/to_triplets.h"
#include "PreProcessing/setup_modes.h"
#include "PreProcessing/setup_rotation_cluster.h"
#include "PreProcessing/setup_skinning_handles.h"
using namespace Eigen;
using namespace std;
using json = nlohmann::json;
typedef Eigen::Triplet<double> Trip;
typedef Matrix<double, 12, 1> Vector12d;
// typedef PhysicalSystemFEM<double, LinearTet> FEMLinearTets;
// typedef World<double, std::tuple<FEMLinearTets *>, std::tuple<ForceSpringFEMParticle<double> *>, std::tuple<ConstraintFixedPoint<double> *> > MyWorld;
class Mesh
{
protected:
MatrixXd mV, discV;
MatrixXi mT, discT;
//Used in the sim
SparseMatrix<double> mMass, mGF, mGR, mGS, mGU, mP, mC, m_P, mPA, mWr, mWw;
SparseMatrix<double> mA, mFree, mConstrained, mN, mAN, mY;
VectorXi melemType, mr_elem_cluster_map, ms_handles_ind;
VectorXd mcontx, mx, mx0, mred_s, melemYoungs,
melemPoissons, mred_r, mred_x, mred_w, mPAx0, mFPAx;
MatrixXd mR, mG, msW, mUvecs, mJ;
VectorXd mmass_diag, mbones, m_relativeStiffness;
std::vector<int> mfix, mmov;
std::map<int, std::vector<int>> mr_cluster_elem_map;
std::map<int, std::vector<int>> ms_handle_elem_map;
std::vector<SparseMatrix<double>> mRotationBLOCK;
std::vector<VectorXi> mmuscles;
std::vector<MatrixXd> mjoints;
std::map<std::string, int> mmuscle_name_index_map;
std::map<std::string, int> mbone_name_index_map;
std::vector< std::pair<std::vector<std::string>, MatrixXd>> mjoint_bones_verts;
bool reduced;
//end
public:
Mesh(){}
Mesh(
MatrixXd& iV,
MatrixXi& iT,
MatrixXd& iUvecs,
std::vector<std::string>& ifix_bones,
std::vector<VectorXi>& ibone_tets,
std::vector<VectorXi>& imuscle_tets,
std::map<std::string, int>& ibone_name_index_map,
std::map<std::string, int>& imuscle_name_index_map,
std::vector< std::pair<std::vector<std::string>, MatrixXd>>& ijoint_bones_verts,
VectorXd& relativeStiffness,
json& j_input,
std::vector<int> fd_fix = {},
std::vector<int> imov = {})
{
mV = iV;
mT = iT;
mmov = imov;
mmuscles = imuscle_tets;
mmuscle_name_index_map = imuscle_name_index_map;
mbone_name_index_map = ibone_name_index_map;
mjoint_bones_verts = ijoint_bones_verts;
double youngs = j_input["youngs"];
double poissons = j_input["poissons"];
int num_modes = j_input["number_modes"];
int nsh = j_input["number_skinning_handles"];
int nrc = j_input["number_rot_clusters"];
reduced = j_input["reduced"];
cout<<"if it fails here, make sure indexing is within bounds"<<endl;
std::set<int> fix_verts_set;
for(int ii=0; ii<ifix_bones.size(); ii++){
cout<<ifix_bones[ii]<<endl;
int bone_ind = mbone_name_index_map[ifix_bones[ii]];
fix_verts_set.insert(mT.row(ibone_tets[bone_ind][10])[0]);
fix_verts_set.insert(mT.row(ibone_tets[bone_ind][10])[1]);
fix_verts_set.insert(mT.row(ibone_tets[bone_ind][10])[2]);
fix_verts_set.insert(mT.row(ibone_tets[bone_ind][10])[3]);
}
mfix.assign(fix_verts_set.begin(), fix_verts_set.end());
std::sort (mfix.begin(), mfix.end());
if(fd_fix.size() != 0){
mfix = fd_fix;
}
print("step 1");
mx0.resize(mV.cols()*mV.rows());
mx.resize(mV.cols()*mV.rows());
for(int i=0; i<mV.rows(); i++){
mx0[3*i+0] = mV(i,0); mx0[3*i+1] = mV(i,1); mx0[3*i+2] = mV(i,2);
}
mx.setZero();
mbones.resize(mT.rows());
mbones.setZero();
for(int b=0; b<ibone_tets.size(); b++){
for(int i=0; i<ibone_tets[b].size(); i++){
mbones[ibone_tets[b][i]] = 1;
}
}
for(int m=0; m<imuscle_tets.size(); m++){
for(int i=0; i<imuscle_tets[m].size(); i++){
mbones[imuscle_tets[m][i]] -=1;
}
}
print("step 2");
setP();
print("step 3");
setA();
print("step 4");
setC();
print("step 5");
setFreedConstrainedMatrices();
print("step 6");
setVertexWiseMassDiag();
print("step 7");
setHandleModesMatrix(ibone_tets, imuscle_tets, ifix_bones);
print("step 8");
setElemWiseYoungsPoissons(youngs, poissons, relativeStiffness);
m_relativeStiffness = relativeStiffness;
print("step 9");
setDiscontinuousMeshT();
print("step 10");
setup_rotation_cluster(nrc, reduced, mT, mV, ibone_tets, imuscle_tets, mred_x, mred_r, mred_w, mC, mA, mG, mx0, mRotationBLOCK, mr_cluster_elem_map, mr_elem_cluster_map);
print("step 11");
setup_skinning_handles(nsh, reduced, mT, mV, ibone_tets, imuscle_tets, mC, mA, mG, mx0, mred_s, msW, ms_handle_elem_map);
print("step 12");
MatrixXd temp1;
std::string outputfile = j_input["output"];
igl::readDMAT(outputfile+"/"+to_string((int)j_input["number_modes"])+"modes.dmat", temp1);
if(temp1.rows() == 0){
setup_modes(j_input, num_modes, reduced, mP, mA, mConstrained, mFree, mY, mV, mT, mmass_diag, temp1);
}
mG = mY*temp1;
print("step 13");
mUvecs.resize(mT.rows(), 3);
mUvecs.setZero();
for(int i=0; i<imuscle_tets.size(); i++){
for(int j=0; j<imuscle_tets[i].size(); j++){
mUvecs.row(imuscle_tets[i][j]) = iUvecs.row(imuscle_tets[i][j]);
}
}
if(mG.cols()==0){
mred_x.resize(3*mV.rows());
}else{
mred_x.resize(mG.cols());
}
mred_x.setZero();
mGR.resize(12*mT.rows(), 12*mT.rows());
mGU.resize(12*mT.rows(), 12*mT.rows());
mGS.resize(12*mT.rows(), 12*mT.rows());
print("step 13.5");
if(ijoint_bones_verts.size()>0){
SparseMatrix<double> jointsY;
setJointConstraintMatrix(jointsY, ibone_tets, imuscle_tets, ifix_bones, mjoint_bones_verts);
cout<<jointsY.rows()<<", "<<jointsY.cols()<<endl;
cout<<temp1.rows()<<", "<<temp1.cols()<<endl;
mJ = MatrixXd(jointsY)*temp1;
}
print("step 14");
setGlobalF(false, false, true);
print("step 15");
setN(ibone_tets);
print("step 16");
cout<<"mA: "<<mA.rows()<<", "<<mA.cols()<<endl;
cout<<"mP: "<<mP.rows()<<", "<<mP.cols()<<endl;
print("step 17");
mPAx0 = mP*mA*mx0;
print("step 18");
mFPAx.resize(mPAx0.size());
print("step 19");
setupWrWw();
}
void setElemWiseYoungsPoissons(double youngs, double poissons, VectorXd& relativeStiffness){
melemYoungs.resize(mT.rows());
melemPoissons.resize(mT.rows());
for(int i=0; i<mT.rows(); i++){
if(mbones[i]>0.5){
//if bone, give it higher youngs
melemYoungs[i] = youngs*10000;
}else{
melemYoungs[i] = youngs*relativeStiffness[i];
}
melemPoissons[i] = poissons;
}
}
void setDiscontinuousMeshT(){
discT.resize(mT.rows(), 4);
discV.resize(4*mT.rows(), 3);
for(int i=0; i<mT.rows(); i++){
discT(i, 0) = 4*i+0; discT(i, 1) = 4*i+1; discT(i, 2) = 4*i+2; discT(i, 3) = 4*i+3;
}
}
void setC(){
mC.resize(12*mT.rows(), 12*mT.rows());
vector<Trip> triplets;
triplets.reserve(3*16*mT.rows());
for(int i=0; i<mT.rows(); i++){
for(int j=0; j<3; j++){
triplets.push_back(Trip(12*i+0+j, 12*i+0+j, 1.0/4));
triplets.push_back(Trip(12*i+0+j, 12*i+3+j, 1.0/4));
triplets.push_back(Trip(12*i+0+j, 12*i+6+j, 1.0/4));
triplets.push_back(Trip(12*i+0+j, 12*i+9+j, 1.0/4));
triplets.push_back(Trip(12*i+3+j, 12*i+0+j, 1/4.0));
triplets.push_back(Trip(12*i+3+j, 12*i+3+j, 1/4.0));
triplets.push_back(Trip(12*i+3+j, 12*i+6+j, 1/4.0));
triplets.push_back(Trip(12*i+3+j, 12*i+9+j, 1/4.0));
triplets.push_back(Trip(12*i+6+j, 12*i+0+j, 1/4.0));
triplets.push_back(Trip(12*i+6+j, 12*i+3+j, 1/4.0));
triplets.push_back(Trip(12*i+6+j, 12*i+6+j, 1/4.0));
triplets.push_back(Trip(12*i+6+j, 12*i+9+j, 1/4.0));
triplets.push_back(Trip(12*i+9+j, 12*i+0+j, 1/4.0));
triplets.push_back(Trip(12*i+9+j, 12*i+3+j, 1/4.0));
triplets.push_back(Trip(12*i+9+j, 12*i+6+j, 1/4.0));
triplets.push_back(Trip(12*i+9+j, 12*i+9+j, 1/4.0));
}
}
mC.setFromTriplets(triplets.begin(), triplets.end());
}
void setHandleModesMatrix(std::vector<VectorXi>& ibones, std::vector<VectorXi>& imuscle, std::vector<std::string> fixedbones){
VectorXd vert_free_or_not = mFree*mFree.transpose()*VectorXd::Ones(3*mV.rows());// check if vert is fixed
//TODO fixed bones, used this vector (Y*Y'Ones(3*V.rows())) to create the mFree matrix and mConstrained matrix
//ibones should have fixed bones at the front, rest at the back
VectorXd bone_or_muscle = VectorXd::Zero(3*mV.rows()); //0 for muscle, 1,2 for each bone
bone_or_muscle.array() += -1;
for(int i=ibones.size() -1; i>=0; i--){ //go through in reverse so joints are part of the fixed bone
for(int j=0; j<ibones[i].size(); j++){
bone_or_muscle.segment<3>(3*mT.row(ibones[i][j])[0])[0] = i+1;
bone_or_muscle.segment<3>(3*mT.row(ibones[i][j])[0])[1] = i+1;
bone_or_muscle.segment<3>(3*mT.row(ibones[i][j])[0])[2] = i+1;
bone_or_muscle.segment<3>(3*mT.row(ibones[i][j])[1])[0] = i+1;
bone_or_muscle.segment<3>(3*mT.row(ibones[i][j])[1])[1] = i+1;
bone_or_muscle.segment<3>(3*mT.row(ibones[i][j])[1])[2] = i+1;
bone_or_muscle.segment<3>(3*mT.row(ibones[i][j])[2])[0] = i+1;
bone_or_muscle.segment<3>(3*mT.row(ibones[i][j])[2])[1] = i+1;
bone_or_muscle.segment<3>(3*mT.row(ibones[i][j])[2])[2] = i+1;
bone_or_muscle.segment<3>(3*mT.row(ibones[i][j])[3])[0] = i+1;
bone_or_muscle.segment<3>(3*mT.row(ibones[i][j])[3])[1] = i+1;
bone_or_muscle.segment<3>(3*mT.row(ibones[i][j])[3])[2] = i+1;
}
}
int muscleVerts = 0;
for(int i=0; i<bone_or_muscle.size()/3; i++){
if(bone_or_muscle[3*i]<-1e-8){
muscleVerts += 1;
}
}
std::vector<Trip> mY_trips = {};
//set top |bones|*12 dofs to be the bones
//set the rest to be muscles, indexed correctly
int muscle_index = 0;
for(int i=0; i<bone_or_muscle.size()/3; i++){
if(bone_or_muscle[3*i]<-1e-8){
//its a muscle, figure out which one, and index it correctly
mY_trips.push_back(Trip(3*i+0, 12*(ibones.size()-fixedbones.size())+3*muscle_index+0, 1.0));
mY_trips.push_back(Trip(3*i+1, 12*(ibones.size()-fixedbones.size())+3*muscle_index+1, 1.0));
mY_trips.push_back(Trip(3*i+2, 12*(ibones.size()-fixedbones.size())+3*muscle_index+2, 1.0));
muscle_index +=1;
}
}
for(int i=0; i<bone_or_muscle.size()/3; i++){
if(bone_or_muscle[3*i]>fixedbones.size()){
mY_trips.push_back(Trip(3*i+0, (int)(12*(bone_or_muscle[3*i]-1 - fixedbones.size()))+0, mV.row(i)[0]));
mY_trips.push_back(Trip(3*i+1, (int)(12*(bone_or_muscle[3*i]-1 - fixedbones.size()))+1, mV.row(i)[0]));
mY_trips.push_back(Trip(3*i+2, (int)(12*(bone_or_muscle[3*i]-1 - fixedbones.size()))+2, mV.row(i)[0]));
mY_trips.push_back(Trip(3*i+0, (int)(12*(bone_or_muscle[3*i]-1 - fixedbones.size()))+3, mV.row(i)[1]));
mY_trips.push_back(Trip(3*i+1, (int)(12*(bone_or_muscle[3*i]-1 - fixedbones.size()))+4, mV.row(i)[1]));
mY_trips.push_back(Trip(3*i+2, (int)(12*(bone_or_muscle[3*i]-1 - fixedbones.size()))+5, mV.row(i)[1]));
mY_trips.push_back(Trip(3*i+0, (int)(12*(bone_or_muscle[3*i]-1 - fixedbones.size()))+6, mV.row(i)[2]));
mY_trips.push_back(Trip(3*i+1, (int)(12*(bone_or_muscle[3*i]-1 - fixedbones.size()))+7, mV.row(i)[2]));
mY_trips.push_back(Trip(3*i+2, (int)(12*(bone_or_muscle[3*i]-1 - fixedbones.size()))+8, mV.row(i)[2]));
mY_trips.push_back(Trip(3*i+0, (int)(12*(bone_or_muscle[3*i]-1 - fixedbones.size()))+9, 1.0));
mY_trips.push_back(Trip(3*i+1, (int)(12*(bone_or_muscle[3*i]-1 - fixedbones.size()))+10, 1.0));
mY_trips.push_back(Trip(3*i+2, (int)(12*(bone_or_muscle[3*i]-1 - fixedbones.size()))+11, 1.0));
}
}
mY.resize(3*mV.rows(), 3*muscleVerts + 12*(ibones.size() - fixedbones.size()));
mY.setFromTriplets(mY_trips.begin(), mY_trips.end());
}
void setJointConstraintMatrix(SparseMatrix<double>& jointsY, std::vector<VectorXi>& ibones, std::vector<VectorXi>& imuscle, std::vector<std::string> fixedbones, std::vector< std::pair<std::vector<std::string>, MatrixXd>>& joints_bones_verts){
int hingejoints = 0;
int socketjoints = 0;
std::vector<Trip> joint_trips;
for(int i=0; i<joints_bones_verts.size(); i++){
MatrixXd joint = joints_bones_verts[i].second;
int bone1ind = mbone_name_index_map[joints_bones_verts[i].first[0]];
int bone2ind = mbone_name_index_map[joints_bones_verts[i].first[1]];
cout<<"bones: "<<bone1ind<<", "<<bone2ind<<", "<<joint.rows()<<", "<<endl;
if(joint.rows()>1){
hingejoints +=1;
RowVector3d p1 = joint.row(0);
RowVector3d p2 = joint.row(1);
if(bone1ind>=fixedbones.size()){
joint_trips.push_back(Trip(6*i+0, (int)12*(bone1ind-fixedbones.size())+0, p1[0]));
joint_trips.push_back(Trip(6*i+1, (int)12*(bone1ind-fixedbones.size())+1, p1[0]));
joint_trips.push_back(Trip(6*i+2, (int)12*(bone1ind-fixedbones.size())+2, p1[0]));
joint_trips.push_back(Trip(6*i+0, (int)12*(bone1ind-fixedbones.size())+3, p1[1]));
joint_trips.push_back(Trip(6*i+1, (int)12*(bone1ind-fixedbones.size())+4, p1[1]));
joint_trips.push_back(Trip(6*i+2, (int)12*(bone1ind-fixedbones.size())+5, p1[1]));
joint_trips.push_back(Trip(6*i+0, (int)12*(bone1ind-fixedbones.size())+6, p1[2]));
joint_trips.push_back(Trip(6*i+1, (int)12*(bone1ind-fixedbones.size())+7, p1[2]));
joint_trips.push_back(Trip(6*i+2, (int)12*(bone1ind-fixedbones.size())+8, p1[2]));
joint_trips.push_back(Trip(6*i+0, (int)12*(bone1ind-fixedbones.size())+9, 1));
joint_trips.push_back(Trip(6*i+1, (int)12*(bone1ind-fixedbones.size())+10, 1));
joint_trips.push_back(Trip(6*i+2, (int)12*(bone1ind-fixedbones.size())+11, 1));
joint_trips.push_back(Trip(6*i+3, (int)12*(bone1ind-fixedbones.size())+0, p2[0]));
joint_trips.push_back(Trip(6*i+4, (int)12*(bone1ind-fixedbones.size())+1, p2[0]));
joint_trips.push_back(Trip(6*i+5, (int)12*(bone1ind-fixedbones.size())+2, p2[0]));
joint_trips.push_back(Trip(6*i+3, (int)12*(bone1ind-fixedbones.size())+3, p2[1]));
joint_trips.push_back(Trip(6*i+4, (int)12*(bone1ind-fixedbones.size())+4, p2[1]));
joint_trips.push_back(Trip(6*i+5, (int)12*(bone1ind-fixedbones.size())+5, p2[1]));
joint_trips.push_back(Trip(6*i+3, (int)12*(bone1ind-fixedbones.size())+6, p2[2]));
joint_trips.push_back(Trip(6*i+4, (int)12*(bone1ind-fixedbones.size())+7, p2[2]));
joint_trips.push_back(Trip(6*i+5, (int)12*(bone1ind-fixedbones.size())+8, p2[2]));
joint_trips.push_back(Trip(6*i+3, (int)12*(bone1ind-fixedbones.size())+9, 1));
joint_trips.push_back(Trip(6*i+4, (int)12*(bone1ind-fixedbones.size())+10, 1));
joint_trips.push_back(Trip(6*i+5, (int)12*(bone1ind-fixedbones.size())+11, 1));
}
if(bone2ind>=fixedbones.size()){
joint_trips.push_back(Trip(6*i+0, (int)12*(bone2ind - fixedbones.size())+0, -p1[0]));
joint_trips.push_back(Trip(6*i+1, (int)12*(bone2ind - fixedbones.size())+1, -p1[0]));
joint_trips.push_back(Trip(6*i+2, (int)12*(bone2ind - fixedbones.size())+2, -p1[0]));
joint_trips.push_back(Trip(6*i+0, (int)12*(bone2ind - fixedbones.size())+3, -p1[1]));
joint_trips.push_back(Trip(6*i+1, (int)12*(bone2ind - fixedbones.size())+4, -p1[1]));
joint_trips.push_back(Trip(6*i+2, (int)12*(bone2ind - fixedbones.size())+5, -p1[1]));
joint_trips.push_back(Trip(6*i+0, (int)12*(bone2ind - fixedbones.size())+6, -p1[2]));
joint_trips.push_back(Trip(6*i+1, (int)12*(bone2ind - fixedbones.size())+7, -p1[2]));
joint_trips.push_back(Trip(6*i+2, (int)12*(bone2ind - fixedbones.size())+8, -p1[2]));
joint_trips.push_back(Trip(6*i+0, (int)12*(bone2ind - fixedbones.size())+9, -1));
joint_trips.push_back(Trip(6*i+1, (int)12*(bone2ind - fixedbones.size())+10,-1));
joint_trips.push_back(Trip(6*i+2, (int)12*(bone2ind - fixedbones.size())+11,-1));
joint_trips.push_back(Trip(6*i+3, (int)12*(bone2ind - fixedbones.size())+0, -p2[0]));
joint_trips.push_back(Trip(6*i+4, (int)12*(bone2ind - fixedbones.size())+1, -p2[0]));
joint_trips.push_back(Trip(6*i+5, (int)12*(bone2ind - fixedbones.size())+2, -p2[0]));
joint_trips.push_back(Trip(6*i+3, (int)12*(bone2ind - fixedbones.size())+3, -p2[1]));
joint_trips.push_back(Trip(6*i+4, (int)12*(bone2ind - fixedbones.size())+4, -p2[1]));
joint_trips.push_back(Trip(6*i+5, (int)12*(bone2ind - fixedbones.size())+5, -p2[1]));
joint_trips.push_back(Trip(6*i+3, (int)12*(bone2ind - fixedbones.size())+6, -p2[2]));
joint_trips.push_back(Trip(6*i+4, (int)12*(bone2ind - fixedbones.size())+7, -p2[2]));
joint_trips.push_back(Trip(6*i+5, (int)12*(bone2ind - fixedbones.size())+8, -p2[2]));
joint_trips.push_back(Trip(6*i+3, (int)12*(bone2ind - fixedbones.size())+9, -1));
joint_trips.push_back(Trip(6*i+4, (int)12*(bone2ind - fixedbones.size())+10,-1));
joint_trips.push_back(Trip(6*i+5, (int)12*(bone2ind - fixedbones.size())+11,-1));
}
}else{
socketjoints +=1;
RowVector3d p1 = joint.row(0);
if(bone1ind>=fixedbones.size()){
joint_trips.push_back(Trip(3*i+0, (int)12*(bone1ind - fixedbones.size())+0, p1[0]));
joint_trips.push_back(Trip(3*i+1, (int)12*(bone1ind - fixedbones.size())+1, p1[0]));
joint_trips.push_back(Trip(3*i+2, (int)12*(bone1ind - fixedbones.size())+2, p1[0]));
joint_trips.push_back(Trip(3*i+0, (int)12*(bone1ind - fixedbones.size())+3, p1[1]));
joint_trips.push_back(Trip(3*i+1, (int)12*(bone1ind - fixedbones.size())+4, p1[1]));
joint_trips.push_back(Trip(3*i+2, (int)12*(bone1ind - fixedbones.size())+5, p1[1]));
joint_trips.push_back(Trip(3*i+0, (int)12*(bone1ind - fixedbones.size())+6, p1[2]));
joint_trips.push_back(Trip(3*i+1, (int)12*(bone1ind - fixedbones.size())+7, p1[2]));
joint_trips.push_back(Trip(3*i+2, (int)12*(bone1ind - fixedbones.size())+8, p1[2]));
joint_trips.push_back(Trip(3*i+0, (int)12*(bone1ind - fixedbones.size())+9, 1));
joint_trips.push_back(Trip(3*i+1, (int)12*(bone1ind - fixedbones.size())+10,1));
joint_trips.push_back(Trip(3*i+2, (int)12*(bone1ind - fixedbones.size())+11,1));
}
if(bone2ind>=fixedbones.size()){
joint_trips.push_back(Trip(3*i+0, (int)12*(bone2ind - fixedbones.size())+0, -p1[0]));
joint_trips.push_back(Trip(3*i+1, (int)12*(bone2ind - fixedbones.size())+1, -p1[0]));
joint_trips.push_back(Trip(3*i+2, (int)12*(bone2ind - fixedbones.size())+2, -p1[0]));
joint_trips.push_back(Trip(3*i+0, (int)12*(bone2ind - fixedbones.size())+3, -p1[1]));
joint_trips.push_back(Trip(3*i+1, (int)12*(bone2ind - fixedbones.size())+4, -p1[1]));
joint_trips.push_back(Trip(3*i+2, (int)12*(bone2ind - fixedbones.size())+5, -p1[1]));
joint_trips.push_back(Trip(3*i+0, (int)12*(bone2ind - fixedbones.size())+6, -p1[2]));
joint_trips.push_back(Trip(3*i+1, (int)12*(bone2ind - fixedbones.size())+7, -p1[2]));
joint_trips.push_back(Trip(3*i+2, (int)12*(bone2ind - fixedbones.size())+8, -p1[2]));
joint_trips.push_back(Trip(3*i+0, (int)12*(bone2ind - fixedbones.size())+9, -1));
joint_trips.push_back(Trip(3*i+1, (int)12*(bone2ind - fixedbones.size())+10,-1));
joint_trips.push_back(Trip(3*i+2, (int)12*(bone2ind - fixedbones.size())+11,-1));
}
}
}
jointsY.resize(6*hingejoints + 3*socketjoints, mY.cols());
jointsY.setFromTriplets(joint_trips.begin(), joint_trips.end());
}
void setN(std::vector<VectorXi> bones){
//TODO make this work for reduced skinning
int nsh_bones = bones.size();
mN.resize(mred_s.size(), mred_s.size() - 6*nsh_bones); //#nsh x nsh for muscles (project out bones handles)
mN.setZero();
int j=0;
for(int i=0; i<mN.rows()/6; i++){
if(i<bones.size()){
continue;
}
mN.coeffRef(6*i+0, 6*j+0) = 1;
mN.coeffRef(6*i+1, 6*j+1) = 1;
mN.coeffRef(6*i+2, 6*j+2) = 1;
mN.coeffRef(6*i+3, 6*j+3) = 1;
mN.coeffRef(6*i+4, 6*j+4) = 1;
mN.coeffRef(6*i+5, 6*j+5) = 1;
j++;
}
mAN.resize(mred_s.size(), 6*nsh_bones); //#nsh x nsh for muscles (project out muscle handles)
mAN.setZero();
j=0;
for(int i=0; i<mAN.rows()/6; i++){
if(i>=bones.size()){
continue;
}
mAN.coeffRef(6*i+0, 6*j+0) = 1;
mAN.coeffRef(6*i+1, 6*j+1) = 1;
mAN.coeffRef(6*i+2, 6*j+2) = 1;
mAN.coeffRef(6*i+3, 6*j+3) = 1;
mAN.coeffRef(6*i+4, 6*j+4) = 1;
mAN.coeffRef(6*i+5, 6*j+5) = 1;
j++;
}
}
void setP(){
mP.resize(12*mT.rows(), 12*mT.rows());
Matrix4d p;
p<< 3, -1, -1, -1,
-1, 3, -1, -1,
-1, -1, 3, -1,
-1, -1, -1, 3;
vector<Trip> triplets;
triplets.reserve(3*16*mT.rows());
for(int i=0; i<mT.rows(); i++){
double weight = 1;
if(mbones[i]==1){
weight = 1;
}
for(int j=0; j<3; j++){
triplets.push_back(Trip(12*i+0+j, 12*i+0+j, weight*p(0,0)/4));
triplets.push_back(Trip(12*i+0+j, 12*i+3+j, weight*p(0,1)/4));
triplets.push_back(Trip(12*i+0+j, 12*i+6+j, weight*p(0,2)/4));
triplets.push_back(Trip(12*i+0+j, 12*i+9+j, weight*p(0,3)/4));
triplets.push_back(Trip(12*i+3+j, 12*i+0+j, weight*p(1,0)/4));
triplets.push_back(Trip(12*i+3+j, 12*i+3+j, weight*p(1,1)/4));
triplets.push_back(Trip(12*i+3+j, 12*i+6+j, weight*p(1,2)/4));
triplets.push_back(Trip(12*i+3+j, 12*i+9+j, weight*p(1,3)/4));
triplets.push_back(Trip(12*i+6+j, 12*i+0+j, weight*p(2,0)/4));
triplets.push_back(Trip(12*i+6+j, 12*i+3+j, weight*p(2,1)/4));
triplets.push_back(Trip(12*i+6+j, 12*i+6+j, weight*p(2,2)/4));
triplets.push_back(Trip(12*i+6+j, 12*i+9+j, weight*p(2,3)/4));
triplets.push_back(Trip(12*i+9+j, 12*i+0+j, weight*p(3,0)/4));
triplets.push_back(Trip(12*i+9+j, 12*i+3+j, weight*p(3,1)/4));
triplets.push_back(Trip(12*i+9+j, 12*i+6+j, weight*p(3,2)/4));
triplets.push_back(Trip(12*i+9+j, 12*i+9+j, weight*p(3,3)/4));
}
}
mP.setFromTriplets(triplets.begin(), triplets.end());
m_P.resize(12*mT.rows(), 12*mT.rows());
vector<Trip> triplets_;
triplets_.reserve(3*16*mT.rows());
for(int i=0; i<mT.rows(); i++){
for(int j=0; j<3; j++){
triplets_.push_back(Trip(12*i+0+j, 12*i+0+j, p(0,0)/4));
triplets_.push_back(Trip(12*i+0+j, 12*i+3+j, p(0,1)/4));
triplets_.push_back(Trip(12*i+0+j, 12*i+6+j, p(0,2)/4));
triplets_.push_back(Trip(12*i+0+j, 12*i+9+j, p(0,3)/4));
triplets_.push_back(Trip(12*i+3+j, 12*i+0+j, p(1,0)/4));
triplets_.push_back(Trip(12*i+3+j, 12*i+3+j, p(1,1)/4));
triplets_.push_back(Trip(12*i+3+j, 12*i+6+j, p(1,2)/4));
triplets_.push_back(Trip(12*i+3+j, 12*i+9+j, p(1,3)/4));
triplets_.push_back(Trip(12*i+6+j, 12*i+0+j, p(2,0)/4));
triplets_.push_back(Trip(12*i+6+j, 12*i+3+j, p(2,1)/4));
triplets_.push_back(Trip(12*i+6+j, 12*i+6+j, p(2,2)/4));
triplets_.push_back(Trip(12*i+6+j, 12*i+9+j, p(2,3)/4));
triplets_.push_back(Trip(12*i+9+j, 12*i+0+j, p(3,0)/4));
triplets_.push_back(Trip(12*i+9+j, 12*i+3+j, p(3,1)/4));
triplets_.push_back(Trip(12*i+9+j, 12*i+6+j, p(3,2)/4));
triplets_.push_back(Trip(12*i+9+j, 12*i+9+j, p(3,3)/4));
}
}
m_P.setFromTriplets(triplets_.begin(), triplets_.end());
}
void setA(){
mA.resize(12*mT.rows(), 3*mV.rows());
vector<Trip> triplets;
triplets.reserve(12*mT.rows());
for(int i=0; i<mT.rows(); i++){
VectorXi inds = mT.row(i);
for(int j=0; j<4; j++){
int v = inds[j];
triplets.push_back(Trip(12*i+3*j+0, 3*v+0, 1));
triplets.push_back(Trip(12*i+3*j+1, 3*v+1, 1));
triplets.push_back(Trip(12*i+3*j+2, 3*v+2, 1));
}
}
mA.setFromTriplets(triplets.begin(), triplets.end());
}
void setVertexWiseMassDiag(){
mmass_diag.resize(3*mV.rows());
mmass_diag.setZero();
for(int i=0; i<mT.rows(); i++){
double undef_vol = get_volume(
mV.row(mT.row(i)[0]),
mV.row(mT.row(i)[1]),
mV.row(mT.row(i)[2]),
mV.row(mT.row(i)[3]));
mmass_diag(3*mT.row(i)[0]+0) += undef_vol/4.0;
mmass_diag(3*mT.row(i)[0]+1) += undef_vol/4.0;
mmass_diag(3*mT.row(i)[0]+2) += undef_vol/4.0;
mmass_diag(3*mT.row(i)[1]+0) += undef_vol/4.0;
mmass_diag(3*mT.row(i)[1]+1) += undef_vol/4.0;
mmass_diag(3*mT.row(i)[1]+2) += undef_vol/4.0;
mmass_diag(3*mT.row(i)[2]+0) += undef_vol/4.0;
mmass_diag(3*mT.row(i)[2]+1) += undef_vol/4.0;
mmass_diag(3*mT.row(i)[2]+2) += undef_vol/4.0;
mmass_diag(3*mT.row(i)[3]+0) += undef_vol/4.0;
mmass_diag(3*mT.row(i)[3]+1) += undef_vol/4.0;
mmass_diag(3*mT.row(i)[3]+2) += undef_vol/4.0;
}
}
void setFreedConstrainedMatrices(){
if(mmov.size()>0){
mfix.insert(mfix.end(), mmov.begin(), mmov.end());
}
std::sort (mfix.begin(), mfix.end());
vector<int> notfix;
mFree.resize(3*mV.rows(), 3*mV.rows() - 3*mfix.size());
mFree.setZero();
int i = 0;
int f = 0;
for(int j =0; j<mFree.cols()/3; j++){
if (i==mfix[f]){
f++;
i++;
j--;
continue;
}
notfix.push_back(i);
mFree.coeffRef(3*i+0, 3*j+0) = 1;
mFree.coeffRef(3*i+1, 3*j+1) = 1;
mFree.coeffRef(3*i+2, 3*j+2) = 1;
i++;
}
mConstrained.resize(3*mV.rows(), 3*mV.rows() - 3*notfix.size());
mConstrained.setZero();
i = 0;
f = 0;
for(int j =0; j<mConstrained.cols()/3; j++){
if (i==notfix[f]){
f++;
i++;
j--;
continue;
}
mConstrained.coeffRef(3*i+0, 3*j+0) = 1;
mConstrained.coeffRef(3*i+1, 3*j+1) = 1;
mConstrained.coeffRef(3*i+2, 3*j+2) = 1;
i++;
}
}
void setupWrWw(){
std::vector<Trip> wr_trips;
std::vector<Trip> ww_trips;
std::map<int, std::vector<int>>& c_e_map = mr_cluster_elem_map;
for (int i=0; i<mred_r.size()/9; i++){
std::vector<int> cluster_elem = c_e_map[i];
for(int e=0; e<cluster_elem.size(); e++){
wr_trips.push_back(Trip(9*cluster_elem[e]+0, 9*i+0, 1));
wr_trips.push_back(Trip(9*cluster_elem[e]+1, 9*i+1, 1));
wr_trips.push_back(Trip(9*cluster_elem[e]+2, 9*i+2, 1));
wr_trips.push_back(Trip(9*cluster_elem[e]+3, 9*i+3, 1));
wr_trips.push_back(Trip(9*cluster_elem[e]+4, 9*i+4, 1));
wr_trips.push_back(Trip(9*cluster_elem[e]+5, 9*i+5, 1));
wr_trips.push_back(Trip(9*cluster_elem[e]+6, 9*i+6, 1));
wr_trips.push_back(Trip(9*cluster_elem[e]+7, 9*i+7, 1));
wr_trips.push_back(Trip(9*cluster_elem[e]+8, 9*i+8, 1));
ww_trips.push_back(Trip(3*cluster_elem[e]+0, 3*i+0, 1));
ww_trips.push_back(Trip(3*cluster_elem[e]+1, 3*i+1, 1));
ww_trips.push_back(Trip(3*cluster_elem[e]+2, 3*i+2, 1));
}
}
mWr.resize( 9*mT.rows(), mred_r.size());
mWr.setFromTriplets(wr_trips.begin(), wr_trips.end());
mWw.resize( 3*mT.rows(), mred_w.size());
mWw.setFromTriplets(ww_trips.begin(), ww_trips.end());
}
void constTimeFPAx0(VectorXd& iFPAx0){
iFPAx0.setZero();
if(reduced==true){
//TODO make this more efficient
VectorXd ms;
if(6*mT.rows()==mred_s.size()){
ms = mred_s;
}else{
ms = msW*mred_s;
}
VectorXd mr;
if(9*mT.rows()==mred_r.size()){
mr = mred_r;
}else{
mr = mWr*mred_r;
}
for(int i=0; i<mT.rows(); i++){
Matrix3d r = Map<Matrix3d>(mred_r.segment<9>(9*mr_elem_cluster_map[i]).data()).transpose();
Matrix3d s;
s<< ms[6*i + 0], ms[6*i + 3], ms[6*i + 4],
ms[6*i + 3], ms[6*i + 1], ms[6*i + 5],
ms[6*i + 4], ms[6*i + 5], ms[6*i + 2];
Matrix3d rs = r*s;
iFPAx0.segment<3>(12*i+0) = rs*mPAx0.segment<3>(12*i+0);
iFPAx0.segment<3>(12*i+3) = rs*mPAx0.segment<3>(12*i+3);
iFPAx0.segment<3>(12*i+6) = rs*mPAx0.segment<3>(12*i+6);
iFPAx0.segment<3>(12*i+9) = rs*mPAx0.segment<3>(12*i+9);
}
}else{
for(int i=0; i<mT.rows(); i++){
Matrix3d r = Map<Matrix3d>(mred_r.segment<9>(9*mr_elem_cluster_map[i]).data()).transpose();
Matrix3d s;
s<< mred_s[6*i + 0], mred_s[6*i + 3], mred_s[6*i + 4],
mred_s[6*i + 3], mred_s[6*i + 1], mred_s[6*i + 5],
mred_s[6*i + 4], mred_s[6*i + 5], mred_s[6*i + 2];
Matrix3d rs = r*s;
iFPAx0.segment<3>(12*i+0) = rs*mPAx0.segment<3>(12*i+0);
iFPAx0.segment<3>(12*i+3) = rs*mPAx0.segment<3>(12*i+3);
iFPAx0.segment<3>(12*i+6) = rs*mPAx0.segment<3>(12*i+6);
iFPAx0.segment<3>(12*i+9) = rs*mPAx0.segment<3>(12*i+9);
}
}
}
void setGlobalF(bool updateR, bool updateS, bool updateU){
if(updateU){
mGU.setIdentity();
Vector3d a = Vector3d::UnitX();
for(int t = 0; t<mT.rows(); t++){
//TODO: update to be parametrized by input mU
Vector3d b = mUvecs.row(t);
if(b.norm()==0){
b = Vector3d::UnitY();
mUvecs.row(t) = b;
}
}
}
// if(updateR){
// mGR.setZero();
// //iterate through rotation clusters
// Matrix3d ri = Matrix3d::Zero();
// Matrix3d r;
// vector<Trip> gr_trips;
// gr_trips.reserve(9*4*mT.rows());
// for (int t=0; t<mred_r.size()/9; t++){
// //dont use the RotBLOCK matrix like I did in python.
// //Insert manually into elements within
// //the rotation cluster
// ri(0,0) = mred_r[9*t+0];
// ri(0,1) = mred_r[9*t+1];
// ri(0,2) = mred_r[9*t+2];
// ri(1,0) = mred_r[9*t+3];
// ri(1,1) = mred_r[9*t+4];
// ri(1,2) = mred_r[9*t+5];
// ri(2,0) = mred_r[9*t+6];
// ri(2,1) = mred_r[9*t+7];
// ri(2,2) = mred_r[9*t+8];
// // % Rodrigues formula %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Vector3d w;
// w<<mred_w(3*t+0),mred_w(3*t+1),mred_w(3*t+2);
// double wlen = w.norm();
// if (wlen>1e-9){
// double wX = w(0);
// double wY = w(1);
// double wZ = w(2);
// Matrix3d cross;
// cross<<0, -wZ, wY,
// wZ, 0, -wX,
// -wY, wX, 0;
// Matrix3d Rot = cross.exp();
// r = ri*Rot;
// }else{
// r = ri;
// }
// // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// for(int c=0; c<mr_cluster_elem_map[t].size(); c++){
// for(int j=0; j<4; j++){
// gr_trips.push_back(Trip(3*j+12*mr_cluster_elem_map[t][c] + 0, 3*j+12*mr_cluster_elem_map[t][c] + 0, r(0 ,0)));
// gr_trips.push_back(Trip(3*j+12*mr_cluster_elem_map[t][c] + 0, 3*j+12*mr_cluster_elem_map[t][c] + 1, r(0 ,1)));
// gr_trips.push_back(Trip(3*j+12*mr_cluster_elem_map[t][c] + 0, 3*j+12*mr_cluster_elem_map[t][c] + 2, r(0 ,2)));
// gr_trips.push_back(Trip(3*j+12*mr_cluster_elem_map[t][c] + 1, 3*j+12*mr_cluster_elem_map[t][c] + 0, r(1 ,0)));
// gr_trips.push_back(Trip(3*j+12*mr_cluster_elem_map[t][c] + 1, 3*j+12*mr_cluster_elem_map[t][c] + 1, r(1 ,1)));
// gr_trips.push_back(Trip(3*j+12*mr_cluster_elem_map[t][c] + 1, 3*j+12*mr_cluster_elem_map[t][c] + 2, r(1 ,2)));
// gr_trips.push_back(Trip(3*j+12*mr_cluster_elem_map[t][c] + 2, 3*j+12*mr_cluster_elem_map[t][c] + 0, r(2 ,0)));
// gr_trips.push_back(Trip(3*j+12*mr_cluster_elem_map[t][c] + 2, 3*j+12*mr_cluster_elem_map[t][c] + 1, r(2 ,1)));
// gr_trips.push_back(Trip(3*j+12*mr_cluster_elem_map[t][c] + 2, 3*j+12*mr_cluster_elem_map[t][c] + 2, r(2 ,2)));
// }
// }
// }
// mGR.setFromTriplets(gr_trips.begin(), gr_trips.end());
// }
// if(updateS){
// mGS.setZero();
// vector<Trip> gs_trips;
// gs_trips.reserve(9*4*mT.rows());
// VectorXd ms;
// if(6*mT.rows()==mred_s.size()){
// ms = mred_s;
// }else{
// ms = msW*mred_s;
// }
// //iterate through skinning handles
// for(int t = 0; t<mT.rows(); t++){
// for(int j = 0; j<4; j++){
// gs_trips.push_back(Trip(3*j+12*t + 0, 3*j+12*t + 0, ms[6*t + 0]));
// gs_trips.push_back(Trip(3*j+12*t + 0, 3*j+12*t + 1, ms[6*t + 3]));
// gs_trips.push_back(Trip(3*j+12*t + 0, 3*j+12*t + 2, ms[6*t + 4]));
// gs_trips.push_back(Trip(3*j+12*t + 1, 3*j+12*t + 0, ms[6*t + 3]));
// gs_trips.push_back(Trip(3*j+12*t + 1, 3*j+12*t + 1, ms[6*t + 1]));
// gs_trips.push_back(Trip(3*j+12*t + 1, 3*j+12*t + 2, ms[6*t + 5]));
// gs_trips.push_back(Trip(3*j+12*t + 2, 3*j+12*t + 0, ms[6*t + 4]));
// gs_trips.push_back(Trip(3*j+12*t + 2, 3*j+12*t + 1, ms[6*t + 5]));
// gs_trips.push_back(Trip(3*j+12*t + 2, 3*j+12*t + 2, ms[6*t + 2]));
// }
// }
// mGS.setFromTriplets(gs_trips.begin(), gs_trips.end());
// }
// mGF = mGR*mGU*mGS*mGU.transpose();
}
double get_volume(Vector3d p1, Vector3d p2, Vector3d p3, Vector3d p4){
Matrix3d Dm;
Dm.col(0) = p1 - p4;
Dm.col(1) = p2 - p4;
Dm.col(2) = p3 - p4;
double density = 1000;
double m_undeformedVol = (1.0/6)*fabs(Dm.determinant());
return m_undeformedVol;
}
MatrixXd& V(){ return mV; }
MatrixXi& T(){ return mT; }
// SparseMatrix<double>& GR(){ return mGR; }
// SparseMatrix<double>& GS(){ return mGS; }
// SparseMatrix<double>& GU(){ return mGU; }
// SparseMatrix<double>& GF(){ return mGF; }
SparseMatrix<double>& P(){ return mP; }
SparseMatrix<double>& A(){ return mA; }
SparseMatrix<double>& N(){ return mN; }
SparseMatrix<double>& AN(){ return mAN; }
SparseMatrix<double>& Y(){ return mY; }
MatrixXd& JointY(){ return mJ;}
MatrixXd& G(){ return mG; }
MatrixXd& Uvecs(){ return mUvecs; }
SparseMatrix<double>& B(){ return mFree; }
SparseMatrix<double>& AB(){ return mConstrained; }
VectorXd& red_r(){ return mred_r; }
VectorXd& red_w(){ return mred_w; }
VectorXd& eYoungs(){ return melemYoungs; }
VectorXd& ePoissons(){ return melemPoissons; }
VectorXd& x0(){ return mx0; }
VectorXd& red_s(){return mred_s; }
std::vector<int>& fixed_verts(){ return mfix; }
std::map<int, std::vector<int>>& r_cluster_elem_map(){ return mr_cluster_elem_map; }
std::map<int, std::vector<int>>& s_handle_elem_map(){ return ms_handle_elem_map; }
VectorXi& r_elem_cluster_map(){ return mr_elem_cluster_map; }
VectorXd& relativeStiffness() { return m_relativeStiffness;}
VectorXd& bones(){ return mbones; }
std::vector<VectorXi> muscle_vecs() { return mmuscles; }
// std::vector<MatrixXd> joints(){ return mjoints; }
MatrixXd& sW(){
if(mred_s.size()== 6*mT.rows() && reduced==false){
print("skinning is unreduced, don't call this function");
exit(0);
}
return msW;
}
std::vector<SparseMatrix<double>>& RotBLOCK(){ return mRotationBLOCK; }
VectorXd& dx(){ return mx;}
VectorXd& red_x(){ return mred_x; }
void red_x(VectorXd& ix){
for(int i=0; i<ix.size(); i++){
mred_x[i] = ix[i];
}
return;
}
void dx(VectorXd& ix){
mx = ix;
return;
}
MatrixXd continuousV(){
VectorXd x;
if(3*mV.rows()==mred_x.size()){
x = mred_x + mx0;
}else{
x = mG*mred_x + mx0;
}
Eigen::Map<Eigen::MatrixXd> newV(x.data(), mV.cols(), mV.rows());
return newV.transpose();
}
MatrixXi& discontinuousT(){ return discT; }
MatrixXd& discontinuousV(){
VectorXd x;
VectorXd ms;
if(3*mV.rows()==mred_x.size()){
x = mred_x+mx0;
}else{
print("reduced G");
x = mG*mred_x + mx0;
}
if(6*mT.rows() == mred_s.size()){
ms = mred_s;
}else{
ms = msW*mred_s;
}
VectorXd PAx = m_P*mA*x;
mFPAx.setZero();
for(int i=0; i<mT.rows(); i++){
Matrix3d r = Map<Matrix3d>(mred_r.segment<9>(9*mr_elem_cluster_map[i]).data()).transpose();
Matrix3d s;
s<< ms[6*i + 0], ms[6*i + 3], ms[6*i + 4],
ms[6*i + 3], ms[6*i + 1], ms[6*i + 5],
ms[6*i + 4], ms[6*i + 5], ms[6*i + 2];
Matrix3d rs = r*s;
mFPAx.segment<3>(12*i+0) = rs*PAx.segment<3>(12*i+0);
mFPAx.segment<3>(12*i+3) = rs*PAx.segment<3>(12*i+3);
mFPAx.segment<3>(12*i+6) = rs*PAx.segment<3>(12*i+6);
mFPAx.segment<3>(12*i+9) = rs*PAx.segment<3>(12*i+9);
}
VectorXd CAx = mC*mA*x;
VectorXd newx = mFPAx + CAx;
for(int t =0; t<mT.rows(); t++){
discV(4*t+0, 0) = newx[12*t+0];
discV(4*t+0, 1) = newx[12*t+1];
discV(4*t+0, 2) = newx[12*t+2];
discV(4*t+1, 0) = newx[12*t+3];
discV(4*t+1, 1) = newx[12*t+4];
discV(4*t+1, 2) = newx[12*t+5];
discV(4*t+2, 0) = newx[12*t+6];
discV(4*t+2, 1) = newx[12*t+7];
discV(4*t+2, 2) = newx[12*t+8];
discV(4*t+3, 0) = newx[12*t+9];
discV(4*t+3, 1) = newx[12*t+10];
discV(4*t+3, 2) = newx[12*t+11];
}
return discV;
}
SparseMatrix<double>& M(){ return mMass; }
template<class T>
void print(T a){ std::cout<<a<<std::endl; }
};
#endif | 42.972084 | 246 | 0.508666 | [
"mesh",
"vector"
] |
1618860557c9933e66fbb06afec9125ba4c6f156 | 2,484 | h | C | src/kdtree.h | konstatoivanen/SoftwareRayTracer | 0b007b6d88ac7652a503ae8add9c4a8d1f9adfc3 | [
"MIT"
] | null | null | null | src/kdtree.h | konstatoivanen/SoftwareRayTracer | 0b007b6d88ac7652a503ae8add9c4a8d1f9adfc3 | [
"MIT"
] | null | null | null | src/kdtree.h | konstatoivanen/SoftwareRayTracer | 0b007b6d88ac7652a503ae8add9c4a8d1f9adfc3 | [
"MIT"
] | null | null | null | #pragma once
#include "memoryblock.h"
#include "structs.h"
namespace sr::utilities
{
// Sources:
// https://dcgi.fel.cvut.cz/home/havran/ARTICLES/cgf2011.pdf
// https://graphics.cg.uni-saarland.de/courses/cg1-2017/slides/CG03-SpatialIndex.pdf
// https://www.keithlantz.net/2013/04/kd-tree-construction-using-the-surface-area-heuristic-stack-based-traversal-and-the-hyperplane-separation-theorem/
// https://medium.com/@bromanz/how-to-create-awesome-accelerators-the-surface-area-heuristic-e14b5dec6160
class kdtree
{
public:
explicit kdtree(const structs::mesh* mesh);
kdtree(kdtree const&) = delete;
kdtree& operator=(kdtree const&) = delete;
bool raycast(const math::float3& origin, const math::float3& direction, structs::raycasthit* hit) const;
constexpr const structs::mesh* get_mesh() const { return m_mesh; }
constexpr const uint32_t get_node_count() const { return m_nodeCount; }
constexpr const uint32_t get_branch_count() const { return m_nodeCount - m_faceRangeCount; }
constexpr const uint32_t get_leaf_count() const { return m_faceRangeCount; }
constexpr const uint32_t get_face_count() const { return m_faceCount; }
constexpr const uint32_t get_depth() const { return m_depth; }
private:
constexpr static const uint32_t LEAF_FLAG = 4;
constexpr static const uint32_t FLAG_MASK_OFFS = 28;
constexpr static const uint32_t FLAG_MASK = 0xFu;
constexpr static const uint32_t INDEX_MASK = 0xFFFFFFu;
constexpr static const uint32_t MIN_SPLIT_FACES = 2;
struct kdnode
{
uint32_t data;
float offset;
};
bool compute_split(const math::bounds& bounds, uint32_t* faces, uint32_t faceCount, float costThreshold, float* offset, uint32_t* axis);
void build_recursive(uint32_t nodeIndex, const math::bounds& bounds, uint32_t* faces, uint32_t faceCount, uint32_t depth);
const structs::mesh* m_mesh = nullptr;
memoryblock<kdnode> m_nodes;
memoryblock<uint32_t> m_faces;
memoryblock<structs::facerange> m_faceRanges;
uint32_t m_depth = 0u;
uint32_t m_nodeCount = 1u;
uint32_t m_faceCount = 0u;
uint32_t m_faceRangeCount = 0u;
};
} | 46 | 156 | 0.64533 | [
"mesh"
] |
161aa9576009fa32e732d5aa11a2dd3e6157798d | 3,364 | h | C | be/src/runtime/mysql_table_writer.h | winfys/starrocks | 3c5c8b54c6e5de02eac837791e7d44cb90da3083 | [
"Zlib",
"PSF-2.0",
"Apache-2.0",
"MIT",
"ECL-2.0"
] | null | null | null | be/src/runtime/mysql_table_writer.h | winfys/starrocks | 3c5c8b54c6e5de02eac837791e7d44cb90da3083 | [
"Zlib",
"PSF-2.0",
"Apache-2.0",
"MIT",
"ECL-2.0"
] | null | null | null | be/src/runtime/mysql_table_writer.h | winfys/starrocks | 3c5c8b54c6e5de02eac837791e7d44cb90da3083 | [
"Zlib",
"PSF-2.0",
"Apache-2.0",
"MIT",
"ECL-2.0"
] | null | null | null | // This file is made available under Elastic License 2.0.
// This file is based on code available under the Apache license here:
// https://github.com/apache/incubator-doris/blob/master/be/src/runtime/mysql_table_writer.h
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#pragma once
#include <string>
#include <string_view>
#include <variant>
#include <vector>
#include "column/binary_column.h"
#include "column/column_viewer.h"
#include "column/vectorized_fwd.h"
#include "common/status.h"
#include "fmt/format.h"
#ifndef __StarRocksMysql
#define __StarRocksMysql void
#endif
namespace starrocks {
struct MysqlConnInfo {
std::string host;
std::string user;
std::string passwd;
std::string db;
int port = 0;
std::string debug_string() const;
};
class ExprContext;
#define APPLY_FOR_ALL_PRIMITIVE_TYPE(M) \
M(TYPE_TINYINT) \
M(TYPE_SMALLINT) \
M(TYPE_INT) \
M(TYPE_BIGINT) \
M(TYPE_LARGEINT) \
M(TYPE_FLOAT) \
M(TYPE_DOUBLE) \
M(TYPE_VARCHAR) \
M(TYPE_CHAR) \
M(TYPE_DATE) \
M(TYPE_DATETIME) \
M(TYPE_DECIMALV2) \
M(TYPE_DECIMAL32) \
M(TYPE_DECIMAL64) \
M(TYPE_DECIMAL128) \
M(TYPE_BOOLEAN)
#define APPLY_FOR_ALL_NULL_TYPE(N) M(TYPE_NULL)
class MysqlTableWriter {
public:
using VariantViewer = std::variant<
#define M(NAME) vectorized::ColumnViewer<NAME>,
APPLY_FOR_ALL_PRIMITIVE_TYPE(M)
#undef M
vectorized::ColumnViewer<TYPE_NULL>>;
MysqlTableWriter(const std::vector<ExprContext*>& output_exprs, int batch_size);
~MysqlTableWriter();
// connnect to mysql server
Status open(const MysqlConnInfo& conn_info, const std::string& tbl);
Status begin_trans() { return Status::OK(); }
Status append(vectorized::Chunk* chunk);
Status abort_tarns() { return Status::OK(); }
Status finish_tarns() { return Status::OK(); }
private:
Status _build_viewers(vectorized::Columns& columns);
Status _build_insert_sql(int from, int to, std::string_view* sql);
const std::vector<ExprContext*>& _output_expr_ctxs;
std::vector<VariantViewer> _viewers;
fmt::memory_buffer _stmt_buffer;
std::string _escape_buffer;
std::string _mysql_tbl;
__StarRocksMysql* _mysql_conn;
int _batch_size;
};
} // namespace starrocks
| 30.306306 | 94 | 0.649822 | [
"vector"
] |
163bedc679bd74d042adb95775db0fc849aab7a8 | 2,169 | h | C | lib/inc/drogon/HttpSimpleController.h | gitter-badger/drogon | 32275dfa58ca9354f6fc81b942f9fcd02b76d409 | [
"MIT",
"BSD-3-Clause"
] | 1 | 2019-03-31T05:27:27.000Z | 2019-03-31T05:27:27.000Z | lib/inc/drogon/HttpSimpleController.h | gitter-badger/drogon | 32275dfa58ca9354f6fc81b942f9fcd02b76d409 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | lib/inc/drogon/HttpSimpleController.h | gitter-badger/drogon | 32275dfa58ca9354f6fc81b942f9fcd02b76d409 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | /**
*
* HttpSimpleController.h
* An Tao
*
* Copyright 2018, An Tao. All rights reserved.
* https://github.com/an-tao/drogon
* Use of this source code is governed by a MIT license
* that can be found in the License file.
*
* Drogon
*
*/
#pragma once
#include <drogon/DrObject.h>
#include <drogon/HttpAppFramework.h>
#include <trantor/utils/Logger.h>
#include <string>
#include <vector>
#include <iostream>
#define PATH_LIST_BEGIN \
static void ___paths___() \
{
#define PATH_ADD(path, filters...) __registerSelf(path, {filters});
#define PATH_LIST_END \
}
namespace drogon
{
class HttpSimpleControllerBase : public virtual DrObjectBase
{
public:
virtual void asyncHandleHttpRequest(const HttpRequestPtr &req, const std::function<void(const HttpResponsePtr &)> &callback) = 0;
virtual ~HttpSimpleControllerBase() {}
};
template <typename T>
class HttpSimpleController : public DrObject<T>, public HttpSimpleControllerBase
{
public:
virtual ~HttpSimpleController() {}
protected:
HttpSimpleController() {}
static void __registerSelf(const std::string &path, const std::vector<any> &filtersAndMethods)
{
LOG_TRACE << "register simple controller(" << HttpSimpleController<T>::classTypeName() << ") on path:" << path;
HttpAppFramework::instance().registerHttpSimpleController(path, HttpSimpleController<T>::classTypeName(), filtersAndMethods);
}
private:
class pathRegister
{
public:
pathRegister()
{
T::___paths___();
}
// protected:
// void _register(const std::string &className, const std::vector<std::string> &paths)
// {
// for (auto const &reqPath : paths)
// {
// std::cout << "register controller class " << className << " on path " << reqPath << std::endl;
// }
// }
};
friend pathRegister;
static pathRegister _register;
virtual void *touch()
{
return &_register;
}
};
template <typename T>
typename HttpSimpleController<T>::pathRegister HttpSimpleController<T>::_register;
} // namespace drogon
| 26.13253 | 133 | 0.650991 | [
"vector"
] |
163d660723276cc761a434a028a4da8589091304 | 3,921 | h | C | src/core/alien/core/backend/IVectorConverter.h | cedricga91/alien | 2cb1c80a6125dd6f70d4a57d7bbb55c9461b0bb0 | [
"Apache-2.0"
] | 8 | 2021-09-30T08:29:44.000Z | 2022-02-23T18:39:32.000Z | src/core/alien/core/backend/IVectorConverter.h | cedricga91/alien | 2cb1c80a6125dd6f70d4a57d7bbb55c9461b0bb0 | [
"Apache-2.0"
] | 42 | 2021-07-01T17:32:05.000Z | 2022-03-03T14:53:56.000Z | src/core/alien/core/backend/IVectorConverter.h | cedricga91/alien | 2cb1c80a6125dd6f70d4a57d7bbb55c9461b0bb0 | [
"Apache-2.0"
] | 9 | 2021-09-28T12:59:32.000Z | 2022-03-18T06:35:01.000Z | /*
* Copyright 2020 IFPEN-CEA
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
/*!
* \file IVectorConverter.h
* \brief IVectorConverter.h
*/
#pragma once
#include <alien/core/backend/BackEnd.h>
#include <alien/core/impl/IVectorImpl.h>
#include <alien/utils/ObjectWithTrace.h>
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
namespace Alien
{
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/*!
* \ingroup core
* \brief Vectors converter
*
* Interface to convert a vector in another format, provided a converter between those two
* formats has been registered.
* If there is no direct converter between the source and target format, a third
* intermediate format will be used if available.
*
* \todo IVectorImpl.h is needed only for the template definition. Could be removed
*/
class IVectorConverter : public ObjectWithTrace
{
public:
//! Free resources
virtual ~IVectorConverter() {}
public:
/*!
* \brief Get the source backend id
* \returns The source backend id
*/
virtual BackEndId sourceBackend() const = 0;
/*!
* \brief Get the target backend id
* \returns The target backend id
*/
virtual BackEndId targetBackend() const = 0;
/*!
* \brief Convert a vector from one format to another
* \param[in] sourceImpl Implementation of the source vector
* \param[in,out] targetImpl Implementation of the target vector
*/
virtual void convert(const IVectorImpl* sourceImpl, IVectorImpl* targetImpl) const = 0;
protected:
/*!
* \brief Get the target backend id
* \returns The target backend id
*/
template <typename T>
BackEndId backendId() const { return AlgebraTraits<T>::name(); }
/*!
* \brief Cast a vector implementation in its actual type
* \param[in] impl Vector implementation
* \param[in] backend Backend id
* \returns The actual vector implementation
*
* \todo Check backend using T
*/
template <typename T>
static T& cast(IVectorImpl* impl, BackEndId backend)
{
ALIEN_ASSERT((impl != NULL), ("Null implementation"));
ALIEN_ASSERT((impl->backend() == backend), ("Bad backend"));
T* t = dynamic_cast<T*>(impl);
ALIEN_ASSERT((t != NULL), ("Bad dynamic cast"));
return *t;
}
/*!
* \brief Const cast a vector implementation in its actual type
* \param[in] impl Vector implemenantation
* \param[in] backend Backend id
* \returns The actual vector implementation
*
* \todo Check backend using T
*/
template <typename T>
static const T& cast(const IVectorImpl* impl, BackEndId backend)
{
ALIEN_ASSERT((impl != NULL), ("Null implementation"));
ALIEN_ASSERT((impl->backend() == backend), ("Bad backend"));
const T* t = dynamic_cast<const T*>(impl);
ALIEN_ASSERT((t != NULL), ("Bad dynamic cast"));
return *t;
}
};
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
} // namespace Alien
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
| 30.632813 | 90 | 0.577914 | [
"vector"
] |
16420bce6a335ee3776071e32fe8c133ab9e5b82 | 3,265 | h | C | framework/codec/Android/jni/MediaCodec_Decoder.h | aliyun/CicadaPlayer | 9d2b515a52403034a6e764e30fd0c9508edec889 | [
"MIT"
] | 38 | 2019-12-16T14:31:00.000Z | 2020-01-11T03:01:26.000Z | framework/codec/Android/jni/MediaCodec_Decoder.h | aliyun/CicadaPlayer | 9d2b515a52403034a6e764e30fd0c9508edec889 | [
"MIT"
] | 11 | 2020-01-07T06:32:11.000Z | 2020-01-13T03:52:37.000Z | framework/codec/Android/jni/MediaCodec_Decoder.h | aliyun/CicadaPlayer | 9d2b515a52403034a6e764e30fd0c9508edec889 | [
"MIT"
] | 14 | 2019-12-30T01:19:04.000Z | 2020-01-11T02:12:35.000Z | //
// Created by SuperMan on 2020/10/13.
//
#ifndef SOURCE_MEDIACODEC_DECODER_H
#define SOURCE_MEDIACODEC_DECODER_H
#include <base/media/IAFPacket.h>
#include <cassert>
#include <jni.h>
#include <map>
#include <string>
#define MC_ERROR (-1)
#define MC_INFO_OUTPUT_FORMAT_CHANGED (-2)
#define MC_INFO_OUTPUT_BUFFERS_CHANGED (-3)
#define MC_INFO_TRYAGAIN (-11)
#define CATEGORY_VIDEO (0)
#define CATEGORY_AUDIO (1)
namespace Cicada {
struct mc_out {
int type;
bool b_eos;
union {
struct {
int index;
int64_t pts;
const uint8_t *p_ptr;
size_t size;
} buf;
union {
struct {
unsigned int width, height;
unsigned int stride;
unsigned int slice_height;
int pixel_format;
int crop_left;
int crop_top;
int crop_right;
int crop_bottom;
} video;
struct {
int channel_count;
int channel_mask;
int sample_rate;
int format;
} audio;
} conf;
};
};
class CodecSpecificData {
public:
CodecSpecificData() = default;
~CodecSpecificData()
{
if (buffer != nullptr) {
free(buffer);
}
}
void setScd(const std::string& keyStr ,void* data, int size){
assert(data != nullptr);
len = size;
key = keyStr;
buffer = malloc(size);
memcpy(buffer, data, size);
}
std::string key{};
void *buffer = nullptr;
int len = 0;
};
class MediaCodec_Decoder {
public:
static void init(JNIEnv *env);
static void unInit(JNIEnv *env);
public:
MediaCodec_Decoder();
~MediaCodec_Decoder();
void setCodecSpecificData(const std::list<std::unique_ptr<CodecSpecificData>> &csds);
int setDrmInfo(const std::string &uuid, const void *sessionId, int size);
void setForceInsecureDecoder(bool force);
int
configureVideo(const std::string &mime, int width, int height, int angle, void *surface);
int configureAudio(const std::string &mime, int sampleRate, int channelCount, int isADTS);
int start();
int flush();
int stop();
int release();
int dequeueInputBufferIndex(int64_t timeoutUs);
int queueInputBuffer(int index, void *buffer, size_t size, int64_t pts, bool isConfig);
int queueSecureInputBuffer(int index, void *buffer, size_t size,
IAFPacket::EncryptionInfo *pEncryptionInfo, int64_t pts,
bool isConfig);
int dequeueOutputBufferIndex(int64_t timeoutUs);
int getOutput(int index, mc_out *out, bool readBuffer);
int releaseOutputBuffer(int index, bool render);
private:
jobject mMediaCodec{nullptr};
int mCodecCategory{CATEGORY_VIDEO};
};
}
#endif //SOURCE_MEDIACODEC_DECODER_H
| 24.734848 | 98 | 0.545482 | [
"render"
] |
1644015a4f0a2720b520ebbeff741b231375a918 | 8,353 | h | C | ImGuiBackend.h | SirNate0/Archival | a1b94978246be9a43a7a0ada5776d8d2dbf322e6 | [
"MIT"
] | null | null | null | ImGuiBackend.h | SirNate0/Archival | a1b94978246be9a43a7a0ada5776d8d2dbf322e6 | [
"MIT"
] | null | null | null | ImGuiBackend.h | SirNate0/Archival | a1b94978246be9a43a7a0ada5776d8d2dbf322e6 | [
"MIT"
] | null | null | null | #pragma once
#include <Urho3D/Container/Str.h>
#include "ArchiveDetail.h"
#include <Urhox/Urhox.h>
#include <ImGui/imgui.h>
inline namespace Archival {
namespace Detail {
using namespace Urho3D;
/// Archival Backend that uses Dear IMGUI to display and edit the values in a GUI.
class ImGuiBackend: public Backend
{
/// The default implementation of archiving a type. Defers to Get<T>/Set<T>.
/// Get/Set must exist for the types bool, int, unsigned, float, and String.
/// Maybe also for null, (unsigned) short, (unsigned) long, and double.
/// Values may possibly be cast between different types by the underlying implementation, e.g. XML stores all as a String.
/// The name "value" is reserved. It is used to handle the case of inline values (like JSON [1,2,3]).
/// Internal constructor that is used for CreateGroup/SeriesEntry for non-root groups in the tree. Takes the name of the node, the depth in the tree, and the series entry if it was an entry in a series element rather than a group.
ImGuiBackend(const String& groupName, unsigned treeDepth, int seriesEntry);
public:
/// Creates the backend that will use the provided window name.
ImGuiBackend(const String& windowName);
/// Destructor. Closes the window if the backend was for the top-level (as opposed to an element deeper in the tree).
virtual ~ImGuiBackend() override;
/// Registers the backend with the Context, setting up the IMGUI interface.
static void RegisterBackend(Context* context);
/// Utility method to create a save button with input text. Returns true on button press. Optionally creates a separator beforehand.
static bool SaveButton(String& filename, const String& button = "Save", bool withSeparator = true);
/// Utility method to create a graph from the provided points.
static bool Graph(const String &name, const float *pts, unsigned count, unsigned dataStride = sizeof(float));
/// Test IMGUI method to be called per-frame.
static void TestImGuiUpdate();
Backend* CreateGroup(const String &name, bool isInput) override;
Backend* CreateSeriesEntry(const String &name, bool isInput) override;
bool GetSeriesSize(const String &name, unsigned &size) override;
bool SetSeriesSize(const String &, const unsigned &) override { return false; }
bool GetEntryNames(StringVector &) override { return true; /* we don't need to pre-serialize names */}
bool SetEntryNames(const StringVector &) override { return false; /* we do not support setting values */ }
unsigned char InlineSeriesVerbosity() const override { return 20; }
bool Get(const String &name, const std::nullptr_t &) override;
bool Get(const String &name, bool &val) override;
bool Get(const String &name, unsigned char &val) override;
bool Get(const String &name, signed char &val) override;
bool Get(const String &name, unsigned short &val) override;
bool Get(const String &name, signed short &val) override;
bool Get(const String &name, unsigned int &val) override;
bool Get(const String &name, signed int &val) override;
bool Get(const String &name, unsigned long long &val) override;
bool Get(const String &name, signed long long &val) override;
bool Get(const String &name, float &val) override;
bool Get(const String &name, double &val) override;
bool Get(const String &name, String &val) override;
#ifdef EXTENDED_ARCHIVE_TYPES
bool Get(const String &name, Urho3D::IntVector2 &val) override;
bool Get(const String &name, Urho3D::IntVector3 &val) override;
bool Get(const String &name, Urho3D::Vector2 &val) override;
bool Get(const String &name, Urho3D::Vector3 &val) override;
bool Get(const String &name, Urho3D::Vector4 &val) override;
bool Get(const String &name, Urho3D::Quaternion &val) override;
bool Get(const String &name, Urho3D::Color &val) override;
bool Get(const String &name, Urho3D::Matrix3 &val) override;
bool Get(const String &name, Urho3D::Matrix3x4 &val) override;
bool Get(const String &name, Urho3D::Matrix4 &val) override;
#endif
/// ImGui backend should be treated only as an Input backend. It will update it's values based on what was present when Get is called.
bool Set(const String &, const std::nullptr_t &) override { return false; }
bool Set(const String &, const bool &) override { return false; }
bool Set(const String &, const unsigned char &) override { return false; }
bool Set(const String &, const signed char &) override { return false; }
bool Set(const String &, const unsigned short &) override { return false; }
bool Set(const String &, const signed short &) override { return false; }
bool Set(const String &, const unsigned int &) override { return false; }
bool Set(const String &, const signed int &) override { return false; }
bool Set(const String &, const unsigned long long &) override { return false; }
bool Set(const String &, const signed long long &) override { return false; }
bool Set(const String &, const float &) override { return false; }
bool Set(const String &, const double &) override { return false; }
bool Set(const String &, const String &) override { return false; }
using Backend::AddHint;
/// Adds a hint to the stack. Returns true if the hint kind is recognized.
bool AddHint(const Hint& hint) override { hints_.Push(hint); return true; }
/// Returns true if a hint of this kind is present.
virtual bool HasHint(Hint::HINT kind) override { for (Hint& h: hints_) if (h.kind == kind) return true; return false; }
/// Returns a pointer to a hint with the requested kind or nullptr if the hint has not been set or is unsupported.
const Hint& GetHint(Hint::HINT kind) override { for (Hint& h: hints_) if (h.kind == kind) return h; return Hint::EMPTY_HINT; }
/// Removes the requested hint kind. Returns true if it found such a hint.
bool RemoveHint(Hint::HINT kind) override
{
bool found = false;
for (unsigned i = 0; i < hints_.Size(); ++i)
if (hints_[i].kind == kind)
{
hints_.Erase(i);
--i;
found = true;
}
return found;
}
/// Clears set hints. Returns true if succeeded.
bool ClearHints() override { hints_.Clear(); return true; }
/// Returns true if the condition is allowed. Used so that binary backend can "bake" the result of a conditional write.
bool WriteConditional(bool condition, bool isInput) override;
/// Returns the name of the backend
const String& GetBackendName() override { static const String name("IMGUI"); return name; }
private:
/// Sentinal value to indicate we aren't a first-level element in a series (so we don't need to push to the id stack)
static constexpr int INVALID_SERIES_ENTRY{-1};
/// Holds the entry in the parent series or the invalid value if the parent is a group.
int seriesEntry_{INVALID_SERIES_ENTRY};
/// List of the number of elements in each entry child.
Urho3D::HashMap<String, unsigned> entries_;
/// True if the last written series entry was an open value.
bool lastSeriesOpen_{true};
/// Stores the last created series entry's name so we know when we have to create a new header.
String lastSeriesName_;
/// The hints that we have set.
Vector<Hint> hints_;
/// Integer representing the depth in the tree of this instance of the backend. 0 represents windows, >0 is somewhere in the tree.
unsigned myTreeDepth_;
/// String that is the name of the element (node for the tree or window title).
String myTreeName_;
/// Holds the current global tree depth so we know how many times to PopID from the stack.
static int globalTreeDepth_;
/// Holds the current tree-name stack so we know what to pop from the tree.
static StringVector lastTreeNames_;
/// Method to be called before a value is written to IMGUI to set up the necessary IDs on the stack and such.
void BeginValue();
/// Method to be called after a value is written to IMGUI to clean up the necessary IDs on the stack and such.
void EndValue();
/// Returns the speed to use for drag inputs. Based on the hint, defaults to 0.1f;
float GetSpeedHint();
};
}
}
| 49.135294 | 234 | 0.69927 | [
"vector"
] |
164febee5bf5bedf034ba38862ceb18b987b2a48 | 299 | h | C | Tests/Pods/Headers/Public/DataKit/IDPBufferArray.h | idapgroup/CoreLocationKit | 4c3833cfaa0e2b1e416e6f0f5ada7ac076a7a6dc | [
"BSD-3-Clause"
] | null | null | null | Tests/Pods/Headers/Public/DataKit/IDPBufferArray.h | idapgroup/CoreLocationKit | 4c3833cfaa0e2b1e416e6f0f5ada7ac076a7a6dc | [
"BSD-3-Clause"
] | null | null | null | Tests/Pods/Headers/Public/DataKit/IDPBufferArray.h | idapgroup/CoreLocationKit | 4c3833cfaa0e2b1e416e6f0f5ada7ac076a7a6dc | [
"BSD-3-Clause"
] | null | null | null | //
// IDPBufferArray.h
// liverpool1
//
// Created by Oleksa 'trimm' Korin on 7/4/13.
// Copyright (c) 2013 IDAP Group. All rights reserved.
//
#import "IDPMutableArray.h"
// This is a classic FIFO buffer
@interface IDPBufferArray : IDPMutableArray
- (void)push:(id)object;
- (id)pop;
@end
| 15.736842 | 55 | 0.682274 | [
"object"
] |
3fbe3d29f953c1aae93676d1526f152a99053f4b | 49,122 | c | C | qemu/hw/arm/mps2-tz.c | hyunjoy/scripts | 01114d3627730d695b5ebe61093c719744432ffa | [
"Apache-2.0"
] | null | null | null | qemu/hw/arm/mps2-tz.c | hyunjoy/scripts | 01114d3627730d695b5ebe61093c719744432ffa | [
"Apache-2.0"
] | null | null | null | qemu/hw/arm/mps2-tz.c | hyunjoy/scripts | 01114d3627730d695b5ebe61093c719744432ffa | [
"Apache-2.0"
] | null | null | null | /*
* ARM V2M MPS2 board emulation, trustzone aware FPGA images
*
* Copyright (c) 2017 Linaro Limited
* Written by Peter Maydell
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 or
* (at your option) any later version.
*/
/* The MPS2 and MPS2+ dev boards are FPGA based (the 2+ has a bigger
* FPGA but is otherwise the same as the 2). Since the CPU itself
* and most of the devices are in the FPGA, the details of the board
* as seen by the guest depend significantly on the FPGA image.
* This source file covers the following FPGA images, for TrustZone cores:
* "mps2-an505" -- Cortex-M33 as documented in ARM Application Note AN505
* "mps2-an521" -- Dual Cortex-M33 as documented in Application Note AN521
* "mps2-an524" -- Dual Cortex-M33 as documented in Application Note AN524
* "mps2-an547" -- Single Cortex-M55 as documented in Application Note AN547
*
* Links to the TRM for the board itself and to the various Application
* Notes which document the FPGA images can be found here:
* https://developer.arm.com/products/system-design/development-boards/fpga-prototyping-boards/mps2
*
* Board TRM:
* https://developer.arm.com/documentation/100112/latest/
* Application Note AN505:
* https://developer.arm.com/documentation/dai0505/latest/
* Application Note AN521:
* https://developer.arm.com/documentation/dai0521/latest/
* Application Note AN524:
* https://developer.arm.com/documentation/dai0524/latest/
* Application Note AN547:
* https://developer.arm.com/-/media/Arm%20Developer%20Community/PDF/DAI0547B_SSE300_PLUS_U55_FPGA_for_mps3.pdf
*
* The AN505 defers to the Cortex-M33 processor ARMv8M IoT Kit FVP User Guide
* (ARM ECM0601256) for the details of some of the device layout:
* https://developer.arm.com/documentation/ecm0601256/latest
* Similarly, the AN521 and AN524 use the SSE-200, and the SSE-200 TRM defines
* most of the device layout:
* https://developer.arm.com/documentation/101104/latest/
* and the AN547 uses the SSE-300, whose layout is in the SSE-300 TRM:
* https://developer.arm.com/documentation/101773/latest/
*/
#include "qemu/osdep.h"
#include "qemu/units.h"
#include "qemu/cutils.h"
#include "qapi/error.h"
#include "qemu/error-report.h"
#include "hw/arm/boot.h"
#include "hw/arm/armv7m.h"
#include "hw/or-irq.h"
#include "hw/boards.h"
#include "exec/address-spaces.h"
#include "sysemu/sysemu.h"
#include "hw/misc/unimp.h"
#include "hw/char/cmsdk-apb-uart.h"
#include "hw/timer/cmsdk-apb-timer.h"
#include "hw/misc/mps2-scc.h"
#include "hw/misc/mps2-fpgaio.h"
#include "hw/misc/tz-mpc.h"
#include "hw/misc/tz-msc.h"
#include "hw/arm/armsse.h"
#include "hw/dma/pl080.h"
#include "hw/rtc/pl031.h"
#include "hw/ssi/pl022.h"
#include "hw/i2c/arm_sbcon_i2c.h"
#include "hw/net/lan9118.h"
#include "net/net.h"
#include "hw/core/split-irq.h"
#include "hw/qdev-clock.h"
#include "qom/object.h"
#define MPS2TZ_NUMIRQ_MAX 96
#define MPS2TZ_RAM_MAX 5
typedef enum MPS2TZFPGAType {
FPGA_AN505,
FPGA_AN521,
FPGA_AN524,
FPGA_AN547,
} MPS2TZFPGAType;
/*
* Define the layout of RAM in a board, including which parts are
* behind which MPCs.
* mrindex specifies the index into mms->ram[] to use for the backing RAM;
* -1 means "use the system RAM".
*/
typedef struct RAMInfo {
const char *name;
uint32_t base;
uint32_t size;
int mpc; /* MPC number, -1 for "not behind an MPC" */
int mrindex;
int flags;
} RAMInfo;
/*
* Flag values:
* IS_ALIAS: this RAM area is an alias to the upstream end of the
* MPC specified by its .mpc value
* IS_ROM: this RAM area is read-only
*/
#define IS_ALIAS 1
#define IS_ROM 2
struct MPS2TZMachineClass {
MachineClass parent;
MPS2TZFPGAType fpga_type;
uint32_t scc_id;
uint32_t sysclk_frq; /* Main SYSCLK frequency in Hz */
uint32_t apb_periph_frq; /* APB peripheral frequency in Hz */
uint32_t len_oscclk;
const uint32_t *oscclk;
uint32_t fpgaio_num_leds; /* Number of LEDs in FPGAIO LED0 register */
bool fpgaio_has_switches; /* Does FPGAIO have SWITCH register? */
bool fpgaio_has_dbgctrl; /* Does FPGAIO have DBGCTRL register? */
int numirq; /* Number of external interrupts */
int uart_overflow_irq; /* number of the combined UART overflow IRQ */
uint32_t init_svtor; /* init-svtor setting for SSE */
const RAMInfo *raminfo;
const char *armsse_type;
};
struct MPS2TZMachineState {
MachineState parent;
ARMSSE iotkit;
MemoryRegion ram[MPS2TZ_RAM_MAX];
MemoryRegion eth_usb_container;
MPS2SCC scc;
MPS2FPGAIO fpgaio;
TZPPC ppc[5];
TZMPC mpc[3];
PL022State spi[5];
ArmSbconI2CState i2c[5];
UnimplementedDeviceState i2s_audio;
UnimplementedDeviceState gpio[4];
UnimplementedDeviceState gfx;
UnimplementedDeviceState cldc;
UnimplementedDeviceState usb;
PL031State rtc;
PL080State dma[4];
TZMSC msc[4];
CMSDKAPBUART uart[6];
SplitIRQ sec_resp_splitter;
qemu_or_irq uart_irq_orgate;
DeviceState *lan9118;
SplitIRQ cpu_irq_splitter[MPS2TZ_NUMIRQ_MAX];
Clock *sysclk;
Clock *s32kclk;
};
#define TYPE_MPS2TZ_MACHINE "mps2tz"
#define TYPE_MPS2TZ_AN505_MACHINE MACHINE_TYPE_NAME("mps2-an505")
#define TYPE_MPS2TZ_AN521_MACHINE MACHINE_TYPE_NAME("mps2-an521")
#define TYPE_MPS3TZ_AN524_MACHINE MACHINE_TYPE_NAME("mps3-an524")
#define TYPE_MPS3TZ_AN547_MACHINE MACHINE_TYPE_NAME("mps3-an547")
OBJECT_DECLARE_TYPE(MPS2TZMachineState, MPS2TZMachineClass, MPS2TZ_MACHINE)
/* Slow 32Khz S32KCLK frequency in Hz */
#define S32KCLK_FRQ (32 * 1000)
/*
* The MPS3 DDR is 2GiB, but on a 32-bit host QEMU doesn't permit
* emulation of that much guest RAM, so artificially make it smaller.
*/
#if HOST_LONG_BITS == 32
#define MPS3_DDR_SIZE (1 * GiB)
#else
#define MPS3_DDR_SIZE (2 * GiB)
#endif
static const uint32_t an505_oscclk[] = {
40000000,
24580000,
25000000,
};
static const uint32_t an524_oscclk[] = {
24000000,
32000000,
50000000,
50000000,
24576000,
23750000,
};
static const RAMInfo an505_raminfo[] = { {
.name = "ssram-0",
.base = 0x00000000,
.size = 0x00400000,
.mpc = 0,
.mrindex = 0,
}, {
.name = "ssram-1",
.base = 0x28000000,
.size = 0x00200000,
.mpc = 1,
.mrindex = 1,
}, {
.name = "ssram-2",
.base = 0x28200000,
.size = 0x00200000,
.mpc = 2,
.mrindex = 2,
}, {
.name = "ssram-0-alias",
.base = 0x00400000,
.size = 0x00400000,
.mpc = 0,
.mrindex = 3,
.flags = IS_ALIAS,
}, {
/* Use the largest bit of contiguous RAM as our "system memory" */
.name = "mps.ram",
.base = 0x80000000,
.size = 16 * MiB,
.mpc = -1,
.mrindex = -1,
}, {
.name = NULL,
},
};
static const RAMInfo an524_raminfo[] = { {
.name = "bram",
.base = 0x00000000,
.size = 512 * KiB,
.mpc = 0,
.mrindex = 0,
}, {
.name = "sram",
.base = 0x20000000,
.size = 32 * 4 * KiB,
.mpc = 1,
.mrindex = 1,
}, {
/* We don't model QSPI flash yet; for now expose it as simple ROM */
.name = "QSPI",
.base = 0x28000000,
.size = 8 * MiB,
.mpc = 1,
.mrindex = 2,
.flags = IS_ROM,
}, {
.name = "DDR",
.base = 0x60000000,
.size = MPS3_DDR_SIZE,
.mpc = 2,
.mrindex = -1,
}, {
.name = NULL,
},
};
static const RAMInfo an547_raminfo[] = { {
.name = "itcm",
.base = 0x00000000,
.size = 512 * KiB,
.mpc = -1,
.mrindex = 0,
}, {
.name = "sram",
.base = 0x01000000,
.size = 2 * MiB,
.mpc = 0,
.mrindex = 1,
}, {
.name = "dtcm",
.base = 0x20000000,
.size = 4 * 128 * KiB,
.mpc = -1,
.mrindex = 2,
}, {
.name = "sram 2",
.base = 0x21000000,
.size = 4 * MiB,
.mpc = -1,
.mrindex = 3,
}, {
/* We don't model QSPI flash yet; for now expose it as simple ROM */
.name = "QSPI",
.base = 0x28000000,
.size = 8 * MiB,
.mpc = 1,
.mrindex = 4,
.flags = IS_ROM,
}, {
.name = "DDR",
.base = 0x60000000,
.size = MPS3_DDR_SIZE,
.mpc = 2,
.mrindex = -1,
}, {
.name = NULL,
},
};
static const RAMInfo *find_raminfo_for_mpc(MPS2TZMachineState *mms, int mpc)
{
MPS2TZMachineClass *mmc = MPS2TZ_MACHINE_GET_CLASS(mms);
const RAMInfo *p;
for (p = mmc->raminfo; p->name; p++) {
if (p->mpc == mpc && !(p->flags & IS_ALIAS)) {
return p;
}
}
/* if raminfo array doesn't have an entry for each MPC this is a bug */
g_assert_not_reached();
}
static MemoryRegion *mr_for_raminfo(MPS2TZMachineState *mms,
const RAMInfo *raminfo)
{
/* Return an initialized MemoryRegion for the RAMInfo. */
MemoryRegion *ram;
if (raminfo->mrindex < 0) {
/* Means this RAMInfo is for QEMU's "system memory" */
MachineState *machine = MACHINE(mms);
assert(!(raminfo->flags & IS_ROM));
return machine->ram;
}
assert(raminfo->mrindex < MPS2TZ_RAM_MAX);
ram = &mms->ram[raminfo->mrindex];
memory_region_init_ram(ram, NULL, raminfo->name,
raminfo->size, &error_fatal);
if (raminfo->flags & IS_ROM) {
memory_region_set_readonly(ram, true);
}
return ram;
}
/* Create an alias of an entire original MemoryRegion @orig
* located at @base in the memory map.
*/
static void make_ram_alias(MemoryRegion *mr, const char *name,
MemoryRegion *orig, hwaddr base)
{
memory_region_init_alias(mr, NULL, name, orig, 0,
memory_region_size(orig));
memory_region_add_subregion(get_system_memory(), base, mr);
}
static qemu_irq get_sse_irq_in(MPS2TZMachineState *mms, int irqno)
{
/*
* Return a qemu_irq which will signal IRQ n to all CPUs in the
* SSE. The irqno should be as the CPU sees it, so the first
* external-to-the-SSE interrupt is 32.
*/
MachineClass *mc = MACHINE_GET_CLASS(mms);
MPS2TZMachineClass *mmc = MPS2TZ_MACHINE_GET_CLASS(mms);
assert(irqno >= 32 && irqno < (mmc->numirq + 32));
/*
* Convert from "CPU irq number" (as listed in the FPGA image
* documentation) to the SSE external-interrupt number.
*/
irqno -= 32;
if (mc->max_cpus > 1) {
return qdev_get_gpio_in(DEVICE(&mms->cpu_irq_splitter[irqno]), 0);
} else {
return qdev_get_gpio_in_named(DEVICE(&mms->iotkit), "EXP_IRQ", irqno);
}
}
/* Most of the devices in the AN505 FPGA image sit behind
* Peripheral Protection Controllers. These data structures
* define the layout of which devices sit behind which PPCs.
* The devfn for each port is a function which creates, configures
* and initializes the device, returning the MemoryRegion which
* needs to be plugged into the downstream end of the PPC port.
*/
typedef MemoryRegion *MakeDevFn(MPS2TZMachineState *mms, void *opaque,
const char *name, hwaddr size,
const int *irqs);
typedef struct PPCPortInfo {
const char *name;
MakeDevFn *devfn;
void *opaque;
hwaddr addr;
hwaddr size;
int irqs[3]; /* currently no device needs more IRQ lines than this */
} PPCPortInfo;
typedef struct PPCInfo {
const char *name;
PPCPortInfo ports[TZ_NUM_PORTS];
} PPCInfo;
static MemoryRegion *make_unimp_dev(MPS2TZMachineState *mms,
void *opaque,
const char *name, hwaddr size,
const int *irqs)
{
/* Initialize, configure and realize a TYPE_UNIMPLEMENTED_DEVICE,
* and return a pointer to its MemoryRegion.
*/
UnimplementedDeviceState *uds = opaque;
object_initialize_child(OBJECT(mms), name, uds, TYPE_UNIMPLEMENTED_DEVICE);
qdev_prop_set_string(DEVICE(uds), "name", name);
qdev_prop_set_uint64(DEVICE(uds), "size", size);
sysbus_realize(SYS_BUS_DEVICE(uds), &error_fatal);
return sysbus_mmio_get_region(SYS_BUS_DEVICE(uds), 0);
}
static MemoryRegion *make_uart(MPS2TZMachineState *mms, void *opaque,
const char *name, hwaddr size,
const int *irqs)
{
/* The irq[] array is tx, rx, combined, in that order */
MPS2TZMachineClass *mmc = MPS2TZ_MACHINE_GET_CLASS(mms);
CMSDKAPBUART *uart = opaque;
int i = uart - &mms->uart[0];
SysBusDevice *s;
DeviceState *orgate_dev = DEVICE(&mms->uart_irq_orgate);
object_initialize_child(OBJECT(mms), name, uart, TYPE_CMSDK_APB_UART);
qdev_prop_set_chr(DEVICE(uart), "chardev", serial_hd(i));
qdev_prop_set_uint32(DEVICE(uart), "pclk-frq", mmc->apb_periph_frq);
sysbus_realize(SYS_BUS_DEVICE(uart), &error_fatal);
s = SYS_BUS_DEVICE(uart);
sysbus_connect_irq(s, 0, get_sse_irq_in(mms, irqs[0]));
sysbus_connect_irq(s, 1, get_sse_irq_in(mms, irqs[1]));
sysbus_connect_irq(s, 2, qdev_get_gpio_in(orgate_dev, i * 2));
sysbus_connect_irq(s, 3, qdev_get_gpio_in(orgate_dev, i * 2 + 1));
sysbus_connect_irq(s, 4, get_sse_irq_in(mms, irqs[2]));
return sysbus_mmio_get_region(SYS_BUS_DEVICE(uart), 0);
}
static MemoryRegion *make_scc(MPS2TZMachineState *mms, void *opaque,
const char *name, hwaddr size,
const int *irqs)
{
MPS2SCC *scc = opaque;
DeviceState *sccdev;
MPS2TZMachineClass *mmc = MPS2TZ_MACHINE_GET_CLASS(mms);
uint32_t i;
object_initialize_child(OBJECT(mms), "scc", scc, TYPE_MPS2_SCC);
sccdev = DEVICE(scc);
qdev_prop_set_uint32(sccdev, "scc-cfg4", 0x2);
qdev_prop_set_uint32(sccdev, "scc-aid", 0x00200008);
qdev_prop_set_uint32(sccdev, "scc-id", mmc->scc_id);
qdev_prop_set_uint32(sccdev, "len-oscclk", mmc->len_oscclk);
for (i = 0; i < mmc->len_oscclk; i++) {
g_autofree char *propname = g_strdup_printf("oscclk[%u]", i);
qdev_prop_set_uint32(sccdev, propname, mmc->oscclk[i]);
}
sysbus_realize(SYS_BUS_DEVICE(scc), &error_fatal);
return sysbus_mmio_get_region(SYS_BUS_DEVICE(sccdev), 0);
}
static MemoryRegion *make_fpgaio(MPS2TZMachineState *mms, void *opaque,
const char *name, hwaddr size,
const int *irqs)
{
MPS2FPGAIO *fpgaio = opaque;
MPS2TZMachineClass *mmc = MPS2TZ_MACHINE_GET_CLASS(mms);
object_initialize_child(OBJECT(mms), "fpgaio", fpgaio, TYPE_MPS2_FPGAIO);
qdev_prop_set_uint32(DEVICE(fpgaio), "num-leds", mmc->fpgaio_num_leds);
qdev_prop_set_bit(DEVICE(fpgaio), "has-switches", mmc->fpgaio_has_switches);
qdev_prop_set_bit(DEVICE(fpgaio), "has-dbgctrl", mmc->fpgaio_has_dbgctrl);
sysbus_realize(SYS_BUS_DEVICE(fpgaio), &error_fatal);
return sysbus_mmio_get_region(SYS_BUS_DEVICE(fpgaio), 0);
}
static MemoryRegion *make_eth_dev(MPS2TZMachineState *mms, void *opaque,
const char *name, hwaddr size,
const int *irqs)
{
SysBusDevice *s;
NICInfo *nd = &nd_table[0];
/* In hardware this is a LAN9220; the LAN9118 is software compatible
* except that it doesn't support the checksum-offload feature.
*/
qemu_check_nic_model(nd, "lan9118");
mms->lan9118 = qdev_new(TYPE_LAN9118);
qdev_set_nic_properties(mms->lan9118, nd);
s = SYS_BUS_DEVICE(mms->lan9118);
sysbus_realize_and_unref(s, &error_fatal);
sysbus_connect_irq(s, 0, get_sse_irq_in(mms, irqs[0]));
return sysbus_mmio_get_region(s, 0);
}
static MemoryRegion *make_eth_usb(MPS2TZMachineState *mms, void *opaque,
const char *name, hwaddr size,
const int *irqs)
{
/*
* The AN524 makes the ethernet and USB share a PPC port.
* irqs[] is the ethernet IRQ.
*/
SysBusDevice *s;
NICInfo *nd = &nd_table[0];
memory_region_init(&mms->eth_usb_container, OBJECT(mms),
"mps2-tz-eth-usb-container", 0x200000);
/*
* In hardware this is a LAN9220; the LAN9118 is software compatible
* except that it doesn't support the checksum-offload feature.
*/
qemu_check_nic_model(nd, "lan9118");
mms->lan9118 = qdev_new(TYPE_LAN9118);
qdev_set_nic_properties(mms->lan9118, nd);
s = SYS_BUS_DEVICE(mms->lan9118);
sysbus_realize_and_unref(s, &error_fatal);
sysbus_connect_irq(s, 0, get_sse_irq_in(mms, irqs[0]));
memory_region_add_subregion(&mms->eth_usb_container,
0, sysbus_mmio_get_region(s, 0));
/* The USB OTG controller is an ISP1763; we don't have a model of it. */
object_initialize_child(OBJECT(mms), "usb-otg",
&mms->usb, TYPE_UNIMPLEMENTED_DEVICE);
qdev_prop_set_string(DEVICE(&mms->usb), "name", "usb-otg");
qdev_prop_set_uint64(DEVICE(&mms->usb), "size", 0x100000);
s = SYS_BUS_DEVICE(&mms->usb);
sysbus_realize(s, &error_fatal);
memory_region_add_subregion(&mms->eth_usb_container,
0x100000, sysbus_mmio_get_region(s, 0));
return &mms->eth_usb_container;
}
static MemoryRegion *make_mpc(MPS2TZMachineState *mms, void *opaque,
const char *name, hwaddr size,
const int *irqs)
{
TZMPC *mpc = opaque;
int i = mpc - &mms->mpc[0];
MemoryRegion *upstream;
const RAMInfo *raminfo = find_raminfo_for_mpc(mms, i);
MemoryRegion *ram = mr_for_raminfo(mms, raminfo);
object_initialize_child(OBJECT(mms), name, mpc, TYPE_TZ_MPC);
object_property_set_link(OBJECT(mpc), "downstream", OBJECT(ram),
&error_fatal);
sysbus_realize(SYS_BUS_DEVICE(mpc), &error_fatal);
/* Map the upstream end of the MPC into system memory */
upstream = sysbus_mmio_get_region(SYS_BUS_DEVICE(mpc), 1);
memory_region_add_subregion(get_system_memory(), raminfo->base, upstream);
/* and connect its interrupt to the IoTKit */
qdev_connect_gpio_out_named(DEVICE(mpc), "irq", 0,
qdev_get_gpio_in_named(DEVICE(&mms->iotkit),
"mpcexp_status", i));
/* Return the register interface MR for our caller to map behind the PPC */
return sysbus_mmio_get_region(SYS_BUS_DEVICE(mpc), 0);
}
static MemoryRegion *make_dma(MPS2TZMachineState *mms, void *opaque,
const char *name, hwaddr size,
const int *irqs)
{
/* The irq[] array is DMACINTR, DMACINTERR, DMACINTTC, in that order */
PL080State *dma = opaque;
int i = dma - &mms->dma[0];
SysBusDevice *s;
char *mscname = g_strdup_printf("%s-msc", name);
TZMSC *msc = &mms->msc[i];
DeviceState *iotkitdev = DEVICE(&mms->iotkit);
MemoryRegion *msc_upstream;
MemoryRegion *msc_downstream;
/*
* Each DMA device is a PL081 whose transaction master interface
* is guarded by a Master Security Controller. The downstream end of
* the MSC connects to the IoTKit AHB Slave Expansion port, so the
* DMA devices can see all devices and memory that the CPU does.
*/
object_initialize_child(OBJECT(mms), mscname, msc, TYPE_TZ_MSC);
msc_downstream = sysbus_mmio_get_region(SYS_BUS_DEVICE(&mms->iotkit), 0);
object_property_set_link(OBJECT(msc), "downstream",
OBJECT(msc_downstream), &error_fatal);
object_property_set_link(OBJECT(msc), "idau", OBJECT(mms), &error_fatal);
sysbus_realize(SYS_BUS_DEVICE(msc), &error_fatal);
qdev_connect_gpio_out_named(DEVICE(msc), "irq", 0,
qdev_get_gpio_in_named(iotkitdev,
"mscexp_status", i));
qdev_connect_gpio_out_named(iotkitdev, "mscexp_clear", i,
qdev_get_gpio_in_named(DEVICE(msc),
"irq_clear", 0));
qdev_connect_gpio_out_named(iotkitdev, "mscexp_ns", i,
qdev_get_gpio_in_named(DEVICE(msc),
"cfg_nonsec", 0));
qdev_connect_gpio_out(DEVICE(&mms->sec_resp_splitter),
ARRAY_SIZE(mms->ppc) + i,
qdev_get_gpio_in_named(DEVICE(msc),
"cfg_sec_resp", 0));
msc_upstream = sysbus_mmio_get_region(SYS_BUS_DEVICE(msc), 0);
object_initialize_child(OBJECT(mms), name, dma, TYPE_PL081);
object_property_set_link(OBJECT(dma), "downstream", OBJECT(msc_upstream),
&error_fatal);
sysbus_realize(SYS_BUS_DEVICE(dma), &error_fatal);
s = SYS_BUS_DEVICE(dma);
/* Wire up DMACINTR, DMACINTERR, DMACINTTC */
sysbus_connect_irq(s, 0, get_sse_irq_in(mms, irqs[0]));
sysbus_connect_irq(s, 1, get_sse_irq_in(mms, irqs[1]));
sysbus_connect_irq(s, 2, get_sse_irq_in(mms, irqs[2]));
g_free(mscname);
return sysbus_mmio_get_region(s, 0);
}
static MemoryRegion *make_spi(MPS2TZMachineState *mms, void *opaque,
const char *name, hwaddr size,
const int *irqs)
{
/*
* The AN505 has five PL022 SPI controllers.
* One of these should have the LCD controller behind it; the others
* are connected only to the FPGA's "general purpose SPI connector"
* or "shield" expansion connectors.
* Note that if we do implement devices behind SPI, the chip select
* lines are set via the "MISC" register in the MPS2 FPGAIO device.
*/
PL022State *spi = opaque;
SysBusDevice *s;
object_initialize_child(OBJECT(mms), name, spi, TYPE_PL022);
sysbus_realize(SYS_BUS_DEVICE(spi), &error_fatal);
s = SYS_BUS_DEVICE(spi);
sysbus_connect_irq(s, 0, get_sse_irq_in(mms, irqs[0]));
return sysbus_mmio_get_region(s, 0);
}
static MemoryRegion *make_i2c(MPS2TZMachineState *mms, void *opaque,
const char *name, hwaddr size,
const int *irqs)
{
ArmSbconI2CState *i2c = opaque;
SysBusDevice *s;
object_initialize_child(OBJECT(mms), name, i2c, TYPE_ARM_SBCON_I2C);
s = SYS_BUS_DEVICE(i2c);
sysbus_realize(s, &error_fatal);
return sysbus_mmio_get_region(s, 0);
}
static MemoryRegion *make_rtc(MPS2TZMachineState *mms, void *opaque,
const char *name, hwaddr size,
const int *irqs)
{
PL031State *pl031 = opaque;
SysBusDevice *s;
object_initialize_child(OBJECT(mms), name, pl031, TYPE_PL031);
s = SYS_BUS_DEVICE(pl031);
sysbus_realize(s, &error_fatal);
/*
* The board docs don't give an IRQ number for the PL031, so
* presumably it is not connected.
*/
return sysbus_mmio_get_region(s, 0);
}
static void create_non_mpc_ram(MPS2TZMachineState *mms)
{
/*
* Handle the RAMs which are either not behind MPCs or which are
* aliases to another MPC.
*/
const RAMInfo *p;
MPS2TZMachineClass *mmc = MPS2TZ_MACHINE_GET_CLASS(mms);
for (p = mmc->raminfo; p->name; p++) {
if (p->flags & IS_ALIAS) {
SysBusDevice *mpc_sbd = SYS_BUS_DEVICE(&mms->mpc[p->mpc]);
MemoryRegion *upstream = sysbus_mmio_get_region(mpc_sbd, 1);
make_ram_alias(&mms->ram[p->mrindex], p->name, upstream, p->base);
} else if (p->mpc == -1) {
/* RAM not behind an MPC */
MemoryRegion *mr = mr_for_raminfo(mms, p);
memory_region_add_subregion(get_system_memory(), p->base, mr);
}
}
}
static uint32_t boot_ram_size(MPS2TZMachineState *mms)
{
/* Return the size of the RAM block at guest address zero */
const RAMInfo *p;
MPS2TZMachineClass *mmc = MPS2TZ_MACHINE_GET_CLASS(mms);
for (p = mmc->raminfo; p->name; p++) {
if (p->base == 0) {
return p->size;
}
}
g_assert_not_reached();
}
static void mps2tz_common_init(MachineState *machine)
{
MPS2TZMachineState *mms = MPS2TZ_MACHINE(machine);
MPS2TZMachineClass *mmc = MPS2TZ_MACHINE_GET_CLASS(mms);
MachineClass *mc = MACHINE_GET_CLASS(machine);
MemoryRegion *system_memory = get_system_memory();
DeviceState *iotkitdev;
DeviceState *dev_splitter;
const PPCInfo *ppcs;
int num_ppcs;
int i;
if (strcmp(machine->cpu_type, mc->default_cpu_type) != 0) {
error_report("This board can only be used with CPU %s",
mc->default_cpu_type);
exit(1);
}
if (machine->ram_size != mc->default_ram_size) {
char *sz = size_to_str(mc->default_ram_size);
error_report("Invalid RAM size, should be %s", sz);
g_free(sz);
exit(EXIT_FAILURE);
}
/* These clocks don't need migration because they are fixed-frequency */
mms->sysclk = clock_new(OBJECT(machine), "SYSCLK");
clock_set_hz(mms->sysclk, mmc->sysclk_frq);
mms->s32kclk = clock_new(OBJECT(machine), "S32KCLK");
clock_set_hz(mms->s32kclk, S32KCLK_FRQ);
object_initialize_child(OBJECT(machine), TYPE_IOTKIT, &mms->iotkit,
mmc->armsse_type);
iotkitdev = DEVICE(&mms->iotkit);
object_property_set_link(OBJECT(&mms->iotkit), "memory",
OBJECT(system_memory), &error_abort);
qdev_prop_set_uint32(iotkitdev, "EXP_NUMIRQ", mmc->numirq);
qdev_prop_set_uint32(iotkitdev, "init-svtor", mmc->init_svtor);
qdev_connect_clock_in(iotkitdev, "MAINCLK", mms->sysclk);
qdev_connect_clock_in(iotkitdev, "S32KCLK", mms->s32kclk);
sysbus_realize(SYS_BUS_DEVICE(&mms->iotkit), &error_fatal);
/*
* If this board has more than one CPU, then we need to create splitters
* to feed the IRQ inputs for each CPU in the SSE from each device in the
* board. If there is only one CPU, we can just wire the device IRQ
* directly to the SSE's IRQ input.
*/
assert(mmc->numirq <= MPS2TZ_NUMIRQ_MAX);
if (mc->max_cpus > 1) {
for (i = 0; i < mmc->numirq; i++) {
char *name = g_strdup_printf("mps2-irq-splitter%d", i);
SplitIRQ *splitter = &mms->cpu_irq_splitter[i];
object_initialize_child_with_props(OBJECT(machine), name,
splitter, sizeof(*splitter),
TYPE_SPLIT_IRQ, &error_fatal,
NULL);
g_free(name);
object_property_set_int(OBJECT(splitter), "num-lines", 2,
&error_fatal);
qdev_realize(DEVICE(splitter), NULL, &error_fatal);
qdev_connect_gpio_out(DEVICE(splitter), 0,
qdev_get_gpio_in_named(DEVICE(&mms->iotkit),
"EXP_IRQ", i));
qdev_connect_gpio_out(DEVICE(splitter), 1,
qdev_get_gpio_in_named(DEVICE(&mms->iotkit),
"EXP_CPU1_IRQ", i));
}
}
/* The sec_resp_cfg output from the IoTKit must be split into multiple
* lines, one for each of the PPCs we create here, plus one per MSC.
*/
object_initialize_child(OBJECT(machine), "sec-resp-splitter",
&mms->sec_resp_splitter, TYPE_SPLIT_IRQ);
object_property_set_int(OBJECT(&mms->sec_resp_splitter), "num-lines",
ARRAY_SIZE(mms->ppc) + ARRAY_SIZE(mms->msc),
&error_fatal);
qdev_realize(DEVICE(&mms->sec_resp_splitter), NULL, &error_fatal);
dev_splitter = DEVICE(&mms->sec_resp_splitter);
qdev_connect_gpio_out_named(iotkitdev, "sec_resp_cfg", 0,
qdev_get_gpio_in(dev_splitter, 0));
/*
* The IoTKit sets up much of the memory layout, including
* the aliases between secure and non-secure regions in the
* address space, and also most of the devices in the system.
* The FPGA itself contains various RAMs and some additional devices.
* The FPGA images have an odd combination of different RAMs,
* because in hardware they are different implementations and
* connected to different buses, giving varying performance/size
* tradeoffs. For QEMU they're all just RAM, though. We arbitrarily
* call the largest lump our "system memory".
*/
/*
* The overflow IRQs for all UARTs are ORed together.
* Tx, Rx and "combined" IRQs are sent to the NVIC separately.
* Create the OR gate for this: it has one input for the TX overflow
* and one for the RX overflow for each UART we might have.
* (If the board has fewer than the maximum possible number of UARTs
* those inputs are never wired up and are treated as always-zero.)
*/
object_initialize_child(OBJECT(mms), "uart-irq-orgate",
&mms->uart_irq_orgate, TYPE_OR_IRQ);
object_property_set_int(OBJECT(&mms->uart_irq_orgate), "num-lines",
2 * ARRAY_SIZE(mms->uart),
&error_fatal);
qdev_realize(DEVICE(&mms->uart_irq_orgate), NULL, &error_fatal);
qdev_connect_gpio_out(DEVICE(&mms->uart_irq_orgate), 0,
get_sse_irq_in(mms, mmc->uart_overflow_irq));
/* Most of the devices in the FPGA are behind Peripheral Protection
* Controllers. The required order for initializing things is:
* + initialize the PPC
* + initialize, configure and realize downstream devices
* + connect downstream device MemoryRegions to the PPC
* + realize the PPC
* + map the PPC's MemoryRegions to the places in the address map
* where the downstream devices should appear
* + wire up the PPC's control lines to the IoTKit object
*/
const PPCInfo an505_ppcs[] = { {
.name = "apb_ppcexp0",
.ports = {
{ "ssram-0-mpc", make_mpc, &mms->mpc[0], 0x58007000, 0x1000 },
{ "ssram-1-mpc", make_mpc, &mms->mpc[1], 0x58008000, 0x1000 },
{ "ssram-2-mpc", make_mpc, &mms->mpc[2], 0x58009000, 0x1000 },
},
}, {
.name = "apb_ppcexp1",
.ports = {
{ "spi0", make_spi, &mms->spi[0], 0x40205000, 0x1000, { 51 } },
{ "spi1", make_spi, &mms->spi[1], 0x40206000, 0x1000, { 52 } },
{ "spi2", make_spi, &mms->spi[2], 0x40209000, 0x1000, { 53 } },
{ "spi3", make_spi, &mms->spi[3], 0x4020a000, 0x1000, { 54 } },
{ "spi4", make_spi, &mms->spi[4], 0x4020b000, 0x1000, { 55 } },
{ "uart0", make_uart, &mms->uart[0], 0x40200000, 0x1000, { 32, 33, 42 } },
{ "uart1", make_uart, &mms->uart[1], 0x40201000, 0x1000, { 34, 35, 43 } },
{ "uart2", make_uart, &mms->uart[2], 0x40202000, 0x1000, { 36, 37, 44 } },
{ "uart3", make_uart, &mms->uart[3], 0x40203000, 0x1000, { 38, 39, 45 } },
{ "uart4", make_uart, &mms->uart[4], 0x40204000, 0x1000, { 40, 41, 46 } },
{ "i2c0", make_i2c, &mms->i2c[0], 0x40207000, 0x1000 },
{ "i2c1", make_i2c, &mms->i2c[1], 0x40208000, 0x1000 },
{ "i2c2", make_i2c, &mms->i2c[2], 0x4020c000, 0x1000 },
{ "i2c3", make_i2c, &mms->i2c[3], 0x4020d000, 0x1000 },
},
}, {
.name = "apb_ppcexp2",
.ports = {
{ "scc", make_scc, &mms->scc, 0x40300000, 0x1000 },
{ "i2s-audio", make_unimp_dev, &mms->i2s_audio,
0x40301000, 0x1000 },
{ "fpgaio", make_fpgaio, &mms->fpgaio, 0x40302000, 0x1000 },
},
}, {
.name = "ahb_ppcexp0",
.ports = {
{ "gfx", make_unimp_dev, &mms->gfx, 0x41000000, 0x140000 },
{ "gpio0", make_unimp_dev, &mms->gpio[0], 0x40100000, 0x1000 },
{ "gpio1", make_unimp_dev, &mms->gpio[1], 0x40101000, 0x1000 },
{ "gpio2", make_unimp_dev, &mms->gpio[2], 0x40102000, 0x1000 },
{ "gpio3", make_unimp_dev, &mms->gpio[3], 0x40103000, 0x1000 },
{ "eth", make_eth_dev, NULL, 0x42000000, 0x100000, { 48 } },
},
}, {
.name = "ahb_ppcexp1",
.ports = {
{ "dma0", make_dma, &mms->dma[0], 0x40110000, 0x1000, { 58, 56, 57 } },
{ "dma1", make_dma, &mms->dma[1], 0x40111000, 0x1000, { 61, 59, 60 } },
{ "dma2", make_dma, &mms->dma[2], 0x40112000, 0x1000, { 64, 62, 63 } },
{ "dma3", make_dma, &mms->dma[3], 0x40113000, 0x1000, { 67, 65, 66 } },
},
},
};
const PPCInfo an524_ppcs[] = { {
.name = "apb_ppcexp0",
.ports = {
{ "bram-mpc", make_mpc, &mms->mpc[0], 0x58007000, 0x1000 },
{ "qspi-mpc", make_mpc, &mms->mpc[1], 0x58008000, 0x1000 },
{ "ddr-mpc", make_mpc, &mms->mpc[2], 0x58009000, 0x1000 },
},
}, {
.name = "apb_ppcexp1",
.ports = {
{ "i2c0", make_i2c, &mms->i2c[0], 0x41200000, 0x1000 },
{ "i2c1", make_i2c, &mms->i2c[1], 0x41201000, 0x1000 },
{ "spi0", make_spi, &mms->spi[0], 0x41202000, 0x1000, { 52 } },
{ "spi1", make_spi, &mms->spi[1], 0x41203000, 0x1000, { 53 } },
{ "spi2", make_spi, &mms->spi[2], 0x41204000, 0x1000, { 54 } },
{ "i2c2", make_i2c, &mms->i2c[2], 0x41205000, 0x1000 },
{ "i2c3", make_i2c, &mms->i2c[3], 0x41206000, 0x1000 },
{ /* port 7 reserved */ },
{ "i2c4", make_i2c, &mms->i2c[4], 0x41208000, 0x1000 },
},
}, {
.name = "apb_ppcexp2",
.ports = {
{ "scc", make_scc, &mms->scc, 0x41300000, 0x1000 },
{ "i2s-audio", make_unimp_dev, &mms->i2s_audio,
0x41301000, 0x1000 },
{ "fpgaio", make_fpgaio, &mms->fpgaio, 0x41302000, 0x1000 },
{ "uart0", make_uart, &mms->uart[0], 0x41303000, 0x1000, { 32, 33, 42 } },
{ "uart1", make_uart, &mms->uart[1], 0x41304000, 0x1000, { 34, 35, 43 } },
{ "uart2", make_uart, &mms->uart[2], 0x41305000, 0x1000, { 36, 37, 44 } },
{ "uart3", make_uart, &mms->uart[3], 0x41306000, 0x1000, { 38, 39, 45 } },
{ "uart4", make_uart, &mms->uart[4], 0x41307000, 0x1000, { 40, 41, 46 } },
{ "uart5", make_uart, &mms->uart[5], 0x41308000, 0x1000, { 124, 125, 126 } },
{ /* port 9 reserved */ },
{ "clcd", make_unimp_dev, &mms->cldc, 0x4130a000, 0x1000 },
{ "rtc", make_rtc, &mms->rtc, 0x4130b000, 0x1000 },
},
}, {
.name = "ahb_ppcexp0",
.ports = {
{ "gpio0", make_unimp_dev, &mms->gpio[0], 0x41100000, 0x1000 },
{ "gpio1", make_unimp_dev, &mms->gpio[1], 0x41101000, 0x1000 },
{ "gpio2", make_unimp_dev, &mms->gpio[2], 0x41102000, 0x1000 },
{ "gpio3", make_unimp_dev, &mms->gpio[3], 0x41103000, 0x1000 },
{ "eth-usb", make_eth_usb, NULL, 0x41400000, 0x200000, { 48 } },
},
},
};
const PPCInfo an547_ppcs[] = { {
.name = "apb_ppcexp0",
.ports = {
{ "ssram-mpc", make_mpc, &mms->mpc[0], 0x57000000, 0x1000 },
{ "qspi-mpc", make_mpc, &mms->mpc[1], 0x57001000, 0x1000 },
{ "ddr-mpc", make_mpc, &mms->mpc[2], 0x57002000, 0x1000 },
},
}, {
.name = "apb_ppcexp1",
.ports = {
{ "i2c0", make_i2c, &mms->i2c[0], 0x49200000, 0x1000 },
{ "i2c1", make_i2c, &mms->i2c[1], 0x49201000, 0x1000 },
{ "spi0", make_spi, &mms->spi[0], 0x49202000, 0x1000, { 53 } },
{ "spi1", make_spi, &mms->spi[1], 0x49203000, 0x1000, { 54 } },
{ "spi2", make_spi, &mms->spi[2], 0x49204000, 0x1000, { 55 } },
{ "i2c2", make_i2c, &mms->i2c[2], 0x49205000, 0x1000 },
{ "i2c3", make_i2c, &mms->i2c[3], 0x49206000, 0x1000 },
{ /* port 7 reserved */ },
{ "i2c4", make_i2c, &mms->i2c[4], 0x49208000, 0x1000 },
},
}, {
.name = "apb_ppcexp2",
.ports = {
{ "scc", make_scc, &mms->scc, 0x49300000, 0x1000 },
{ "i2s-audio", make_unimp_dev, &mms->i2s_audio, 0x49301000, 0x1000 },
{ "fpgaio", make_fpgaio, &mms->fpgaio, 0x49302000, 0x1000 },
{ "uart0", make_uart, &mms->uart[0], 0x49303000, 0x1000, { 33, 34, 43 } },
{ "uart1", make_uart, &mms->uart[1], 0x49304000, 0x1000, { 35, 36, 44 } },
{ "uart2", make_uart, &mms->uart[2], 0x49305000, 0x1000, { 37, 38, 45 } },
{ "uart3", make_uart, &mms->uart[3], 0x49306000, 0x1000, { 39, 40, 46 } },
{ "uart4", make_uart, &mms->uart[4], 0x49307000, 0x1000, { 41, 42, 47 } },
{ "uart5", make_uart, &mms->uart[5], 0x49308000, 0x1000, { 125, 126, 127 } },
{ /* port 9 reserved */ },
{ "clcd", make_unimp_dev, &mms->cldc, 0x4930a000, 0x1000 },
{ "rtc", make_rtc, &mms->rtc, 0x4930b000, 0x1000 },
},
}, {
.name = "ahb_ppcexp0",
.ports = {
{ "gpio0", make_unimp_dev, &mms->gpio[0], 0x41100000, 0x1000 },
{ "gpio1", make_unimp_dev, &mms->gpio[1], 0x41101000, 0x1000 },
{ "gpio2", make_unimp_dev, &mms->gpio[2], 0x41102000, 0x1000 },
{ "gpio3", make_unimp_dev, &mms->gpio[3], 0x41103000, 0x1000 },
{ "eth-usb", make_eth_usb, NULL, 0x41400000, 0x200000, { 49 } },
},
},
};
switch (mmc->fpga_type) {
case FPGA_AN505:
case FPGA_AN521:
ppcs = an505_ppcs;
num_ppcs = ARRAY_SIZE(an505_ppcs);
break;
case FPGA_AN524:
ppcs = an524_ppcs;
num_ppcs = ARRAY_SIZE(an524_ppcs);
break;
case FPGA_AN547:
ppcs = an547_ppcs;
num_ppcs = ARRAY_SIZE(an547_ppcs);
break;
default:
g_assert_not_reached();
}
for (i = 0; i < num_ppcs; i++) {
const PPCInfo *ppcinfo = &ppcs[i];
TZPPC *ppc = &mms->ppc[i];
DeviceState *ppcdev;
int port;
char *gpioname;
object_initialize_child(OBJECT(machine), ppcinfo->name, ppc,
TYPE_TZ_PPC);
ppcdev = DEVICE(ppc);
for (port = 0; port < TZ_NUM_PORTS; port++) {
const PPCPortInfo *pinfo = &ppcinfo->ports[port];
MemoryRegion *mr;
char *portname;
if (!pinfo->devfn) {
continue;
}
mr = pinfo->devfn(mms, pinfo->opaque, pinfo->name, pinfo->size,
pinfo->irqs);
portname = g_strdup_printf("port[%d]", port);
object_property_set_link(OBJECT(ppc), portname, OBJECT(mr),
&error_fatal);
g_free(portname);
}
sysbus_realize(SYS_BUS_DEVICE(ppc), &error_fatal);
for (port = 0; port < TZ_NUM_PORTS; port++) {
const PPCPortInfo *pinfo = &ppcinfo->ports[port];
if (!pinfo->devfn) {
continue;
}
sysbus_mmio_map(SYS_BUS_DEVICE(ppc), port, pinfo->addr);
gpioname = g_strdup_printf("%s_nonsec", ppcinfo->name);
qdev_connect_gpio_out_named(iotkitdev, gpioname, port,
qdev_get_gpio_in_named(ppcdev,
"cfg_nonsec",
port));
g_free(gpioname);
gpioname = g_strdup_printf("%s_ap", ppcinfo->name);
qdev_connect_gpio_out_named(iotkitdev, gpioname, port,
qdev_get_gpio_in_named(ppcdev,
"cfg_ap", port));
g_free(gpioname);
}
gpioname = g_strdup_printf("%s_irq_enable", ppcinfo->name);
qdev_connect_gpio_out_named(iotkitdev, gpioname, 0,
qdev_get_gpio_in_named(ppcdev,
"irq_enable", 0));
g_free(gpioname);
gpioname = g_strdup_printf("%s_irq_clear", ppcinfo->name);
qdev_connect_gpio_out_named(iotkitdev, gpioname, 0,
qdev_get_gpio_in_named(ppcdev,
"irq_clear", 0));
g_free(gpioname);
gpioname = g_strdup_printf("%s_irq_status", ppcinfo->name);
qdev_connect_gpio_out_named(ppcdev, "irq", 0,
qdev_get_gpio_in_named(iotkitdev,
gpioname, 0));
g_free(gpioname);
qdev_connect_gpio_out(dev_splitter, i,
qdev_get_gpio_in_named(ppcdev,
"cfg_sec_resp", 0));
}
create_unimplemented_device("FPGA NS PC", 0x48007000, 0x1000);
if (mmc->fpga_type == FPGA_AN547) {
create_unimplemented_device("U55 timing adapter 0", 0x48102000, 0x1000);
create_unimplemented_device("U55 timing adapter 1", 0x48103000, 0x1000);
}
create_non_mpc_ram(mms);
armv7m_load_kernel(ARM_CPU(first_cpu), machine->kernel_filename,
boot_ram_size(mms));
}
static void mps2_tz_idau_check(IDAUInterface *ii, uint32_t address,
int *iregion, bool *exempt, bool *ns, bool *nsc)
{
/*
* The MPS2 TZ FPGA images have IDAUs in them which are connected to
* the Master Security Controllers. Thes have the same logic as
* is used by the IoTKit for the IDAU connected to the CPU, except
* that MSCs don't care about the NSC attribute.
*/
int region = extract32(address, 28, 4);
*ns = !(region & 1);
*nsc = false;
/* 0xe0000000..0xe00fffff and 0xf0000000..0xf00fffff are exempt */
*exempt = (address & 0xeff00000) == 0xe0000000;
*iregion = region;
}
static void mps2tz_class_init(ObjectClass *oc, void *data)
{
MachineClass *mc = MACHINE_CLASS(oc);
IDAUInterfaceClass *iic = IDAU_INTERFACE_CLASS(oc);
mc->init = mps2tz_common_init;
iic->check = mps2_tz_idau_check;
}
static void mps2tz_set_default_ram_info(MPS2TZMachineClass *mmc)
{
/*
* Set mc->default_ram_size and default_ram_id from the
* information in mmc->raminfo.
*/
MachineClass *mc = MACHINE_CLASS(mmc);
const RAMInfo *p;
for (p = mmc->raminfo; p->name; p++) {
if (p->mrindex < 0) {
/* Found the entry for "system memory" */
mc->default_ram_size = p->size;
mc->default_ram_id = p->name;
return;
}
}
g_assert_not_reached();
}
static void mps2tz_an505_class_init(ObjectClass *oc, void *data)
{
MachineClass *mc = MACHINE_CLASS(oc);
MPS2TZMachineClass *mmc = MPS2TZ_MACHINE_CLASS(oc);
mc->desc = "ARM MPS2 with AN505 FPGA image for Cortex-M33";
mc->default_cpus = 1;
mc->min_cpus = mc->default_cpus;
mc->max_cpus = mc->default_cpus;
mmc->fpga_type = FPGA_AN505;
mc->default_cpu_type = ARM_CPU_TYPE_NAME("cortex-m33");
mmc->scc_id = 0x41045050;
mmc->sysclk_frq = 20 * 1000 * 1000; /* 20MHz */
mmc->apb_periph_frq = mmc->sysclk_frq;
mmc->oscclk = an505_oscclk;
mmc->len_oscclk = ARRAY_SIZE(an505_oscclk);
mmc->fpgaio_num_leds = 2;
mmc->fpgaio_has_switches = false;
mmc->fpgaio_has_dbgctrl = false;
mmc->numirq = 92;
mmc->uart_overflow_irq = 47;
mmc->init_svtor = 0x10000000;
mmc->raminfo = an505_raminfo;
mmc->armsse_type = TYPE_IOTKIT;
mps2tz_set_default_ram_info(mmc);
}
static void mps2tz_an521_class_init(ObjectClass *oc, void *data)
{
MachineClass *mc = MACHINE_CLASS(oc);
MPS2TZMachineClass *mmc = MPS2TZ_MACHINE_CLASS(oc);
mc->desc = "ARM MPS2 with AN521 FPGA image for dual Cortex-M33";
mc->default_cpus = 2;
mc->min_cpus = mc->default_cpus;
mc->max_cpus = mc->default_cpus;
mmc->fpga_type = FPGA_AN521;
mc->default_cpu_type = ARM_CPU_TYPE_NAME("cortex-m33");
mmc->scc_id = 0x41045210;
mmc->sysclk_frq = 20 * 1000 * 1000; /* 20MHz */
mmc->apb_periph_frq = mmc->sysclk_frq;
mmc->oscclk = an505_oscclk; /* AN521 is the same as AN505 here */
mmc->len_oscclk = ARRAY_SIZE(an505_oscclk);
mmc->fpgaio_num_leds = 2;
mmc->fpgaio_has_switches = false;
mmc->fpgaio_has_dbgctrl = false;
mmc->numirq = 92;
mmc->uart_overflow_irq = 47;
mmc->init_svtor = 0x10000000;
mmc->raminfo = an505_raminfo; /* AN521 is the same as AN505 here */
mmc->armsse_type = TYPE_SSE200;
mps2tz_set_default_ram_info(mmc);
}
static void mps3tz_an524_class_init(ObjectClass *oc, void *data)
{
MachineClass *mc = MACHINE_CLASS(oc);
MPS2TZMachineClass *mmc = MPS2TZ_MACHINE_CLASS(oc);
mc->desc = "ARM MPS3 with AN524 FPGA image for dual Cortex-M33";
mc->default_cpus = 2;
mc->min_cpus = mc->default_cpus;
mc->max_cpus = mc->default_cpus;
mmc->fpga_type = FPGA_AN524;
mc->default_cpu_type = ARM_CPU_TYPE_NAME("cortex-m33");
mmc->scc_id = 0x41045240;
mmc->sysclk_frq = 32 * 1000 * 1000; /* 32MHz */
mmc->apb_periph_frq = mmc->sysclk_frq;
mmc->oscclk = an524_oscclk;
mmc->len_oscclk = ARRAY_SIZE(an524_oscclk);
mmc->fpgaio_num_leds = 10;
mmc->fpgaio_has_switches = true;
mmc->fpgaio_has_dbgctrl = false;
mmc->numirq = 95;
mmc->uart_overflow_irq = 47;
mmc->init_svtor = 0x10000000;
mmc->raminfo = an524_raminfo;
mmc->armsse_type = TYPE_SSE200;
mps2tz_set_default_ram_info(mmc);
}
static void mps3tz_an547_class_init(ObjectClass *oc, void *data)
{
MachineClass *mc = MACHINE_CLASS(oc);
MPS2TZMachineClass *mmc = MPS2TZ_MACHINE_CLASS(oc);
mc->desc = "ARM MPS3 with AN547 FPGA image for Cortex-M55";
mc->default_cpus = 1;
mc->min_cpus = mc->default_cpus;
mc->max_cpus = mc->default_cpus;
mmc->fpga_type = FPGA_AN547;
mc->default_cpu_type = ARM_CPU_TYPE_NAME("cortex-m55");
mmc->scc_id = 0x41055470;
mmc->sysclk_frq = 32 * 1000 * 1000; /* 32MHz */
mmc->apb_periph_frq = 25 * 1000 * 1000; /* 25MHz */
mmc->oscclk = an524_oscclk; /* same as AN524 */
mmc->len_oscclk = ARRAY_SIZE(an524_oscclk);
mmc->fpgaio_num_leds = 10;
mmc->fpgaio_has_switches = true;
mmc->fpgaio_has_dbgctrl = true;
mmc->numirq = 96;
mmc->uart_overflow_irq = 48;
mmc->init_svtor = 0x00000000;
mmc->raminfo = an547_raminfo;
mmc->armsse_type = TYPE_SSE300;
mps2tz_set_default_ram_info(mmc);
}
static const TypeInfo mps2tz_info = {
.name = TYPE_MPS2TZ_MACHINE,
.parent = TYPE_MACHINE,
.abstract = true,
.instance_size = sizeof(MPS2TZMachineState),
.class_size = sizeof(MPS2TZMachineClass),
.class_init = mps2tz_class_init,
.interfaces = (InterfaceInfo[]) {
{ TYPE_IDAU_INTERFACE },
{ }
},
};
static const TypeInfo mps2tz_an505_info = {
.name = TYPE_MPS2TZ_AN505_MACHINE,
.parent = TYPE_MPS2TZ_MACHINE,
.class_init = mps2tz_an505_class_init,
};
static const TypeInfo mps2tz_an521_info = {
.name = TYPE_MPS2TZ_AN521_MACHINE,
.parent = TYPE_MPS2TZ_MACHINE,
.class_init = mps2tz_an521_class_init,
};
static const TypeInfo mps3tz_an524_info = {
.name = TYPE_MPS3TZ_AN524_MACHINE,
.parent = TYPE_MPS2TZ_MACHINE,
.class_init = mps3tz_an524_class_init,
};
static const TypeInfo mps3tz_an547_info = {
.name = TYPE_MPS3TZ_AN547_MACHINE,
.parent = TYPE_MPS2TZ_MACHINE,
.class_init = mps3tz_an547_class_init,
};
static void mps2tz_machine_init(void)
{
type_register_static(&mps2tz_info);
type_register_static(&mps2tz_an505_info);
type_register_static(&mps2tz_an521_info);
type_register_static(&mps3tz_an524_info);
type_register_static(&mps3tz_an547_info);
}
type_init(mps2tz_machine_init);
| 37.786154 | 111 | 0.595619 | [
"object",
"model"
] |
3fc629272ed9aa5c0277014fd410613a8b6530ea | 2,893 | h | C | daemon/armnn/IGlobalState.h | rossburton/gator | 9d8d75fa08352470c51abc23fe3b314879bd8b78 | [
"BSD-3-Clause"
] | 118 | 2015-03-24T16:09:42.000Z | 2022-03-21T09:01:59.000Z | daemon/armnn/IGlobalState.h | rossburton/gator | 9d8d75fa08352470c51abc23fe3b314879bd8b78 | [
"BSD-3-Clause"
] | 26 | 2016-03-03T23:24:08.000Z | 2022-03-21T10:24:43.000Z | daemon/armnn/IGlobalState.h | rossburton/gator | 9d8d75fa08352470c51abc23fe3b314879bd8b78 | [
"BSD-3-Clause"
] | 73 | 2015-06-09T09:44:06.000Z | 2021-12-30T09:49:00.000Z | /* Copyright (C) 2019-2020 by Arm Limited. All rights reserved. */
#pragma once
#include "armnn/CaptureMode.h"
#include "armnn/ICounterDirectoryConsumer.h"
#include "lib/Optional.h"
#include <memory>
#include <string>
#include <tuple>
#include <vector>
namespace armnn {
struct EventId {
std::string category;
lib::Optional<std::string> device;
lib::Optional<std::string> counterSet;
std::string name;
};
inline bool operator==(const EventId & lhs, const EventId & rhs)
{
return std::tie(lhs.category, lhs.device, lhs.counterSet, lhs.name) ==
std::tie(rhs.category, rhs.device, rhs.counterSet, rhs.name);
}
inline bool operator<(const EventId & lhs, const EventId & rhs)
{
if (lhs.category < rhs.category) {
return true;
}
if (lhs.category > rhs.category) {
return false;
}
if (lhs.device < rhs.device) {
return true;
}
if (lhs.device > rhs.device) {
return false;
}
if (lhs.counterSet < rhs.counterSet) {
return true;
}
if (lhs.counterSet > rhs.counterSet) {
return false;
}
return lhs.name < rhs.name;
}
struct EventProperties {
std::uint16_t counterSetCount;
ICounterDirectoryConsumer::Class clazz;
ICounterDirectoryConsumer::Interpolation interpolation;
double multiplier;
std::string description;
std::string units;
};
inline bool operator==(const EventProperties & lhs, const EventProperties & rhs)
{
return std::tie(lhs.counterSetCount,
lhs.clazz,
lhs.interpolation,
lhs.multiplier,
lhs.description,
lhs.units) ==
std::tie(rhs.counterSetCount, rhs.clazz, rhs.interpolation, rhs.multiplier, rhs.description, rhs.units);
}
using EventKeyMap = std::map<armnn::EventId, int>;
/**
* Interface for class that listens for state changes on the session, provides access to global state
* All methods in this interface should be multithread safe
*/
class IGlobalState {
public:
virtual ~IGlobalState() = default;
/** @return A map from global event id to APC counter key */
virtual EventKeyMap getRequestedCounters() const = 0;
/** @return The requested capture mode */
virtual CaptureMode getCaptureMode() const = 0;
/** @return The requested sample period */
virtual std::uint32_t getSamplePeriod() const = 0;
/**
* Notify the global state of a set of events available from an armnn Session
*/
virtual void addEvents(std::vector<std::tuple<EventId, EventProperties>>) = 0;
};
}
| 29.222222 | 119 | 0.587971 | [
"vector"
] |
3fd05e8c5c9de4fde313d502829b004709d2cf60 | 13,869 | c | C | programs/xphelloworld/xpsimplehelloworld/xpsimplehelloworld.c | sourcecode-reloaded/Xming | b9f2e99d00f9445a29803d622d24b5314ee35991 | [
"X11",
"MIT"
] | 4 | 2020-08-21T04:21:14.000Z | 2022-01-15T11:26:11.000Z | programs/xphelloworld/xpsimplehelloworld/xpsimplehelloworld.c | sourcecode-reloaded/Xming | b9f2e99d00f9445a29803d622d24b5314ee35991 | [
"X11",
"MIT"
] | 1 | 2020-02-23T19:22:52.000Z | 2020-02-23T19:22:52.000Z | programs/xphelloworld/xpsimplehelloworld/xpsimplehelloworld.c | talregev/Xming | e7a997e3c6441c572df6953468fd8e88ca9e07e7 | [
"X11",
"MIT"
] | 3 | 2020-12-18T06:33:36.000Z | 2022-02-22T16:25:50.000Z | /*
* $Xorg: xphelloworld.c,v 1.2 2002/05/10 06:54:^1 gisburn Exp $
*
* xphelloworld - Xprint version of hello world
*
*
Copyright 2002-2004 Roland Mainz <roland.mainz@nrubsig.org>
All Rights Reserved.
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
OPEN GROUP 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.
Except as contained in this notice, the name of The Open Group shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from The Open Group.
*
* Author: Roland Mainz <roland.mainz@nrubsig.org>
*/
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/XprintUtil/xprintutil.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
/* Turn a NULL pointer string into an empty string */
#define NULLSTR(x) (((x)!=NULL)?(x):(""))
#define Log(x) { if(verbose) printf x; }
#define Msg(x) { if(!quiet) printf x; }
static const char *ProgramName; /* program name (from argv[0]) */
static Bool verbose = False; /* verbose output what the program is doing */
Bool quiet = False; /* be quiet (no output except errors) */
static
void usage(void)
{
fprintf (stderr, "usage: %s [options]\n", ProgramName);
fprintf (stderr, "-printer printernname\tprinter to use\n");
fprintf (stderr, "-printfile file\tprint to file instead of printer\n");
fprintf (stderr, "-embedpsl2data string\tPostScript level 2 fragment to embed\n"
"\t\t(use 'xppsembeddemo1' to embed demo data)\n");
fprintf (stderr, "-v\tverbose output\n");
fprintf (stderr, "-q\tbe quiet (no output except errors)\n");
fprintf (stderr, "\n");
exit(EXIT_FAILURE);
}
/* strstr(), case-insensitive */
static
char *str_case_str(const char *s, const char *find)
{
size_t len;
char c,
sc;
if ((c = tolower(*find++)) != '\0')
{
len = strlen(find);
do
{
do
{
if ((sc = tolower(*s++)) == '\0')
return NULL;
} while (sc != c);
} while (strncasecmp(s, find, len) != 0);
s--;
}
return ((char *)s);
}
static
int do_hello_world(const char *printername, const char *printerfile, const char *psembeddata )
{
Display *pdpy; /* X connection */
XPContext pcontext; /* Xprint context */
void *printtofile_handle; /* "context" when printing to file */
int xp_event_base, /* XpExtension even base */
xp_error_base; /* XpExtension error base */
long dpi_x = 0L,
dpi_y = 0L;
Screen *pscreen;
int pscreennumber;
Window pwin;
XGCValues gcvalues;
GC pgc;
unsigned short dummy;
XRectangle winrect;
char fontname[256]; /* BUG: is this really big enougth ? */
XFontStruct *font;
char *scr;
if( XpuGetPrinter(printername, &pdpy, &pcontext) != 1 )
{
fprintf(stderr, "Cannot open printer '%s'\n", printername);
return(EXIT_FAILURE);
}
if( XpQueryExtension(pdpy, &xp_event_base, &xp_error_base) == False )
{
fprintf(stderr, "XpQueryExtension() failed.\n");
XpuClosePrinterDisplay(pdpy, pcontext);
return(EXIT_FAILURE);
}
/* Listen to XP(Start|End)(Job|Doc|Page)Notify events).
* This is mantatory as Xp(Start|End)(Job|Doc|Page) functions are _not_
* syncronous !!
* Not waiting for such events may cause that subsequent data may be
* destroyed/corrupted!!
*/
XpSelectInput(pdpy, pcontext, XPPrintMask);
/* Set job title */
XpuSetJobTitle(pdpy, pcontext, "Hello world for Xprint");
/* Set print context
* Note that this modifies the available fonts, including builtin printer prints.
* All XListFonts()/XLoadFont() stuff should be done _after_ setting the print
* context to obtain the proper fonts.
*/
XpSetContext(pdpy, pcontext);
/* Get default printer reolution */
if( XpuGetResolution(pdpy, pcontext, &dpi_x, &dpi_y) != 1 )
{
fprintf(stderr, "No default resolution for printer '%s'.\n", printername);
XpuClosePrinterDisplay(pdpy, pcontext);
return(EXIT_FAILURE);
}
if( printerfile )
{
Log(("starting job (to file '%s').\n", printerfile));
printtofile_handle = XpuStartJobToFile(pdpy, pcontext, printerfile);
if( !printtofile_handle )
{
fprintf(stderr, "%s: Error: %s while trying to print to file.\n",
ProgramName, strerror(errno));
XpuClosePrinterDisplay(pdpy, pcontext);
return(EXIT_FAILURE);
}
XpuWaitForPrintNotify(pdpy, xp_event_base, XPStartJobNotify);
}
else
{
Log(("starting job.\n"));
XpuStartJobToSpooler(pdpy);
XpuWaitForPrintNotify(pdpy, xp_event_base, XPStartJobNotify);
}
#ifdef MULTIPLE_DOCUMENTS_IN_ONE_JOB
/* Start document (one job can contain any number of "documents")
* XpStartDoc() isn't mandatory if job only contains one document - first
* XpStartPage() will generate a "synthetic" XpStartDoc() if one had not
* already been done.
*/
XpStartDoc(pdpy, XPDocNormal);
XpuWaitForPrintNotify(pdpy, xp_event_base, XPStartDocNotify);
#endif /* MULTIPLE_DOCUMENTS_IN_ONE_JOB */
pscreen = XpGetScreenOfContext(pdpy, pcontext);
pscreennumber = XScreenNumberOfScreen(pscreen);
/* Obtain some info about page geometry */
XpGetPageDimensions(pdpy, pcontext, &dummy, &dummy, &winrect);
pwin = XCreateSimpleWindow(pdpy, XRootWindowOfScreen(pscreen),
winrect.x, winrect.y, winrect.width, winrect.height,
10,
XBlackPixel(pdpy, pscreennumber),
XWhitePixel(pdpy, pscreennumber));
gcvalues.background = XWhitePixel(pdpy, pscreennumber);
gcvalues.foreground = XBlackPixel(pdpy, pscreennumber);
pgc = XCreateGC(pdpy, pwin, GCBackground|GCForeground, &gcvalues);
Log(("start page.\n"));
XpStartPage(pdpy, pwin);
XpuWaitForPrintNotify(pdpy, xp_event_base, XPStartPageNotify);
/* Mapping the window inside XpStartPage()/XpEndPage()
* Set XCreateWindow/border_width to 0 or move XMapWindow in front of
* XpStartPage() to get rid of the surrounding black border lines.
* (This is usually done before XpStartPage() in real applications)
*/
XMapWindow(pdpy, pwin);
/* usual rendering stuff..... */
sprintf(fontname, "-*-*-*-*-*-*-*-180-%ld-%ld-*-*-iso8859-1", dpi_x, dpi_y);
font = XLoadQueryFont(pdpy, fontname);
XSetFont(pdpy, pgc, font->fid);
XDrawString(pdpy, pwin, pgc, 100, 100, "hello world from X11 print system", 33);
#define DO_EMBED_TEST 1
#ifdef DO_EMBED_TEST
if( psembeddata )
{
char *embedded_formats_supported;
embedded_formats_supported = XpGetOneAttribute(pdpy, pcontext, XPPrinterAttr, "xp-embedded-formats-supported");
Log(("psembed: xp-embedded-formats-supported='%s'\n", NULLSTR(embedded_formats_supported)));
/* MAX(XExtendedMaxRequestSize(pdpy), XMaxRequestSize(pdpy)) defines the
* maximum length of emebdded PostScript data which can be send in one
* step using XpPutDocumentData() */
Log(("psembed: XExtendedMaxRequestSize=%ld\n", (long)XExtendedMaxRequestSize(pdpy)));
Log(("psembed: XMaxRequestSize=%ld\n", (long)XMaxRequestSize(pdpy)));
/* Should we embed the demo ? */
if( !strcmp(psembeddata, "xppsembeddemo1") )
{
Log(("psembed: Using PS embedding demo 1\n"));
psembeddata = "newpath\n270 360 moveto\n 0 72 rlineto\n"
"72 0 rlineto\n 0 -72 rlineto\n closepath\n fill\n";
}
else
{
Log(("psembed: Using user PS embedding data = '%s'\n", psembeddata));
}
/* Check whether "PostScript Level 2" is supported as embedding format
* (The content of the "xp-embedded-formats-supported" attribute needs
* to be searched in a case-insensitive way since the model-configs
* may use the same word with multiple variants of case
* (e.g. "PostScript" vs. "Postscript" or "PCL" vs. "Pcl" etc.")
* To avoid problems we simply use |str_case_str()| (case-insensitive
* strstr()) instead of |strstr()| here...)
*/
if( embedded_formats_supported &&
(str_case_str(embedded_formats_supported, "PostScript 2") != NULL) )
{
/* Note that the emebdded PostScript code uses the same resolution and
* coordinate space as currently be used by the DDX (if you don not
* want that simply reset it yourself :) */
char *test = (char *)psembeddata;
int test_len = strlen(test);
char *type = "PostScript 2"; /* Format of embedded data
* (older PS DDX may be picky, fixed via
* http://xprint.mozdev.org/bugs/show_bug.cgi?id=4023)
*/
char *option = ""; /* PostScript DDX does not support any options yet
* (in general |BadValue| will be returned for not
* supported options/option values) */
XpPutDocumentData(pdpy, pwin, test, test_len, type, option);
}
else
{
Log(("psembed: error: cannot embed data, 'PostScript 2' not supported as embedded data format for this printer\n"));
}
}
#endif /* DO_EMBED_TEST */
XpEndPage(pdpy);
XpuWaitForPrintNotify(pdpy, xp_event_base, XPEndPageNotify);
Log(("end page.\n"));
#ifdef DO_SOME_MORE_RENDERING
XpStartPage(pdpy);
XpuWaitForPrintNotify(pdpy, xp_event_base, XPStartPageNotify);
/* some more rendering..... */
XpEndPage(pdpy);
XpuWaitForPrintNotify(pdpy, xp_event_base, XPEndPageNotify);
#endif /* DO_SOME_MORE_RENDERING */
#ifdef MULTIPLE_DOCUMENTS_IN_ONE_JOB
/* End document. Do _not_ use it if you did not explicitly used
* XpStartDoc() above (e.g. if XpStartDoc() was triggered by first
* XpStartPage() - see comment about XpStartDoc() above...
*/
XpEndDoc(pdpy);
XpuWaitForPrintNotify(pdpy, xp_event_base, XPEndDocNotify);
#endif /* MULTIPLE_DOCUMENTS_IN_ONE_JOB */
/* End the print job - the final results are sent by the X print
* server to the spooler sub system.
*/
XpEndJob(pdpy);
XpuWaitForPrintNotify(pdpy, xp_event_base, XPEndJobNotify);
Log(("end job.\n"));
if( printerfile )
{
if( XpuWaitForPrintFileChild(printtofile_handle) != XPGetDocFinished )
{
fprintf(stderr, "%s: Error while printing to file.\n", ProgramName);
XpuClosePrinterDisplay(pdpy, pcontext);
return(EXIT_FAILURE);
}
}
/* End of spooled job - get spooler command results and print them */
scr = XpGetOneAttribute(pdpy, pcontext, XPJobAttr, "xp-spooler-command-results");
if( scr )
{
if( strlen(scr) > 0 )
{
const char *msg = XpuCompoundTextToXmb(pdpy, scr);
if( msg )
{
Msg(("Spooler command returned '%s'.\n", msg));
XpuFreeXmbString(msg);
}
else
{
Msg(("Spooler command returned '%s' (unconverted).\n", scr));
}
}
XFree((void *)scr);
}
XpuClosePrinterDisplay(pdpy, pcontext);
return(EXIT_SUCCESS);
}
int main (int argc, char *argv[])
{
const char *printername = NULL; /* printer to query */
const char *toFile = NULL; /* output file (instead of printer) */
const char *embedpsl2data = NULL; /* PS Level 2 code fragment for embedding in output */
XPPrinterList plist; /* list of printers */
int plist_count; /* number of entries in |plist|-array */
int i;
int retval;
ProgramName = argv[0];
for (i = 1; i < argc; i++)
{
char *arg = argv[i];
int len = strlen(arg);
if (!strncmp("-printer", arg, len))
{
if (++i >= argc)
usage();
printername = argv[i];
}
else if (!strncmp("-printfile", arg, len))
{
if (++i >= argc)
usage();
toFile = argv[i];
}
else if (!strncmp("-embedpsl2data", arg, len))
{
if (++i >= argc)
usage();
embedpsl2data = argv[i];
}
else if (!strncmp("-v", arg, len))
{
verbose = True;
quiet = False;
}
else if (!strncmp("-q", arg, len))
{
verbose = False;
quiet = True;
}
else
{
usage();
}
}
plist = XpuGetPrinterList(printername, &plist_count);
if (!plist) {
fprintf(stderr, "%s: no printers found for printer spec \"%s\".\n",
ProgramName, NULLSTR(printername));
exit(EXIT_FAILURE);
}
Log(("Using printer '%s'\n", plist[0].name));
retval = do_hello_world(plist[0].name, toFile, embedpsl2data);
XpuFreePrinterList(plist);
return(retval);
}
| 34.160099 | 124 | 0.605812 | [
"geometry",
"model"
] |
3fd09f0e27418c717e8c28eb8ec1aa56c262c440 | 1,730 | c | C | d/underdark/mon/warrior1.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-07-19T05:24:44.000Z | 2021-11-18T04:08:19.000Z | d/underdark/mon/warrior1.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 4 | 2021-03-15T18:56:39.000Z | 2021-08-17T17:08:22.000Z | d/underdark/mon/warrior1.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-09-12T06:22:38.000Z | 2022-01-31T01:15:12.000Z | #include <std.h>
#include "../underdark.h";
inherit MONSTER;
void create() {
::create();
set_name("drow");
set_id(({"drow","warrior","drow warrior"}));
set_short("%^BOLD%^%^BLACK%^Drow Warrior%^RESET%^");
set_long(
"%^BOLD%^%^BLACK%^Pointy ears, angular features, and slender form are among the identical features these drow have in common with the surface elves. However, the red glowing eyes and dark skin are the obvious and among the few physical differences that seperate drow from elf. These drow must be from some nearby city as they are geared for battle and appear to be standing guard."
);
set_class("fighter");
set_guild_level("fighter",15);
set_mlevel("fighter",15);
set_race("drow");
set_body_type("humanoid");
set_gender("male");
set_hd(15,6);
set_alignment(9);
set_max_hp(187);
set_hp(187);
set_overall_ac(0);
set_size(2);
set_exp(9000);
set_property("full attacks",1);
set_mob_magic_resistance("average");
set_stats("strength",16);
set_stats("dexterity", 18);
set_stats("wisdom",11);
set_stats("dexterity",18);
set_stats("constitution",15);
set_stats("charisma",9);
set_stats("intelligence",15);
new(BLACKDAGGER)->move(TO);
new(BLACKSWORD)->move(TO);
new(OBJ+"slboots")->move(TO);
new(OBJ+"dchain")->move(TO);
command("wield dagger");
command("wield sword");
command("wear boots");
command("wear chain");
set_funcs( ({"flashit","rushit","rushit"}) );
set_func_chance(45);
add_search_path("/cmds/fighter");
set("aggressive", 25);
}
void rushit(object targ) {
TO->force_me("rush "+targ->query_name());
}
void flashit(object targ) {
TO->force_me("flash "+targ->query_name());
}
| 30.350877 | 387 | 0.665318 | [
"object"
] |
3fd15799c08e21bb25dd94fd06f116734657ad56 | 5,944 | h | C | tensorflow/lite/delegates/gpu/cl/kernels/fully_connected.h | zjzh/tensorflow | 5b40fe4db7c889b3969807209171d44a5773b9a4 | [
"Apache-2.0"
] | null | null | null | tensorflow/lite/delegates/gpu/cl/kernels/fully_connected.h | zjzh/tensorflow | 5b40fe4db7c889b3969807209171d44a5773b9a4 | [
"Apache-2.0"
] | null | null | null | tensorflow/lite/delegates/gpu/cl/kernels/fully_connected.h | zjzh/tensorflow | 5b40fe4db7c889b3969807209171d44a5773b9a4 | [
"Apache-2.0"
] | 1 | 2020-09-17T02:44:40.000Z | 2020-09-17T02:44:40.000Z | /* Copyright 2019 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_LITE_DELEGATES_GPU_CL_KERNELS_FULLY_CONNECTED_H_
#define TENSORFLOW_LITE_DELEGATES_GPU_CL_KERNELS_FULLY_CONNECTED_H_
#include <string>
#include <utility>
#include <vector>
#include "absl/memory/memory.h"
#include "tensorflow/lite/delegates/gpu/cl/arguments.h"
#include "tensorflow/lite/delegates/gpu/cl/buffer.h"
#include "tensorflow/lite/delegates/gpu/cl/cl_kernel.h"
#include "tensorflow/lite/delegates/gpu/cl/device_info.h"
#include "tensorflow/lite/delegates/gpu/cl/kernels/gpu_operation.h"
#include "tensorflow/lite/delegates/gpu/cl/kernels/tuning_parameters.h"
#include "tensorflow/lite/delegates/gpu/cl/linear_storage.h"
#include "tensorflow/lite/delegates/gpu/cl/precision.h"
#include "tensorflow/lite/delegates/gpu/common/data_type.h"
#include "tensorflow/lite/delegates/gpu/common/operations.h"
#include "tensorflow/lite/delegates/gpu/common/shape.h"
#include "tensorflow/lite/delegates/gpu/common/tensor.h"
#include "tensorflow/lite/delegates/gpu/common/types.h"
#include "tensorflow/lite/delegates/gpu/common/util.h"
namespace tflite {
namespace gpu {
namespace cl {
template <DataType T, typename S>
void RearrangeFCWeightsToIOO4I4(const tflite::gpu::Tensor<OHWI, T>& weights,
S* dst) {
const int src_channels = weights.shape.i;
const int padded_src_channels = AlignByN(src_channels, 4);
const int dst_channels = weights.shape.o;
const int padded_dst_channels = AlignByN(dst_channels, 4);
// Change the travelsal order of the weight matrix in such a way that the
// first 4 elements of all rows are scanned first, followed by elements 5 to 8
// of all rows, then elements 9 to 12 of all rows, and so on. As an example,
// an 8x8 matrix would be traversed as below.
//
// | 0 1 2 3 32 33 34 35 |
// | 4 5 6 7 36 37 38 39 |
// | 8 9 10 11 40 41 42 43 |
// | 12 13 14 15 44 45 46 47 |
// | 16 17 18 19 48 49 50 51 |
// | 20 21 22 23 52 53 54 55 |
// | 24 25 26 27 56 57 58 59 |
// | 28 29 30 31 60 61 62 63 |
//
// If (any) dimension of the weight matrix size is not divisible by 4, then
// the output is padded with zeros.
//
// The benefit of doing this is that reading contigous 16 elements gives a 4x4
// block of the matrix, where the first 4 elements is the first row of the
// block, second 4 elements is the second row of the block, etc.
for (int y = 0; y < padded_dst_channels; y++) {
for (int block_x = 0; 4 * block_x < padded_src_channels; block_x++) {
for (int x_in_block = 0; x_in_block < 4; x_in_block++) {
int x = 4 * block_x + x_in_block;
int dst_index = padded_dst_channels * 4 * block_x + 4 * y + x_in_block;
if (x < src_channels && y < dst_channels) {
dst[dst_index] = weights.data[src_channels * y + x];
} else {
dst[dst_index] = 0.0f;
}
}
}
}
}
class FullyConnected : public GPUOperation {
public:
FullyConnected() = default;
void GetPossibleKernelWorkGroups(
TuningType tuning_type, const DeviceInfo& device_info,
const KernelInfo& kernel_info,
std::vector<int3>* work_groups) const override {
work_groups->push_back(work_group_size_);
}
int3 GetGridSize() const override;
// Move only
FullyConnected(FullyConnected&& kernel);
FullyConnected& operator=(FullyConnected&& kernel);
FullyConnected(const FullyConnected&) = delete;
FullyConnected& operator=(const FullyConnected&) = delete;
private:
FullyConnected(const OperationDef& definition, const DeviceInfo& device_info);
friend FullyConnected CreateFullyConnected(
const DeviceInfo& device_info, const OperationDef& definition,
const FullyConnectedAttributes& attr);
template <DataType T>
void UploadWeights(const tflite::gpu::Tensor<OHWI, T>& weights);
std::string GetFullyConnectedKernelCode(const OperationDef& op_def,
const int3& work_group_size);
};
template <DataType T>
void FullyConnected::UploadWeights(
const tflite::gpu::Tensor<OHWI, T>& weights) {
const int src_depth = DivideRoundUp(weights.shape.i, 4);
const int dst_depth = DivideRoundUp(weights.shape.o, 4);
const int elements_count = src_depth * dst_depth * 4;
const bool f32_weights = definition_.precision == CalculationsPrecision::F32;
const int float4_size = f32_weights ? 16 : 8;
BufferDescriptor desc;
desc.element_type = f32_weights ? DataType::FLOAT32 : DataType::FLOAT16;
desc.element_size = 16;
desc.size = float4_size * elements_count;
desc.data.resize(desc.size);
if (f32_weights) {
float* ptr = reinterpret_cast<float*>(desc.data.data());
RearrangeFCWeightsToIOO4I4(weights, ptr);
} else {
half* ptr = reinterpret_cast<half*>(desc.data.data());
RearrangeFCWeightsToIOO4I4(weights, ptr);
}
args_.AddObject("weights",
absl::make_unique<BufferDescriptor>(std::move(desc)));
}
FullyConnected CreateFullyConnected(const DeviceInfo& device_info,
const OperationDef& definition,
const FullyConnectedAttributes& attr);
} // namespace cl
} // namespace gpu
} // namespace tflite
#endif // TENSORFLOW_LITE_DELEGATES_GPU_CL_KERNELS_FULLY_CONNECTED_H_
| 38.348387 | 80 | 0.699865 | [
"shape",
"vector"
] |
3fd7f8dbfa4babbd1e5e8beed6d5b409687071cb | 4,017 | h | C | src/connectivity/network/mdns/service/common/type_converters.h | fabio-d/fuchsia-stardock | e57f5d1cf015fe2294fc2a5aea704842294318d2 | [
"BSD-2-Clause"
] | 5 | 2022-01-10T20:22:17.000Z | 2022-01-21T20:14:17.000Z | src/connectivity/network/mdns/service/common/type_converters.h | fabio-d/fuchsia-stardock | e57f5d1cf015fe2294fc2a5aea704842294318d2 | [
"BSD-2-Clause"
] | null | null | null | src/connectivity/network/mdns/service/common/type_converters.h | fabio-d/fuchsia-stardock | e57f5d1cf015fe2294fc2a5aea704842294318d2 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SRC_CONNECTIVITY_NETWORK_MDNS_SERVICE_COMMON_TYPE_CONVERTERS_H_
#define SRC_CONNECTIVITY_NETWORK_MDNS_SERVICE_COMMON_TYPE_CONVERTERS_H_
#include <fuchsia/net/mdns/cpp/fidl.h>
#include <lib/syslog/cpp/macros.h>
#include "lib/fidl/cpp/type_converter.h"
#include "src/connectivity/network/mdns/service/common/types.h"
#include "src/lib/fsl/types/type_converters.h"
namespace fidl {
template <>
struct TypeConverter<mdns::Media, fuchsia::net::mdns::Media> {
static mdns::Media Convert(fuchsia::net::mdns::Media value) {
switch (value) {
case fuchsia::net::mdns::Media::WIRED:
return mdns::Media::kWired;
case fuchsia::net::mdns::Media::WIRELESS:
return mdns::Media::kWireless;
default:
FX_DCHECK(value == (fuchsia::net::mdns::Media::WIRED | fuchsia::net::mdns::Media::WIRELESS))
<< "Unrecognized fuchsia::net::mdns::Media value " << static_cast<uint32_t>(value);
return mdns::Media::kBoth;
}
}
};
template <>
struct TypeConverter<mdns::IpVersions, fuchsia::net::mdns::IpVersions> {
static mdns::IpVersions Convert(fuchsia::net::mdns::IpVersions value) {
switch (value) {
case fuchsia::net::mdns::IpVersions::V4:
return mdns::IpVersions::kV4;
case fuchsia::net::mdns::IpVersions::V6:
return mdns::IpVersions::kV6;
default:
FX_DCHECK(value ==
(fuchsia::net::mdns::IpVersions::V4 | fuchsia::net::mdns::IpVersions::V6));
return mdns::IpVersions::kBoth;
}
}
};
template <>
struct TypeConverter<fuchsia::net::mdns::ServiceInstancePublicationCause, mdns::PublicationCause> {
static fuchsia::net::mdns::ServiceInstancePublicationCause Convert(mdns::PublicationCause value) {
switch (value) {
case mdns::PublicationCause::kAnnouncement:
return fuchsia::net::mdns::ServiceInstancePublicationCause::ANNOUNCEMENT;
case mdns::PublicationCause::kQueryMulticastResponse:
return fuchsia::net::mdns::ServiceInstancePublicationCause::QUERY_MULTICAST_RESPONSE;
case mdns::PublicationCause::kQueryUnicastResponse:
return fuchsia::net::mdns::ServiceInstancePublicationCause::QUERY_UNICAST_RESPONSE;
}
}
};
template <>
struct TypeConverter<fuchsia::net::mdns::PublicationCause, mdns::PublicationCause> {
static fuchsia::net::mdns::PublicationCause Convert(mdns::PublicationCause value) {
switch (value) {
case mdns::PublicationCause::kAnnouncement:
return fuchsia::net::mdns::PublicationCause::ANNOUNCEMENT;
case mdns::PublicationCause::kQueryMulticastResponse:
return fuchsia::net::mdns::PublicationCause::QUERY_MULTICAST_RESPONSE;
case mdns::PublicationCause::kQueryUnicastResponse:
return fuchsia::net::mdns::PublicationCause::QUERY_UNICAST_RESPONSE;
}
}
};
template <>
struct TypeConverter<std::vector<std::string>, std::vector<std::vector<uint8_t>>> {
static std::vector<std::string> Convert(const std::vector<std::vector<uint8_t>>& value) {
std::vector<std::string> result;
std::transform(
value.begin(), value.end(), std::back_inserter(result),
[](const std::vector<uint8_t>& bytes) { return std::string(bytes.begin(), bytes.end()); });
return result;
}
};
template <>
struct TypeConverter<std::vector<std::vector<uint8_t>>, std::vector<std::string>> {
static std::vector<std::vector<uint8_t>> Convert(const std::vector<std::string>& value) {
std::vector<std::vector<uint8_t>> result;
std::transform(value.begin(), value.end(), std::back_inserter(result),
[](const std::string& string) {
return std::vector<uint8_t>(string.data(), string.data() + string.size());
});
return result;
}
};
} // namespace fidl
#endif // SRC_CONNECTIVITY_NETWORK_MDNS_SERVICE_COMMON_TYPE_CONVERTERS_H_
| 39 | 100 | 0.696789 | [
"vector",
"transform"
] |
3fd9353a07fae83679f63c630bb07ef86de71e1e | 1,928 | h | C | gcc-build/i686-pc-linux-gnu/libjava/java/sql/SQLOutput.h | giraffe/jrate | 764bbf973d1de4e38f93ba9b9c7be566f1541e16 | [
"Xnet",
"Linux-OpenIB",
"X11"
] | 1 | 2021-06-15T05:43:22.000Z | 2021-06-15T05:43:22.000Z | gcc-build/i686-pc-linux-gnu/libjava/java/sql/SQLOutput.h | giraffe/jrate | 764bbf973d1de4e38f93ba9b9c7be566f1541e16 | [
"Xnet",
"Linux-OpenIB",
"X11"
] | null | null | null | gcc-build/i686-pc-linux-gnu/libjava/java/sql/SQLOutput.h | giraffe/jrate | 764bbf973d1de4e38f93ba9b9c7be566f1541e16 | [
"Xnet",
"Linux-OpenIB",
"X11"
] | null | null | null | // DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*-
#ifndef __java_sql_SQLOutput__
#define __java_sql_SQLOutput__
#pragma interface
#include <java/lang/Object.h>
#include <gcj/array.h>
extern "Java"
{
namespace java
{
namespace net
{
class URL;
}
namespace sql
{
class SQLOutput;
class Array;
class Struct;
class Clob;
class Blob;
class Ref;
class SQLData;
class Timestamp;
class Time;
class Date;
}
namespace math
{
class BigDecimal;
}
}
};
class ::java::sql::SQLOutput : public ::java::lang::Object
{
public:
virtual void writeString (::java::lang::String *) = 0;
virtual void writeBoolean (jboolean) = 0;
virtual void writeByte (jbyte) = 0;
virtual void writeShort (jshort) = 0;
virtual void writeInt (jint) = 0;
virtual void writeLong (jlong) = 0;
virtual void writeFloat (jfloat) = 0;
virtual void writeDouble (jdouble) = 0;
virtual void writeBigDecimal (::java::math::BigDecimal *) = 0;
virtual void writeBytes (jbyteArray) = 0;
virtual void writeDate (::java::sql::Date *) = 0;
virtual void writeTime (::java::sql::Time *) = 0;
virtual void writeTimestamp (::java::sql::Timestamp *) = 0;
virtual void writeCharacterStream (::java::io::Reader *) = 0;
virtual void writeAsciiStream (::java::io::InputStream *) = 0;
virtual void writeBinaryStream (::java::io::InputStream *) = 0;
virtual void writeObject (::java::sql::SQLData *) = 0;
virtual void writeRef (::java::sql::Ref *) = 0;
virtual void writeBlob (::java::sql::Blob *) = 0;
virtual void writeClob (::java::sql::Clob *) = 0;
virtual void writeStruct (::java::sql::Struct *) = 0;
virtual void writeArray (::java::sql::Array *) = 0;
virtual void writeURL (::java::net::URL *) = 0;
static ::java::lang::Class class$;
} __attribute__ ((java_interface));
#endif /* __java_sql_SQLOutput__ */
| 27.542857 | 65 | 0.643154 | [
"object"
] |
3fea4a15fd90b33da3ba0aba1e318f29135ab2f9 | 1,328 | h | C | Engine/include/Common/Transform.h | Proyecto03/Motor | 9e7f379f1f64bc911293434fdfb8aa18bb8f99ab | [
"MIT"
] | 1 | 2021-07-24T03:10:38.000Z | 2021-07-24T03:10:38.000Z | Engine/include/Common/Transform.h | Proyecto03/Motor | 9e7f379f1f64bc911293434fdfb8aa18bb8f99ab | [
"MIT"
] | null | null | null | Engine/include/Common/Transform.h | Proyecto03/Motor | 9e7f379f1f64bc911293434fdfb8aa18bb8f99ab | [
"MIT"
] | 2 | 2021-05-11T10:47:37.000Z | 2021-07-24T03:10:39.000Z | #pragma once
#ifndef _COMMON_TRANSFORM_H
#define _COMMON_TRANSFORM_H
#include "Component.h"
#include "Vector3.h"
#include <map>
#include <string>
//class Vector3;
class CommonManager;
class Transform : public Component {
private:
Vector3 _position;
Vector3 _velocity;
Vector3 _dimensions;
Vector3 _rotation;
public:
Transform();
Transform(const Vector3& pos, const Vector3& vel, const Vector3& dim, const Vector3& rotation);
virtual ~Transform();
virtual void init();
virtual void load(const nlohmann::json& params);
virtual void update(float deltaTime);
// position
//const Vector3& getPos();
const Vector3& getPos() const;
void setPos(const Vector3& pos);
void setPosX(double x);
void setPosY(double y);
void setPosZ(double z);
// rotation
//const Vector3& getRot();
const Vector3& getRot() const;
void setRot(Vector3 angle);
void setRotX(double x);
void setRotY(double y);
void setRotZ(double z);
// velocity
//const Vector3& getVel();
const Vector3& getVel() const;
void setVel(const Vector3& vel);
void setVelX(double x);
void setVelY(double y);
void setVelZ(double z);
//Dimensions
//const Vector3& getDimensions();
const Vector3& getDimensions() const;
void setDimensions(const Vector3 dim);
void setDimX(double x);
void setDimY(double y);
void setDimZ(double z);
};
#endif | 21.419355 | 96 | 0.732681 | [
"transform"
] |
3ff1edd0688fb62e0222eff1dd67bf09766e80f6 | 59,573 | h | C | Source/Services/Multiplayer/Manager/multiplayer_manager_internal.h | natiskan/xbox-live-api | 9e7e51e0863b5983c2aa334a7b0db579b3bdf1de | [
"MIT"
] | 118 | 2019-05-13T22:56:02.000Z | 2022-03-16T06:12:39.000Z | Source/Services/Multiplayer/Manager/multiplayer_manager_internal.h | aspavlov/xbox-live-api | 4bec6f92347d0ad6c85463b601821333de631e3a | [
"MIT"
] | 31 | 2019-05-07T13:09:28.000Z | 2022-01-26T10:02:59.000Z | Source/Services/Multiplayer/Manager/multiplayer_manager_internal.h | aspavlov/xbox-live-api | 4bec6f92347d0ad6c85463b601821333de631e3a | [
"MIT"
] | 48 | 2019-05-28T23:55:31.000Z | 2021-12-22T03:47:56.000Z | // Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#pragma once
#include <mutex>
#include <set>
#include "xbox_live_context_internal.h"
#include "multiplayer_internal.h"
#include "xsapi-c/multiplayer_manager_c.h"
typedef void* context_t;
struct XblMultiplayerEventArgs : public xbox::services::RefCounter, public std::enable_shared_from_this<XblMultiplayerEventArgs>
{
XblMultiplayerEventArgs() = default;
virtual ~XblMultiplayerEventArgs() = default;
private:
std::shared_ptr<xbox::services::RefCounter> GetSharedThis() override
{
return shared_from_this();
}
};
namespace xbox { namespace services { namespace multiplayer { namespace manager {
class MultiplayerMatchClient;
class MultiplayerClientManager;
class MultiplayerLocalUserManager;
class MultiplayerLobbyClient;
class MultiplayerGameClient;
class MultiplayerLocalUser;
enum class MultiplayerLocalUserLobbyState
{
Unknown,
Add,
Join,
InSession,
Leave,
Remove
};
enum class MultiplayerLocalUserGameState
{
Unknown,
PendingJoin,
Join,
InSession,
Leave
};
enum class PendingRequestType
{
SynchronizedChanges,
NonSynchronizedChanges
};
class MultiplayerMember
{
public:
MultiplayerMember();
MultiplayerMember(
_In_ const XblMultiplayerSessionMember* member,
_In_ bool isLocal,
_In_ bool isGameHost,
_In_ bool isLobbyHost,
_In_ bool isInLobby,
_In_ bool isInGame
);
uint32_t MemberId() const;
const xsapi_internal_string& TeamId() const;
const xsapi_internal_string& InitialTeam() const;
uint64_t Xuid() const;
const xsapi_internal_string& DebugGamertag() const;
bool IsLocal() const;
bool IsInLobby() const;
bool IsInGame() const;
XblMultiplayerSessionMemberStatus Status() const;
const xsapi_internal_string& ConnectionAddress() const;
const xsapi_internal_string& CustomPropertiesJson() const;
bool IsMemberOnSameDevice(
_In_ std::shared_ptr<MultiplayerMember> member
) const;
const xsapi_internal_string& DeviceToken() const;
static std::shared_ptr<MultiplayerMember> CreateFromSessionMember(
_In_ const XblMultiplayerSessionMember* member,
_In_ const std::shared_ptr<XblMultiplayerSession>& lobbySession,
_In_ const std::shared_ptr<XblMultiplayerSession>& gameSession,
_In_ const xsapi_internal_map<uint64_t, std::shared_ptr<MultiplayerLocalUser>>& xboxLiveContextMap
);
static std::shared_ptr<MultiplayerMember> CreateFromSessionMember(
_In_ const XblMultiplayerSessionMember* member,
_In_ const std::shared_ptr<XblMultiplayerSession>& lobbySession,
_In_ const std::shared_ptr<XblMultiplayerSession>& gameSession,
_In_ bool isLocal
);
XblMultiplayerManagerMember GetReference() const;
private:
xsapi_internal_string m_teamId;
xsapi_internal_string m_initialTeam;
uint32_t m_memberId;
uint64_t m_xuid;
xsapi_internal_string m_gamertag;
xsapi_internal_string m_deviceToken;
bool m_isLocal;
bool m_isInLobby;
bool m_isInGame;
XblMultiplayerSessionMemberStatus m_status;
xsapi_internal_string m_connectionAddress;
xsapi_internal_string m_jsonProperties;
};
class MultiplayerLobbySession
{
public:
MultiplayerLobbySession();
MultiplayerLobbySession(_In_ const MultiplayerLobbySession& other);
MultiplayerLobbySession(_In_ std::shared_ptr<MultiplayerClientManager> multiplayerClientManagerInstance);
MultiplayerLobbySession(
_In_ std::shared_ptr<XblMultiplayerSession> session,
_In_ std::shared_ptr<MultiplayerMember> host,
_In_ const xsapi_internal_vector<std::shared_ptr<MultiplayerMember>>& members,
_In_ const xsapi_internal_vector<std::shared_ptr<MultiplayerMember>>& localMmembers
);
~MultiplayerLobbySession();
const xsapi_internal_string& CorrelationId() const;
const XblMultiplayerSessionReference& SessionReference() const;
const xsapi_internal_vector<std::shared_ptr<MultiplayerMember>>& LocalMembers() const;
const xsapi_internal_vector<std::shared_ptr<MultiplayerMember>>& Members() const;
std::shared_ptr<MultiplayerMember> Host() const;
const xsapi_internal_string& CustomPropertiesJson() const;
const XblMultiplayerSessionConstants& SessionConstants() const;
HRESULT AddLocalUser(
_In_ xbox_live_user_t user
);
HRESULT RemoveLocalUser(
_In_ xbox_live_user_t user
);
HRESULT SetLocalMemberProperties(
_In_ xbox_live_user_t user,
_In_ const xsapi_internal_string& name,
_In_ const JsonValue& valueJson,
_In_opt_ context_t context = nullptr
);
HRESULT DeleteLocalMemberProperties(
_In_ xbox_live_user_t user,
_In_ const xsapi_internal_string& name,
_In_opt_ context_t context = nullptr
);
HRESULT SetLocalMemberConnectionAddress(
_In_ xbox_live_user_t user,
_In_ const xsapi_internal_string& connectionAddress,
_In_opt_ context_t context = nullptr
);
bool IsHost(
_In_ uint64_t xuid
);
HRESULT SetProperties(
_In_ const xsapi_internal_string& name,
_In_ const JsonValue& valueJson,
_In_opt_ context_t context = nullptr
);
HRESULT SetSynchronizedProperties(
_In_ const xsapi_internal_string& name,
_In_ const JsonValue& valueJson,
_In_opt_ context_t context = nullptr
);
HRESULT SetSynchronizedHost(
_In_ const xsapi_internal_string& hostDeviceToken,
_In_opt_ context_t context = nullptr
);
#if HC_PLATFORM_IS_MICROSOFT
HRESULT InviteFriends(
_In_ xbox_live_user_t user,
_In_ const xsapi_internal_string& contextStringId = xsapi_internal_string(),
_In_ const xsapi_internal_string& customActivationContext = xsapi_internal_string()
);
#endif
HRESULT InviteUsers(
_In_ xbox_live_user_t user,
_In_ const xsapi_internal_vector<uint64_t>& xuids,
_In_ const xsapi_internal_string& contextStringId = xsapi_internal_string(),
_In_ const xsapi_internal_string& customActivationContext = xsapi_internal_string()
);
uint64_t ChangeNumber() const;
void SetMultiplayerClientManager(
_In_ std::shared_ptr<MultiplayerClientManager> clientManager
);
void SetHost(_In_ std::shared_ptr<MultiplayerMember> hostMember);
#if defined(XSAPI_CPPWINRT)
#if HC_PLATFORM == HC_PLATFORM_XDK
// TODO is there a better way to do this?
HRESULT AddLocalUser(
_In_ winrt::Windows::Xbox::System::User user
)
{
return AddLocalUser(convert_user_to_cppcx(user));
}
HRESULT RemoveLocalUser(
_In_ winrt::Windows::Xbox::System::User user
)
{
return RemoveLocalUser(convert_user_to_cppcx(user));
}
HRESULT SetLocalMemberProperties(
_In_ winrt::Windows::Xbox::System::User user,
_In_ const xsapi_internal_string& name,
_In_ const JsonValue& valueJson,
_In_opt_ context_t context = nullptr
)
{
return SetLocalMemberProperties(
convert_user_to_cppcx(user),
name,
valueJson,
context
);
}
HRESULT DeleteLocalMemberProperties(
_In_ winrt::Windows::Xbox::System::User user,
_In_ const xsapi_internal_string& name,
_In_opt_ context_t context = nullptr
)
{
return DeleteLocalMemberProperties(
convert_user_to_cppcx(user),
name,
context
);
}
HRESULT SetLocalMemberConnectionAddress(
_In_ winrt::Windows::Xbox::System::User user,
_In_ const xsapi_internal_string& connectionAddress,
_In_opt_ context_t context = nullptr
)
{
return SetLocalMemberConnectionAddress(
convert_user_to_cppcx(user),
connectionAddress,
context
);
}
HRESULT InviteFriends(
_In_ winrt::Windows::Xbox::System::User user,
_In_ const xsapi_internal_string& contextStringId = xsapi_internal_string(),
_In_ const xsapi_internal_string& customActivationContext = xsapi_internal_string()
)
{
return InviteFriends(
convert_user_to_cppcx(user),
contextStringId,
customActivationContext
);
}
HRESULT InviteUsers(
_In_ winrt::Windows::Xbox::System::User user,
_In_ const xsapi_internal_vector<xsapi_internal_string>& xboxUserIds,
_In_ const xsapi_internal_string& contextStringId = xsapi_internal_string(),
_In_ const xsapi_internal_string& customActivationContext = xsapi_internal_string()
)
{
return InviteUsers(
convert_user_to_cppcx(user),
xboxUserIds,
contextStringId,
customActivationContext
);
}
#endif
#endif
private:
void DeepCopyConstants(const XblMultiplayerSessionConstants& other);
std::shared_ptr<MultiplayerClientManager> m_multiplayerClientManager;
xsapi_internal_string m_correlationId;
uint64_t m_changeNumber;
XblMultiplayerSessionReference m_sessionReference;
std::shared_ptr<MultiplayerMember> m_host;
xsapi_internal_vector<std::shared_ptr<MultiplayerMember>> m_members;
xsapi_internal_vector<std::shared_ptr<MultiplayerMember>> m_localMembers;
xsapi_internal_string m_customPropertiesJson;
XblMultiplayerSessionConstants m_sessionConstants{};
xsapi_internal_vector<uint64_t> m_initiatorXuids;
XblMultiplayerMemberInitialization m_memberInitialization{};
xsapi_internal_string m_constantsCustomJson;
xsapi_internal_string m_constantsCloudComputePackageJson;
xsapi_internal_string m_constantsMeasurementServerAddressesJson;
};
class MultiplayerGameSession
{
public:
MultiplayerGameSession();
MultiplayerGameSession(_In_ const MultiplayerGameSession& other);
MultiplayerGameSession(
_In_ std::shared_ptr<XblMultiplayerSession> session,
_In_ std::shared_ptr<MultiplayerMember> host,
_In_ xsapi_internal_vector<std::shared_ptr<MultiplayerMember>> members
);
const xsapi_internal_string& CorrelationId() const;
const XblMultiplayerSessionReference& SessionReference() const;
const xsapi_internal_vector<std::shared_ptr<MultiplayerMember>>& Members() const;
std::shared_ptr<MultiplayerMember> Host() const;
const xsapi_internal_string& Properties() const;
const XblMultiplayerSessionConstants& SessionConstants() const;
bool IsHost(
_In_ uint64_t xuid
);
HRESULT SetProperties(
_In_ const xsapi_internal_string& name,
_In_ const JsonValue& valueJson,
_In_opt_ context_t context = nullptr
);
HRESULT SetSynchronizedProperties(
_In_ const xsapi_internal_string& name,
_In_ const JsonValue& valueJson,
_In_opt_ context_t context = nullptr
);
HRESULT SetSynchronizedHost(
_In_ const xsapi_internal_string& deviceToken,
_In_opt_ context_t context = nullptr
);
uint64_t ChangeNumber() const;
void SetMultiplayerClientManager(
_In_ std::shared_ptr<MultiplayerClientManager> clientManager
);
void SetHost(_In_ std::shared_ptr<MultiplayerMember> hostMember);
private:
void DeepCopyConstants(const XblMultiplayerSessionConstants& other);
xsapi_internal_string m_correlationId;
uint64_t m_changeNumber;
XblMultiplayerSessionReference m_sessionReference;
std::shared_ptr<MultiplayerMember> m_host;
xsapi_internal_vector<std::shared_ptr<MultiplayerMember>> m_members;
xsapi_internal_string m_properties;
std::shared_ptr<MultiplayerClientManager> m_multiplayerClientManager;
// Constants
XblMultiplayerSessionConstants m_sessionConstants;
xsapi_internal_vector<uint64_t> m_initiatorXuids;
XblMultiplayerMemberInitialization m_memberInitialization;
xsapi_internal_string m_constantsCustomJson;
xsapi_internal_string m_constantsCloudComputePackageJson;
xsapi_internal_string m_constantsMeasurementServerAddressesJson;
};
struct UserAddedEventArgs : public XblMultiplayerEventArgs
{
UserAddedEventArgs(_In_ uint64_t xuid) : Xuid(xuid) {}
uint64_t Xuid;
};
struct UserRemovedEventArgs : public XblMultiplayerEventArgs
{
UserRemovedEventArgs(_In_ uint64_t xuid) : Xuid(xuid) {}
uint64_t Xuid;
};
struct MemberJoinedEventArgs : public XblMultiplayerEventArgs
{
MemberJoinedEventArgs(const _In_ xsapi_internal_vector<std::shared_ptr<MultiplayerMember>>& members) : Members(members) {}
xsapi_internal_vector<std::shared_ptr<MultiplayerMember>> Members;
};
struct MemberLeftEventArgs : public XblMultiplayerEventArgs
{
MemberLeftEventArgs(const _In_ xsapi_internal_vector<std::shared_ptr<MultiplayerMember>>& members) : Members(members) {}
xsapi_internal_vector<std::shared_ptr<MultiplayerMember>> Members;
};
struct HostChangedEventArgs : public XblMultiplayerEventArgs
{
HostChangedEventArgs(_In_ std::shared_ptr<MultiplayerMember> hostMember) : HostMember(hostMember) {}
std::shared_ptr<MultiplayerMember> HostMember;
};
struct MemberPropertyChangedEventArgs : public XblMultiplayerEventArgs
{
MemberPropertyChangedEventArgs(
_In_ std::shared_ptr<MultiplayerMember> member,
_In_ const xsapi_internal_string& jsonProperties
) : Member(member),
Properties(jsonProperties)
{
}
std::shared_ptr<MultiplayerMember> Member;
xsapi_internal_string Properties;
};
struct SessionPropertyChangedEventArgs : public XblMultiplayerEventArgs
{
SessionPropertyChangedEventArgs(_In_ const xsapi_internal_string& jsonProperties) : Properties(jsonProperties) {}
xsapi_internal_string Properties;
};
struct JoinLobbyCompletedEventArgs : public XblMultiplayerEventArgs
{
JoinLobbyCompletedEventArgs(_In_ uint64_t xuid) : Xuid(xuid) {}
uint64_t Xuid;
};
struct FindMatchCompletedEventArgs : public XblMultiplayerEventArgs
{
FindMatchCompletedEventArgs(
_In_ XblMultiplayerMatchStatus status,
_In_ XblMultiplayerMeasurementFailure failure
) : MatchStatus(status),
InitializationFailure(failure)
{
}
XblMultiplayerMatchStatus MatchStatus;
XblMultiplayerMeasurementFailure InitializationFailure;
};
struct PerformQosMeasurementsEventArgs : public XblMultiplayerEventArgs
{
PerformQosMeasurementsEventArgs() { }
~PerformQosMeasurementsEventArgs()
{
for (auto& client : remoteClients)
{
Delete(client.connectionAddress);
}
}
void AddRemoteClient(const xsapi_internal_string& connectionAddress, const xsapi_internal_string& deviceToken)
{
XblMultiplayerConnectionAddressDeviceTokenPair client{};
client.connectionAddress = Make(connectionAddress);
utils::strcpy(client.deviceToken.Value, sizeof(client.deviceToken.Value), deviceToken.data());
remoteClients.push_back(std::move(client));
}
xsapi_internal_vector<XblMultiplayerConnectionAddressDeviceTokenPair> remoteClients;
};
class MultiplayerEventQueue
{
public:
MultiplayerEventQueue();
MultiplayerEventQueue(const MultiplayerEventQueue& other);
MultiplayerEventQueue& operator=(MultiplayerEventQueue other);
~MultiplayerEventQueue();
size_t Size() const;
bool Empty() const;
void Clear();
xsapi_internal_vector<XblMultiplayerEvent>::const_iterator begin() const;
xsapi_internal_vector<XblMultiplayerEvent>::const_iterator end() const;
void AddEvent(
_In_ XblMultiplayerEventType eventType,
_In_ XblMultiplayerSessionType sessionType,
_In_ std::shared_ptr<XblMultiplayerEventArgs> eventArgs = nullptr,
_In_ Result<void> error = {},
_In_opt_ context_t context = nullptr
);
void AddEvent(_In_ const XblMultiplayerEvent& multiplayerEvent);
private:
xsapi_internal_vector<XblMultiplayerEvent> m_events;
mutable std::mutex m_lock;
};
class MultiplayerManager
{
public:
MultiplayerManager() = default;
~MultiplayerManager();
void Initialize(
_In_ const xsapi_internal_string& lobbySessionTemplateName,
_In_opt_ XTaskQueueHandle asyncQueue
);
bool IsInitialized();
const MultiplayerEventQueue& DoWork();
std::shared_ptr<MultiplayerLobbySession> LobbySession() const;
std::shared_ptr<MultiplayerGameSession> GameSession() const;
HRESULT JoinLobby(
_In_ const xsapi_internal_string& handleId,
_In_ xbox_live_user_t user
);
#if HC_PLATFORM == HC_PLATFORM_UWP || HC_PLATFORM == HC_PLATFORM_XDK
HRESULT JoinLobby(
_In_ Windows::ApplicationModel::Activation::IProtocolActivatedEventArgs^ eventArgs,
_In_ xbox_live_user_t user
);
#endif
#if HC_PLATFORM == HC_PLATFORM_XDK
HRESULT JoinLobby(
_In_ const xsapi_internal_string& handleId,
_In_ xsapi_internal_vector<Windows::Xbox::System::User^> users
);
HRESULT JoinLobby(
_In_ Windows::ApplicationModel::Activation::IProtocolActivatedEventArgs^ eventArgs,
_In_ xsapi_internal_vector<Windows::Xbox::System::User^> users
);
void InvitePartyToGame();
#endif
HRESULT JoinGameFromLobby(
_In_ const xsapi_internal_string& sessionTemplateName
);
HRESULT JoinGame(
_In_ const xsapi_internal_string& sessionName,
_In_ const xsapi_internal_string& sessionTemplateName,
_In_ const xsapi_internal_vector<uint64_t>& xuids = xsapi_internal_vector<uint64_t>()
);
HRESULT LeaveGame();
HRESULT FindMatch(
_In_ const xsapi_internal_string& hopperName,
_In_ JsonValue& attributes,
_In_ const std::chrono::seconds& timeout = std::chrono::seconds(60)
);
void CancelMatch();
XblMultiplayerMatchStatus MatchStatus() const;
std::chrono::seconds EstimatedMatchWaitTime() const;
bool AutoFillMembersDuringMatchmaking() const;
void SetAutoFillMembersDuringMatchmaking(
_In_ bool autoFillMembers
);
void SetQosMeasurements(
_In_ const JsonValue& measurements
);
XblMultiplayerJoinability Joinability() const;
HRESULT SetJoinability(
_In_ XblMultiplayerJoinability value,
_In_opt_ context_t context = nullptr
);
bool IsDirty();
std::shared_ptr<MultiplayerClientManager> GetMultiplayerClientManager() { return m_multiplayerClientManager; }
std::shared_ptr<MultiplayerGameClient> GameClient();
std::shared_ptr<MultiplayerLobbyClient> LobbyClient();
#if XSAPI_UNIT_TESTS
void Shutdown();
#endif
#if defined(XSAPI_CPPWINRT)
#if HC_PLATFORM == HC_PLATFORM_XDK
xbox_live_result<void> join_lobby(
_In_ const xsapi_internal_string& handleId,
_In_ xsapi_internal_vector<winrt::Windows::Xbox::System::User> users
)
{
return join_lobby(handleId, convert_user_vector_to_cppcx(users));
}
#endif
#endif
private:
MultiplayerManager(MultiplayerManager const&) = delete;
void operator=(MultiplayerManager const&) = delete;
bool m_isDirty = false;
void SetMultiplayerGameSession(_In_ std::shared_ptr<MultiplayerGameSession> gameSession);
void SetMultiplayerLobbySession(_In_ std::shared_ptr<MultiplayerLobbySession> multiplayerLobby);
mutable std::mutex m_lock;
XblMultiplayerJoinability m_joinability = XblMultiplayerJoinability::None;
std::shared_ptr<MultiplayerLobbySession> m_multiplayerLobbySession;
std::shared_ptr<MultiplayerGameSession> m_multiplayerGameSession;
std::shared_ptr<MultiplayerClientManager> m_multiplayerClientManager;
MultiplayerEventQueue m_eventQueue;
XTaskQueueHandle m_queue{ nullptr };
};
typedef Callback<Result<std::shared_ptr<XblMultiplayerSession>>> MultiplayerSessionCallback;
typedef Callback<Result<MultiplayerEventQueue>> MultiplayerEventQueueCallback; // Maybe just pass queue
class MultiplayerClientPendingRequest
{
public:
MultiplayerClientPendingRequest();
PendingRequestType RequestType() const;
context_t Context();
uint32_t Identifier() const;
// Local user properties
std::shared_ptr<MultiplayerLocalUser> LocalUser();
void SetLocalUser(_In_ std::shared_ptr<MultiplayerLocalUser> user);
MultiplayerLocalUserLobbyState LobbyState();
void SetLobbyState(_In_ MultiplayerLocalUserLobbyState userState);
const xsapi_internal_string& LobbyHandleId() const;
void SetLobbyHandleId(_In_ const xsapi_internal_string& handleId);
const xsapi_internal_string& LocalUserSecureDeivceAddress() const;
void SetLocalUserConnectionAddress(
_In_ std::shared_ptr<MultiplayerLocalUser> localUser,
_In_ const xsapi_internal_string& connectionAddress,
_In_opt_ context_t context
);
const xsapi_internal_map<xsapi_internal_string, JsonDocument>& LocalUserProperties() const;
void SetLocalUserProperties(
_In_ std::shared_ptr<MultiplayerLocalUser> localUser,
_In_ const xsapi_internal_string& name,
_In_ const JsonValue& valueJson,
_In_opt_ context_t context
);
// Session non-synchronized properties
XblMultiplayerJoinability Joinability();
void SetJoinability(_In_ XblMultiplayerJoinability value, _In_opt_ context_t context);
const xsapi_internal_map<xsapi_internal_string, JsonDocument>& SessionProperties() const;
void SetSessionProperties(_In_ const xsapi_internal_string& name, _In_ const JsonValue& valueJson, _In_opt_ context_t context);
// Session synchronized properties
const xsapi_internal_string& SynchronizedHostDeviceToken() const;
void SetSynchronizedHostDeviceToken(_In_ const xsapi_internal_string& hostDeviceToken, _In_opt_ context_t context);
const xsapi_internal_map<xsapi_internal_string, JsonDocument>& SynchronizedSessionProperties() const;
void SetSynchronizedSessionProperties(_In_ const xsapi_internal_string& name, const _In_ JsonValue& valueJson, _In_opt_ context_t context);
void AppendPendingChanges(
_In_ std::shared_ptr<XblMultiplayerSession> sessionToCommit,
_In_ std::shared_ptr<MultiplayerLocalUser> localUser,
_In_ bool isGameInProgress = false
);
private:
context_t m_context;
PendingRequestType m_requestType{};
uint32_t m_identifier{ s_nextUniqueIdentifier++ };
// Local user properties
std::shared_ptr<MultiplayerLocalUser> m_localUser;
MultiplayerLocalUserLobbyState m_localUserLobbyState;
xsapi_internal_map<xsapi_internal_string, JsonDocument> m_localUserProperties;
xsapi_internal_string m_localUserSecureDeivceAddress;
xsapi_internal_string m_lobbyHandleId; // Only used while joining a friend's lobby
// Session non-synchronized properties
xsapi_internal_map<xsapi_internal_string, JsonDocument> m_sessionProperties;
XblMultiplayerJoinability m_joinability{};
// Session synchronized properties
xsapi_internal_string m_synchronizedHostDeviceToken;
xsapi_internal_map<xsapi_internal_string, JsonDocument> m_synchronizedSessionProperties;
static std::atomic<uint32_t> s_nextUniqueIdentifier;
};
class MultiplayerSessionWriter : public std::enable_shared_from_this<MultiplayerSessionWriter>
{
public:
MultiplayerSessionWriter(const TaskQueue& queue) noexcept;
MultiplayerSessionWriter(
const TaskQueue& queue,
_In_ std::shared_ptr<MultiplayerLocalUserManager> localUserManager
) noexcept;
uint64_t Id() const;
const std::shared_ptr<XblMultiplayerSession>& Session() const;
void UpdateSession(_In_ const std::shared_ptr<XblMultiplayerSession>& updatedSession);
uint64_t TapChangeNumber() const;
void SetTapChangeNumber(_In_ uint64_t changeNumber);
bool IsTapReceived() const;
void SetTapReceived(_In_ bool bReceived);
bool IsWriteInProgress() const;
void SetWriteInProgress(_In_ bool writeInProgress);
void OnSessionChanged(
_In_ XblMultiplayerSessionChangeEventArgs args
) noexcept;
HRESULT CommitSynchronizedChanges(
_In_ std::shared_ptr<XblMultiplayerSession> sessionToCommit,
_In_ MultiplayerSessionCallback callback
) noexcept;
HRESULT LeaveRemoteSession(
_In_ std::shared_ptr<XblMultiplayerSession> session,
_In_ MultiplayerSessionCallback callback
) noexcept;
HRESULT CommitPendingChanges(
_In_ Vector<std::shared_ptr<MultiplayerClientPendingRequest>> processingQueue,
_In_ XblMultiplayerSessionType sessionType,
_In_ bool isGameInProgress,
_In_ MultiplayerEventQueueCallback callback
) noexcept;
HRESULT CommitPendingSynchronizedChanges(
_In_ Vector<std::shared_ptr<MultiplayerClientPendingRequest>> processingQueue,
_In_ XblMultiplayerSessionType sessionType,
_In_ MultiplayerEventQueueCallback callback
) noexcept;
HRESULT WriteSession(
_In_ std::shared_ptr<XblContext> xboxLiveContext,
_In_ std::shared_ptr<XblMultiplayerSession> session,
_In_ XblMultiplayerSessionWriteMode mode,
_In_ bool updateLatest,
_In_ MultiplayerSessionCallback callback
) noexcept;
HRESULT WriteSessionByHandle(
_In_ std::shared_ptr<XblContext> xboxLiveContext,
_In_ std::shared_ptr<XblMultiplayerSession> session,
_In_ XblMultiplayerSessionWriteMode mode,
_In_ const String& handleId,
_In_ bool updateLatest,
_In_ MultiplayerSessionCallback callback
) noexcept;
void OnSessionUpdated(
_In_ const std::shared_ptr<XblMultiplayerSession>& updatedSession
);
XblFunctionContext AddMultiplayerSessionUpdatedHandler(
_In_ Callback<const std::shared_ptr<XblMultiplayerSession>&> handler
);
void OnResyncMessageReceived();
std::shared_ptr<XblContext> GetPrimaryContext();
MultiplayerEventQueue HandleEvents(
_In_ xsapi_internal_vector<std::shared_ptr<MultiplayerClientPendingRequest>> processingQueue,
_In_ Result<void> error,
_In_ XblMultiplayerSessionType sessionType
);
private:
void Destroy();
void Resync();
// Synchronize write session result with any changes that happened in the interim.
void HandleWriteSessionResult(
_In_ Result<std::shared_ptr<XblMultiplayerSession>> writeSessionResult,
_In_ bool updateLatest,
_In_ MultiplayerSessionCallback callback
) noexcept;
HRESULT GetCurrentSessionHelper(
_In_ std::shared_ptr<XblContext> xboxLiveContext,
_In_ const XblMultiplayerSessionReference& sessionReference,
_In_ MultiplayerSessionCallback callback
) noexcept;
TaskQueue m_queue;
// resync
bool m_isResyncTaskInProgress{ false };
XblFunctionContext m_handleResyncEventCounter{ 0 };
std::mutex m_resyncLock;
std::mutex m_stateLock;
XblFunctionContext m_sessionUpdateEventHandlerCounter{ 0 };
UnorderedMap<uint32_t, Callback<const std::shared_ptr<XblMultiplayerSession>>> m_sessionUpdateEventHandler;
uint64_t m_id{ 0 }; // used to ignore calls made before resetting the state via destory()
std::mutex m_synchronizeWriteWithTapLock;
uint64_t m_tapChangeNumber{ 0 };
bool m_isTapReceived{ false };
uint64_t m_numOfWritesInProgress{ 0 };
std::shared_ptr<XblMultiplayerSession> m_session;
std::shared_ptr<MultiplayerLocalUserManager> m_multiplayerLocalUserManager;
};
class MultiplayerGameClient : public std::enable_shared_from_this<MultiplayerGameClient>
{
public:
MultiplayerGameClient(const TaskQueue& queue) noexcept;
MultiplayerGameClient(
const TaskQueue& queue,
_In_ std::shared_ptr<MultiplayerLocalUserManager> localUserManager
) noexcept;
~MultiplayerGameClient();
// TODO
void deep_copy_if_updated(_In_ const MultiplayerGameClient& other);
void Initialize();
void SetGameSessionTemplate(_In_ const xsapi_internal_string& sessionTemplateName);
std::shared_ptr<MultiplayerSessionWriter> SessionWriter() const;
std::shared_ptr<MultiplayerGameSession> Game() const;
void UpdateGame(_In_ const std::shared_ptr<MultiplayerGameSession>& multiplayerGame);
MultiplayerEventQueue DoWork();
bool IsRequestInProgress();
bool IsPendingGameChanges();
void ClearPendingQueue();
void AddToPendingQueue(_In_ std::shared_ptr<MultiplayerClientPendingRequest> pendingRequest);
void AddToProcessingQueue(_In_ xsapi_internal_vector<std::shared_ptr<MultiplayerClientPendingRequest>> processingQueue);
void RemoveFromProcessingQueue(_In_ uint32_t identifier);
const MultiplayerEventQueue& EventQueue();
xsapi_internal_vector<std::shared_ptr<MultiplayerClientPendingRequest>> GetProcessingQueue();
void UpdateGameSession(_In_ const std::shared_ptr<XblMultiplayerSession>& session);
void UpdateObjects(
const std::shared_ptr<XblMultiplayerSession>& updatedSession,
const std::shared_ptr<XblMultiplayerSession>& lobbySession
);
std::shared_ptr<XblMultiplayerSession> Session() const;
void UpdateSession(_In_ const std::shared_ptr<XblMultiplayerSession>& session);
void RemoveStaleUsersFromRemoteSession();
void SetLocalMemberPropertiesToRemoteSession(
_In_ const std::shared_ptr<xbox::services::multiplayer::manager::MultiplayerLocalUser>& localUser,
_In_ const Map<String, JsonDocument>& propertiesToWrite,
_In_ const String& localUserSecureDeviceAddress
) noexcept;
HRESULT JoinGameHelper(
_In_ const String& sessionName,
_In_ Callback<Result<void>> callback
) noexcept;
void LeaveRemoteSession(
_In_ std::shared_ptr<XblMultiplayerSession> session,
_In_ bool stopAdvertisingGameSession,
_In_ bool triggerCompletionEvent
) noexcept;
HRESULT JoinGameFromLobbyHelper(
_In_ MultiplayerSessionCallback callback
) noexcept;
HRESULT JoinGameBySessionReference(
_In_ const XblMultiplayerSessionReference& gameSessionRef,
_In_ MultiplayerSessionCallback callback
) noexcept;
HRESULT JoinGameByHandle(
_In_ const String& handleId,
_In_ bool createGameIfFailedToJoin,
_In_ MultiplayerSessionCallback callback
) noexcept;
private:
std::shared_ptr<XblMultiplayerSession> LobbySession() const;
std::shared_ptr<MultiplayerLobbyClient> LobbyClient() const;
std::shared_ptr<MultiplayerGameSession> ConvertToMultiplayerGame(
_In_ const std::shared_ptr<XblMultiplayerSession>& sessionToConvert,
_In_ const std::shared_ptr<XblMultiplayerSession>& lobbySession
);
HRESULT JoinGameForAllLocalMembers(
_In_ const XblMultiplayerSessionReference& sessionRefToJoin,
_In_ const String& handleIdToJoin,
_In_ bool createGameIfFailedToJoin,
_In_ MultiplayerSessionCallback callback
) noexcept;
HRESULT JoinHelper(
_In_ std::shared_ptr<MultiplayerLocalUser> localUser,
_In_ std::shared_ptr<XblMultiplayerSession> session,
_In_ bool writeMemberPropertiesFromLobby,
_In_ const String& handleId,
_In_ MultiplayerSessionCallback callback
) const noexcept;
TaskQueue m_queue;
mutable std::mutex m_clientRequestLock;
std::atomic<bool> m_pendingCommitInProgress{ false };
String m_gameSessionTemplateName;
uint64_t m_updateNumber{ 0 };
std::shared_ptr<MultiplayerSessionWriter> m_sessionWriter;
MultiplayerEventQueue m_multiplayerEventQueue;
std::shared_ptr<MultiplayerGameSession> m_multiplayerGame;
std::shared_ptr<MultiplayerLocalUserManager> m_multiplayerLocalUserManager;
Queue<std::shared_ptr<MultiplayerClientPendingRequest>> m_pendingRequestQueue;
Vector<std::shared_ptr<MultiplayerClientPendingRequest>> m_processingQueue;
};
#define MultiplayerLobbyClient_TransferHandlePropertyName "GameSessionTransferHandle"
#define MultiplayerLobbyClient_JoinabilityPropertyName "Joinability"
class MultiplayerLobbyClient : public std::enable_shared_from_this<MultiplayerLobbyClient>
{
public:
MultiplayerLobbyClient(_In_ const TaskQueue& queue) noexcept;
MultiplayerLobbyClient(
_In_ const TaskQueue& queue,
_In_ String lobbySessionTemplateName,
_In_ std::shared_ptr<MultiplayerLocalUserManager> localUserManager
) noexcept;
~MultiplayerLobbyClient() noexcept;
// TODO
void deep_copy_if_updated(_In_ const MultiplayerLobbyClient& other);
void Initialize();
const std::shared_ptr<MultiplayerSessionWriter>& SessionWriter() const;
const std::shared_ptr<MultiplayerLobbySession>& Lobby() const;
void ClearPendingQueue();
void AddToPendingQueue(_In_ std::shared_ptr<MultiplayerClientPendingRequest> pendingRequest);
void AddToProcessingQueue(_In_ xsapi_internal_vector<std::shared_ptr<MultiplayerClientPendingRequest>> processingQueue);
void RemoveFromProcessingQueue(_In_ uint32_t identifier);
HRESULT AddLocalUser(
_In_ xbox_live_user_t user,
_In_ MultiplayerLocalUserLobbyState userState,
_In_ const xsapi_internal_string& handleId = xsapi_internal_string()
);
void AddLocalUsers(_In_ xsapi_internal_vector<xbox_live_user_t> user, _In_ const xsapi_internal_string& handleId);
void AddLocalUsers(_In_ xsapi_internal_vector<xbox_live_user_t> user);
HRESULT RemoveLocalUser(_In_ xbox_live_user_t user);
void RemoveAllLocalUsers();
HRESULT SetLocalMemberProperties(
_In_ xbox_live_user_t user,
_In_ const xsapi_internal_string& name,
_In_ const JsonValue& valueJson,
_In_opt_ context_t context
);
HRESULT DeleteLocalMemberProperties(
_In_ xbox_live_user_t user,
_In_ const xsapi_internal_string& name,
_In_opt_ context_t context
);
HRESULT SetLocalMemberConnectionAddress(
_In_ xbox_live_user_t user,
_In_ const xsapi_internal_string& address,
_In_opt_ context_t context
);
MultiplayerEventQueue DoWork();
bool IsPendingLobbyChanges();
bool IsRequestInProgress();
HRESULT CreateGameFromLobby() noexcept;
XblMultiplayerJoinability Joinability();
HRESULT SetJoinability(
_In_ XblMultiplayerJoinability value,
_In_opt_ context_t context
);
const MultiplayerEventQueue& EventQueue();
xsapi_internal_vector<std::shared_ptr<MultiplayerClientPendingRequest>> GetProcessingQueue();
void UpdateLobbySession(_In_ const std::shared_ptr<XblMultiplayerSession>& updatedSession);
void UpdateObjects(
const std::shared_ptr<XblMultiplayerSession>& updatedSession,
const std::shared_ptr<XblMultiplayerSession>& gameSession
);
const std::shared_ptr<XblMultiplayerSession>& Session() const;
void UpdateSession(
_In_ const std::shared_ptr<XblMultiplayerSession>& updatedSession
);
void LeaveRemoteSession(
_In_ std::shared_ptr<XblMultiplayerSession> session
);
void StopAdvertisingGameSession(
_In_ Result<std::shared_ptr<XblMultiplayerSession>> result
);
void AdvertiseGameSession() noexcept;
void ClearGameSessionFromLobby();
bool IsTransferHandleState(_In_ const xsapi_internal_string& state);
xsapi_internal_string GetTransferHandle();
void RemoveStaleXboxLiveContextFromMap();
const xsapi_internal_map<uint64_t, std::shared_ptr<MultiplayerLocalUser>>& GetLocalUserMap();
std::shared_ptr<XblContext> GetPrimaryContext();
private:
std::shared_ptr<MultiplayerGameClient> GameClient();
std::shared_ptr<XblMultiplayerSession> GameSession();
HRESULT CommitPendingLobbyChanges(
_In_ const Vector<uint64_t>& xuidsInOrder,
_In_ bool joinByHandleId,
_In_ XblMultiplayerSessionReference sessionRef,
_In_ MultiplayerEventQueueCallback callback
) noexcept;
HRESULT CommitLobbyChanges(
_In_ const Vector<uint64_t>& xuidsInOrder,
_In_ std::shared_ptr<XblMultiplayerSession> lobbySessionToCommit,
_In_ Callback<Result<void>> callback
) noexcept;
void UpdateLobby(_In_ std::shared_ptr<MultiplayerLobbySession> multiplayerLobby);
void UpdateLocalLobbyMembers(
_In_ const std::shared_ptr<XblMultiplayerSession>& lobbySession,
_In_ const std::shared_ptr<XblMultiplayerSession>& gameSession
);
bool IsPendingLobbyLocalUserChanges();
bool ShouldUpdateHostToken(
_In_ std::shared_ptr<xbox::services::multiplayer::manager::MultiplayerLocalUser> localUser,
_In_ std::shared_ptr<XblMultiplayerSession> session
);
void UserStateChanged(
_In_ Result<void> error,
_In_ MultiplayerLocalUserLobbyState localUserLobbyState,
_In_ uint64_t xboxUserId
);
void HandleLobbyChangeEvents(
_In_ Result<void> error,
_In_ std::shared_ptr<MultiplayerLocalUser> localUser,
_In_ const xsapi_internal_vector<std::shared_ptr<MultiplayerClientPendingRequest>>& processingQueue
);
void HandleJoinLobbyCompleted(
_In_ Result<void> error,
_In_ uint64_t joinedXuid
);
void JoinLobbyCompleted(
_In_ Result<void> error,
_In_ uint64_t invitedXboxUserId
);
void AddEvent(
_In_ XblMultiplayerEventType eventType,
_In_opt_ std::shared_ptr<XblMultiplayerEventArgs> eventArgs = nullptr,
_In_opt_ Result<void> error = {},
_In_opt_ context_t context = nullptr
);
std::shared_ptr<MultiplayerLobbySession> ConvertToMultiplayerLobby(
_In_ const std::shared_ptr<XblMultiplayerSession>& sessionToConvert,
_In_ const std::shared_ptr<XblMultiplayerSession>& gameSession
);
TaskQueue m_queue;
String m_lobbySessionTemplateName;
std::atomic<bool> m_pendingCommitInProgress{ false };
uint64_t m_updateNumber{ 0 };
XblMultiplayerJoinability m_joinability{ XblMultiplayerJoinability::None };
mutable std::mutex m_clientRequestLock;
Queue<std::shared_ptr<MultiplayerClientPendingRequest>> m_pendingRequestQueue;
MultiplayerEventQueue m_multiplayerEventQueue;
std::shared_ptr<MultiplayerSessionWriter> m_sessionWriter;
std::shared_ptr<MultiplayerLobbySession> m_multiplayerLobby;
Vector<std::shared_ptr<MultiplayerMember>> m_localLobbyMembers;
std::shared_ptr<MultiplayerLocalUserManager> m_multiplayerLocalUserManager;
Vector<std::shared_ptr<MultiplayerClientPendingRequest>> m_processingQueue;
};
class MultiplayerClientPendingReader : public std::enable_shared_from_this<MultiplayerClientPendingReader>
{
public:
MultiplayerClientPendingReader(const TaskQueue& queue);
~MultiplayerClientPendingReader();
MultiplayerClientPendingReader(
_In_ const TaskQueue& queue,
_In_ const xsapi_internal_string& lobbySessionTemplateName,
_In_ std::shared_ptr<MultiplayerLocalUserManager> localUserManager
);
// TODO
void deep_copy_if_updated(_In_ const MultiplayerClientPendingReader& other);
bool IsUpdateAvailable(_In_ const MultiplayerClientPendingReader& other);
void DoWork();
void ProcessMatchEvents();
std::shared_ptr<MultiplayerLobbyClient> LobbyClient();
std::shared_ptr<MultiplayerGameClient> GameClient();
std::shared_ptr<MultiplayerMatchClient> MatchClient();
const MultiplayerEventQueue& EventQueue() const;
void ClearEventQueue();
void AddEvent(
_In_ XblMultiplayerEventType eventType,
_In_ std::shared_ptr<XblMultiplayerEventArgs> eventArgs,
_In_ XblMultiplayerSessionType sessionType,
_In_ Result<void> error,
_In_opt_ context_t context = nullptr
);
void AddEvent(_In_ const XblMultiplayerEvent& multiplayerEvent);
void AddEvents(_In_ const MultiplayerEventQueue& multiplayerEventQueue);
std::shared_ptr<XblMultiplayerSession> GetSession(_In_ XblMultiplayerSessionReference sessionRef);
void UpdateSession(_In_ XblMultiplayerSessionReference sessionRef, _In_ std::shared_ptr<XblMultiplayerSession> session);
bool IsLobby(_In_ XblMultiplayerSessionReference sessionRef);
bool IsGame(_In_ XblMultiplayerSessionReference sessionRef);
bool IsMatch(_In_ XblMultiplayerSessionReference sessionRef);
HRESULT FindMatch(
_In_ const xsapi_internal_string& hopperName,
_In_ JsonValue& attributes,
_In_ const std::chrono::seconds& timeout
);
void SetAutoFillMembersDuringMatchmaking(_In_ bool autoFillMembers);
HRESULT SetJoinability(
_In_ XblMultiplayerJoinability value,
_In_opt_ context_t context
);
HRESULT SetProperties(
_In_ const XblMultiplayerSessionReference& sessionRef,
_In_ const xsapi_internal_string& name,
_In_ const JsonValue& valueJson,
_In_opt_ context_t context
);
HRESULT SetSynchronizedProperties(
_In_ const XblMultiplayerSessionReference& sessionRef,
_In_ const xsapi_internal_string& name,
_In_ const JsonValue& valueJson,
_In_opt_ context_t context
);
HRESULT SetSynchronizedHost(
_In_ const XblMultiplayerSessionReference& sessionRef,
_In_ const xsapi_internal_string& hostDeviceToken,
_In_opt_ context_t context
);
std::shared_ptr<MultiplayerMember> ConvertToGameMember(_In_ const XblMultiplayerSessionMember* member);
private:
void AddToPendingQueue(
_In_ const XblMultiplayerSessionReference& sessionRef,
_In_ std::shared_ptr<MultiplayerClientPendingRequest> pendingRequest
);
static bool IsLocal(_In_ uint64_t xuid, _In_ const xsapi_internal_map<uint64_t, std::shared_ptr<MultiplayerLocalUser>>& xboxLiveContextMap);
TaskQueue m_queue;
bool m_autoFillMembers;
MultiplayerEventQueue m_multiplayerEventQueue;
mutable std::mutex m_clientRequestLock;
std::shared_ptr<MultiplayerLobbyClient> m_lobbyClient;
std::shared_ptr<MultiplayerGameClient> m_gameClient;
std::shared_ptr<xbox::services::multiplayer::manager::MultiplayerMatchClient> m_matchClient;
std::shared_ptr<MultiplayerLocalUserManager> m_multiplayerLocalUserManager;
};
class MultiplayerLocalUser
{
public:
MultiplayerLocalUser(
_In_ User&& user,
_In_ uint64_t xboxUserId,
_In_ bool isPrimary
);
~MultiplayerLocalUser();
uint64_t Xuid() const;
std::shared_ptr<XblContext> Context() const;
const xsapi_internal_string& LobbyHandleId() const;
void SetLobbyHandleId(_In_ const xsapi_internal_string& handleId);
MultiplayerLocalUserLobbyState LobbyState() const;
void SetLobbyState(_In_ MultiplayerLocalUserLobbyState userState);
MultiplayerLocalUserGameState GameState() const;
void SetGameState(_In_ MultiplayerLocalUserGameState userState);
const xsapi_internal_string& ConnectionAddress() const;
void SetConnectionAddress(_In_ const xsapi_internal_string& address);
bool IsPrimaryXboxLiveContext() const;
void SetIsPrimaryXboxLiveContext(_In_ bool isPrimary);
bool WriteChangesToService() const;
void SetWriteChangesToService(_In_ bool value);
XblFunctionContext SessionChangedContext() const;
void SetSessionChangedContext(_In_ XblFunctionContext functionContext);
XblFunctionContext RtaResyncContext() const;
void SetRtaResyncContext(_In_ XblFunctionContext functionContext);
XblFunctionContext ConnectionIdChangedContext() const;
void SetConnectionIdChangedContext(_In_ XblFunctionContext functionContext);
XblFunctionContext SubscriptionLostContext() const;
void SetSubscriptionLostContext(_In_ XblFunctionContext functionContext);
private:
XblFunctionContext m_sessionChangedContext{};
XblFunctionContext m_connectionIdChangedContext{};
XblFunctionContext m_subscriptionLostContext{};
XblFunctionContext m_rtaResyncContext{};
bool m_writeChangesToService{ false };
uint64_t m_xuid{ 0 };
xsapi_internal_string m_connectionAddress;
xsapi_internal_string m_lobbyHandleId;
MultiplayerLocalUserLobbyState m_lobbyState{ MultiplayerLocalUserLobbyState::Unknown };
MultiplayerLocalUserGameState m_gameState{ MultiplayerLocalUserGameState::Unknown };
bool m_isPrimaryXboxLiveContext{ false };
std::shared_ptr<XblContext> m_xboxLiveContextImpl;
};
class MultiplayerLocalUserManager : public std::enable_shared_from_this<MultiplayerLocalUserManager>
{
public:
MultiplayerLocalUserManager();
~MultiplayerLocalUserManager();
std::shared_ptr<XblContext> GetPrimaryContext();
void ChangeAllLocalUserLobbyState(_In_ MultiplayerLocalUserLobbyState state);
void ChangeAllLocalUserGameState(_In_ MultiplayerLocalUserGameState state);
bool IsLocalUserGameState(_In_ MultiplayerLocalUserGameState state);
const xsapi_internal_map<uint64_t, std::shared_ptr<MultiplayerLocalUser>>& GetLocalUserMap();
std::shared_ptr<XblContext> GetContext(_In_ uint64_t xuid);
std::shared_ptr<MultiplayerLocalUser> GetLocalUser(_In_ uint64_t xuid);
std::shared_ptr<MultiplayerLocalUser> GetLocalUserHelper(_In_ uint64_t xuid);
std::shared_ptr<MultiplayerLocalUser> GetLocalUser(
_In_ xbox_live_user_t user
);
std::shared_ptr<MultiplayerLocalUser> GetLocalUserHelper(
_In_ xbox_live_user_t user
);
Result<const std::shared_ptr<MultiplayerLocalUser>> AddUserToXboxLiveContextToMap(_In_ xbox_live_user_t user);
void RemoveStaleLocalUsersFromMap();
void ActivateMultiplayerEvents(_In_ const std::shared_ptr<xbox::services::multiplayer::manager::MultiplayerLocalUser>& localuser);
void DeactivateMultiplayerEvents(_In_ const std::shared_ptr<xbox::services::multiplayer::manager::MultiplayerLocalUser>& localUser);
XblFunctionContext AddMultiplayerSessionChangedHandler(
_In_ Callback<XblMultiplayerSessionChangeEventArgs> handler
);
void RemoveMultiplayerSessionChangedHandler(_In_ XblFunctionContext context);
XblFunctionContext AddMultiplayerConnectionIdChangedHandler(_In_ Function<void()> handler);
void RemoveMultiplayerConnectionIdChangedHandler(_In_ XblFunctionContext context);
XblFunctionContext AddMultiplayerSubscriptionLostHandler(_In_ Function<void()> handler);
void RemoveMultiplayerSubscriptionLostHandler(_In_ XblFunctionContext context);
XblFunctionContext AddRtaResyncHandler(_In_ Function<void()> handler);
void RemoveRtaResyncHandler(_In_ XblFunctionContext context);
private:
std::mutex m_lock;
void OnConnectionIdChanged();
void OnSubscriptionsLost(_In_ uint64_t xuid);
void OnSessionChanged(
_In_ const XblMultiplayerSessionChangeEventArgs& args
);
void OnConnectionStateChanged(
_In_ uint64_t xuid,
_In_ XblRealTimeActivityConnectionState state
);
void OnResyncMessageReceived();
std::mutex m_subscriptionLock;
XblFunctionContext m_sessionChangeEventHandlerCounter{};
XblFunctionContext m_multiplayerConnectionIdChangedEventHandlerCounter{};
XblFunctionContext m_multiplayerSubscriptionLostEventHandlerCounter{};
XblFunctionContext m_rtaResyncEventHandlerCounter{};
xsapi_internal_unordered_map<uint32_t, Callback<XblMultiplayerSessionChangeEventArgs>> m_sessionChangeEventHandler;
xsapi_internal_unordered_map<uint32_t, Function<void()>> m_multiplayerConnectionIdChangedEventHandler;
xsapi_internal_unordered_map<uint32_t, Function<void()>> m_multiplayerSubscriptionLostEventHandler;
xsapi_internal_unordered_map<uint32_t, Function<void()>> m_rtaResyncEventHandler;
xsapi_internal_map<uint64_t, std::shared_ptr<MultiplayerLocalUser>> m_localUserRequestMap;
std::shared_ptr<XblContext> m_primaryXboxLiveContext;
TaskQueue m_queue;
};
class MultiplayerClientManager : public std::enable_shared_from_this<MultiplayerClientManager>
{
public:
MultiplayerClientManager(_In_ const MultiplayerClientManager& other);
MultiplayerClientManager(
_In_ const xsapi_internal_string& lobbySessionTemplateName,
_In_ const TaskQueue& queue
);
~MultiplayerClientManager() = default;
void Initialize();
void Shutdown();
void RegisterLocalUserManagerEvents();
bool IsUpdateAvailable();
bool IsRequestInProgress();
std::shared_ptr<MultiplayerLocalUserManager> LocalUserManager();
std::shared_ptr<XblContext> GetPrimaryContext();
std::shared_ptr<MultiplayerLobbyClient> LobbyClient() const;
std::shared_ptr<MultiplayerClientPendingReader> LatestPendingRead() const;
std::shared_ptr<MultiplayerClientPendingReader> LastPendingRead() const;
HRESULT JoinLobbyByHandle(
_In_ const xsapi_internal_string& handleId,
_In_ const xsapi_internal_vector<xbox_live_user_t>& users
);
#if HC_PLATFORM == HC_PLATFORM_UWP || HC_PLATFORM == HC_PLATFORM_XDK
HRESULT JoinLobby(
_In_ Windows::ApplicationModel::Activation::IProtocolActivatedEventArgs^ eventArgs,
_In_ xsapi_internal_vector<xbox_live_user_t> users
);
HRESULT JoinLobby( _In_ Windows::Foundation::Uri^ url, _In_ xsapi_internal_vector<xbox_live_user_t> users);
#endif
HRESULT JoinGameFromLobby(_In_ const xsapi_internal_string& sessionTemplateName);
HRESULT JoinGame(
_In_ const xsapi_internal_string& sessionName,
_In_ const xsapi_internal_string& sessionTemplateName,
_In_ const xsapi_internal_vector<uint64_t>& xuids
);
HRESULT LeaveGame();
MultiplayerEventQueue DoWork(); // TODO see if we can switch these to ref
HRESULT GetActivitiesForSocialGroup(
_In_ xbox_live_user_t user,
_In_ const xsapi_internal_string& socialGroup,
_In_ XTaskQueueHandle queue,
_In_ Callback<Result<xsapi_internal_vector<XblMultiplayerActivityDetails>>> callback
);
HRESULT InviteFriends(
_In_ xbox_live_user_t user,
_In_ const xsapi_internal_string& contextStringId,
_In_ const xsapi_internal_string& customActivationContext
);
HRESULT InviteUsers(
_In_ xbox_live_user_t user,
_In_ const xsapi_internal_vector<uint64_t>& xboxUserIds,
_In_ const xsapi_internal_string& contextStringId,
_In_ const xsapi_internal_string& customActivationContext
);
HRESULT SetProperties(
_In_ const XblMultiplayerSessionReference& sessionRef,
_In_ const xsapi_internal_string& name,
_In_ const JsonValue& valueJson,
_In_opt_ context_t context
);
HRESULT SetJoinability(
_In_ XblMultiplayerJoinability value,
_In_opt_ context_t context
);
HRESULT SetSynchronizedHost(
_In_ const XblMultiplayerSessionReference& sessionRef,
_In_ const xsapi_internal_string& hostDeviceToken,
_In_opt_ context_t context
);
HRESULT SetSynchronizedProperties(
_In_ const XblMultiplayerSessionReference& sessionRef,
_In_ const xsapi_internal_string& name,
_In_ const JsonValue& valueJson,
_In_opt_ context_t context
);
std::shared_ptr<MultiplayerMatchClient> MatchClient();
HRESULT FindMatch(
_In_ const xsapi_internal_string& hopperName,
_In_ JsonValue& attributes,
_In_ const std::chrono::seconds& timeout
);
void SetAutoFillMembersDuringMatchmaking(_In_ bool autoFillMembers);
void OnSessionChanged(
_In_ XblMultiplayerSessionChangeEventArgs args
);
const MultiplayerEventQueue& EventQueue() const;
void ClearEventQueue();
void OnMultiplayerConnectionIdChanged();
void OnMultiplayerSubscriptionsLost();
private:
MultiplayerClientManager& operator=(MultiplayerClientManager other) = delete;
void Destroy();
Result<std::shared_ptr<xbox::services::multiplayer::MultiplayerService>> GetMultiplayerService(
_In_ xbox_live_user_t user
);
xsapi_internal_map<uint64_t, std::shared_ptr<MultiplayerLocalUser>> GetXboxLiveContextMap();
void OnResyncMessageReceived();
void AddToLatestPendingReadEventQueue(
_In_ XblMultiplayerEventType eventType,
_In_ XblMultiplayerSessionType sessionType,
_In_ std::shared_ptr<XblMultiplayerEventArgs> eventArgs = nullptr,
_In_opt_ Result<void> error = {},
_In_opt_ context_t context = nullptr
);
XblMultiplayerSessionType GetSessionType(
_In_ std::shared_ptr<XblMultiplayerSession> session
);
void ProcessEvents(
_In_ std::shared_ptr<XblMultiplayerSession> currentSession,
_In_ std::shared_ptr<XblMultiplayerSession> oldSession,
_In_ XblMultiplayerSessionType sessionType
);
void HandleMemberListChanged(
_In_ std::shared_ptr<XblMultiplayerSession> currentSession,
_In_ std::shared_ptr<XblMultiplayerSession> oldSession,
_In_ XblMultiplayerSessionType sessionType
);
void HandleMemberPropertiesChanged(
_In_ std::shared_ptr<XblMultiplayerSession> currentSession,
_In_ std::shared_ptr<XblMultiplayerSession> oldSession,
_In_ XblMultiplayerSessionType sessionType
);
void HandleSessionPropertiesChanged(
_In_ std::shared_ptr<XblMultiplayerSession> currentSession,
_In_ std::shared_ptr<XblMultiplayerSession> oldSession,
_In_ XblMultiplayerSessionType sessionType
);
void HandleHostChanged(
_In_ std::shared_ptr<XblMultiplayerSession> currentSession,
_In_ XblMultiplayerSessionType sessionType
);
void HandleMatchStatusChanged(
_In_ std::shared_ptr<XblMultiplayerSession> currentSession
);
void HandleInitializationStateChanged(
_In_ std::shared_ptr<XblMultiplayerSession> currentSession
);
void SynchronizedWriteCompleted(
_In_ std::error_code errorCode,
_In_ XblMultiplayerEventType eventType,
_In_ XblMultiplayerSessionType sessionType
);
mutable std::mutex m_clientRequestLock;
std::mutex m_synchronizeWriteWithTapLock;
std::atomic<bool> m_subscriptionsLostFired;
bool m_autoFillMembers{ false };
xsapi_internal_string m_lobbySessionTemplateName;
XblFunctionContext m_sessionChangedContext{ 0 };
XblFunctionContext m_connectionIdChangedContext{ 0 };
XblFunctionContext m_subscriptionLostContext{ 0 };
XblFunctionContext m_rtaResyncContext{ 0 };
MultiplayerEventQueue m_multiplayerEventQueue;
std::shared_ptr<XblContext> m_primaryXboxLiveContext;
std::shared_ptr<MultiplayerLocalUserManager> m_multiplayerLocalUserManager;
std::shared_ptr<MultiplayerClientPendingReader> m_lastPendingRead;
std::shared_ptr<MultiplayerClientPendingReader> m_latestPendingRead;
TaskQueue m_queue;
};
class MultiplayerMatchClient : public std::enable_shared_from_this<MultiplayerMatchClient>
{
public:
MultiplayerMatchClient(
_In_ const TaskQueue& queue,
_In_ std::shared_ptr<MultiplayerLocalUserManager> localUserManager
) noexcept;
~MultiplayerMatchClient() noexcept = default;
MultiplayerEventQueue DoWork();
const MultiplayerEventQueue& EventQueue();
// TODO remove in favor of assignment operator
void deep_copy_if_updated(_In_ const MultiplayerMatchClient& other);
XblMultiplayerMatchStatus MatchStatus() const;
void SetMatchStatus(_In_ XblMultiplayerMatchStatus status);
const std::chrono::seconds EstimatedMatchWaitTime() const;
HRESULT FindMatch(
_In_ const xsapi_internal_string& hopperName,
_In_ JsonValue& attributes,
_In_ const std::chrono::seconds& timeout,
_In_ std::shared_ptr<XblMultiplayerSession> session,
_In_ bool preserveSession = false
);
HRESULT FindMatch(
_In_ std::shared_ptr<XblMultiplayerSession> session,
_In_ bool preserveSession
);
void CancelMatch();
void UpdateSession(_In_ std::shared_ptr<XblMultiplayerSession> currentSession);
std::shared_ptr<XblMultiplayerSession> Session();
void HandleMatchStatusChanged(
_In_ std::shared_ptr<XblMultiplayerSession> matchSession
);
void HandleInitializationStateChanged(
_In_ std::shared_ptr<XblMultiplayerSession> matchSession
);
void OnSessionChanged(
_In_ const XblMultiplayerSessionChangeEventArgs& args
);
void SetQosMeasurements(
_In_ const JsonValue& measurements
) noexcept;
void ResubmitMatchmaking(
_In_ std::shared_ptr<XblMultiplayerSession> session
);
void HandleFindMatchCompleted(
_In_ Result<void> error
);
void DisableNextTimer(bool value);
bool m_disableNextTimer{ false };
private:
void CheckNextTimer();
void HandleSessionJoined();
void GetLatestSession();
void HandleQosMeasurements();
void HandleMatchFound(
_In_ std::shared_ptr<XblMultiplayerSession> currentSession
) noexcept;
HRESULT JoinSession(
_In_ std::shared_ptr<XblMultiplayerSession> session,
_In_ MultiplayerSessionCallback callback
) noexcept;
TaskQueue m_queue;
std::mutex m_lock;
std::mutex m_getSessionLock;
xbox::services::datetime m_nextTimerToFetchSession;
String m_hopperName;
JsonDocument m_attributes;
std::chrono::seconds m_timeout{};
bool m_preservingMatchmakingSession{ false };
std::atomic<XblMultiplayerMatchStatus> m_matchStatus{ XblMultiplayerMatchStatus::None };
mutable std::mutex m_multiplayerEventQueueLock;
MultiplayerEventQueue m_multiplayerEventQueue;
XblCreateMatchTicketResponse m_matchTicketResponse{};
XblMultiplayerSessionReference m_matchTicketSessionRef{};
std::shared_ptr<XblMultiplayerSession> m_matchSession;
std::shared_ptr<MultiplayerLocalUserManager> m_multiplayerLocalUserManager;
std::atomic<bool> m_getSessionInProgress{ false };
std::atomic<bool> m_joinTargetSessionComplete{ false };
Result<std::shared_ptr<XblMultiplayerSession>> m_joinTargetSessionResult;
};
class MultiplayerManagerUtils
{
public:
static bool IsMultiplayerSessionChangeType(
_In_ XblMultiplayerSessionChangeTypes diffType,
_In_ XblMultiplayerSessionChangeTypes value
)
{
return (diffType & value) == value;
}
static bool CompareSessions(
_In_ const std::shared_ptr<XblMultiplayerSession>& session1,
_In_ const std::shared_ptr<XblMultiplayerSession>& session2
);
static void SetJoinability(
_In_ XblMultiplayerJoinability value,
_In_ std::shared_ptr<XblMultiplayerSession> sessionToCommit,
_In_ bool isGameInProgress
);
static XblMultiplayerJoinability GetJoinability(
_In_ const XblMultiplayerSessionProperties& sessionProperties
);
static XblMultiplayerJoinability ConvertStringToJoinability(
_In_ const xsapi_internal_string& value
);
static xsapi_internal_string ConvertJoinabilityToString(_In_ XblMultiplayerJoinability value);
};
}}}}
| 35.02234 | 144 | 0.74846 | [
"vector"
] |
3ff3514e19228ebe64dad9b59e5607017bbfee81 | 108,053 | h | C | Include/10.0.17134.0/cppwinrt/winrt/Windows.Graphics.Display.h | sezero/windows-sdk-headers | e8e9d4d50769ded01a2df905c6bf4355eb3fa8b5 | [
"MIT"
] | 5 | 2020-05-29T06:22:17.000Z | 2021-11-28T08:21:38.000Z | Include/10.0.17134.0/cppwinrt/winrt/Windows.Graphics.Display.h | sezero/windows-sdk-headers | e8e9d4d50769ded01a2df905c6bf4355eb3fa8b5 | [
"MIT"
] | null | null | null | Include/10.0.17134.0/cppwinrt/winrt/Windows.Graphics.Display.h | sezero/windows-sdk-headers | e8e9d4d50769ded01a2df905c6bf4355eb3fa8b5 | [
"MIT"
] | 5 | 2020-05-30T04:15:11.000Z | 2021-11-28T08:48:56.000Z | // C++/WinRT v1.0.180227.3
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include "winrt/base.h"
WINRT_WARNING_PUSH
#include "winrt/Windows.Foundation.h"
#include "winrt/Windows.Foundation.Collections.h"
#include "winrt/impl/Windows.Storage.Streams.2.h"
#include "winrt/impl/Windows.Graphics.Display.2.h"
#include "winrt/Windows.Graphics.h"
namespace winrt::impl {
template <typename D> Windows::Graphics::Display::AdvancedColorKind consume_Windows_Graphics_Display_IAdvancedColorInfo<D>::CurrentAdvancedColorKind() const
{
Windows::Graphics::Display::AdvancedColorKind value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IAdvancedColorInfo)->get_CurrentAdvancedColorKind(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::Point consume_Windows_Graphics_Display_IAdvancedColorInfo<D>::RedPrimary() const
{
Windows::Foundation::Point value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IAdvancedColorInfo)->get_RedPrimary(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::Point consume_Windows_Graphics_Display_IAdvancedColorInfo<D>::GreenPrimary() const
{
Windows::Foundation::Point value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IAdvancedColorInfo)->get_GreenPrimary(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::Point consume_Windows_Graphics_Display_IAdvancedColorInfo<D>::BluePrimary() const
{
Windows::Foundation::Point value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IAdvancedColorInfo)->get_BluePrimary(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::Point consume_Windows_Graphics_Display_IAdvancedColorInfo<D>::WhitePoint() const
{
Windows::Foundation::Point value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IAdvancedColorInfo)->get_WhitePoint(put_abi(value)));
return value;
}
template <typename D> float consume_Windows_Graphics_Display_IAdvancedColorInfo<D>::MaxLuminanceInNits() const
{
float value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IAdvancedColorInfo)->get_MaxLuminanceInNits(&value));
return value;
}
template <typename D> float consume_Windows_Graphics_Display_IAdvancedColorInfo<D>::MinLuminanceInNits() const
{
float value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IAdvancedColorInfo)->get_MinLuminanceInNits(&value));
return value;
}
template <typename D> float consume_Windows_Graphics_Display_IAdvancedColorInfo<D>::MaxAverageFullFrameLuminanceInNits() const
{
float value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IAdvancedColorInfo)->get_MaxAverageFullFrameLuminanceInNits(&value));
return value;
}
template <typename D> float consume_Windows_Graphics_Display_IAdvancedColorInfo<D>::SdrWhiteLevelInNits() const
{
float value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IAdvancedColorInfo)->get_SdrWhiteLevelInNits(&value));
return value;
}
template <typename D> bool consume_Windows_Graphics_Display_IAdvancedColorInfo<D>::IsHdrMetadataFormatCurrentlySupported(Windows::Graphics::Display::HdrMetadataFormat const& format) const
{
bool result{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IAdvancedColorInfo)->IsHdrMetadataFormatCurrentlySupported(get_abi(format), &result));
return result;
}
template <typename D> bool consume_Windows_Graphics_Display_IAdvancedColorInfo<D>::IsAdvancedColorKindAvailable(Windows::Graphics::Display::AdvancedColorKind const& kind) const
{
bool result{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IAdvancedColorInfo)->IsAdvancedColorKindAvailable(get_abi(kind), &result));
return result;
}
template <typename D> bool consume_Windows_Graphics_Display_IBrightnessOverride<D>::IsSupported() const
{
bool value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IBrightnessOverride)->get_IsSupported(&value));
return value;
}
template <typename D> bool consume_Windows_Graphics_Display_IBrightnessOverride<D>::IsOverrideActive() const
{
bool value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IBrightnessOverride)->get_IsOverrideActive(&value));
return value;
}
template <typename D> double consume_Windows_Graphics_Display_IBrightnessOverride<D>::BrightnessLevel() const
{
double level{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IBrightnessOverride)->get_BrightnessLevel(&level));
return level;
}
template <typename D> void consume_Windows_Graphics_Display_IBrightnessOverride<D>::SetBrightnessLevel(double brightnessLevel, Windows::Graphics::Display::DisplayBrightnessOverrideOptions const& options) const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IBrightnessOverride)->SetBrightnessLevel(brightnessLevel, get_abi(options)));
}
template <typename D> void consume_Windows_Graphics_Display_IBrightnessOverride<D>::SetBrightnessScenario(Windows::Graphics::Display::DisplayBrightnessScenario const& scenario, Windows::Graphics::Display::DisplayBrightnessOverrideOptions const& options) const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IBrightnessOverride)->SetBrightnessScenario(get_abi(scenario), get_abi(options)));
}
template <typename D> double consume_Windows_Graphics_Display_IBrightnessOverride<D>::GetLevelForScenario(Windows::Graphics::Display::DisplayBrightnessScenario const& scenario) const
{
double brightnessLevel{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IBrightnessOverride)->GetLevelForScenario(get_abi(scenario), &brightnessLevel));
return brightnessLevel;
}
template <typename D> void consume_Windows_Graphics_Display_IBrightnessOverride<D>::StartOverride() const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IBrightnessOverride)->StartOverride());
}
template <typename D> void consume_Windows_Graphics_Display_IBrightnessOverride<D>::StopOverride() const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IBrightnessOverride)->StopOverride());
}
template <typename D> event_token consume_Windows_Graphics_Display_IBrightnessOverride<D>::IsSupportedChanged(Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::BrightnessOverride, Windows::Foundation::IInspectable> const& handler) const
{
event_token token{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IBrightnessOverride)->add_IsSupportedChanged(get_abi(handler), put_abi(token)));
return token;
}
template <typename D> event_revoker<Windows::Graphics::Display::IBrightnessOverride> consume_Windows_Graphics_Display_IBrightnessOverride<D>::IsSupportedChanged(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::BrightnessOverride, Windows::Foundation::IInspectable> const& handler) const
{
return impl::make_event_revoker<D, Windows::Graphics::Display::IBrightnessOverride>(this, &abi_t<Windows::Graphics::Display::IBrightnessOverride>::remove_IsSupportedChanged, IsSupportedChanged(handler));
}
template <typename D> void consume_Windows_Graphics_Display_IBrightnessOverride<D>::IsSupportedChanged(event_token const& token) const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IBrightnessOverride)->remove_IsSupportedChanged(get_abi(token)));
}
template <typename D> event_token consume_Windows_Graphics_Display_IBrightnessOverride<D>::IsOverrideActiveChanged(Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::BrightnessOverride, Windows::Foundation::IInspectable> const& handler) const
{
event_token token{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IBrightnessOverride)->add_IsOverrideActiveChanged(get_abi(handler), put_abi(token)));
return token;
}
template <typename D> event_revoker<Windows::Graphics::Display::IBrightnessOverride> consume_Windows_Graphics_Display_IBrightnessOverride<D>::IsOverrideActiveChanged(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::BrightnessOverride, Windows::Foundation::IInspectable> const& handler) const
{
return impl::make_event_revoker<D, Windows::Graphics::Display::IBrightnessOverride>(this, &abi_t<Windows::Graphics::Display::IBrightnessOverride>::remove_IsOverrideActiveChanged, IsOverrideActiveChanged(handler));
}
template <typename D> void consume_Windows_Graphics_Display_IBrightnessOverride<D>::IsOverrideActiveChanged(event_token const& token) const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IBrightnessOverride)->remove_IsOverrideActiveChanged(get_abi(token)));
}
template <typename D> event_token consume_Windows_Graphics_Display_IBrightnessOverride<D>::BrightnessLevelChanged(Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::BrightnessOverride, Windows::Foundation::IInspectable> const& handler) const
{
event_token token{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IBrightnessOverride)->add_BrightnessLevelChanged(get_abi(handler), put_abi(token)));
return token;
}
template <typename D> event_revoker<Windows::Graphics::Display::IBrightnessOverride> consume_Windows_Graphics_Display_IBrightnessOverride<D>::BrightnessLevelChanged(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::BrightnessOverride, Windows::Foundation::IInspectable> const& handler) const
{
return impl::make_event_revoker<D, Windows::Graphics::Display::IBrightnessOverride>(this, &abi_t<Windows::Graphics::Display::IBrightnessOverride>::remove_BrightnessLevelChanged, BrightnessLevelChanged(handler));
}
template <typename D> void consume_Windows_Graphics_Display_IBrightnessOverride<D>::BrightnessLevelChanged(event_token const& token) const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IBrightnessOverride)->remove_BrightnessLevelChanged(get_abi(token)));
}
template <typename D> double consume_Windows_Graphics_Display_IBrightnessOverrideSettings<D>::DesiredLevel() const
{
double value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IBrightnessOverrideSettings)->get_DesiredLevel(&value));
return value;
}
template <typename D> float consume_Windows_Graphics_Display_IBrightnessOverrideSettings<D>::DesiredNits() const
{
float value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IBrightnessOverrideSettings)->get_DesiredNits(&value));
return value;
}
template <typename D> Windows::Graphics::Display::BrightnessOverrideSettings consume_Windows_Graphics_Display_IBrightnessOverrideSettingsStatics<D>::CreateFromLevel(double level) const
{
Windows::Graphics::Display::BrightnessOverrideSettings result{ nullptr };
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IBrightnessOverrideSettingsStatics)->CreateFromLevel(level, put_abi(result)));
return result;
}
template <typename D> Windows::Graphics::Display::BrightnessOverrideSettings consume_Windows_Graphics_Display_IBrightnessOverrideSettingsStatics<D>::CreateFromNits(float nits) const
{
Windows::Graphics::Display::BrightnessOverrideSettings result{ nullptr };
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IBrightnessOverrideSettingsStatics)->CreateFromNits(nits, put_abi(result)));
return result;
}
template <typename D> Windows::Graphics::Display::BrightnessOverrideSettings consume_Windows_Graphics_Display_IBrightnessOverrideSettingsStatics<D>::CreateFromDisplayBrightnessOverrideScenario(Windows::Graphics::Display::DisplayBrightnessOverrideScenario const& overrideScenario) const
{
Windows::Graphics::Display::BrightnessOverrideSettings result{ nullptr };
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IBrightnessOverrideSettingsStatics)->CreateFromDisplayBrightnessOverrideScenario(get_abi(overrideScenario), put_abi(result)));
return result;
}
template <typename D> Windows::Graphics::Display::BrightnessOverride consume_Windows_Graphics_Display_IBrightnessOverrideStatics<D>::GetDefaultForSystem() const
{
Windows::Graphics::Display::BrightnessOverride value{ nullptr };
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IBrightnessOverrideStatics)->GetDefaultForSystem(put_abi(value)));
return value;
}
template <typename D> Windows::Graphics::Display::BrightnessOverride consume_Windows_Graphics_Display_IBrightnessOverrideStatics<D>::GetForCurrentView() const
{
Windows::Graphics::Display::BrightnessOverride value{ nullptr };
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IBrightnessOverrideStatics)->GetForCurrentView(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::IAsyncOperation<bool> consume_Windows_Graphics_Display_IBrightnessOverrideStatics<D>::SaveForSystemAsync(Windows::Graphics::Display::BrightnessOverride const& value) const
{
Windows::Foundation::IAsyncOperation<bool> operation{ nullptr };
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IBrightnessOverrideStatics)->SaveForSystemAsync(get_abi(value), put_abi(operation)));
return operation;
}
template <typename D> Windows::Graphics::Display::DisplayColorOverrideScenario consume_Windows_Graphics_Display_IColorOverrideSettings<D>::DesiredDisplayColorOverrideScenario() const
{
Windows::Graphics::Display::DisplayColorOverrideScenario value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IColorOverrideSettings)->get_DesiredDisplayColorOverrideScenario(put_abi(value)));
return value;
}
template <typename D> Windows::Graphics::Display::ColorOverrideSettings consume_Windows_Graphics_Display_IColorOverrideSettingsStatics<D>::CreateFromDisplayColorOverrideScenario(Windows::Graphics::Display::DisplayColorOverrideScenario const& overrideScenario) const
{
Windows::Graphics::Display::ColorOverrideSettings result{ nullptr };
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IColorOverrideSettingsStatics)->CreateFromDisplayColorOverrideScenario(get_abi(overrideScenario), put_abi(result)));
return result;
}
template <typename D> Windows::Graphics::Display::ColorOverrideSettings consume_Windows_Graphics_Display_IDisplayEnhancementOverride<D>::ColorOverrideSettings() const
{
Windows::Graphics::Display::ColorOverrideSettings value{ nullptr };
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayEnhancementOverride)->get_ColorOverrideSettings(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_Graphics_Display_IDisplayEnhancementOverride<D>::ColorOverrideSettings(Windows::Graphics::Display::ColorOverrideSettings const& value) const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayEnhancementOverride)->put_ColorOverrideSettings(get_abi(value)));
}
template <typename D> Windows::Graphics::Display::BrightnessOverrideSettings consume_Windows_Graphics_Display_IDisplayEnhancementOverride<D>::BrightnessOverrideSettings() const
{
Windows::Graphics::Display::BrightnessOverrideSettings value{ nullptr };
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayEnhancementOverride)->get_BrightnessOverrideSettings(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_Graphics_Display_IDisplayEnhancementOverride<D>::BrightnessOverrideSettings(Windows::Graphics::Display::BrightnessOverrideSettings const& value) const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayEnhancementOverride)->put_BrightnessOverrideSettings(get_abi(value)));
}
template <typename D> bool consume_Windows_Graphics_Display_IDisplayEnhancementOverride<D>::CanOverride() const
{
bool value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayEnhancementOverride)->get_CanOverride(&value));
return value;
}
template <typename D> bool consume_Windows_Graphics_Display_IDisplayEnhancementOverride<D>::IsOverrideActive() const
{
bool value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayEnhancementOverride)->get_IsOverrideActive(&value));
return value;
}
template <typename D> Windows::Graphics::Display::DisplayEnhancementOverrideCapabilities consume_Windows_Graphics_Display_IDisplayEnhancementOverride<D>::GetCurrentDisplayEnhancementOverrideCapabilities() const
{
Windows::Graphics::Display::DisplayEnhancementOverrideCapabilities value{ nullptr };
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayEnhancementOverride)->GetCurrentDisplayEnhancementOverrideCapabilities(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_Graphics_Display_IDisplayEnhancementOverride<D>::RequestOverride() const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayEnhancementOverride)->RequestOverride());
}
template <typename D> void consume_Windows_Graphics_Display_IDisplayEnhancementOverride<D>::StopOverride() const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayEnhancementOverride)->StopOverride());
}
template <typename D> event_token consume_Windows_Graphics_Display_IDisplayEnhancementOverride<D>::CanOverrideChanged(Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayEnhancementOverride, Windows::Foundation::IInspectable> const& handler) const
{
event_token token{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayEnhancementOverride)->add_CanOverrideChanged(get_abi(handler), put_abi(token)));
return token;
}
template <typename D> event_revoker<Windows::Graphics::Display::IDisplayEnhancementOverride> consume_Windows_Graphics_Display_IDisplayEnhancementOverride<D>::CanOverrideChanged(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayEnhancementOverride, Windows::Foundation::IInspectable> const& handler) const
{
return impl::make_event_revoker<D, Windows::Graphics::Display::IDisplayEnhancementOverride>(this, &abi_t<Windows::Graphics::Display::IDisplayEnhancementOverride>::remove_CanOverrideChanged, CanOverrideChanged(handler));
}
template <typename D> void consume_Windows_Graphics_Display_IDisplayEnhancementOverride<D>::CanOverrideChanged(event_token const& token) const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayEnhancementOverride)->remove_CanOverrideChanged(get_abi(token)));
}
template <typename D> event_token consume_Windows_Graphics_Display_IDisplayEnhancementOverride<D>::IsOverrideActiveChanged(Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayEnhancementOverride, Windows::Foundation::IInspectable> const& handler) const
{
event_token token{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayEnhancementOverride)->add_IsOverrideActiveChanged(get_abi(handler), put_abi(token)));
return token;
}
template <typename D> event_revoker<Windows::Graphics::Display::IDisplayEnhancementOverride> consume_Windows_Graphics_Display_IDisplayEnhancementOverride<D>::IsOverrideActiveChanged(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayEnhancementOverride, Windows::Foundation::IInspectable> const& handler) const
{
return impl::make_event_revoker<D, Windows::Graphics::Display::IDisplayEnhancementOverride>(this, &abi_t<Windows::Graphics::Display::IDisplayEnhancementOverride>::remove_IsOverrideActiveChanged, IsOverrideActiveChanged(handler));
}
template <typename D> void consume_Windows_Graphics_Display_IDisplayEnhancementOverride<D>::IsOverrideActiveChanged(event_token const& token) const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayEnhancementOverride)->remove_IsOverrideActiveChanged(get_abi(token)));
}
template <typename D> event_token consume_Windows_Graphics_Display_IDisplayEnhancementOverride<D>::DisplayEnhancementOverrideCapabilitiesChanged(Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayEnhancementOverride, Windows::Graphics::Display::DisplayEnhancementOverrideCapabilitiesChangedEventArgs> const& handler) const
{
event_token token{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayEnhancementOverride)->add_DisplayEnhancementOverrideCapabilitiesChanged(get_abi(handler), put_abi(token)));
return token;
}
template <typename D> event_revoker<Windows::Graphics::Display::IDisplayEnhancementOverride> consume_Windows_Graphics_Display_IDisplayEnhancementOverride<D>::DisplayEnhancementOverrideCapabilitiesChanged(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayEnhancementOverride, Windows::Graphics::Display::DisplayEnhancementOverrideCapabilitiesChangedEventArgs> const& handler) const
{
return impl::make_event_revoker<D, Windows::Graphics::Display::IDisplayEnhancementOverride>(this, &abi_t<Windows::Graphics::Display::IDisplayEnhancementOverride>::remove_DisplayEnhancementOverrideCapabilitiesChanged, DisplayEnhancementOverrideCapabilitiesChanged(handler));
}
template <typename D> void consume_Windows_Graphics_Display_IDisplayEnhancementOverride<D>::DisplayEnhancementOverrideCapabilitiesChanged(event_token const& token) const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayEnhancementOverride)->remove_DisplayEnhancementOverrideCapabilitiesChanged(get_abi(token)));
}
template <typename D> bool consume_Windows_Graphics_Display_IDisplayEnhancementOverrideCapabilities<D>::IsBrightnessControlSupported() const
{
bool value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayEnhancementOverrideCapabilities)->get_IsBrightnessControlSupported(&value));
return value;
}
template <typename D> bool consume_Windows_Graphics_Display_IDisplayEnhancementOverrideCapabilities<D>::IsBrightnessNitsControlSupported() const
{
bool value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayEnhancementOverrideCapabilities)->get_IsBrightnessNitsControlSupported(&value));
return value;
}
template <typename D> Windows::Foundation::Collections::IVectorView<Windows::Graphics::Display::NitRange> consume_Windows_Graphics_Display_IDisplayEnhancementOverrideCapabilities<D>::GetSupportedNitRanges() const
{
Windows::Foundation::Collections::IVectorView<Windows::Graphics::Display::NitRange> result{ nullptr };
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayEnhancementOverrideCapabilities)->GetSupportedNitRanges(put_abi(result)));
return result;
}
template <typename D> Windows::Graphics::Display::DisplayEnhancementOverrideCapabilities consume_Windows_Graphics_Display_IDisplayEnhancementOverrideCapabilitiesChangedEventArgs<D>::Capabilities() const
{
Windows::Graphics::Display::DisplayEnhancementOverrideCapabilities value{ nullptr };
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayEnhancementOverrideCapabilitiesChangedEventArgs)->get_Capabilities(put_abi(value)));
return value;
}
template <typename D> Windows::Graphics::Display::DisplayEnhancementOverride consume_Windows_Graphics_Display_IDisplayEnhancementOverrideStatics<D>::GetForCurrentView() const
{
Windows::Graphics::Display::DisplayEnhancementOverride result{ nullptr };
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayEnhancementOverrideStatics)->GetForCurrentView(put_abi(result)));
return result;
}
template <typename D> Windows::Graphics::Display::DisplayOrientations consume_Windows_Graphics_Display_IDisplayInformation<D>::CurrentOrientation() const
{
Windows::Graphics::Display::DisplayOrientations value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformation)->get_CurrentOrientation(put_abi(value)));
return value;
}
template <typename D> Windows::Graphics::Display::DisplayOrientations consume_Windows_Graphics_Display_IDisplayInformation<D>::NativeOrientation() const
{
Windows::Graphics::Display::DisplayOrientations value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformation)->get_NativeOrientation(put_abi(value)));
return value;
}
template <typename D> event_token consume_Windows_Graphics_Display_IDisplayInformation<D>::OrientationChanged(Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation, Windows::Foundation::IInspectable> const& handler) const
{
event_token token{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformation)->add_OrientationChanged(get_abi(handler), put_abi(token)));
return token;
}
template <typename D> event_revoker<Windows::Graphics::Display::IDisplayInformation> consume_Windows_Graphics_Display_IDisplayInformation<D>::OrientationChanged(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation, Windows::Foundation::IInspectable> const& handler) const
{
return impl::make_event_revoker<D, Windows::Graphics::Display::IDisplayInformation>(this, &abi_t<Windows::Graphics::Display::IDisplayInformation>::remove_OrientationChanged, OrientationChanged(handler));
}
template <typename D> void consume_Windows_Graphics_Display_IDisplayInformation<D>::OrientationChanged(event_token const& token) const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformation)->remove_OrientationChanged(get_abi(token)));
}
template <typename D> Windows::Graphics::Display::ResolutionScale consume_Windows_Graphics_Display_IDisplayInformation<D>::ResolutionScale() const
{
Windows::Graphics::Display::ResolutionScale value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformation)->get_ResolutionScale(put_abi(value)));
return value;
}
template <typename D> float consume_Windows_Graphics_Display_IDisplayInformation<D>::LogicalDpi() const
{
float value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformation)->get_LogicalDpi(&value));
return value;
}
template <typename D> float consume_Windows_Graphics_Display_IDisplayInformation<D>::RawDpiX() const
{
float value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformation)->get_RawDpiX(&value));
return value;
}
template <typename D> float consume_Windows_Graphics_Display_IDisplayInformation<D>::RawDpiY() const
{
float value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformation)->get_RawDpiY(&value));
return value;
}
template <typename D> event_token consume_Windows_Graphics_Display_IDisplayInformation<D>::DpiChanged(Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation, Windows::Foundation::IInspectable> const& handler) const
{
event_token token{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformation)->add_DpiChanged(get_abi(handler), put_abi(token)));
return token;
}
template <typename D> event_revoker<Windows::Graphics::Display::IDisplayInformation> consume_Windows_Graphics_Display_IDisplayInformation<D>::DpiChanged(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation, Windows::Foundation::IInspectable> const& handler) const
{
return impl::make_event_revoker<D, Windows::Graphics::Display::IDisplayInformation>(this, &abi_t<Windows::Graphics::Display::IDisplayInformation>::remove_DpiChanged, DpiChanged(handler));
}
template <typename D> void consume_Windows_Graphics_Display_IDisplayInformation<D>::DpiChanged(event_token const& token) const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformation)->remove_DpiChanged(get_abi(token)));
}
template <typename D> bool consume_Windows_Graphics_Display_IDisplayInformation<D>::StereoEnabled() const
{
bool value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformation)->get_StereoEnabled(&value));
return value;
}
template <typename D> event_token consume_Windows_Graphics_Display_IDisplayInformation<D>::StereoEnabledChanged(Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation, Windows::Foundation::IInspectable> const& handler) const
{
event_token token{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformation)->add_StereoEnabledChanged(get_abi(handler), put_abi(token)));
return token;
}
template <typename D> event_revoker<Windows::Graphics::Display::IDisplayInformation> consume_Windows_Graphics_Display_IDisplayInformation<D>::StereoEnabledChanged(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation, Windows::Foundation::IInspectable> const& handler) const
{
return impl::make_event_revoker<D, Windows::Graphics::Display::IDisplayInformation>(this, &abi_t<Windows::Graphics::Display::IDisplayInformation>::remove_StereoEnabledChanged, StereoEnabledChanged(handler));
}
template <typename D> void consume_Windows_Graphics_Display_IDisplayInformation<D>::StereoEnabledChanged(event_token const& token) const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformation)->remove_StereoEnabledChanged(get_abi(token)));
}
template <typename D> Windows::Foundation::IAsyncOperation<Windows::Storage::Streams::IRandomAccessStream> consume_Windows_Graphics_Display_IDisplayInformation<D>::GetColorProfileAsync() const
{
Windows::Foundation::IAsyncOperation<Windows::Storage::Streams::IRandomAccessStream> asyncInfo{ nullptr };
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformation)->GetColorProfileAsync(put_abi(asyncInfo)));
return asyncInfo;
}
template <typename D> event_token consume_Windows_Graphics_Display_IDisplayInformation<D>::ColorProfileChanged(Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation, Windows::Foundation::IInspectable> const& handler) const
{
event_token token{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformation)->add_ColorProfileChanged(get_abi(handler), put_abi(token)));
return token;
}
template <typename D> event_revoker<Windows::Graphics::Display::IDisplayInformation> consume_Windows_Graphics_Display_IDisplayInformation<D>::ColorProfileChanged(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation, Windows::Foundation::IInspectable> const& handler) const
{
return impl::make_event_revoker<D, Windows::Graphics::Display::IDisplayInformation>(this, &abi_t<Windows::Graphics::Display::IDisplayInformation>::remove_ColorProfileChanged, ColorProfileChanged(handler));
}
template <typename D> void consume_Windows_Graphics_Display_IDisplayInformation<D>::ColorProfileChanged(event_token const& token) const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformation)->remove_ColorProfileChanged(get_abi(token)));
}
template <typename D> double consume_Windows_Graphics_Display_IDisplayInformation2<D>::RawPixelsPerViewPixel() const
{
double value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformation2)->get_RawPixelsPerViewPixel(&value));
return value;
}
template <typename D> Windows::Foundation::IReference<double> consume_Windows_Graphics_Display_IDisplayInformation3<D>::DiagonalSizeInInches() const
{
Windows::Foundation::IReference<double> value{ nullptr };
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformation3)->get_DiagonalSizeInInches(put_abi(value)));
return value;
}
template <typename D> uint32_t consume_Windows_Graphics_Display_IDisplayInformation4<D>::ScreenWidthInRawPixels() const
{
uint32_t value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformation4)->get_ScreenWidthInRawPixels(&value));
return value;
}
template <typename D> uint32_t consume_Windows_Graphics_Display_IDisplayInformation4<D>::ScreenHeightInRawPixels() const
{
uint32_t value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformation4)->get_ScreenHeightInRawPixels(&value));
return value;
}
template <typename D> Windows::Graphics::Display::AdvancedColorInfo consume_Windows_Graphics_Display_IDisplayInformation5<D>::GetAdvancedColorInfo() const
{
Windows::Graphics::Display::AdvancedColorInfo value{ nullptr };
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformation5)->GetAdvancedColorInfo(put_abi(value)));
return value;
}
template <typename D> event_token consume_Windows_Graphics_Display_IDisplayInformation5<D>::AdvancedColorInfoChanged(Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation, Windows::Foundation::IInspectable> const& handler) const
{
event_token token{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformation5)->add_AdvancedColorInfoChanged(get_abi(handler), put_abi(token)));
return token;
}
template <typename D> event_revoker<Windows::Graphics::Display::IDisplayInformation5> consume_Windows_Graphics_Display_IDisplayInformation5<D>::AdvancedColorInfoChanged(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation, Windows::Foundation::IInspectable> const& handler) const
{
return impl::make_event_revoker<D, Windows::Graphics::Display::IDisplayInformation5>(this, &abi_t<Windows::Graphics::Display::IDisplayInformation5>::remove_AdvancedColorInfoChanged, AdvancedColorInfoChanged(handler));
}
template <typename D> void consume_Windows_Graphics_Display_IDisplayInformation5<D>::AdvancedColorInfoChanged(event_token const& token) const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformation5)->remove_AdvancedColorInfoChanged(get_abi(token)));
}
template <typename D> Windows::Graphics::Display::DisplayInformation consume_Windows_Graphics_Display_IDisplayInformationStatics<D>::GetForCurrentView() const
{
Windows::Graphics::Display::DisplayInformation current{ nullptr };
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformationStatics)->GetForCurrentView(put_abi(current)));
return current;
}
template <typename D> Windows::Graphics::Display::DisplayOrientations consume_Windows_Graphics_Display_IDisplayInformationStatics<D>::AutoRotationPreferences() const
{
Windows::Graphics::Display::DisplayOrientations value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformationStatics)->get_AutoRotationPreferences(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_Graphics_Display_IDisplayInformationStatics<D>::AutoRotationPreferences(Windows::Graphics::Display::DisplayOrientations const& value) const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformationStatics)->put_AutoRotationPreferences(get_abi(value)));
}
template <typename D> event_token consume_Windows_Graphics_Display_IDisplayInformationStatics<D>::DisplayContentsInvalidated(Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation, Windows::Foundation::IInspectable> const& handler) const
{
event_token token{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformationStatics)->add_DisplayContentsInvalidated(get_abi(handler), put_abi(token)));
return token;
}
template <typename D> event_revoker<Windows::Graphics::Display::IDisplayInformationStatics> consume_Windows_Graphics_Display_IDisplayInformationStatics<D>::DisplayContentsInvalidated(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation, Windows::Foundation::IInspectable> const& handler) const
{
return impl::make_event_revoker<D, Windows::Graphics::Display::IDisplayInformationStatics>(this, &abi_t<Windows::Graphics::Display::IDisplayInformationStatics>::remove_DisplayContentsInvalidated, DisplayContentsInvalidated(handler));
}
template <typename D> void consume_Windows_Graphics_Display_IDisplayInformationStatics<D>::DisplayContentsInvalidated(event_token const& token) const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayInformationStatics)->remove_DisplayContentsInvalidated(get_abi(token)));
}
template <typename D> Windows::Graphics::Display::DisplayOrientations consume_Windows_Graphics_Display_IDisplayPropertiesStatics<D>::CurrentOrientation() const
{
Windows::Graphics::Display::DisplayOrientations value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayPropertiesStatics)->get_CurrentOrientation(put_abi(value)));
return value;
}
template <typename D> Windows::Graphics::Display::DisplayOrientations consume_Windows_Graphics_Display_IDisplayPropertiesStatics<D>::NativeOrientation() const
{
Windows::Graphics::Display::DisplayOrientations value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayPropertiesStatics)->get_NativeOrientation(put_abi(value)));
return value;
}
template <typename D> Windows::Graphics::Display::DisplayOrientations consume_Windows_Graphics_Display_IDisplayPropertiesStatics<D>::AutoRotationPreferences() const
{
Windows::Graphics::Display::DisplayOrientations value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayPropertiesStatics)->get_AutoRotationPreferences(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_Graphics_Display_IDisplayPropertiesStatics<D>::AutoRotationPreferences(Windows::Graphics::Display::DisplayOrientations const& value) const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayPropertiesStatics)->put_AutoRotationPreferences(get_abi(value)));
}
template <typename D> event_token consume_Windows_Graphics_Display_IDisplayPropertiesStatics<D>::OrientationChanged(Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler) const
{
event_token token{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayPropertiesStatics)->add_OrientationChanged(get_abi(handler), put_abi(token)));
return token;
}
template <typename D> event_revoker<Windows::Graphics::Display::IDisplayPropertiesStatics> consume_Windows_Graphics_Display_IDisplayPropertiesStatics<D>::OrientationChanged(auto_revoke_t, Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler) const
{
return impl::make_event_revoker<D, Windows::Graphics::Display::IDisplayPropertiesStatics>(this, &abi_t<Windows::Graphics::Display::IDisplayPropertiesStatics>::remove_OrientationChanged, OrientationChanged(handler));
}
template <typename D> void consume_Windows_Graphics_Display_IDisplayPropertiesStatics<D>::OrientationChanged(event_token const& token) const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayPropertiesStatics)->remove_OrientationChanged(get_abi(token)));
}
template <typename D> Windows::Graphics::Display::ResolutionScale consume_Windows_Graphics_Display_IDisplayPropertiesStatics<D>::ResolutionScale() const
{
Windows::Graphics::Display::ResolutionScale value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayPropertiesStatics)->get_ResolutionScale(put_abi(value)));
return value;
}
template <typename D> float consume_Windows_Graphics_Display_IDisplayPropertiesStatics<D>::LogicalDpi() const
{
float value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayPropertiesStatics)->get_LogicalDpi(&value));
return value;
}
template <typename D> event_token consume_Windows_Graphics_Display_IDisplayPropertiesStatics<D>::LogicalDpiChanged(Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler) const
{
event_token token{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayPropertiesStatics)->add_LogicalDpiChanged(get_abi(handler), put_abi(token)));
return token;
}
template <typename D> event_revoker<Windows::Graphics::Display::IDisplayPropertiesStatics> consume_Windows_Graphics_Display_IDisplayPropertiesStatics<D>::LogicalDpiChanged(auto_revoke_t, Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler) const
{
return impl::make_event_revoker<D, Windows::Graphics::Display::IDisplayPropertiesStatics>(this, &abi_t<Windows::Graphics::Display::IDisplayPropertiesStatics>::remove_LogicalDpiChanged, LogicalDpiChanged(handler));
}
template <typename D> void consume_Windows_Graphics_Display_IDisplayPropertiesStatics<D>::LogicalDpiChanged(event_token const& token) const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayPropertiesStatics)->remove_LogicalDpiChanged(get_abi(token)));
}
template <typename D> bool consume_Windows_Graphics_Display_IDisplayPropertiesStatics<D>::StereoEnabled() const
{
bool value{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayPropertiesStatics)->get_StereoEnabled(&value));
return value;
}
template <typename D> event_token consume_Windows_Graphics_Display_IDisplayPropertiesStatics<D>::StereoEnabledChanged(Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler) const
{
event_token token{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayPropertiesStatics)->add_StereoEnabledChanged(get_abi(handler), put_abi(token)));
return token;
}
template <typename D> event_revoker<Windows::Graphics::Display::IDisplayPropertiesStatics> consume_Windows_Graphics_Display_IDisplayPropertiesStatics<D>::StereoEnabledChanged(auto_revoke_t, Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler) const
{
return impl::make_event_revoker<D, Windows::Graphics::Display::IDisplayPropertiesStatics>(this, &abi_t<Windows::Graphics::Display::IDisplayPropertiesStatics>::remove_StereoEnabledChanged, StereoEnabledChanged(handler));
}
template <typename D> void consume_Windows_Graphics_Display_IDisplayPropertiesStatics<D>::StereoEnabledChanged(event_token const& token) const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayPropertiesStatics)->remove_StereoEnabledChanged(get_abi(token)));
}
template <typename D> Windows::Foundation::IAsyncOperation<Windows::Storage::Streams::IRandomAccessStream> consume_Windows_Graphics_Display_IDisplayPropertiesStatics<D>::GetColorProfileAsync() const
{
Windows::Foundation::IAsyncOperation<Windows::Storage::Streams::IRandomAccessStream> asyncInfo{ nullptr };
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayPropertiesStatics)->GetColorProfileAsync(put_abi(asyncInfo)));
return asyncInfo;
}
template <typename D> event_token consume_Windows_Graphics_Display_IDisplayPropertiesStatics<D>::ColorProfileChanged(Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler) const
{
event_token token{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayPropertiesStatics)->add_ColorProfileChanged(get_abi(handler), put_abi(token)));
return token;
}
template <typename D> event_revoker<Windows::Graphics::Display::IDisplayPropertiesStatics> consume_Windows_Graphics_Display_IDisplayPropertiesStatics<D>::ColorProfileChanged(auto_revoke_t, Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler) const
{
return impl::make_event_revoker<D, Windows::Graphics::Display::IDisplayPropertiesStatics>(this, &abi_t<Windows::Graphics::Display::IDisplayPropertiesStatics>::remove_ColorProfileChanged, ColorProfileChanged(handler));
}
template <typename D> void consume_Windows_Graphics_Display_IDisplayPropertiesStatics<D>::ColorProfileChanged(event_token const& token) const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayPropertiesStatics)->remove_ColorProfileChanged(get_abi(token)));
}
template <typename D> event_token consume_Windows_Graphics_Display_IDisplayPropertiesStatics<D>::DisplayContentsInvalidated(Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler) const
{
event_token token{};
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayPropertiesStatics)->add_DisplayContentsInvalidated(get_abi(handler), put_abi(token)));
return token;
}
template <typename D> event_revoker<Windows::Graphics::Display::IDisplayPropertiesStatics> consume_Windows_Graphics_Display_IDisplayPropertiesStatics<D>::DisplayContentsInvalidated(auto_revoke_t, Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler) const
{
return impl::make_event_revoker<D, Windows::Graphics::Display::IDisplayPropertiesStatics>(this, &abi_t<Windows::Graphics::Display::IDisplayPropertiesStatics>::remove_DisplayContentsInvalidated, DisplayContentsInvalidated(handler));
}
template <typename D> void consume_Windows_Graphics_Display_IDisplayPropertiesStatics<D>::DisplayContentsInvalidated(event_token const& token) const
{
check_hresult(WINRT_SHIM(Windows::Graphics::Display::IDisplayPropertiesStatics)->remove_DisplayContentsInvalidated(get_abi(token)));
}
template <> struct delegate<Windows::Graphics::Display::DisplayPropertiesEventHandler>
{
template <typename H>
struct type : implements_delegate<Windows::Graphics::Display::DisplayPropertiesEventHandler, H>
{
type(H&& handler) : implements_delegate<Windows::Graphics::Display::DisplayPropertiesEventHandler, H>(std::forward<H>(handler)) {}
HRESULT __stdcall Invoke(void* sender) noexcept final
{
try
{
(*this)(*reinterpret_cast<Windows::Foundation::IInspectable const*>(&sender));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
};
template <typename D>
struct produce<D, Windows::Graphics::Display::IAdvancedColorInfo> : produce_base<D, Windows::Graphics::Display::IAdvancedColorInfo>
{
HRESULT __stdcall get_CurrentAdvancedColorKind(Windows::Graphics::Display::AdvancedColorKind* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Graphics::Display::AdvancedColorKind>(this->shim().CurrentAdvancedColorKind());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_RedPrimary(Windows::Foundation::Point* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Foundation::Point>(this->shim().RedPrimary());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_GreenPrimary(Windows::Foundation::Point* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Foundation::Point>(this->shim().GreenPrimary());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_BluePrimary(Windows::Foundation::Point* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Foundation::Point>(this->shim().BluePrimary());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_WhitePoint(Windows::Foundation::Point* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Foundation::Point>(this->shim().WhitePoint());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_MaxLuminanceInNits(float* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<float>(this->shim().MaxLuminanceInNits());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_MinLuminanceInNits(float* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<float>(this->shim().MinLuminanceInNits());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_MaxAverageFullFrameLuminanceInNits(float* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<float>(this->shim().MaxAverageFullFrameLuminanceInNits());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_SdrWhiteLevelInNits(float* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<float>(this->shim().SdrWhiteLevelInNits());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall IsHdrMetadataFormatCurrentlySupported(Windows::Graphics::Display::HdrMetadataFormat format, bool* result) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_from<bool>(this->shim().IsHdrMetadataFormatCurrentlySupported(*reinterpret_cast<Windows::Graphics::Display::HdrMetadataFormat const*>(&format)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall IsAdvancedColorKindAvailable(Windows::Graphics::Display::AdvancedColorKind kind, bool* result) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_from<bool>(this->shim().IsAdvancedColorKindAvailable(*reinterpret_cast<Windows::Graphics::Display::AdvancedColorKind const*>(&kind)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Graphics::Display::IBrightnessOverride> : produce_base<D, Windows::Graphics::Display::IBrightnessOverride>
{
HRESULT __stdcall get_IsSupported(bool* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<bool>(this->shim().IsSupported());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_IsOverrideActive(bool* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<bool>(this->shim().IsOverrideActive());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_BrightnessLevel(double* level) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*level = detach_from<double>(this->shim().BrightnessLevel());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall SetBrightnessLevel(double brightnessLevel, Windows::Graphics::Display::DisplayBrightnessOverrideOptions options) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetBrightnessLevel(brightnessLevel, *reinterpret_cast<Windows::Graphics::Display::DisplayBrightnessOverrideOptions const*>(&options));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall SetBrightnessScenario(Windows::Graphics::Display::DisplayBrightnessScenario scenario, Windows::Graphics::Display::DisplayBrightnessOverrideOptions options) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetBrightnessScenario(*reinterpret_cast<Windows::Graphics::Display::DisplayBrightnessScenario const*>(&scenario), *reinterpret_cast<Windows::Graphics::Display::DisplayBrightnessOverrideOptions const*>(&options));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall GetLevelForScenario(Windows::Graphics::Display::DisplayBrightnessScenario scenario, double* brightnessLevel) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*brightnessLevel = detach_from<double>(this->shim().GetLevelForScenario(*reinterpret_cast<Windows::Graphics::Display::DisplayBrightnessScenario const*>(&scenario)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall StartOverride() noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().StartOverride();
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall StopOverride() noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().StopOverride();
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall add_IsSupportedChanged(void* handler, event_token* token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*token = detach_from<event_token>(this->shim().IsSupportedChanged(*reinterpret_cast<Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::BrightnessOverride, Windows::Foundation::IInspectable> const*>(&handler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_IsSupportedChanged(event_token token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().IsSupportedChanged(*reinterpret_cast<event_token const*>(&token));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall add_IsOverrideActiveChanged(void* handler, event_token* token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*token = detach_from<event_token>(this->shim().IsOverrideActiveChanged(*reinterpret_cast<Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::BrightnessOverride, Windows::Foundation::IInspectable> const*>(&handler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_IsOverrideActiveChanged(event_token token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().IsOverrideActiveChanged(*reinterpret_cast<event_token const*>(&token));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall add_BrightnessLevelChanged(void* handler, event_token* token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*token = detach_from<event_token>(this->shim().BrightnessLevelChanged(*reinterpret_cast<Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::BrightnessOverride, Windows::Foundation::IInspectable> const*>(&handler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_BrightnessLevelChanged(event_token token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().BrightnessLevelChanged(*reinterpret_cast<event_token const*>(&token));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Graphics::Display::IBrightnessOverrideSettings> : produce_base<D, Windows::Graphics::Display::IBrightnessOverrideSettings>
{
HRESULT __stdcall get_DesiredLevel(double* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<double>(this->shim().DesiredLevel());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_DesiredNits(float* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<float>(this->shim().DesiredNits());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Graphics::Display::IBrightnessOverrideSettingsStatics> : produce_base<D, Windows::Graphics::Display::IBrightnessOverrideSettingsStatics>
{
HRESULT __stdcall CreateFromLevel(double level, void** result) noexcept final
{
try
{
*result = nullptr;
typename D::abi_guard guard(this->shim());
*result = detach_from<Windows::Graphics::Display::BrightnessOverrideSettings>(this->shim().CreateFromLevel(level));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall CreateFromNits(float nits, void** result) noexcept final
{
try
{
*result = nullptr;
typename D::abi_guard guard(this->shim());
*result = detach_from<Windows::Graphics::Display::BrightnessOverrideSettings>(this->shim().CreateFromNits(nits));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall CreateFromDisplayBrightnessOverrideScenario(Windows::Graphics::Display::DisplayBrightnessOverrideScenario overrideScenario, void** result) noexcept final
{
try
{
*result = nullptr;
typename D::abi_guard guard(this->shim());
*result = detach_from<Windows::Graphics::Display::BrightnessOverrideSettings>(this->shim().CreateFromDisplayBrightnessOverrideScenario(*reinterpret_cast<Windows::Graphics::Display::DisplayBrightnessOverrideScenario const*>(&overrideScenario)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Graphics::Display::IBrightnessOverrideStatics> : produce_base<D, Windows::Graphics::Display::IBrightnessOverrideStatics>
{
HRESULT __stdcall GetDefaultForSystem(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Graphics::Display::BrightnessOverride>(this->shim().GetDefaultForSystem());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall GetForCurrentView(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Graphics::Display::BrightnessOverride>(this->shim().GetForCurrentView());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall SaveForSystemAsync(void* value, void** operation) noexcept final
{
try
{
*operation = nullptr;
typename D::abi_guard guard(this->shim());
*operation = detach_from<Windows::Foundation::IAsyncOperation<bool>>(this->shim().SaveForSystemAsync(*reinterpret_cast<Windows::Graphics::Display::BrightnessOverride const*>(&value)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Graphics::Display::IColorOverrideSettings> : produce_base<D, Windows::Graphics::Display::IColorOverrideSettings>
{
HRESULT __stdcall get_DesiredDisplayColorOverrideScenario(Windows::Graphics::Display::DisplayColorOverrideScenario* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Graphics::Display::DisplayColorOverrideScenario>(this->shim().DesiredDisplayColorOverrideScenario());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Graphics::Display::IColorOverrideSettingsStatics> : produce_base<D, Windows::Graphics::Display::IColorOverrideSettingsStatics>
{
HRESULT __stdcall CreateFromDisplayColorOverrideScenario(Windows::Graphics::Display::DisplayColorOverrideScenario overrideScenario, void** result) noexcept final
{
try
{
*result = nullptr;
typename D::abi_guard guard(this->shim());
*result = detach_from<Windows::Graphics::Display::ColorOverrideSettings>(this->shim().CreateFromDisplayColorOverrideScenario(*reinterpret_cast<Windows::Graphics::Display::DisplayColorOverrideScenario const*>(&overrideScenario)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Graphics::Display::IDisplayEnhancementOverride> : produce_base<D, Windows::Graphics::Display::IDisplayEnhancementOverride>
{
HRESULT __stdcall get_ColorOverrideSettings(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Graphics::Display::ColorOverrideSettings>(this->shim().ColorOverrideSettings());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall put_ColorOverrideSettings(void* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().ColorOverrideSettings(*reinterpret_cast<Windows::Graphics::Display::ColorOverrideSettings const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_BrightnessOverrideSettings(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Graphics::Display::BrightnessOverrideSettings>(this->shim().BrightnessOverrideSettings());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall put_BrightnessOverrideSettings(void* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().BrightnessOverrideSettings(*reinterpret_cast<Windows::Graphics::Display::BrightnessOverrideSettings const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_CanOverride(bool* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<bool>(this->shim().CanOverride());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_IsOverrideActive(bool* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<bool>(this->shim().IsOverrideActive());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall GetCurrentDisplayEnhancementOverrideCapabilities(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Graphics::Display::DisplayEnhancementOverrideCapabilities>(this->shim().GetCurrentDisplayEnhancementOverrideCapabilities());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall RequestOverride() noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().RequestOverride();
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall StopOverride() noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().StopOverride();
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall add_CanOverrideChanged(void* handler, event_token* token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*token = detach_from<event_token>(this->shim().CanOverrideChanged(*reinterpret_cast<Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayEnhancementOverride, Windows::Foundation::IInspectable> const*>(&handler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_CanOverrideChanged(event_token token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().CanOverrideChanged(*reinterpret_cast<event_token const*>(&token));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall add_IsOverrideActiveChanged(void* handler, event_token* token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*token = detach_from<event_token>(this->shim().IsOverrideActiveChanged(*reinterpret_cast<Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayEnhancementOverride, Windows::Foundation::IInspectable> const*>(&handler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_IsOverrideActiveChanged(event_token token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().IsOverrideActiveChanged(*reinterpret_cast<event_token const*>(&token));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall add_DisplayEnhancementOverrideCapabilitiesChanged(void* handler, event_token* token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*token = detach_from<event_token>(this->shim().DisplayEnhancementOverrideCapabilitiesChanged(*reinterpret_cast<Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayEnhancementOverride, Windows::Graphics::Display::DisplayEnhancementOverrideCapabilitiesChangedEventArgs> const*>(&handler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_DisplayEnhancementOverrideCapabilitiesChanged(event_token token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().DisplayEnhancementOverrideCapabilitiesChanged(*reinterpret_cast<event_token const*>(&token));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Graphics::Display::IDisplayEnhancementOverrideCapabilities> : produce_base<D, Windows::Graphics::Display::IDisplayEnhancementOverrideCapabilities>
{
HRESULT __stdcall get_IsBrightnessControlSupported(bool* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<bool>(this->shim().IsBrightnessControlSupported());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_IsBrightnessNitsControlSupported(bool* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<bool>(this->shim().IsBrightnessNitsControlSupported());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall GetSupportedNitRanges(void** result) noexcept final
{
try
{
*result = nullptr;
typename D::abi_guard guard(this->shim());
*result = detach_from<Windows::Foundation::Collections::IVectorView<Windows::Graphics::Display::NitRange>>(this->shim().GetSupportedNitRanges());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Graphics::Display::IDisplayEnhancementOverrideCapabilitiesChangedEventArgs> : produce_base<D, Windows::Graphics::Display::IDisplayEnhancementOverrideCapabilitiesChangedEventArgs>
{
HRESULT __stdcall get_Capabilities(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Graphics::Display::DisplayEnhancementOverrideCapabilities>(this->shim().Capabilities());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Graphics::Display::IDisplayEnhancementOverrideStatics> : produce_base<D, Windows::Graphics::Display::IDisplayEnhancementOverrideStatics>
{
HRESULT __stdcall GetForCurrentView(void** result) noexcept final
{
try
{
*result = nullptr;
typename D::abi_guard guard(this->shim());
*result = detach_from<Windows::Graphics::Display::DisplayEnhancementOverride>(this->shim().GetForCurrentView());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Graphics::Display::IDisplayInformation> : produce_base<D, Windows::Graphics::Display::IDisplayInformation>
{
HRESULT __stdcall get_CurrentOrientation(Windows::Graphics::Display::DisplayOrientations* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Graphics::Display::DisplayOrientations>(this->shim().CurrentOrientation());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_NativeOrientation(Windows::Graphics::Display::DisplayOrientations* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Graphics::Display::DisplayOrientations>(this->shim().NativeOrientation());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall add_OrientationChanged(void* handler, event_token* token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*token = detach_from<event_token>(this->shim().OrientationChanged(*reinterpret_cast<Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation, Windows::Foundation::IInspectable> const*>(&handler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_OrientationChanged(event_token token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().OrientationChanged(*reinterpret_cast<event_token const*>(&token));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_ResolutionScale(Windows::Graphics::Display::ResolutionScale* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Graphics::Display::ResolutionScale>(this->shim().ResolutionScale());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_LogicalDpi(float* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<float>(this->shim().LogicalDpi());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_RawDpiX(float* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<float>(this->shim().RawDpiX());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_RawDpiY(float* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<float>(this->shim().RawDpiY());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall add_DpiChanged(void* handler, event_token* token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*token = detach_from<event_token>(this->shim().DpiChanged(*reinterpret_cast<Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation, Windows::Foundation::IInspectable> const*>(&handler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_DpiChanged(event_token token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().DpiChanged(*reinterpret_cast<event_token const*>(&token));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_StereoEnabled(bool* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<bool>(this->shim().StereoEnabled());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall add_StereoEnabledChanged(void* handler, event_token* token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*token = detach_from<event_token>(this->shim().StereoEnabledChanged(*reinterpret_cast<Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation, Windows::Foundation::IInspectable> const*>(&handler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_StereoEnabledChanged(event_token token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().StereoEnabledChanged(*reinterpret_cast<event_token const*>(&token));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall GetColorProfileAsync(void** asyncInfo) noexcept final
{
try
{
*asyncInfo = nullptr;
typename D::abi_guard guard(this->shim());
*asyncInfo = detach_from<Windows::Foundation::IAsyncOperation<Windows::Storage::Streams::IRandomAccessStream>>(this->shim().GetColorProfileAsync());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall add_ColorProfileChanged(void* handler, event_token* token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*token = detach_from<event_token>(this->shim().ColorProfileChanged(*reinterpret_cast<Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation, Windows::Foundation::IInspectable> const*>(&handler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_ColorProfileChanged(event_token token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().ColorProfileChanged(*reinterpret_cast<event_token const*>(&token));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Graphics::Display::IDisplayInformation2> : produce_base<D, Windows::Graphics::Display::IDisplayInformation2>
{
HRESULT __stdcall get_RawPixelsPerViewPixel(double* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<double>(this->shim().RawPixelsPerViewPixel());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Graphics::Display::IDisplayInformation3> : produce_base<D, Windows::Graphics::Display::IDisplayInformation3>
{
HRESULT __stdcall get_DiagonalSizeInInches(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Foundation::IReference<double>>(this->shim().DiagonalSizeInInches());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Graphics::Display::IDisplayInformation4> : produce_base<D, Windows::Graphics::Display::IDisplayInformation4>
{
HRESULT __stdcall get_ScreenWidthInRawPixels(uint32_t* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<uint32_t>(this->shim().ScreenWidthInRawPixels());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_ScreenHeightInRawPixels(uint32_t* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<uint32_t>(this->shim().ScreenHeightInRawPixels());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Graphics::Display::IDisplayInformation5> : produce_base<D, Windows::Graphics::Display::IDisplayInformation5>
{
HRESULT __stdcall GetAdvancedColorInfo(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Graphics::Display::AdvancedColorInfo>(this->shim().GetAdvancedColorInfo());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall add_AdvancedColorInfoChanged(void* handler, event_token* token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*token = detach_from<event_token>(this->shim().AdvancedColorInfoChanged(*reinterpret_cast<Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation, Windows::Foundation::IInspectable> const*>(&handler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_AdvancedColorInfoChanged(event_token token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().AdvancedColorInfoChanged(*reinterpret_cast<event_token const*>(&token));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Graphics::Display::IDisplayInformationStatics> : produce_base<D, Windows::Graphics::Display::IDisplayInformationStatics>
{
HRESULT __stdcall GetForCurrentView(void** current) noexcept final
{
try
{
*current = nullptr;
typename D::abi_guard guard(this->shim());
*current = detach_from<Windows::Graphics::Display::DisplayInformation>(this->shim().GetForCurrentView());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_AutoRotationPreferences(Windows::Graphics::Display::DisplayOrientations* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Graphics::Display::DisplayOrientations>(this->shim().AutoRotationPreferences());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall put_AutoRotationPreferences(Windows::Graphics::Display::DisplayOrientations value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().AutoRotationPreferences(*reinterpret_cast<Windows::Graphics::Display::DisplayOrientations const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall add_DisplayContentsInvalidated(void* handler, event_token* token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*token = detach_from<event_token>(this->shim().DisplayContentsInvalidated(*reinterpret_cast<Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation, Windows::Foundation::IInspectable> const*>(&handler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_DisplayContentsInvalidated(event_token token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().DisplayContentsInvalidated(*reinterpret_cast<event_token const*>(&token));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::Graphics::Display::IDisplayPropertiesStatics> : produce_base<D, Windows::Graphics::Display::IDisplayPropertiesStatics>
{
HRESULT __stdcall get_CurrentOrientation(Windows::Graphics::Display::DisplayOrientations* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Graphics::Display::DisplayOrientations>(this->shim().CurrentOrientation());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_NativeOrientation(Windows::Graphics::Display::DisplayOrientations* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Graphics::Display::DisplayOrientations>(this->shim().NativeOrientation());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_AutoRotationPreferences(Windows::Graphics::Display::DisplayOrientations* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Graphics::Display::DisplayOrientations>(this->shim().AutoRotationPreferences());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall put_AutoRotationPreferences(Windows::Graphics::Display::DisplayOrientations value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().AutoRotationPreferences(*reinterpret_cast<Windows::Graphics::Display::DisplayOrientations const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall add_OrientationChanged(void* handler, event_token* token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*token = detach_from<event_token>(this->shim().OrientationChanged(*reinterpret_cast<Windows::Graphics::Display::DisplayPropertiesEventHandler const*>(&handler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_OrientationChanged(event_token token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().OrientationChanged(*reinterpret_cast<event_token const*>(&token));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_ResolutionScale(Windows::Graphics::Display::ResolutionScale* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Graphics::Display::ResolutionScale>(this->shim().ResolutionScale());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_LogicalDpi(float* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<float>(this->shim().LogicalDpi());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall add_LogicalDpiChanged(void* handler, event_token* token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*token = detach_from<event_token>(this->shim().LogicalDpiChanged(*reinterpret_cast<Windows::Graphics::Display::DisplayPropertiesEventHandler const*>(&handler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_LogicalDpiChanged(event_token token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().LogicalDpiChanged(*reinterpret_cast<event_token const*>(&token));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_StereoEnabled(bool* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<bool>(this->shim().StereoEnabled());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall add_StereoEnabledChanged(void* handler, event_token* token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*token = detach_from<event_token>(this->shim().StereoEnabledChanged(*reinterpret_cast<Windows::Graphics::Display::DisplayPropertiesEventHandler const*>(&handler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_StereoEnabledChanged(event_token token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().StereoEnabledChanged(*reinterpret_cast<event_token const*>(&token));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall GetColorProfileAsync(void** asyncInfo) noexcept final
{
try
{
*asyncInfo = nullptr;
typename D::abi_guard guard(this->shim());
*asyncInfo = detach_from<Windows::Foundation::IAsyncOperation<Windows::Storage::Streams::IRandomAccessStream>>(this->shim().GetColorProfileAsync());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall add_ColorProfileChanged(void* handler, event_token* token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*token = detach_from<event_token>(this->shim().ColorProfileChanged(*reinterpret_cast<Windows::Graphics::Display::DisplayPropertiesEventHandler const*>(&handler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_ColorProfileChanged(event_token token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().ColorProfileChanged(*reinterpret_cast<event_token const*>(&token));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall add_DisplayContentsInvalidated(void* handler, event_token* token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*token = detach_from<event_token>(this->shim().DisplayContentsInvalidated(*reinterpret_cast<Windows::Graphics::Display::DisplayPropertiesEventHandler const*>(&handler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_DisplayContentsInvalidated(event_token token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().DisplayContentsInvalidated(*reinterpret_cast<event_token const*>(&token));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
}
WINRT_EXPORT namespace winrt::Windows::Graphics::Display {
inline Windows::Graphics::Display::BrightnessOverride BrightnessOverride::GetDefaultForSystem()
{
return get_activation_factory<BrightnessOverride, Windows::Graphics::Display::IBrightnessOverrideStatics>().GetDefaultForSystem();
}
inline Windows::Graphics::Display::BrightnessOverride BrightnessOverride::GetForCurrentView()
{
return get_activation_factory<BrightnessOverride, Windows::Graphics::Display::IBrightnessOverrideStatics>().GetForCurrentView();
}
inline Windows::Foundation::IAsyncOperation<bool> BrightnessOverride::SaveForSystemAsync(Windows::Graphics::Display::BrightnessOverride const& value)
{
return get_activation_factory<BrightnessOverride, Windows::Graphics::Display::IBrightnessOverrideStatics>().SaveForSystemAsync(value);
}
inline Windows::Graphics::Display::BrightnessOverrideSettings BrightnessOverrideSettings::CreateFromLevel(double level)
{
return get_activation_factory<BrightnessOverrideSettings, Windows::Graphics::Display::IBrightnessOverrideSettingsStatics>().CreateFromLevel(level);
}
inline Windows::Graphics::Display::BrightnessOverrideSettings BrightnessOverrideSettings::CreateFromNits(float nits)
{
return get_activation_factory<BrightnessOverrideSettings, Windows::Graphics::Display::IBrightnessOverrideSettingsStatics>().CreateFromNits(nits);
}
inline Windows::Graphics::Display::BrightnessOverrideSettings BrightnessOverrideSettings::CreateFromDisplayBrightnessOverrideScenario(Windows::Graphics::Display::DisplayBrightnessOverrideScenario const& overrideScenario)
{
return get_activation_factory<BrightnessOverrideSettings, Windows::Graphics::Display::IBrightnessOverrideSettingsStatics>().CreateFromDisplayBrightnessOverrideScenario(overrideScenario);
}
inline Windows::Graphics::Display::ColorOverrideSettings ColorOverrideSettings::CreateFromDisplayColorOverrideScenario(Windows::Graphics::Display::DisplayColorOverrideScenario const& overrideScenario)
{
return get_activation_factory<ColorOverrideSettings, Windows::Graphics::Display::IColorOverrideSettingsStatics>().CreateFromDisplayColorOverrideScenario(overrideScenario);
}
inline Windows::Graphics::Display::DisplayEnhancementOverride DisplayEnhancementOverride::GetForCurrentView()
{
return get_activation_factory<DisplayEnhancementOverride, Windows::Graphics::Display::IDisplayEnhancementOverrideStatics>().GetForCurrentView();
}
inline Windows::Graphics::Display::DisplayInformation DisplayInformation::GetForCurrentView()
{
return get_activation_factory<DisplayInformation, Windows::Graphics::Display::IDisplayInformationStatics>().GetForCurrentView();
}
inline Windows::Graphics::Display::DisplayOrientations DisplayInformation::AutoRotationPreferences()
{
return get_activation_factory<DisplayInformation, Windows::Graphics::Display::IDisplayInformationStatics>().AutoRotationPreferences();
}
inline void DisplayInformation::AutoRotationPreferences(Windows::Graphics::Display::DisplayOrientations const& value)
{
get_activation_factory<DisplayInformation, Windows::Graphics::Display::IDisplayInformationStatics>().AutoRotationPreferences(value);
}
inline event_token DisplayInformation::DisplayContentsInvalidated(Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation, Windows::Foundation::IInspectable> const& handler)
{
return get_activation_factory<DisplayInformation, Windows::Graphics::Display::IDisplayInformationStatics>().DisplayContentsInvalidated(handler);
}
inline factory_event_revoker<Windows::Graphics::Display::IDisplayInformationStatics> DisplayInformation::DisplayContentsInvalidated(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::Graphics::Display::DisplayInformation, Windows::Foundation::IInspectable> const& handler)
{
auto factory = get_activation_factory<DisplayInformation, Windows::Graphics::Display::IDisplayInformationStatics>();
return { factory, &impl::abi_t<Windows::Graphics::Display::IDisplayInformationStatics>::remove_DisplayContentsInvalidated, factory.DisplayContentsInvalidated(handler) };
}
inline void DisplayInformation::DisplayContentsInvalidated(event_token const& token)
{
get_activation_factory<DisplayInformation, Windows::Graphics::Display::IDisplayInformationStatics>().DisplayContentsInvalidated(token);
}
inline Windows::Graphics::Display::DisplayOrientations DisplayProperties::CurrentOrientation()
{
return get_activation_factory<DisplayProperties, Windows::Graphics::Display::IDisplayPropertiesStatics>().CurrentOrientation();
}
inline Windows::Graphics::Display::DisplayOrientations DisplayProperties::NativeOrientation()
{
return get_activation_factory<DisplayProperties, Windows::Graphics::Display::IDisplayPropertiesStatics>().NativeOrientation();
}
inline Windows::Graphics::Display::DisplayOrientations DisplayProperties::AutoRotationPreferences()
{
return get_activation_factory<DisplayProperties, Windows::Graphics::Display::IDisplayPropertiesStatics>().AutoRotationPreferences();
}
inline void DisplayProperties::AutoRotationPreferences(Windows::Graphics::Display::DisplayOrientations const& value)
{
get_activation_factory<DisplayProperties, Windows::Graphics::Display::IDisplayPropertiesStatics>().AutoRotationPreferences(value);
}
inline event_token DisplayProperties::OrientationChanged(Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler)
{
return get_activation_factory<DisplayProperties, Windows::Graphics::Display::IDisplayPropertiesStatics>().OrientationChanged(handler);
}
inline factory_event_revoker<Windows::Graphics::Display::IDisplayPropertiesStatics> DisplayProperties::OrientationChanged(auto_revoke_t, Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler)
{
auto factory = get_activation_factory<DisplayProperties, Windows::Graphics::Display::IDisplayPropertiesStatics>();
return { factory, &impl::abi_t<Windows::Graphics::Display::IDisplayPropertiesStatics>::remove_OrientationChanged, factory.OrientationChanged(handler) };
}
inline void DisplayProperties::OrientationChanged(event_token const& token)
{
get_activation_factory<DisplayProperties, Windows::Graphics::Display::IDisplayPropertiesStatics>().OrientationChanged(token);
}
inline Windows::Graphics::Display::ResolutionScale DisplayProperties::ResolutionScale()
{
return get_activation_factory<DisplayProperties, Windows::Graphics::Display::IDisplayPropertiesStatics>().ResolutionScale();
}
inline float DisplayProperties::LogicalDpi()
{
return get_activation_factory<DisplayProperties, Windows::Graphics::Display::IDisplayPropertiesStatics>().LogicalDpi();
}
inline event_token DisplayProperties::LogicalDpiChanged(Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler)
{
return get_activation_factory<DisplayProperties, Windows::Graphics::Display::IDisplayPropertiesStatics>().LogicalDpiChanged(handler);
}
inline factory_event_revoker<Windows::Graphics::Display::IDisplayPropertiesStatics> DisplayProperties::LogicalDpiChanged(auto_revoke_t, Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler)
{
auto factory = get_activation_factory<DisplayProperties, Windows::Graphics::Display::IDisplayPropertiesStatics>();
return { factory, &impl::abi_t<Windows::Graphics::Display::IDisplayPropertiesStatics>::remove_LogicalDpiChanged, factory.LogicalDpiChanged(handler) };
}
inline void DisplayProperties::LogicalDpiChanged(event_token const& token)
{
get_activation_factory<DisplayProperties, Windows::Graphics::Display::IDisplayPropertiesStatics>().LogicalDpiChanged(token);
}
inline bool DisplayProperties::StereoEnabled()
{
return get_activation_factory<DisplayProperties, Windows::Graphics::Display::IDisplayPropertiesStatics>().StereoEnabled();
}
inline event_token DisplayProperties::StereoEnabledChanged(Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler)
{
return get_activation_factory<DisplayProperties, Windows::Graphics::Display::IDisplayPropertiesStatics>().StereoEnabledChanged(handler);
}
inline factory_event_revoker<Windows::Graphics::Display::IDisplayPropertiesStatics> DisplayProperties::StereoEnabledChanged(auto_revoke_t, Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler)
{
auto factory = get_activation_factory<DisplayProperties, Windows::Graphics::Display::IDisplayPropertiesStatics>();
return { factory, &impl::abi_t<Windows::Graphics::Display::IDisplayPropertiesStatics>::remove_StereoEnabledChanged, factory.StereoEnabledChanged(handler) };
}
inline void DisplayProperties::StereoEnabledChanged(event_token const& token)
{
get_activation_factory<DisplayProperties, Windows::Graphics::Display::IDisplayPropertiesStatics>().StereoEnabledChanged(token);
}
inline Windows::Foundation::IAsyncOperation<Windows::Storage::Streams::IRandomAccessStream> DisplayProperties::GetColorProfileAsync()
{
return get_activation_factory<DisplayProperties, Windows::Graphics::Display::IDisplayPropertiesStatics>().GetColorProfileAsync();
}
inline event_token DisplayProperties::ColorProfileChanged(Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler)
{
return get_activation_factory<DisplayProperties, Windows::Graphics::Display::IDisplayPropertiesStatics>().ColorProfileChanged(handler);
}
inline factory_event_revoker<Windows::Graphics::Display::IDisplayPropertiesStatics> DisplayProperties::ColorProfileChanged(auto_revoke_t, Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler)
{
auto factory = get_activation_factory<DisplayProperties, Windows::Graphics::Display::IDisplayPropertiesStatics>();
return { factory, &impl::abi_t<Windows::Graphics::Display::IDisplayPropertiesStatics>::remove_ColorProfileChanged, factory.ColorProfileChanged(handler) };
}
inline void DisplayProperties::ColorProfileChanged(event_token const& token)
{
get_activation_factory<DisplayProperties, Windows::Graphics::Display::IDisplayPropertiesStatics>().ColorProfileChanged(token);
}
inline event_token DisplayProperties::DisplayContentsInvalidated(Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler)
{
return get_activation_factory<DisplayProperties, Windows::Graphics::Display::IDisplayPropertiesStatics>().DisplayContentsInvalidated(handler);
}
inline factory_event_revoker<Windows::Graphics::Display::IDisplayPropertiesStatics> DisplayProperties::DisplayContentsInvalidated(auto_revoke_t, Windows::Graphics::Display::DisplayPropertiesEventHandler const& handler)
{
auto factory = get_activation_factory<DisplayProperties, Windows::Graphics::Display::IDisplayPropertiesStatics>();
return { factory, &impl::abi_t<Windows::Graphics::Display::IDisplayPropertiesStatics>::remove_DisplayContentsInvalidated, factory.DisplayContentsInvalidated(handler) };
}
inline void DisplayProperties::DisplayContentsInvalidated(event_token const& token)
{
get_activation_factory<DisplayProperties, Windows::Graphics::Display::IDisplayPropertiesStatics>().DisplayContentsInvalidated(token);
}
template <typename L> DisplayPropertiesEventHandler::DisplayPropertiesEventHandler(L handler) :
DisplayPropertiesEventHandler(impl::make_delegate<DisplayPropertiesEventHandler>(std::forward<L>(handler)))
{}
template <typename F> DisplayPropertiesEventHandler::DisplayPropertiesEventHandler(F* handler) :
DisplayPropertiesEventHandler([=](auto&&... args) { handler(args...); })
{}
template <typename O, typename M> DisplayPropertiesEventHandler::DisplayPropertiesEventHandler(O* object, M method) :
DisplayPropertiesEventHandler([=](auto&&... args) { ((*object).*(method))(args...); })
{}
inline void DisplayPropertiesEventHandler::operator()(Windows::Foundation::IInspectable const& sender) const
{
check_hresult((*(impl::abi_t<DisplayPropertiesEventHandler>**)this)->Invoke(get_abi(sender)));
}
}
WINRT_EXPORT namespace std {
template<> struct hash<winrt::Windows::Graphics::Display::IAdvancedColorInfo> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::IAdvancedColorInfo> {};
template<> struct hash<winrt::Windows::Graphics::Display::IBrightnessOverride> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::IBrightnessOverride> {};
template<> struct hash<winrt::Windows::Graphics::Display::IBrightnessOverrideSettings> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::IBrightnessOverrideSettings> {};
template<> struct hash<winrt::Windows::Graphics::Display::IBrightnessOverrideSettingsStatics> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::IBrightnessOverrideSettingsStatics> {};
template<> struct hash<winrt::Windows::Graphics::Display::IBrightnessOverrideStatics> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::IBrightnessOverrideStatics> {};
template<> struct hash<winrt::Windows::Graphics::Display::IColorOverrideSettings> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::IColorOverrideSettings> {};
template<> struct hash<winrt::Windows::Graphics::Display::IColorOverrideSettingsStatics> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::IColorOverrideSettingsStatics> {};
template<> struct hash<winrt::Windows::Graphics::Display::IDisplayEnhancementOverride> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::IDisplayEnhancementOverride> {};
template<> struct hash<winrt::Windows::Graphics::Display::IDisplayEnhancementOverrideCapabilities> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::IDisplayEnhancementOverrideCapabilities> {};
template<> struct hash<winrt::Windows::Graphics::Display::IDisplayEnhancementOverrideCapabilitiesChangedEventArgs> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::IDisplayEnhancementOverrideCapabilitiesChangedEventArgs> {};
template<> struct hash<winrt::Windows::Graphics::Display::IDisplayEnhancementOverrideStatics> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::IDisplayEnhancementOverrideStatics> {};
template<> struct hash<winrt::Windows::Graphics::Display::IDisplayInformation> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::IDisplayInformation> {};
template<> struct hash<winrt::Windows::Graphics::Display::IDisplayInformation2> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::IDisplayInformation2> {};
template<> struct hash<winrt::Windows::Graphics::Display::IDisplayInformation3> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::IDisplayInformation3> {};
template<> struct hash<winrt::Windows::Graphics::Display::IDisplayInformation4> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::IDisplayInformation4> {};
template<> struct hash<winrt::Windows::Graphics::Display::IDisplayInformation5> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::IDisplayInformation5> {};
template<> struct hash<winrt::Windows::Graphics::Display::IDisplayInformationStatics> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::IDisplayInformationStatics> {};
template<> struct hash<winrt::Windows::Graphics::Display::IDisplayPropertiesStatics> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::IDisplayPropertiesStatics> {};
template<> struct hash<winrt::Windows::Graphics::Display::AdvancedColorInfo> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::AdvancedColorInfo> {};
template<> struct hash<winrt::Windows::Graphics::Display::BrightnessOverride> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::BrightnessOverride> {};
template<> struct hash<winrt::Windows::Graphics::Display::BrightnessOverrideSettings> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::BrightnessOverrideSettings> {};
template<> struct hash<winrt::Windows::Graphics::Display::ColorOverrideSettings> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::ColorOverrideSettings> {};
template<> struct hash<winrt::Windows::Graphics::Display::DisplayEnhancementOverride> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::DisplayEnhancementOverride> {};
template<> struct hash<winrt::Windows::Graphics::Display::DisplayEnhancementOverrideCapabilities> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::DisplayEnhancementOverrideCapabilities> {};
template<> struct hash<winrt::Windows::Graphics::Display::DisplayEnhancementOverrideCapabilitiesChangedEventArgs> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::DisplayEnhancementOverrideCapabilitiesChangedEventArgs> {};
template<> struct hash<winrt::Windows::Graphics::Display::DisplayInformation> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::DisplayInformation> {};
template<> struct hash<winrt::Windows::Graphics::Display::DisplayProperties> : winrt::impl::hash_base<winrt::Windows::Graphics::Display::DisplayProperties> {};
}
WINRT_WARNING_POP
| 42.725583 | 419 | 0.716038 | [
"object"
] |
3ff5777ca2e561e3e7e75bf47ac1cabc68ec9b21 | 78,820 | c | C | msquic/portable/mitls/kremlinit.c | ThadHouse/everest-dist | 4e71b972d4629ac8a562d7f161e4995b32900309 | [
"Apache-2.0"
] | 1 | 2019-11-22T20:15:11.000Z | 2019-11-22T20:15:11.000Z | msquic/portable/mitls/kremlinit.c | ThadHouse/everest-dist | 4e71b972d4629ac8a562d7f161e4995b32900309 | [
"Apache-2.0"
] | null | null | null | msquic/portable/mitls/kremlinit.c | ThadHouse/everest-dist | 4e71b972d4629ac8a562d7f161e4995b32900309 | [
"Apache-2.0"
] | 2 | 2019-11-22T20:29:17.000Z | 2020-03-13T16:59:49.000Z | /*
This file was generated by KreMLin <https://github.com/FStarLang/kremlin>
KreMLin invocation: /home/everest/everest/kremlin/krml -minimal -add-include "kremlib.h" -fnoanonymous-unions -warn-error -9-7-6@4-14-15 -fsopts --debug,yes -verbose -library EverCrypt,EverCrypt.*,Hacl.*,Interop_assumptions,Check_sha_stdcall,Sha_update_bytes_stdcall,Check_aesni_stdcall -drop MonotoneMap -drop MonotoneMapNonDep -drop FStar.Tactics.\* -drop FStar.Tactics -drop Crypto.AEAD.\* -drop Crypto.HKDF -drop Crypto.HMAC -add-include "hacks.h" -add-include "kremlin/internal/compat.h" -bundle LowParse.\*,LowParseWrappers[rename=LowParse] -bundle Format.\* -bundle EverCrypt=EverCrypt,EverCrypt.\* -bundle FStar.\*,LowStar.\*,C,C.\*[rename=Mitls_Kremlib] -bundle Parsers.\* -bundle Spec.\* -bundle Meta.\* -bundle Lib.*[rename=Hacl_Lib] -bundle TLSConstants=TLSConstants,QD.TLS_protocolVersion,List.Helpers -bundle Hashing=Hashing.Spec,Hashing,Hashing.CRF,HMAC,HKDF,HMAC.UFCMA -bundle Old.Handshake=Old.HMAC.UFCMA,Old.Epochs,Old.KeySchedule,Old.Handshake -bundle StatefulLHAE=AEAD_GCM,LHAEPlain,StatefulPlain,StatefulLHAE -bundle StreamAE=StreamPlain,StreamAE -bundle CommonDH=TLS.Curve25519,DHGroup,ECGroup,CommonDH -bundle Content=Content,DataStream -bundle Record=Record,StAE,Transport,StreamDeltas -bundle PMS=PMS,RSAKey,TLSPRF -bundle Crypto.Plain=Buffer.Utils,Crypto.Indexing,Crypto.Plain,Crypto.Symmetric.Bytes -bundle Flags=DebugFlags,Flags,Flag,TLSInfoFlags -bundle Vale.Stdcalls.*,Vale.Interop,Vale.Interop.*,Vale.Wrapper.X64.*[rename=Vale] -bundle Vale.Inline.X64.*[rename=Vale_Inline] -bundle Vale.*[rename=Unused2] -ldopts -L,/home/everest/everest/MLCrypto/openssl,-lcrypto,-lssl extract/Kremlin/FStar_Pervasives_Native.krml extract/Kremlin/FStar_Pervasives.krml extract/Kremlin/FStar_Squash.krml extract/Kremlin/FStar_Classical.krml extract/Kremlin/FStar_Preorder.krml extract/Kremlin/FStar_Calc.krml extract/Kremlin/FStar_Mul.krml extract/Kremlin/FStar_Math_Lib.krml extract/Kremlin/FStar_Math_Lemmas.krml extract/Kremlin/FStar_StrongExcludedMiddle.krml extract/Kremlin/FStar_FunctionalExtensionality.krml extract/Kremlin/FStar_List_Tot_Base.krml extract/Kremlin/FStar_List_Tot_Properties.krml extract/Kremlin/FStar_List_Tot.krml extract/Kremlin/FStar_Seq_Base.krml extract/Kremlin/FStar_Seq_Properties.krml extract/Kremlin/FStar_Seq.krml extract/Kremlin/FStar_BitVector.krml extract/Kremlin/FStar_UInt.krml extract/Kremlin/FStar_UInt32.krml extract/Kremlin/FStar_UInt8.krml extract/Kremlin/FStar_Exn.krml extract/Kremlin/FStar_Set.krml extract/Kremlin/FStar_Monotonic_Witnessed.krml extract/Kremlin/FStar_Ghost.krml extract/Kremlin/FStar_ErasedLogic.krml extract/Kremlin/FStar_PropositionalExtensionality.krml extract/Kremlin/FStar_PredicateExtensionality.krml extract/Kremlin/FStar_TSet.krml extract/Kremlin/FStar_Monotonic_Heap.krml extract/Kremlin/FStar_Heap.krml extract/Kremlin/FStar_ST.krml extract/Kremlin/FStar_All.krml extract/Kremlin/Lib_LoopCombinators.krml extract/Kremlin/FStar_Int.krml extract/Kremlin/FStar_Int64.krml extract/Kremlin/FStar_Int63.krml extract/Kremlin/FStar_Int32.krml extract/Kremlin/FStar_Int16.krml extract/Kremlin/FStar_Int8.krml extract/Kremlin/FStar_UInt64.krml extract/Kremlin/FStar_UInt63.krml extract/Kremlin/FStar_UInt16.krml extract/Kremlin/FStar_Int_Cast.krml extract/Kremlin/FStar_UInt128.krml extract/Kremlin/FStar_Int_Cast_Full.krml extract/Kremlin/FStar_Int128.krml extract/Kremlin/Lib_IntTypes.krml extract/Kremlin/Lib_RawIntTypes.krml extract/Kremlin/Lib_Sequence.krml extract/Kremlin/Lib_ByteSequence.krml extract/Kremlin/Spec_Chacha20.krml extract/Kremlin/Meta_Attribute.krml extract/Kremlin/FStar_Map.krml extract/Kremlin/FStar_Monotonic_HyperHeap.krml extract/Kremlin/FStar_Monotonic_HyperStack.krml extract/Kremlin/FStar_HyperStack.krml extract/Kremlin/FStar_HyperStack_ST.krml extract/Kremlin/FStar_Universe.krml extract/Kremlin/FStar_GSet.krml extract/Kremlin/FStar_ModifiesGen.krml extract/Kremlin/FStar_Range.krml extract/Kremlin/FStar_Reflection_Types.krml extract/Kremlin/FStar_Tactics_Types.krml extract/Kremlin/FStar_Tactics_Result.krml extract/Kremlin/FStar_Tactics_Effect.krml extract/Kremlin/FStar_Tactics_Util.krml extract/Kremlin/FStar_Reflection_Data.krml extract/Kremlin/FStar_Reflection_Const.krml extract/Kremlin/FStar_Char.krml extract/Kremlin/FStar_List.krml extract/Kremlin/FStar_String.krml extract/Kremlin/FStar_Order.krml extract/Kremlin/FStar_Reflection_Basic.krml extract/Kremlin/FStar_Reflection_Derived.krml extract/Kremlin/FStar_Tactics_Builtins.krml extract/Kremlin/FStar_Reflection_Formula.krml extract/Kremlin/FStar_Reflection_Derived_Lemmas.krml extract/Kremlin/FStar_Reflection.krml extract/Kremlin/FStar_Tactics_Derived.krml extract/Kremlin/FStar_Tactics_Logic.krml extract/Kremlin/FStar_Tactics.krml extract/Kremlin/FStar_BigOps.krml extract/Kremlin/LowStar_Monotonic_Buffer.krml extract/Kremlin/LowStar_Buffer.krml extract/Kremlin/LowStar_BufferOps.krml extract/Kremlin/Spec_Loops.krml extract/Kremlin/C_Loops.krml extract/Kremlin/Lib_Loops.krml extract/Kremlin/FStar_Endianness.krml extract/Kremlin/LowStar_Endianness.krml extract/Kremlin/LowStar_ImmutableBuffer.krml extract/Kremlin/Lib_Buffer.krml extract/Kremlin/Lib_ByteBuffer.krml extract/Kremlin/FStar_HyperStack_All.krml extract/Kremlin/Lib_IntVector_Intrinsics.krml extract/Kremlin/Spec_GaloisField.krml extract/Kremlin/Spec_AES.krml extract/Kremlin/Lib_IntVector.krml extract/Kremlin/Hacl_Spec_Chacha20_Vec.krml extract/Kremlin/Hacl_Spec_Chacha20_Lemmas.krml extract/Kremlin/Lib_Sequence_Lemmas.krml extract/Kremlin/Hacl_Spec_Chacha20_Equiv.krml extract/Kremlin/Hacl_Impl_Chacha20_Core32xN.krml extract/Kremlin/Hacl_Impl_Chacha20_Vec.krml extract/Kremlin/Vale_Lib_Set.krml extract/Kremlin/Vale_Def_Opaque_s.krml extract/Kremlin/Vale_Lib_Meta.krml extract/Kremlin/Vale_Def_Words_s.krml extract/Kremlin/Vale_Def_Words_Two_s.krml extract/Kremlin/Vale_Lib_Seqs_s.krml extract/Kremlin/Vale_Def_Words_Four_s.krml extract/Kremlin/Vale_Def_Words_Seq_s.krml extract/Kremlin/Vale_Def_Types_s.krml extract/Kremlin/Vale_Def_Words_Two.krml extract/Kremlin/Vale_Lib_Seqs.krml extract/Kremlin/Vale_Def_TypesNative_s.krml extract/Kremlin/Vale_Arch_TypesNative.krml extract/Kremlin/Vale_Def_Words_Seq.krml extract/Kremlin/Vale_Arch_Types.krml extract/Kremlin/Vale_Def_Prop_s.krml extract/Kremlin/Vale_Arch_MachineHeap_s.krml extract/Kremlin/Vale_Arch_MachineHeap.krml extract/Kremlin/FStar_Option.krml extract/Kremlin/Vale_X64_Machine_s.krml extract/Kremlin/Vale_X64_Instruction_s.krml extract/Kremlin/Vale_X64_Bytes_Code_s.krml extract/Kremlin/Vale_AES_AES_s.krml extract/Kremlin/Vale_Math_Poly2_Defs_s.krml extract/Kremlin/Vale_Math_Poly2_s.krml extract/Kremlin/Vale_Math_Poly2_Bits_s.krml extract/Kremlin/Spec_Hash_Definitions.krml extract/Kremlin/Spec_Hash_Lemmas0.krml extract/Kremlin/Spec_Hash_PadFinish.krml extract/Kremlin/Spec_SHA2_Constants.krml extract/Kremlin/Spec_SHA2.krml extract/Kremlin/Vale_X64_CryptoInstructions_s.krml extract/Kremlin/Vale_X64_CPU_Features_s.krml extract/Kremlin/Vale_X64_Instructions_s.krml extract/Kremlin/LowStar_BufferView_Down.krml extract/Kremlin/LowStar_BufferView_Up.krml extract/Kremlin/Vale_Interop_Views.krml extract/Kremlin/Vale_Arch_HeapTypes_s.krml extract/Kremlin/Vale_Interop_Types.krml extract/Kremlin/Vale_Interop_Heap_s.krml extract/Kremlin/LowStar_Modifies.krml extract/Kremlin/LowStar_ModifiesPat.krml extract/Kremlin/LowStar_BufferView.krml extract/Kremlin/Vale_Lib_BufferViewHelpers.krml extract/Kremlin/Vale_Interop.krml extract/Kremlin/Vale_Arch_HeapImpl.krml extract/Kremlin/Vale_Arch_Heap.krml extract/Kremlin/Vale_X64_Machine_Semantics_s.krml extract/Kremlin/Vale_Interop_Base.krml extract/Kremlin/Vale_X64_Memory.krml extract/Kremlin/Vale_X64_Stack_i.krml extract/Kremlin/Vale_Lib_Map16.krml extract/Kremlin/Vale_X64_Flags.krml extract/Kremlin/Vale_Curve25519_Fast_lemmas_internal.krml extract/Kremlin/Vale_Curve25519_Fast_defs.krml extract/Kremlin/FStar_Algebra_CommMonoid.krml extract/Kremlin/FStar_Tactics_CanonCommSemiring.krml extract/Kremlin/Vale_Curve25519_FastUtil_helpers.krml extract/Kremlin/Vale_Curve25519_FastHybrid_helpers.krml extract/Kremlin/Vale_Curve25519_Fast_lemmas_external.krml extract/Kremlin/Vale_X64_Regs.krml extract/Kremlin/FStar_Float.krml extract/Kremlin/FStar_IO.krml extract/Kremlin/Vale_Def_PossiblyMonad.krml extract/Kremlin/Vale_X64_Stack_Sems.krml extract/Kremlin/Vale_X64_BufferViewStore.krml extract/Kremlin/Vale_X64_Memory_Sems.krml extract/Kremlin/Vale_X64_State.krml extract/Kremlin/Vale_X64_StateLemmas.krml extract/Kremlin/Vale_X64_Lemmas.krml extract/Kremlin/Vale_X64_Print_s.krml extract/Kremlin/Vale_X64_Decls.krml extract/Kremlin/Vale_X64_QuickCode.krml extract/Kremlin/Vale_X64_QuickCodes.krml extract/Kremlin/Vale_X64_Taint_Semantics.krml extract/Kremlin/Vale_X64_InsLemmas.krml extract/Kremlin/Vale_X64_InsBasic.krml extract/Kremlin/Vale_X64_InsMem.krml extract/Kremlin/Vale_X64_InsVector.krml extract/Kremlin/Vale_X64_InsStack.krml extract/Kremlin/Vale_Curve25519_X64_FastHybrid.krml extract/Kremlin/Vale_Bignum_Defs.krml extract/Kremlin/Vale_Bignum_X64.krml extract/Kremlin/Vale_Curve25519_FastSqr_helpers.krml extract/Kremlin/Vale_Curve25519_X64_FastSqr.krml extract/Kremlin/Vale_Curve25519_FastMul_helpers.krml extract/Kremlin/Vale_Curve25519_X64_FastMul.krml extract/Kremlin/Vale_Curve25519_X64_FastWide.krml extract/Kremlin/Vale_Curve25519_X64_FastUtil.krml extract/Kremlin/Vale_X64_MemoryAdapters.krml extract/Kremlin/Vale_Interop_Assumptions.krml extract/Kremlin/Vale_Interop_X64.krml extract/Kremlin/Vale_AsLowStar_ValeSig.krml extract/Kremlin/Vale_AsLowStar_LowStarSig.krml extract/Kremlin/Vale_AsLowStar_MemoryHelpers.krml extract/Kremlin/Vale_AsLowStar_Wrapper.krml extract/Kremlin/Vale_Stdcalls_X64_Fadd.krml extract/Kremlin/Vale_Wrapper_X64_Fadd.krml extract/Kremlin/Spec_SHA1.krml extract/Kremlin/Spec_MD5.krml extract/Kremlin/Spec_Agile_Hash.krml extract/Kremlin/Spec_Hash_Incremental.krml extract/Kremlin/Spec_Hash_Lemmas.krml extract/Kremlin/FStar_Kremlin_Endianness.krml extract/Kremlin/Hacl_Hash_Lemmas.krml extract/Kremlin/Hacl_Hash_Definitions.krml extract/Kremlin/Hacl_Hash_PadFinish.krml extract/Kremlin/Hacl_Hash_MD.krml extract/Kremlin/Spec_SHA2_Lemmas.krml extract/Kremlin/Vale_X64_Stack.krml extract/Kremlin/Vale_SHA_SHA_helpers.krml extract/Kremlin/Vale_X64_InsSha.krml extract/Kremlin/Vale_SHA_X64.krml extract/Kremlin/Vale_Stdcalls_X64_Sha.krml extract/Kremlin/FStar_BV.krml extract/Kremlin/FStar_Reflection_Arith.krml extract/Kremlin/FStar_Tactics_BV.krml extract/Kremlin/Vale_Lib_Bv_s.krml extract/Kremlin/Vale_Math_Bits.krml extract/Kremlin/Vale_Lib_Tactics.krml extract/Kremlin/Vale_Poly1305_Bitvectors.krml extract/Kremlin/Vale_Math_Lemmas_Int.krml extract/Kremlin/FStar_Tactics_Canon.krml extract/Kremlin/Vale_Poly1305_Spec_s.krml extract/Kremlin/Vale_Poly1305_Math.krml extract/Kremlin/Vale_Poly1305_Util.krml extract/Kremlin/Vale_Poly1305_X64.krml extract/Kremlin/Vale_Stdcalls_X64_Poly.krml extract/Kremlin/Vale_Wrapper_X64_Poly.krml extract/Kremlin/Vale_Arch_BufferFriend.krml extract/Kremlin/Vale_SHA_Simplify_Sha.krml extract/Kremlin/Vale_Wrapper_X64_Sha.krml extract/Kremlin/Hacl_Hash_Core_SHA2_Constants.krml extract/Kremlin/Hacl_Hash_Core_SHA2.krml extract/Kremlin/Hacl_Hash_SHA2.krml extract/Kremlin/Hacl_Hash_Core_SHA1.krml extract/Kremlin/Hacl_Hash_SHA1.krml extract/Kremlin/Hacl_Hash_Core_MD5.krml extract/Kremlin/Hacl_Hash_MD5.krml extract/Kremlin/C_Endianness.krml extract/Kremlin/C.krml extract/Kremlin/C_String.krml extract/Kremlin/C_Failure.krml extract/Kremlin/FStar_Int31.krml extract/Kremlin/FStar_UInt31.krml extract/Kremlin/FStar_Integers.krml extract/Kremlin/EverCrypt_StaticConfig.krml extract/Kremlin/EverCrypt_TargetConfig.krml extract/Kremlin/Vale_Lib_Basic.krml extract/Kremlin/Vale_Lib_X64_Cpuid.krml extract/Kremlin/Vale_Lib_X64_Cpuidstdcall.krml extract/Kremlin/Vale_Stdcalls_X64_Cpuid.krml extract/Kremlin/Vale_Wrapper_X64_Cpuid.krml extract/Kremlin/EverCrypt_AutoConfig2.krml extract/Kremlin/EverCrypt_Helpers.krml extract/Kremlin/EverCrypt_Hash.krml extract/Kremlin/Spec_Agile_HMAC.krml extract/Kremlin/Hacl_HMAC.krml extract/Kremlin/EverCrypt_HMAC.krml extract/Kremlin/Declassify.krml extract/Kremlin/FStar_Bytes.krml extract/Kremlin/Hashing_Spec.krml extract/Kremlin/LowParse_Bytes32.krml extract/Kremlin/LowParse_Bytes.krml extract/Kremlin/LowParse_Spec_Base.krml extract/Kremlin/LowParse_SLow_Base.krml extract/Kremlin/LowParse_Spec_Option.krml extract/Kremlin/LowParse_SLow_Option.krml extract/Kremlin/LowParse_Spec_Combinators.krml extract/Kremlin/LowParse_Spec_IfThenElse.krml extract/Kremlin/Spec_Curve25519_Lemmas.krml extract/Kremlin/Spec_Curve25519.krml extract/Kremlin/Hacl_Spec_Curve25519_AddAndDouble.krml extract/Kremlin/Hacl_Impl_Curve25519_Lemmas.krml extract/Kremlin/Hacl_Spec_Curve25519_Field64_Definition.krml extract/Kremlin/Hacl_Spec_Curve25519_Field64_Lemmas.krml extract/Kremlin/Hacl_Spec_Curve25519_Field64_Core.krml extract/Kremlin/Hacl_Spec_Curve25519_Field64.krml extract/Kremlin/Hacl_Spec_Curve25519_Field51_Definition.krml extract/Kremlin/Hacl_Spec_Curve25519_Field51_Lemmas.krml extract/Kremlin/Hacl_Spec_Curve25519_Field51.krml extract/Kremlin/Hacl_Impl_Curve25519_Fields_Core.krml extract/Kremlin/Hacl_Impl_Curve25519_Field64.krml extract/Kremlin/Hacl_Impl_Curve25519_Field51.krml extract/Kremlin/Hacl_Impl_Curve25519_Fields.krml extract/Kremlin/Hacl_Impl_Curve25519_AddAndDouble.krml extract/Kremlin/LowParse_SLow_Combinators.krml extract/Kremlin/LowParse_Spec_List.krml extract/Kremlin/LowParse_SLow_List.krml extract/Kremlin/Spec_Poly1305.krml extract/Kremlin/Hacl_Spec_Poly1305_Vec.krml extract/Kremlin/Hacl_Spec_Poly1305_Field32xN.krml extract/Kremlin/Hacl_Poly1305_Field32xN_Lemmas.krml extract/Kremlin/Hacl_Impl_Poly1305_Lemmas.krml extract/Kremlin/Hacl_Spec_Poly1305_Field32xN_Lemmas.krml extract/Kremlin/Hacl_Impl_Poly1305_Field32xN.krml extract/Kremlin/Hacl_Spec_Poly1305_Lemmas.krml extract/Kremlin/Hacl_Spec_Poly1305_Equiv.krml extract/Kremlin/Hacl_Impl_Poly1305_Field32xN_256.krml extract/Kremlin/Hacl_Impl_Poly1305_Field32xN_128.krml extract/Kremlin/Hacl_Impl_Poly1305_Field32xN_32.krml extract/Kremlin/Hacl_Impl_Poly1305_Fields.krml extract/Kremlin/Hacl_Impl_Poly1305.krml extract/Kremlin/Spec_Chacha20Poly1305.krml extract/Kremlin/Hacl_Impl_Chacha20Poly1305_PolyCore.krml extract/Kremlin/Hacl_Impl_Chacha20Poly1305.krml extract/Kremlin/FStar_List_Pure_Base.krml extract/Kremlin/FStar_List_Pure_Properties.krml extract/Kremlin/FStar_List_Pure.krml extract/Kremlin/Meta_Interface.krml extract/Kremlin/Hacl_Meta_Chacha20Poly1305.krml extract/Kremlin/Hacl_Impl_Chacha20_Core32.krml extract/Kremlin/Hacl_Impl_Chacha20.krml extract/Kremlin/Hacl_Chacha20.krml extract/Kremlin/Hacl_Meta_Poly1305.krml extract/Kremlin/Hacl_Poly1305_32.krml extract/Kremlin/Hacl_Chacha20Poly1305_32.krml extract/Kremlin/FStar_Dyn.krml extract/Kremlin/EverCrypt_Vale.krml extract/Kremlin/EverCrypt_Specs.krml extract/Kremlin/EverCrypt_OpenSSL.krml extract/Kremlin/EverCrypt_Hacl.krml extract/Kremlin/EverCrypt_BCrypt.krml extract/Kremlin/EverCrypt_Cipher.krml extract/Kremlin/Hacl_Spec_Curve25519_Finv.krml extract/Kremlin/Hacl_Impl_Curve25519_Finv.krml extract/Kremlin/Hacl_Impl_Curve25519_Generic.krml extract/Kremlin/Hacl_Meta_Curve25519.krml extract/Kremlin/Hacl_Curve25519_51.krml extract/Kremlin/Vale_Stdcalls_X64_Fswap.krml extract/Kremlin/Vale_Wrapper_X64_Fswap.krml extract/Kremlin/Vale_X64_Print_Inline_s.krml extract/Kremlin/Vale_Inline_X64_Fswap_inline.krml extract/Kremlin/Vale_Stdcalls_X64_Fsqr.krml extract/Kremlin/Vale_Wrapper_X64_Fsqr.krml extract/Kremlin/Vale_Inline_X64_Fsqr_inline.krml extract/Kremlin/Vale_Stdcalls_X64_Fmul.krml extract/Kremlin/Vale_Wrapper_X64_Fmul.krml extract/Kremlin/Vale_Inline_X64_Fmul_inline.krml extract/Kremlin/Vale_Stdcalls_X64_Fsub.krml extract/Kremlin/Vale_Wrapper_X64_Fsub.krml extract/Kremlin/Vale_Inline_X64_Fadd_inline.krml extract/Kremlin/Hacl_Impl_Curve25519_Field64_Vale.krml extract/Kremlin/Hacl_Curve25519_64.krml extract/Kremlin/EverCrypt_Curve25519.krml extract/Kremlin/Hacl_Poly1305_128.krml extract/Kremlin/Hacl_Poly1305_256.krml extract/Kremlin/Vale_Poly1305_Equiv.krml extract/Kremlin/Vale_Poly1305_CallingFromLowStar.krml extract/Kremlin/EverCrypt_Poly1305.krml extract/Kremlin/Lib_Memzero.krml extract/Kremlin/Spec_HMAC_DRBG.krml extract/Kremlin/Hacl_HMAC_DRBG.krml extract/Kremlin/Lib_RandomBuffer_System.krml extract/Kremlin/EverCrypt_DRBG.krml extract/Kremlin/Spec_Agile_HKDF.krml extract/Kremlin/Hacl_HKDF.krml extract/Kremlin/EverCrypt_HKDF.krml extract/Kremlin/EverCrypt.krml extract/Kremlin/FStar_Printf.krml extract/Kremlin/FStar_Error.krml extract/Kremlin/FStar_Tcp.krml extract/Kremlin/LowParse_Spec_FLData.krml extract/Kremlin/LowParse_Math.krml extract/Kremlin/LowParse_Slice.krml extract/Kremlin/LowParse_Low_Base.krml extract/Kremlin/LowParse_Low_Combinators.krml extract/Kremlin/LowParse_Low_FLData.krml extract/Kremlin/LowParse_BigEndian.krml extract/Kremlin/LowParse_Spec_Int_Aux.krml extract/Kremlin/LowParse_Spec_Int.krml extract/Kremlin/LowParse_Spec_BoundedInt.krml extract/Kremlin/LowParse_BigEndianImpl_Base.krml extract/Kremlin/LowParse_BigEndianImpl_Low.krml extract/Kremlin/LowParse_Low_BoundedInt.krml extract/Kremlin/LowParse_Spec_SeqBytes_Base.krml extract/Kremlin/LowParse_Spec_DER.krml extract/Kremlin/LowParse_Spec_BCVLI.krml extract/Kremlin/LowParse_Spec_AllIntegers.krml extract/Kremlin/LowParse_Spec_VLData.krml extract/Kremlin/LowParse_Low_VLData.krml extract/Kremlin/LowParse_Spec_VLGen.krml extract/Kremlin/LowParse_Low_VLGen.krml extract/Kremlin/LowParse_Spec_Int_Unique.krml extract/Kremlin/LowParse_Low_Int_Aux.krml extract/Kremlin/LowParse_Low_Int.krml extract/Kremlin/LowParse_Low_DER.krml extract/Kremlin/LowParse_Low_BCVLI.krml extract/Kremlin/LowParse_Low_List.krml extract/Kremlin/LowParse_Spec_Array.krml extract/Kremlin/LowParse_Spec_VCList.krml extract/Kremlin/LowParse_Low_VCList.krml extract/Kremlin/LowParse_Low_IfThenElse.krml extract/Kremlin/LowParse_TacLib.krml extract/Kremlin/LowParse_Spec_Enum.krml extract/Kremlin/LowParse_Spec_Sum.krml extract/Kremlin/LowParse_Low_Enum.krml extract/Kremlin/LowParse_Low_Sum.krml extract/Kremlin/LowParse_Low_Tac_Sum.krml extract/Kremlin/LowParse_Low_Option.krml extract/Kremlin/LowParse_Spec_Bytes.krml extract/Kremlin/LowParse_Low_Bytes.krml extract/Kremlin/LowParse_Low_Array.krml extract/Kremlin/LowParse_Low.krml extract/Kremlin/LowParse_SLow_FLData.krml extract/Kremlin/LowParse_SLow_VLGen.krml extract/Kremlin/LowParse_BigEndianImpl_SLow.krml extract/Kremlin/LowParse_SLow_BoundedInt.krml extract/Kremlin/LowParse_SLow_Int_Aux.krml extract/Kremlin/LowParse_SLow_Int.krml extract/Kremlin/LowParse_SLow_DER.krml extract/Kremlin/LowParse_SLow_BCVLI.krml extract/Kremlin/LowParse_SLow_VCList.krml extract/Kremlin/LowParse_SLow_IfThenElse.krml extract/Kremlin/LowParse_SLow_Enum.krml extract/Kremlin/LowParse_SLow_Sum.krml extract/Kremlin/LowParse_SLow_Tac_Enum.krml extract/Kremlin/LowParse_SLow_Tac_Sum.krml extract/Kremlin/LowParse_SLow_VLData.krml extract/Kremlin/LowParse_SLow_Bytes.krml extract/Kremlin/LowParse_SLow_Array.krml extract/Kremlin/LowParse_Spec_Tac_Combinators.krml extract/Kremlin/LowParse_SLow.krml extract/Kremlin/Parsers_AlertDescription.krml extract/Kremlin/Parsers_AlertLevel.krml extract/Kremlin/Parsers_Alert.krml extract/Kremlin/TLSError.krml extract/Kremlin/Parsers_NamedGroup.krml extract/Kremlin/Format_Constants.krml extract/Kremlin/Format_UncompressedPointRepresentation.krml extract/Kremlin/Format_KeyShareEntry.krml extract/Kremlin/Flags.krml extract/Kremlin/Parsers_ECCurveType.krml extract/Kremlin/DebugFlags.krml extract/Kremlin/FStar_DependentMap.krml extract/Kremlin/FStar_Monotonic_DependentMap.krml extract/Kremlin/Mem.krml extract/Kremlin/Random.krml extract/Kremlin/TLS_Curve25519.krml extract/Kremlin/Parse.krml extract/Kremlin/ECGroup.krml extract/Kremlin/DHGroup.krml extract/Kremlin/Parsers_NamedGroupList.krml extract/Kremlin/CommonDH.krml extract/Kremlin/FFICallbacks.krml extract/Kremlin/Parsers_CompressionMethod.krml extract/Kremlin/Parsers_SignatureScheme.krml extract/Kremlin/Parsers_SignatureSchemeList.krml extract/Kremlin/LowParseWrappers.krml extract/Kremlin/Parsers_CipherSuite.krml extract/Kremlin/CipherSuite.krml extract/Kremlin/Parsers_ProtocolVersion.krml extract/Kremlin/TLSConstants.krml extract/Kremlin/HMAC.krml extract/Kremlin/RSAKey.krml extract/Kremlin/PMS.krml extract/Kremlin/List_Helpers.krml extract/Kremlin/PSK.krml extract/Kremlin/Extensions.krml extract/Kremlin/Cert.krml extract/Kremlin/TLSInfoFlags.krml extract/Kremlin/FStar_Date.krml extract/Kremlin/Nonce.krml extract/Kremlin/TLSInfo.krml extract/Kremlin/Crypto_Indexing.krml extract/Kremlin/Flag.krml extract/Kremlin/FStar_Old_Endianness.krml extract/Kremlin/FStar_Buffer.krml extract/Kremlin/C_Compat_Loops.krml extract/Kremlin/Buffer_Utils.krml extract/Kremlin/Crypto_Symmetric_Bytes.krml extract/Kremlin/Crypto_Plain.krml extract/Kremlin/AEADProvider.krml extract/Kremlin/Range.krml extract/Kremlin/DataStream.krml extract/Kremlin/Alert.krml extract/Kremlin/Content.krml extract/Kremlin/StreamPlain.krml extract/Kremlin/Hashing.krml extract/Kremlin/TLSPRF.krml extract/Kremlin/Hashing_CRF.krml extract/Kremlin/HandshakeMessages.krml extract/Kremlin/HandshakeLog.krml extract/Kremlin/Parsers_Boolean.krml extract/Kremlin/Parsers_TicketContents13_custom_data.krml extract/Kremlin/Parsers_TicketContents13_nonce.krml extract/Kremlin/Parsers_TicketContents13_rms.krml extract/Kremlin/Parsers_TicketContents13.krml extract/Kremlin/Parsers_TicketContents12_master_secret.krml extract/Kremlin/Parsers_TicketContents12.krml extract/Kremlin/Parsers_TicketVersion.krml extract/Kremlin/Parsers_TicketContents.krml extract/Kremlin/Parsers_TicketContents12_master_secret_Low.krml extract/Kremlin/Parsers_Ticket_Low.krml extract/Kremlin/Ticket.krml extract/Kremlin/Negotiation.krml extract/Kremlin/FStar_Monotonic_Seq.krml extract/Kremlin/StreamAE.krml extract/Kremlin/StatefulPlain.krml extract/Kremlin/LHAEPlain.krml extract/Kremlin/AEAD_GCM.krml extract/Kremlin/StatefulLHAE.krml extract/Kremlin/StAE.krml extract/Kremlin/Old_HMAC_UFCMA.krml extract/Kremlin/Parsers_HKDF_HkdfLabel_context.krml extract/Kremlin/Parsers_HKDF_HkdfLabel_label.krml extract/Kremlin/Parsers_HKDF_HkdfLabel.krml extract/Kremlin/HKDF.krml extract/Kremlin/Old_KeySchedule.krml extract/Kremlin/Old_Epochs.krml extract/Kremlin/FStar_HyperStack_IO.krml extract/Kremlin/StreamDeltas.krml extract/Kremlin/Old_Handshake.krml extract/Kremlin/Transport.krml extract/Kremlin/BufferBytes.krml extract/Kremlin/Record.krml extract/Kremlin/Connection.krml extract/Kremlin/TLS.krml extract/Kremlin/FFI.krml extract/Kremlin/Pkg.krml extract/Kremlin/Idx.krml extract/Kremlin/Model.krml extract/Kremlin/FStar_Test.krml extract/Kremlin/Pkg_Tree.krml extract/Kremlin/KDF.krml extract/Kremlin/QUIC.krml extract/Kremlin/IV.krml extract/Kremlin/KDF_Rekey.krml -tmpdir extract/Kremlin-Library -skip-compilation
F* version: 946ec3ee
KreMLin version: 88253438
*/
#include "kremlinit.h"
#if defined(__GNUC__) && !(defined(_WIN32) || defined(_WIN64))
__attribute__ ((visibility ("hidden")))
#endif
void kremlinit_globals()
{
FStar_Bytes_bytes s = FStar_Bytes_bytes_of_string("tls13 ");
HKDF_tls13_prefix = s;
CipherSuite_parse_cipherSuiteName_error_msg =
FStar_Error_perror("CipherSuite.fsti",
(krml_checked_int_t)367,
"");
Prims_string
p1 =
"ffffffffffffffffadf85458a2bb4a9aafdc5620273d3cf1d8b9c583ce2d3695a9e13641146433fbcc939dce249b3ef97d2fe363630c75d8f681b202aec4617ad3df1ed5d5fd65612433f51f5f066ed0856365553ded1af3b557135e7f57c935984f0c70e0e68b77e2a689daf3efe8721df158a136ade73530acca4f483a797abc0ab182b324fb61d108a94bb2c8e3fbb96adab760d7f4681d4f42a3de394df4ae56ede76372bb190b07a7c8ee0a6d709e02fce1cdf7e2ecc03404cd28342f619172fe9ce98583ff8e4f1232eef28183c3fe3b1b4c6fad733bb5fcbc2ec22005c58ef1837d1683b2c6f34a26c1b2effa886b423861285c97ffffffffffffffff";
Prims_string
q0 =
"7fffffffffffffffd6fc2a2c515da54d57ee2b10139e9e78ec5ce2c1e7169b4ad4f09b208a3219fde649cee7124d9f7cbe97f1b1b1863aec7b40d901576230bd69ef8f6aeafeb2b09219fa8faf83376842b1b2aa9ef68d79daab89af3fabe49acc278638707345bbf15344ed79f7f4390ef8ac509b56f39a98566527a41d3cbd5e0558c159927db0e88454a5d96471fddcb56d5bb06bfa340ea7a151ef1ca6fa572b76f3b1b95d8c8583d3e4770536b84f017e70e6fbf176601a0266941a17b0c8b97f4e74c2c1ffc7278919777940c1e1ff1d8da637d6b99ddafe5e17611002e2c778c1be8b41d96379a51360d977fd4435a11c30942e4bffffffffffffffff";
DHGroup_ffdhe2048 = DHGroup_make_ffdhe(p1, q0);
Prims_string
p10 =
"ffffffffffffffffadf85458a2bb4a9aafdc5620273d3cf1d8b9c583ce2d3695a9e13641146433fbcc939dce249b3ef97d2fe363630c75d8f681b202aec4617ad3df1ed5d5fd65612433f51f5f066ed0856365553ded1af3b557135e7f57c935984f0c70e0e68b77e2a689daf3efe8721df158a136ade73530acca4f483a797abc0ab182b324fb61d108a94bb2c8e3fbb96adab760d7f4681d4f42a3de394df4ae56ede76372bb190b07a7c8ee0a6d709e02fce1cdf7e2ecc03404cd28342f619172fe9ce98583ff8e4f1232eef28183c3fe3b1b4c6fad733bb5fcbc2ec22005c58ef1837d1683b2c6f34a26c1b2effa886b4238611fcfdcde355b3b6519035bbc34f4def99c023861b46fc9d6e6c9077ad91d2691f7f7ee598cb0fac186d91caefe130985139270b4130c93bc437944f4fd4452e2d74dd364f2e21e71f54bff5cae82ab9c9df69ee86d2bc522363a0dabc521979b0deada1dbf9a42d5c4484e0abcd06bfa53ddef3c1b20ee3fd59d7c25e41d2b66c62e37ffffffffffffffff";
Prims_string
q1 =
"7fffffffffffffffd6fc2a2c515da54d57ee2b10139e9e78ec5ce2c1e7169b4ad4f09b208a3219fde649cee7124d9f7cbe97f1b1b1863aec7b40d901576230bd69ef8f6aeafeb2b09219fa8faf83376842b1b2aa9ef68d79daab89af3fabe49acc278638707345bbf15344ed79f7f4390ef8ac509b56f39a98566527a41d3cbd5e0558c159927db0e88454a5d96471fddcb56d5bb06bfa340ea7a151ef1ca6fa572b76f3b1b95d8c8583d3e4770536b84f017e70e6fbf176601a0266941a17b0c8b97f4e74c2c1ffc7278919777940c1e1ff1d8da637d6b99ddafe5e17611002e2c778c1be8b41d96379a51360d977fd4435a11c308fe7ee6f1aad9db28c81adde1a7a6f7cce011c30da37e4eb736483bd6c8e9348fbfbf72cc6587d60c36c8e577f0984c289c9385a098649de21bca27a7ea229716ba6e9b279710f38faa5ffae574155ce4efb4f743695e2911b1d06d5e290cbcd86f56d0edfcd216ae22427055e6835fd29eef79e0d90771feacebe12f20e95b363171bffffffffffffffff";
DHGroup_ffdhe3072 = DHGroup_make_ffdhe(p10, q1);
Prims_string
p11 =
"ffffffffffffffffadf85458a2bb4a9aafdc5620273d3cf1d8b9c583ce2d3695a9e13641146433fbcc939dce249b3ef97d2fe363630c75d8f681b202aec4617ad3df1ed5d5fd65612433f51f5f066ed0856365553ded1af3b557135e7f57c935984f0c70e0e68b77e2a689daf3efe8721df158a136ade73530acca4f483a797abc0ab182b324fb61d108a94bb2c8e3fbb96adab760d7f4681d4f42a3de394df4ae56ede76372bb190b07a7c8ee0a6d709e02fce1cdf7e2ecc03404cd28342f619172fe9ce98583ff8e4f1232eef28183c3fe3b1b4c6fad733bb5fcbc2ec22005c58ef1837d1683b2c6f34a26c1b2effa886b4238611fcfdcde355b3b6519035bbc34f4def99c023861b46fc9d6e6c9077ad91d2691f7f7ee598cb0fac186d91caefe130985139270b4130c93bc437944f4fd4452e2d74dd364f2e21e71f54bff5cae82ab9c9df69ee86d2bc522363a0dabc521979b0deada1dbf9a42d5c4484e0abcd06bfa53ddef3c1b20ee3fd59d7c25e41d2b669e1ef16e6f52c3164df4fb7930e9e4e58857b6ac7d5f42d69f6d187763cf1d5503400487f55ba57e31cc7a7135c886efb4318aed6a1e012d9e6832a907600a918130c46dc778f971ad0038092999a333cb8b7a1a1db93d7140003c2a4ecea9f98d0acc0a8291cdcec97dcf8ec9b55a7f88a46b4db5a851f44182e1c68a007e5e655f6affffffffffffffff";
Prims_string
q2 =
"7fffffffffffffffd6fc2a2c515da54d57ee2b10139e9e78ec5ce2c1e7169b4ad4f09b208a3219fde649cee7124d9f7cbe97f1b1b1863aec7b40d901576230bd69ef8f6aeafeb2b09219fa8faf83376842b1b2aa9ef68d79daab89af3fabe49acc278638707345bbf15344ed79f7f4390ef8ac509b56f39a98566527a41d3cbd5e0558c159927db0e88454a5d96471fddcb56d5bb06bfa340ea7a151ef1ca6fa572b76f3b1b95d8c8583d3e4770536b84f017e70e6fbf176601a0266941a17b0c8b97f4e74c2c1ffc7278919777940c1e1ff1d8da637d6b99ddafe5e17611002e2c778c1be8b41d96379a51360d977fd4435a11c308fe7ee6f1aad9db28c81adde1a7a6f7cce011c30da37e4eb736483bd6c8e9348fbfbf72cc6587d60c36c8e577f0984c289c9385a098649de21bca27a7ea229716ba6e9b279710f38faa5ffae574155ce4efb4f743695e2911b1d06d5e290cbcd86f56d0edfcd216ae22427055e6835fd29eef79e0d90771feacebe12f20e95b34f0f78b737a9618b26fa7dbc9874f272c42bdb563eafa16b4fb68c3bb1e78eaa81a00243faadd2bf18e63d389ae44377da18c576b50f0096cf34195483b00548c0986236e3bc7cb8d6801c0494ccd199e5c5bd0d0edc9eb8a0001e15276754fcc68566054148e6e764bee7c764daad3fc45235a6dad428fa20c170e345003f2f32afb57fffffffffffffff";
DHGroup_ffdhe4096 = DHGroup_make_ffdhe(p11, q2);
Prims_string
p12 =
"ffffffffffffffffadf85458a2bb4a9aafdc5620273d3cf1d8b9c583ce2d3695a9e13641146433fbcc939dce249b3ef97d2fe363630c75d8f681b202aec4617ad3df1ed5d5fd65612433f51f5f066ed0856365553ded1af3b557135e7f57c935984f0c70e0e68b77e2a689daf3efe8721df158a136ade73530acca4f483a797abc0ab182b324fb61d108a94bb2c8e3fbb96adab760d7f4681d4f42a3de394df4ae56ede76372bb190b07a7c8ee0a6d709e02fce1cdf7e2ecc03404cd28342f619172fe9ce98583ff8e4f1232eef28183c3fe3b1b4c6fad733bb5fcbc2ec22005c58ef1837d1683b2c6f34a26c1b2effa886b4238611fcfdcde355b3b6519035bbc34f4def99c023861b46fc9d6e6c9077ad91d2691f7f7ee598cb0fac186d91caefe130985139270b4130c93bc437944f4fd4452e2d74dd364f2e21e71f54bff5cae82ab9c9df69ee86d2bc522363a0dabc521979b0deada1dbf9a42d5c4484e0abcd06bfa53ddef3c1b20ee3fd59d7c25e41d2b669e1ef16e6f52c3164df4fb7930e9e4e58857b6ac7d5f42d69f6d187763cf1d5503400487f55ba57e31cc7a7135c886efb4318aed6a1e012d9e6832a907600a918130c46dc778f971ad0038092999a333cb8b7a1a1db93d7140003c2a4ecea9f98d0acc0a8291cdcec97dcf8ec9b55a7f88a46b4db5a851f44182e1c68a007e5e0dd9020bfd64b645036c7a4e677d2c38532a3a23ba4442caf53ea63bb454329b7624c8917bdd64b1c0fd4cb38e8c334c701c3acdad0657fccfec719b1f5c3e4e46041f388147fb4cfdb477a52471f7a9a96910b855322edb6340d8a00ef092350511e30abec1fff9e3a26e7fb29f8c183023c3587e38da0077d9b4763e4e4b94b2bbc194c6651e77caf992eeaac0232a281bf6b3a739c1226116820ae8db5847a67cbef9c9091b462d538cd72b03746ae77f5e62292c311562a846505dc82db854338ae49f5235c95b91178ccf2dd5cacef403ec9d1810c6272b045b3b71f9dc6b80d63fdd4a8e9adb1e6962a69526d43161c1a41d570d7938dad4a40e329cd0e40e65ffffffffffffffff";
Prims_string
q3 =
"7fffffffffffffffd6fc2a2c515da54d57ee2b10139e9e78ec5ce2c1e7169b4ad4f09b208a3219fde649cee7124d9f7cbe97f1b1b1863aec7b40d901576230bd69ef8f6aeafeb2b09219fa8faf83376842b1b2aa9ef68d79daab89af3fabe49acc278638707345bbf15344ed79f7f4390ef8ac509b56f39a98566527a41d3cbd5e0558c159927db0e88454a5d96471fddcb56d5bb06bfa340ea7a151ef1ca6fa572b76f3b1b95d8c8583d3e4770536b84f017e70e6fbf176601a0266941a17b0c8b97f4e74c2c1ffc7278919777940c1e1ff1d8da637d6b99ddafe5e17611002e2c778c1be8b41d96379a51360d977fd4435a11c308fe7ee6f1aad9db28c81adde1a7a6f7cce011c30da37e4eb736483bd6c8e9348fbfbf72cc6587d60c36c8e577f0984c289c9385a098649de21bca27a7ea229716ba6e9b279710f38faa5ffae574155ce4efb4f743695e2911b1d06d5e290cbcd86f56d0edfcd216ae22427055e6835fd29eef79e0d90771feacebe12f20e95b34f0f78b737a9618b26fa7dbc9874f272c42bdb563eafa16b4fb68c3bb1e78eaa81a00243faadd2bf18e63d389ae44377da18c576b50f0096cf34195483b00548c0986236e3bc7cb8d6801c0494ccd199e5c5bd0d0edc9eb8a0001e15276754fcc68566054148e6e764bee7c764daad3fc45235a6dad428fa20c170e345003f2f06ec8105feb25b2281b63d2733be961c29951d11dd2221657a9f531dda2a194dbb126448bdeeb258e07ea659c74619a6380e1d66d6832bfe67f638cd8fae1f2723020f9c40a3fda67eda3bd29238fbd4d4b4885c2a99176db1a06c500778491a8288f1855f60fffcf1d1373fd94fc60c1811e1ac3f1c6d003becda3b1f2725ca595de0ca63328f3be57cc97755601195140dfb59d39ce091308b4105746dac23d33e5f7ce4848da316a9c66b9581ba3573bfaf311496188ab15423282ee416dc2a19c5724fa91ae4adc88bc66796eae5677a01f64e8c08631395822d9db8fcee35c06b1feea5474d6d8f34b1534a936a18b0e0d20eab86bc9c6d6a5207194e68720732ffffffffffffffff";
DHGroup_ffdhe6144 = DHGroup_make_ffdhe(p12, q3);
Prims_string
p13 =
"ffffffffffffffffadf85458a2bb4a9aafdc5620273d3cf1d8b9c583ce2d3695a9e13641146433fbcc939dce249b3ef97d2fe363630c75d8f681b202aec4617ad3df1ed5d5fd65612433f51f5f066ed0856365553ded1af3b557135e7f57c935984f0c70e0e68b77e2a689daf3efe8721df158a136ade73530acca4f483a797abc0ab182b324fb61d108a94bb2c8e3fbb96adab760d7f4681d4f42a3de394df4ae56ede76372bb190b07a7c8ee0a6d709e02fce1cdf7e2ecc03404cd28342f619172fe9ce98583ff8e4f1232eef28183c3fe3b1b4c6fad733bb5fcbc2ec22005c58ef1837d1683b2c6f34a26c1b2effa886b4238611fcfdcde355b3b6519035bbc34f4def99c023861b46fc9d6e6c9077ad91d2691f7f7ee598cb0fac186d91caefe130985139270b4130c93bc437944f4fd4452e2d74dd364f2e21e71f54bff5cae82ab9c9df69ee86d2bc522363a0dabc521979b0deada1dbf9a42d5c4484e0abcd06bfa53ddef3c1b20ee3fd59d7c25e41d2b669e1ef16e6f52c3164df4fb7930e9e4e58857b6ac7d5f42d69f6d187763cf1d5503400487f55ba57e31cc7a7135c886efb4318aed6a1e012d9e6832a907600a918130c46dc778f971ad0038092999a333cb8b7a1a1db93d7140003c2a4ecea9f98d0acc0a8291cdcec97dcf8ec9b55a7f88a46b4db5a851f44182e1c68a007e5e0dd9020bfd64b645036c7a4e677d2c38532a3a23ba4442caf53ea63bb454329b7624c8917bdd64b1c0fd4cb38e8c334c701c3acdad0657fccfec719b1f5c3e4e46041f388147fb4cfdb477a52471f7a9a96910b855322edb6340d8a00ef092350511e30abec1fff9e3a26e7fb29f8c183023c3587e38da0077d9b4763e4e4b94b2bbc194c6651e77caf992eeaac0232a281bf6b3a739c1226116820ae8db5847a67cbef9c9091b462d538cd72b03746ae77f5e62292c311562a846505dc82db854338ae49f5235c95b91178ccf2dd5cacef403ec9d1810c6272b045b3b71f9dc6b80d63fdd4a8e9adb1e6962a69526d43161c1a41d570d7938dad4a40e329ccff46aaa36ad004cf600c8381e425a31d951ae64fdb23fcec9509d43687feb69edd1cc5e0b8cc3bdf64b10ef86b63142a3ab8829555b2f747c932665cb2c0f1cc01bd70229388839d2af05e454504ac78b7582822846c0ba35c35f5c59160cc046fd8251541fc68c9c86b022bb7099876a460e7451a8a93109703fee1c217e6c3826e52c51aa691e0e423cfc99e9e31650c1217b624816cdad9a95f9d5b8019488d9c0a0a1fe3075a577e23183f81d4a3f2fa4571efc8ce0ba8a4fe8b6855dfe72b0a66eded2fbabfbe58a30fafabe1c5d71a87e2f741ef8c1fe86fea6bbfde530677f0d97d11d49f7a8443d0822e506a9f4614e011e2a94838ff88cd68c8bb7c5c6424cffffffffffffffff";
Prims_string
q =
"7fffffffffffffffd6fc2a2c515da54d57ee2b10139e9e78ec5ce2c1e7169b4ad4f09b208a3219fde649cee7124d9f7cbe97f1b1b1863aec7b40d901576230bd69ef8f6aeafeb2b09219fa8faf83376842b1b2aa9ef68d79daab89af3fabe49acc278638707345bbf15344ed79f7f4390ef8ac509b56f39a98566527a41d3cbd5e0558c159927db0e88454a5d96471fddcb56d5bb06bfa340ea7a151ef1ca6fa572b76f3b1b95d8c8583d3e4770536b84f017e70e6fbf176601a0266941a17b0c8b97f4e74c2c1ffc7278919777940c1e1ff1d8da637d6b99ddafe5e17611002e2c778c1be8b41d96379a51360d977fd4435a11c308fe7ee6f1aad9db28c81adde1a7a6f7cce011c30da37e4eb736483bd6c8e9348fbfbf72cc6587d60c36c8e577f0984c289c9385a098649de21bca27a7ea229716ba6e9b279710f38faa5ffae574155ce4efb4f743695e2911b1d06d5e290cbcd86f56d0edfcd216ae22427055e6835fd29eef79e0d90771feacebe12f20e95b34f0f78b737a9618b26fa7dbc9874f272c42bdb563eafa16b4fb68c3bb1e78eaa81a00243faadd2bf18e63d389ae44377da18c576b50f0096cf34195483b00548c0986236e3bc7cb8d6801c0494ccd199e5c5bd0d0edc9eb8a0001e15276754fcc68566054148e6e764bee7c764daad3fc45235a6dad428fa20c170e345003f2f06ec8105feb25b2281b63d2733be961c29951d11dd2221657a9f531dda2a194dbb126448bdeeb258e07ea659c74619a6380e1d66d6832bfe67f638cd8fae1f2723020f9c40a3fda67eda3bd29238fbd4d4b4885c2a99176db1a06c500778491a8288f1855f60fffcf1d1373fd94fc60c1811e1ac3f1c6d003becda3b1f2725ca595de0ca63328f3be57cc97755601195140dfb59d39ce091308b4105746dac23d33e5f7ce4848da316a9c66b9581ba3573bfaf311496188ab15423282ee416dc2a19c5724fa91ae4adc88bc66796eae5677a01f64e8c08631395822d9db8fcee35c06b1feea5474d6d8f34b1534a936a18b0e0d20eab86bc9c6d6a5207194e67fa35551b5680267b00641c0f212d18eca8d7327ed91fe764a84ea1b43ff5b4f6e8e62f05c661defb258877c35b18a151d5c414aaad97ba3e499332e596078e600deb81149c441ce95782f22a282563c5bac1411423605d1ae1afae2c8b0660237ec128aa0fe3464e4358115db84cc3b523073a28d4549884b81ff70e10bf361c13729628d5348f07211e7e4cf4f18b286090bdb1240b66d6cd4afceadc00ca446ce05050ff183ad2bbf118c1fc0ea51f97d22b8f7e46705d4527f45b42aeff395853376f697dd5fdf2c5187d7d5f0e2eb8d43f17ba0f7c60ff437f535dfef29833bf86cbe88ea4fbd4221e8411728354fa30a7008f154a41c7fc466b4645dbe2e321267fffffffffffffff";
DHGroup_ffdhe8192 = DHGroup_make_ffdhe(p13, q);
TLSConstants_parse_protocolVersion_error_msg =
FStar_Error_perror("TLSConstants.fst",
(krml_checked_int_t)81,
"");
TLSConstants_max_TLSCompressed_fragment_length =
Prims_op_Addition(TLSConstants_max_TLSPlaintext_fragment_length,
(krml_checked_int_t)1024);
TLSConstants_max_TLSCiphertext_fragment_length =
Prims_op_Addition(TLSConstants_max_TLSPlaintext_fragment_length,
(krml_checked_int_t)2048);
TLSConstants_max_TLSCiphertext_fragment_length_13 =
Prims_op_Addition(TLSConstants_max_TLSPlaintext_fragment_length,
(krml_checked_int_t)256);
TLSConstants_extract_label = FStar_Bytes_utf8_encode("master secret");
TLSConstants_extended_extract_label = FStar_Bytes_utf8_encode("extended master secret");
TLSConstants_kdf_label = FStar_Bytes_utf8_encode("key expansion");
Nonce_nonce_rid_table = FStar_Monotonic_DependentMap_alloc__FStar_Bytes_bytes______();
TLSPRF_tls_client_label = FStar_Bytes_utf8_encode("client finished");
TLSPRF_tls_server_label = FStar_Bytes_utf8_encode("server finished");
PSK_tickets = FStar_Monotonic_DependentMap_alloc__Prims_string_FStar_Bytes_bytes_Prims_l_True();
PSK_sessions12 =
FStar_Monotonic_DependentMap_alloc__FStar_Bytes_bytes_Parsers_ProtocolVersion_protocolVersion___CipherSuite_cipherSuite____bool___FStar_Bytes_bytes_Prims_l_True();
PSK_app_psk_table =
FStar_Monotonic_DependentMap_alloc__FStar_Bytes_bytes_FStar_Bytes_bytes___TLSConstants_pskInfo___bool___();
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite), (uint32_t)1U);
Prims_list__Parsers_CipherSuite_cipherSuite
*buf0 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite));
buf0[0U] = ((Prims_list__Parsers_CipherSuite_cipherSuite){ .tag = Prims_Nil });
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite), (uint32_t)1U);
Prims_list__Parsers_CipherSuite_cipherSuite
*buf1 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite));
buf1[0U]
=
(
(Prims_list__Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = { .tag = Parsers_CipherSuite_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 },
.tl = buf0
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite), (uint32_t)1U);
Prims_list__Parsers_CipherSuite_cipherSuite
*buf2 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite));
buf2[0U]
=
(
(Prims_list__Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = { .tag = Parsers_CipherSuite_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 },
.tl = buf1
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite), (uint32_t)1U);
Prims_list__Parsers_CipherSuite_cipherSuite
*buf3 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite));
buf3[0U]
=
(
(Prims_list__Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = { .tag = Parsers_CipherSuite_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 },
.tl = buf2
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite), (uint32_t)1U);
Prims_list__Parsers_CipherSuite_cipherSuite
*buf4 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite));
buf4[0U]
=
(
(Prims_list__Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = { .tag = Parsers_CipherSuite_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 },
.tl = buf3
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite), (uint32_t)1U);
Prims_list__Parsers_CipherSuite_cipherSuite
*buf5 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite));
buf5[0U]
=
(
(Prims_list__Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = { .tag = Parsers_CipherSuite_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 },
.tl = buf4
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite), (uint32_t)1U);
Prims_list__Parsers_CipherSuite_cipherSuite
*buf6 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite));
buf6[0U]
=
(
(Prims_list__Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = { .tag = Parsers_CipherSuite_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 },
.tl = buf5
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite), (uint32_t)1U);
Prims_list__Parsers_CipherSuite_cipherSuite
*buf7 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite));
buf7[0U]
=
(
(Prims_list__Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = { .tag = Parsers_CipherSuite_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 },
.tl = buf6
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite), (uint32_t)1U);
Prims_list__Parsers_CipherSuite_cipherSuite
*buf8 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite));
buf8[0U]
=
(
(Prims_list__Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = { .tag = Parsers_CipherSuite_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 },
.tl = buf7
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite), (uint32_t)1U);
Prims_list__Parsers_CipherSuite_cipherSuite
*buf9 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite));
buf9[0U]
=
(
(Prims_list__Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = { .tag = Parsers_CipherSuite_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 },
.tl = buf8
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite), (uint32_t)1U);
Prims_list__Parsers_CipherSuite_cipherSuite
*buf10 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite));
buf10[0U]
=
(
(Prims_list__Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = { .tag = Parsers_CipherSuite_TLS_CHACHA20_POLY1305_SHA256 },
.tl = buf9
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite), (uint32_t)1U);
Prims_list__Parsers_CipherSuite_cipherSuite
*buf11 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite));
buf11[0U]
=
(
(Prims_list__Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = { .tag = Parsers_CipherSuite_TLS_AES_256_GCM_SHA384 },
.tl = buf10
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite), (uint32_t)1U);
Prims_list__Parsers_CipherSuite_cipherSuite
*buf12 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_CipherSuite_cipherSuite));
buf12[0U]
=
(
(Prims_list__Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = { .tag = Parsers_CipherSuite_TLS_AES_128_GCM_SHA256 },
.tl = buf11
}
);
TLSInfo_default_cipherSuites = buf12;
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme), (uint32_t)1U);
Prims_list__Parsers_SignatureScheme_signatureScheme
*buf13 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme));
buf13[0U] = ((Prims_list__Parsers_SignatureScheme_signatureScheme){ .tag = Prims_Nil });
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme), (uint32_t)1U);
Prims_list__Parsers_SignatureScheme_signatureScheme
*buf14 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme));
buf14[0U]
=
(
(Prims_list__Parsers_SignatureScheme_signatureScheme){
.tag = Prims_Cons,
.hd = { .tag = Parsers_SignatureScheme_Rsa_pkcs1_sha1 },
.tl = buf13
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme), (uint32_t)1U);
Prims_list__Parsers_SignatureScheme_signatureScheme
*buf15 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme));
buf15[0U]
=
(
(Prims_list__Parsers_SignatureScheme_signatureScheme){
.tag = Prims_Cons,
.hd = { .tag = Parsers_SignatureScheme_Ecdsa_sha1 },
.tl = buf14
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme), (uint32_t)1U);
Prims_list__Parsers_SignatureScheme_signatureScheme
*buf16 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme));
buf16[0U]
=
(
(Prims_list__Parsers_SignatureScheme_signatureScheme){
.tag = Prims_Cons,
.hd = { .tag = Parsers_SignatureScheme_Rsa_pkcs1_sha512 },
.tl = buf15
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme), (uint32_t)1U);
Prims_list__Parsers_SignatureScheme_signatureScheme
*buf17 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme));
buf17[0U]
=
(
(Prims_list__Parsers_SignatureScheme_signatureScheme){
.tag = Prims_Cons,
.hd = { .tag = Parsers_SignatureScheme_Rsa_pkcs1_sha384 },
.tl = buf16
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme), (uint32_t)1U);
Prims_list__Parsers_SignatureScheme_signatureScheme
*buf18 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme));
buf18[0U]
=
(
(Prims_list__Parsers_SignatureScheme_signatureScheme){
.tag = Prims_Cons,
.hd = { .tag = Parsers_SignatureScheme_Rsa_pkcs1_sha256 },
.tl = buf17
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme), (uint32_t)1U);
Prims_list__Parsers_SignatureScheme_signatureScheme
*buf19 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme));
buf19[0U]
=
(
(Prims_list__Parsers_SignatureScheme_signatureScheme){
.tag = Prims_Cons,
.hd = { .tag = Parsers_SignatureScheme_Rsa_pss_rsae_sha512 },
.tl = buf18
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme), (uint32_t)1U);
Prims_list__Parsers_SignatureScheme_signatureScheme
*buf20 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme));
buf20[0U]
=
(
(Prims_list__Parsers_SignatureScheme_signatureScheme){
.tag = Prims_Cons,
.hd = { .tag = Parsers_SignatureScheme_Rsa_pss_rsae_sha384 },
.tl = buf19
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme), (uint32_t)1U);
Prims_list__Parsers_SignatureScheme_signatureScheme
*buf21 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme));
buf21[0U]
=
(
(Prims_list__Parsers_SignatureScheme_signatureScheme){
.tag = Prims_Cons,
.hd = { .tag = Parsers_SignatureScheme_Rsa_pss_rsae_sha256 },
.tl = buf20
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme), (uint32_t)1U);
Prims_list__Parsers_SignatureScheme_signatureScheme
*buf22 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme));
buf22[0U]
=
(
(Prims_list__Parsers_SignatureScheme_signatureScheme){
.tag = Prims_Cons,
.hd = { .tag = Parsers_SignatureScheme_Ecdsa_secp521r1_sha512 },
.tl = buf21
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme), (uint32_t)1U);
Prims_list__Parsers_SignatureScheme_signatureScheme
*buf23 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme));
buf23[0U]
=
(
(Prims_list__Parsers_SignatureScheme_signatureScheme){
.tag = Prims_Cons,
.hd = { .tag = Parsers_SignatureScheme_Ecdsa_secp384r1_sha384 },
.tl = buf22
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme), (uint32_t)1U);
Prims_list__Parsers_SignatureScheme_signatureScheme
*buf24 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_SignatureScheme_signatureScheme));
buf24[0U]
=
(
(Prims_list__Parsers_SignatureScheme_signatureScheme){
.tag = Prims_Cons,
.hd = { .tag = Parsers_SignatureScheme_Ecdsa_secp256r1_sha256 },
.tl = buf23
}
);
TLSInfo_default_signature_schemes = buf24;
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_NamedGroup_namedGroup), (uint32_t)1U);
Prims_list__Parsers_NamedGroup_namedGroup
*buf25 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_NamedGroup_namedGroup));
buf25[0U] = ((Prims_list__Parsers_NamedGroup_namedGroup){ .tag = Prims_Nil });
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_NamedGroup_namedGroup), (uint32_t)1U);
Prims_list__Parsers_NamedGroup_namedGroup
*buf26 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_NamedGroup_namedGroup));
buf26[0U]
=
(
(Prims_list__Parsers_NamedGroup_namedGroup){
.tag = Prims_Cons,
.hd = { .tag = Parsers_NamedGroup_Ffdhe2048 },
.tl = buf25
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_NamedGroup_namedGroup), (uint32_t)1U);
Prims_list__Parsers_NamedGroup_namedGroup
*buf27 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_NamedGroup_namedGroup));
buf27[0U]
=
(
(Prims_list__Parsers_NamedGroup_namedGroup){
.tag = Prims_Cons,
.hd = { .tag = Parsers_NamedGroup_Ffdhe3072 },
.tl = buf26
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_NamedGroup_namedGroup), (uint32_t)1U);
Prims_list__Parsers_NamedGroup_namedGroup
*buf28 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_NamedGroup_namedGroup));
buf28[0U]
=
(
(Prims_list__Parsers_NamedGroup_namedGroup){
.tag = Prims_Cons,
.hd = { .tag = Parsers_NamedGroup_Ffdhe4096 },
.tl = buf27
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_NamedGroup_namedGroup), (uint32_t)1U);
Prims_list__Parsers_NamedGroup_namedGroup
*buf29 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_NamedGroup_namedGroup));
buf29[0U]
=
(
(Prims_list__Parsers_NamedGroup_namedGroup){
.tag = Prims_Cons,
.hd = { .tag = Parsers_NamedGroup_Secp256r1 },
.tl = buf28
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_NamedGroup_namedGroup), (uint32_t)1U);
Prims_list__Parsers_NamedGroup_namedGroup
*buf30 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_NamedGroup_namedGroup));
buf30[0U]
=
(
(Prims_list__Parsers_NamedGroup_namedGroup){
.tag = Prims_Cons,
.hd = { .tag = Parsers_NamedGroup_X25519 },
.tl = buf29
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_NamedGroup_namedGroup), (uint32_t)1U);
Prims_list__Parsers_NamedGroup_namedGroup
*buf31 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_NamedGroup_namedGroup));
buf31[0U]
=
(
(Prims_list__Parsers_NamedGroup_namedGroup){
.tag = Prims_Cons,
.hd = { .tag = Parsers_NamedGroup_Secp384r1 },
.tl = buf30
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_NamedGroup_namedGroup), (uint32_t)1U);
Prims_list__Parsers_NamedGroup_namedGroup
*buf32 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_NamedGroup_namedGroup));
buf32[0U]
=
(
(Prims_list__Parsers_NamedGroup_namedGroup){
.tag = Prims_Cons,
.hd = { .tag = Parsers_NamedGroup_Secp521r1 },
.tl = buf31
}
);
TLSInfo_default_groups = buf32;
TLSInfo_defaultTicketCB =
(
(TLSConstants_ticket_cb){
.ticket_context = FStar_Dyn_mkdyn____(),
.new_ticket = TLSInfo_defaultTicketCBFun
}
);
TLSInfo_defaultServerNegoCB =
(
(TLSConstants_nego_cb){
.nego_context = FStar_Dyn_mkdyn____(),
.negotiate = TLSInfo_defaultServerNegoCBFun
}
);
FStar_Dyn_dyn uu____0 = FStar_Dyn_mkdyn____();
FStar_Dyn_dyn uu____1 = FStar_Dyn_mkdyn____();
FStar_Dyn_dyn uu____2 = FStar_Dyn_mkdyn____();
FStar_Dyn_dyn uu____3 = FStar_Dyn_mkdyn____();
TLSInfo_defaultCertCB =
TLSConstants_mk_cert_cb(uu____0,
uu____1,
TLSInfo_none6__FStar_Dyn_dyn_FStar_Dyn_dyn_Parsers_ProtocolVersion_protocolVersion_FStar_Bytes_bytes_FStar_Bytes_bytes_Prims_list_Parsers_SignatureScheme_signatureScheme_uint64_t___Parsers_SignatureScheme_signatureScheme,
uu____2,
TLSInfo_empty3__FStar_Dyn_dyn_FStar_Dyn_dyn_uint64_t_FStar_Bytes_bytes,
uu____3,
TLSInfo_none5__FStar_Dyn_dyn_FStar_Dyn_dyn_uint64_t_Parsers_SignatureScheme_signatureScheme_FStar_Bytes_bytes_FStar_Bytes_bytes,
FStar_Dyn_mkdyn____(),
TLSInfo_false6__FStar_Dyn_dyn_FStar_Dyn_dyn_Prims_list_FStar_Bytes_bytes_Parsers_SignatureScheme_signatureScheme_FStar_Bytes_bytes_FStar_Bytes_bytes);
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_NamedGroup_namedGroup), (uint32_t)1U);
Prims_list__Parsers_NamedGroup_namedGroup
*buf33 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_NamedGroup_namedGroup));
buf33[0U] = ((Prims_list__Parsers_NamedGroup_namedGroup){ .tag = Prims_Nil });
KRML_CHECK_SIZE(sizeof (Prims_list__Parsers_NamedGroup_namedGroup), (uint32_t)1U);
Prims_list__Parsers_NamedGroup_namedGroup
*buf34 = KRML_HOST_MALLOC(sizeof (Prims_list__Parsers_NamedGroup_namedGroup));
buf34[0U]
=
(
(Prims_list__Parsers_NamedGroup_namedGroup){
.tag = Prims_Cons,
.hd = { .tag = Parsers_NamedGroup_X25519 },
.tl = buf33
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___uint16_t_FStar_Bytes_bytes), (uint32_t)1U);
Prims_list__K___uint16_t_FStar_Bytes_bytes
*buf35 = KRML_HOST_MALLOC(sizeof (Prims_list__K___uint16_t_FStar_Bytes_bytes));
buf35[0U] = ((Prims_list__K___uint16_t_FStar_Bytes_bytes){ .tag = Prims_Nil });
KRML_CHECK_SIZE(sizeof (Prims_list__K___FStar_Bytes_bytes_FStar_Bytes_bytes), (uint32_t)1U);
Prims_list__K___FStar_Bytes_bytes_FStar_Bytes_bytes
*buf = KRML_HOST_MALLOC(sizeof (Prims_list__K___FStar_Bytes_bytes_FStar_Bytes_bytes));
buf[0U] = ((Prims_list__K___FStar_Bytes_bytes_FStar_Bytes_bytes){ .tag = Prims_Nil });
TLSInfo_defaultConfig =
(
(TLSConstants_config){
.min_version = { .tag = Parsers_ProtocolVersion_TLS_1p2 },
.max_version = { .tag = Parsers_ProtocolVersion_TLS_1p3 },
.is_quic = false,
.cipher_suites = CipherSuite_cipherSuites_of_nameList(TLSInfo_default_cipherSuites),
.named_groups = TLSInfo_default_groups,
.signature_algorithms = TLSInfo_default_signature_schemes,
.hello_retry = true,
.offer_shares = CommonDH_as_supportedNamedGroups(buf34),
.custom_extensions = buf35,
.use_tickets = buf,
.send_ticket = { .tag = FStar_Pervasives_Native_Some, .v = FStar_Bytes_empty_bytes },
.check_client_version_in_pms_for_old_tls = true,
.request_client_certificate = false,
.non_blocking_read = false,
.max_early_data = { .tag = FStar_Pervasives_Native_None },
.max_ticket_age = (uint32_t)3600U,
.safe_renegotiation = true,
.extended_master_secret = true,
.enable_tickets = true,
.ticket_callback = TLSInfo_defaultTicketCB,
.nego_callback = TLSInfo_defaultServerNegoCB,
.cert_callbacks = TLSInfo_defaultCertCB,
.alpn = { .tag = FStar_Pervasives_Native_None },
.peer_name = { .tag = FStar_Pervasives_Native_None }
}
);
HandshakeMessages_helloRequestBytes =
HandshakeMessages_messageBytes(HandshakeMessages_HT_hello_request,
FStar_Bytes_empty_bytes);
HandshakeMessages_ccsBytes = FStar_Bytes_abyte((uint8_t)1U);
HandshakeMessages_serverHelloDoneBytes =
HandshakeMessages_messageBytes(HandshakeMessages_HT_server_hello_done,
FStar_Bytes_empty_bytes);
HandshakeMessages_endOfEarlyDataBytes =
HandshakeMessages_messageBytes(HandshakeMessages_HT_end_of_early_data,
FStar_Bytes_empty_bytes);
KRML_CHECK_SIZE(sizeof (FStar_Pervasives_Native_option__Ticket_ticket_key), (uint32_t)1U);
FStar_Pervasives_Native_option__Ticket_ticket_key
*buf36 = KRML_HOST_MALLOC(sizeof (FStar_Pervasives_Native_option__Ticket_ticket_key));
buf36[0U]
= ((FStar_Pervasives_Native_option__Ticket_ticket_key){ .tag = FStar_Pervasives_Native_None });
Ticket_ticket_enc = buf36;
KRML_CHECK_SIZE(sizeof (FStar_Pervasives_Native_option__Ticket_ticket_key), (uint32_t)1U);
FStar_Pervasives_Native_option__Ticket_ticket_key
*buf37 = KRML_HOST_MALLOC(sizeof (FStar_Pervasives_Native_option__Ticket_ticket_key));
buf37[0U]
= ((FStar_Pervasives_Native_option__Ticket_ticket_key){ .tag = FStar_Pervasives_Native_None });
Ticket_sealing_enc = buf37;
Range_zero = Range_point((krml_checked_int_t)0);
Range_fragment_range =
(
(K___Prims_int_Prims_int){
.fst = (krml_checked_int_t)0,
.snd = TLSConstants_max_TLSPlaintext_fragment_length
}
);
Content_ccsBytes = FStar_Bytes_abyte((uint8_t)1U);
StreamAE_max_ctr =
Prims_op_Subtraction(Prims_pow2((krml_checked_int_t)64),
(krml_checked_int_t)1);
Record_headerLength = FStar_UInt32_v(Record_headerLen);
Record_fake =
FStar_Bytes_append(Record_ctBytes(Content_Application_data),
Record_versionBytes((
(Parsers_ProtocolVersion_protocolVersion){ .tag = Parsers_ProtocolVersion_TLS_1p2 }
)));
Record_maxlen =
Record_headerLen
+ FStar_UInt32_uint_to_t(TLSConstants_max_TLSCiphertext_fragment_length);
TLS_fragment_range = Range_fragment_range;
TLS_ad_overflow = TLSError_fatal____(Parsers_AlertDescription_Record_overflow, "seqn overflow");
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite
*buf38 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite));
buf38[0U]
= ((Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite){ .tag = Prims_Nil });
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite
*buf39 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite));
buf39[0U]
=
(
(Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = {
.fst = "DHE-RSA-CHACHA20-POLY1305-SHA256",
.snd = { .tag = Parsers_CipherSuite_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 }
},
.tl = buf38
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite
*buf40 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite));
buf40[0U]
=
(
(Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = {
.fst = "DHE-RSA-AES128-GCM-SHA256",
.snd = { .tag = Parsers_CipherSuite_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 }
},
.tl = buf39
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite
*buf41 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite));
buf41[0U]
=
(
(Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = {
.fst = "DHE-RSA-AES256-GCM-SHA384",
.snd = { .tag = Parsers_CipherSuite_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 }
},
.tl = buf40
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite
*buf42 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite));
buf42[0U]
=
(
(Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = {
.fst = "ECDHE-ECDSA-CHACHA20-POLY1305-SHA256",
.snd = { .tag = Parsers_CipherSuite_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 }
},
.tl = buf41
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite
*buf43 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite));
buf43[0U]
=
(
(Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = {
.fst = "ECDHE-ECDSA-AES128-GCM-SHA256",
.snd = { .tag = Parsers_CipherSuite_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 }
},
.tl = buf42
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite
*buf44 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite));
buf44[0U]
=
(
(Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = {
.fst = "ECDHE-ECDSA-AES256-GCM-SHA384",
.snd = { .tag = Parsers_CipherSuite_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 }
},
.tl = buf43
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite
*buf45 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite));
buf45[0U]
=
(
(Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = {
.fst = "ECDHE-RSA-CHACHA20-POLY1305-SHA256",
.snd = { .tag = Parsers_CipherSuite_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 }
},
.tl = buf44
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite
*buf46 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite));
buf46[0U]
=
(
(Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = {
.fst = "ECDHE-RSA-AES128-GCM-SHA256",
.snd = { .tag = Parsers_CipherSuite_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 }
},
.tl = buf45
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite
*buf47 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite));
buf47[0U]
=
(
(Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = {
.fst = "ECDHE-RSA-AES256-GCM-SHA384",
.snd = { .tag = Parsers_CipherSuite_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 }
},
.tl = buf46
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite
*buf48 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite));
buf48[0U]
=
(
(Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = {
.fst = "TLS_AES_128_CCM_8_SHA256",
.snd = { .tag = Parsers_CipherSuite_TLS_AES_128_CCM_8_SHA256 }
},
.tl = buf47
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite
*buf49 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite));
buf49[0U]
=
(
(Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = {
.fst = "TLS_AES_128_CCM_SHA256",
.snd = { .tag = Parsers_CipherSuite_TLS_AES_128_CCM_SHA256 }
},
.tl = buf48
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite
*buf50 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite));
buf50[0U]
=
(
(Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = {
.fst = "TLS_CHACHA20_POLY1305_SHA256",
.snd = { .tag = Parsers_CipherSuite_TLS_CHACHA20_POLY1305_SHA256 }
},
.tl = buf49
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite
*buf51 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite));
buf51[0U]
=
(
(Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = {
.fst = "TLS_AES_256_GCM_SHA384",
.snd = { .tag = Parsers_CipherSuite_TLS_AES_256_GCM_SHA384 }
},
.tl = buf50
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite
*buf52 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite));
buf52[0U]
=
(
(Prims_list__K___Prims_string_Parsers_CipherSuite_cipherSuite){
.tag = Prims_Cons,
.hd = {
.fst = "TLS_AES_128_GCM_SHA256",
.snd = { .tag = Parsers_CipherSuite_TLS_AES_128_GCM_SHA256 }
},
.tl = buf51
}
);
FFI_css = buf52;
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme
*buf53 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme));
buf53[0U]
= ((Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme){ .tag = Prims_Nil });
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme
*buf54 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme));
buf54[0U]
=
(
(Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme){
.tag = Prims_Cons,
.hd = { .fst = "ECDSA+SHA1", .snd = { .tag = Parsers_SignatureScheme_Ecdsa_sha1 } },
.tl = buf53
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme
*buf55 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme));
buf55[0U]
=
(
(Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme){
.tag = Prims_Cons,
.hd = { .fst = "RSA+SHA1", .snd = { .tag = Parsers_SignatureScheme_Rsa_pkcs1_sha1 } },
.tl = buf54
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme
*buf56 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme));
buf56[0U]
=
(
(Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme){
.tag = Prims_Cons,
.hd = { .fst = "RSA+SHA256", .snd = { .tag = Parsers_SignatureScheme_Rsa_pkcs1_sha256 } },
.tl = buf55
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme
*buf57 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme));
buf57[0U]
=
(
(Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme){
.tag = Prims_Cons,
.hd = { .fst = "RSA+SHA384", .snd = { .tag = Parsers_SignatureScheme_Rsa_pkcs1_sha384 } },
.tl = buf56
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme
*buf58 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme));
buf58[0U]
=
(
(Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme){
.tag = Prims_Cons,
.hd = { .fst = "RSA+SHA512", .snd = { .tag = Parsers_SignatureScheme_Rsa_pkcs1_sha512 } },
.tl = buf57
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme
*buf59 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme));
buf59[0U]
=
(
(Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme){
.tag = Prims_Cons,
.hd = {
.fst = "ECDSA+SHA256",
.snd = { .tag = Parsers_SignatureScheme_Ecdsa_secp256r1_sha256 }
},
.tl = buf58
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme
*buf60 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme));
buf60[0U]
=
(
(Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme){
.tag = Prims_Cons,
.hd = {
.fst = "ECDSA+SHA384",
.snd = { .tag = Parsers_SignatureScheme_Ecdsa_secp384r1_sha384 }
},
.tl = buf59
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme
*buf61 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme));
buf61[0U]
=
(
(Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme){
.tag = Prims_Cons,
.hd = {
.fst = "ECDSA+SHA512",
.snd = { .tag = Parsers_SignatureScheme_Ecdsa_secp521r1_sha512 }
},
.tl = buf60
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme
*buf62 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme));
buf62[0U]
=
(
(Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme){
.tag = Prims_Cons,
.hd = {
.fst = "RSAPSS+SHA256",
.snd = { .tag = Parsers_SignatureScheme_Rsa_pss_rsae_sha512 }
},
.tl = buf61
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme
*buf63 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme));
buf63[0U]
=
(
(Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme){
.tag = Prims_Cons,
.hd = {
.fst = "RSAPSS+SHA384",
.snd = { .tag = Parsers_SignatureScheme_Rsa_pss_rsae_sha384 }
},
.tl = buf62
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme
*buf64 =
KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme));
buf64[0U]
=
(
(Prims_list__K___Prims_string_Parsers_SignatureScheme_signatureScheme){
.tag = Prims_Cons,
.hd = {
.fst = "RSAPSS+SHA512",
.snd = { .tag = Parsers_SignatureScheme_Rsa_pss_rsae_sha256 }
},
.tl = buf63
}
);
FFI_sas = buf64;
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup
*buf65 = KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup));
buf65[0U] = ((Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup){ .tag = Prims_Nil });
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup
*buf66 = KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup));
buf66[0U]
=
(
(Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup){
.tag = Prims_Cons,
.hd = { .fst = "FFDHE2048", .snd = { .tag = Parsers_NamedGroup_Ffdhe2048 } },
.tl = buf65
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup
*buf67 = KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup));
buf67[0U]
=
(
(Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup){
.tag = Prims_Cons,
.hd = { .fst = "FFDHE3072", .snd = { .tag = Parsers_NamedGroup_Ffdhe3072 } },
.tl = buf66
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup
*buf68 = KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup));
buf68[0U]
=
(
(Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup){
.tag = Prims_Cons,
.hd = { .fst = "FFDHE4096", .snd = { .tag = Parsers_NamedGroup_Ffdhe4096 } },
.tl = buf67
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup
*buf69 = KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup));
buf69[0U]
=
(
(Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup){
.tag = Prims_Cons,
.hd = { .fst = "X448", .snd = { .tag = Parsers_NamedGroup_X448 } },
.tl = buf68
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup
*buf70 = KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup));
buf70[0U]
=
(
(Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup){
.tag = Prims_Cons,
.hd = { .fst = "X25519", .snd = { .tag = Parsers_NamedGroup_X25519 } },
.tl = buf69
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup
*buf71 = KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup));
buf71[0U]
=
(
(Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup){
.tag = Prims_Cons,
.hd = { .fst = "P-256", .snd = { .tag = Parsers_NamedGroup_Secp256r1 } },
.tl = buf70
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup
*buf72 = KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup));
buf72[0U]
=
(
(Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup){
.tag = Prims_Cons,
.hd = { .fst = "P-384", .snd = { .tag = Parsers_NamedGroup_Secp384r1 } },
.tl = buf71
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup),
(uint32_t)1U);
Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup
*buf73 = KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup));
buf73[0U]
=
(
(Prims_list__K___Prims_string_Parsers_NamedGroup_namedGroup){
.tag = Prims_Cons,
.hd = { .fst = "P-521", .snd = { .tag = Parsers_NamedGroup_Secp521r1 } },
.tl = buf72
}
);
FFI_ngs = buf73;
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_EverCrypt_aead_alg), (uint32_t)1U);
Prims_list__K___Prims_string_EverCrypt_aead_alg
*buf74 = KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_EverCrypt_aead_alg));
buf74[0U] = ((Prims_list__K___Prims_string_EverCrypt_aead_alg){ .tag = Prims_Nil });
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_EverCrypt_aead_alg), (uint32_t)1U);
Prims_list__K___Prims_string_EverCrypt_aead_alg
*buf75 = KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_EverCrypt_aead_alg));
buf75[0U]
=
(
(Prims_list__K___Prims_string_EverCrypt_aead_alg){
.tag = Prims_Cons,
.hd = { .fst = "CHACHA20-POLY1305", .snd = EverCrypt_CHACHA20_POLY1305 },
.tl = buf74
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_EverCrypt_aead_alg), (uint32_t)1U);
Prims_list__K___Prims_string_EverCrypt_aead_alg
*buf76 = KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_EverCrypt_aead_alg));
buf76[0U]
=
(
(Prims_list__K___Prims_string_EverCrypt_aead_alg){
.tag = Prims_Cons,
.hd = { .fst = "AES256-GCM", .snd = EverCrypt_AES256_GCM },
.tl = buf75
}
);
KRML_CHECK_SIZE(sizeof (Prims_list__K___Prims_string_EverCrypt_aead_alg), (uint32_t)1U);
Prims_list__K___Prims_string_EverCrypt_aead_alg
*buf77 = KRML_HOST_MALLOC(sizeof (Prims_list__K___Prims_string_EverCrypt_aead_alg));
buf77[0U]
=
(
(Prims_list__K___Prims_string_EverCrypt_aead_alg){
.tag = Prims_Cons,
.hd = { .fst = "AES128-GCM", .snd = EverCrypt_AES128_GCM },
.tl = buf76
}
);
FFI_aeads = buf77;
}
| 67.773001 | 22,916 | 0.822456 | [
"model"
] |
3ff72d344b141b4a6f80f751a791ce0f099cf0bd | 786 | h | C | CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/java/awt/ItemSelectable.h | chewaiwai/huaweicloud-sdk-c-obs | fbcd3dadd910c22af3a91aeb73ca0fee94d759fb | [
"Apache-2.0"
] | 22 | 2019-06-13T01:16:44.000Z | 2022-03-29T02:42:39.000Z | CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/java/awt/ItemSelectable.h | chewaiwai/huaweicloud-sdk-c-obs | fbcd3dadd910c22af3a91aeb73ca0fee94d759fb | [
"Apache-2.0"
] | 26 | 2019-09-20T06:46:05.000Z | 2022-03-11T08:07:14.000Z | CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/java/awt/ItemSelectable.h | chewaiwai/huaweicloud-sdk-c-obs | fbcd3dadd910c22af3a91aeb73ca0fee94d759fb | [
"Apache-2.0"
] | 14 | 2019-07-15T06:42:39.000Z | 2022-02-15T10:32:28.000Z |
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*-
#ifndef __java_awt_ItemSelectable__
#define __java_awt_ItemSelectable__
#pragma interface
#include <java/lang/Object.h>
#include <gcj/array.h>
extern "Java"
{
namespace java
{
namespace awt
{
class ItemSelectable;
namespace event
{
class ItemListener;
}
}
}
}
class java::awt::ItemSelectable : public ::java::lang::Object
{
public:
virtual JArray< ::java::lang::Object * > * getSelectedObjects() = 0;
virtual void addItemListener(::java::awt::event::ItemListener *) = 0;
virtual void removeItemListener(::java::awt::event::ItemListener *) = 0;
static ::java::lang::Class class$;
} __attribute__ ((java_interface));
#endif // __java_awt_ItemSelectable__
| 20.684211 | 74 | 0.671756 | [
"object"
] |
3ffd4b8490cc2d0c480229ed1a92e2a61f008dc1 | 78,846 | c | C | src/SL_objects.c | sschaal2/SL | 9d05bbc9c323bccda12f28d75428851c3406a614 | [
"Apache-2.0"
] | 1 | 2020-04-20T15:32:18.000Z | 2020-04-20T15:32:18.000Z | src/SL_objects.c | sschaal2/SL | 9d05bbc9c323bccda12f28d75428851c3406a614 | [
"Apache-2.0"
] | null | null | null | src/SL_objects.c | sschaal2/SL | 9d05bbc9c323bccda12f28d75428851c3406a614 | [
"Apache-2.0"
] | null | null | null | /*!=============================================================================
==============================================================================
\ingroup SLcommon
\file SL_objects.c
\author
\date
==============================================================================
\remarks
handling of objects in SL
============================================================================*/
// SL general includes of system headers
#include "SL_system_headers.h"
/* private includes */
#include "SL.h"
#include "SL_objects.h"
#include "SL_terrains.h"
#include "SL_common.h"
#include "SL_kinematics.h"
#include "SL_simulation_servo.h"
#include "SL_shared_memory.h"
#include "SL_unix_common.h"
// defines
#define N_CSPECS_THREADS 8
// contact related defines
enum ForceConditions {
F_FULL=1, //!< admit forces in all directions
F_HALF, //!< admit forces only in half space
F_ORTH, //!< admit forces only perpindicular to a line
F_NULL, //!< place holder for not used
NFC
};
#define N_FORCE_CONDITIONS (NFC-1)
static char f_cond_names[][20]= {
{"dummy"},
{"full"},
{"half"},
{"orth"},
{"not_used"}
};
// global variables
ObjectPtr objs = NULL;
ContactPtr contacts=NULL;
SL_uext *ucontact;
int n_contacts;
// local variables
typedef struct {
int i;
ObjectPtr optr;
double x[N_CART+1];
} ContactSpecs;
////////////////////////////////////////////////////////
//////// locomotion SL /////////////////////////////////
#ifdef __XENO__
static int use_threads = FALSE;
#else
static int use_threads = TRUE;
#endif
//////// apollo 12.04 version //////////////////////////
//static int use_threads = TRUE;
////////////////////////////////////////////////////////
static pthread_t cspecs_thread[N_CSPECS_THREADS+1]; // threads for contact checking
static ContactSpecs *cspecs_data[N_CSPECS_THREADS+1]; // data used for thread communication
static sl_rt_cond cspecs_status[N_CSPECS_THREADS+1]; // conditional variable of thread
static sl_rt_mutex cspecs_mutex[N_CSPECS_THREADS+1]; // mutex of threads
static int n_cspecs_data[N_CSPECS_THREADS+1]; // counter of how much to do per thread
// global functions
// local functions
static void computeContactForces(ObjectPtr optr, ContactPtr cptr);
static void contactVelocity(int cID, ObjectPtr optr, double *v);
static void addObjectSync(char *name, int type, int contact, double *rgb, double *pos,
double *rot, double *scale, double *cparms, double *oparms);
static void deleteObjByNameSync(char *name);
static void changeHideObjByNameSync(char *name, int hide);
static void changeObjPosByNameSync(char *name, double *pos, double *rot);
static void convertGlobal2Object(ObjectPtr optr, double *xg, double *xl);
static void computeStart2EndNorm(double *xs, double *xe, ObjectPtr optr, double *n);
static void projectForce(ContactPtr cptr, ObjectPtr optr);
static void checkContactSpecifics(ContactSpecs cspecs);
static void *contactThread(void *num);
static void spawnContactSpecsThread(long num) ;
static void accumulateFinalForces(ContactPtr cptr);
// external functions
/*!*****************************************************************************
*******************************************************************************
\note initObjects
\date Nov 2007
\remarks
initializes object related variables
*******************************************************************************
Function Parameters: [in]=input,[out]=output
none
******************************************************************************/
int
initObjects(void)
{
int i,n;
// check how may contact points we need
n=count_extra_contact_points(config_files[CONTACTS]);
// contacts
contacts = my_calloc(n_links+1+n,sizeof(Contact),MY_STOP);
ucontact = my_calloc(n_dofs+1,sizeof(SL_uext),MY_STOP);
// initalize objects in the environment
readObjects(config_files[OBJECTS]);
n_contacts = n+n_links;
// allocate thread related data
for (i=1; i<=N_CSPECS_THREADS; ++i)
cspecs_data[i]=my_calloc(n_contacts+1,sizeof(ContactSpecs),MY_STOP);
// start contact threads
if (strcmp(servo_name,"sim")==0 && use_threads) {
for (n=1; n<=N_CSPECS_THREADS; ++n) {
sl_rt_mutex_init(&(cspecs_mutex[n]));
sl_rt_cond_init(&(cspecs_status[n]));
spawnContactSpecsThread(n);
}
}
return TRUE;
}
/*!*****************************************************************************
*******************************************************************************
\note addObject
\date Nov 2000
\remarks
add an object to the environment
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] name : name of the object
\param[in] type : object type
\param[in] contact : contact type
\param[in] rgb : rgb values for color
\param[in] trans : translatory offset
\param[in] rot : rotary offset
\param[in] scale : scaling of object
\param[in] cspecs : contact specifications (0-th element has #parm)
\param[in] ospecs : object specifications (0-th element has #parm)
******************************************************************************/
ObjectPtr
addObject(char *name, int type, int contact, double *rgb, double *trans, double *rot,
double *scale, Vector cspecs, Vector ospecs)
{
int i;
ObjectPtr ptr=NULL;
ObjectPtr last_ptr=NULL;
char string[1000];
int n_cps=0, n_ops=0;
int new_obj_flag = TRUE;
/* is object already present and only needs update? */
if (objs != NULL) {
ptr = objs;
do {
if (strcmp(ptr->name,name)==0) {
new_obj_flag = FALSE;
break;
}
last_ptr = ptr;
ptr = (ObjectPtr) ptr->nptr;
} while ( ptr != NULL);
}
if (new_obj_flag) {
/* allocate new object */
ptr = my_calloc(1,sizeof(Object),MY_STOP);
}
if (cspecs == NULL) {
n_cps = 0;
} else {
n_cps = cspecs[0];
if (n_cps > 0 && new_obj_flag)
ptr->contact_parms = my_vector(1,n_cps);
}
if (ospecs == NULL) {
n_ops = 0;
} else {
n_ops = ospecs[0];
if (n_ops > 0 && new_obj_flag)
ptr->object_parms = my_vector(1,n_ops);
}
/* assign values */
strcpy(ptr->name, name);
ptr->type = type;
ptr->display_list_active = FALSE;
ptr->hide = FALSE;
ptr->contact_model = contact;
for (i=1; i<=N_CART; ++i) {
ptr->rgb[i] = rgb[i];
ptr->trans[i] = trans[i];
ptr->rot[i] = rot[i];
ptr->scale[i] = scale[i];
}
for (i=1; i<=n_ops; ++i) {
ptr->object_parms[i]=ospecs[i];
}
for (i=1; i<=n_cps; ++i) {
ptr->contact_parms[i]=cspecs[i];
}
if (new_obj_flag) {
ptr->nptr=NULL;
if (objs == NULL) {
objs = ptr;
} else {
last_ptr->nptr = (char *) ptr;
}
}
if (strcmp(servo_name,"task")==0) // communicate info to other servos
addObjectSync(name, type, contact, rgb, trans, rot, scale, cspecs, ospecs);
return ptr;
}
/*!*****************************************************************************
*******************************************************************************
\note addCube
\date Nov 2000
\remarks
add a cube to the object list
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] name : name of the object
\param[in] rgb : rgb values for color
\param[in] pos : pointer to position vector
\param[in] rot : pointer to rotation vector
\param[in] scale : pointer to rotation vector
\param[in] contact : ID of contact model
\param[in] parms : array of contact parameters
******************************************************************************/
ObjectPtr
addCube(char *name, double *rgb, double *pos, double *rot,
double *scale, int contact,
double *parms)
{
return (addObject(name,CUBE,contact,rgb,pos,rot,scale,parms,NULL));
}
/*!*****************************************************************************
*******************************************************************************
\note addSphere
\date Nov 2000
\remarks
add a sphere to the object list
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] name : name of the object
\param[in] rgb : rgb values for color
\param[in] pos : pointer to position vector
\param[in] rot : pointer to rotation vector
\param[in] scale : pointer to rotation vector
\param[in] contact : ID of contact model
\param[in] parms : array of contact parameters
\param[in] n_faces : number of faces
******************************************************************************/
ObjectPtr
addSphere(char *name, double *rgb, double *pos, double *rot,
double *scale, int contact,
Vector parms, int n_faces)
{
double ospecs[1+1];
ospecs[0]=1;
ospecs[1]=n_faces;
return (addObject(name,SPHERE,contact,rgb,pos,rot,scale,parms,ospecs));
}
/*!*****************************************************************************
*******************************************************************************
\note addCylinder
\date Nov 2000
\remarks
Add a cylinder to the object list. The axis of the cylinder is aligned
with the local z axis
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] name : name of the object
\param[in] rgb : rgb values for color
\param[in] pos : pointer to position vector
\param[in] rot : pointer to rotation vector
\param[in] scale : pointer to scale vector
\param[in] contact : ID of contact model
\param[in] parms : array of contact parameters
\param[in] n_faces : number of faces
******************************************************************************/
ObjectPtr
addCylinder(char *name, double *rgb, double *pos, double *rot,
double *scale, int contact,
Vector parms, int n_faces)
{
double ospecs[1+1];
ospecs[0]=1;
ospecs[1]=n_faces;
return (addObject(name,CYLINDER,contact,rgb,pos,rot,scale,parms,ospecs));
}
/*!*****************************************************************************
*******************************************************************************
\note changeObjPosByName
\date Nov 2000
\remarks
changes the object position by name (slower, since search is required)
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] name : name of the object
\param[in] pos : pointer to position vector
\param[in] rot : pointer to rotation vector
******************************************************************************/
int
changeObjPosByName(char *name, double *pos, double *rot)
{
ObjectPtr ptr = getObjPtrByName(name);
if (ptr == NULL)
return FALSE;
changeObjPosByPtr(ptr, pos, rot);
if (strcmp(servo_name,"task")==0) // communicate info to other servos
changeObjPosByNameSync(name, pos, rot);
return TRUE;
}
/*!*****************************************************************************
*******************************************************************************
\note changeHideObjByName
\date Nov 2000
\remarks
changes the hide status of object by name
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] name : name of the object
\param[in] hide : TRUE/FALSE
******************************************************************************/
int
changeHideObjByName(char *name, int hide)
{
ObjectPtr ptr;
int i;
if (objs == NULL)
return FALSE;
ptr = objs;
do {
if (strcmp(name,ptr->name)==0) {
ptr->hide = hide;
if (strcmp(servo_name,"task")==0) // communicate info to other servos
changeHideObjByNameSync(name, hide);
return TRUE;
}
ptr = (ObjectPtr) ptr->nptr;
} while (ptr != NULL);
return FALSE;
}
/*!*****************************************************************************
*******************************************************************************
\note getObjForcesByName
\date June 2007
\remarks
returns the force and torque vector acting on an object
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] name : name of the object
\param[in] f : pointer to force vector
\param[in] t : pointer to torque vector
******************************************************************************/
int
getObjForcesByName(char *name, double *f, double *t)
{
ObjectPtr ptr;
int i;
if (objs == NULL)
return FALSE;
ptr = objs;
do {
if (strcmp(name,ptr->name)==0) {
for (i=1;i<=N_CART; ++i) {
f[i] = ptr->f[i];
t[i] = ptr->t[i];
}
return TRUE;
}
ptr = (ObjectPtr) ptr->nptr;
} while (ptr != NULL);
return FALSE;
}
/*!*****************************************************************************
*******************************************************************************
\note getObjForcesByPtr
\date June 2007
\remarks
returns the force and torque vector acting on an object
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] ptr : pointer to object
\param[in] f : pointer to force vector
\param[in] t : pointer to torque vector
******************************************************************************/
int
getObjForcesByPtr(ObjectPtr ptr, double *f, double *t)
{
int i;
for (i=1;i<=N_CART; ++i) {
f[i] = ptr->f[i];
t[i] = ptr->t[i];
}
return TRUE;
}
/*!*****************************************************************************
*******************************************************************************
\note getObjPtrByName
\date Nov 2000
\remarks
returns the pointer to a specific object
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] name : name of the object
******************************************************************************/
ObjectPtr
getObjPtrByName(char *name)
{
ObjectPtr ptr;
int i;
if (objs == NULL)
return NULL;
ptr = objs;
do {
if (strcmp(name,ptr->name)==0) {
return ptr;
}
ptr = (ObjectPtr) ptr->nptr;
} while (ptr != NULL);
return NULL;
}
/*!*****************************************************************************
*******************************************************************************
\note changeObjPosByPtr
\date Nov 2000
\remarks
changes the object position by pointer
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] ptr : ptr of the object
\param[in] pos : pointer to position vector
\param[in] rot : pointer to rotation vector
******************************************************************************/
void
changeObjPosByPtr(ObjectPtr ptr, double *pos, double *rot)
{
int i;
for (i=1;i<=N_CART; ++i) {
ptr->trans[i]=pos[i];
ptr->rot[i]=rot[i];
}
if (strcmp(servo_name,"task")==0) // communicate info to other servos
changeObjPosByNameSync(ptr->name, pos, rot);
}
/*!*****************************************************************************
*******************************************************************************
\note deleteObjByName
\date Nov 2000
\remarks
deletes an object by name
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] name : name of the object
******************************************************************************/
int
deleteObjByName(char *name)
{
ObjectPtr ptr,ptr2;
char *nptr;
int i;
if (objs == NULL)
return FALSE;
ptr = objs;
do {
if (strcmp(name,ptr->name)==0) {
ptr2=objs;
if (ptr2 == ptr) {
objs = (ObjectPtr) ptr->nptr;
} else {
do {
if (ptr2->nptr == (char *)ptr) {
ptr2->nptr = ptr->nptr;
break;
}
ptr2 = (ObjectPtr) ptr2->nptr;
} while (ptr2 != NULL);
}
free(ptr);
return TRUE;
}
ptr = (ObjectPtr) ptr->nptr;
} while (ptr != NULL);
if (strcmp(servo_name,"task")==0) // communicate info to other servos
deleteObjByName(name);
return FALSE;
}
/*!*****************************************************************************
*******************************************************************************
\note checkContacts
\date June 1999
\remarks
checks for contacts and computes the contact forces
*******************************************************************************
Function Parameters: [in]=input,[out]=output
none
******************************************************************************/
void
checkContacts(void)
{
int i,j;
ObjectPtr optr;
double x[N_CART+1];
double aux,aux1,aux2;
int ind=0;
int first_contact_flag = FALSE;
int contact_flag = FALSE;
double z;
double n[N_CART+1];
double v[N_CART+1];
char tfname[100];
double no_go;
double dist_z;
ContactSpecs cspecs;
int count_thread=0;
int n_threads_used = N_CSPECS_THREADS;
int threads_ready_flag;
/* zero contact forces */
bzero((void *)ucontact,sizeof(SL_uext)*(n_dofs+1));
bzero((void *)&cspecs,sizeof(ContactSpecs));
/* if there are no objects, exit */
if (objs==NULL)
return;
// zero all object forces and torques
optr = objs;
do {
for (i=1; i<=N_CART; ++i)
optr->f[i] = optr->t[i] = 0.0;
optr = (ObjectPtr) optr->nptr;
} while (optr != NULL);
// zero thread counters
for (i=1; i<=N_CSPECS_THREADS; ++i)
n_cspecs_data[i] = 0;
for (i=0; i<=n_contacts; ++i) { /* loop over all contact points */
if (!contacts[i].active)
continue;
first_contact_flag = FALSE;
contact_flag = FALSE;
optr = objs;
do { /* check all objects */
/* check whether this is a contact */
if (optr->contact_model == NO_CONTACT || optr->hide) {
optr = (ObjectPtr) optr->nptr;
continue;
}
/* step one: transform potential contact point into object
coordinates */
// compute the current contact point
computeContactPoint(&(contacts[i]),link_pos_sim,Alink_sim,x);
// convert to local coordinates
for (j=1; j<=N_CART; ++j)
x[j] -= optr->trans[j];
// rotate the contact point into object centered coordinates
convertGlobal2Object(optr, x, x);
// is this point inside the object?
switch (optr->type) {
case CUBE: //---------------------------------------------------------------
if (fabs(x[1]) < optr->scale[1]/2. &&
fabs(x[2]) < optr->scale[2]/2. &&
fabs(x[3]) < optr->scale[3]/2.) {
cspecs.i = i;
cspecs.optr = optr;
for (j=1; j<=N_CART; ++j)
cspecs.x[j] = x[j];
if (use_threads) {
if (++count_thread > n_threads_used)
count_thread = 1;
cspecs_data[count_thread][++n_cspecs_data[count_thread]] = cspecs;
} else {
checkContactSpecifics(cspecs);
}
contact_flag = TRUE;
optr = NULL;
continue; /* only one object can be in contact with a contact point */
}
break;
case SPHERE: //---------------------------------------------------------------
if ((sqr(x[1]/optr->scale[1]*2.) + sqr(x[2]/optr->scale[2]*2.) +
sqr(x[3]/optr->scale[3]*2.)) < 1.0) {
cspecs.i = i;
cspecs.optr = optr;
for (j=1; j<=N_CART; ++j)
cspecs.x[j] = x[j];
if (use_threads) {
if (++count_thread > n_threads_used)
count_thread = 1;
cspecs_data[count_thread][++n_cspecs_data[count_thread]] = cspecs;
} else {
checkContactSpecifics(cspecs);
}
contact_flag = TRUE;
optr=NULL;
continue; /* only one object can be in contact with a contact point */
}
break;
case CYLINDER: //---------------------------------------------------------------
// the cylinder axis is aliged with te Z axis
if ((sqr(x[1]/optr->scale[1]*2.) + sqr(x[2]/optr->scale[2]*2.)) < 1.0 &&
fabs(x[3]) < optr->scale[3]/2.) {
cspecs.i = i;
cspecs.optr = optr;
for (j=1; j<=N_CART; ++j)
cspecs.x[j] = x[j];
if (use_threads) {
if (++count_thread > n_threads_used)
count_thread = 1;
cspecs_data[count_thread][++n_cspecs_data[count_thread]] = cspecs;
} else {
checkContactSpecifics(cspecs);
}
contact_flag = TRUE;
optr=NULL;
continue; /* only one object can be in contact with a contact point */
}
break;
case TERRAIN: //---------------------------------------------------------------
if (!getContactTerrainInfo(x[1], x[2], optr->name, &z, n, &no_go))
break;
if (x[3] < z) {
cspecs.i = i;
cspecs.optr = optr;
for (j=1; j<=N_CART; ++j)
cspecs.x[j] = x[j];
if (use_threads) {
if (++count_thread > n_threads_used)
count_thread = 1;
cspecs_data[count_thread][++n_cspecs_data[count_thread]] = cspecs;
} else {
checkContactSpecifics(cspecs);
}
contact_flag = TRUE;
optr = NULL;
continue; /* only one object can be in contact with a contact point */
}
break;
}
optr = (ObjectPtr) optr->nptr;
} while (optr != NULL);
if (!contact_flag) { // this is just for easy data interpretation
for (j=1; j<=N_CART; ++j) {
contacts[i].normal[j] = 0.0;
contacts[i].normvel[j] = 0.0;
contacts[i].tangent[j] = 0.0;
contacts[i].tanvel[j] = 0.0;
contacts[i].viscvel[j] = 0.0;
contacts[i].f[j] = 0.0;
contacts[i].n[j] = 0.0;
contacts[i].status = FALSE;
}
}
}
if (use_threads) {
// start all the threads
for (i=1; i<=n_threads_used; ++i) {
//printf("start thread %d with %d items\n",i,n_cspecs_data[i]);
if (n_cspecs_data[i] > 0)
sl_rt_cond_signal(&(cspecs_status[i]));
}
// check for thread completion
threads_ready_flag = FALSE;
while (!threads_ready_flag) {
threads_ready_flag = TRUE;
for (i=1; i<=n_threads_used; ++i) {
sl_rt_mutex_lock(&(cspecs_mutex[i]));
if (n_cspecs_data[i] != 0)
threads_ready_flag = FALSE;
sl_rt_mutex_unlock(&(cspecs_mutex[i]));
}
}
}
// accumulate forces in global structures
for (i=0; i<=n_contacts; ++i) { /* loop over all contact points */
if (!contacts[i].status)
continue;
accumulateFinalForces(&(contacts[i]));
}
/* add simulated external forces to contact forces */
for (i=0; i<=n_dofs; ++i)
for (j=_X_; j<=_Z_; ++j) {
ucontact[i].f[j] += uext_sim[i].f[j];
ucontact[i].t[j] += uext_sim[i].t[j];
}
}
/*!*****************************************************************************
*******************************************************************************
\note computeStart2EndNorm
\date Aug 2010
\remarks
computes the norm vector from start to end point of line in object centered
coordinates
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] xs : start point of line (global coordinates)
\param[in] xe : end point of line (global coordinates)
\param[in] optr: point to object
\param[out] n : norm vector from start to end
note: xl and xg can be the same pointers
******************************************************************************/
static void
computeStart2EndNorm(double *xs, double *xe, ObjectPtr optr, double *n)
{
int i,j;
double x[N_CART+1];
double aux = 0;
// difference vector pointing from start to end
for (i=1; i<=N_CART; ++i) {
x[i] = xe[i] - xs[i];
aux += sqr(x[i]);
}
aux = sqrt(aux);
// normalize
for (i=1; i<=N_CART; ++i)
x[i] /= (aux + 1.e-10);
// convert to local coordinates
convertGlobal2Object(optr, x, n);
}
/*!*****************************************************************************
*******************************************************************************
\note convertGlobal2Object
\date Aug 2010
\remarks
rotates global coordinates to object coordinates (no translation). This uses
Euler angle notation x-y-z rotations
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] optr: point to object
\param[in] xg : vector in global coordinates
\param[out] xl : vector in local coordinates
note: xl and xg can be the same pointers
******************************************************************************/
static void
convertGlobal2Object(ObjectPtr optr, double *xg, double *xl)
{
int i;
double aux;
for (i=1; i<=N_CART; ++i)
xl[i] = xg[i];
// the link point in object centered coordinates
if (optr->rot[1] != 0.0) {
aux = xl[2]*cos(optr->rot[1])+xl[3]*sin(optr->rot[1]);
xl[3] = -xl[2]*sin(optr->rot[1])+xl[3]*cos(optr->rot[1]);
xl[2] = aux;
}
if (optr->rot[2] != 0.0) {
aux = xl[1]*cos(optr->rot[2])-xl[3]*sin(optr->rot[2]);
xl[3] = xl[1]*sin(optr->rot[2])+xl[3]*cos(optr->rot[2]);
xl[1] = aux;
}
if (optr->rot[3] != 0.0) {
aux = xl[1]*cos(optr->rot[3])+xl[2]*sin(optr->rot[3]);
xl[2] = -xl[1]*sin(optr->rot[3])+xl[2]*cos(optr->rot[3]);
xl[1] = aux;
}
}
/*!*****************************************************************************
*******************************************************************************
\note projectForce
\date Aug 2010
\remarks
projects a force vector onto the space that is defined by the information in
the contact structure. Note that contact points coinciding with links are
processed differently than contact points that interpolate between links.
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in,out] cptr : pointer to contact structure
\param[in] optr : pointer to object structure
returns cptr->f adjusted according to the projection information
******************************************************************************/
static void
projectForce(ContactPtr cptr, ObjectPtr optr)
{
int i,j;
double aux;
double nv[N_CART+1];
double sf[N_CART+1];
double nnv[N_CART+1];
/***********************************************************************************************/
if (cptr->n_connected_links == 0) { // this is a interpolated contact point or a special contact point
if (cptr->point_contact_flag) { // for special contact points
double xs[N_CART+1];
double xe[N_CART+1];
for (i=1; i<=N_CART; ++i) {
xs[i] = Alink_sim[cptr->id_start][i][4];
xe[i] = Alink_sim[cptr->id_start][i][4];
for (j=1; j<=N_CART; ++j) {
xs[i] += Alink_sim[cptr->id_start][i][j]*cptr->local_point_pos[j];
xe[i] += Alink_sim[cptr->id_start][i][j]*(cptr->local_point_pos[j]+cptr->local_point_norm[j]);
}
}
// compute norm vector from start to end of line
computeStart2EndNorm(xs,xe,optr,nv);
// act according to contact condition, stored in force_condition[1] for point_contacts
switch (cptr->force_condition[1]) {
case F_FULL: // no projection needed
break;
case F_HALF: // project away forces pointing in the same direction of norm
// inner product norm with contact force
aux = 0.0;
for (j=1; j<=N_CART; ++j)
aux += cptr->f[j]*nv[j];
if (aux < 0)
aux = 0;
// subtract this component out
for (j=1; j<=N_CART; ++j)
cptr->f[j] -= aux * nv[j];
break;
case F_ORTH: // only allow force components orthogonal to norm
// inner product norm with contact force
aux = 0.0;
for (j=1; j<=N_CART; ++j)
aux += cptr->f[j]*nv[j];
// subtract this component out
for (j=1; j<=N_CART; ++j)
cptr->f[j] -= aux * nv[j];
break;
default:
printf("Unknown force condition\n");
} // switch(cptr->force_condition)
} else { // for interpolated line contact points
// compute norm vector from start to end of line
computeStart2EndNorm(link_pos_sim[cptr->id_start],
link_pos_sim[cptr->id_end],
optr,nv);
// inner product norm with contact force
aux = 0.0;
for (j=1; j<=N_CART; ++j)
aux += cptr->f[j]*nv[j];
// subtract this component out
for (j=1; j<=N_CART; ++j)
cptr->f[j] -= aux * nv[j];
}
/***********************************************************************************************/
} else { // this is a contact point coinciding with a link point
// loop over all connected links, and compute average contact force
// from all projections
for (j=1; j<=N_CART; ++j)
sf[j] = 0.0;
for (i=1; i<=cptr->n_connected_links; ++i) {
switch (cptr->force_condition[i]) {
case F_FULL: // no projection needed
for (j=1; j<=N_CART; ++j)
sf[j] += cptr->f[j];
break;
case F_HALF: // project away force aligned with line, pointing out of line
// compute norm vector from start to end of line
computeStart2EndNorm(link_pos_sim[cptr->connected_links[i]],
link_pos_sim[cptr->id_start],
optr,nv);
// inner product norm with contact force
aux = 0.0;
for (j=1; j<=N_CART; ++j)
aux += cptr->f[j]*nv[j];
if (aux < 0)
aux = 0;
// subtract this component out
for (j=1; j<=N_CART; ++j)
sf[j] += cptr->f[j] - aux * nv[j];
break;
case F_ORTH: // only allow force components orthogonal to line
// compute norm vector from start to end of line
computeStart2EndNorm(link_pos_sim[cptr->connected_links[i]],
link_pos_sim[cptr->id_start],
optr,nv);
// inner product norm with contact force
aux = 0.0;
for (j=1; j<=N_CART; ++j)
aux += cptr->f[j]*nv[j];
// subtract this component out
for (j=1; j<=N_CART; ++j)
sf[j] += cptr->f[j] - aux * nv[j];
break;
default:
printf("Unknown force condition\n");
} // switch(cptr->force_condition)
} // for (i=1; i<=cptr->n_connected_links; ++i)
// compute average of accumulated force
for (j=1; j<=N_CART; ++j)
cptr->f[j] = sf[j]/(double)(cptr->n_connected_links);
}
}
/*!*****************************************************************************
*******************************************************************************
\note readObjects
\date June 2006
\remarks
Parses an arbitrary objects file. Objects are defined by multiple lines, given
as in the following example:
floor 1 ( name and ID of object type )
1.0 0.0 0.0 ( rgb color specification)
0.0 0.0 -1.65 ( 3D position of center of object )
0.0 0.0 0.0 ( x-y-z Euler angle orientation )
40.0 40.0 1.0 ( scale applied to x, y, z of object)
2 ( contact model: see computeContactForces() below )
10 ( object parameters: see SL_openGL.c: drawObjects() )
1000 30 1000 30 0.5 0.4 ( contact parameters: see computeContactForces() below )
The number of object parameters and contact parameters can vary for
different objects and different contact models. The parsing of these
parameters is pretty rudimentary, and simply all lines are expected in
the correct sequence, and the "new-line" character is interpreted as the
end of line indicator.
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] cfname : file name of objects file
******************************************************************************/
void
readObjects(char *cfname)
{
int j, i, ID;
FILE *in;
double dum;
double rgb[N_CART+1];
double pos[N_CART+1];
double rot[N_CART+1];
double scale[N_CART+1];
int contact;
int objtype;
char name[100];
char fname[100];
char name2[200];
double oparms[MAX_OBJ_PARMS+1];
double cparms[MAX_CONTACT_PARMS+1];
double display_grid_delta;
ObjectPtr optr;
double x,y,z;
double n[N_CART+1];
char string[STRING100];
static int objects_read = FALSE;
if (objects_read)
printf("Re-initializing objects from file >%s%s<\n",CONFIG,cfname);
sprintf(string,"%s%s",CONFIG,cfname);
in = fopen_strip(string);
if (in == NULL) {
printf("ERROR: Cannot open file >%s<!\n",string);
return;
}
/* find objects in file */
while (fscanf(in,"%s %d %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %d",
name,&objtype,&rgb[1],&rgb[2],&rgb[3],
&pos[1],&pos[2],&pos[3],&rot[1],&rot[2],&rot[3],
&scale[1],&scale[2],&scale[3],&contact) == 15) {
while (fgetc(in) != '\n')
;
i=0;
while ((string[i++]=fgetc(in))!= '\n' && i<499 )
;
string[i]='\0';
i=sscanf(string,"%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf ",
&oparms[1],&oparms[2],&oparms[3],&oparms[4],&oparms[5],
&oparms[6],&oparms[7],&oparms[8],&oparms[9],&oparms[10],
&oparms[11],&oparms[12],&oparms[13],&oparms[14],&oparms[15],
&oparms[16],&oparms[17],&oparms[18],&oparms[19],&oparms[20],
&oparms[21],&oparms[22],&oparms[23],&oparms[24],&oparms[25],
&oparms[26],&oparms[27],&oparms[28],&oparms[29],&oparms[30]);
oparms[0] = i;
i=0;
while ((string[i++]=fgetc(in)) != '\n' && i<499)
;
string[i]='\0';
i=sscanf(string,"%lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf ",
&cparms[1],&cparms[2],&cparms[3],&cparms[4],&cparms[5],
&cparms[6],&cparms[7],&cparms[8],&cparms[9],&cparms[10],
&cparms[11],&cparms[12],&cparms[13],&cparms[14],&cparms[15],
&cparms[16],&cparms[17],&cparms[18],&cparms[19],&cparms[20],
&cparms[21],&cparms[22],&cparms[23],&cparms[24],&cparms[25],
&cparms[26],&cparms[27],&cparms[28],&cparms[29],&cparms[30]);
cparms[0] = i;
if (objtype == TERRAIN) { // terrains use .asc names
sprintf(name2,"%s.asc",name);
strcpy(name,name2);
}
optr = addObject(name,objtype,contact,rgb,pos,rot,scale,cparms,oparms);
/* if there is a floor, initialize the gound level for the terrains */
if (strcmp("floor",name) == 0) {
setTerrainGroundZ(optr->trans[_Z_] + 0.5*optr->scale[_Z_]);
printf("\nFound object >floor< and intialized ground level to %f\n",
optr->trans[_Z_] + 0.5*optr->scale[_Z_]);
}
// for terrains we need to add the terrain and create a display list for this terrain
if (objtype == TERRAIN) {
if ((ID=getNextTerrainID())) {
SL_quat q;
eulerToQuat(rot,&q);
// Note: oparms[1] = reg_rad oparms[2]=reg_down oparms[3]=reg_crad oparms[4]=disp_grid_delta
setTerrainInfo(ID,ID,name,pos,q.q,
(int)rint(oparms[1]),(int)rint(oparms[2]),(int)rint(oparms[3]));
} else {
printf("No more terrains possible -- increase MAX_TERRAINS\n");
}
}
}
fclose(in);
remove_temp_file();
objects_read = TRUE;
}
/*!*****************************************************************************
*******************************************************************************
\note computeContactForces
\date Dec.2000
\remarks
for a given contact point and object, compute the contact forces
and add them to the appropriate structure
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] optr : ptr to object
\param[in] ctpr : ptr to contact point
******************************************************************************/
static void
computeContactForces(ObjectPtr optr, ContactPtr cptr)
{
int i,j;
double aux;
double temp[N_CART+1];
double temp1[N_CART+1];
double temp2[N_CART+1];
double moment_arm[N_CART+1];
double moment_arm_object[N_CART+1];
double normal_force;
double normal_velocity;
double tangent_force;
double tangent_velocity;
double viscvel;
int option=0;
/* compute the contact forces in object centered coordinates */
switch (optr->contact_model) {
case DAMPED_SPRING_STATIC_FRICTION:
/* note: the contact_parms arrays has the following elements:
contact_parms[1] = normal spring coefficient
contact_parms[2] = normal damping coefficient
contact_parms[3] = static friction spring coefficient
contact_parms[4] = static friction damping spring coefficient
contact_parms[5] = static friction coefficient (friction cone)
contact_parms[6] = dynamic friction coefficient (proportional to normal force)
*/
// the normal contact force in object centered coordinates
normal_force = 0;
for (i=1; i<=N_CART; ++i) {
cptr->f[i] = optr->contact_parms[1] * cptr->normal[i] +
optr->contact_parms[2] * cptr->normvel[i];
// make sure the damping part does not attract a contact force with wrong sign
if (macro_sign(cptr->f[i])*macro_sign(cptr->normal[i])<0)
cptr->f[i] = 0.0;
normal_force += sqr(cptr->f[i]);
}
normal_force = sqrt(normal_force);
// project the spring force according to the information in the contact and object structures
projectForce(cptr,optr);
// the force due to static friction, modeled as horizontal damper, again
// in object centered coordinates
tangent_force = 0;
viscvel = 1.e-10;
for (i=1; i<=N_CART; ++i) {
temp[i] = -optr->contact_parms[3] * cptr->tangent[i] -
optr->contact_parms[4]*cptr->tanvel[i];
tangent_force += sqr(temp[i]);
viscvel += sqr(cptr->viscvel[i]);
}
tangent_force = sqrt(tangent_force);
viscvel = sqrt(viscvel);
/* If static friction too large -> spring breaks -> dynamic friction in
the direction of the viscvel vector; we also reset the x_start
vector such that static friction would be triggered appropriately,
i.e., when the viscvel becomes zero */
if (tangent_force > optr->contact_parms[5] * normal_force || cptr->friction_flag) {
cptr->friction_flag = TRUE;
for (i=1; i<=N_CART; ++i) {
cptr->f[i] += -optr->contact_parms[6] * normal_force * cptr->viscvel[i]/viscvel;
if (viscvel < 0.01) {
cptr->friction_flag = FALSE;
cptr->x_start[i] = cptr->x[i];
}
}
} else {
for (i=1; i<=N_CART; ++i) {
cptr->f[i] += temp[i];
}
}
break;
case DAMPED_SPRING_VISCOUS_FRICTION:
/* note: the contact_parms arrays has the following elements:
contact_parms[1] = normal spring coefficient
contact_parms[2] = normal damping coefficient
contact_parms[3] = viscous friction coefficient
*/
/* normal contact force */
for (i=1; i<=N_CART; ++i) {
cptr->f[i] = optr->contact_parms[1] * cptr->normal[i] +
optr->contact_parms[2] * cptr->normvel[i];
// make sure the damping part does not attract a contact force with wrong sign
if (macro_sign(cptr->f[i])*macro_sign(cptr->normal[i])<0)
cptr->f[i] = 0.0;
}
// project the spring force according to the information in the contact and object structures
projectForce(cptr,optr);
/* the force due to viscous friction */
for (i=1; i<=N_CART; ++i) {
cptr->f[i] += -optr->contact_parms[3] * cptr->viscvel[i];
}
break;
case DAMPED_SPRING_LIMITED_REBOUND:
/* note: the contact_parms arrays has the following elements:
contact_parms[1] = normal spring coefficient
contact_parms[2] = normal damping coefficient
contact_parms[3] = static friction spring coefficient
contact_parms[4] = static friction damping spring coefficient
contact_parms[5] = static friction coefficient (friction cone)
contact_parms[6] = dynamic friction coefficient (proportional to normal force)
contact_parms[7] = normal max rebound velocity
contact_parms[8] = static friction max rebound velocity
*/
// the normal contact force in object centered coordinates
normal_velocity = 0.0;
aux = 0;
for (i=1; i<=N_CART; ++i) {
temp1[i] = optr->contact_parms[1] * cptr->normal[i];
temp2[i] = optr->contact_parms[2] * cptr->normvel[i];
normal_velocity += sqr(cptr->normvel[i]);
aux += cptr->normvel[i]*cptr->normal[i];
}
normal_velocity = -sqrt(normal_velocity)*macro_sign(aux);
aux = 1.0-normal_velocity/optr->contact_parms[7];
if (aux < 0)
aux = 0.0;
normal_force = 0;
for (i=1; i<=N_CART; ++i) {
cptr->f[i] = temp1[i]*aux + temp2[i]*sqrt(aux);
// make sure the damping part does not attract a contact force with wrong sign
if (macro_sign(cptr->f[i])*macro_sign(cptr->normal[i])<0)
cptr->f[i] = 0.0;
normal_force += sqr(cptr->f[i]);
}
normal_force = sqrt(normal_force);
// project the spring force according to the information in the contact and object structures
projectForce(cptr,optr);
// the force due to static friction, modeled as horizontal damper, again
// in object centered coordinates
tangent_force = 0;
tangent_velocity = 0;
viscvel = 1.e-10;
aux = 0;
for (i=1; i<=N_CART; ++i) {
temp1[i] = -optr->contact_parms[3] * cptr->tangent[i];
temp2[i] = -optr->contact_parms[4]*cptr->tanvel[i];
tangent_velocity += sqr(cptr->tanvel[i]);
viscvel += sqr(cptr->viscvel[i]);
aux += (cptr->x[i]-cptr->x_start[i])*cptr->tanvel[i];
}
tangent_velocity = -sqrt(tangent_velocity)*macro_sign(aux);
viscvel = sqrt(viscvel);
aux = 1.0-tangent_velocity/optr->contact_parms[8];
if (aux < 0)
aux = 0.0;
tangent_force = 0.0;
for (i=1; i<=N_CART; ++i) {
temp[i] = temp1[i]*aux + temp2[i]*sqrt(aux);
tangent_force += sqr(temp[i]);
}
tangent_force = sqrt(tangent_force);
/* If static friction too large -> spring breaks -> dynamic friction in
the direction of the viscvel vector; we also reset the x_start
vector such that static friction would be triggered appropriately,
i.e., when the viscvel becomes zero */
if (tangent_force > optr->contact_parms[5] * normal_force || cptr->friction_flag) {
cptr->friction_flag = TRUE;
for (i=1; i<=N_CART; ++i) {
cptr->f[i] += -optr->contact_parms[6] * normal_force * cptr->viscvel[i]/viscvel;
if (viscvel < 0.01) {
cptr->friction_flag = FALSE;
cptr->x_start[i] = cptr->x[i];
}
}
} else {
for (i=1; i<=N_CART; ++i) {
cptr->f[i] += temp[i];
}
}
break;
default:
break;
}
/* convert the object centered forces and normals into global coordinates */
// assign the normal
aux = 0.0;
for (i=1; i<=N_CART; ++i) {
cptr->n[i] = cptr->normal[i];
aux += sqr(cptr->n[i]);
}
aux = sqrt(aux);
for (i=1; i<=N_CART; ++i)
cptr->n[i] /= aux;
if (optr->rot[_G_] != 0.0) {
aux = cptr->f[_X_]*cos(optr->rot[_G_])-cptr->f[_Y_]*sin(optr->rot[_G_]);
cptr->f[_Y_] = cptr->f[_X_]*sin(optr->rot[_G_])+cptr->f[_Y_]*cos(optr->rot[_G_]);
cptr->f[_X_] = aux;
aux = cptr->n[_X_]*cos(optr->rot[_G_])-cptr->n[_Y_]*sin(optr->rot[_G_]);
cptr->n[_Y_] = cptr->n[_X_]*sin(optr->rot[_G_])+cptr->n[_Y_]*cos(optr->rot[_G_]);
cptr->n[_X_] = aux;
}
if (optr->rot[_B_] != 0.0) {
aux = cptr->f[_X_]*cos(optr->rot[_B_])+cptr->f[_Z_]*sin(optr->rot[_B_]);
cptr->f[_Z_] = -cptr->f[_X_]*sin(optr->rot[_B_])+cptr->f[_Z_]*cos(optr->rot[_B_]);
cptr->f[_X_] = aux;
aux = cptr->n[_X_]*cos(optr->rot[_B_])+cptr->n[_Z_]*sin(optr->rot[_B_]);
cptr->n[_Z_] = -cptr->n[_X_]*sin(optr->rot[_B_])+cptr->n[_Z_]*cos(optr->rot[_B_]);
cptr->n[_X_] = aux;
}
if (optr->rot[_A_] != 0.0) {
aux = cptr->f[_Y_]*cos(optr->rot[_A_])-cptr->f[_Z_]*sin(optr->rot[_A_]);
cptr->f[_Z_] = cptr->f[_Y_]*sin(optr->rot[_A_])+cptr->f[_Z_]*cos(optr->rot[_A_]);
cptr->f[_Y_] = aux;
aux = cptr->n[_Y_]*cos(optr->rot[_A_])-cptr->n[_Z_]*sin(optr->rot[_A_]);
cptr->n[_Z_] = cptr->n[_Y_]*sin(optr->rot[_A_])+cptr->n[_Z_]*cos(optr->rot[_A_]);
cptr->n[_Y_] = aux;
}
}
/*!*****************************************************************************
*******************************************************************************
\note contactVelocity
\date March 2006
\remarks
computes the velocity of a contact point in object coordinates
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] cID : ID of contact point
\param[in] optr : object pointer
\param[out] v : velocity vector
******************************************************************************/
static void
contactVelocity(int cID, ObjectPtr optr, double *v)
{
int i;
double aux;
double v_start[N_CART+1];
double v_end[N_CART+1];
double x[N_CART+1];
// get the velocity in world coordinates
if (contacts[cID].point_contact_flag) {
computeContactPoint(&(contacts[cID]),link_pos_sim,Alink_sim,x);
computeLinkVelocityPoint(contacts[cID].id_start, x, link_pos_sim, joint_origin_pos_sim,
joint_axis_pos_sim, joint_sim_state, v);
//computeLinkVelocity(contacts[cID].id_start, link_pos_sim, joint_origin_pos_sim,
// joint_axis_pos_sim, joint_sim_state, v);
/*
for (i=1; i<=N_CART; ++i)
v[i] = base_state.xd[i];
*/
} else {
computeLinkVelocity(contacts[cID].id_start, link_pos_sim, joint_origin_pos_sim,
joint_axis_pos_sim, joint_sim_state, v_start);
computeLinkVelocity(contacts[cID].id_end, link_pos_sim, joint_origin_pos_sim,
joint_axis_pos_sim, joint_sim_state, v_end);
for (i=1; i<=N_CART; ++i)
v[i] = v_start[i]*contacts[cID].fraction_start + v_end[i]*contacts[cID].fraction_end;
}
// convert the velocity to object coordinates
if (optr->rot[_A_] != 0.0) {
aux = v[2]*cos(optr->rot[1])+v[3]*sin(optr->rot[_A_]);
v[3] = -v[2]*sin(optr->rot[1])+v[3]*cos(optr->rot[_A_]);
v[2] = aux;
}
if (optr->rot[_B_] != 0.0) {
aux = v[1]*cos(optr->rot[2])-v[3]*sin(optr->rot[_B_]);
v[3] = v[1]*sin(optr->rot[2])+v[3]*cos(optr->rot[_B_]);
v[1] = aux;
}
if (optr->rot[_G_] != 0.0) {
aux = v[1]*cos(optr->rot[3])+v[2]*sin(optr->rot[_G_]);
v[2] = -v[1]*sin(optr->rot[3])+v[2]*cos(optr->rot[_G_]);
v[1] = aux;
}
}
/*!*****************************************************************************
*******************************************************************************
\note addObjectSync
\date May 2010
\remarks
synchronizes adding of an object through shared memory communication
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] name : name of the object
\param[in] type : type of object
\param[in] contact : ID of contact model
\param[in] rgb : rgb values for color
\param[in] pos : pointer to position vector
\param[in] rot : pointer to rotation vector
\param[in] scale : pointer to rotation vector
\param[in] cparms : array of contact parameters
\param[in] oparms : array of object parameters
******************************************************************************/
static void
addObjectSync(char *name, int type, int contact, double *rgb, double *pos, double *rot,
double *scale, double *cparms, double *oparms)
{
int i,j;
int n_objs_parm;
int n_c_parm;
struct {
char name[STRING100]; /*!< object name */
int type; /*!< object type */
double trans[N_CART+1]; /*!< translatory offset of object */
double rot[N_CART+1]; /*!< rotational offset of object */
double scale[N_CART+1]; /*!< scaling in x,y,z */
double rgb[N_CART+1]; /*!< color information */
double object_parms[MAX_OBJ_PARMS+1]; /*!< object parameters */
int contact_model; /*!< which contact model to be used */
double contact_parms[MAX_CONTACT_PARMS+1];/*!< contact parameters */
} data;
unsigned char cbuf[sizeof(data)];
strcpy(data.name,name);
data.type = type;
for (i=1; i<=N_CART; ++i) {
data.trans[i] = pos[i];
data.rot[i] = rot[i];
data.scale[i] = scale[i];
data.rgb[i] = rgb[i];
}
switch (type) {
case CUBE:
n_objs_parm = N_CUBE_PARMS;
break;
case SPHERE:
n_objs_parm = N_SPHERE_PARMS;
break;
case TERRAIN:
n_objs_parm = N_TERRAIN_PARMS;
break;
case CYLINDER:
n_objs_parm = N_CYLINDER_PARMS;
break;
default:
n_objs_parm = 0;
}
for (i=1; i<=n_objs_parm; ++i)
data.object_parms[i] = oparms[i];
data.object_parms[0] = n_objs_parm;
switch (contact) {
case NO_CONTACT:
n_c_parm = N_NO_CONTACT_PARMS;
break;
case DAMPED_SPRING_STATIC_FRICTION:
n_c_parm = N_DAMPED_SPRING_STATIC_FRICTION_PARMS;
break;
case DAMPED_SPRING_VISCOUS_FRICTION:
n_c_parm = N_DAMPED_SPRING_VISCOUS_FRICTION_PARMS;
break;
case DAMPED_SPRING_LIMITED_REBOUND:
n_c_parm = N_DAMPED_SPRING_LIMITED_REBOUND_PARMS;
break;
default:
n_c_parm = 0;
}
for (i=1; i<=n_c_parm; ++i)
data.contact_parms[i] = cparms[i];
data.contact_parms[0] = n_c_parm;
data.contact_model = contact;
memcpy(cbuf,(void *)&data,sizeof(data));
sendMessageSimulationServo("addObject",(void *)cbuf,sizeof(data));
sendMessageOpenGLServo("addObject",(void *)cbuf,sizeof(data));
}
/*!*****************************************************************************
*******************************************************************************
\note changeObjPosByNameSync
\date May 2010
\remarks
synchronizes change of object position by name on all relevant processes
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] name : name of the object
\param[in] pos : pointer to position vector
\param[in] rot : pointer to rotation vector
******************************************************************************/
static void
changeObjPosByNameSync(char *name, double *pos, double *rot)
{
int i,j;
struct {
char obj_name[100];
double pos[N_CART+1];
double rot[N_CART+1];
} data;
unsigned char buf[sizeof(data)];
static double last_update_pos_time = 0;
strcpy(data.obj_name,name);
for (i=1; i<=N_CART; ++i) {
data.pos[i] = pos[i];
data.rot[i] = rot[i];
}
memcpy(buf,&data,sizeof(data));
if (servo_time - last_update_pos_time > 1./60.) { // 60Hz update is sufficient
sendMessageOpenGLServo("changeObjectPos",(void *)buf,sizeof(data));
last_update_pos_time = servo_time;
}
sendMessageSimulationServo("changeObjectPos",(void *)buf,sizeof(data));
}
/*!*****************************************************************************
*******************************************************************************
\note changeHideObjByNameSync
\date Nov. 2005
\remarks
synchronizes hiding of objects across processes
*******************************************************************************
[ Function Parameters: [in]=input,[out]=output
\param[in] name : name object
\param[in] hide : TRUE/FALSE
******************************************************************************/
static void
changeHideObjByNameSync(char *name, int hide)
{
int i,j;
struct {
int hide;
char obj_name[100];
} data;
unsigned char buf[sizeof(data)];
data.hide = hide;
strcpy(data.obj_name,name);
memcpy(buf,&data,sizeof(data));
sendMessageOpenGLServo("hideObject",(void *)buf,sizeof(data));
sendMessageSimulationServo("hideObject",(void *)buf,sizeof(data));
}
/*!*****************************************************************************
*******************************************************************************
\note deleteObjByNameSync
\date May 2010
\remarks
synchronizes delete of an object on all servos
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] name : name object
******************************************************************************/
static void
deleteObjByNameSync(char *name)
{
int i,j;
struct {
char obj_name[100];
} data;
unsigned char buf[sizeof(data)];
strcpy(data.obj_name,name);
memcpy(buf,&data,sizeof(data));
sendMessageOpenGLServo("deleteObject",(void *)buf,sizeof(data));
sendMessageSimulationServo("deleteObject",(void *)buf,sizeof(data));
}
/*!*****************************************************************************
*******************************************************************************
\note read_extra_contact_points
\date July 2010
\remarks
parses from the appropriate contact configuration file the extra contact
point specifications. The contacts data structure is assumed to exist and
to have all memory allocated. Moreover, the first n_links components need to
be assigned correctly, which is achieved from including the LEKin_contacts.h,
which also calls read_extra_contact_points.
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] fname : file name of file where config files are stored
******************************************************************************/
int
read_extra_contact_points(char *fname)
{
int j,i,rc;
char string[100];
FILE *in;
int count;
char name1[100],name2[100];
int id1,id2;
char fcond1[100],fcond2[100];
int fcond1ID,fcond2ID;
int n_checks;
int active;
int f_full_flag;
double lpos[N_CART+1];
double lnorm[N_CART+1];
int point_contact_flag;
double aux;
// open file and strip comments
sprintf(string,"%s%s",CONFIG,fname);
in = fopen_strip(string);
if (in == NULL) {
printf("ERROR: Cannot open file >%s<!\n",string);
return FALSE;
}
// read the file until EOF
count = n_links;
while (TRUE) {
point_contact_flag = FALSE;
id1 = -999;
id2 = -999;
rc = fscanf(in,"%s %s %d %d %s %s",name1,name2,&active,&n_checks,fcond1,fcond2);
if (rc == 6) { // add the appropriate number of contact points
if (!active)
continue;
// check whether this is a point contact
if (strcmp("POINT_CONTACT",name2) == 0) {
// read the local position vector and norm vector
rc = fscanf(in,"%lf %lf %lf %lf %lf %lf",&(lpos[_X_]),&(lpos[_Y_]),&(lpos[_Z_]),&(lnorm[_X_]),&(lnorm[_Y_]),&(lnorm[_Z_]));
if (rc != 6) {
printf("Problems reading position and norm vector for contact point >%s< >%s<\n",name1,name2);
continue;
}
point_contact_flag = TRUE;
// make sure that the norm vector is unit length
aux = sqrt(sqr(lnorm[_X_])+sqr(lnorm[_Y_])+sqr(lnorm[_Z_]));
for (i=1; i<=N_CART; ++i)
lnorm[i] /= (aux+1.e-10);
// overwrite some of the contact variables to ensure they are right
strcpy(name2,name1); // in line-contact notation, start and end point are the same for contact points
n_checks = 1; // only one check permitted as this is just a point
strcpy(fcond2,"null"); // to indicate that only the start point will create a force
} else { // not a POINT_CONTACT
// just zero out for easier debugging
for (i=1; i<=N_CART; ++i)
lpos[i] = lnorm[i] = 0.0;
}
// convert link names into IDs
for (i=0; i<=n_links; ++i)
if (strcmp(link_names[i],name1) == 0) {
id1 = i;
break;
}
for (i=0; i<=n_links; ++i)
if (strcmp(link_names[i],name2) == 0) {
id2 = i;
break;
}
if (id1 == -999) {
printf(">%s< does not seem to be a valid link name\n",name1);
continue;
}
if (id2 == -999) {
printf(">%s< does not seem to be a valid link name\n",name2);
continue;
}
// set these two link points as active
contacts[id1].active = active;
contacts[id2].active = active;
// parse the force condition
fcond1ID = F_FULL;
fcond2ID = F_FULL;
for (i=1; i<=N_FORCE_CONDITIONS; ++i) {
if (strcmp(f_cond_names[i],fcond1)==0)
fcond1ID = i;
if (strcmp(f_cond_names[i],fcond2)==0)
fcond2ID = i;
}
// update the connected link structures for these two links
if (!point_contact_flag) { // point contacts are isolated and do not fill the connect_links array
// the start point
f_full_flag = FALSE;
for (i=1; i<=contacts[id1].n_connected_links; ++i)
if (contacts[id1].force_condition[i] == F_FULL) { // a full force conditin overwrites any partial force condition
contacts[id1].force_condition[1] = F_FULL;
contacts[id1].connected_links[1] = id2;
contacts[id1].n_connected_links = 1;
f_full_flag = TRUE;
}
if (!f_full_flag) { // a full force condition overwrites any partial force conditions
if (fcond1ID == F_FULL) {
contacts[id1].force_condition[1] = F_FULL;
contacts[id1].connected_links[1] = id2;
contacts[id1].n_connected_links = 1;
} else {
if (contacts[id1].n_connected_links < MAX_CONNECTED) {
j = ++contacts[id1].n_connected_links;
contacts[id1].connected_links[j] = id2;
contacts[id1].force_condition[j] = fcond1ID;
} else {
printf("ERROR: ran out of memory for connected links -- increase MAX_CONNECTED in SL_objects.h\n");
}
}
}
// the end point
f_full_flag = FALSE;
for (i=1; i<=contacts[id2].n_connected_links; ++i)
if (contacts[id2].force_condition[i] == F_FULL) { // a full force condition overwrites any partial force conditions
contacts[id2].force_condition[1] = F_FULL;
contacts[id2].connected_links[1] = id1;
contacts[id2].n_connected_links = 1;
f_full_flag = TRUE;
}
if (!f_full_flag) { // a full force condition overwrites any partial force conditions
if (fcond2ID == F_FULL) {
contacts[id2].force_condition[1] = F_FULL;
contacts[id2].connected_links[1] = id1;
contacts[id2].n_connected_links = 1;
} else {
if (contacts[id2].n_connected_links < MAX_CONNECTED) {
j = ++contacts[id2].n_connected_links;
contacts[id2].connected_links[j] = id1;
contacts[id2].force_condition[j] = fcond2ID;
} else {
printf("ERROR: ran out of memory for connected links -- increase MAX_CONNECTED in SL_objects.h\n");
}
}
}
} // if (!point_contact)
// initialize the current contact structure
for (i=1; i<=n_checks; ++i) {
if (++count > n_contacts) {
printf("BUG: not enough contact elements allocated\n");
return FALSE;
}
contacts[count].id_start = id1;
contacts[count].id_end = id2;
contacts[count].off_link_start = contacts[id1].off_link_start;
contacts[count].off_link_end = contacts[id2].off_link_end;
contacts[count].base_dof_start = contacts[id1].base_dof_start;
contacts[count].base_dof_end = contacts[id2].base_dof_end;
contacts[count].active = active;
contacts[count].fraction_start = ((double)i)/((double)(n_checks+1));
if (point_contact_flag) {
contacts[count].fraction_start = 1.0;
contacts[count].force_condition[1] = fcond1ID;
}
contacts[count].fraction_end = 1.-contacts[count].fraction_start;
contacts[count].point_contact_flag = point_contact_flag;
for (j=1; j<=N_CART; ++j) {
contacts[count].local_point_pos[j] = lpos[j];
contacts[count].local_point_norm[j] = lnorm[j];
}
}
} else { // should be EOF
if (rc != EOF)
printf("Parsing error in read_extra_contact_points in SL_objects.c (rc=%d)\n",rc);
break;
}
} // while (TRUE)
fclose(in);
return TRUE;
}
/*!*****************************************************************************
*******************************************************************************
\note computeContactPoint
\date Oct 2010
\remarks
computes the global coordinates of the contact point from the contact
structure
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] cptr: pointer to contact structure
\param[in] lp : pointer to link_pos array
\param[in] al : pointer to Alink array
\param[out] x : contact point in global coordinates
******************************************************************************/
void
computeContactPoint(ContactPtr cptr, double **lp, double ***al, double *x)
{
int i,j;
double aux;
if (cptr->point_contact_flag) { // a point contact
// convert the local contact point to global coordinates
for (i=1; i<=N_CART; ++i) {
x[i] = al[cptr->id_start][i][4];
for (j=1; j<=N_CART; ++j)
x[i] += al[cptr->id_start][i][j]*cptr->local_point_pos[j];
}
} else { // a line contact
for (j=1; j<=N_CART; ++j)
x[j] = (lp[cptr->id_start][j]*cptr->fraction_start +
lp[cptr->id_end][j]*cptr->fraction_end);
}
}
/*!*****************************************************************************
*******************************************************************************
\note checkContactSpecifics
\date June 1999
\remarks
given an identified contact point and object, the contact specifics are
computed
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] cspecs: contact specifications
******************************************************************************/
static void
checkContactSpecifics(ContactSpecs cspecs)
{
int i,j;
double x[N_CART+1];
ObjectPtr optr;
double aux,aux1,aux2;
int ind=0;
int first_contact_flag = FALSE;
int contact_flag = FALSE;
double z;
double n[N_CART+1];
double v[N_CART+1];
char tfname[100];
double no_go;
double dist_z;
first_contact_flag = FALSE;
contact_flag = FALSE;
i = cspecs.i;
optr = cspecs.optr;
for (j=1; j<=N_CART; ++j)
x[j] = cspecs.x[j];
switch (optr->type) {
case CUBE: //---------------------------------------------------------------
// remember which object we are contacting, and also the
// contact point in object centered coordinates
if (!contacts[i].status || contacts[i].optr != optr ) {
for (j=1; j<=N_CART; ++j) {
contacts[i].x_start[j] = x[j];
contacts[i].x[j] = x[j];
}
contacts[i].friction_flag = FALSE;
first_contact_flag = TRUE;
}
contacts[i].status = contact_flag = TRUE;
contacts[i].optr = optr;
for (j=1; j<=N_CART; ++j) {
contacts[i].x[j] = x[j];
}
// compute relevant geometric information
if (first_contact_flag) {
// what is the closest face of the cube
if ( (optr->scale[1]/2.-fabs(x[1]) ) < (optr->scale[2]/2.-fabs(x[2]) ) &&
(optr->scale[1]/2.-fabs(x[1]) ) < (optr->scale[3]/2.-fabs(x[3]) )) {
ind = 1;
} else if ( (optr->scale[2]/2.-fabs(x[2]) ) < (optr->scale[1]/2.-fabs(x[1]) ) &&
(optr->scale[2]/2.-fabs(x[2]) ) < (optr->scale[3]/2.-fabs(x[3]) )) {
ind = 2;
} else {
ind = 3;
}
contacts[i].face_index = ind;
} else {
ind = contacts[i].face_index;
}
// the local veclocity of the contact point
contactVelocity(i,optr,v);
// the normal vector
for (j=1; j<=N_CART; ++j) {
if (j==ind) {
// the contact normal never change direction relativ to the start point
contacts[i].normal[j] =
optr->scale[j]/2.*macro_sign(contacts[i].x_start[j]) - x[j];
contacts[i].normvel[j] = -v[j];
} else {
contacts[i].normal[j] = 0.0;
contacts[i].normvel[j] = 0.0;
}
}
// the tangential vector
for (j=1; j<=N_CART; ++j) {
if (j!=ind) {
contacts[i].tangent[j] = x[j]-contacts[i].x_start[j];
contacts[i].tanvel[j] = v[j];
} else {
contacts[i].tangent[j] = 0.0;
contacts[i].tanvel[j] = 0.0;
}
}
// the tangential velocity for viscous friction
for (j=1; j<=N_CART; ++j) {
if (j!=ind) {
contacts[i].viscvel[j] = v[j];
} else {
contacts[i].viscvel[j]=0.0;
}
}
// finally apply contact models
computeContactForces(optr,&contacts[i]);
break;
case SPHERE: //---------------------------------------------------------------
if (!contacts[i].status || contacts[i].optr != optr ) {
for (j=1; j<=N_CART; ++j) {
contacts[i].x_start[j] = x[j];
contacts[i].x[j] = x[j];
}
contacts[i].friction_flag = FALSE;
first_contact_flag = TRUE;
}
contacts[i].status = contact_flag = TRUE;
contacts[i].optr = optr;
for (j=1; j<=N_CART; ++j) {
contacts[i].x[j] = x[j];
}
// the local veclocity of the contact point
contactVelocity(i,optr,v);
/* the normal displacement vector: map the current x into the unit sphere,
compute the point where this vector pierces through the unit sphere,
and map it back to the deformed sphere. The difference between this
vector and x is the normal displacement */
aux2 = 1.e-10;
for (j=1; j<=N_CART; ++j) {
aux2 += sqr(x[j]/(optr->scale[j]/2.));
}
aux2 = sqrt(aux2); /* length in unit sphere */
aux = 1.e-10;
for (j=1; j<=N_CART; ++j) {
contacts[i].normal[j] = x[j]*(1./aux2-1.);
aux += sqr(contacts[i].normal[j]);
}
aux = sqrt(aux);
// unit vector of contact normal
aux2 = 0.0;
for (j=1; j<=N_CART; ++j) {
n[j] = contacts[i].normal[j]/aux;
aux2 += n[j]*v[j];
}
// the normal velocity
for (j=1; j<=N_CART; ++j)
contacts[i].normvel[j] = -aux2*n[j];
/* the tangential vector */
aux1 = 0.0;
for (j=1; j<=N_CART; ++j) {
contacts[i].tangent[j]= x[j]-contacts[i].x_start[j];
aux1 += n[j] * contacts[i].tangent[j];
}
// subtract the all components in the direction of the normal
for (j=1; j<=N_CART; ++j) {
contacts[i].tangent[j] -= n[j] * aux1;
contacts[i].tanvel[j] = v[j] - n[j]*aux2;
}
/* the vicous velocity */
for (j=1; j<=N_CART; ++j) {
contacts[i].viscvel[j] = v[j] - n[j]*aux2;
}
computeContactForces(optr,&contacts[i]);
break;
case CYLINDER: //---------------------------------------------------------------
// the cylinder axis is aliged with te Z axis
if (!contacts[i].status || contacts[i].optr != optr ) {
for (j=1; j<=N_CART; ++j) {
contacts[i].x_start[j] = x[j];
contacts[i].x[j] = x[j];
}
contacts[i].friction_flag = FALSE;
first_contact_flag = TRUE;
}
contacts[i].status = contact_flag = TRUE;
contacts[i].optr = optr;
for (j=1; j<=N_CART; ++j) {
contacts[i].x[j] = x[j];
}
// the local veclocity of the contact point
contactVelocity(i,optr,v);
if (first_contact_flag || contacts[i].face_index != _Z_) {
/* the normal displacement vector: map the current x into the unit cylinder,
compute the point where this vector pierces through the unit cylinder,
and map it back to the deformed cylinder. The difference between this
vector and x is the normal displacement */
aux2 = 1.e-10;
for (j=1; j<=_Y_; ++j) {
aux2 += sqr(x[j]/(optr->scale[j]/2.));
}
aux2 = sqrt(aux2); // length in unit cylinder
aux = 1.e-10;
for (j=1; j<=_Y_; ++j) {
contacts[i].normal[j] = x[j]*(1./aux2-1.);
aux += sqr(contacts[i].normal[j]);
}
contacts[i].normal[_Z_] = 0.0;
aux = sqrt(aux);
// unit vector of contact normal
aux2 = 0.0;
for (j=1; j<=N_CART; ++j) {
n[j] = contacts[i].normal[j]/aux;
aux2 += n[j]*v[j];
}
// the normal velocity
for (j=1; j<=N_CART; ++j)
contacts[i].normvel[j] = -aux2*n[j];
/* the tangential vector */
aux1 = 0.0;
for (j=1; j<=N_CART; ++j) {
contacts[i].tangent[j]= x[j]-contacts[i].x_start[j];
aux1 += n[j] * contacts[i].tangent[j];
}
// subtract the all components in the direction of the normal
for (j=1; j<=N_CART; ++j) {
contacts[i].tangent[j] -= n[j] * aux1;
contacts[i].tanvel[j] = v[j] - n[j]*aux2;
}
/* the vicous velocity */
for (j=1; j<=N_CART; ++j) {
contacts[i].viscvel[j] = v[j] - n[j]*aux2;
}
}
// now we check which face is the nearest to th surface
if (first_contact_flag) {
// distance from nearest cylinder flat surface
dist_z = optr->scale[3]/2.-fabs(x[3]);
if (dist_z < aux)
contacts[i].face_index = _Z_;
else
contacts[i].face_index = _X_; // could also choose _Y_ -- !_Z_ matters
}
// compute with the cylinder ends as contact face
if (contacts[i].face_index == _Z_) {
ind = _Z_;
// the normal vector
for (j=1; j<=N_CART; ++j) {
if (j==ind) {
// the contact normal never change direction relativ to the start point
contacts[i].normal[j] =
optr->scale[j]/2.*macro_sign(contacts[i].x_start[j]) - x[j];
contacts[i].normvel[j] = -v[j];
} else {
contacts[i].normal[j] = 0.0;
contacts[i].normvel[j] = 0.0;
}
}
// the tangential vector
for (j=1; j<=N_CART; ++j) {
if (j!=ind) {
contacts[i].tangent[j] = x[j]-contacts[i].x_start[j];
contacts[i].tanvel[j] = v[j];
} else {
contacts[i].tangent[j] = 0.0;
contacts[i].tanvel[j] = 0.0;
}
}
// the tangential velocity for viscous friction
for (j=1; j<=N_CART; ++j) {
if (j!=ind) {
contacts[i].viscvel[j] = v[j];
} else {
contacts[i].viscvel[j]=0.0;
}
}
}
computeContactForces(optr,&contacts[i]);
break;
case TERRAIN: //---------------------------------------------------------------
getContactTerrainInfo(x[1], x[2], optr->name, &z, n, &no_go);
// remember which object we are contacting, and also the
// contact point in object centered coordinates
if (!contacts[i].status || contacts[i].optr != optr ) {
for (j=1; j<=N_CART; ++j) {
contacts[i].x_start[j] = x[j];
contacts[i].x[j] = x[j];
}
contacts[i].friction_flag = FALSE;
first_contact_flag = TRUE;
}
contacts[i].status = contact_flag = TRUE;
contacts[i].optr = optr;
for (j=1; j<=N_CART; ++j) {
contacts[i].x[j] = x[j];
}
// the local veclocity of the contact point
contactVelocity(i,optr,v);
aux1 = n[_X_]*v[_X_]+n[_Y_]*v[_Y_]+n[_Z_]*v[_Z_];
// compute relevant geometric information
// the normal vector
for (j=1; j<=N_CART; ++j) {
// note: n'*[ 0 0 (z-x[3])] = (z-x[3])*n[3] is the effective
// projection of the vertical distance to the surface onto
// the normal
contacts[i].normal[j] = n[j]*((z-x[3])*n[3]);
contacts[i].normvel[j] = -aux1*n[j];
}
// the tangential vector: project x-x_start into the null-space of normal
aux = 0.0;
for (j=1; j<=N_CART; ++j) {
contacts[i].tangent[j]=x[j]-contacts[i].x_start[j];
aux += contacts[i].tangent[j]*n[j];
}
for (j=1; j<=N_CART; ++j) {
contacts[i].tangent[j] -= n[j]*aux;
contacts[i].tanvel[j] = v[j]-n[j]*aux1;
}
// the tangential velocity for viscous friction
for (j=1; j<=N_CART; ++j)
contacts[i].viscvel[j] = v[j]-n[j]*aux1;
computeContactForces(optr,&contacts[i]);
break;
}
}
/*!*****************************************************************************
*******************************************************************************
\note spawnContactSpecsThread
\date May, 2013
\remarks
spawns a thread for contact specifics computation
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[i] num: the number of the thread
******************************************************************************/
static void
spawnContactSpecsThread(long num)
{
int err = 0;
int rc;
pthread_attr_t pth_attr;
size_t stack_size = 0;
err = pthread_attr_init(&pth_attr);
pthread_attr_getstacksize(&pth_attr, &stack_size);
double reqd = 1024*1024*8;
if (stack_size < reqd)
pthread_attr_setstacksize(&pth_attr, reqd);
// initialize the thread
if ((rc=pthread_create(&(cspecs_thread[num]), &pth_attr, contactThread, (void *)num)))
printf("pthread_create returned with %d\n",rc);
}
/*!*****************************************************************************
*******************************************************************************
\note contactThread
\date May 2013
\remarks
the thread for contact checking
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] num : the ID number of this thread
******************************************************************************/
static void *
contactThread(void *num)
{
int i;
long t = (long) num;
int ID;
char name[100];
ID = (int) t;
sprintf(name,"Contact thread #%d",ID);
printf("%s started\n",name);
#ifdef __XENO__
rt_task_shadow(NULL, name, 90, T_CPU((ID-1)));
#endif
sl_rt_mutex_lock(&(cspecs_mutex[ID]));
while ( TRUE ) {
sl_rt_cond_wait(&(cspecs_status[ID]),&(cspecs_mutex[ID]));
//printf("running %d for %d\n",ID,cspecs_data[ID].i);
for (i=1; i<=n_cspecs_data[ID]; ++i)
checkContactSpecifics(cspecs_data[ID][i]);
// done ...
n_cspecs_data[ID] = 0;
//printf("done %d for %d\n",ID,cspecs_data[ID].i);
}
printf("Contact thread #%d terminated\n",ID);
return NULL;
}
/*!*****************************************************************************
*******************************************************************************
\note accumulateFinalForces
\date June 2013
\remarks
for a given contact point and object, the final forces acting on the
joint and objects are accumulated. The force/torque structures must
have been zeros before accumulation over all contact points. The forces
at the contact point must be pre-computed. This function was separated
as it requires writing to memory structures that need to be shared
between threads.
*******************************************************************************
Function Parameters: [in]=input,[out]=output
\param[in] optr : ptr to object
\param[in] ctpr : ptr to contact point
******************************************************************************/
static void
accumulateFinalForces(ContactPtr cptr)
{
int i,j;
double moment_arm[N_CART+1];
double moment_arm_object[N_CART+1];
double x[N_CART+1];
ObjectPtr optr;
optr = cptr->optr;
// compute the contact point in global coordinates
computeContactPoint(cptr,link_pos_sim,Alink_sim,x);
/* first the start link */
for (i=1; i<=N_CART; ++i) {
ucontact[cptr->base_dof_start].f[i] += cptr->f[i]*cptr->fraction_start;
optr->f[i] += cptr->f[i]*cptr->fraction_start;
moment_arm[i] = x[i]-link_pos_sim[cptr->off_link_start][i];
moment_arm_object[i] = x[i]-optr->trans[i];
}
/* get the torque at the DOF from the cross product */
ucontact[cptr->base_dof_start].t[_A_] += moment_arm[_Y_]*cptr->f[_Z_]*cptr->fraction_start -
moment_arm[_Z_]*cptr->f[_Y_]*cptr->fraction_start;
ucontact[cptr->base_dof_start].t[_B_] += moment_arm[_Z_]*cptr->f[_X_]*cptr->fraction_start -
moment_arm[_X_]*cptr->f[_Z_]*cptr->fraction_start;
ucontact[cptr->base_dof_start].t[_G_] += moment_arm[_X_]*cptr->f[_Y_]*cptr->fraction_start -
moment_arm[_Y_]*cptr->f[_X_]*cptr->fraction_start;
/* get the torque at the object center from the cross product */
optr->t[_A_] += moment_arm_object[_Y_]*cptr->f[_Z_]*cptr->fraction_start -
moment_arm_object[_Z_]*cptr->f[_Y_]*cptr->fraction_start;
optr->t[_B_] += moment_arm_object[_Z_]*cptr->f[_X_]*cptr->fraction_start -
moment_arm_object[_X_]*cptr->f[_Z_]*cptr->fraction_start;
optr->t[_G_] += moment_arm_object[_X_]*cptr->f[_Y_]*cptr->fraction_start -
moment_arm_object[_Y_]*cptr->f[_X_]*cptr->fraction_start;
/* second the end link */
for (i=1; i<=N_CART; ++i) {
ucontact[cptr->base_dof_end].f[i] += cptr->f[i]*cptr->fraction_end;
optr->f[i] += cptr->f[i]*cptr->fraction_end;
moment_arm[i] = x[i]-link_pos_sim[cptr->off_link_end][i];
moment_arm_object[i] = x[i]-optr->trans[i];
}
/* get the torque at the DOF from the cross product */
ucontact[cptr->base_dof_end].t[_A_] += moment_arm[_Y_]*cptr->f[_Z_]*cptr->fraction_end -
moment_arm[_Z_]*cptr->f[_Y_]*cptr->fraction_end;
ucontact[cptr->base_dof_end].t[_B_] += moment_arm[_Z_]*cptr->f[_X_]*cptr->fraction_end -
moment_arm[_X_]*cptr->f[_Z_]*cptr->fraction_end;
ucontact[cptr->base_dof_end].t[_G_] += moment_arm[_X_]*cptr->f[_Y_]*cptr->fraction_end -
moment_arm[_Y_]*cptr->f[_X_]*cptr->fraction_end;
/* get the torque at the object center from the cross product */
optr->t[_A_] += moment_arm_object[_Y_]*cptr->f[_Z_]*cptr->fraction_end -
moment_arm_object[_Z_]*cptr->f[_Y_]*cptr->fraction_end;
optr->t[_B_] += moment_arm_object[_Z_]*cptr->f[_X_]*cptr->fraction_end -
moment_arm_object[_X_]*cptr->f[_Z_]*cptr->fraction_end;
optr->t[_G_] += moment_arm_object[_X_]*cptr->f[_Y_]*cptr->fraction_end -
moment_arm_object[_Y_]*cptr->f[_X_]*cptr->fraction_end;
}
| 28.765414 | 143 | 0.535373 | [
"object",
"vector",
"model",
"transform",
"3d"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.