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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3b97148251f48df9b972f39531063f365517b86f | 2,169 | h | C | OpenGL-Laboratory/Src/GLCore/Util/Core/Framebuffer.h | ishanshLal-tRED/OpenGL-TestSite | 6887725e0c268f9949050547578509e06be83eae | [
"Apache-2.0"
] | null | null | null | OpenGL-Laboratory/Src/GLCore/Util/Core/Framebuffer.h | ishanshLal-tRED/OpenGL-TestSite | 6887725e0c268f9949050547578509e06be83eae | [
"Apache-2.0"
] | null | null | null | OpenGL-Laboratory/Src/GLCore/Util/Core/Framebuffer.h | ishanshLal-tRED/OpenGL-TestSite | 6887725e0c268f9949050547578509e06be83eae | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "GLCore/Core/Core.h"
namespace GLCore
{
namespace Utils
{
enum class FramebufferTextureFormat
{
None = 0,
// Depth/stencil
// Color
RGBA8,
RGBA32F,
RED_INTEGER,
RED_FLOAT,
DEPTH24STENCIL8,
// Defaults
Depth = DEPTH24STENCIL8
};
struct FramebufferTextureSpecification
{
FramebufferTextureSpecification () = default;
FramebufferTextureSpecification (FramebufferTextureFormat format)
: TextureFormat (format)
{}
FramebufferTextureFormat TextureFormat = FramebufferTextureFormat::None;
// TODO: filtering/wrap
};
struct FramebufferAttachmentSpecification
{
FramebufferAttachmentSpecification () = default;
FramebufferAttachmentSpecification (std::initializer_list<FramebufferTextureSpecification> attachments)
: Attachments (attachments)
{}
std::vector<FramebufferTextureSpecification> Attachments;
};
struct FramebufferSpecification
{
uint32_t Width = 0, Height = 0;
FramebufferAttachmentSpecification Attachments;
uint32_t Samples = 1;
bool SwapChainTarget = false;
};
class Framebuffer
{
public:
Framebuffer (const FramebufferSpecification &spec);
virtual ~Framebuffer ();
virtual void Bind ();
virtual void Unbind ();
virtual void Resize (uint32_t width, uint32_t height);
void ReadPixel (uint32_t attachmentIndex, int x, int y, void* cantainer);
virtual void ClearAttachment (uint32_t attachmentIndex, int value);
virtual uint32_t GetColorAttachmentRendererID (uint32_t index = 0) const;
virtual const FramebufferSpecification &GetSpecification () const { return m_Specification; };
static std::shared_ptr<Framebuffer> Create (const FramebufferSpecification &spec);
private:
void Invalidate ();
private:
uint32_t m_RendererID = 0;
FramebufferSpecification m_Specification;
std::vector<FramebufferTextureSpecification> m_ColorAttachmentSpecifications; // That Last one is for Depth
FramebufferTextureSpecification m_DepthAttachmentSpecification = FramebufferTextureFormat::None;
std::vector<uint32_t> m_ColorAttachments;
uint32_t m_DepthAttachment = 0;
};
}
} | 24.370787 | 110 | 0.749654 | [
"vector"
] |
3b9d71d35e6b7754ed97bc1543fda2cc6c2e47fc | 336 | h | C | Wine.h | sjablo/backpropagation | 2b41279a16a58ccf4bac5807041b5ddbba34f773 | [
"MIT"
] | null | null | null | Wine.h | sjablo/backpropagation | 2b41279a16a58ccf4bac5807041b5ddbba34f773 | [
"MIT"
] | null | null | null | Wine.h | sjablo/backpropagation | 2b41279a16a58ccf4bac5807041b5ddbba34f773 | [
"MIT"
] | null | null | null | #pragma once
class Wine
{
public:
int typeInt;
std::vector<double> parameters, type;
static std::vector<Wine> wineList, trainingData, testData;
Wine(int type, double p1, double p2, double p3, double p4, double p5, double p6, double p7, double p8, double p9, double p10, double p11, double p12, double p13);
~Wine();
}; | 28 | 164 | 0.696429 | [
"vector"
] |
3bafc9455ad2a0381a8f7dee673282225eef982b | 15,895 | h | C | sfm_sdk/src/main/include/UF_WSQ.h | hyeonchang/sfm-sdk-android-module | 2ace40a203dcf4f43dd095010b505ef98b0f2b13 | [
"MIT"
] | null | null | null | sfm_sdk/src/main/include/UF_WSQ.h | hyeonchang/sfm-sdk-android-module | 2ace40a203dcf4f43dd095010b505ef98b0f2b13 | [
"MIT"
] | null | null | null | sfm_sdk/src/main/include/UF_WSQ.h | hyeonchang/sfm-sdk-android-module | 2ace40a203dcf4f43dd095010b505ef98b0f2b13 | [
"MIT"
] | null | null | null | /**
* WSQ API
*/
/*
* Copyright (c) 2001-2019 Suprema Inc. All Rights Reserved.
*
* This software is the confidential and proprietary information of
* Suprema Inc. ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Suprema.
*/
#ifndef __UNIFINGER_WSQ_H__
#define __UNIFINGER_WSQ_H__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
//#include <algorithm>
//using namespace std;
#ifndef _WIN32
#define max(x, y) x >= y ? x : y
#endif
#ifndef TRUE
#define TRUE 1
#define FALSE 0
#endif
#define TBLS_N_SOF 2
/* WSQ Marker Definitions */
/******************************************************************
* X'FFA0' SOI * Start of Image
* X'FFA1' EOI * End of Image
* X'FFA2' SOF Start of Frame
* X'FFA3' SOB Start of Block
* X'FFA4' DTT Define Transform Table
* X'FFA5' DQT Define Quantization Table
* X'FFA6' DHT Define Huffman table(s)
* X'FFA7' DRI Define Restart Interval
* X'FFB0' - X'FFB7' RSTm* Restart with modulo 8 count ��m��
* X'FFA8' COM Comment
******************************************************************/
#define SOI_WSQ 0xffa0 //Start of Image
#define EOI_WSQ 0xffa1 //End of Image
#define SOF_WSQ 0xffa2 //Start of Frame
#define SOB_WSQ 0xffa3 //Start of Block
#define DTT_WSQ 0xffa4 //Define Transform Table
#define DQT_WSQ 0xffa5 //Define Quantization Table
#define DHT_WSQ 0xffa6 //Define Huffman table(s)
#define DRT_WSQ 0xffa7 //Define Restart Interval
#define COM_WSQ 0xffa8 //Comment
/* Case for getting ANY marker. */
#define ANY_WSQ 0xffff
#define TBLS_N_SOB (TBLS_N_SOF + 2)
// ??????
//#define FILTBANK_EVEN_8X8_1
/* Filter Bank Definitions */
#ifdef FILTBANK_EVEN_8X8_1
#define MAX_HIFILT 8
#define MAX_LOFILT 8
#else
#define MAX_HIFILT 7
#define MAX_LOFILT 9
#endif
/* Subband Definitions */
#define STRT_SUBBAND_2 19
#define STRT_SUBBAND_3 52
#define MAX_SUBBANDS 64
#define NUM_SUBBANDS 60
#define STRT_SUBBAND_DEL (NUM_SUBBANDS)
#define STRT_SIZE_REGION_2 4
#define STRT_SIZE_REGION_3 51
#define MIN_IMG_DIM 256
#define WHITE 255
#define BLACK 0
#define COEFF_CODE 0
#define RUN_CODE 1
#define RAW_IMAGE 1
#define IHEAD_IMAGE 0
#define VARIANCE_THRESH 1.01
#define NCM_PPI "PPI" /* -1 if unknown (manditory)*/
/* nistcom.h */
#define NCM_HEADER "NIST_COM" /* manditory */
/* jpegl.h */
#define READ_TABLE_LEN 1
#define NO_READ_TABLE_LEN 0
/* wsq.h */
#define MAXFETS 100
#define W_TREELEN 20
#define Q_TREELEN 64
#define MAX_DHT_TABLES 8
/* Defined in jpegl.h */
#define MAX_HUFFBITS 16
#define MAX_HUFFCOUNTS_WSQ 256 /* Length of code table: change as needed */
/* but DO NOT EXCEED 256 */
#define MAX_HUFFCOEFF 74 /* -73 .. +74 */
#define MAX_HUFFZRUN 100
#define MAXFETLENGTH 512
/* nistcom.h */
#define NCM_COLORSPACE "COLORSPACE" /* RGB,YCbCr,GRAY */
#define NCM_COMPRESSION "COMPRESSION" /* NONE,JPEGB,JPEGL,WSQ */
#define NCM_WSQ_RATE "WSQ_BITRATE" /* ex. .75,2.25 (-1.0 if unknown)*/
#define NCM_PIX_WIDTH "PIX_WIDTH" /* manditory */
#define NCM_PIX_HEIGHT "PIX_HEIGHT" /* manditory */
#define NCM_PIX_DEPTH "PIX_DEPTH" /* 1,8,24 (manditory)*/
#define NCM_LOSSY "LOSSY" /* 0,1 */
/* defs.h */
#define sround(x) ((int)(((x) < 0) ? (x)-0.5 : (x) + 0.5))
#define sround_uint(x) ((unsigned int)(((x) < 0) ? (x)-0.5 : (x) + 0.5))
/* Defined in swap.h */
#define swap_short_bytes(_a_) \
{ \
short _b_ = _a_; \
char *_f_ = (char *)&_b_; \
char *_t_ = (char *)&_a_; \
_t_[1] = _f_[0]; \
_t_[0] = _f_[1]; \
}
#define swap_int_bytes(_ui_) \
{ \
int _b_ = _ui_; \
unsigned char *_f_ = (unsigned char *)&(_b_); \
unsigned char *_t_ = (unsigned char *)&(_ui_); \
_t_[3] = _f_[0]; \
_t_[2] = _f_[1]; \
_t_[1] = _f_[2]; \
_t_[0] = _f_[3]; \
}
typedef struct header_frm
{
unsigned char black;
unsigned char white;
unsigned short width;
unsigned short height;
float m_shift;
float r_scale;
unsigned char wsq_encoder;
unsigned short software;
} FRM_HEADER_WSQ;
typedef struct table_dtt
{
float *lofilt;
float *hifilt;
unsigned char losz;
unsigned char hisz;
char lodef;
char hidef;
} DTT_TABLE;
typedef struct table_dqt
{
float bin_center;
float q_bin[MAX_SUBBANDS];
float z_bin[MAX_SUBBANDS];
char dqt_def;
} DQT_TABLE;
typedef struct wavlet_tree
{
int x;
int y;
int lenx;
int leny;
int inv_rw;
int inv_cl;
} W_TREE;
typedef struct quant_tree
{
short x; /* UL corner of block */
short y;
short lenx; /* block size */
short leny; /* block size */
} Q_TREE;
typedef struct fetstruct
{
int alloc;
int num;
char **names;
char **values;
} FET;
typedef FET NISTCOM;
typedef struct hcode
{
short size;
unsigned int code;
} HUFFCODE;
typedef struct table_dht
{
unsigned char tabdef;
unsigned char huffbits[MAX_HUFFBITS];
unsigned char huffvalues[MAX_HUFFCOUNTS_WSQ + 1];
} DHT_TABLE;
typedef struct quantization
{
float q; /* quantization level */
float cr; /* compression ratio */
float r; /* compression bitrate */
float qbss_t[MAX_SUBBANDS];
float qbss[MAX_SUBBANDS];
float qzbs[MAX_SUBBANDS];
float var[MAX_SUBBANDS];
} QUANT_VALS;
#ifdef __cplusplus
extern "C"
{
#endif
int wsq_decode_file(unsigned char **odata, int *ow, int *oh, int *od, int *oppi, int *lossyflag, FILE *infp);
int wsq_decode_mem(unsigned char **odata, int *ow, int *oh, int *od, int *oppi, int *lossyflag, unsigned char *idata, const int ilen);
int wsq_encode_mem(unsigned char **odata, int *olen, const float r_bitrate, unsigned char *idata, const int w, const int h, const int d, const int ppi, char *comment_text);
int write_raw_from_memsize(char *ofile, unsigned char *odata, const int olen);
/* encoder.c */
int gen_hufftable_wsq(HUFFCODE **ohufftable, unsigned char **ohuffbits, unsigned char **ohuffvalues, short *sip, const int *block_sizes, const int num_sizes);
int compress_block(unsigned char *outbuf, int *obytes, short *sip, const int sip_siz, const int MaxCoeff, const int MaxZRun, HUFFCODE *codes);
int count_block(int **ocounts, const int max_huffcounts, short *sip, const int sip_siz, const int MaxCoeff, const int MaxZRun);
/* tree.c */
void build_wsq_trees(W_TREE w_tree[], const int w_treelen, Q_TREE q_tree[], const int q_treelen, const int width, const int height);
void build_w_tree(W_TREE w_tree[], const int width, const int height);
void build_q_tree(W_TREE *w_tree, Q_TREE *q_tree);
void q_tree4(Q_TREE *q_tree, const int start, const int lenx, const int leny, const int x, const int y);
void w_tree4(W_TREE w_tree[], const int start1, const int start2, const int lenx, const int leny, const int x, const int y, const int stop1);
void q_tree16(Q_TREE *q_tree, const int start, const int lenx, const int leny, const int x, const int y, const int rw, const int cl);
/* tableio.c */
int read_table_wsq(unsigned short marker, DTT_TABLE *dtt_table, DQT_TABLE *dqt_table, DHT_TABLE *dht_table, FILE *infp);
int read_frame_header_wsq(FRM_HEADER_WSQ *frm_header, FILE *infp);
int read_marker_wsq(unsigned short *omarker, const int type, FILE *infp);
int read_transform_table(DTT_TABLE *dtt_table, FILE *infp);
int read_quantization_table(DQT_TABLE *dqt_table, FILE *infp);
int read_huffman_table_wsq(DHT_TABLE *dht_table, FILE *infp);
int read_block_header(unsigned char *huff_table, FILE *infp);
int getc_marker_wsq(unsigned short *omarker, const int type, unsigned char **cbufptr, unsigned char *ebufptr);
int getc_table_wsq(unsigned short marker, DTT_TABLE *dtt_table, DQT_TABLE *dqt_table, DHT_TABLE *dht_table, unsigned char **cbufptr, unsigned char *ebufptr);
int getc_frame_header_wsq(FRM_HEADER_WSQ *frm_header, unsigned char **cbufptr, unsigned char *ebufptr);
int getc_nistcom_wsq(NISTCOM **onistcom, unsigned char *idata, const int ilen);
int getc_transform_table(DTT_TABLE *dtt_table, unsigned char **cbufptr, unsigned char *ebufptr);
int getc_quantization_table(DQT_TABLE *dqt_table, unsigned char **cbufptr, unsigned char *ebufptr);
int getc_huffman_table_wsq(DHT_TABLE *dht_table, unsigned char **cbufptr, unsigned char *ebufptr);
int getc_block_header(unsigned char *huff_table, unsigned char **cbufptr, unsigned char *ebufptr);
int putc_transform_table(float *lofilt, const int losz, float *hifilt, const int hisz, unsigned char *odata, const int oalloc, int *olen);
int putc_nistcom_wsq(char *comment_text, const int w, const int h, const int d, const int ppi, const int lossyflag, const float r_bitrate, unsigned char *odata, const int oalloc, int *olen);
int putc_quantization_table(QUANT_VALS *quant_vals, unsigned char *odata, const int oalloc, int *olen);
int putc_frame_header_wsq(const int width, const int height, const float m_shift, const float r_scale, unsigned char *odata, const int oalloc, int *olen);
int putc_block_header(const int table, unsigned char *odata, const int oalloc, int *olen);
/* tableio.c 2*/
int read_nistcom_wsq(NISTCOM **onistcom, FILE *infp);
int getc_comment(unsigned char **ocomment, unsigned char **cbufptr, unsigned char *ebufptr);
int read_comment(unsigned char **ocomment, FILE *infp);
int putc_comment(const unsigned short marker, unsigned char *comment, const int cs, unsigned char *odata, const int oalloc, int *olen);
/* extrfet.c */
int extractfet_ret(char **ovalue, char *feature, FET *fet);
/* freefet.c */
void freefet(FET *fet);
/* util.c */
int wsq_reconstruct(float *fdata, const int width, const int height, W_TREE w_tree[], const int w_treelen, const DTT_TABLE *dtt_table);
int unquantize(float **ofip, const DQT_TABLE *dqt_table, Q_TREE q_tree[], const int q_treelen, short *sip, const int width, const int height);
void init_wsq_decoder_resources();
void free_wsq_decoder_resources();
void conv_img_2_flt(float *fip, float *m_shift, float *r_scale, unsigned char *data, const int num_pix);
int wsq_decompose(float *fdata, const int width, const int height, W_TREE w_tree[], const int w_treelen, float *hifilt, const int hisz, float *lofilt, const int losz);
void variance(QUANT_VALS *quant_vals, Q_TREE q_tree[], const int q_treelen, float *fip, const int width, const int height);
int quantize(short **osip, int *ocmp_siz, QUANT_VALS *quant_vals, Q_TREE q_tree[], const int q_treelen, float *fip, const int width, const int height);
void quant_block_sizes(int *oqsize1, int *oqsize2, int *oqsize3, QUANT_VALS *quant_vals, W_TREE w_tree[], const int w_treelen, Q_TREE q_tree[], const int q_treelen);
void get_lets(float *new_, float *old, const int len1, const int len2, const int pitch, const int stride, float *hi, const int hsz, float *lo, const int lsz, const int inv);
/* huff.c */
int check_huffcodes_wsq(HUFFCODE *hufftable, int last_size);
int getc_huffman_table(unsigned char *otable_id, unsigned char **ohuffbits, unsigned char **ohuffvalues, const int max_huffcounts, unsigned char **cbufptr, unsigned char *ebufptr, const int read_table_len, int *bytes_left);
int putc_huffman_table(const unsigned short marker, const unsigned char table_id, unsigned char *huffbits, unsigned char *huffvalues, unsigned char *outbuf, const int outalloc, int *outlen);
int find_huff_sizes(int **ocodesize, int *freq, const int max_huffcounts);
int find_num_huff_sizes(unsigned char **obits, int *adjust, int *codesize, const int max_huffcounts);
int sort_huffbits(unsigned char *bits);
int sort_code_sizes(unsigned char **ovalues, int *codesize, const int max_huffcounts);
int build_huffcode_table(HUFFCODE **ohuffcode_table, HUFFCODE *in_huffcode_table, const int last_size, unsigned char *values, const int max_huffcounts);
void find_least_freq(int *value1, int *value2, int *freq, const int max_huffcounts);
/* huff.c jpg */
void gen_decode_table(HUFFCODE *huffcode_table, int *maxcode, int *mincode, int *valptr, unsigned char *huffbits);
void build_huffcodes(HUFFCODE *huffcode_table);
int build_huffsizes(HUFFCODE **ohuffcode_table, int *temp_size, unsigned char *huffbits, const int max_huffcounts);
int read_huffman_table(unsigned char *otable_id, unsigned char **ohuffbits, unsigned char **ohuffvalues, const int max_huffcounts, FILE *infp, const int read_table_len, int *bytes_left);
/* decoder.c */
int decode_data_file(int *onodeptr, int *mincode, int *maxcode, int *valptr, unsigned char *huffvalues, FILE *infp, int *bit_count, unsigned short *marker);
int decode_data_mem(int *onodeptr, int *mincode, int *maxcode, int *valptr, unsigned char *huffvalues, unsigned char **cbufptr, unsigned char *ebufptr, int *bit_count, unsigned short *marker);
int huffman_decode_data_mem(short *ip, DTT_TABLE *dtt_table, DQT_TABLE *dqt_table, DHT_TABLE *dht_table, unsigned char **cbufptr, unsigned char *ebufptr);
int huffman_decode_data_file(short *ip, DTT_TABLE *dtt_table, DQT_TABLE *dqt_table, DHT_TABLE *dht_table, FILE *infp);
int getc_nextbits_wsq(unsigned short *obits, unsigned short *marker, unsigned char **cbufptr, unsigned char *ebufptr, int *bit_count, const int bits_req);
int nextbits_wsq(unsigned short *obits, unsigned short *marker, FILE *file, int *bit_count, const int bits_req);
/* dataio.c */
int read_uint(unsigned int *oint_dat, FILE *infp);
int read_ushort(unsigned short *oshrt_dat, FILE *infp);
int read_byte(unsigned char *ochar_dat, FILE *infp);
int getc_uint(unsigned int *oint_dat, unsigned char **cbufptr, unsigned char *ebufptr);
int getc_ushort(unsigned short *oshrt_dat, unsigned char **cbufptr, unsigned char *ebufptr);
int getc_byte(unsigned char *ochar_dat, unsigned char **cbufptr, unsigned char *ebufptr);
int getc_bytes(unsigned char **ochar_dat, const int ilen, unsigned char **cbufptr, unsigned char *ebufptr);
int putc_ushort(unsigned short ishort, unsigned char *odata, const int oalloc, int *olen);
int putc_bytes(unsigned char *idata, const int ilen, unsigned char *odata, const int oalloc, int *olen);
int putc_byte(const unsigned char idata, unsigned char *odata, const int oalloc, int *olen);
int putc_uint(unsigned int iint, unsigned char *odata, const int oalloc, int *olen);
void write_bits(unsigned char **outbuf, const unsigned short code, const short size, int *outbit, unsigned char *bits, int *bytes);
void flush_bits(unsigned char **outbuf, int *outbit, unsigned char *bits, int *bytes);
/* util.c */
int int_sign(const int power);
void conv_img_2_uchar(unsigned char *data, float *img, const int width, const int height, const float m_shift, const float r_scale);
void join_lets(float *news, float *old, const int len1, const int len2, const int pitch, const int stride, float *hi, const int hsz, float *lo, const int lsz, const int inv);
/* updatfet.c */
int updatefet_ret(char *feature, char *value, FET *fet);
/* strfet.c */
int string2fet(FET **ofet, char *istr);
/* computil.c */
int read_skip_marker_segment(const unsigned short marker, FILE *infp);
int getc_skip_marker_segment(const unsigned short marker, unsigned char **cbufptr, unsigned char *ebufptr);
/* allocfet.c */
int allocfet_ret(FET **ofet, int numfeatures);
int reallocfet_ret(FET **ofet, int newlen);
/* ppi.c */
int getc_ppi_wsq(int *oppi, unsigned char *idata, const int ilen);
int read_ppi_wsq(int *oppi, FILE *infp);
/* strfet.c */
int fet2string(char **ostr, FET *fet);
/* lkupfet.c */
int lookupfet(char **ovalue, char *feature, FET *fet);
/* nistcom.c */
int combine_wsq_nistcom(NISTCOM **onistcom, const int w, const int h, const int d, const int ppi, const int lossyflag, const float r_bitrate);
int combine_nistcom(NISTCOM **onistcom, const int w, const int h, const int d, const int ppi, const int lossyflag);
#ifdef __cplusplus
}
#endif
#endif // __i386__
| 43.787879 | 224 | 0.724127 | [
"transform"
] |
3bb6d32db4293295e171677b7629b6102d929f4f | 2,995 | h | C | src/cir/cirMgr.h | tomchean/fraig | fe402304cda31bc733bd4352cdb2603f94cec4b7 | [
"MIT"
] | null | null | null | src/cir/cirMgr.h | tomchean/fraig | fe402304cda31bc733bd4352cdb2603f94cec4b7 | [
"MIT"
] | null | null | null | src/cir/cirMgr.h | tomchean/fraig | fe402304cda31bc733bd4352cdb2603f94cec4b7 | [
"MIT"
] | null | null | null | /****************************************************************************
FileName [ cirMgr.h ]
PackageName [ cir ]
Synopsis [ Define circuit manager ]
Author [ Chung-Yang (Ric) Huang ]
Copyright [ Copyleft(c) 2008-present LaDs(III), GIEE, NTU, Taiwan ]
****************************************************************************/
#ifndef CIR_MGR_H
#define CIR_MGR_H
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
#include "myHashMap.h"
#include "cirGate.h"
#include "util.h"
using namespace std;
// TODO: Feel free to define your own classes, variables, or functions.
#include "cirDef.h"
extern CirMgr *cirMgr;
extern CirGate** gate_all;
class CirMgr
{
public:
CirMgr() { simulated = false; myfecgrps =0; _dfsList_fec =0; }
~CirMgr() ;
// Access functions
// return '0' if "gid" corresponds to an undefined gate.
CirGate* getGate(unsigned gid) const ;
// Member functions about circuit construction
bool readCircuit(const string&);
// Member functions about circuit optimization
void sweep();
void optimize();
// Member functions about simulation
void randomSim();
void fileSim(ifstream&);
void setSimLog(ofstream *logFile) { _simLog = logFile; }
// Member functions about fraig
void strash();
void printFEC() const;
void fraig();
// Member functions about circuit reporting
void printSummary() const;
void printNetlist() ;
void printPIs() const;
void printPOs() const;
void printFloatGates() const;
void printFECPairs() const;
void writeAag(ostream&) const;
void writeGate(ostream&, CirGate*) const;
// self define
void DFS(CirGate* gate) ;
void dfsviset(CirGate* gate) ;
void resetvisit();
//about sweep
void sweepGate(CirGate*,unsigned);
void update();
//about opt
void remove_one(CirGate*);
void remove_zero(CirGate*);
void neglect_gate(CirGate*);
void check_opt(CirGate*);
// about strash
void merge(CirGate*,CirGate*);
void merge_invert(CirGate*,CirGate*);
// about simulation
void initsim();
void simulation();
void simulation_po();
void simulation_stream(size_t*);
//about fec
size_t update_fec(size_t&);
void assign_fec();
void reset_fec();
void set_dfsfec();
void init_dfsfec();
void set_sim();
void sort_fec();
// about fraig
void construct_fraig(SatSolver& ,unsigned*&);
class AIG_REC{
friend CirMgr;
public:
AIG_REC(unsigned i1,unsigned i2,unsigned i){ ip[0] = i1; ip[1] =i2 ; id =i; };
private:
unsigned ip[2];
unsigned id;
};
private:
ofstream *_simLog;
unsigned cir_para[5];
vector<unsigned> ID_IP,ID_OP,ID_AIG,ID_UNDEF,_dfsList,_dfsList_nopio;
// FOR FEC
vector<vector<unsigned>*>* myfecgrps;
vector<unsigned>* _dfsList_fec;
bool simulated;
vector<size_t*> useful_sim;
// FOR SOLVE SAT
SatSolver solver;
};
#endif // CIR_MGR_H
| 23.038462 | 85 | 0.629048 | [
"vector"
] |
3bbe9e8c5779cf62283c16e0a9a1702342a96a05 | 24,777 | c | C | src/nethuns/sockets/xdp.c | larthia/nethuns | bf66314ec35871f805e1421ccf8e303133ea00aa | [
"BSD-3-Clause"
] | 1 | 2022-03-11T14:56:59.000Z | 2022-03-11T14:56:59.000Z | src/nethuns/sockets/xdp.c | larthia/nethuns | bf66314ec35871f805e1421ccf8e303133ea00aa | [
"BSD-3-Clause"
] | 1 | 2021-09-18T12:35:20.000Z | 2021-09-18T12:35:20.000Z | src/nethuns/sockets/xdp.c | larthia/nethuns | bf66314ec35871f805e1421ccf8e303133ea00aa | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright 2021 Larthia, University of Pisa. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
#ifdef NETHUNS_SOCKET
#undef NETHUNS_SOCKET
#endif
#define NETHUNS_SOCKET NETHUNS_SOCKET_XDP
#include "ring.h"
#define SOCKET_TYPE xdp
#include "file.inc"
#include "../misc/compiler.h"
#include "../api.h"
#include "xdp.h"
#include "xsk_ext.h"
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <net/if.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <src/bpf.h>
#include <src/libbpf.h>
#include <linux/if_link.h>
#include <linux/if_xdp.h>
#include <linux/err.h>
struct bpf_object*
load_bpf_object_file(const char *filename, int ifindex)
{
int first_prog_fd = -1;
struct bpf_object *obj;
int err;
// Struct used to set ifindex for hardware offloading XDP programs.
// This sets libbpf bpf_program->prog_ifindex, and foreach bpf_map->map_ifindex.
struct bpf_prog_load_attr prog_load_attr = {
.prog_type = BPF_PROG_TYPE_XDP,
.ifindex = ifindex,
};
prog_load_attr.file = filename;
// Use libbpf for extracting BPF byte-code from BPF-ELF object, and
// loading this into the kernel via bpf-syscall
err = bpf_prog_load_xattr(&prog_load_attr, &obj, &first_prog_fd);
if (err) {
nethuns_fprintf(stderr, "load_bpf_object_file: loading BPF-OBJ file(%s) (%d): %s\n", filename, err, strerror(-err));
return NULL;
}
// Return pointer to a libbpf bpf_object
return obj;
}
static struct bpf_object*
open_bpf_object(const char *file, int ifindex)
{
int err;
struct bpf_object *obj;
struct bpf_map *map;
struct bpf_program *prog, *first_prog = NULL;
struct bpf_object_open_attr open_attr = {
.file = file,
.prog_type = BPF_PROG_TYPE_XDP,
};
obj = bpf_object__open_xattr(&open_attr);
if (IS_ERR_OR_NULL(obj)) {
err = -PTR_ERR(obj);
nethuns_fprintf(stderr, "open_bpf_object: error opening BPF-OBJ file(%s) (%d): %s\n", file, err, strerror(-err));
return NULL;
}
bpf_object__for_each_program(prog, obj) {
bpf_program__set_type(prog, BPF_PROG_TYPE_XDP);
bpf_program__set_ifindex(prog, ifindex);
if (!first_prog)
first_prog = prog;
}
bpf_object__for_each_map(map, obj) {
if (!bpf_map__is_offload_neutral(map))
bpf_map__set_ifindex(map, ifindex);
}
if (!first_prog) {
nethuns_fprintf(stderr, "open_bpf_object: file %s contains no programs\n", file);
return NULL;
}
return obj;
}
static int
reuse_maps(struct bpf_object *obj, const char *path)
{
struct bpf_map *map;
if (!obj)
return -ENOENT;
if (!path)
return -EINVAL;
bpf_object__for_each_map(map, obj) {
int len, err;
int pinned_map_fd;
char buf[PATH_MAX];
len = snprintf(buf, PATH_MAX, "%s/%s", path, bpf_map__name(map));
if (len < 0) {
return -EINVAL;
} else if (len >= PATH_MAX) {
return -ENAMETOOLONG;
}
pinned_map_fd = bpf_obj_get(buf);
if (pinned_map_fd < 0)
return pinned_map_fd;
err = bpf_map__reuse_fd(map, pinned_map_fd);
if (err)
return err;
}
return 0;
}
struct bpf_object*
load_bpf_object_file_reuse_maps(const char *file, int ifindex, const char *pin_dir)
{
int err;
struct bpf_object *obj;
obj = open_bpf_object(file, ifindex);
if (!obj) {
nethuns_fprintf(stderr, "load_bpf_object_file_reuse_maps: failed to open object %s\n", file);
return NULL;
}
err = reuse_maps(obj, pin_dir);
if (err) {
nethuns_fprintf(stderr, "load_bpf_object_file_reuse_maps: failed to reuse maps for object %s, pin_dir=%s\n", file, pin_dir);
return NULL;
}
err = bpf_object__load(obj);
if (err) {
nethuns_fprintf(stderr, "load_bpf_object_file_reuse_maps: error loading BPF-OBJ file(%s) (%d): %s\n", file, err, strerror(-err));
return NULL;
}
return obj;
}
int
xdp_link_attach(int ifindex, __u32 xdp_flags, int prog_fd)
{
int err;
// libbpf provides the XDP net_device link-level hook attach helper
err = bpf_set_link_xdp_fd(ifindex, prog_fd, xdp_flags);
if (err == -EEXIST && !(xdp_flags & XDP_FLAGS_UPDATE_IF_NOEXIST)) {
// Force mode didn't work, probably because a program of the opposite type is loaded.
// Let's unload that and try loading again.
__u32 old_flags = xdp_flags;
xdp_flags &= ~XDP_FLAGS_MODES;
xdp_flags |= (old_flags & XDP_FLAGS_SKB_MODE) ? XDP_FLAGS_DRV_MODE : XDP_FLAGS_SKB_MODE;
err = bpf_set_link_xdp_fd(ifindex, -1, xdp_flags);
if (!err)
err = bpf_set_link_xdp_fd(ifindex, prog_fd, old_flags);
}
if (err < 0) {
nethuns_fprintf(stderr, "xdp_link_attach: ifindex(%d) link set xdp fd failed (%d): %s\n", ifindex, -err, strerror(-err));
switch (-err) {
case EBUSY:
case EEXIST:
nethuns_fprintf(stderr, "xdp_link_attach: XDP already loaded on device, use --force to swap/replace\n");
break;
case EOPNOTSUPP:
nethuns_fprintf(stderr, "xdp_link_attach:: native-XDP not supported, use --skb-mode or --auto-mode\n");
break;
default:
break;
}
return -1;
}
return 0;
}
static struct bpf_object*
load_bpf_and_xdp_attach(struct nethuns_socket_xdp *s)
{
struct bpf_program *bpf_prog;
struct bpf_object *bpf_obj;
int offload_ifindex = 0;
int prog_fd = -1;
int err;
// If flags indicate hardware offload, supply ifindex.
if (s->xdp_flags & XDP_FLAGS_HW_MODE)
offload_ifindex = nethuns_socket(s)->ifindex;
// Load the BPF-ELF object file and get back libbpf bpf_object.
if (nethuns_socket(s)->opt.reuse_maps) {
// Find pinned maps to reuse.
bpf_obj = load_bpf_object_file_reuse_maps(nethuns_socket(s)->opt.xdp_prog, offload_ifindex, nethuns_socket(s)->opt.pin_dir);
} else {
// No pinned maps to reuse.
bpf_obj = load_bpf_object_file(nethuns_socket(s)->opt.xdp_prog, offload_ifindex);
}
if (!bpf_obj) {
nethuns_perror(nethuns_socket(s)->errbuf, "load_bpf_and_xdp_attach: error loading BPF object file %s...\n", nethuns_socket(s)->opt.xdp_prog);
return NULL;
}
// All XDP/BPF programs from xdp_prog have been loaded into the kernel, and evaluated by the verifier.
// Only one of these gets attached to XDP hook, the others will get freed once this process exit.
if (nethuns_socket(s)->opt.xdp_prog_sec) {
// Find a matching BPF prog section name.
bpf_prog = bpf_object__find_program_by_title(bpf_obj, nethuns_socket(s)->opt.xdp_prog_sec);
} else {
// Find the first program.
bpf_prog = bpf_program__next(NULL, bpf_obj);
}
if (!bpf_prog) {
nethuns_perror(nethuns_socket(s)->errbuf, "load_bpf_and_xdp_attach: couldn't find a program in ELF section '%s'\n", nethuns_socket(s)->opt.xdp_prog_sec);
return NULL;
}
//strncpy(nethuns_socket(s)->opt.xdp_prog_sec, bpf_program__title(bpf_prog, false), strlen(nethuns_socket(s)->opt.xdp_prog_sec));
prog_fd = bpf_program__fd(bpf_prog);
if (prog_fd <= 0) {
nethuns_perror(nethuns_socket(s)->errbuf, "load_bpf_and_xdp_attach: bpf_program__fd failed\n");
return NULL;
}
// BPF-progs are (only) loaded by the kernel, and prog_fd is the selected file-descriptor handle.
// This FD is now attached to a kernel hook point (the XDP net_device link-level hook).
err = xdp_link_attach(nethuns_socket(s)->ifindex, s->xdp_flags, prog_fd);
if (err == -1) {
nethuns_perror(nethuns_socket(s)->errbuf, "load_bpf_and_xdp_attach: xdp_link_attach failed\n");
return NULL;
}
return bpf_obj;
}
static int
load_xdp_program(struct nethuns_socket_xdp *s, const char *dev)
{
nethuns_lock_global();
struct nethuns_netinfo *info = nethuns_lookup_netinfo(dev);
if (info == NULL) {
info = nethuns_create_netinfo(dev);
if (info == NULL) {
goto err;
}
}
if (info->xdp_prog_refcnt++ == 0) {
// Load custom program if configured.
if (nethuns_socket(s)->opt.xdp_prog) {
s->obj = load_bpf_and_xdp_attach(s);
if (!s->obj) {
// Error handling done in load_bpf_and_xdp_attach()
goto err;
}
nethuns_fprintf(stderr, "bpf_prog_load: done\n");
} else {
nethuns_fprintf(stderr, "bpf_prog_load: using default program\n");
goto out;
}
}
out:
nethuns_unlock_global();
return 0;
err:
nethuns_unlock_global();
return -1;
}
/*
static int
load_xdp_program(struct nethuns_socket_xdp *s, const char *dev)
{
nethuns_lock_global();
struct nethuns_netinfo *info = nethuns_lookup_netinfo(dev);
if (info == NULL) {
info = nethuns_create_netinfo(dev);
if (info == NULL) {
goto err;
}
}
if (info->xdp_prog_refcnt++ == 0) {
struct bpf_prog_load_attr prog_load_attr = {
.prog_type = BPF_PROG_TYPE_XDP,
.file = nethuns_socket(s)->opt.xdp_prog,
};
if (prog_load_attr.file == NULL) {
nethuns_fprintf(stderr, "bpf_prog_load: using default program\n");
goto out;
}
int prog_fd;
nethuns_fprintf(stderr, "bpf_prog_load: loading %s program...\n", nethuns_socket(s)->opt.xdp_prog);
if (bpf_prog_load_xattr(&prog_load_attr, &s->obj, &prog_fd)) {
nethuns_perror(nethuns_socket(s)->errbuf, "bpf_prog_load: could not load %s program", nethuns_socket(s)->opt.xdp_prog);
goto err;
}
if (prog_fd < 0) {
nethuns_perror(nethuns_socket(s)->errbuf, "bpf_prog_load: no program found: %s", strerror(prog_fd));
goto err;
}
if (bpf_set_link_xdp_fd(nethuns_socket(s)->ifindex, prog_fd, s->xdp_flags) < 0) {
nethuns_perror(nethuns_socket(s)->errbuf, "bpf_set_link_fd: set link xpd failed");
goto err;
}
// retrieve the actual xdp program id...
//
if (bpf_get_link_xdp_id(nethuns_socket(s)->ifindex, &info->xdp_prog_id, s->xdp_flags))
{
nethuns_perror(nethuns_socket(s)->errbuf, "bpf_get_link_id: get link xpd failed");
goto err;
}
nethuns_fprintf(stderr, "bpf_prog_load: done\n");
}
out:
nethuns_unlock_global();
return 0;
err:
nethuns_unlock_global();
return -1;
}
*/
static int
unload_xdp_program(struct nethuns_socket_xdp *s)
{
uint32_t curr_prog_id = 0;
nethuns_lock_global();
struct nethuns_netinfo *info = nethuns_lookup_netinfo(nethuns_socket(s)->devname);
if (info != NULL) {
if (--info->xdp_prog_refcnt == 0)
{
nethuns_fprintf(stderr, "bpf_prog_load: unloading %s program...\n", nethuns_socket(s)->opt.xdp_prog ? nethuns_socket(s)->opt.xdp_prog : "default");
if (bpf_get_link_xdp_id(nethuns_socket(s)->ifindex, &curr_prog_id, s->xdp_flags)) {
nethuns_perror(nethuns_socket(s)->errbuf, "bpf_get_link: could get xdp id");
goto err;
}
if (info->xdp_prog_id == 0 || info->xdp_prog_id == curr_prog_id) {
bpf_set_link_xdp_fd(nethuns_socket(s)->ifindex, -1, s->xdp_flags);
} else if (!curr_prog_id) {
nethuns_perror(nethuns_socket(s)->errbuf, "bpf_prog: could get find a prog id on dev '%s'", nethuns_socket(s)->devname);
goto err;
} else {
nethuns_perror(nethuns_socket(s)->errbuf, "bpf_prog: program on dev '%s' changed?", nethuns_socket(s)->devname);
goto err;
}
nethuns_fprintf(stderr, "bpf_prog_load: done\n");
}
} else {
nethuns_perror(nethuns_socket(s)->errbuf, "unload_xdp_program: could not find dev '%s'", nethuns_socket(s)->devname);
goto err;
}
nethuns_unlock_global();
return 0;
err:
nethuns_unlock_global();
return -1;
}
struct nethuns_socket_xdp *
nethuns_open_xdp(struct nethuns_socket_options *opt, char *errbuf)
{
struct nethuns_socket_xdp *s;
unsigned int n;
s = calloc(1, sizeof(struct nethuns_socket_xdp));
if (!s)
{
nethuns_perror(errbuf, "open: could not allocate socket");
return NULL;
}
/* set defualt xdp_flags */
s->xdp_flags = 0; // or safer XDP_FLAGS_UPDATE_IF_NOEXIST;
s->xdp_bind_flags = 0; // XDP_USE_NEED_WAKEUP;
switch(opt->capture)
{
case nethuns_cap_default: {
s->xdp_flags |= XDP_FLAGS_SKB_MODE;
s->xdp_bind_flags |= XDP_COPY;
} break;
case nethuns_cap_skb_mode: {
s->xdp_flags |= XDP_FLAGS_SKB_MODE;
s->xdp_bind_flags |= XDP_COPY;
} break;
case nethuns_cap_drv_mode: {
s->xdp_flags |= XDP_FLAGS_DRV_MODE;
s->xdp_bind_flags |= XDP_COPY;
} break;
case nethuns_cap_zero_copy: {
s->xdp_flags |= XDP_FLAGS_DRV_MODE;
s->xdp_bind_flags |= XDP_ZEROCOPY;
}
}
nethuns_socket(s)->ifindex = 0;
// TODO: support for HUGE pages
// -> opt_umem_flags |= XDP_UMEM_UNALIGNED_CHUNK_FLAG;
// adjust packet size...
//
static const size_t size_[] = {2048, 4096};
for (n = 0; n < sizeof(size_)/sizeof(size_[0]); n++)
{
if (opt->packetsize <= size_[n]) {
opt->packetsize = size_[n];
break;
}
}
if (n == sizeof(size_)/sizeof(size_[0])) {
nethuns_perror(errbuf, "open: XDP packet size too large!");
goto err0;
}
s->rx = false;
s->tx = false;
if (opt->mode == nethuns_socket_rx_tx || opt->mode == nethuns_socket_rx_only) {
s->rx = true;
}
if (opt->mode == nethuns_socket_rx_tx || opt->mode == nethuns_socket_tx_only) {
s->tx = true;
}
if (!s->rx && !s->tx) {
nethuns_perror(errbuf, "open: please select at least one between rx and tx");
goto err0;
}
// what is the purpose of numblock?
s->first_rx_frame = 0;
s->first_tx_frame = 0;
if (s->rx) {
if (nethuns_make_ring(opt->numblocks * opt->numpackets, opt->packetsize, &s->base.rx_ring) < 0)
{
nethuns_perror(errbuf, "open: failed to allocate ring");
goto err0;
}
s->first_tx_frame = s->base.rx_ring.mask + 1;
}
if (s->tx) {
if (nethuns_make_ring(opt->numblocks * opt->numpackets, opt->packetsize, &s->base.tx_ring) < 0)
{
nethuns_perror(errbuf, "open: failed to allocate ring");
goto err1;
}
}
s->framesz = nethuns_lpow2(opt->packetsize);
s->fshift = __builtin_ctzl(s->framesz);
s->total_mem = !!s->tx * (s->base.tx_ring.mask + 1) * s->framesz +
!!s->rx * (s->base.rx_ring.mask + 1) * s->framesz;
s->bufs = mmap(NULL, s->total_mem,
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS /* | MAP_HUGETLB */, -1, 0);
if (s->bufs == MAP_FAILED) {
nethuns_perror(errbuf, "open: XDP bufs mmap failed");
goto err1;
}
s->umem = xsk_configure_umem(s, s->bufs, s->total_mem, s->framesz);
if (!s->umem) {
nethuns_perror(errbuf, "open: XDP configure umem failed!");
goto err2;
}
// postpone the creation of the socket to bind stage...
s->xsk = NULL;
nethuns_socket(s)->opt = *opt;
return s;
err2:
munmap(s->bufs, s->total_mem);
err1:
if (s->rx) {
nethuns_delete_ring(&s->base.rx_ring);
}
err0:
free(s);
return NULL;
}
int nethuns_close_xdp(struct nethuns_socket_xdp *s)
{
if (s)
{
if (s->xsk) {
xsk_socket__delete(s->xsk->xsk);
}
xsk_umem__delete(s->umem->umem);
munmap(s->bufs, s->total_mem);
unload_xdp_program(s);
if (nethuns_socket(s)->opt.promisc)
{
__nethuns_clear_if_promisc(s, nethuns_socket(s)->devname);
}
__nethuns_free_base(s);
free(s);
}
return 0;
}
int nethuns_bind_xdp(struct nethuns_socket_xdp *s, const char *dev, int queue)
{
if (queue == NETHUNS_ANY_QUEUE)
{
nethuns_fprintf(stderr, "bind: ANY_QUEUE is not supported by XDP device -> reverting to queue 0\n");
queue = 0;
}
nethuns_socket(s)->queue = queue;
nethuns_socket(s)->ifindex = (int)if_nametoindex(dev);
nethuns_socket(s)->devname = strdup(dev);
// actually open the xsk socket here...
s->xsk = xsk_configure_socket(s);
if (!s->xsk) {
nethuns_perror(s->base.errbuf, "bind: configure socket (%s)", nethuns_dev_queue_name(dev, queue));
return -1;
}
if (load_xdp_program(s, dev) < 0) {
nethuns_perror(s->base.errbuf, "bind: could not load xdp program %s (%s)", nethuns_socket(s)->opt.xdp_prog, nethuns_dev_queue_name(dev, queue));
return -1;
}
if (nethuns_socket(s)->opt.xdp_prog) {
if (xsk_enter_into_map(s, queue) < 0) {
nethuns_perror(s->base.errbuf, "bind: could not enter into map (%s)", nethuns_dev_queue_name(dev, queue));
return -1;
}
}
if (nethuns_socket(s)->opt.promisc)
{
if (__nethuns_set_if_promisc(s, dev) < 0) {
nethuns_perror(s->base.errbuf, "bind: could not set promisc (%s)", nethuns_dev_queue_name(dev, queue));
return -1;
}
}
nethuns_lock_global();
struct nethuns_netinfo *info = nethuns_lookup_netinfo(dev);
if (info->xdp_prog_id == 0) {
// the library has loaded the default program, retrieve its id
if (bpf_get_link_xdp_id(nethuns_socket(s)->ifindex, &info->xdp_prog_id, s->xdp_flags))
{
nethuns_perror(nethuns_socket(s)->errbuf, "bpf_get_link_id: get link xpd failed");
nethuns_unlock_global();
return -1;
}
}
nethuns_unlock_global();
return 0;
}
static int
__nethuns_xdp_free_slots(struct nethuns_ring_slot *slot, __maybe_unused uint64_t id, void *user)
{
struct nethuns_socket_xdp *s = (struct nethuns_socket_xdp *)user;
xsk_ring_cons__release(&s->xsk->rx, 1);
(void)slot;
return 0;
}
uint64_t
nethuns_recv_xdp(struct nethuns_socket_xdp *s, nethuns_pkthdr_t const **pkthdr, uint8_t const **payload)
{
// unsigned int caplen = nethuns_socket(s)->opt.packetsize;
uint32_t idx_fq = 0;
unsigned int ret;
unsigned int i, stock_frames;
nethuns_ring_free_slots(&s->base.rx_ring, __nethuns_xdp_free_slots, s);
struct nethuns_ring_slot * slot = nethuns_ring_get_slot(&s->base.rx_ring, s->base.rx_ring.head);
if (__atomic_load_n(&slot->inuse, __ATOMIC_ACQUIRE))
{
return 0;
}
// retrieve the pointer to the packet
//
if (s->rcvd == 0) {
s->rcvd = xsk_ring_cons__peek(&s->xsk->rx, 1, &s->idx_rx);
if (s->rcvd == 0) {
return 0;
}
stock_frames = xsk_prod_nb_free(&s->xsk->umem->fq, 16);
if (stock_frames > 0) {
ret = xsk_ring_prod__reserve(&s->xsk->umem->fq, stock_frames, &idx_fq);
while (ret != stock_frames)
ret = xsk_ring_prod__reserve(&s->xsk->umem->fq, s->rcvd, &idx_fq);
for (i = 0; i < stock_frames; i++) {
//printf("rx_frame(%d) %lx\n", idx_fq, rx_frame(s, idx_fq));
*xsk_ring_prod__fill_addr(&s->xsk->umem->fq, idx_fq) = rx_frame(s, idx_fq);
idx_fq++;
}
xsk_ring_prod__submit(&s->xsk->umem->fq, stock_frames);
}
}
/* process the packet */
uint64_t addr;
slot->pkthdr.addr = addr = xsk_ring_cons__rx_desc(&s->xsk->rx, s->idx_rx)->addr;
uint32_t len = xsk_ring_cons__rx_desc(&s->xsk->rx, s->idx_rx++)->len;
s->rcvd--;
addr = xsk_umem__add_offset_to_addr(addr);
unsigned char *pkt = xsk_umem__get_data(s->xsk->umem->buffer, addr);
//__atomic_add_fetch(&s->xsk->rx_npkts, 1, __ATOMIC_RELAXED);
// get timestamp...
struct timespec tp;
//clock_gettime(CLOCK_MONOTONIC_COARSE, &tp);
struct xdp_pkthdr header = {
.sec = (int32_t)tp.tv_sec
, .nsec = (int32_t)tp.tv_nsec
, .len = len
, .snaplen = len
};
if (!nethuns_socket(s)->filter || nethuns_socket(s)->filter(nethuns_socket(s)->filter_ctx, &header, pkt))
{
memcpy(&slot->pkthdr, &header, sizeof(slot->pkthdr));
slot->pkthdr.packet = pkt;
__atomic_store_n(&slot->inuse, 1, __ATOMIC_RELEASE);
*pkthdr = &slot->pkthdr;
*payload = pkt;
// TODO: this will give 0 when head wraps around
return ++s->base.rx_ring.head;
}
return 0;
}
static void kick_tx(struct xsk_socket_info *xsk)
{
int ret;
ret = sendto(xsk_socket__fd(xsk->xsk), NULL, 0, MSG_DONTWAIT, NULL, 0);
if (ret >= 0 || errno == ENOBUFS || errno == EAGAIN || errno == EBUSY)
return;
}
static void xdp_complete_tx(struct nethuns_socket_xdp *s)
{
if (s->xsk->outstanding_tx > 0) {
if (xsk_ring_prod__needs_wakeup(&s->xsk->tx))
kick_tx(s->xsk);
// int rcvd = xsk_ring_cons__peek(&s->xsk->umem->cq, XSK_RING_PROD__DEFAULT_NUM_DESCS, &dummy);
// if (rcvd > 0) {
// xsk_ring_cons__release(&s->xsk->umem->cq, rcvd);
// s->xsk->outstanding_tx -= rcvd;
// }
}
}
uint8_t *
nethuns_get_buf_addr_xdp(struct nethuns_socket_xdp *s, uint64_t pktid)
{
return xsk_umem__get_data(s->xsk->umem->buffer,
tx_frame(s, (pktid & s->base.tx_ring.mask)));
}
int
nethuns_send_xdp(struct nethuns_socket_xdp *s, uint8_t const *packet, unsigned int len)
{
uint64_t tail = s->base.tx_ring.tail;
struct nethuns_ring_slot *slot = nethuns_ring_get_slot(&s->base.tx_ring, tail);
uint8_t *frame = xsk_umem__get_data(s->xsk->umem->buffer, tx_frame(s, tail));
if (__atomic_load_n(&slot->inuse, __ATOMIC_RELAXED)) {
return 0;
}
memcpy(frame, packet, len);
s->base.tx_ring.tail++;
nethuns_send_slot(s, tail, len);
//printf("marking slot %d\n", tail);
return 1;
}
int
nethuns_flush_xdp(struct nethuns_socket_xdp *s)
{
uint32_t idx = 0;
unsigned int cmpl, i, toflush;
// mark completed transmissions
cmpl = xsk_ring_cons__peek(&s->xsk->umem->cq, s->base.tx_ring.size, &idx);
for (i = 0; i < cmpl; i++) {
uint64_t addr = *xsk_ring_cons__comp_addr(&s->xsk->umem->cq, idx);
uint64_t slotnr = tx_slot(s, addr);
struct nethuns_ring_slot *slot = nethuns_ring_get_slot(&s->base.tx_ring, slotnr);
//printf("release slot %lu addr %lx\n", slotnr, addr);
__atomic_store_n(&slot->inuse, 0, __ATOMIC_RELEASE);
idx++;
}
xsk_ring_cons__release(&s->xsk->umem->cq, cmpl);
s->xsk->outstanding_tx -= cmpl;
//printf("cmpl %d outstanding %d\n", cmpl, s->xsk->outstanding_tx);
//__atomic_add_fetch(&s->xsk->tx_npkts, cmpl, __ATOMIC_RELAXED);
toflush = 0;
for (i = 0; i < s->base.tx_ring.size; i++) {
uint64_t head = s->base.tx_ring.head;
struct nethuns_ring_slot *slot = nethuns_ring_get_slot(&s->base.tx_ring, head);
if (__atomic_load_n(&slot->inuse, __ATOMIC_ACQUIRE) != 1)
break;
__atomic_store_n(&slot->inuse, 2, __ATOMIC_RELAXED);
xsk_ring_prod__reserve(&s->xsk->tx, 1, &idx);
xsk_ring_prod__tx_desc(&s->xsk->tx, idx)->addr = tx_frame(s, head);
//printf("slot %d sending %lx\n", head, tx_frame(s, head));
xsk_ring_prod__tx_desc(&s->xsk->tx, idx)->len = slot->len;
toflush++;
s->base.tx_ring.head++;
}
if (toflush) {
xsk_ring_prod__submit(&s->xsk->tx, toflush);
s->xsk->outstanding_tx += toflush;
//printf("toflush %d outstanding %d\n", cmpl, s->xsk->outstanding_tx);
xdp_complete_tx(s);
}
return 0;
}
int
nethuns_stats_xdp(struct nethuns_socket_xdp *s, struct nethuns_stat *stats)
{
struct xdp_statistics xdp_stats;
if (likely(s->xsk != NULL))
{
socklen_t len = sizeof(xdp_stats);
stats->rx_packets = __atomic_load_n(&s->xsk->rx_npkts, __ATOMIC_RELAXED);
stats->tx_packets = __atomic_load_n(&s->xsk->tx_npkts, __ATOMIC_RELAXED);
if (getsockopt(xsk_socket__fd(s->xsk->xsk), SOL_XDP, XDP_STATISTICS, &xdp_stats, &len) == 0) {
stats->rx_dropped = xdp_stats.rx_dropped;
stats->rx_invalid = xdp_stats.rx_invalid_descs;
stats->tx_invalid = xdp_stats.tx_invalid_descs;
} else {
stats->rx_dropped = 0;
stats->rx_invalid = 0;
stats->tx_invalid = 0;
}
}
else {
stats->rx_packets = 0;
stats->tx_packets = 0;
stats->rx_invalid = 0;
stats->tx_invalid = 0;
stats->rx_dropped = 0;
}
stats->rx_if_dropped = 0;
stats->freeze = 0;
return 0;
}
int nethuns_fd_xdp(__maybe_unused struct nethuns_socket_xdp *s)
{
return xsk_socket__fd(s->xsk->xsk);
}
int
nethuns_fanout_xdp(__maybe_unused struct nethuns_socket_xdp *s, __maybe_unused int group, __maybe_unused const char *fanout)
{
nethuns_perror(s->base.errbuf, "fanout: not supported (%s)", nethuns_device_name(s));
return -1;
}
void
nethuns_dump_rings_xdp(__maybe_unused struct nethuns_socket_xdp *s)
{
}
| 28.123723 | 159 | 0.641401 | [
"object"
] |
3bc09c0173b721fa4db3442381791a21544aa648 | 52,143 | c | C | source/blender/blenkernel/intern/data_transfer.c | 1-MillionParanoidTterabytes/Blender-2.79b-blackened | e8d767324e69015aa66850d13bee7db1dc7d084b | [
"Unlicense"
] | 2 | 2018-06-18T01:50:25.000Z | 2018-06-18T01:50:32.000Z | source/blender/blenkernel/intern/data_transfer.c | 1-MillionParanoidTterabytes/Blender-2.79b-blackened | e8d767324e69015aa66850d13bee7db1dc7d084b | [
"Unlicense"
] | null | null | null | source/blender/blenkernel/intern/data_transfer.c | 1-MillionParanoidTterabytes/Blender-2.79b-blackened | e8d767324e69015aa66850d13bee7db1dc7d084b | [
"Unlicense"
] | null | null | null | /*
* ***** BEGIN GPL LICENSE BLOCK *****
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* The Original Code is Copyright (C) 2014 by Blender Foundation.
* All rights reserved.
*
* The Original Code is: all of this file.
*
* Contributor(s): Bastien Montagne.
*
* ***** END GPL LICENSE BLOCK *****
*/
/** \file blender/blenkernel/intern/data_transfer.c
* \ingroup bke
*/
#include "MEM_guardedalloc.h"
#include "DNA_customdata_types.h"
#include "DNA_meshdata_types.h"
#include "DNA_mesh_types.h"
#include "DNA_object_types.h"
#include "DNA_scene_types.h"
#include "BLI_array.h"
#include "BLI_math.h"
#include "BLI_blenlib.h"
#include "BLI_utildefines.h"
#include "BKE_cdderivedmesh.h"
#include "BKE_context.h"
#include "BKE_customdata.h"
#include "BKE_data_transfer.h"
#include "BKE_deform.h"
#include "BKE_DerivedMesh.h"
#include "BKE_mesh.h"
#include "BKE_mesh_mapping.h"
#include "BKE_mesh_remap.h"
#include "BKE_object.h"
#include "BKE_object_deform.h"
#include "BKE_report.h"
#include "data_transfer_intern.h"
CustomDataMask BKE_object_data_transfer_dttypes_to_cdmask(const int dtdata_types)
{
CustomDataMask cddata_mask = 0;
int i;
for (i = 0; i < DT_TYPE_MAX; i++) {
const int dtdata_type = 1 << i;
int cddata_type;
if (!(dtdata_types & dtdata_type)) {
continue;
}
cddata_type = BKE_object_data_transfer_dttype_to_cdtype(dtdata_type);
if (!(cddata_type & CD_FAKE)) {
cddata_mask |= 1LL << cddata_type;
}
else if (cddata_type == CD_FAKE_MDEFORMVERT) {
cddata_mask |= CD_MASK_MDEFORMVERT; /* Exception for vgroups :/ */
}
else if (cddata_type == CD_FAKE_UV) {
cddata_mask |= CD_MASK_MTEXPOLY | CD_MASK_MLOOPUV;
}
else if (cddata_type == CD_FAKE_LNOR) {
cddata_mask |= CD_MASK_NORMAL | CD_MASK_CUSTOMLOOPNORMAL;
}
}
return cddata_mask;
}
/* Check what can do each layer type (if it is actually handled by transferdata, if it supports advanced mixing... */
bool BKE_object_data_transfer_get_dttypes_capacity(
const int dtdata_types, bool *r_advanced_mixing, bool *r_threshold)
{
int i;
bool ret = false;
*r_advanced_mixing = false;
*r_threshold = false;
for (i = 0; (i < DT_TYPE_MAX) && !(ret && *r_advanced_mixing && *r_threshold); i++) {
const int dtdata_type = 1 << i;
if (!(dtdata_types & dtdata_type)) {
continue;
}
switch (dtdata_type) {
/* Vertex data */
case DT_TYPE_MDEFORMVERT:
*r_advanced_mixing = true;
*r_threshold = true;
ret = true;
break;
case DT_TYPE_SKIN:
*r_threshold = true;
ret = true;
break;
case DT_TYPE_BWEIGHT_VERT:
ret = true;
break;
/* Edge data */
case DT_TYPE_SHARP_EDGE:
*r_threshold = true;
ret = true;
break;
case DT_TYPE_SEAM:
*r_threshold = true;
ret = true;
break;
case DT_TYPE_CREASE:
ret = true;
break;
case DT_TYPE_BWEIGHT_EDGE:
ret = true;
break;
case DT_TYPE_FREESTYLE_EDGE:
*r_threshold = true;
ret = true;
break;
/* Loop/Poly data */
case DT_TYPE_UV:
ret = true;
break;
case DT_TYPE_VCOL:
*r_advanced_mixing = true;
*r_threshold = true;
ret = true;
break;
case DT_TYPE_LNOR:
*r_advanced_mixing = true;
ret = true;
break;
case DT_TYPE_SHARP_FACE:
*r_threshold = true;
ret = true;
break;
case DT_TYPE_FREESTYLE_FACE:
*r_threshold = true;
ret = true;
break;
}
}
return ret;
}
int BKE_object_data_transfer_get_dttypes_item_types(const int dtdata_types)
{
int i, ret = 0;
for (i = 0; (i < DT_TYPE_MAX) && (ret ^ (ME_VERT | ME_EDGE | ME_LOOP | ME_POLY)); i++) {
const int dtdata_type = 1 << i;
if (!(dtdata_types & dtdata_type)) {
continue;
}
if (DT_DATATYPE_IS_VERT(dtdata_type)) {
ret |= ME_VERT;
}
if (DT_DATATYPE_IS_EDGE(dtdata_type)) {
ret |= ME_EDGE;
}
if (DT_DATATYPE_IS_LOOP(dtdata_type)) {
ret |= ME_LOOP;
}
if (DT_DATATYPE_IS_POLY(dtdata_type)) {
ret |= ME_POLY;
}
}
return ret;
}
int BKE_object_data_transfer_dttype_to_cdtype(const int dtdata_type)
{
switch (dtdata_type) {
case DT_TYPE_MDEFORMVERT:
return CD_FAKE_MDEFORMVERT;
case DT_TYPE_SHAPEKEY:
return CD_FAKE_SHAPEKEY;
case DT_TYPE_SKIN:
return CD_MVERT_SKIN;
case DT_TYPE_BWEIGHT_VERT:
return CD_FAKE_BWEIGHT;
case DT_TYPE_SHARP_EDGE:
return CD_FAKE_SHARP;
case DT_TYPE_SEAM:
return CD_FAKE_SEAM;
case DT_TYPE_CREASE:
return CD_FAKE_CREASE;
case DT_TYPE_BWEIGHT_EDGE:
return CD_FAKE_BWEIGHT;
case DT_TYPE_FREESTYLE_EDGE:
return CD_FREESTYLE_EDGE;
case DT_TYPE_UV:
return CD_FAKE_UV;
case DT_TYPE_SHARP_FACE:
return CD_FAKE_SHARP;
case DT_TYPE_FREESTYLE_FACE:
return CD_FREESTYLE_FACE;
case DT_TYPE_VCOL:
return CD_MLOOPCOL;
case DT_TYPE_LNOR:
return CD_FAKE_LNOR;
default:
BLI_assert(0);
}
return 0; /* Should never be reached! */
}
int BKE_object_data_transfer_dttype_to_srcdst_index(const int dtdata_type)
{
switch (dtdata_type) {
case DT_TYPE_MDEFORMVERT:
return DT_MULTILAYER_INDEX_MDEFORMVERT;
case DT_TYPE_SHAPEKEY:
return DT_MULTILAYER_INDEX_SHAPEKEY;
case DT_TYPE_UV:
return DT_MULTILAYER_INDEX_UV;
case DT_TYPE_VCOL:
return DT_MULTILAYER_INDEX_VCOL;
default:
return DT_MULTILAYER_INDEX_INVALID;
}
}
/* ********** */
/* Generic pre/post processing, only used by custom loop normals currently. */
static void data_transfer_dtdata_type_preprocess(
Object *UNUSED(ob_src), Object *UNUSED(ob_dst), DerivedMesh *dm_src, DerivedMesh *dm_dst, Mesh *me_dst,
const int dtdata_type, const bool dirty_nors_dst, const bool use_split_nors_src, const float split_angle_src)
{
if (dtdata_type == DT_TYPE_LNOR) {
/* Compute custom normals into regular loop normals, which will be used for the transfer. */
MVert *verts_dst = dm_dst ? dm_dst->getVertArray(dm_dst) : me_dst->mvert;
const int num_verts_dst = dm_dst ? dm_dst->getNumVerts(dm_dst) : me_dst->totvert;
MEdge *edges_dst = dm_dst ? dm_dst->getEdgeArray(dm_dst) : me_dst->medge;
const int num_edges_dst = dm_dst ? dm_dst->getNumEdges(dm_dst) : me_dst->totedge;
MPoly *polys_dst = dm_dst ? dm_dst->getPolyArray(dm_dst) : me_dst->mpoly;
const int num_polys_dst = dm_dst ? dm_dst->getNumPolys(dm_dst) : me_dst->totpoly;
MLoop *loops_dst = dm_dst ? dm_dst->getLoopArray(dm_dst) : me_dst->mloop;
const int num_loops_dst = dm_dst ? dm_dst->getNumLoops(dm_dst) : me_dst->totloop;
CustomData *pdata_dst = dm_dst ? dm_dst->getPolyDataLayout(dm_dst) : &me_dst->pdata;
CustomData *ldata_dst = dm_dst ? dm_dst->getLoopDataLayout(dm_dst) : &me_dst->ldata;
const bool use_split_nors_dst = (me_dst->flag & ME_AUTOSMOOTH) != 0;
const float split_angle_dst = me_dst->smoothresh;
dm_src->calcLoopNormals(dm_src, use_split_nors_src, split_angle_src);
if (dm_dst) {
dm_dst->calcLoopNormals(dm_dst, use_split_nors_dst, split_angle_dst);
}
else {
float (*poly_nors_dst)[3];
float (*loop_nors_dst)[3];
short (*custom_nors_dst)[2] = CustomData_get_layer(ldata_dst, CD_CUSTOMLOOPNORMAL);
/* Cache poly nors into a temp CDLayer. */
poly_nors_dst = CustomData_get_layer(pdata_dst, CD_NORMAL);
if (dirty_nors_dst || !poly_nors_dst) {
if (!poly_nors_dst) {
poly_nors_dst = CustomData_add_layer(pdata_dst, CD_NORMAL, CD_CALLOC, NULL, num_polys_dst);
CustomData_set_layer_flag(pdata_dst, CD_NORMAL, CD_FLAG_TEMPORARY);
}
BKE_mesh_calc_normals_poly(verts_dst, NULL, num_verts_dst, loops_dst, polys_dst,
num_loops_dst, num_polys_dst, poly_nors_dst, true);
}
/* Cache loop nors into a temp CDLayer. */
loop_nors_dst = CustomData_get_layer(ldata_dst, CD_NORMAL);
if (dirty_nors_dst || loop_nors_dst) {
if (!loop_nors_dst) {
loop_nors_dst = CustomData_add_layer(ldata_dst, CD_NORMAL, CD_CALLOC, NULL, num_loops_dst);
CustomData_set_layer_flag(ldata_dst, CD_NORMAL, CD_FLAG_TEMPORARY);
}
BKE_mesh_normals_loop_split(verts_dst, num_verts_dst, edges_dst, num_edges_dst,
loops_dst, loop_nors_dst, num_loops_dst,
polys_dst, (const float (*)[3])poly_nors_dst, num_polys_dst,
use_split_nors_dst, split_angle_dst, NULL, custom_nors_dst, NULL);
}
}
}
}
static void data_transfer_dtdata_type_postprocess(
Object *UNUSED(ob_src), Object *UNUSED(ob_dst), DerivedMesh *UNUSED(dm_src), DerivedMesh *dm_dst, Mesh *me_dst,
const int dtdata_type, const bool changed)
{
if (dtdata_type == DT_TYPE_LNOR) {
/* Bake edited destination loop normals into custom normals again. */
MVert *verts_dst = dm_dst ? dm_dst->getVertArray(dm_dst) : me_dst->mvert;
const int num_verts_dst = dm_dst ? dm_dst->getNumVerts(dm_dst) : me_dst->totvert;
MEdge *edges_dst = dm_dst ? dm_dst->getEdgeArray(dm_dst) : me_dst->medge;
const int num_edges_dst = dm_dst ? dm_dst->getNumEdges(dm_dst) : me_dst->totedge;
MPoly *polys_dst = dm_dst ? dm_dst->getPolyArray(dm_dst) : me_dst->mpoly;
const int num_polys_dst = dm_dst ? dm_dst->getNumPolys(dm_dst) : me_dst->totpoly;
MLoop *loops_dst = dm_dst ? dm_dst->getLoopArray(dm_dst) : me_dst->mloop;
const int num_loops_dst = dm_dst ? dm_dst->getNumLoops(dm_dst) : me_dst->totloop;
CustomData *pdata_dst = dm_dst ? dm_dst->getPolyDataLayout(dm_dst) : &me_dst->pdata;
CustomData *ldata_dst = dm_dst ? dm_dst->getLoopDataLayout(dm_dst) : &me_dst->ldata;
const float (*poly_nors_dst)[3] = CustomData_get_layer(pdata_dst, CD_NORMAL);
float (*loop_nors_dst)[3] = CustomData_get_layer(ldata_dst, CD_NORMAL);
short (*custom_nors_dst)[2] = CustomData_get_layer(ldata_dst, CD_CUSTOMLOOPNORMAL);
BLI_assert(poly_nors_dst);
if (!changed) {
return;
}
if (!custom_nors_dst) {
custom_nors_dst = CustomData_add_layer(ldata_dst, CD_CUSTOMLOOPNORMAL, CD_CALLOC, NULL, num_loops_dst);
}
/* Note loop_nors_dst contains our custom normals as transferred from source... */
BKE_mesh_normals_loop_custom_set(verts_dst, num_verts_dst, edges_dst, num_edges_dst,
loops_dst, loop_nors_dst, num_loops_dst,
polys_dst, poly_nors_dst, num_polys_dst,
custom_nors_dst);
}
}
/* ********** */
static MeshRemapIslandsCalc data_transfer_get_loop_islands_generator(const int cddata_type)
{
switch (cddata_type) {
case CD_FAKE_UV:
return BKE_mesh_calc_islands_loop_poly_edgeseam;
default:
break;
}
return NULL;
}
float data_transfer_interp_float_do(
const int mix_mode, const float val_dst, const float val_src, const float mix_factor)
{
float val_ret;
if (((mix_mode == CDT_MIX_REPLACE_ABOVE_THRESHOLD && (val_dst < mix_factor)) ||
(mix_mode == CDT_MIX_REPLACE_BELOW_THRESHOLD && (val_dst > mix_factor))))
{
return val_dst; /* Do not affect destination. */
}
switch (mix_mode) {
case CDT_MIX_REPLACE_ABOVE_THRESHOLD:
case CDT_MIX_REPLACE_BELOW_THRESHOLD:
return val_src;
case CDT_MIX_MIX:
val_ret = (val_dst + val_src) * 0.5f;
break;
case CDT_MIX_ADD:
val_ret = val_dst + val_src;
break;
case CDT_MIX_SUB:
val_ret = val_dst - val_src;
break;
case CDT_MIX_MUL:
val_ret = val_dst * val_src;
break;
case CDT_MIX_TRANSFER:
default:
val_ret = val_src;
break;
}
return interpf(val_ret, val_dst, mix_factor);
}
static void data_transfer_interp_char(
const CustomDataTransferLayerMap *laymap, void *dest,
const void **sources, const float *weights, const int count, const float mix_factor)
{
const char **data_src = (const char **)sources;
char *data_dst = (char *)dest;
const int mix_mode = laymap->mix_mode;
float val_src = 0.0f;
const float val_dst = (float)(*data_dst) / 255.0f;
int i;
for (i = count; i--;) {
val_src += ((float)(*data_src[i]) / 255.0f) * weights[i];
}
val_src = data_transfer_interp_float_do(mix_mode, val_dst, val_src, mix_factor);
CLAMP(val_src, 0.0f, 1.0f);
*data_dst = (char)(val_src * 255.0f);
}
/* Helpers to match sources and destinations data layers (also handles 'conversions' in CD_FAKE cases). */
void data_transfer_layersmapping_add_item(
ListBase *r_map, const int cddata_type, const int mix_mode, const float mix_factor, const float *mix_weights,
const void *data_src, void *data_dst, const int data_src_n, const int data_dst_n,
const size_t elem_size, const size_t data_size, const size_t data_offset, const uint64_t data_flag,
cd_datatransfer_interp interp, void *interp_data)
{
CustomDataTransferLayerMap *item = MEM_mallocN(sizeof(*item), __func__);
BLI_assert(data_dst != NULL);
item->data_type = cddata_type;
item->mix_mode = mix_mode;
item->mix_factor = mix_factor;
item->mix_weights = mix_weights;
item->data_src = data_src;
item->data_dst = data_dst;
item->data_src_n = data_src_n;
item->data_dst_n = data_dst_n;
item->elem_size = elem_size;
item->data_size = data_size;
item->data_offset = data_offset;
item->data_flag = data_flag;
item->interp = interp;
item->interp_data = interp_data;
BLI_addtail(r_map, item);
}
static void data_transfer_layersmapping_add_item_cd(
ListBase *r_map, const int cddata_type, const int mix_mode, const float mix_factor, const float *mix_weights,
void *data_src, void *data_dst, cd_datatransfer_interp interp, void *interp_data)
{
uint64_t data_flag = 0;
if (cddata_type == CD_FREESTYLE_EDGE) {
data_flag = FREESTYLE_EDGE_MARK;
}
else if (cddata_type == CD_FREESTYLE_FACE) {
data_flag = FREESTYLE_FACE_MARK;
}
data_transfer_layersmapping_add_item(
r_map, cddata_type, mix_mode, mix_factor, mix_weights, data_src, data_dst,
0, 0, 0, 0, 0, data_flag, interp, interp_data);
}
/* Note: All those layer mapping handlers return false *only* if they were given invalid parameters.
* This means that even if they do nothing, they will return true if all given parameters were OK.
* Also, r_map may be NULL, in which case they will 'only' create/delete destination layers according
* to given parameters.
*/
static bool data_transfer_layersmapping_cdlayers_multisrc_to_dst(
ListBase *r_map, const int cddata_type, const int mix_mode, const float mix_factor, const float *mix_weights,
const int num_elem_dst, const bool use_create, const bool use_delete,
CustomData *cd_src, CustomData *cd_dst, const bool use_dupref_dst,
const int tolayers, bool *use_layers_src, const int num_layers_src,
cd_datatransfer_interp interp, void *interp_data)
{
void *data_src, *data_dst = NULL;
int idx_src = num_layers_src;
int idx_dst, tot_dst = CustomData_number_of_layers(cd_dst, cddata_type);
bool *data_dst_to_delete = NULL;
if (!use_layers_src) {
/* No source at all, we can only delete all dest if requested... */
if (use_delete) {
idx_dst = tot_dst;
while (idx_dst--) {
CustomData_free_layer(cd_dst, cddata_type, num_elem_dst, idx_dst);
}
}
return true;
}
switch (tolayers) {
case DT_LAYERS_INDEX_DST:
idx_dst = tot_dst;
/* Find last source actually used! */
while (idx_src-- && !use_layers_src[idx_src]);
idx_src++;
if (idx_dst < idx_src) {
if (!use_create) {
return true;
}
/* Create as much data layers as necessary! */
for (; idx_dst < idx_src; idx_dst++) {
CustomData_add_layer(cd_dst, cddata_type, CD_CALLOC, NULL, num_elem_dst);
}
}
else if (use_delete && idx_dst > idx_src) {
while (idx_dst-- > idx_src) {
CustomData_free_layer(cd_dst, cddata_type, num_elem_dst, idx_dst);
}
}
if (r_map) {
while (idx_src--) {
if (!use_layers_src[idx_src]) {
continue;
}
data_src = CustomData_get_layer_n(cd_src, cddata_type, idx_src);
/* If dest is a derivedmesh, we do not want to overwrite cdlayers of org mesh! */
if (use_dupref_dst) {
data_dst = CustomData_duplicate_referenced_layer_n(cd_dst, cddata_type, idx_src, num_elem_dst);
}
else {
data_dst = CustomData_get_layer_n(cd_dst, cddata_type, idx_src);
}
data_transfer_layersmapping_add_item_cd(r_map, cddata_type, mix_mode, mix_factor, mix_weights,
data_src, data_dst, interp, interp_data);
}
}
break;
case DT_LAYERS_NAME_DST:
if (use_delete) {
if (tot_dst) {
data_dst_to_delete = MEM_mallocN(sizeof(*data_dst_to_delete) * (size_t)tot_dst, __func__);
memset(data_dst_to_delete, true, sizeof(*data_dst_to_delete) * (size_t)tot_dst);
}
}
while (idx_src--) {
const char *name;
if (!use_layers_src[idx_src]) {
continue;
}
name = CustomData_get_layer_name(cd_src, cddata_type, idx_src);
data_src = CustomData_get_layer_n(cd_src, cddata_type, idx_src);
if ((idx_dst = CustomData_get_named_layer(cd_dst, cddata_type, name)) == -1) {
if (!use_create) {
if (r_map) {
BLI_freelistN(r_map);
}
return true;
}
CustomData_add_layer_named(cd_dst, cddata_type, CD_CALLOC, NULL, num_elem_dst, name);
idx_dst = CustomData_get_named_layer(cd_dst, cddata_type, name);
}
else if (data_dst_to_delete) {
data_dst_to_delete[idx_dst] = false;
}
if (r_map) {
/* If dest is a derivedmesh, we do not want to overwrite cdlayers of org mesh! */
if (use_dupref_dst) {
data_dst = CustomData_duplicate_referenced_layer_n(cd_dst, cddata_type, idx_dst, num_elem_dst);
}
else {
data_dst = CustomData_get_layer_n(cd_dst, cddata_type, idx_dst);
}
data_transfer_layersmapping_add_item_cd(r_map, cddata_type, mix_mode, mix_factor, mix_weights,
data_src, data_dst, interp, interp_data);
}
}
if (data_dst_to_delete) {
/* Note: This won't affect newly created layers, if any, since tot_dst has not been updated!
* Also, looping backward ensures us we do not suffer from index shifting when deleting a layer.
*/
for (idx_dst = tot_dst; idx_dst--;) {
if (data_dst_to_delete[idx_dst]) {
CustomData_free_layer(cd_dst, cddata_type, num_elem_dst, idx_dst);
}
}
MEM_freeN(data_dst_to_delete);
}
break;
default:
return false;
}
return true;
}
static bool data_transfer_layersmapping_cdlayers(
ListBase *r_map, const int cddata_type, const int mix_mode, const float mix_factor, const float *mix_weights,
const int num_elem_dst, const bool use_create, const bool use_delete,
CustomData *cd_src, CustomData *cd_dst, const bool use_dupref_dst,
const int fromlayers, const int tolayers,
cd_datatransfer_interp interp, void *interp_data)
{
int idx_src, idx_dst;
void *data_src, *data_dst = NULL;
if (CustomData_layertype_is_singleton(cddata_type)) {
if (!(data_src = CustomData_get_layer(cd_src, cddata_type))) {
if (use_delete) {
CustomData_free_layer(cd_dst, cddata_type, num_elem_dst, 0);
}
return true;
}
data_dst = CustomData_get_layer(cd_dst, cddata_type);
if (!data_dst) {
if (!use_create) {
return true;
}
data_dst = CustomData_add_layer(cd_dst, cddata_type, CD_CALLOC, NULL, num_elem_dst);
}
else if (use_dupref_dst && r_map) {
/* If dest is a derivedmesh, we do not want to overwrite cdlayers of org mesh! */
data_dst = CustomData_duplicate_referenced_layer(cd_dst, cddata_type, num_elem_dst);
}
if (r_map) {
data_transfer_layersmapping_add_item_cd(r_map, cddata_type, mix_mode, mix_factor, mix_weights,
data_src, data_dst, interp, interp_data);
}
}
else if (fromlayers == DT_LAYERS_ACTIVE_SRC || fromlayers >= 0) {
/* Note: use_delete has not much meaning in this case, ignored. */
if (fromlayers >= 0) { /* Real-layer index */
idx_src = fromlayers;
}
else {
if ((idx_src = CustomData_get_active_layer(cd_src, cddata_type)) == -1) {
return true;
}
}
data_src = CustomData_get_layer_n(cd_src, cddata_type, idx_src);
if (!data_src) {
return true;
}
if (tolayers >= 0) { /* Real-layer index */
idx_dst = tolayers;
/* If dest is a derivedmesh, we do not want to overwrite cdlayers of org mesh! */
if (use_dupref_dst && r_map) {
data_dst = CustomData_duplicate_referenced_layer_n(cd_dst, cddata_type, idx_dst, num_elem_dst);
}
else {
data_dst = CustomData_get_layer_n(cd_dst, cddata_type, idx_dst);
}
}
else if (tolayers == DT_LAYERS_ACTIVE_DST) {
if ((idx_dst = CustomData_get_active_layer(cd_dst, cddata_type)) == -1) {
if (!use_create) {
return true;
}
data_dst = CustomData_add_layer(cd_dst, cddata_type, CD_CALLOC, NULL, num_elem_dst);
}
else {
/* If dest is a derivedmesh, we do not want to overwrite cdlayers of org mesh! */
if (use_dupref_dst && r_map) {
data_dst = CustomData_duplicate_referenced_layer_n(cd_dst, cddata_type, idx_dst, num_elem_dst);
}
else {
data_dst = CustomData_get_layer_n(cd_dst, cddata_type, idx_dst);
}
}
}
else if (tolayers == DT_LAYERS_INDEX_DST) {
int num = CustomData_number_of_layers(cd_dst, cddata_type);
idx_dst = idx_src;
if (num <= idx_dst) {
if (!use_create) {
return true;
}
/* Create as much data layers as necessary! */
for (; num <= idx_dst; num++) {
CustomData_add_layer(cd_dst, cddata_type, CD_CALLOC, NULL, num_elem_dst);
}
}
/* If dest is a derivedmesh, we do not want to overwrite cdlayers of org mesh! */
if (use_dupref_dst && r_map) {
data_dst = CustomData_duplicate_referenced_layer_n(cd_dst, cddata_type, idx_dst, num_elem_dst);
}
else {
data_dst = CustomData_get_layer_n(cd_dst, cddata_type, idx_dst);
}
}
else if (tolayers == DT_LAYERS_NAME_DST) {
const char *name = CustomData_get_layer_name(cd_src, cddata_type, idx_src);
if ((idx_dst = CustomData_get_named_layer(cd_dst, cddata_type, name)) == -1) {
if (!use_create) {
return true;
}
CustomData_add_layer_named(cd_dst, cddata_type, CD_CALLOC, NULL, num_elem_dst, name);
idx_dst = CustomData_get_named_layer(cd_dst, cddata_type, name);
}
/* If dest is a derivedmesh, we do not want to overwrite cdlayers of org mesh! */
if (use_dupref_dst && r_map) {
data_dst = CustomData_duplicate_referenced_layer_n(cd_dst, cddata_type, idx_dst, num_elem_dst);
}
else {
data_dst = CustomData_get_layer_n(cd_dst, cddata_type, idx_dst);
}
}
else {
return false;
}
if (!data_dst) {
return false;
}
if (r_map) {
data_transfer_layersmapping_add_item_cd(
r_map, cddata_type, mix_mode, mix_factor, mix_weights, data_src, data_dst, interp, interp_data);
}
}
else if (fromlayers == DT_LAYERS_ALL_SRC) {
int num_src = CustomData_number_of_layers(cd_src, cddata_type);
bool *use_layers_src = num_src ? MEM_mallocN(sizeof(*use_layers_src) * (size_t)num_src, __func__) : NULL;
bool ret;
if (use_layers_src) {
memset(use_layers_src, true, sizeof(*use_layers_src) * num_src);
}
ret = data_transfer_layersmapping_cdlayers_multisrc_to_dst(
r_map, cddata_type, mix_mode, mix_factor, mix_weights,
num_elem_dst, use_create, use_delete, cd_src, cd_dst, use_dupref_dst,
tolayers, use_layers_src, num_src,
interp, interp_data);
if (use_layers_src) {
MEM_freeN(use_layers_src);
}
return ret;
}
else {
return false;
}
return true;
}
static bool data_transfer_layersmapping_generate(
ListBase *r_map, Object *ob_src, Object *ob_dst, DerivedMesh *dm_src, DerivedMesh *dm_dst, Mesh *me_dst,
const int elem_type, int cddata_type, int mix_mode, float mix_factor, const float *mix_weights,
const int num_elem_dst, const bool use_create, const bool use_delete, const int fromlayers, const int tolayers,
SpaceTransform *space_transform)
{
CustomData *cd_src, *cd_dst;
cd_datatransfer_interp interp = NULL;
void *interp_data = NULL;
if (elem_type == ME_VERT) {
if (!(cddata_type & CD_FAKE)) {
cd_src = dm_src->getVertDataLayout(dm_src);
cd_dst = dm_dst ? dm_dst->getVertDataLayout(dm_dst) : &me_dst->vdata;
if (!data_transfer_layersmapping_cdlayers(r_map, cddata_type, mix_mode, mix_factor, mix_weights,
num_elem_dst, use_create, use_delete,
cd_src, cd_dst, dm_dst != NULL,
fromlayers, tolayers,
interp, interp_data))
{
/* We handle specific source selection cases here. */
return false;
}
return true;
}
else if (cddata_type == CD_FAKE_BWEIGHT) {
const size_t elem_size = sizeof(*((MVert *)NULL));
const size_t data_size = sizeof(((MVert *)NULL)->bweight);
const size_t data_offset = offsetof(MVert, bweight);
const uint64_t data_flag = 0;
if (!(dm_src->cd_flag & ME_CDFLAG_VERT_BWEIGHT)) {
if (use_delete && !dm_dst) {
me_dst->cd_flag &= ~ME_CDFLAG_VERT_BWEIGHT;
}
return true;
}
if (dm_dst) {
dm_dst->cd_flag |= ME_CDFLAG_VERT_BWEIGHT;
}
else {
me_dst->cd_flag |= ME_CDFLAG_VERT_BWEIGHT;
}
if (r_map) {
data_transfer_layersmapping_add_item(r_map, cddata_type, mix_mode, mix_factor, mix_weights,
dm_src->getVertArray(dm_src),
dm_dst ? dm_dst->getVertArray(dm_dst) : me_dst->mvert,
dm_src->getNumVerts(dm_src),
dm_dst ? dm_dst->getNumVerts(dm_dst) : me_dst->totvert,
elem_size, data_size, data_offset, data_flag,
data_transfer_interp_char, interp_data);
}
return true;
}
else if (cddata_type == CD_FAKE_MDEFORMVERT) {
bool ret;
cd_src = dm_src->getVertDataLayout(dm_src);
cd_dst = dm_dst ? dm_dst->getVertDataLayout(dm_dst) : &me_dst->vdata;
ret = data_transfer_layersmapping_vgroups(r_map, mix_mode, mix_factor, mix_weights,
num_elem_dst, use_create, use_delete,
ob_src, ob_dst, cd_src, cd_dst, dm_dst != NULL,
fromlayers, tolayers);
/* Mesh stores its dvert in a specific pointer too. :( */
me_dst->dvert = CustomData_get_layer(&me_dst->vdata, CD_MDEFORMVERT);
return ret;
}
else if (cddata_type == CD_FAKE_SHAPEKEY) {
/* TODO: leaving shapekeys asside for now, quite specific case, since we can't access them from MVert :/ */
return false;
}
}
else if (elem_type == ME_EDGE) {
if (!(cddata_type & CD_FAKE)) { /* Unused for edges, currently... */
cd_src = dm_src->getEdgeDataLayout(dm_src);
cd_dst = dm_dst ? dm_dst->getEdgeDataLayout(dm_dst) : &me_dst->edata;
if (!data_transfer_layersmapping_cdlayers(r_map, cddata_type, mix_mode, mix_factor, mix_weights,
num_elem_dst, use_create, use_delete,
cd_src, cd_dst, dm_dst != NULL,
fromlayers, tolayers,
interp, interp_data))
{
/* We handle specific source selection cases here. */
return false;
}
return true;
}
else if (cddata_type == CD_FAKE_CREASE) {
const size_t elem_size = sizeof(*((MEdge *)NULL));
const size_t data_size = sizeof(((MEdge *)NULL)->crease);
const size_t data_offset = offsetof(MEdge, crease);
const uint64_t data_flag = 0;
if (!(dm_src->cd_flag & ME_CDFLAG_EDGE_CREASE)) {
if (use_delete && !dm_dst) {
me_dst->cd_flag &= ~ME_CDFLAG_EDGE_CREASE;
}
return true;
}
if (dm_dst) {
dm_dst->cd_flag |= ME_CDFLAG_EDGE_CREASE;
}
else {
me_dst->cd_flag |= ME_CDFLAG_EDGE_CREASE;
}
if (r_map) {
data_transfer_layersmapping_add_item(r_map, cddata_type, mix_mode, mix_factor, mix_weights,
dm_src->getEdgeArray(dm_src),
dm_dst ? dm_dst->getEdgeArray(dm_dst) : me_dst->medge,
dm_src->getNumEdges(dm_src),
dm_dst ? dm_dst->getNumEdges(dm_dst) : me_dst->totedge,
elem_size, data_size, data_offset, data_flag,
data_transfer_interp_char, interp_data);
}
return true;
}
else if (cddata_type == CD_FAKE_BWEIGHT) {
const size_t elem_size = sizeof(*((MEdge *)NULL));
const size_t data_size = sizeof(((MEdge *)NULL)->bweight);
const size_t data_offset = offsetof(MEdge, bweight);
const uint64_t data_flag = 0;
if (!(dm_src->cd_flag & ME_CDFLAG_EDGE_BWEIGHT)) {
if (use_delete && !dm_dst) {
me_dst->cd_flag &= ~ME_CDFLAG_EDGE_BWEIGHT;
}
return true;
}
if (dm_dst) {
dm_dst->cd_flag |= ME_CDFLAG_EDGE_BWEIGHT;
}
else {
me_dst->cd_flag |= ME_CDFLAG_EDGE_BWEIGHT;
}
if (r_map) {
data_transfer_layersmapping_add_item(r_map, cddata_type, mix_mode, mix_factor, mix_weights,
dm_src->getEdgeArray(dm_src),
dm_dst ? dm_dst->getEdgeArray(dm_dst) : me_dst->medge,
dm_src->getNumEdges(dm_src),
dm_dst ? dm_dst->getNumEdges(dm_dst) : me_dst->totedge,
elem_size, data_size, data_offset, data_flag,
data_transfer_interp_char, interp_data);
}
return true;
}
else if (r_map && ELEM(cddata_type, CD_FAKE_SHARP, CD_FAKE_SEAM)) {
const size_t elem_size = sizeof(*((MEdge *)NULL));
const size_t data_size = sizeof(((MEdge *)NULL)->flag);
const size_t data_offset = offsetof(MEdge, flag);
const uint64_t data_flag = (cddata_type == CD_FAKE_SHARP) ? ME_SHARP : ME_SEAM;
data_transfer_layersmapping_add_item(
r_map, cddata_type, mix_mode, mix_factor, mix_weights,
dm_src->getEdgeArray(dm_src),
dm_dst ? dm_dst->getEdgeArray(dm_dst) : me_dst->medge,
dm_src->getNumEdges(dm_src),
dm_dst ? dm_dst->getNumEdges(dm_dst) : me_dst->totedge,
elem_size, data_size, data_offset, data_flag, NULL, interp_data);
return true;
}
else {
return false;
}
}
else if (elem_type == ME_LOOP) {
if (cddata_type == CD_FAKE_UV) {
cddata_type = CD_MLOOPUV;
}
else if (cddata_type == CD_FAKE_LNOR) {
/* Preprocess should have generated it, Postprocess will convert it back to CD_CUSTOMLOOPNORMAL. */
cddata_type = CD_NORMAL;
interp_data = space_transform;
interp = customdata_data_transfer_interp_normal_normals;
}
if (!(cddata_type & CD_FAKE)) {
cd_src = dm_src->getLoopDataLayout(dm_src);
cd_dst = dm_dst ? dm_dst->getLoopDataLayout(dm_dst) : &me_dst->ldata;
if (!data_transfer_layersmapping_cdlayers(
r_map, cddata_type, mix_mode, mix_factor, mix_weights,
num_elem_dst, use_create, use_delete, cd_src, cd_dst, dm_dst != NULL,
fromlayers, tolayers,
interp, interp_data))
{
/* We handle specific source selection cases here. */
return false;
}
return true;
}
else {
return false;
}
}
else if (elem_type == ME_POLY) {
if (cddata_type == CD_FAKE_UV) {
cddata_type = CD_MTEXPOLY;
}
if (!(cddata_type & CD_FAKE)) {
cd_src = dm_src->getPolyDataLayout(dm_src);
cd_dst = dm_dst ? dm_dst->getPolyDataLayout(dm_dst) : &me_dst->pdata;
if (!data_transfer_layersmapping_cdlayers(
r_map, cddata_type, mix_mode, mix_factor, mix_weights,
num_elem_dst, use_create, use_delete, cd_src, cd_dst, dm_dst != NULL,
fromlayers, tolayers,
interp, interp_data))
{
/* We handle specific source selection cases here. */
return false;
}
return true;
}
else if (r_map && cddata_type == CD_FAKE_SHARP) {
const size_t elem_size = sizeof(*((MPoly *)NULL));
const size_t data_size = sizeof(((MPoly *)NULL)->flag);
const size_t data_offset = offsetof(MPoly, flag);
const uint64_t data_flag = ME_SMOOTH;
data_transfer_layersmapping_add_item(
r_map, cddata_type, mix_mode, mix_factor, mix_weights,
dm_src->getPolyArray(dm_src),
dm_dst ? dm_dst->getPolyArray(dm_dst) : me_dst->mpoly,
dm_src->getNumPolys(dm_src),
dm_dst ? dm_dst->getNumPolys(dm_dst) : me_dst->totpoly,
elem_size, data_size, data_offset, data_flag, NULL, interp_data);
return true;
}
else {
return false;
}
}
return false;
}
/**
* Transfer data *layout* of selected types from source to destination object.
* By default, it only creates new data layers if needed on \a ob_dst.
* If \a use_delete is true, it will also delete data layers on \a ob_dst that do not match those from \a ob_src,
* to get (as much as possible) exact copy of source data layout.
*/
void BKE_object_data_transfer_layout(
Scene *scene, Object *ob_src, Object *ob_dst, const int data_types, const bool use_delete,
const int fromlayers_select[DT_MULTILAYER_INDEX_MAX], const int tolayers_select[DT_MULTILAYER_INDEX_MAX])
{
DerivedMesh *dm_src;
Mesh *me_dst;
int i;
const bool use_create = true; /* We always create needed layers here. */
CustomDataMask dm_src_mask = CD_MASK_BAREMESH;
BLI_assert((ob_src != ob_dst) && (ob_src->type == OB_MESH) && (ob_dst->type == OB_MESH));
me_dst = ob_dst->data;
/* Get source DM.*/
dm_src_mask |= BKE_object_data_transfer_dttypes_to_cdmask(data_types);
dm_src = mesh_get_derived_final(scene, ob_src, dm_src_mask);
if (!dm_src) {
return;
}
/* Check all possible data types. */
for (i = 0; i < DT_TYPE_MAX; i++) {
const int dtdata_type = 1 << i;
int cddata_type;
int fromlayers, tolayers, fromto_idx;
if (!(data_types & dtdata_type)) {
continue;
}
cddata_type = BKE_object_data_transfer_dttype_to_cdtype(dtdata_type);
fromto_idx = BKE_object_data_transfer_dttype_to_srcdst_index(dtdata_type);
if (fromto_idx != DT_MULTILAYER_INDEX_INVALID) {
fromlayers = fromlayers_select[fromto_idx];
tolayers = tolayers_select[fromto_idx];
}
else {
fromlayers = tolayers = 0;
}
if (DT_DATATYPE_IS_VERT(dtdata_type)) {
const int num_elem_dst = me_dst->totvert;
data_transfer_layersmapping_generate(
NULL, ob_src, ob_dst, dm_src, NULL, me_dst, ME_VERT, cddata_type, 0, 0.0f, NULL,
num_elem_dst, use_create, use_delete, fromlayers, tolayers, NULL);
}
if (DT_DATATYPE_IS_EDGE(dtdata_type)) {
const int num_elem_dst = me_dst->totedge;
data_transfer_layersmapping_generate(
NULL, ob_src, ob_dst, dm_src, NULL, me_dst, ME_EDGE, cddata_type, 0, 0.0f, NULL,
num_elem_dst, use_create, use_delete, fromlayers, tolayers, NULL);
}
if (DT_DATATYPE_IS_LOOP(dtdata_type)) {
const int num_elem_dst = me_dst->totloop;
data_transfer_layersmapping_generate(
NULL, ob_src, ob_dst, dm_src, NULL, me_dst, ME_LOOP, cddata_type, 0, 0.0f, NULL,
num_elem_dst, use_create, use_delete, fromlayers, tolayers, NULL);
}
if (DT_DATATYPE_IS_POLY(dtdata_type)) {
const int num_elem_dst = me_dst->totpoly;
data_transfer_layersmapping_generate(
NULL, ob_src, ob_dst, dm_src, NULL, me_dst, ME_POLY, cddata_type, 0, 0.0f, NULL,
num_elem_dst, use_create, use_delete, fromlayers, tolayers, NULL);
}
}
}
bool BKE_object_data_transfer_dm(
Scene *scene, Object *ob_src, Object *ob_dst, DerivedMesh *dm_dst, const int data_types, bool use_create,
const int map_vert_mode, const int map_edge_mode, const int map_loop_mode, const int map_poly_mode,
SpaceTransform *space_transform, const bool auto_transform,
const float max_distance, const float ray_radius, const float islands_handling_precision,
const int fromlayers_select[DT_MULTILAYER_INDEX_MAX], const int tolayers_select[DT_MULTILAYER_INDEX_MAX],
const int mix_mode, const float mix_factor, const char *vgroup_name, const bool invert_vgroup,
ReportList *reports)
{
#define VDATA 0
#define EDATA 1
#define LDATA 2
#define PDATA 3
#define DATAMAX 4
SpaceTransform auto_space_transform;
DerivedMesh *dm_src;
Mesh *me_dst, *me_src;
bool dirty_nors_dst = true; /* Assumed always true if not using a dm as destination. */
int i;
MDeformVert *mdef = NULL;
int vg_idx = -1;
float *weights[DATAMAX] = {NULL};
MeshPairRemap geom_map[DATAMAX] = {{0}};
bool geom_map_init[DATAMAX] = {0};
ListBase lay_map = {NULL};
bool changed = false;
const bool use_delete = false; /* We never delete data layers from destination here. */
CustomDataMask dm_src_mask = CD_MASK_BAREMESH;
BLI_assert((ob_src != ob_dst) && (ob_src->type == OB_MESH) && (ob_dst->type == OB_MESH));
me_dst = ob_dst->data;
me_src = ob_src->data;
if (dm_dst) {
dirty_nors_dst = (dm_dst->dirty & DM_DIRTY_NORMALS) != 0;
use_create = false; /* Never create needed custom layers on DM (modifier case). */
}
if (vgroup_name) {
if (dm_dst) {
mdef = dm_dst->getVertDataArray(dm_dst, CD_MDEFORMVERT);
}
else {
mdef = CustomData_get_layer(&me_dst->vdata, CD_MDEFORMVERT);
}
if (mdef) {
vg_idx = defgroup_name_index(ob_dst, vgroup_name);
}
}
/* Get source DM.*/
dm_src_mask |= BKE_object_data_transfer_dttypes_to_cdmask(data_types);
/* XXX Hack! In case this is being evaluated from dm stack, we cannot compute final dm,
* can lead to infinite recursion in case of dependency cycles of DataTransfer modifiers...
* Issue is, this means we cannot be sure to have requested cd layers in source.
*
* Also, we need to make a local copy of dm_src, otherwise we may end with concurrent creation
* of data in it (multi-threaded evaluation of the modifier stack, see T46672).
*/
dm_src = dm_dst ? ob_src->derivedFinal : mesh_get_derived_final(scene, ob_src, dm_src_mask);
if (!dm_src) {
return changed;
}
dm_src = CDDM_copy(dm_src);
if (auto_transform) {
MVert *verts_dst = dm_dst ? dm_dst->getVertArray(dm_dst) : me_dst->mvert;
const int num_verts_dst = dm_dst ? dm_dst->getNumVerts(dm_dst) : me_dst->totvert;
if (space_transform == NULL) {
space_transform = &auto_space_transform;
}
BKE_mesh_remap_find_best_match_from_dm(verts_dst, num_verts_dst, dm_src, space_transform);
}
/* Check all possible data types.
* Note item mappings and dest mix weights are cached. */
for (i = 0; i < DT_TYPE_MAX; i++) {
const int dtdata_type = 1 << i;
int cddata_type;
int fromlayers, tolayers, fromto_idx;
if (!(data_types & dtdata_type)) {
continue;
}
data_transfer_dtdata_type_preprocess(ob_src, ob_dst, dm_src, dm_dst, me_dst,
dtdata_type, dirty_nors_dst,
(me_src->flag & ME_AUTOSMOOTH) != 0, me_src->smoothresh);
cddata_type = BKE_object_data_transfer_dttype_to_cdtype(dtdata_type);
fromto_idx = BKE_object_data_transfer_dttype_to_srcdst_index(dtdata_type);
if (fromto_idx != DT_MULTILAYER_INDEX_INVALID) {
fromlayers = fromlayers_select[fromto_idx];
tolayers = tolayers_select[fromto_idx];
}
else {
fromlayers = tolayers = 0;
}
if (DT_DATATYPE_IS_VERT(dtdata_type)) {
MVert *verts_dst = dm_dst ? dm_dst->getVertArray(dm_dst) : me_dst->mvert;
const int num_verts_dst = dm_dst ? dm_dst->getNumVerts(dm_dst) : me_dst->totvert;
if (!geom_map_init[VDATA]) {
const int num_verts_src = dm_src->getNumVerts(dm_src);
if ((map_vert_mode == MREMAP_MODE_TOPOLOGY) && (num_verts_dst != num_verts_src)) {
BKE_report(reports, RPT_ERROR,
"Source and destination meshes do not have the same amount of vertices, "
"'Topology' mapping cannot be used in this case");
continue;
}
if ((map_vert_mode & MREMAP_USE_EDGE) && (dm_src->getNumEdges(dm_src) == 0)) {
BKE_report(reports, RPT_ERROR,
"Source mesh doesn't have any edges, "
"None of the 'Edge' mappings can be used in this case");
continue;
}
if ((map_vert_mode & MREMAP_USE_POLY) && (dm_src->getNumPolys(dm_src) == 0)) {
BKE_report(reports, RPT_ERROR,
"Source mesh doesn't have any faces, "
"None of the 'Face' mappings can be used in this case");
continue;
}
if (ELEM(0, num_verts_dst, num_verts_src)) {
BKE_report(reports, RPT_ERROR,
"Source or destination meshes do not have any vertices, cannot transfer vertex data");
continue;
}
BKE_mesh_remap_calc_verts_from_dm(
map_vert_mode, space_transform, max_distance, ray_radius,
verts_dst, num_verts_dst, dirty_nors_dst, dm_src, &geom_map[VDATA]);
geom_map_init[VDATA] = true;
}
if (mdef && vg_idx != -1 && !weights[VDATA]) {
weights[VDATA] = MEM_mallocN(sizeof(*(weights[VDATA])) * (size_t)num_verts_dst, __func__);
BKE_defvert_extract_vgroup_to_vertweights(mdef, vg_idx, num_verts_dst, weights[VDATA], invert_vgroup);
}
if (data_transfer_layersmapping_generate(
&lay_map, ob_src, ob_dst, dm_src, dm_dst, me_dst, ME_VERT,
cddata_type, mix_mode, mix_factor, weights[VDATA],
num_verts_dst, use_create, use_delete, fromlayers, tolayers, space_transform))
{
CustomDataTransferLayerMap *lay_mapit;
changed = (lay_map.first != NULL);
for (lay_mapit = lay_map.first; lay_mapit; lay_mapit = lay_mapit->next) {
CustomData_data_transfer(&geom_map[VDATA], lay_mapit);
}
BLI_freelistN(&lay_map);
}
}
if (DT_DATATYPE_IS_EDGE(dtdata_type)) {
MVert *verts_dst = dm_dst ? dm_dst->getVertArray(dm_dst) : me_dst->mvert;
const int num_verts_dst = dm_dst ? dm_dst->getNumVerts(dm_dst) : me_dst->totvert;
MEdge *edges_dst = dm_dst ? dm_dst->getEdgeArray(dm_dst) : me_dst->medge;
const int num_edges_dst = dm_dst ? dm_dst->getNumEdges(dm_dst) : me_dst->totedge;
if (!geom_map_init[EDATA]) {
const int num_edges_src = dm_src->getNumEdges(dm_src);
if ((map_edge_mode == MREMAP_MODE_TOPOLOGY) && (num_edges_dst != num_edges_src)) {
BKE_report(reports, RPT_ERROR,
"Source and destination meshes do not have the same amount of edges, "
"'Topology' mapping cannot be used in this case");
continue;
}
if ((map_edge_mode & MREMAP_USE_POLY) && (dm_src->getNumPolys(dm_src) == 0)) {
BKE_report(reports, RPT_ERROR,
"Source mesh doesn't have any faces, "
"None of the 'Face' mappings can be used in this case");
continue;
}
if (ELEM(0, num_edges_dst, num_edges_src)) {
BKE_report(reports, RPT_ERROR,
"Source or destination meshes do not have any edges, cannot transfer edge data");
continue;
}
BKE_mesh_remap_calc_edges_from_dm(
map_edge_mode, space_transform, max_distance, ray_radius,
verts_dst, num_verts_dst, edges_dst, num_edges_dst, dirty_nors_dst,
dm_src, &geom_map[EDATA]);
geom_map_init[EDATA] = true;
}
if (mdef && vg_idx != -1 && !weights[EDATA]) {
weights[EDATA] = MEM_mallocN(sizeof(*weights[EDATA]) * (size_t)num_edges_dst, __func__);
BKE_defvert_extract_vgroup_to_edgeweights(
mdef, vg_idx, num_verts_dst, edges_dst, num_edges_dst,
weights[EDATA], invert_vgroup);
}
if (data_transfer_layersmapping_generate(
&lay_map, ob_src, ob_dst, dm_src, dm_dst, me_dst, ME_EDGE,
cddata_type, mix_mode, mix_factor, weights[EDATA],
num_edges_dst, use_create, use_delete, fromlayers, tolayers, space_transform))
{
CustomDataTransferLayerMap *lay_mapit;
changed = (lay_map.first != NULL);
for (lay_mapit = lay_map.first; lay_mapit; lay_mapit = lay_mapit->next) {
CustomData_data_transfer(&geom_map[EDATA], lay_mapit);
}
BLI_freelistN(&lay_map);
}
}
if (DT_DATATYPE_IS_LOOP(dtdata_type)) {
MVert *verts_dst = dm_dst ? dm_dst->getVertArray(dm_dst) : me_dst->mvert;
const int num_verts_dst = dm_dst ? dm_dst->getNumVerts(dm_dst) : me_dst->totvert;
MEdge *edges_dst = dm_dst ? dm_dst->getEdgeArray(dm_dst) : me_dst->medge;
const int num_edges_dst = dm_dst ? dm_dst->getNumEdges(dm_dst) : me_dst->totedge;
MPoly *polys_dst = dm_dst ? dm_dst->getPolyArray(dm_dst) : me_dst->mpoly;
const int num_polys_dst = dm_dst ? dm_dst->getNumPolys(dm_dst) : me_dst->totpoly;
MLoop *loops_dst = dm_dst ? dm_dst->getLoopArray(dm_dst) : me_dst->mloop;
const int num_loops_dst = dm_dst ? dm_dst->getNumLoops(dm_dst) : me_dst->totloop;
CustomData *pdata_dst = dm_dst ? dm_dst->getPolyDataLayout(dm_dst) : &me_dst->pdata;
CustomData *ldata_dst = dm_dst ? dm_dst->getLoopDataLayout(dm_dst) : &me_dst->ldata;
MeshRemapIslandsCalc island_callback = data_transfer_get_loop_islands_generator(cddata_type);
if (!geom_map_init[LDATA]) {
const int num_loops_src = dm_src->getNumLoops(dm_src);
if ((map_loop_mode == MREMAP_MODE_TOPOLOGY) && (num_loops_dst != num_loops_src)) {
BKE_report(reports, RPT_ERROR,
"Source and destination meshes do not have the same amount of face corners, "
"'Topology' mapping cannot be used in this case");
continue;
}
if ((map_loop_mode & MREMAP_USE_EDGE) && (dm_src->getNumEdges(dm_src) == 0)) {
BKE_report(reports, RPT_ERROR,
"Source mesh doesn't have any edges, "
"None of the 'Edge' mappings can be used in this case");
continue;
}
if (ELEM(0, num_loops_dst, num_loops_src)) {
BKE_report(reports, RPT_ERROR,
"Source or destination meshes do not have any faces, cannot transfer corner data");
continue;
}
BKE_mesh_remap_calc_loops_from_dm(
map_loop_mode, space_transform, max_distance, ray_radius,
verts_dst, num_verts_dst, edges_dst, num_edges_dst,
loops_dst, num_loops_dst, polys_dst, num_polys_dst,
ldata_dst, pdata_dst,
(me_dst->flag & ME_AUTOSMOOTH) != 0, me_dst->smoothresh, dirty_nors_dst,
dm_src, (me_src->flag & ME_AUTOSMOOTH) != 0, me_src->smoothresh,
island_callback, islands_handling_precision, &geom_map[LDATA]);
geom_map_init[LDATA] = true;
}
if (mdef && vg_idx != -1 && !weights[LDATA]) {
weights[LDATA] = MEM_mallocN(sizeof(*weights[LDATA]) * (size_t)num_loops_dst, __func__);
BKE_defvert_extract_vgroup_to_loopweights(
mdef, vg_idx, num_verts_dst, loops_dst, num_loops_dst,
weights[LDATA], invert_vgroup);
}
if (data_transfer_layersmapping_generate(
&lay_map, ob_src, ob_dst, dm_src, dm_dst, me_dst, ME_LOOP,
cddata_type, mix_mode, mix_factor, weights[LDATA],
num_loops_dst, use_create, use_delete, fromlayers, tolayers, space_transform))
{
CustomDataTransferLayerMap *lay_mapit;
changed = (lay_map.first != NULL);
for (lay_mapit = lay_map.first; lay_mapit; lay_mapit = lay_mapit->next) {
CustomData_data_transfer(&geom_map[LDATA], lay_mapit);
}
BLI_freelistN(&lay_map);
}
}
if (DT_DATATYPE_IS_POLY(dtdata_type)) {
MVert *verts_dst = dm_dst ? dm_dst->getVertArray(dm_dst) : me_dst->mvert;
const int num_verts_dst = dm_dst ? dm_dst->getNumVerts(dm_dst) : me_dst->totvert;
MPoly *polys_dst = dm_dst ? dm_dst->getPolyArray(dm_dst) : me_dst->mpoly;
const int num_polys_dst = dm_dst ? dm_dst->getNumPolys(dm_dst) : me_dst->totpoly;
MLoop *loops_dst = dm_dst ? dm_dst->getLoopArray(dm_dst) : me_dst->mloop;
const int num_loops_dst = dm_dst ? dm_dst->getNumLoops(dm_dst) : me_dst->totloop;
CustomData *pdata_dst = dm_dst ? dm_dst->getPolyDataLayout(dm_dst) : &me_dst->pdata;
if (!geom_map_init[PDATA]) {
const int num_polys_src = dm_src->getNumPolys(dm_src);
if ((map_poly_mode == MREMAP_MODE_TOPOLOGY) && (num_polys_dst != num_polys_src)) {
BKE_report(reports, RPT_ERROR,
"Source and destination meshes do not have the same amount of faces, "
"'Topology' mapping cannot be used in this case");
continue;
}
if ((map_poly_mode & MREMAP_USE_EDGE) && (dm_src->getNumEdges(dm_src) == 0)) {
BKE_report(reports, RPT_ERROR,
"Source mesh doesn't have any edges, "
"None of the 'Edge' mappings can be used in this case");
continue;
}
if (ELEM(0, num_polys_dst, num_polys_src)) {
BKE_report(reports, RPT_ERROR,
"Source or destination meshes do not have any faces, cannot transfer face data");
continue;
}
BKE_mesh_remap_calc_polys_from_dm(
map_poly_mode, space_transform, max_distance, ray_radius,
verts_dst, num_verts_dst, loops_dst, num_loops_dst,
polys_dst, num_polys_dst, pdata_dst, dirty_nors_dst,
dm_src, &geom_map[PDATA]);
geom_map_init[PDATA] = true;
}
if (mdef && vg_idx != -1 && !weights[PDATA]) {
weights[PDATA] = MEM_mallocN(sizeof(*weights[PDATA]) * (size_t)num_polys_dst, __func__);
BKE_defvert_extract_vgroup_to_polyweights(
mdef, vg_idx, num_verts_dst, loops_dst, num_loops_dst,
polys_dst, num_polys_dst, weights[PDATA], invert_vgroup);
}
if (data_transfer_layersmapping_generate(
&lay_map, ob_src, ob_dst, dm_src, dm_dst, me_dst, ME_POLY,
cddata_type, mix_mode, mix_factor, weights[PDATA],
num_polys_dst, use_create, use_delete, fromlayers, tolayers, space_transform))
{
CustomDataTransferLayerMap *lay_mapit;
changed = (lay_map.first != NULL);
for (lay_mapit = lay_map.first; lay_mapit; lay_mapit = lay_mapit->next) {
CustomData_data_transfer(&geom_map[PDATA], lay_mapit);
}
BLI_freelistN(&lay_map);
}
}
data_transfer_dtdata_type_postprocess(ob_src, ob_dst, dm_src, dm_dst, me_dst, dtdata_type, changed);
}
for (i = 0; i < DATAMAX; i++) {
BKE_mesh_remap_free(&geom_map[i]);
MEM_SAFE_FREE(weights[i]);
}
dm_src->release(dm_src);
return changed;
#undef VDATA
#undef EDATA
#undef LDATA
#undef PDATA
#undef DATAMAX
}
bool BKE_object_data_transfer_mesh(
Scene *scene, Object *ob_src, Object *ob_dst, const int data_types, const bool use_create,
const int map_vert_mode, const int map_edge_mode, const int map_loop_mode, const int map_poly_mode,
SpaceTransform *space_transform, const bool auto_transform,
const float max_distance, const float ray_radius, const float islands_handling_precision,
const int fromlayers_select[DT_MULTILAYER_INDEX_MAX], const int tolayers_select[DT_MULTILAYER_INDEX_MAX],
const int mix_mode, const float mix_factor, const char *vgroup_name, const bool invert_vgroup,
ReportList *reports)
{
return BKE_object_data_transfer_dm(
scene, ob_src, ob_dst, NULL, data_types, use_create,
map_vert_mode, map_edge_mode, map_loop_mode, map_poly_mode,
space_transform, auto_transform,
max_distance, ray_radius, islands_handling_precision,
fromlayers_select, tolayers_select,
mix_mode, mix_factor, vgroup_name, invert_vgroup, reports);
}
| 35.327236 | 119 | 0.67919 | [
"mesh",
"object"
] |
3bcef6fee6caa2c60092a71a80ea760f3915e8c6 | 1,397 | h | C | src/simulator/task_io.h | k101w/phyre_ODE | 5d775d3722043725b254cc8be83cad56462d9bef | [
"Apache-2.0"
] | 432 | 2019-08-15T15:45:43.000Z | 2022-02-26T23:13:34.000Z | src/simulator/task_io.h | k101w/phyre_ODE | 5d775d3722043725b254cc8be83cad56462d9bef | [
"Apache-2.0"
] | 38 | 2019-09-06T15:39:03.000Z | 2022-03-12T00:11:25.000Z | src/simulator/task_io.h | k101w/phyre_ODE | 5d775d3722043725b254cc8be83cad56462d9bef | [
"Apache-2.0"
] | 69 | 2019-08-16T02:08:41.000Z | 2022-01-27T23:23:03.000Z | // Copyright (c) Facebook, Inc. and its affiliates.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef TASK_IO_H
#define TASK_IO_H
#include <string>
#include <vector>
#include "gen-cpp/shared_types.h"
#include "gen-cpp/task_types.h"
#include "boost/filesystem.hpp"
constexpr char kTaskFolder[] = "data/generated_tasks";
boost::filesystem::path getTasksPath(const char* taskFolder);
std::vector<int32_t> listTasks(const char* taskFolder = kTaskFolder);
task::Task getTaskFromId(const int32_t pTaskId,
const char* taskFolder = kTaskFolder);
task::Task getTaskFromPath(const std::string& file_path);
void dumpInputPointsToFile(const std::vector<::scene::IntVector>& input_points,
const std::string& filename);
std::vector<::scene::IntVector> readInputPointsFromFile(
const std::string& filename);
#endif // TASK_IO_H
| 32.488372 | 79 | 0.727989 | [
"vector"
] |
3be0dccf3c2d5118151655e411db589163e29efb | 497 | h | C | BaseLibraries/ALGO_GRAPH/test/test_shortest_path.h | RomanFesenko/Hbot | 15f5a804b293f4a2bd78005e7c3adafe22ced64c | [
"MIT"
] | null | null | null | BaseLibraries/ALGO_GRAPH/test/test_shortest_path.h | RomanFesenko/Hbot | 15f5a804b293f4a2bd78005e7c3adafe22ced64c | [
"MIT"
] | null | null | null | BaseLibraries/ALGO_GRAPH/test/test_shortest_path.h | RomanFesenko/Hbot | 15f5a804b293f4a2bd78005e7c3adafe22ced64c | [
"MIT"
] | null | null | null |
#ifndef _test_shortest_path_
#define _test_shortest_path_
#include <vector>
#include <array>
namespace spd{
void test_shortest_path_impl(const std::vector<std::array<int,3>>&,
const std::vector<std::vector<int>>&);
void test_shortest_path_impl(const std::vector<std::array<int,3>>&);
void test_bellman_ford(const std::vector<std::array<int,3>>&,
const std::vector<std::vector<int>>&);
void test_shortest_path();
}
#endif
| 21.608696 | 68 | 0.645875 | [
"vector"
] |
3be275d158a803e37f063a4557b60f71bd2d83bd | 41,067 | h | C | ImperasLib/source/power.ovpworld.org/processor/powerpc32/1.0/model/ppc32Structure.h | emanuellucas2/OVPsimProject | 6c9f5bfaaa135fa63d63746bacf5759c6d6c0e9e | [
"TCL"
] | null | null | null | ImperasLib/source/power.ovpworld.org/processor/powerpc32/1.0/model/ppc32Structure.h | emanuellucas2/OVPsimProject | 6c9f5bfaaa135fa63d63746bacf5759c6d6c0e9e | [
"TCL"
] | null | null | null | ImperasLib/source/power.ovpworld.org/processor/powerpc32/1.0/model/ppc32Structure.h | emanuellucas2/OVPsimProject | 6c9f5bfaaa135fa63d63746bacf5759c6d6c0e9e | [
"TCL"
] | null | null | null | /*
* Copyright (c) 2005-2021 Imperas Software Ltd., www.imperas.com
*
* 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 PPC32_STRUCTURE_H
#define PPC32_STRUCTURE_H
#include "vmi/vmiTypes.h"
#include "ppc32TypeRefs.h"
#include "ppc32Variant.h"
#include "ppc32Config.h"
#include "ppc32SPR.h"
#define NUM_MEMBERS(_A) (sizeof(_A)/sizeof((_A)[0]))
#define PPC32_DISASSEMBLE_MASK 0x00000001
#define PPC32_DISASSEMBLE(_P) ((_P)->flags & PPC32_DISASSEMBLE_MASK)
// decoder callback function to decode instruction at the passed address
#define PPC32_DECODER_FN(_NAME) void _NAME ( \
ppc32P ppc32, \
Uns32 thisPC, \
ppc32InstructionInfoP info \
)
typedef PPC32_DECODER_FN((*ppc32DecoderFn));
typedef enum ppc32ExceptionsS {
ppc32_E_Reset ,
ppc32_E_Undefined,
ppc32_E_Arith ,
ppc32_E_RdAlign ,
ppc32_E_WrAlign ,
ppc32_E_RdAbort ,
ppc32_E_WrAbort ,
ppc32_E_RdPriv ,
ppc32_E_WrPriv ,
ppc32_E_Fetch ,
} ppc32Exception;
typedef enum ppc32VMModeE {
VM_MODE_REAL = 0,
VM_MODE_REAL_PRIV = VM_MODE_REAL,
VM_MODE_REAL_USER,
VM_MODE_REAL_HYPV,
VM_MODE_FIRST_VIRTUAL,
VM_MODE_VIRTUAL_PRIV_D = VM_MODE_FIRST_VIRTUAL,
VM_MODE_VIRTUAL_PRIV_I,
VM_MODE_VIRTUAL_PRIV_DI,
VM_MODE_VIRTUAL_USER_D,
VM_MODE_VIRTUAL_USER_I,
VM_MODE_VIRTUAL_USER_DI,
VM_MODE_VIRTUAL_HYPV_D,
VM_MODE_VIRTUAL_HYPV_I,
VM_MODE_VIRTUAL_HYPV_DI,
VM_MODE_LAST_VIRTUAL = VM_MODE_VIRTUAL_HYPV_DI,
VM_MODE_LAST
} ppc32VMMode;
// this enumeration specifies modes enabling instruction subsets
typedef enum ppc32BlockMask {
BM_NONE = 0x0000, // no requirement
BM_FP_AVAIL = 0x0001, // requires enabled floating point unit
} ppc32BlockMask;
//
// Enum to indicate the type of FPU operation for checks in
//
typedef struct ppc32NetPortS *ppc32NetPortP, **ppc32NetPortPP;
typedef union {
Uns32 reg;
struct {
Uns32 CR7 : 4; // LT, GT, EQ, SO
Uns32 CR6 : 4; // LT, GT, EQ, SO
Uns32 CR5 : 4; // LT, GT, EQ, SO
Uns32 CR4 : 4; // LT, GT, EQ, SO
Uns32 CR3 : 4; // LT, GT, EQ, SO
Uns32 CR2 : 4; // LT, GT, EQ, SO
Uns32 CR1 : 4; // LT, GT, EQ, SO
Uns32 CR0 : 4; // LT, GT, EQ, SO
} bits;
} TYPE_CR;
typedef union {
Uns32 reg;
struct {
Uns32 RN : 2;
Uns32 NI : 1; // None-ieee mode, RESERVED
Uns32 XE : 1;
Uns32 ZE : 1;
Uns32 UE : 1;
Uns32 OE : 1;
Uns32 VE : 1;
Uns32 VXCVI : 1; // Sticky flags
Uns32 VXSQRT : 1; // Sticky flags
Uns32 VXSOFT : 1; // Sticky flags
Uns32 RSV1 : 1;
Uns32 FU : 1; // NaN ->FLG_FP_FU
Uns32 FE : 1; // EQ-ZERO ->FLG_FP_FE
Uns32 FG : 1; // GT-ZERO ->FLG_FP_FG
Uns32 FL : 1; // LT-ZERO ->FLG_FP_FL
Uns32 C : 1; // FPCC ->FLG_FP_C
Uns32 FI : 1; // Inexact during rounding, or disabled overflow
Uns32 FR : 1;
Uns32 VXVC : 1; // Sticky flags
Uns32 VXIMZ : 1; // Sticky flags
Uns32 VXZDZ : 1; // Sticky flags
Uns32 VXIDI : 1; // Sticky flags
Uns32 VXISI : 1; // Sticky flags
Uns32 VXSNAN : 1; // Sticky flags
Uns32 XX : 1; // Sticky flags (FI)
Uns32 ZX : 1; // Sticky flags
Uns32 UX : 1; // Sticky flags
Uns32 OX : 1; // Sticky flags
Uns32 VX : 1;
Uns32 FEX : 1;
Uns32 FX : 1;
} bits;
} TYPE_FPSCR;
typedef union {
Uns32 reg;
struct {
Uns32 FRMC : 2;
Uns32 FOVFE : 1;
Uns32 FUNFE : 1;
Uns32 FDBZE : 1;
Uns32 FINVE : 1;
Uns32 FINXE : 1;
Uns32 RSV2 : 1;
Uns32 FOVF : 1;
Uns32 FUNF : 1;
Uns32 FDBZ : 1;
Uns32 FINV : 1;
Uns32 FX : 1;
Uns32 FG : 1;
Uns32 SO : 1;
Uns32 SOV : 1;
Uns32 RSV1 : 1;
Uns32 FOVFS : 1;
Uns32 FUNFS : 1;
Uns32 FDBZS : 1;
Uns32 FINVS : 1;
Uns32 FINXS : 1;
Uns32 RSV0 : 2;
Uns32 FOVFH : 1;
Uns32 FUNFH : 1;
Uns32 FDBZH : 1;
Uns32 FINVH : 1;
Uns32 FXH : 1;
Uns32 FGH : 1;
Uns32 OVH : 1;
Uns32 SOVH : 1;
} bits;
} TYPE_SPEFSCR;
typedef union {
Uns64 reg;
struct {
Uns64 BYTES : 7;
Uns64 RSV1 : 22;
Uns64 CA : 1;
Uns64 OV : 1;
Uns64 SO : 1;
Uns64 RSV0 : 32;
} bits;
} TYPE_XER;
typedef struct ppc32sprS *ppc32sprP;
typedef struct ppc32S {
//
// User Defined and Builtin Registers
//
Uns32 GPR[32];
Uns64 FPR[32];
Uns64 VR[32];
TYPE_CR CR, CR_rmask, CR_wmask;
TYPE_FPSCR FPSCR, FPSCR_rmask, FPSCR_wmask;
TYPE_SPEFSCR SPEFSCR, SPEFSCR_rmask, SPEFSCR_wmask;
TYPE_XER XER, XER_rmask, XER_wmask;
Uns64 LR;
Uns64 CTR;
Uns8 XER_SO;
Uns8 XER_OV;
Uns8 XER_CA;
Uns8 LT[8];
Uns8 GT[8];
Uns8 EQ[8];
Uns8 SO[8];
Uns32 TEMP[4];
//
// Exception holding register
//
Uns64 except;
//
// SPR Structure and Delta offset
//
ppc32sprP SPR;
UnsPS SPRdelta;
Uns64 RESERVE_ADDR;
Uns8 RESERVE_LENGTH;
Uns8 RESERVE;
//
// Integer OPS flags
//
Bool FLG_CI;
Bool FLG_CO;
Bool FLG_PA;
Bool FLG_ZR;
Bool FLG_SI;
Bool FLG_OV;
Bool FLG_TEMP;
//
// FLoating point Flags
//
Uns64 FPU_TEMP[4]; // Last FPU Arguments for future Flag Reference
Uns64 FPU_RES; // Last FPU calculated result for future Flag Reference
Uns32 FPU_OP; // BINOP(8), OP(8)
// Flags Relation
// UNORDERED=0x1, EQ=0x2, LT=0x4 GT=0x8
Uns8 FPU_REL, FPU_REL_GEN; // FPU_REL and flag to indicate when to generate
Uns8 QNAN_FLG; // Flag to indicate QNAN handler called
Uns8 TEMP_REL; // only used for comparison ops - not saved to FPSCR
// Flags FPU Operations
// P, U, O, Z, D, I
Uns8 FPU_FLG, FPU_FLG_STICKY;
Uns8 CMP_FLG;
Uns8 CNV32_FLG, CNV32_REL, CNV64_FLG;
// Flags additional
Uns8 FLG_FP_SI;
// Other Sticky flags
Uns8 FLG_FPSCR_VXCVI;
Uns8 FLG_FPSCR_VXSQRT;
Uns8 FLG_FPSCR_VXSOFT;
Uns8 FLG_FPSCR_VXVC;
Uns8 FLG_FPSCR_VXIMZ;
Uns8 FLG_FPSCR_VXZDZ;
Uns8 FLG_FPSCR_VXIDI;
Uns8 FLG_FPSCR_VXISI;
Uns8 FLG_FPSCR_VXSNAN;
//
// Flags to help with Load/Store alignment checks
//
Bool FLG_FP_LDST;
Bool FLG_ST;
//
// Model Support Registers
//
Uns32 flags;
ppc32Config configInfo;
Bool verbose;
memEndian dendian;
memEndian iendian;
ppc32Exception exception;
ppc32BlockMask blockMask;
struct {
Bool UISA_I_B;
Bool UISA_I_BCDA;
Bool UISA_I_S;
Bool UISA_I_E;
Bool UISA_I_E_PC;
Bool UISA_I_E_PD;
Bool UISA_I_EC;
Bool UISA_I_FP;
Bool UISA_I_DFP;
Bool UISA_I_MA;
Bool UISA_I_SP;
Bool UISA_I_V;
Bool UISA_I_LMA;
Bool UISA_I_WT;
Bool UISA_I_VLE;
Bool ENABLE_FPU;
Bool UNIMP_TO_NOP;
Bool WARN_NOP;
} params;
// Bus ports
vmiBusPortP busPorts;
// Net ports
ppc32NetPortP netPorts;
// generic instruction decoder
ppc32DecoderFn decoder;
} ppc32;
#define PPC32_FLAG_BITS (sizeof(Uns8) * 8)
#define PPC32_CPU_OFFSET(_F) VMI_CPU_OFFSET(ppc32P, _F)
#define PPC32_CPU_REG(_F) VMI_CPU_REG(ppc32P, _F)
#define PPC32_TEMP_REG(_F) VMI_CPU_TEMP(ppc32P, _F)
#define PPC32_SPR_REG(_P, _F) VMI_CPU_REG_DELTA(ppc32sprP, _F, _P->SPRdelta)
#define PPC32_GPR_BITS (sizeof(Uns32) * 8)
#define PPC32_GPR_RD(_R) PPC32_CPU_REG(GPR[_R])
#define PPC32_GPR_WR(_R) PPC32_CPU_REG(GPR[_R])
#define PPC32_FPR_BITS (sizeof(Uns64) * 8)
#define PPC32_FPR_RD(_R) PPC32_CPU_REG(FPR[_R])
#define PPC32_FPR_WR(_R) PPC32_CPU_REG(FPR[_R])
#define PPC32_FPU_RES PPC32_CPU_REG(FPU_RES)
#define PPC32_FPU_TEMP(_R) PPC32_CPU_REG(FPU_TEMP[_R])
#define PPC32_VR_BITS (sizeof(Uns64) * 8)
#define PPC32_VR_RD(_R) PPC32_CPU_REG(VR[_R])
#define PPC32_VR_WR(_R) PPC32_CPU_REG(VR[_R])
#define PPC32_CR_BITS (sizeof(Uns32) * 8)
#define PPC32_CR_RD PPC32_CPU_REG(CR)
#define PPC32_CR_WR PPC32_CPU_REG(CR)
#define PPC32_XER_BITS (sizeof(Uns64) * 8)
#define PPC32_XER_RD PPC32_CPU_REG(XER)
#define PPC32_XER_WR PPC32_CPU_REG(XER)
#define PPC32_XER_SO_BITS (sizeof(Uns8) * 8)
#define PPC32_XER_SO_RD PPC32_CPU_REG(XER_SO)
#define PPC32_XER_SO_WR PPC32_CPU_REG(XER_SO)
#define PPC32_XER_OV_BITS (sizeof(Uns8) * 8)
#define PPC32_XER_OV_RD PPC32_CPU_REG(XER_OV)
#define PPC32_XER_OV_WR PPC32_CPU_REG(XER_OV)
#define PPC32_XER_CA_BITS (sizeof(Uns8) * 8)
#define PPC32_XER_CA_RD PPC32_CPU_REG(XER_CA)
#define PPC32_XER_CA_WR PPC32_CPU_REG(XER_CA)
#define PPC32_LT_BITS (sizeof(Uns8) * 8)
#define PPC32_LT_RD(_R) PPC32_CPU_REG(LT[_R])
#define PPC32_LT_WR(_R) PPC32_CPU_REG(LT[_R])
#define PPC32_GT_BITS (sizeof(Uns8) * 8)
#define PPC32_GT_RD(_R) PPC32_CPU_REG(GT[_R])
#define PPC32_GT_WR(_R) PPC32_CPU_REG(GT[_R])
#define PPC32_EQ_BITS (sizeof(Uns8) * 8)
#define PPC32_EQ_RD(_R) PPC32_CPU_REG(EQ[_R])
#define PPC32_EQ_WR(_R) PPC32_CPU_REG(EQ[_R])
#define PPC32_SO_BITS (sizeof(Uns8) * 8)
#define PPC32_SO_RD(_R) PPC32_CPU_REG(SO[_R])
#define PPC32_SO_WR(_R) PPC32_CPU_REG(SO[_R])
#define PPC32_TEMP_BITS (sizeof(Uns32) * 8)
#define PPC32_TEMP(_R) PPC32_TEMP_REG(TEMP[_R])
#define PPC32_LR_BITS (sizeof(Uns64) * 8)
#define PPC32_LR_RD PPC32_CPU_REG(LR)
#define PPC32_LR_WR PPC32_CPU_REG(LR)
#define PPC32_CTR_BITS (sizeof(Uns64) * 8)
#define PPC32_CTR_RD PPC32_CPU_REG(CTR)
#define PPC32_CTR_WR PPC32_CPU_REG(CTR)
#define PPC32_DSCR_BITS (sizeof(Uns64) * 8)
#define PPC32_DSCR_RD PPC32_CPU_REG(DSCR)
#define PPC32_DSCR_WR PPC32_CPU_REG(DSCR)
#define PPC32_DSISR_BITS (sizeof(Uns32) * 8)
#define PPC32_DSISR_RD PPC32_CPU_REG(DSISR)
#define PPC32_DSISR_WR PPC32_CPU_REG(DSISR)
#define PPC32_DAR_BITS (sizeof(Uns64) * 8)
#define PPC32_DAR_RD PPC32_CPU_REG(DAR)
#define PPC32_DAR_WR PPC32_CPU_REG(DAR)
#define PPC32_DEC_BITS (sizeof(Uns32) * 8)
#define PPC32_DEC_RD PPC32_CPU_REG(DEC)
#define PPC32_DEC_WR PPC32_CPU_REG(DEC)
#define PPC32_DEC_TMR_BITS (sizeof(Uns64) * 8)
#define PPC32_DEC_TMR_RD PPC32_CPU_REG(DEC_tmr)
#define PPC32_DEC_TMR_WR PPC32_CPU_REG(DEC_tmr)
#define PPC32_SDR1_BITS (sizeof(Uns64) * 8)
#define PPC32_SDR1_RD PPC32_CPU_REG(SDR1)
#define PPC32_SDR1_WR PPC32_CPU_REG(SDR1)
#define PPC32_SRR0_BITS (sizeof(Uns64) * 8)
#define PPC32_SRR0_RD PPC32_CPU_REG(SRR0)
#define PPC32_SRR0_WR PPC32_CPU_REG(SRR0)
#define PPC32_SRR1_BITS (sizeof(Uns64) * 8)
#define PPC32_SRR1_RD PPC32_CPU_REG(SRR1)
#define PPC32_SRR1_WR PPC32_CPU_REG(SRR1)
#define PPC32_CFAR_BITS (sizeof(Uns64) * 8)
#define PPC32_CFAR_RD PPC32_CPU_REG(CFAR)
#define PPC32_CFAR_WR PPC32_CPU_REG(CFAR)
#define PPC32_AMR_BITS (sizeof(Uns64) * 8)
#define PPC32_AMR_RD PPC32_CPU_REG(AMR)
#define PPC32_AMR_WR PPC32_CPU_REG(AMR)
#define PPC32_PID0_BITS (sizeof(Uns32) * 8)
#define PPC32_PID0_RD PPC32_CPU_REG(PID0)
#define PPC32_PID0_WR PPC32_CPU_REG(PID0)
#define PPC32_DECAR_BITS (sizeof(Uns32) * 8)
#define PPC32_DECAR_RD PPC32_CPU_REG(DECAR)
#define PPC32_DECAR_WR PPC32_CPU_REG(DECAR)
#define PPC32_CSRR0_BITS (sizeof(Uns64) * 8)
#define PPC32_CSRR0_RD PPC32_CPU_REG(CSRR0)
#define PPC32_CSRR0_WR PPC32_CPU_REG(CSRR0)
#define PPC32_CSRR1_BITS (sizeof(Uns32) * 8)
#define PPC32_CSRR1_RD PPC32_CPU_REG(CSRR1)
#define PPC32_CSRR1_WR PPC32_CPU_REG(CSRR1)
#define PPC32_DEAR_BITS (sizeof(Uns64) * 8)
#define PPC32_DEAR_RD PPC32_CPU_REG(DEAR)
#define PPC32_DEAR_WR PPC32_CPU_REG(DEAR)
#define PPC32_ESR_BITS (sizeof(Uns32) * 8)
#define PPC32_ESR_RD PPC32_CPU_REG(ESR)
#define PPC32_ESR_WR PPC32_CPU_REG(ESR)
#define PPC32_IVPR_BITS (sizeof(Uns64) * 8)
#define PPC32_IVPR_RD PPC32_CPU_REG(IVPR)
#define PPC32_IVPR_WR PPC32_CPU_REG(IVPR)
#define PPC32_CTRL_BITS (sizeof(Uns32) * 8)
#define PPC32_CTRL_RD PPC32_CPU_REG(CTRL)
#define PPC32_CTRL_WR PPC32_CPU_REG(CTRL)
#define PPC32_VRSAVE_BITS (sizeof(Uns32) * 8)
#define PPC32_VRSAVE_RD PPC32_CPU_REG(VRSAVE)
#define PPC32_VRSAVE_WR PPC32_CPU_REG(VRSAVE)
#define PPC32_SPRG0_BITS (sizeof(Uns64) * 8)
#define PPC32_SPRG0_RD PPC32_CPU_REG(SPRG0)
#define PPC32_SPRG0_WR PPC32_CPU_REG(SPRG0)
#define PPC32_SPRG1_BITS (sizeof(Uns64) * 8)
#define PPC32_SPRG1_RD PPC32_CPU_REG(SPRG1)
#define PPC32_SPRG1_WR PPC32_CPU_REG(SPRG1)
#define PPC32_SPRG2_BITS (sizeof(Uns64) * 8)
#define PPC32_SPRG2_RD PPC32_CPU_REG(SPRG2)
#define PPC32_SPRG2_WR PPC32_CPU_REG(SPRG2)
#define PPC32_SPRG3_BITS (sizeof(Uns64) * 8)
#define PPC32_SPRG3_RD PPC32_CPU_REG(SPRG3)
#define PPC32_SPRG3_WR PPC32_CPU_REG(SPRG3)
#define PPC32_SPRG4_BITS (sizeof(Uns64) * 8)
#define PPC32_SPRG4_RD PPC32_CPU_REG(SPRG4)
#define PPC32_SPRG4_WR PPC32_CPU_REG(SPRG4)
#define PPC32_SPRG5_BITS (sizeof(Uns64) * 8)
#define PPC32_SPRG5_RD PPC32_CPU_REG(SPRG5)
#define PPC32_SPRG5_WR PPC32_CPU_REG(SPRG5)
#define PPC32_SPRG6_BITS (sizeof(Uns64) * 8)
#define PPC32_SPRG6_RD PPC32_CPU_REG(SPRG6)
#define PPC32_SPRG6_WR PPC32_CPU_REG(SPRG6)
#define PPC32_SPRG7_BITS (sizeof(Uns64) * 8)
#define PPC32_SPRG7_RD PPC32_CPU_REG(SPRG7)
#define PPC32_SPRG7_WR PPC32_CPU_REG(SPRG7)
#define PPC32_TB_BITS (sizeof(Uns64) * 8)
#define PPC32_TB_RD PPC32_CPU_REG(TB)
#define PPC32_TB_WR PPC32_CPU_REG(TB)
#define PPC32_TBU_BITS (sizeof(Uns64) * 8)
#define PPC32_TBU_RD PPC32_CPU_REG(TBU)
#define PPC32_TBU_WR PPC32_CPU_REG(TBU)
#define PPC32_EAR_BITS (sizeof(Uns32) * 8)
#define PPC32_EAR_RD PPC32_CPU_REG(EAR)
#define PPC32_EAR_WR PPC32_CPU_REG(EAR)
#define PPC32_PIR_BITS (sizeof(Uns32) * 8)
#define PPC32_PIR_RD PPC32_CPU_REG(PIR)
#define PPC32_PIR_WR PPC32_CPU_REG(PIR)
#define PPC32_PVR_BITS (sizeof(Uns32) * 8)
#define PPC32_PVR_RD PPC32_CPU_REG(PVR)
#define PPC32_PVR_WR PPC32_CPU_REG(PVR)
#define PPC32_HSPRG_BITS (sizeof(Uns64) * 8)
#define PPC32_HSPRG_RD(_R) PPC32_CPU_REG(HSPRG[_R])
#define PPC32_HSPRG_WR(_R) PPC32_CPU_REG(HSPRG[_R])
#define PPC32_DBSR_BITS (sizeof(Uns32) * 8)
#define PPC32_DBSR_RD PPC32_CPU_REG(DBSR)
#define PPC32_DBSR_WR PPC32_CPU_REG(DBSR)
#define PPC32_HDSISR_BITS (sizeof(Uns32) * 8)
#define PPC32_HDSISR_RD PPC32_CPU_REG(HDSISR)
#define PPC32_HDSISR_WR PPC32_CPU_REG(HDSISR)
#define PPC32_HDAR_BITS (sizeof(Uns64) * 8)
#define PPC32_HDAR_RD PPC32_CPU_REG(HDAR)
#define PPC32_HDAR_WR PPC32_CPU_REG(HDAR)
#define PPC32_DBCR0_BITS (sizeof(Uns32) * 8)
#define PPC32_DBCR0_RD PPC32_CPU_REG(DBCR0)
#define PPC32_DBCR0_WR PPC32_CPU_REG(DBCR0)
#define PPC32_SPURR_BITS (sizeof(Uns64) * 8)
#define PPC32_SPURR_RD PPC32_CPU_REG(SPURR)
#define PPC32_SPURR_WR PPC32_CPU_REG(SPURR)
#define PPC32_PURR_BITS (sizeof(Uns64) * 8)
#define PPC32_PURR_RD PPC32_CPU_REG(PURR)
#define PPC32_PURR_WR PPC32_CPU_REG(PURR)
#define PPC32_DBCR1_BITS (sizeof(Uns32) * 8)
#define PPC32_DBCR1_RD PPC32_CPU_REG(DBCR1)
#define PPC32_DBCR1_WR PPC32_CPU_REG(DBCR1)
#define PPC32_HDEC_BITS (sizeof(Uns32) * 8)
#define PPC32_HDEC_RD PPC32_CPU_REG(HDEC)
#define PPC32_HDEC_WR PPC32_CPU_REG(HDEC)
#define PPC32_DBCR2_BITS (sizeof(Uns32) * 8)
#define PPC32_DBCR2_RD PPC32_CPU_REG(DBCR2)
#define PPC32_DBCR2_WR PPC32_CPU_REG(DBCR2)
#define PPC32_RMOR_BITS (sizeof(Uns64) * 8)
#define PPC32_RMOR_RD PPC32_CPU_REG(RMOR)
#define PPC32_RMOR_WR PPC32_CPU_REG(RMOR)
#define PPC32_IAC1_BITS (sizeof(Uns64) * 8)
#define PPC32_IAC1_RD PPC32_CPU_REG(IAC1)
#define PPC32_IAC1_WR PPC32_CPU_REG(IAC1)
#define PPC32_IAC2_BITS (sizeof(Uns64) * 8)
#define PPC32_IAC2_RD PPC32_CPU_REG(IAC2)
#define PPC32_IAC2_WR PPC32_CPU_REG(IAC2)
#define PPC32_IAC3_BITS (sizeof(Uns64) * 8)
#define PPC32_IAC3_RD PPC32_CPU_REG(IAC3)
#define PPC32_IAC3_WR PPC32_CPU_REG(IAC3)
#define PPC32_IAC4_BITS (sizeof(Uns64) * 8)
#define PPC32_IAC4_RD PPC32_CPU_REG(IAC4)
#define PPC32_IAC4_WR PPC32_CPU_REG(IAC4)
#define PPC32_HRMOR_BITS (sizeof(Uns64) * 8)
#define PPC32_HRMOR_RD PPC32_CPU_REG(HRMOR)
#define PPC32_HRMOR_WR PPC32_CPU_REG(HRMOR)
#define PPC32_HSRR0_BITS (sizeof(Uns64) * 8)
#define PPC32_HSRR0_RD PPC32_CPU_REG(HSRR0)
#define PPC32_HSRR0_WR PPC32_CPU_REG(HSRR0)
#define PPC32_HSRR1_BITS (sizeof(Uns64) * 8)
#define PPC32_HSRR1_RD PPC32_CPU_REG(HSRR1)
#define PPC32_HSRR1_WR PPC32_CPU_REG(HSRR1)
#define PPC32_DAC1_BITS (sizeof(Uns64) * 8)
#define PPC32_DAC1_RD PPC32_CPU_REG(DAC1)
#define PPC32_DAC1_WR PPC32_CPU_REG(DAC1)
#define PPC32_DAC2_BITS (sizeof(Uns64) * 8)
#define PPC32_DAC2_RD PPC32_CPU_REG(DAC2)
#define PPC32_DAC2_WR PPC32_CPU_REG(DAC2)
#define PPC32_LPCR_BITS (sizeof(Uns64) * 8)
#define PPC32_LPCR_RD PPC32_CPU_REG(LPCR)
#define PPC32_LPCR_WR PPC32_CPU_REG(LPCR)
#define PPC32_DVC1_BITS (sizeof(Uns64) * 8)
#define PPC32_DVC1_RD PPC32_CPU_REG(DVC1)
#define PPC32_DVC1_WR PPC32_CPU_REG(DVC1)
#define PPC32_DVC2_BITS (sizeof(Uns64) * 8)
#define PPC32_DVC2_RD PPC32_CPU_REG(DVC2)
#define PPC32_DVC2_WR PPC32_CPU_REG(DVC2)
#define PPC32_LPIDR_BITS (sizeof(Uns32) * 8)
#define PPC32_LPIDR_RD PPC32_CPU_REG(LPIDR)
#define PPC32_LPIDR_WR PPC32_CPU_REG(LPIDR)
#define PPC32_TSR_BITS (sizeof(Uns32) * 8)
#define PPC32_TSR_RD PPC32_CPU_REG(TSR)
#define PPC32_TSR_WR PPC32_CPU_REG(TSR)
#define PPC32_HMER_BITS (sizeof(Uns64) * 8)
#define PPC32_HMER_RD PPC32_CPU_REG(HMER)
#define PPC32_HMER_WR PPC32_CPU_REG(HMER)
#define PPC32_HMEER_BITS (sizeof(Uns64) * 8)
#define PPC32_HMEER_RD PPC32_CPU_REG(HMEER)
#define PPC32_HMEER_WR PPC32_CPU_REG(HMEER)
#define PPC32_PCR_BITS (sizeof(Uns64) * 8)
#define PPC32_PCR_RD PPC32_CPU_REG(PCR)
#define PPC32_PCR_WR PPC32_CPU_REG(PCR)
#define PPC32_HEIR_BITS (sizeof(Uns32) * 8)
#define PPC32_HEIR_RD PPC32_CPU_REG(HEIR)
#define PPC32_HEIR_WR PPC32_CPU_REG(HEIR)
#define PPC32_TCR_BITS (sizeof(Uns32) * 8)
#define PPC32_TCR_RD PPC32_CPU_REG(TCR)
#define PPC32_TCR_WR PPC32_CPU_REG(TCR)
#define PPC32_IVOR0_BITS (sizeof(Uns32) * 8)
#define PPC32_IVOR0_RD PPC32_CPU_REG(IVOR0)
#define PPC32_IVOR0_WR PPC32_CPU_REG(IVOR0)
#define PPC32_IVOR1_BITS (sizeof(Uns32) * 8)
#define PPC32_IVOR1_RD PPC32_CPU_REG(IVOR1)
#define PPC32_IVOR1_WR PPC32_CPU_REG(IVOR1)
#define PPC32_IVOR2_BITS (sizeof(Uns32) * 8)
#define PPC32_IVOR2_RD PPC32_CPU_REG(IVOR2)
#define PPC32_IVOR2_WR PPC32_CPU_REG(IVOR2)
#define PPC32_IVOR3_BITS (sizeof(Uns32) * 8)
#define PPC32_IVOR3_RD PPC32_CPU_REG(IVOR3)
#define PPC32_IVOR3_WR PPC32_CPU_REG(IVOR3)
#define PPC32_IVOR4_BITS (sizeof(Uns32) * 8)
#define PPC32_IVOR4_RD PPC32_CPU_REG(IVOR4)
#define PPC32_IVOR4_WR PPC32_CPU_REG(IVOR4)
#define PPC32_IVOR5_BITS (sizeof(Uns32) * 8)
#define PPC32_IVOR5_RD PPC32_CPU_REG(IVOR5)
#define PPC32_IVOR5_WR PPC32_CPU_REG(IVOR5)
#define PPC32_IVOR6_BITS (sizeof(Uns32) * 8)
#define PPC32_IVOR6_RD PPC32_CPU_REG(IVOR6)
#define PPC32_IVOR6_WR PPC32_CPU_REG(IVOR6)
#define PPC32_IVOR7_BITS (sizeof(Uns32) * 8)
#define PPC32_IVOR7_RD PPC32_CPU_REG(IVOR7)
#define PPC32_IVOR7_WR PPC32_CPU_REG(IVOR7)
#define PPC32_IVOR8_BITS (sizeof(Uns32) * 8)
#define PPC32_IVOR8_RD PPC32_CPU_REG(IVOR8)
#define PPC32_IVOR8_WR PPC32_CPU_REG(IVOR8)
#define PPC32_IVOR9_BITS (sizeof(Uns32) * 8)
#define PPC32_IVOR9_RD PPC32_CPU_REG(IVOR9)
#define PPC32_IVOR9_WR PPC32_CPU_REG(IVOR9)
#define PPC32_IVOR10_BITS (sizeof(Uns32) * 8)
#define PPC32_IVOR10_RD PPC32_CPU_REG(IVOR10)
#define PPC32_IVOR10_WR PPC32_CPU_REG(IVOR10)
#define PPC32_IVOR11_BITS (sizeof(Uns32) * 8)
#define PPC32_IVOR11_RD PPC32_CPU_REG(IVOR11)
#define PPC32_IVOR11_WR PPC32_CPU_REG(IVOR11)
#define PPC32_IVOR12_BITS (sizeof(Uns32) * 8)
#define PPC32_IVOR12_RD PPC32_CPU_REG(IVOR12)
#define PPC32_IVOR12_WR PPC32_CPU_REG(IVOR12)
#define PPC32_IVOR13_BITS (sizeof(Uns32) * 8)
#define PPC32_IVOR13_RD PPC32_CPU_REG(IVOR13)
#define PPC32_IVOR13_WR PPC32_CPU_REG(IVOR13)
#define PPC32_IVOR14_BITS (sizeof(Uns32) * 8)
#define PPC32_IVOR14_RD PPC32_CPU_REG(IVOR14)
#define PPC32_IVOR14_WR PPC32_CPU_REG(IVOR14)
#define PPC32_IVOR15_BITS (sizeof(Uns32) * 8)
#define PPC32_IVOR15_RD PPC32_CPU_REG(IVOR15)
#define PPC32_IVOR15_WR PPC32_CPU_REG(IVOR15)
#define PPC32_SPEFSCR_BITS (sizeof(Uns32) * 8)
#define PPC32_SPEFSCR_RD PPC32_CPU_REG(SPEFSCR)
#define PPC32_SPEFSCR_WR PPC32_CPU_REG(SPEFSCR)
#define PPC32_ATB_BITS (sizeof(Uns64) * 8)
#define PPC32_ATB_RD PPC32_CPU_REG(ATB)
#define PPC32_ATB_WR PPC32_CPU_REG(ATB)
#define PPC32_IVOR32_BITS (sizeof(Uns32) * 8)
#define PPC32_IVOR32_RD PPC32_CPU_REG(IVOR32)
#define PPC32_IVOR32_WR PPC32_CPU_REG(IVOR32)
#define PPC32_IVOR33_BITS (sizeof(Uns32) * 8)
#define PPC32_IVOR33_RD PPC32_CPU_REG(IVOR33)
#define PPC32_IVOR33_WR PPC32_CPU_REG(IVOR33)
#define PPC32_IVOR34_BITS (sizeof(Uns32) * 8)
#define PPC32_IVOR34_RD PPC32_CPU_REG(IVOR34)
#define PPC32_IVOR34_WR PPC32_CPU_REG(IVOR34)
#define PPC32_IVOR35_BITS (sizeof(Uns32) * 8)
#define PPC32_IVOR35_RD PPC32_CPU_REG(IVOR35)
#define PPC32_IVOR35_WR PPC32_CPU_REG(IVOR35)
#define PPC32_IVOR36_BITS (sizeof(Uns32) * 8)
#define PPC32_IVOR36_RD PPC32_CPU_REG(IVOR36)
#define PPC32_IVOR36_WR PPC32_CPU_REG(IVOR36)
#define PPC32_IVOR37_BITS (sizeof(Uns32) * 8)
#define PPC32_IVOR37_RD PPC32_CPU_REG(IVOR37)
#define PPC32_IVOR37_WR PPC32_CPU_REG(IVOR37)
#define PPC32_MCSRR0_BITS (sizeof(Uns64) * 8)
#define PPC32_MCSRR0_RD PPC32_CPU_REG(MCSRR0)
#define PPC32_MCSRR0_WR PPC32_CPU_REG(MCSRR0)
#define PPC32_MCSRR1_BITS (sizeof(Uns32) * 8)
#define PPC32_MCSRR1_RD PPC32_CPU_REG(MCSRR1)
#define PPC32_MCSRR1_WR PPC32_CPU_REG(MCSRR1)
#define PPC32_MCSR_BITS (sizeof(Uns64) * 8)
#define PPC32_MCSR_RD PPC32_CPU_REG(MCSR)
#define PPC32_MCSR_WR PPC32_CPU_REG(MCSR)
#define PPC32_DSRR0_BITS (sizeof(Uns64) * 8)
#define PPC32_DSRR0_RD PPC32_CPU_REG(DSRR0)
#define PPC32_DSRR0_WR PPC32_CPU_REG(DSRR0)
#define PPC32_DSRR1_BITS (sizeof(Uns32) * 8)
#define PPC32_DSRR1_RD PPC32_CPU_REG(DSRR1)
#define PPC32_DSRR1_WR PPC32_CPU_REG(DSRR1)
#define PPC32_SPRG8_BITS (sizeof(Uns64) * 8)
#define PPC32_SPRG8_RD PPC32_CPU_REG(SPRG8)
#define PPC32_SPRG8_WR PPC32_CPU_REG(SPRG8)
#define PPC32_SPRG9_BITS (sizeof(Uns64) * 8)
#define PPC32_SPRG9_RD PPC32_CPU_REG(SPRG9)
#define PPC32_SPRG9_WR PPC32_CPU_REG(SPRG9)
#define PPC32_MAS0_BITS (sizeof(Uns32) * 8)
#define PPC32_MAS0_RD PPC32_CPU_REG(MAS0)
#define PPC32_MAS0_WR PPC32_CPU_REG(MAS0)
#define PPC32_MAS1_BITS (sizeof(Uns32) * 8)
#define PPC32_MAS1_RD PPC32_CPU_REG(MAS1)
#define PPC32_MAS1_WR PPC32_CPU_REG(MAS1)
#define PPC32_MAS2_BITS (sizeof(Uns64) * 8)
#define PPC32_MAS2_RD PPC32_CPU_REG(MAS2)
#define PPC32_MAS2_WR PPC32_CPU_REG(MAS2)
#define PPC32_MAS3_BITS (sizeof(Uns32) * 8)
#define PPC32_MAS3_RD PPC32_CPU_REG(MAS3)
#define PPC32_MAS3_WR PPC32_CPU_REG(MAS3)
#define PPC32_MAS4_BITS (sizeof(Uns32) * 8)
#define PPC32_MAS4_RD PPC32_CPU_REG(MAS4)
#define PPC32_MAS4_WR PPC32_CPU_REG(MAS4)
#define PPC32_MAS6_BITS (sizeof(Uns32) * 8)
#define PPC32_MAS6_RD PPC32_CPU_REG(MAS6)
#define PPC32_MAS6_WR PPC32_CPU_REG(MAS6)
#define PPC32_MAS7_BITS (sizeof(Uns32) * 8)
#define PPC32_MAS7_RD PPC32_CPU_REG(MAS7)
#define PPC32_MAS7_WR PPC32_CPU_REG(MAS7)
#define PPC32_PID1_BITS (sizeof(Uns32) * 8)
#define PPC32_PID1_RD PPC32_CPU_REG(PID1)
#define PPC32_PID1_WR PPC32_CPU_REG(PID1)
#define PPC32_PID2_BITS (sizeof(Uns32) * 8)
#define PPC32_PID2_RD PPC32_CPU_REG(PID2)
#define PPC32_PID2_WR PPC32_CPU_REG(PID2)
#define PPC32_TLB0CFG_BITS (sizeof(Uns32) * 8)
#define PPC32_TLB0CFG_RD PPC32_CPU_REG(TLB0CFG)
#define PPC32_TLB0CFG_WR PPC32_CPU_REG(TLB0CFG)
#define PPC32_TLB1CFG_BITS (sizeof(Uns32) * 8)
#define PPC32_TLB1CFG_RD PPC32_CPU_REG(TLB1CFG)
#define PPC32_TLB1CFG_WR PPC32_CPU_REG(TLB1CFG)
#define PPC32_TLB2CFG_BITS (sizeof(Uns32) * 8)
#define PPC32_TLB2CFG_RD PPC32_CPU_REG(TLB2CFG)
#define PPC32_TLB2CFG_WR PPC32_CPU_REG(TLB2CFG)
#define PPC32_TLB3CFG_BITS (sizeof(Uns32) * 8)
#define PPC32_TLB3CFG_RD PPC32_CPU_REG(TLB3CFG)
#define PPC32_TLB3CFG_WR PPC32_CPU_REG(TLB3CFG)
#define PPC32_EPR_BITS (sizeof(Uns32) * 8)
#define PPC32_EPR_RD PPC32_CPU_REG(EPR)
#define PPC32_EPR_WR PPC32_CPU_REG(EPR)
#define PPC32_PERF_MON_BITS (sizeof(Uns64) * 8)
#define PPC32_PERF_MON_RD(_R) PPC32_CPU_REG(perf_mon[_R])
#define PPC32_PERF_MON_WR(_R) PPC32_CPU_REG(perf_mon[_R])
#define PPC32_PPR_BITS (sizeof(Uns64) * 8)
#define PPC32_PPR_RD PPC32_CPU_REG(PPR)
#define PPC32_PPR_WR PPC32_CPU_REG(PPR)
#define PPC32_DCDBTRL_BITS (sizeof(Uns32) * 8)
#define PPC32_DCDBTRL_RD PPC32_CPU_REG(DCDBTRL)
#define PPC32_DCDBTRL_WR PPC32_CPU_REG(DCDBTRL)
#define PPC32_DCDBTRH_BITS (sizeof(Uns32) * 8)
#define PPC32_DCDBTRH_RD PPC32_CPU_REG(DCDBTRH)
#define PPC32_DCDBTRH_WR PPC32_CPU_REG(DCDBTRH)
#define PPC32_ICDBTRL_BITS (sizeof(Uns32) * 8)
#define PPC32_ICDBTRL_RD PPC32_CPU_REG(ICDBTRL)
#define PPC32_ICDBTRL_WR PPC32_CPU_REG(ICDBTRL)
#define PPC32_ICDBTRH_BITS (sizeof(Uns32) * 8)
#define PPC32_ICDBTRH_RD PPC32_CPU_REG(ICDBTRH)
#define PPC32_ICDBTRH_WR PPC32_CPU_REG(ICDBTRH)
#define PPC32_EPLC_BITS (sizeof(Uns32) * 8)
#define PPC32_EPLC_RD PPC32_CPU_REG(EPLC)
#define PPC32_EPLC_WR PPC32_CPU_REG(EPLC)
#define PPC32_EPSC_BITS (sizeof(Uns32) * 8)
#define PPC32_EPSC_RD PPC32_CPU_REG(EPSC)
#define PPC32_EPSC_WR PPC32_CPU_REG(EPSC)
#define PPC32_ICDBDR_BITS (sizeof(Uns32) * 8)
#define PPC32_ICDBDR_RD PPC32_CPU_REG(ICDBDR)
#define PPC32_ICDBDR_WR PPC32_CPU_REG(ICDBDR)
#define PPC32_MMUCSR0_BITS (sizeof(Uns32) * 8)
#define PPC32_MMUCSR0_RD PPC32_CPU_REG(MMUCSR0)
#define PPC32_MMUCSR0_WR PPC32_CPU_REG(MMUCSR0)
#define PPC32_DABR_BITS (sizeof(Uns64) * 8)
#define PPC32_DABR_RD PPC32_CPU_REG(DABR)
#define PPC32_DABR_WR PPC32_CPU_REG(DABR)
#define PPC32_DABRX_BITS (sizeof(Uns64) * 8)
#define PPC32_DABRX_RD PPC32_CPU_REG(DABRX)
#define PPC32_DABRX_WR PPC32_CPU_REG(DABRX)
#define PPC32_MMUCFG_BITS (sizeof(Uns32) * 8)
#define PPC32_MMUCFG_RD PPC32_CPU_REG(MMUCFG)
#define PPC32_MMUCFG_WR PPC32_CPU_REG(MMUCFG)
#define PPC32_FPSCR_BITS (sizeof(Uns64) * 8)
#define PPC32_FPSCR_RD PPC32_CPU_REG(FPSCR)
#define PPC32_FPSCR_WR PPC32_CPU_REG(FPSCR)
#define PPC32_VSCR_BITS (sizeof(Uns32) * 8)
#define PPC32_VSCR_RD PPC32_CPU_REG(VSCR)
#define PPC32_VSCR_WR PPC32_CPU_REG(VSCR)
#define PPC32_ACCUMULATOR_BITS (sizeof(Uns64) * 8)
#define PPC32_ACCUMULATOR_RD PPC32_CPU_REG(Accumulator)
#define PPC32_ACCUMULATOR_WR PPC32_CPU_REG(Accumulator)
#define PPC32_MSR_BITS (sizeof(Uns64) * 8)
#define PPC32_MSR_RD(_P) PPC32_SPR_REG(_P, MSR)
#define PPC32_MSR_WR(_P) PPC32_SPR_REG(_P, MSR)
#define PPC32_RESERVE_ADDR_BITS (sizeof(Uns64) * 8)
#define PPC32_RESERVE_ADDR_RD PPC32_CPU_REG(RESERVE_ADDR)
#define PPC32_RESERVE_ADDR_WR PPC32_CPU_REG(RESERVE_ADDR)
#define PPC32_RESERVE_LENGTH_BITS (sizeof(Uns8) * 8)
#define PPC32_RESERVE_LENGTH_RD PPC32_CPU_REG(RESERVE_LENGTH)
#define PPC32_RESERVE_LENGTH_WR PPC32_CPU_REG(RESERVE_LENGTH)
#define PPC32_RESERVE_BITS (sizeof(Uns8) * 8)
#define PPC32_RESERVE_RD PPC32_CPU_REG(RESERVE)
#define PPC32_RESERVE_WR PPC32_CPU_REG(RESERVE)
#define PPC32_FLG_CI PPC32_CPU_REG(FLG_CI)
#define PPC32_FLG_CO PPC32_CPU_REG(FLG_CO)
#define PPC32_FLG_PA PPC32_CPU_REG(FLG_PA)
#define PPC32_FLG_ZR PPC32_CPU_REG(FLG_ZR)
#define PPC32_FLG_SI PPC32_CPU_REG(FLG_SI)
#define PPC32_FLG_OV PPC32_CPU_REG(FLG_OV)
#define PPC32_FLG_TEMP PPC32_CPU_REG(FLG_TEMP)
#define PPC32_FPU_FLG PPC32_CPU_REG(FPU_FLG)
#define PPC32_FPU_FLG_STICKY PPC32_CPU_REG(FPU_FLG_STICKY)
#define PPC32_CMP_FLG PPC32_CPU_REG(CMP_FLG)
#define PPC32_CNV32_FLG PPC32_CPU_REG(CNV32_FLG)
#define PPC32_CNV64_FLG PPC32_CPU_REG(CNV64_FLG)
#define PPC32_QNAN_FLG PPC32_CPU_REG(QNAN_FLG)
#define PPC32_FLG_FP_SI PPC32_CPU_REG(FLG_FP_SI)
#define PPC32_FLG_FPSCR_VXCVI PPC32_CPU_REG(FLG_FPSCR_VXCVI)
#define PPC32_FLG_FPSCR_VXSQRT PPC32_CPU_REG(FLG_FPSCR_VXSQRT)
#define PPC32_FLG_FPSCR_VXSOFT PPC32_CPU_REG(FLG_FPSCR_VXSOFT)
#define PPC32_FLG_FPSCR_VXVC PPC32_CPU_REG(FLG_FPSCR_VXVC)
#define PPC32_FLG_FPSCR_VXIMZ PPC32_CPU_REG(FLG_FPSCR_VXIMZ)
#define PPC32_FLG_FPSCR_VXZDZ PPC32_CPU_REG(FLG_FPSCR_VXZDZ)
#define PPC32_FLG_FPSCR_VXIDI PPC32_CPU_REG(FLG_FPSCR_VXIDI)
#define PPC32_FLG_FPSCR_VXISI PPC32_CPU_REG(FLG_FPSCR_VXISI)
#define PPC32_FLG_FPSCR_VXSNAN PPC32_CPU_REG(FLG_FPSCR_VXSNAN)
#define PPC32_FPU_OP_BITS (sizeof(Uns8) * 32)
#define PPC32_FPU_OP PPC32_CPU_REG(FPU_OP)
#define PPC32_FPU_REL_GEN PPC32_CPU_REG(FPU_REL_GEN)
#define PPC32_FPU_REL PPC32_CPU_REG(FPU_REL)
#define PPC32_CNV32_REL PPC32_CPU_REG(CNV32_REL)
#define PPC32_TEMP_REL PPC32_CPU_REG(TEMP_REL)
#define PPC32_FLG_FP_LDST PPC32_CPU_REG(FLG_FP_LDST)
#define PPC32_CPU_REG_CONST(_F) VMI_CPU_REG_CONST(ppc32P, _F)
#define PPC32_GPR_CONST(_R) PPC32_CPU_REG_CONST(GPR[_R])
#define PPC32_FPR_CONST(_R) PPC32_CPU_REG_CONST(FPR[_R])
#define PPC32_VR_CONST(_R) PPC32_CPU_REG_CONST(VR[_R])
#define PPC32_CR_CONST PPC32_CPU_REG_CONST(CR)
#define PPC32_XER_CONST PPC32_CPU_REG_CONST(XER)
#define PPC32_XER_SO_CONST PPC32_CPU_REG_CONST(XER_SO)
#define PPC32_XER_OV_CONST PPC32_CPU_REG_CONST(XER_OV)
#define PPC32_XER_CA_CONST PPC32_CPU_REG_CONST(XER_CA)
#define PPC32_LT_CONST(_R) PPC32_CPU_REG_CONST(LT[_R])
#define PPC32_GT_CONST(_R) PPC32_CPU_REG_CONST(GT[_R])
#define PPC32_EQ_CONST(_R) PPC32_CPU_REG_CONST(EQ[_R])
#define PPC32_SO_CONST(_R) PPC32_CPU_REG_CONST(SO[_R])
#define PPC32_TEMP_CONST(_R) PPC32_CPU_TEMP_CONST(TEMP[_R])
#define PPC32_LR_CONST PPC32_CPU_REG_CONST(LR)
#define PPC32_CTR_CONST PPC32_CPU_REG_CONST(CTR)
#define PPC32_DSCR_CONST PPC32_CPU_REG_CONST(DSCR)
#define PPC32_DSISR_CONST PPC32_CPU_REG_CONST(DSISR)
#define PPC32_DAR_CONST PPC32_CPU_REG_CONST(DAR)
#define PPC32_DEC_CONST PPC32_CPU_REG_CONST(DEC)
#define PPC32_DEC_TMR_CONST PPC32_CPU_REG_CONST(DEC_tmr)
#define PPC32_SDR1_CONST PPC32_CPU_REG_CONST(SDR1)
#define PPC32_SRR0_CONST PPC32_CPU_REG_CONST(SRR0)
#define PPC32_SRR1_CONST PPC32_CPU_REG_CONST(SRR1)
#define PPC32_CFAR_CONST PPC32_CPU_REG_CONST(CFAR)
#define PPC32_AMR_CONST PPC32_CPU_REG_CONST(AMR)
#define PPC32_PID0_CONST PPC32_CPU_REG_CONST(PID0)
#define PPC32_DECAR_CONST PPC32_CPU_REG_CONST(DECAR)
#define PPC32_CSRR0_CONST PPC32_CPU_REG_CONST(CSRR0)
#define PPC32_CSRR1_CONST PPC32_CPU_REG_CONST(CSRR1)
#define PPC32_DEAR_CONST PPC32_CPU_REG_CONST(DEAR)
#define PPC32_ESR_CONST PPC32_CPU_REG_CONST(ESR)
#define PPC32_IVPR_CONST PPC32_CPU_REG_CONST(IVPR)
#define PPC32_CTRL_CONST PPC32_CPU_REG_CONST(CTRL)
#define PPC32_VRSAVE_CONST PPC32_CPU_REG_CONST(VRSAVE)
#define PPC32_SPRG0_CONST PPC32_CPU_REG_CONST(SPRG0)
#define PPC32_SPRG1_CONST PPC32_CPU_REG_CONST(SPRG1)
#define PPC32_SPRG2_CONST PPC32_CPU_REG_CONST(SPRG2)
#define PPC32_SPRG3_CONST PPC32_CPU_REG_CONST(SPRG3)
#define PPC32_SPRG4_CONST PPC32_CPU_REG_CONST(SPRG4)
#define PPC32_SPRG5_CONST PPC32_CPU_REG_CONST(SPRG5)
#define PPC32_SPRG6_CONST PPC32_CPU_REG_CONST(SPRG6)
#define PPC32_SPRG7_CONST PPC32_CPU_REG_CONST(SPRG7)
#define PPC32_TB_CONST PPC32_CPU_REG_CONST(TB)
#define PPC32_TBU_CONST PPC32_CPU_REG_CONST(TBU)
#define PPC32_EAR_CONST PPC32_CPU_REG_CONST(EAR)
#define PPC32_PIR_CONST PPC32_CPU_REG_CONST(PIR)
#define PPC32_PVR_CONST PPC32_CPU_REG_CONST(PVR)
#define PPC32_HSPRG_CONST(_R) PPC32_CPU_REG_CONST(HSPRG[_R])
#define PPC32_DBSR_CONST PPC32_CPU_REG_CONST(DBSR)
#define PPC32_HDSISR_CONST PPC32_CPU_REG_CONST(HDSISR)
#define PPC32_HDAR_CONST PPC32_CPU_REG_CONST(HDAR)
#define PPC32_DBCR0_CONST PPC32_CPU_REG_CONST(DBCR0)
#define PPC32_SPURR_CONST PPC32_CPU_REG_CONST(SPURR)
#define PPC32_PURR_CONST PPC32_CPU_REG_CONST(PURR)
#define PPC32_DBCR1_CONST PPC32_CPU_REG_CONST(DBCR1)
#define PPC32_HDEC_CONST PPC32_CPU_REG_CONST(HDEC)
#define PPC32_DBCR2_CONST PPC32_CPU_REG_CONST(DBCR2)
#define PPC32_RMOR_CONST PPC32_CPU_REG_CONST(RMOR)
#define PPC32_IAC1_CONST PPC32_CPU_REG_CONST(IAC1)
#define PPC32_IAC2_CONST PPC32_CPU_REG_CONST(IAC2)
#define PPC32_IAC3_CONST PPC32_CPU_REG_CONST(IAC3)
#define PPC32_IAC4_CONST PPC32_CPU_REG_CONST(IAC4)
#define PPC32_HRMOR_CONST PPC32_CPU_REG_CONST(HRMOR)
#define PPC32_HSRR0_CONST PPC32_CPU_REG_CONST(HSRR0)
#define PPC32_HSRR1_CONST PPC32_CPU_REG_CONST(HSRR1)
#define PPC32_DAC1_CONST PPC32_CPU_REG_CONST(DAC1)
#define PPC32_DAC2_CONST PPC32_CPU_REG_CONST(DAC2)
#define PPC32_LPCR_CONST PPC32_CPU_REG_CONST(LPCR)
#define PPC32_DVC1_CONST PPC32_CPU_REG_CONST(DVC1)
#define PPC32_DVC2_CONST PPC32_CPU_REG_CONST(DVC2)
#define PPC32_LPIDR_CONST PPC32_CPU_REG_CONST(LPIDR)
#define PPC32_TSR_CONST PPC32_CPU_REG_CONST(TSR)
#define PPC32_HMER_CONST PPC32_CPU_REG_CONST(HMER)
#define PPC32_HMEER_CONST PPC32_CPU_REG_CONST(HMEER)
#define PPC32_PCR_CONST PPC32_CPU_REG_CONST(PCR)
#define PPC32_HEIR_CONST PPC32_CPU_REG_CONST(HEIR)
#define PPC32_TCR_CONST PPC32_CPU_REG_CONST(TCR)
#define PPC32_IVOR0_CONST PPC32_CPU_REG_CONST(IVOR0)
#define PPC32_IVOR1_CONST PPC32_CPU_REG_CONST(IVOR1)
#define PPC32_IVOR2_CONST PPC32_CPU_REG_CONST(IVOR2)
#define PPC32_IVOR3_CONST PPC32_CPU_REG_CONST(IVOR3)
#define PPC32_IVOR4_CONST PPC32_CPU_REG_CONST(IVOR4)
#define PPC32_IVOR5_CONST PPC32_CPU_REG_CONST(IVOR5)
#define PPC32_IVOR6_CONST PPC32_CPU_REG_CONST(IVOR6)
#define PPC32_IVOR7_CONST PPC32_CPU_REG_CONST(IVOR7)
#define PPC32_IVOR8_CONST PPC32_CPU_REG_CONST(IVOR8)
#define PPC32_IVOR9_CONST PPC32_CPU_REG_CONST(IVOR9)
#define PPC32_IVOR10_CONST PPC32_CPU_REG_CONST(IVOR10)
#define PPC32_IVOR11_CONST PPC32_CPU_REG_CONST(IVOR11)
#define PPC32_IVOR12_CONST PPC32_CPU_REG_CONST(IVOR12)
#define PPC32_IVOR13_CONST PPC32_CPU_REG_CONST(IVOR13)
#define PPC32_IVOR14_CONST PPC32_CPU_REG_CONST(IVOR14)
#define PPC32_IVOR15_CONST PPC32_CPU_REG_CONST(IVOR15)
#define PPC32_SPEFSCR_CONST PPC32_CPU_REG_CONST(SPEFSCR)
#define PPC32_ATB_CONST PPC32_CPU_REG_CONST(ATB)
#define PPC32_IVOR32_CONST PPC32_CPU_REG_CONST(IVOR32)
#define PPC32_IVOR33_CONST PPC32_CPU_REG_CONST(IVOR33)
#define PPC32_IVOR34_CONST PPC32_CPU_REG_CONST(IVOR34)
#define PPC32_IVOR35_CONST PPC32_CPU_REG_CONST(IVOR35)
#define PPC32_IVOR36_CONST PPC32_CPU_REG_CONST(IVOR36)
#define PPC32_IVOR37_CONST PPC32_CPU_REG_CONST(IVOR37)
#define PPC32_MCSRR0_CONST PPC32_CPU_REG_CONST(MCSRR0)
#define PPC32_MCSRR1_CONST PPC32_CPU_REG_CONST(MCSRR1)
#define PPC32_MCSR_CONST PPC32_CPU_REG_CONST(MCSR)
#define PPC32_DSRR0_CONST PPC32_CPU_REG_CONST(DSRR0)
#define PPC32_DSRR1_CONST PPC32_CPU_REG_CONST(DSRR1)
#define PPC32_SPRG8_CONST PPC32_CPU_REG_CONST(SPRG8)
#define PPC32_SPRG9_CONST PPC32_CPU_REG_CONST(SPRG9)
#define PPC32_MAS0_CONST PPC32_CPU_REG_CONST(MAS0)
#define PPC32_MAS1_CONST PPC32_CPU_REG_CONST(MAS1)
#define PPC32_MAS2_CONST PPC32_CPU_REG_CONST(MAS2)
#define PPC32_MAS3_CONST PPC32_CPU_REG_CONST(MAS3)
#define PPC32_MAS4_CONST PPC32_CPU_REG_CONST(MAS4)
#define PPC32_MAS6_CONST PPC32_CPU_REG_CONST(MAS6)
#define PPC32_MAS7_CONST PPC32_CPU_REG_CONST(MAS7)
#define PPC32_PID1_CONST PPC32_CPU_REG_CONST(PID1)
#define PPC32_PID2_CONST PPC32_CPU_REG_CONST(PID2)
#define PPC32_TLB0CFG_CONST PPC32_CPU_REG_CONST(TLB0CFG)
#define PPC32_TLB1CFG_CONST PPC32_CPU_REG_CONST(TLB1CFG)
#define PPC32_TLB2CFG_CONST PPC32_CPU_REG_CONST(TLB2CFG)
#define PPC32_TLB3CFG_CONST PPC32_CPU_REG_CONST(TLB3CFG)
#define PPC32_EPR_CONST PPC32_CPU_REG_CONST(EPR)
#define PPC32_PERF_MON_CONST(_R) PPC32_CPU_REG_CONST(perf_mon[_R])
#define PPC32_PPR_CONST PPC32_CPU_REG_CONST(PPR)
#define PPC32_DCDBTRL_CONST PPC32_CPU_REG_CONST(DCDBTRL)
#define PPC32_DCDBTRH_CONST PPC32_CPU_REG_CONST(DCDBTRH)
#define PPC32_ICDBTRL_CONST PPC32_CPU_REG_CONST(ICDBTRL)
#define PPC32_ICDBTRH_CONST PPC32_CPU_REG_CONST(ICDBTRH)
#define PPC32_EPLC_CONST PPC32_CPU_REG_CONST(EPLC)
#define PPC32_EPSC_CONST PPC32_CPU_REG_CONST(EPSC)
#define PPC32_ICDBDR_CONST PPC32_CPU_REG_CONST(ICDBDR)
#define PPC32_MMUCSR0_CONST PPC32_CPU_REG_CONST(MMUCSR0)
#define PPC32_DABR_CONST PPC32_CPU_REG_CONST(DABR)
#define PPC32_DABRX_CONST PPC32_CPU_REG_CONST(DABRX)
#define PPC32_MMUCFG_CONST PPC32_CPU_REG_CONST(MMUCFG)
#define PPC32_FPSCR_CONST PPC32_CPU_REG_CONST(FPSCR)
#define PPC32_VSCR_CONST PPC32_CPU_REG_CONST(VSCR)
#define PPC32_ACCUMULATOR_CONST PPC32_CPU_REG_CONST(Accumulator)
#define PPC32_MSR_CONST PPC32_CPU_REG_CONST(MSR)
#define PPC32_RESERVE_ADDR_CONST PPC32_CPU_REG_CONST(RESERVE_ADDR)
#define PPC32_RESERVE_CONST PPC32_CPU_REG_CONST(RESERVE)
#define PPC32_FLG_CI_CONST PPC32_CPU_REG_CONST(FLG_CI)
#define PPC32_FLG_CO_CONST PPC32_CPU_REG_CONST(FLG_CO)
#define PPC32_FLG_PA_CONST PPC32_CPU_REG_CONST(FLG_PA)
#define PPC32_FLG_ZR_CONST PPC32_CPU_REG_CONST(FLG_ZR)
#define PPC32_FLG_SI_CONST PPC32_CPU_REG_CONST(FLG_SI)
#define PPC32_FLG_OV_CONST PPC32_CPU_REG_CONST(FLG_OV)
#define PPC32_FLG_TEMP_CONST PPC32_CPU_REG_CONST(FLG_TEMP)
#define PPC32_FLG_FP_SI_CONST PPC32_CPU_REG_CONST(FLG_FP_SI)
static inline const char *getstr_AALK(int index) {
static const char *lookup[] = {
[0] "",
[1] "L",
[2] "A",
[3] "LA",
};
return lookup[index];
}
static inline const char *getstr_BITSTR(int index) {
static const char *lookup[] = {
[0] "DNZF-",
[1] "DNZF+",
[2] "DZF-",
[3] "DZF+",
[4] "NZF-",
[5] "NZF+",
[6] "ZF-",
[7] "ZF+",
[8] "DNZT-",
[9] "DNZT+",
[10] "DZT-",
[11] "DZT+",
[12] "NZT-",
[13] "NZT+",
[14] "ZT-",
[15] "ZT+",
};
return lookup[index];
}
static inline const char *getstr_BITSTR32(int index) {
static const char *lookup[] = {
[0] "F",
[1] "T",
[2] "DNZ",
[3] "DZ",
};
return lookup[index];
}
static inline const char *getstr_CR(int index) {
static const char *lookup[] = {
[0] "LT",
[1] "GT",
[2] "EQ",
[3] "SO",
[4] "4*CR1+LT",
[5] "4*CR1+GT",
[6] "4*CR1+EQ",
[7] "4*CR1+SO",
[8] "4*CR2+LT",
[9] "4*CR2+GT",
[10] "4*CR2+EQ",
[11] "4*CR2+SO",
[12] "4*CR3+LT",
[13] "4*CR3+GT",
[14] "4*CR3+EQ",
[15] "4*CR3+SO",
[16] "4*CR4+LT",
[17] "4*CR4+GT",
[18] "4*CR4+EQ",
[19] "4*CR4+SO",
[20] "4*CR5+LT",
[21] "4*CR5+GT",
[22] "4*CR5+EQ",
[23] "4*CR5+SO",
[24] "4*CR6+LT",
[25] "4*CR6+GT",
[26] "4*CR6+EQ",
[27] "4*CR6+SO",
[28] "4*CR7+LT",
[29] "4*CR7+GT",
[30] "4*CR7+EQ",
[31] "4*CR7+SO",
};
return lookup[index];
}
static inline const char *getstr_CRVLE(int index) {
static const char *lookup[] = {
[0] "CR0+LT",
[1] "CR0+GT",
[2] "CR0+EQ",
[3] "CR0+SO",
[4] "CR1+LT",
[5] "CR1+GT",
[6] "CR1+EQ",
[7] "CR1+SO",
[8] "CR2+LT",
[9] "CR2+GT",
[10] "CR2+EQ",
[11] "CR2+SO",
[12] "CR3+LT",
[13] "CR3+GT",
[14] "CR3+EQ",
[15] "CR3+SO",
};
return lookup[index];
}
static inline const char *getstr_EH(int index) {
static const char *lookup[] = {
[1] "_1",
};
return lookup[index];
}
static inline const char *getstr_RA(int index) {
static const char *lookup[] = {
[0] "0",
[1] "R1",
[2] "R2",
[3] "R3",
[4] "R4",
[5] "R5",
[6] "R6",
[7] "R7",
[8] "R8",
[9] "R9",
[10] "R10",
[11] "R11",
[12] "R12",
[13] "R13",
[14] "R14",
[15] "R15",
[16] "R16",
[17] "R17",
[18] "R18",
[19] "R19",
[20] "R20",
[21] "R21",
[22] "R22",
[23] "R23",
[24] "R24",
[25] "R25",
[26] "R26",
[27] "R27",
[28] "R28",
[29] "R29",
[30] "R30",
[31] "R31",
};
return lookup[index];
}
static inline const char *getstr_TO(int index) {
static const char *lookup[] = {
[1] "LGT",
[2] "LLT",
[4] "EQ",
[5] "LGE",
[6] "LLE",
[8] "GT",
[12] "GE",
[16] "LT",
[20] "LE",
[24] "NE",
};
return lookup[index];
}
#define CPU_PREFIX "PPC32"
typedef Uns32 ppc32Addr;
#endif // PPC32_NE_H
| 29.312634 | 95 | 0.735822 | [
"model"
] |
3bea05dd5b169cc61c990bce767b0558d4841120 | 5,663 | h | C | src/utils/settings.h | ShnitzelKiller/Reverse-Engineering-Carpentry | 585b5ff053c7e3bf286b663a584bc83687691bd6 | [
"MIT"
] | 3 | 2021-09-08T07:28:13.000Z | 2022-03-02T21:12:40.000Z | src/utils/settings.h | ShnitzelKiller/Reverse-Engineering-Carpentry | 585b5ff053c7e3bf286b663a584bc83687691bd6 | [
"MIT"
] | 1 | 2021-09-21T14:40:55.000Z | 2021-09-26T01:19:38.000Z | src/utils/settings.h | ShnitzelKiller/Reverse-Engineering-Carpentry | 585b5ff053c7e3bf286b663a584bc83687691bd6 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <cmath>
struct Settings {
float final_scale=20.0f;
int random_seed=1234;
/** larger values means finer detail, e.g. more primitives fit more precisely to smaller features */
float master_resolution=300.0f;
//float threshold = -1.0f;
float normal_threshold = -1;//0.4;
/** if greater than 1, merge coplanar points more aggressively, if less than 1, more islands */
float clustering_factor = 0.5f;
float constraint_factor = 3.0f;
//float cluster_epsilon = -1.0f;
/** probability of missing primitives in RANSAC (lower = higher quality) */
float probability = 0.01f;
/** percent of total points that need to be included in a primitive for it to be valid */
float support = 0.25f;
/** detect cylinders along with planes */
int use_cylinders = 0;
//float adjacency_threshold = -1;
/** if greater than 1, consider more primitives adjacent, if less, fewer */
float adjacency_factor = 2.0f;
//float adjacency_edge_threshold = -1;
///** if greater than 1, generate intersection edges between more primitives, if less, fewer */
//float adjacency_edge_factor = 2.0f;
float alpha = -1;
/** resolution of grid for finding cut paths and depths */
float voxel_resolution = 100.0f;
float max_contour_hole_ratio = 5.0f;
int k_n = 15;
int use_winding_number = 0;
int winding_number_stride = 10;
int use_geocuts = 0;
/** threshold for marching squares */
float contour_threshold = 0.25f;
size_t min_view_support = -1;
int max_views_per_cluster = 5;
float max_view_angle = 3*static_cast<float>(M_PI)/8;
float max_view_angle_cos;
/** number of curves used to represent outer shapes */
int outer_curve_count = 7;
/** number of curves used to represent inner holes */
int inner_curve_count = 5;
/** minimum angle at curve interfaces (radians) */
float min_knot_angle = 0.34f;
/** maximum number of knots to consider in curve fitting algorithm (-1: no restriction) */
int max_knots = 50;
/** weight to apply to curves (higher than 1 means more costly) */
float curve_weight = 1.0f;
/** cost of extra line segments in shape fitting */
float line_cost = 0.05f;
/** cost of extra bezier curves in shape fitting */
float curve_cost = 0.1f;
float edge_detection_threshold = 0.0f;
float max_thickness = -1.0f;
int thickness_resolution = 100;
/** total thickness candidates to initially keep per part */
int thickness_candidates = 1;
/** number of unique depths to allow in final model */
int thickness_clusters = 5;
/** factor by which derivative scores are divided for every diameter traversed by depth */
float thickness_spatial_discount_factor = 100.0f;
/** maximum dot product between two planes' normals to be considered adjacent */
float norm_adjacency_threshold = 0.2f;
///** minimum absolute value of dot product between two planes' normals to be considered parallel (for finding otherOpposing pairs of parallel planes) */
float norm_parallel_threshold = 0.9f;
/** minimum dot product for aligning parts to be parallel */
float align_parallel_threshold = 0.99f;
/** number of initial samples to generate in the model bounding box */
size_t sample_count = 1000000;
/** minimum number of samples in an intersection term to be exported to the constraint solver (<0 means do not filter) */
int min_samples = -1;
/** maximum number of intersection terms exported to the constraints file */
int max_constraints = -1;
/** minimum number of parts that must potentially overlap with a point */
int min_part_overlap = 1;
std::string points_filename = "points.ply";
std::string mesh_filename;
std::string reconstruction_path;
std::string image_path;
std::string depth_path;
std::string globfit_export;
std::string globfit_import;
float globfit_scale=1.0f;
std::string result_path="solution";
std::string curvefit_checkpoint;
std::string segmentation_checkpoint;
std::string connection_checkpoint;
std::string selection_checkpoint;
std::string oldresult_checkpoint;
std::string connector_mesh;
float connector_spacing=1;
float connector_scale=1;
float image_scale = 0.5f;
int max_image_resolution=std::numeric_limits<int>::max();
int min_pixels_per_voxel=5;
float correction_factor = 1.0f;
int patch_radius = 3;
int use_segmentation = 0;
int segmentation_max_views_per_cluster = 3;
int segmentation_iters = 5;
float segmentation_scale = 0.5f;
float segmentation_data_weight = 1.0f;
float segmentation_smoothing_weight = 50.0f;
int segmentation_8way = false;
float segmentation_penalty = 100.0f;
float segmentation_sigma = 50.0f;
float segmentation_precision = 1;
int segmentation_levels = 1;
int segmentation_gmm_components = 5;
float segmentation_gmm_min_variance = 10.0f;
int segmentation_min_pixel_support = 200;
float segmentation_clean_precision_threshold = 0.5f;
float segmentation_clean_recall_threshold = 0.9f;
size_t population_size = 1;
int generations = 2000;
float max_overlap_ratio=0.5f;
int alignment_stride=10;
double alignment_tol=1e-6;
int visualization_stride=1;
int visualize=1;
int debug_visualization=0;
std::string settings_path;
bool store_line(const std::string &key, const std::string &value);
bool parse_file(const std::string &settings_filename);
void setDerived();
};
std::ostream &operator<<(std::ostream &o, const Settings &s); | 41.335766 | 157 | 0.705103 | [
"shape",
"model"
] |
3bf85a4ae200387a912db6ff915e64144f008553 | 656 | h | C | include/rrtstar/rrtstarplanner.h | WPI-ARC/rrtstar | 87cb6bf6913f530b6b6a59e33a34840576c1252b | [
"BSD-2-Clause"
] | 3 | 2015-04-16T14:43:20.000Z | 2019-07-30T11:33:58.000Z | include/rrtstar/rrtstarplanner.h | WPI-ARC/rrtstar | 87cb6bf6913f530b6b6a59e33a34840576c1252b | [
"BSD-2-Clause"
] | null | null | null | include/rrtstar/rrtstarplanner.h | WPI-ARC/rrtstar | 87cb6bf6913f530b6b6a59e33a34840576c1252b | [
"BSD-2-Clause"
] | null | null | null | #include "stdlib.h"
#include "stdio.h"
#include <string>
#include "string.h"
#include <iostream>
#include <algorithm>
#include <vector>
#include <openrave/openrave.h>
#ifndef RRTSTAR_PLANNER_H
#define RRTSTAR_PLANNER_H
class RRTstarPlanner : public OpenRAVE::PlannerBase
{
public:
RRTstarPlanner(OpenRAVE::EnvironmentBasePtr penv);
~RRTstarPlanner() {}
bool InitPlan(OpenRAVE::RobotBasePtr robot, OpenRAVE::PlannerBase::PlannerParametersConstPtr params);
OpenRAVE::PlannerStatus PlanPath(OpenRAVE::TrajectoryBasePtr traj);
OpenRAVE::PlannerBase::PlannerParametersConstPtr GetParameters() const;
};
#endif // RRTSTAR_PLANNER_H
| 21.16129 | 105 | 0.769817 | [
"vector"
] |
ce025c7836cfeb2a4f0e67127da1ab2552131f37 | 4,682 | h | C | DependencyLogic/GlobExport/patch.h | josephbirkner/dependency-studio | 478e44afe4285db6d7c3a3e4b4226fa2b95045f5 | [
"MIT"
] | null | null | null | DependencyLogic/GlobExport/patch.h | josephbirkner/dependency-studio | 478e44afe4285db6d7c3a3e4b4226fa2b95045f5 | [
"MIT"
] | null | null | null | DependencyLogic/GlobExport/patch.h | josephbirkner/dependency-studio | 478e44afe4285db6d7c3a3e4b4226fa2b95045f5 | [
"MIT"
] | null | null | null | /* __ __ __ __
____/ /___ ____ ____ ____ ____/ /___ ____ _______ __ ______/ /_ ______/ /_____
/ __, / __ \/ __ \/ __ \/ ,_ \/ __, / __ \/ ,_ \/ ___/ / / / / ___\, / / / / __, /_/ __ \
/ /_/ / /_/ / /_/ / /_/ / / / / /_/ / /_/ / / / / /__/ /_/ / _\__, / / /_/ / /_/ / / /_/ /
\____/ ,___/ ,___/ ,___/\/ /_/\____/ ,___/\/ /_/\___/\__, / \____/\/\___,_\____/\/\____/
\____/\/ \____/ \____/ \/
__ ____ ______ ____ ____ ____ ____________ __ __
/ /_/ / / / / __ \ / __ \/ ,__\ /__, \/ __ \, /__, \ __/ / /_/
/ ,_, / / / / /_/ / / /_/ / / __ ____/ / / / / /___/ / /_/ /_ / /
/ / / / /_/ / ,___/ / ,_, / /_/ / / ,___/ /_/ / / ,___/ / / ,_ \/ /
\/ \/\____/\/ \/ \/\____/ \____/\____/_/\____/ /\ ___/ / /_/ /_/
'/ \___/\____/ */
#ifndef _DEPENDENCYCONTROL_PATCH_H_
#define _DEPENDENCYCONTROL_PATCH_H_
#ifdef DEPENDENCYLOGIC_EXPORTS
#define DEPENDENCYLOGIC_API __declspec(dllexport)
#else
#define DEPENDENCYLOGIC_API __declspec(dllimport)
#endif
#include "StdAfx.h"
#include "contrib\DependencyControl\DependencyLogic\GlobExport\errorlist.h"
namespace DependencyLogic
{
enum PatchMode
{
PatchTestSilent = 1, /** Insertion will be simulated (but the actual binaries will not be replaced) */
PatchTest, /** Insertion will be simulated (but the actual binaries will not be replaced),
and the results of the simulated patch will be displayed. */
TestWithOtherSystem, /** A special resolve test: Using this mode, you can check, whether missing modules
in your database can be resolved using another database file. */
PatchReplaceShowResults, /** Insertion will be simulated (before the actual binaries get replaced).
The user can abort the replacement over the display of the simulation results. */
PatchReplaceForce /** The binaries will be replaced and the database updated, without any user interaction,
regardless of dependency errors introduced by the patch. Optionally, the results will be
written to a patch logfile. */
};
/**
* @about Functor to execute or simulate a patch for one or more binaries.
* A progress dialog will be shown depicting the state of the insertion.
* A PatchMode can be issued to control the behaviour of the functor.
* @see operator bool(), operator int()
*/
class DEPENDENCYLOGIC_API Patch
{
public:
/**
* @about Functor ctor. Will execute the patching/database update.
* @param nMode Indicates one of PatchTest, PatchReplaceShowResults or PatchReplaceForce.
* @param vsPathes
* @param pSystem
* @param sLogFile
*/
Patch(__in PatchMode nMode, __in std::vector<std::string> vsPathes, __in __notnull System* pSystem, __in_opt std::string sLogFile = "");
/** Displays all log messages in a MessageBox. */
int displayLog();
/** Patch destructor. Will close the logfile if necessary. */
~Patch();
/** Writes a log message to the log file if existing. */
void log(std::string sMessage);
/** Executes the patch operation. Returns whether any errors were detected. */
bool execute();
private:
typedef std::pair<Module*, std::string> ModuleAndNewPath;
bool addModulePathForPatch( const std::string& sPath );
bool addModuleForPatchFromOtherSystem( Module const* pOtherModule);
/** The log file which results are written to. Might be Null. */
FILE* m_pLogFile;
/** All the lines that will be displayed/written to the log. */
std::list<std::string> m_lsResult;
/** ProgressDialog displaying the progress of the update process for all given modules. */
CProgressDlg m_dlgProgress;
/** PatchMode issued in the constructor */
PatchMode m_nMode;
/** List of errors taht existed before the Patch was introduced */
ErrorList m_lsOldErrors;
/** List of the module instances with the new pathes they should have */
std::list<ModuleAndNewPath> m_lsModulePathes;
/** Modules to be imported from another system (resolve_with_other_system) */
std::list<Module*> m_lsOtherSystemModules;
/** The system the Patch is executed on */
System* m_pSystem;
/** For the resolve_with_other_system-command, this is the other system */
System* m_pOther;
};
}
#endif | 43.757009 | 139 | 0.594404 | [
"vector"
] |
ce06762bac0c552eb43379c8f2011a29e0912a12 | 1,516 | h | C | RogueEngine/Source/ParentChildSystem.h | silferysky/RogueArcher | 3c77696260f773a0b7adb88b991e09bb35069901 | [
"FSFAP"
] | 1 | 2019-06-18T20:07:47.000Z | 2019-06-18T20:07:47.000Z | RogueEngine/Source/ParentChildSystem.h | silferysky/RogueArcher | 3c77696260f773a0b7adb88b991e09bb35069901 | [
"FSFAP"
] | null | null | null | RogueEngine/Source/ParentChildSystem.h | silferysky/RogueArcher | 3c77696260f773a0b7adb88b991e09bb35069901 | [
"FSFAP"
] | null | null | null | /* Start Header ************************************************************************/
/*!
\file ParentChildSystem.h
\project Exale
\author Chan Wai Kit Terence, c.terence, 440005918 (100%)
\par c.terence\@digipen.edu
\date 3 April,2020
\brief This file contains the functions definitions for ParentChildSystem
All content (C) 2020 DigiPen (SINGAPORE) Corporation, all rights
reserved.
Reproduction or disclosure of this file or its contents
without the prior written consent of DigiPen Institute of
Technology is prohibited.
*/
/* End Header **************************************************************************/
#pragma once
#include "BaseSystem.h"
#include "EventListener.h"
#include "ChildComponent.h"
namespace Rogue
{
class ParentChildSystem
: public System, public EventListener
{
public:
ParentChildSystem();
~ParentChildSystem() = default;
//Basic System
void Init() override;
void Update() override;
void Shutdown() override;
void Receive(Event& ev) override;
//Accessing all entities that are children. Assume they all have ChildComponents
void AddChildToVector(std::vector<Entity>& entityVector, Entity ParentEntity);
//Same as the update loop, but callable
void ApplyParentChildTransform(Entity entity);
//Parent/Child Assignment
bool CheckValidReassign(Entity newParent, Entity child);
void ReassignParentChildFlags(Entity newParent, Entity child);
void ResetParentChildFlags(Entity child);
};
} | 30.938776 | 89 | 0.666887 | [
"vector"
] |
ce0689d69209b514371369f11503b2d5c2f1f5ac | 1,350 | h | C | src/Game.h | KnockerPulsar/Raylib-Pong-ECS | 1451b3d9d77f6caf3748342465c723039cf673a0 | [
"MIT"
] | 5 | 2022-02-21T23:37:54.000Z | 2022-02-23T20:50:36.000Z | src/Game.h | KnockerPulsar/Raylib-Pong-ECS | 1451b3d9d77f6caf3748342465c723039cf673a0 | [
"MIT"
] | null | null | null | src/Game.h | KnockerPulsar/Raylib-Pong-ECS | 1451b3d9d77f6caf3748342465c723039cf673a0 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <string>
#include "../include/raylib-cpp/include/raylib-cpp.hpp"
#include "Event.h"
namespace pong
{
class IScene;
// The glue that holds the game together
// Only one instance should be active at a time
class Game
{
private:
static std::vector<IScene *> scenes;
static std::vector<Event *> events;
public:
static IScene *currScene;
Game(int windowWidth, int windowHeight, std::string windowTitle, int targetFPS = 60, TraceLogLevel logLevel = LOG_INFO);
Game *AddScene(IScene *scene);
// Currently just calls currentScene->Start(nullptr)
// Might be useful for more initializations
void Init();
void Run();
void CheckGameEvents(float dT);
template <typename func, typename... args>
static void AddEvent(float delay, func &&fun, args... arguments)
{
Event *ev = new Event();
ev->fn = std::bind(fun, arguments...);
ev->delay = delay;
Game::events.push_back(ev);
}
template <typename func>
static void AddEvent(float delay, func &&fun)
{
Event *ev = new Event();
ev->fn = fun;
ev->delay = delay;
Game::events.push_back(ev);
}
};
} | 25.471698 | 128 | 0.574815 | [
"vector"
] |
22d16f422b814571b5a5522c18bb07ad93b8c90b | 99,634 | c | C | lsass/server/auth-providers/ad-open-provider/join/join.c | kbore/pbis-open | a05eb9309269b6402b4d6659bc45961986ea5eab | [
"Apache-2.0"
] | null | null | null | lsass/server/auth-providers/ad-open-provider/join/join.c | kbore/pbis-open | a05eb9309269b6402b4d6659bc45961986ea5eab | [
"Apache-2.0"
] | null | null | null | lsass/server/auth-providers/ad-open-provider/join/join.c | kbore/pbis-open | a05eb9309269b6402b4d6659bc45961986ea5eab | [
"Apache-2.0"
] | null | null | null | /* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil; tab-width: 4 -*-
* ex: set softtabstop=4 tabstop=8 expandtab shiftwidth=4: *
* Editor Settings: expandtabs and use 4 spaces for indentation */
/*
* Copyright © BeyondTrust Software 2004 - 2019
* 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.
*
* BEYONDTRUST MAKES THIS SOFTWARE AVAILABLE UNDER OTHER LICENSING TERMS AS
* WELL. IF YOU HAVE ENTERED INTO A SEPARATE LICENSE AGREEMENT WITH
* BEYONDTRUST, THEN YOU MAY ELECT TO USE THE SOFTWARE UNDER THE TERMS OF THAT
* SOFTWARE LICENSE AGREEMENT INSTEAD OF THE TERMS OF THE APACHE LICENSE,
* NOTWITHSTANDING THE ABOVE NOTICE. IF YOU HAVE QUESTIONS, OR WISH TO REQUEST
* A COPY OF THE ALTERNATE LICENSING TERMS OFFERED BY BEYONDTRUST, PLEASE CONTACT
* BEYONDTRUST AT beyondtrust.com/contact
*/
/*
* Copyright (C) BeyondTrust Software. All rights reserved.
*
* Module Name:
*
* join.c
*
* Abstract:
*
* BeyondTrust Security and Authentication Subsystem (LSASS)
*
* Join to Active Directory
*
* Authors: Krishna Ganugapati (krishnag@likewisesoftware.com)
* Sriram Nambakam (snambakam@likewisesoftware.com)
*/
#include "includes.h"
#define LSA_JOIN_MAX_ALLOWED_CLOCK_DRIFT_SECONDS 60
#define MACHPASS_LEN (16)
static
DWORD
LsaJoinDomainInternal(
PWSTR pwszHostname,
PWSTR pwszDnsDomain,
PWSTR pwszDomain,
PWSTR pwszAccountOu,
PWSTR pwszAccount,
PWSTR pwszPassword,
DWORD dwJoinFlags,
DWORD dwUserAccountAttributes,
PWSTR pwszOsName,
PWSTR pwszOsVersion,
PWSTR pwszOsServicePack,
PSTR pszServicePrincipalNameList
);
static
DWORD
LsaRandBytes(
PBYTE pBuffer,
DWORD dwCount
);
static
DWORD
LsaGenerateMachinePassword(
PWSTR pwszPassword,
size_t sPasswordLen
);
DWORD
LsaGenerateRandomString(
PSTR pszBuffer,
size_t sBufferLen
);
static
DWORD
LsaGetAccountName(
const wchar16_t *machname,
const wchar16_t *domain_controller_name,
const wchar16_t *dns_domain_name,
wchar16_t **account_name,
BOOLEAN *exists
);
static
NTSTATUS
LsaCreateMachineAccount(
PWSTR pwszDCName,
LW_PIO_CREDS pCreds,
PWSTR pwszMachineAccountName,
PWSTR pwszMachinePassword,
DWORD dwJoinFlags,
PWSTR *ppwszDomainName,
PSID *ppDomainSid
);
static
NTSTATUS
LsaEncryptPasswordBufferEx(
PBYTE pPasswordBuffer,
DWORD dwPasswordBufferSize,
PWSTR pwszPassword,
DWORD dwPasswordLen,
PBYTE pSessionKey,
DWORD dwSessionKeyLen
);
static
NTSTATUS
LsaEncodePasswordBuffer(
IN PCWSTR pwszPassword,
OUT PBYTE pBlob,
IN DWORD dwBlobSize
);
static
DWORD
LsaSaveMachinePassword(
PCWSTR pwszMachineName,
PCWSTR pwszMachineAccountName,
PCWSTR pwszMachineDnsDomain,
PCWSTR pwszDomainName,
PCWSTR pwszDnsDomainName,
PCWSTR pwszDCName,
PCWSTR pwszSidStr,
PCWSTR pwszPassword,
PSTR pszServicePrincipalNameList
);
static
DWORD
LsaBuildPrincipalName(
OUT PWSTR *ppPrincipalName,
IN PCWSTR InstanceName,
IN PCWSTR HostName,
IN BOOLEAN UpperCaseHostName,
IN OPTIONAL PCWSTR RealmName,
IN OPTIONAL BOOLEAN UpperCaseRealmName
);
static
DWORD
LsaSavePrincipalKey(
PCWSTR pwszName,
PCWSTR pwszPassword,
DWORD dwPasswordLen,
PCWSTR pwszRealm,
PCWSTR pwszSalt,
PCWSTR pwszDCName,
DWORD dwKvno
);
static
DWORD
LsaDirectoryConnect(
PCWSTR pDomain,
LDAP** ppLdConn,
PWSTR* ppDefaultContext
);
static
DWORD
LsaDirectoryDisconnect(
LDAP *ldconn
);
static
DWORD
LsaMachAcctCreate(
LDAP *ld,
const wchar16_t *machine_name,
const wchar16_t *machacct_name,
const wchar16_t *ou,
BOOLEAN move,
BOOLEAN exists
);
static
DWORD
LsaMachDnsNameSearch(
LDAP *ldconn,
const wchar16_t *fqdn,
const wchar16_t *machname,
const wchar16_t *dn_context,
wchar16_t **samacct
);
static
DWORD
LsaMachAcctSearch(
LDAP *ldconn,
const wchar16_t *name,
const wchar16_t *dn_context,
wchar16_t **pDn,
wchar16_t **pDnsName
);
static
DWORD
LsaMachAcctSetAttribute(
LDAP *ldconn,
const wchar16_t *dn,
const wchar16_t *attr_name,
const wchar16_t **attr_val,
int new
);
static
DWORD
LsaGetNtPasswordHash(
IN PCWSTR pwszPassword,
OUT PBYTE pNtHash,
IN DWORD dwNtHashSize
);
static
DWORD
LsaEncryptNtHashVerifier(
IN PBYTE pNewNtHash,
IN DWORD dwNewNtHashLen,
IN PBYTE pOldNtHash,
IN DWORD dwOldNtHashLen,
OUT PBYTE pNtVerifier,
IN DWORD dwNtVerifierSize
);
static
DWORD
LsaPrepareDesKey(
IN PBYTE pInput,
OUT PBYTE pOutput
);
DWORD
LsaJoinDomainUac(
PCSTR pszHostname,
PCSTR pszHostDnsDomain,
PCSTR pszDomain,
PCSTR pszOU,
PCSTR pszUsername,
PCSTR pszPassword,
PCSTR pszOSName,
PCSTR pszOSVersion,
PCSTR pszOSServicePack,
LSA_NET_JOIN_FLAGS dwFlags,
LSA_USER_ACCOUNT_CONTROL_FLAGS dwUac,
PSTR pszServicePrincipalNameList
)
{
DWORD dwError = 0;
PWSTR pwszHostname = NULL;
PWSTR pwszHostDnsDomain = NULL;
PWSTR pwszDomain = NULL;
PWSTR pwszOU = NULL;
PWSTR pwszOSName = NULL;
PWSTR pwszOSVersion = NULL;
PWSTR pwszOSServicePack = NULL;
DWORD dwOptions = (LSAJOIN_JOIN_DOMAIN |
LSAJOIN_ACCT_CREATE |
LSAJOIN_DOMAIN_JOIN_IF_JOINED);
PLSA_CREDS_FREE_INFO pAccessInfo = NULL;
BAIL_ON_INVALID_STRING(pszHostname);
BAIL_ON_INVALID_STRING(pszDomain);
BAIL_ON_INVALID_STRING(pszUsername);
if (geteuid() != 0) {
dwError = LW_ERROR_ACCESS_DENIED;
BAIL_ON_LSA_ERROR(dwError);
}
LSA_LOG_DEBUG("LsaJoinDomainUac(%s, %s, %s, %s, %s, ********, %s, %s, %s, %x, %x)",
LSA_SAFE_LOG_STRING(pszHostname),
LSA_SAFE_LOG_STRING(pszHostDnsDomain),
LSA_SAFE_LOG_STRING(pszDomain),
LSA_SAFE_LOG_STRING(pszOU),
LSA_SAFE_LOG_STRING(pszUsername),
LSA_SAFE_LOG_STRING(pszOSName),
LSA_SAFE_LOG_STRING(pszOSVersion),
LSA_SAFE_LOG_STRING(pszOSServicePack),
dwFlags, dwUac);
if ( !(dwFlags & LSA_NET_JOIN_DOMAIN_NOTIMESYNC) )
{
dwError = LsaSyncTimeToDC(pszDomain);
BAIL_ON_LSA_ERROR(dwError);
}
if (dwFlags & LSA_NET_JOIN_DOMAIN_NO_PRE_COMPUTER_ACCOUNT)
{
dwOptions |= LSAJOIN_NO_PRE_COMPUTER_ACCOUNT;
}
// TODO-2011/01/13-dalmeida -- Ensure we use UPN.
// Otherwise, whether this works depends on krb5.conf.
// Can cons up UPN if needed since we have domain.
dwError = LsaSetSMBCreds(
pszUsername,
pszPassword,
TRUE,
&pAccessInfo);
BAIL_ON_LSA_ERROR(dwError);
dwError = LwMbsToWc16s(
pszHostname,
&pwszHostname);
BAIL_ON_LSA_ERROR(dwError);
if (!LW_IS_NULL_OR_EMPTY_STR(pszHostDnsDomain))
{
dwError = LwMbsToWc16s(
pszHostDnsDomain,
&pwszHostDnsDomain);
BAIL_ON_LSA_ERROR(dwError);
}
dwError = LwMbsToWc16s(
pszDomain,
&pwszDomain);
BAIL_ON_LSA_ERROR(dwError);
if (!LW_IS_NULL_OR_EMPTY_STR(pszOU))
{
dwError = LwMbsToWc16s(
pszOU,
&pwszOU);
BAIL_ON_LSA_ERROR(dwError);
}
if (!LW_IS_NULL_OR_EMPTY_STR(pszOSName)) {
dwError = LwMbsToWc16s(
pszOSName,
&pwszOSName);
BAIL_ON_LSA_ERROR(dwError);
}
if (!LW_IS_NULL_OR_EMPTY_STR(pszOSVersion)) {
dwError = LwMbsToWc16s(
pszOSVersion,
&pwszOSVersion);
BAIL_ON_LSA_ERROR(dwError);
}
if (!LW_IS_NULL_OR_EMPTY_STR(pszOSServicePack)) {
dwError = LwMbsToWc16s(
pszOSServicePack,
&pwszOSServicePack);
BAIL_ON_LSA_ERROR(dwError);
}
dwError = LsaJoinDomainInternal(
pwszHostname,
pwszHostDnsDomain,
pwszDomain,
pwszOU,
NULL,
NULL,
dwOptions,
dwUac,
pwszOSName,
pwszOSVersion,
pwszOSServicePack,
pszServicePrincipalNameList);
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaPstoreSetDomainWTrustEnumerationWaitTime(pwszDomain);
BAIL_ON_LSA_ERROR(dwError);
cleanup:
LsaFreeSMBCreds(&pAccessInfo);
LW_SAFE_FREE_MEMORY(pwszHostname);
LW_SAFE_FREE_MEMORY(pwszHostDnsDomain);
LW_SAFE_FREE_MEMORY(pwszDomain);
LW_SAFE_FREE_MEMORY(pwszOU);
LW_SAFE_FREE_MEMORY(pwszOSName);
LW_SAFE_FREE_MEMORY(pwszOSVersion);
LW_SAFE_FREE_MEMORY(pwszOSServicePack);
return dwError;
error:
goto cleanup;
}
DWORD
LsaSyncTimeToDC(
PCSTR pszDomain
)
{
DWORD dwError = 0;
LWNET_UNIX_TIME_T dcTime = 0;
time_t ttDCTime = 0;
dwError = LWNetGetDCTime(
pszDomain,
&dcTime);
BAIL_ON_LSA_ERROR(dwError);
ttDCTime = (time_t) dcTime;
if (labs(ttDCTime - time(NULL)) > LSA_JOIN_MAX_ALLOWED_CLOCK_DRIFT_SECONDS) {
dwError = LwSetSystemTime(ttDCTime);
BAIL_ON_LSA_ERROR(dwError);
}
cleanup:
return dwError;
error:
goto cleanup;
}
// Distinguish between nfs, nfs/ and http/www.linuxcomputer.com. If it is
// service class name with trailing slash, then strip the slash.
static
VOID
GroomSpn(PSTR *ppszSpn, BOOLEAN *bIsServiceClass)
{
PSTR pszHasPeriod = NULL;
PSTR pszHasSlash = NULL;
LwStripLeadingWhitespace(*ppszSpn);
LwStripTrailingWhitespace(*ppszSpn);
LwStrChr(*ppszSpn, '.', &pszHasPeriod);
if (pszHasPeriod)
{
*bIsServiceClass = FALSE;
return;
}
LwStrChr(*ppszSpn, '/', &pszHasSlash);
if ((pszHasSlash) && (strlen(pszHasSlash) == 1))
{
*pszHasSlash = '\0';
*bIsServiceClass = TRUE;
}
else if ((pszHasSlash) && (strlen(pszHasSlash) >= 1))
*bIsServiceClass = FALSE;
else
*bIsServiceClass = TRUE;
return;
}
// Input: nfs, NFS, http/linuxhostbox, host, HOST/, http/linuxhostbox2
// Output: NFS, HOST, http/linuxhostbox, http/linuxhostbox2
static
VOID GroomSpnList(PSTR pszSPNameList, PSTR *ppGroomedServicePrincipalList)
{
DWORD dwError = LW_ERROR_SUCCESS;
BOOLEAN bIsServiceClass = FALSE;
PSTR pszServicePrincipalNameList = NULL;
PSTR saveStrPtr = NULL;
PSTR aStr = NULL;
PSTR isStrThere = NULL;
PSTR pszTempStr = NULL;
PSTR pszNewServicePrincipalNameList = NULL;
PSTR pszFqdnList = NULL;
PSTR pszServiceClassList = NULL;
dwError = LwStrDupOrNull(pszSPNameList, &pszServicePrincipalNameList);
BAIL_ON_LSA_ERROR(dwError);
// Tokenize the provided SPN list checking for duplicates SPN values and
// upper casing SPN.
aStr = strtok_r(pszServicePrincipalNameList, ",", &saveStrPtr);
while (aStr != NULL)
{
GroomSpn(&aStr, &bIsServiceClass);
if (bIsServiceClass)
{
LwStrToUpper(aStr);
LwStrStr(pszServiceClassList, aStr, &isStrThere);
if (!isStrThere)
{
if (pszServiceClassList)
LwAllocateStringPrintf(&pszTempStr, "%s,%s", pszServiceClassList, aStr);
else
LwAllocateStringPrintf(&pszTempStr, "%s", aStr);
LW_SAFE_FREE_STRING(pszServiceClassList);
pszServiceClassList = pszTempStr;
pszTempStr = NULL;
}
}
else
{
LwStrStr(pszFqdnList, aStr, &isStrThere);
if ((!isStrThere) || (strlen(aStr) != (strlen(isStrThere))))
{
if (pszFqdnList)
LwAllocateStringPrintf(&pszTempStr, "%s,%s", pszFqdnList, aStr);
else
LwAllocateStringPrintf(&pszTempStr, "%s", aStr);
LW_SAFE_FREE_STRING(pszFqdnList);
pszFqdnList = pszTempStr;
pszTempStr = NULL;
}
}
aStr = strtok_r(NULL, ",", &saveStrPtr);
}
if (pszFqdnList && pszServiceClassList)
LwAllocateStringPrintf(&pszNewServicePrincipalNameList, "%s,%s", pszServiceClassList, pszFqdnList);
else if (pszFqdnList && !pszServiceClassList)
LwAllocateStringPrintf(&pszNewServicePrincipalNameList, "%s", pszFqdnList);
else
LwAllocateStringPrintf(&pszNewServicePrincipalNameList, "%s", pszServiceClassList);
// pszNewServicePrincipalNameList contains non-duplicated, uppercase service class.
// Fully qualified SPN is added as is.
*ppGroomedServicePrincipalList = pszNewServicePrincipalNameList;
cleanup:
LW_SAFE_FREE_STRING(pszFqdnList);
LW_SAFE_FREE_STRING(pszServiceClassList);
return;
error:
goto cleanup;
}
static
VOID
LsaFreeSpnAttrVal(
PWSTR *ppwszSpnAttrVal,
DWORD dwNumberOfSpnEntries)
{
DWORD i = 0;
for (i = 0; i < dwNumberOfSpnEntries; i++)
{
LW_SAFE_FREE_MEMORY(ppwszSpnAttrVal[i]);
}
LwFreeMemory(ppwszSpnAttrVal);
}
static
DWORD
LsaCreateSpnAttrVal(
PWSTR pwszDnsHostName,
PWSTR pwszHostname,
PSTR pszServicePrincipalNameList,
PWSTR **pppwszSpnAttrVal,
DWORD *pdwNumberOfSpnEntries)
{
DWORD dwError = ERROR_SUCCESS;
BOOLEAN bIsServiceClass = FALSE;
DWORD dwNumberOfSpnEntries = 150;
DWORD i = 0;
PSTR aStr = NULL;
PSTR saveStrPtr = NULL;
PSTR pszGroomedSPNList = NULL;
PWSTR *ppwszSPNAttrVal = NULL;
GroomSpnList(pszServicePrincipalNameList, &pszGroomedSPNList);
dwError = LwAllocateMemory(dwNumberOfSpnEntries * sizeof(PWSTR), (PVOID*) &ppwszSPNAttrVal);
BAIL_ON_LSA_ERROR(dwError);
for (i = 0; i < dwNumberOfSpnEntries; i++)
ppwszSPNAttrVal[i] = NULL;
i = 0;
aStr = strtok_r(pszGroomedSPNList, ",", &saveStrPtr);
while ((aStr != NULL) && (i < (dwNumberOfSpnEntries-1)))
{
GroomSpn(&aStr, &bIsServiceClass);
if (bIsServiceClass)
{
ppwszSPNAttrVal[i] = LdapAttrValSvcPrincipalName(aStr, pwszDnsHostName);
ppwszSPNAttrVal[i+1] = LdapAttrValSvcPrincipalName(aStr, pwszHostname);
i+=2;
}
else
{
LwMbsToWc16s(aStr, &ppwszSPNAttrVal[i]);
i++;
}
aStr = strtok_r(NULL, ",", &saveStrPtr);
}
*pdwNumberOfSpnEntries = dwNumberOfSpnEntries;
*pppwszSpnAttrVal = ppwszSPNAttrVal;
cleanup:
LW_SAFE_FREE_STRING(pszGroomedSPNList);
return dwError;
error:
goto cleanup;
}
static
DWORD
LsaJoinDomainInternal(
PWSTR pwszHostname,
PWSTR pwszDnsDomain,
PWSTR pwszDomain,
PWSTR pwszAccountOu,
PWSTR pwszAccount,
PWSTR pwszPassword,
DWORD dwJoinFlags,
DWORD dwUserAccountAttributes,
PWSTR pwszOsName,
PWSTR pwszOsVersion,
PWSTR pwszOsServicePack,
PSTR pszServicePrincipalNameList
)
{
const DWORD dwLsaAccess = LSA_ACCESS_LOOKUP_NAMES_SIDS |
LSA_ACCESS_VIEW_POLICY_INFO;
NTSTATUS ntStatus = STATUS_SUCCESS;
DWORD dwError = ERROR_SUCCESS;
LSA_BINDING hLsaBinding = NULL;
POLICY_HANDLE hLsaPolicy = NULL;
LsaPolicyInformation *pLsaPolicyInfo = NULL;
PWSTR pwszMachineName = NULL;
PWSTR pwszMachineAcctName = NULL;
WCHAR pwszMachinePassword[MACHPASS_LEN+1] = {0};
PWSTR pwszDomainName = NULL;
PSID pDomainSid = NULL;
PWSTR pwszDnsDomainName = NULL;
PWSTR pwszDCName = NULL;
LDAP *pLdap = NULL;
PWSTR pwszMachineNameLc = NULL; /* lower cased machine name */
PWSTR pwszBaseDn = NULL;
PWSTR pwszDn = NULL;
PWSTR pwszDnsAttrName = NULL;
PWSTR pwszDnsAttrVal[2] = {0};
PWSTR pwszSpnAttrName = NULL;
PWSTR *ppwszSpnAttrVal = NULL;
PWSTR pwszOSNameAttrName = NULL;
PWSTR pwszOSNameAttrVal[2] = {0};
PWSTR pwszOSVersionAttrName = NULL;
PWSTR pwszOSVersionAttrVal[2] = {0};
PWSTR pwszOSServicePackAttrName = NULL;
PWSTR pwszOSServicePackAttrVal[2] = {0};
PWSTR pwszUserAccountControlName = NULL;
PWSTR pwszUserAccountControlVal[2] = {0};
PWSTR pwszSupportedEncryptionTypesName = NULL;
PWSTR pwszSupportedEncryptionTypesVal[2] = {0};
DWORD dwSupportedEncryptionTypes = 0;
PWSTR pwszSidStr = NULL;
PWSTR pwszComputerContainer = NULL;
WCHAR wszUacVal[11] = {0};
LW_PIO_CREDS pCreds = NULL;
BOOLEAN account_exists = FALSE;
DWORD dwNumberOfSpnEntries = 0;
dwError = LwAllocateWc16String(&pwszMachineName,
pwszHostname);
BAIL_ON_LSA_ERROR(dwError);
dwError = LwWc16sToUpper(pwszMachineName);
BAIL_ON_LSA_ERROR(dwError)
dwError = LsaGetRwDcName(pwszDomain,
TRUE,
&pwszDCName);
BAIL_ON_LSA_ERROR(dwError);
if (pwszAccount && pwszPassword)
{
ntStatus = LwIoCreatePlainCredsW(pwszAccount,
pwszDomain,
pwszPassword,
&pCreds);
BAIL_ON_NT_STATUS(ntStatus);
}
else
{
ntStatus = LwIoGetActiveCreds(NULL,
&pCreds);
BAIL_ON_NT_STATUS(ntStatus);
}
ntStatus = LsaInitBindingDefault(&hLsaBinding,
pwszDCName,
pCreds);
BAIL_ON_NT_STATUS(ntStatus);
ntStatus = LsaOpenPolicy2(hLsaBinding,
pwszDCName,
NULL,
dwLsaAccess,
&hLsaPolicy);
BAIL_ON_NT_STATUS(ntStatus);
ntStatus = LsaQueryInfoPolicy2(hLsaBinding,
hLsaPolicy,
LSA_POLICY_INFO_DNS,
&pLsaPolicyInfo);
BAIL_ON_NT_STATUS(ntStatus);
dwError = LwAllocateWc16StringFromUnicodeString(
&pwszDnsDomainName,
&pLsaPolicyInfo->dns.dns_domain);
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaGetAccountName(
pwszMachineName,
pwszDCName,
pwszDnsDomain ? pwszDnsDomain : pwszDnsDomainName,
&pwszMachineAcctName,
&account_exists);
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaDirectoryConnect(
pwszDCName,
&pLdap,
&pwszBaseDn);
BAIL_ON_LSA_ERROR(dwError);
if (pwszAccountOu == NULL)
{
if (!(dwJoinFlags & LSAJOIN_NO_PRE_COMPUTER_ACCOUNT))
{
pwszComputerContainer = pwszAccountOu = LdapGetWellKnownObject(pLdap, pwszBaseDn, LW_GUID_COMPUTERS_CONTAINER);
}
}
/* Pre-create a disabled machine
account object in given branch of directory. It will
be reset afterwards by means of rpc calls */
if (pwszAccountOu)
{
int move = (dwJoinFlags & LSAJOIN_DOMAIN_JOIN_IF_JOINED) == LSAJOIN_DOMAIN_JOIN_IF_JOINED ? TRUE : FALSE;
// If a specific OU wasn't requested then we don't want to move the Computer account
if (pwszComputerContainer) move = FALSE;
dwError = LsaMachAcctCreate(
pLdap,
pwszMachineName,
pwszMachineAcctName,
pwszAccountOu,
move,
account_exists);
BAIL_ON_LSA_ERROR(dwError);
}
dwError = LsaDirectoryDisconnect(pLdap);
pLdap = NULL;
BAIL_ON_LSA_ERROR(dwError);
LW_SAFE_FREE_MEMORY(pwszBaseDn);
dwError = LsaGenerateMachinePassword(
(PWSTR)pwszMachinePassword,
sizeof(pwszMachinePassword)/sizeof(pwszMachinePassword[0]));
BAIL_ON_LSA_ERROR(dwError);
if (pwszMachinePassword[0] == '\0')
{
BAIL_ON_NT_STATUS(STATUS_INTERNAL_ERROR);
}
ntStatus = LsaCreateMachineAccount(pwszDCName,
pCreds,
pwszMachineAcctName,
(PWSTR)pwszMachinePassword,
dwJoinFlags,
&pwszDomainName,
&pDomainSid);
BAIL_ON_NT_STATUS(ntStatus);
ntStatus = RtlAllocateWC16StringFromSid(&pwszSidStr,
pDomainSid);
BAIL_ON_NT_STATUS(ntStatus);
// Make sure we can access the account
dwError = LsaDirectoryConnect(
pwszDCName,
&pLdap,
&pwszBaseDn);
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaMachAcctSearch(
pLdap,
pwszMachineAcctName,
pwszBaseDn,
&pwszDn,
NULL);
if (dwError == ERROR_INVALID_PARAMETER)
{
dwError = LW_ERROR_LDAP_INSUFFICIENT_ACCESS;
}
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaSaveMachinePassword(
pwszMachineName,
pwszMachineAcctName,
pwszDnsDomain ? pwszDnsDomain : pwszDnsDomainName,
pwszDomainName,
pwszDnsDomainName,
pwszDCName,
pwszSidStr,
(PWSTR)pwszMachinePassword,
pszServicePrincipalNameList);
BAIL_ON_LSA_ERROR(dwError);
/*
* Open connection to directory server if it's going to be needed
*/
if (!(dwJoinFlags & LSAJOIN_DEFER_SPN_SET) ||
pwszOsName || pwszOsVersion || pwszOsServicePack)
{
/*
* Set SPN and dnsHostName attributes unless this part is to be deferred
*/
if (!(dwJoinFlags & LSAJOIN_DEFER_SPN_SET))
{
PWSTR pwszDnsHostName = NULL;
dwError = LwAllocateWc16String(&pwszMachineNameLc,
pwszMachineName);
BAIL_ON_LSA_ERROR(dwError);
dwError = LwWc16sToLower(pwszMachineNameLc);
BAIL_ON_LSA_ERROR(dwError);
dwError = LwMbsToWc16s("dNSHostName", &pwszDnsAttrName);
BAIL_ON_LSA_ERROR(dwError);
pwszDnsAttrVal[0] = LdapAttrValDnsHostName(pwszMachineNameLc,
pwszDnsDomain ? pwszDnsDomain : pwszDnsDomainName);
pwszDnsAttrVal[1] = NULL;
pwszDnsHostName = pwszDnsAttrVal[0];
dwError = LsaMachAcctSetAttribute(pLdap, pwszDn,
pwszDnsAttrName,
(const wchar16_t**)pwszDnsAttrVal, 0);
if (dwError == ERROR_DS_CONSTRAINT_VIOLATION)
{
dwError = ERROR_DS_NAME_ERROR_NO_MAPPING;
}
BAIL_ON_LSA_ERROR(dwError);
dwError = LwMbsToWc16s("servicePrincipalName",
&pwszSpnAttrName);
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaCreateSpnAttrVal(
pwszDnsHostName,
pwszHostname,
pszServicePrincipalNameList,
&ppwszSpnAttrVal,
&dwNumberOfSpnEntries);
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaMachAcctSetAttribute(pLdap, pwszDn, pwszSpnAttrName,
(const wchar16_t**)ppwszSpnAttrVal, 0);
if (dwError == LW_ERROR_LDAP_CONSTRAINT_VIOLATION)
{
dwError = LW_ERROR_LDAP_CONSTRAINT_VIOLATION_SPN;
}
BAIL_ON_LSA_ERROR(dwError);
}
/*
* Set operating system name and version attributes if specified
*/
if (pwszOsName)
{
dwError = LwMbsToWc16s("operatingSystem",
&pwszOSNameAttrName);
BAIL_ON_LSA_ERROR(dwError);
dwError = LwAllocateWc16String(&pwszOSNameAttrVal[0],
pwszOsName);
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaMachAcctSetAttribute(pLdap, pwszDn,
pwszOSNameAttrName,
(const wchar16_t**)pwszOSNameAttrVal,
0);
if (dwError == LW_ERROR_LDAP_INSUFFICIENT_ACCESS)
{
/* The user must be a non-admin. In this case, we cannot
* set the attribute.
*/
dwError = ERROR_SUCCESS;
}
else
{
BAIL_ON_LSA_ERROR(dwError);
}
}
if (pwszOsVersion)
{
dwError = LwMbsToWc16s("operatingSystemVersion",
&pwszOSVersionAttrName);
BAIL_ON_LSA_ERROR(dwError);
dwError = LwAllocateWc16String(&pwszOSVersionAttrVal[0],
pwszOsVersion);
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaMachAcctSetAttribute(pLdap, pwszDn,
pwszOSVersionAttrName,
(const wchar16_t**)pwszOSVersionAttrVal,
0);
if (dwError == LW_ERROR_LDAP_INSUFFICIENT_ACCESS)
{
dwError = ERROR_SUCCESS;
}
else
{
BAIL_ON_LSA_ERROR(dwError);
}
}
if (pwszOsServicePack)
{
dwError = LwMbsToWc16s("operatingSystemServicePack",
&pwszOSServicePackAttrName);
BAIL_ON_LSA_ERROR(dwError);
dwError = LwAllocateWc16String(&pwszOSServicePackAttrVal[0],
pwszOsServicePack);
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaMachAcctSetAttribute(pLdap, pwszDn,
pwszOSServicePackAttrName,
(const wchar16_t**)pwszOSServicePackAttrVal,
0);
if (dwError == LW_ERROR_LDAP_INSUFFICIENT_ACCESS)
{
dwError = ERROR_SUCCESS;
}
else
{
BAIL_ON_LSA_ERROR(dwError);
}
}
if (dwUserAccountAttributes == 0)
{
dwUserAccountAttributes = LSAJOIN_WORKSTATION_TRUST_ACCOUNT;
}
if (dwUserAccountAttributes)
{
dwError = LwMbsToWc16s("userAccountControl",
&pwszUserAccountControlName);
BAIL_ON_LSA_ERROR(dwError);
sw16printfw(
wszUacVal,
sizeof(wszUacVal)/sizeof(wszUacVal[0]),
L"%u",
dwUserAccountAttributes);
pwszUserAccountControlVal[0] = wszUacVal;
dwError = LwAllocateWc16String(&pwszUserAccountControlVal[0],
wszUacVal);
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaMachAcctSetAttribute(pLdap, pwszDn,
pwszUserAccountControlName,
(const wchar16_t**)pwszUserAccountControlVal,
0);
if (dwError == LW_ERROR_LDAP_INSUFFICIENT_ACCESS)
{
dwError = ERROR_SUCCESS;
}
else
{
BAIL_ON_LSA_ERROR(dwError);
}
}
LwKrb5GetSupportedEncryptionTypes(&dwSupportedEncryptionTypes);
if (dwSupportedEncryptionTypes)
{
dwError = LwMbsToWc16s("msDS-SupportedEncryptionTypes",
&pwszSupportedEncryptionTypesName);
BAIL_ON_LSA_ERROR(dwError);
sw16printfw(
wszUacVal,
sizeof(wszUacVal)/sizeof(wszUacVal[0]),
L"%u",
dwSupportedEncryptionTypes);
dwError = LwAllocateWc16String(&pwszSupportedEncryptionTypesVal[0],
wszUacVal);
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaMachAcctSetAttribute(pLdap, pwszDn,
pwszSupportedEncryptionTypesName,
(const wchar16_t**)pwszSupportedEncryptionTypesVal,
0);
if (dwError == LW_ERROR_LDAP_INSUFFICIENT_ACCESS || dwError == LW_ERROR_LDAP_NO_SUCH_ATTRIBUTE)
{
// Ignore if we don't have access or are talking to an old domain that does not have this attribute
dwError = ERROR_SUCCESS;
}
else
{
BAIL_ON_LSA_ERROR(dwError);
}
}
}
cleanup:
if (hLsaBinding && hLsaPolicy)
{
LsaClose(hLsaBinding, hLsaPolicy);
LsaFreeBinding(&hLsaBinding);
}
if (pLsaPolicyInfo)
{
LsaRpcFreeMemory(pLsaPolicyInfo);
}
if (pCreds)
{
LwIoDeleteCreds(pCreds);
}
if (pLdap)
{
LsaDirectoryDisconnect(pLdap);
}
if (ppwszSpnAttrVal)
{
LsaFreeSpnAttrVal(ppwszSpnAttrVal, dwNumberOfSpnEntries);
}
LW_SAFE_FREE_MEMORY(pwszDomainName);
RTL_FREE(&pDomainSid);
RTL_FREE(&pwszSidStr);
LW_SAFE_FREE_MEMORY(pwszDnsDomainName);
LW_SAFE_FREE_MEMORY(pwszMachineName);
LW_SAFE_FREE_MEMORY(pwszMachineAcctName);
LW_SAFE_FREE_MEMORY(pwszMachineNameLc);
LW_SAFE_FREE_MEMORY(pwszBaseDn);
LW_SAFE_FREE_MEMORY(pwszDn);
LW_SAFE_FREE_MEMORY(pwszDnsAttrName);
LW_SAFE_FREE_MEMORY(pwszDnsAttrVal[0]);
LW_SAFE_FREE_MEMORY(pwszSpnAttrName);
LW_SAFE_FREE_MEMORY(pwszOSNameAttrName);
LW_SAFE_FREE_MEMORY(pwszOSNameAttrVal[0]);
LW_SAFE_FREE_MEMORY(pwszOSVersionAttrName);
LW_SAFE_FREE_MEMORY(pwszOSVersionAttrVal[0]);
LW_SAFE_FREE_MEMORY(pwszOSServicePackAttrName);
LW_SAFE_FREE_MEMORY(pwszOSServicePackAttrVal[0]);
LW_SAFE_FREE_MEMORY(pwszDCName);
LW_SAFE_FREE_MEMORY(pwszSupportedEncryptionTypesName);
LW_SAFE_FREE_MEMORY(pwszSupportedEncryptionTypesVal[0]);
LW_SAFE_FREE_MEMORY(pwszComputerContainer);
if (dwError == ERROR_SUCCESS &&
ntStatus != STATUS_SUCCESS)
{
dwError = NtStatusToWin32Error(ntStatus);
}
return dwError;
error:
goto cleanup;
}
static
DWORD
LsaGetAccountName(
const wchar16_t *machname,
const wchar16_t *domain_controller_name,
const wchar16_t *dns_domain_name,
wchar16_t **account_name,
BOOLEAN *exists
)
{
int err = ERROR_SUCCESS;
LDAP *ld = NULL;
wchar16_t *base_dn = NULL;
wchar16_t *dn = NULL;
wchar16_t *machname_lc = NULL;
wchar16_t *samname = NULL; /* short name valid for SAM account */
wchar16_t *dnsname = NULL;
wchar16_t *fqdn = NULL;
wchar16_t *hashstr = NULL;
wchar16_t *samacctname = NULL; /* account name (with trailing '$') */
UINT32 hash = 0;
UINT32 offset = 0;
UINT32 hashoffset = 0;
wchar16_t newname[16] = {0};
wchar16_t searchname[17] = {0};
size_t hashstrlen = 0;
size_t machname_len = 0;
size_t samacctname_len = 0;
if (exists) *exists = FALSE;
err = LwWc16sLen(machname, &machname_len);
BAIL_ON_LSA_ERROR(err);
err = LwAllocateWc16String(&machname_lc, machname);
BAIL_ON_LSA_ERROR(err);
wc16slower(machname_lc);
fqdn = LdapAttrValDnsHostName(machname_lc, dns_domain_name);
if (!fqdn)
{
err = ERROR_OUTOFMEMORY;
BAIL_ON_LSA_ERROR(err);
}
/* look for an existing account using the dns_host_name attribute */
err = LsaDirectoryConnect(
domain_controller_name,
&ld,
&base_dn);
BAIL_ON_LSA_ERROR(err);
err = LsaMachDnsNameSearch(
ld,
fqdn,
machname_lc,
base_dn,
&samname);
if (err == ERROR_SUCCESS)
{
size_t samname_len = 0;
err = LwWc16sLen(samname, &samname_len);
BAIL_ON_LSA_ERROR(err);
samname[samname_len - 1] = 0;
if (exists) *exists = TRUE;
}
else
{
err = ERROR_SUCCESS;
}
if (!samname)
{
LSA_LOG_DEBUG("Machine account not found with DNS name");
/* the host name is short enough to use as is */
if (machname_len < 16)
{
LSA_LOG_DEBUG("Machine account name length < 16");
if (sw16printfw(searchname,
sizeof(searchname)/sizeof(wchar16_t),
L"%ws$",
machname) < 0)
{
err = ErrnoToWin32Error(errno);
BAIL_ON_LSA_ERROR(err);
}
err = LsaMachAcctSearch(ld, searchname, base_dn, NULL, &dnsname);
if ( err != ERROR_SUCCESS || !dnsname)
{
if (err == ERROR_SUCCESS)
{
if (exists) *exists = TRUE;
LSA_LOG_DEBUG("Machine account found with samAccountName but has no DNS name defined");
}
else
{
LSA_LOG_DEBUG("Machine account not found with samAccountName");
}
err = ERROR_SUCCESS;
err = LwAllocateWc16String(&samname, machname);
BAIL_ON_LSA_ERROR(err);
}
if (dnsname) LSA_LOG_DEBUG("Machine account found with different DNS name");
LW_SAFE_FREE_MEMORY(dnsname);
}
}
/*
* No account was found and the name is too long so hash the host
* name and combine with as much of the existing name as will fit
* in the available space. Search for an existing account with
* that name and if a collision is detected, increment the hash
* and try again.
*/
if (!samname)
{
LSA_LOG_DEBUG("Machine account name too long or found with wrong DNS name");
dnsname = LdapAttrValDnsHostName(
machname_lc,
dns_domain_name);
if (dnsname)
{
err = LsaWc16sHash(dnsname, &hash);
BAIL_ON_LSA_ERROR(err);
LW_SAFE_FREE_MEMORY(dnsname);
}
else
{
err = LsaWc16sHash(machname_lc, &hash);
BAIL_ON_LSA_ERROR(err);
}
for (offset = 0 ; offset < 100 ; offset++)
{
err = LsaHashToWc16s(hash + offset, &hashstr);
BAIL_ON_LSA_ERROR(err);
err = LwWc16sLen(hashstr, &hashstrlen);
BAIL_ON_LSA_ERROR(err);
// allow for '-' + hash
hashoffset = 15 - (hashstrlen + 1);
if (hashoffset > machname_len)
{
hashoffset = machname_len;
}
wc16sncpy(newname, machname, hashoffset);
newname[hashoffset++] = (WCHAR)'-';
wc16sncpy(newname + hashoffset, hashstr, hashstrlen + 1);
LW_SAFE_FREE_MEMORY(hashstr);
if (sw16printfw(searchname,
sizeof(searchname)/sizeof(wchar16_t),
L"%ws$",
newname) < 0)
{
err = ErrnoToWin32Error(errno);
BAIL_ON_LSA_ERROR(err);
}
LSA_LOG_DEBUG("Machine account checking hashed name");
err = LsaMachAcctSearch(ld, searchname, base_dn, NULL, &dnsname);
if ( err != ERROR_SUCCESS || !dnsname)
{
if (err == ERROR_SUCCESS)
{
if (exists) *exists = TRUE;
LSA_LOG_DEBUG("Hashed Machine account found with samAccountName but has no DNS name defined");
}
else
{
LSA_LOG_DEBUG("Hashed Machine account not found with samAccountName");
}
err = ERROR_SUCCESS;
err = LwAllocateWc16String(&samname, newname);
BAIL_ON_LSA_ERROR(err);
break;
}
LW_SAFE_FREE_MEMORY(dnsname);
}
if (offset == 100)
{
LSA_LOG_ERROR("Failed to create unique Machine account name after 100 attempts");
err = ERROR_DUP_NAME;
goto error;
}
}
err = LwWc16sLen(samname, &samacctname_len);
BAIL_ON_LSA_ERROR(err);
samacctname_len += 2;
err = LwAllocateMemory(sizeof(samacctname[0]) * samacctname_len,
OUT_PPVOID(&samacctname));
BAIL_ON_LSA_ERROR(err);
if (sw16printfw(samacctname,
samacctname_len,
L"%ws$",
samname) < 0)
{
err = ErrnoToWin32Error(errno);
BAIL_ON_LSA_ERROR(err);
}
// Upper case the sam account name in case it was incorrectly created in AD
// by a previous version.
LwWc16sToUpper(samacctname);
*account_name = samacctname;
cleanup:
if (ld)
{
LsaDirectoryDisconnect(ld);
}
LW_SAFE_FREE_MEMORY(machname_lc);
LW_SAFE_FREE_MEMORY(hashstr);
LW_SAFE_FREE_MEMORY(dn);
LW_SAFE_FREE_MEMORY(dnsname);
LW_SAFE_FREE_MEMORY(samname);
LW_SAFE_FREE_MEMORY(base_dn);
return err;
error:
LW_SAFE_FREE_MEMORY(samacctname);
*account_name = NULL;
goto cleanup;
}
static
DWORD
LsaGenerateMachinePassword(
PWSTR pwszPassword,
size_t sPasswordLen
)
{
DWORD dwError = 0;
DWORD i = 0;
PSTR pszPassword = NULL;
BAIL_ON_INVALID_POINTER(pwszPassword);
pwszPassword[0] = (WCHAR) '\0';
dwError = LwAllocateMemory(sizeof(pszPassword[0]) * sPasswordLen,
OUT_PPVOID(&pszPassword));
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaGenerateRandomString(pszPassword, sPasswordLen);
BAIL_ON_LSA_ERROR(dwError);
/* "Cast" A string to W string */
for (i=0; i<sPasswordLen; i++)
{
pwszPassword[i] = (WCHAR) pszPassword[i];
}
cleanup:
LW_SECURE_FREE_STRING(pszPassword);
return dwError;
error:
goto cleanup;
}
static const CHAR RandomCharsLc[] = "abcdefghijklmnopqrstuvwxyz";
static const CHAR RandomCharsUc[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const CHAR RandomCharsDigits[] = "0123456789";
static const CHAR RandomCharsPunct[] = "-+/*,.;:!<=>%'&()";
static
DWORD
LsaRandBytes(
PBYTE pBuffer,
DWORD dwCount
)
{
DWORD dwError = 0;
unsigned long dwRandError = 0;
const char *pszRandFile = NULL;
int iRandLine = 0;
char *pszData = NULL;
int iFlags = 0;
if (!RAND_bytes(pBuffer, dwCount))
{
dwRandError = ERR_get_error_line_data(
&pszRandFile,
&iRandLine,
(const char **)&pszData,
&iFlags);
if (iFlags & ERR_TXT_STRING)
{
LSA_LOG_DEBUG("RAND_bytes failed with message '%s' and error code %ld at %s:%d",
pszData, dwRandError, pszRandFile, iRandLine);
}
else
{
LSA_LOG_DEBUG("RAND_bytes failed with error code %ld at %s:%d",
dwRandError, pszRandFile, iRandLine);
}
dwError = ERROR_ENCRYPTION_FAILED;
BAIL_ON_LSA_ERROR(dwError);
}
cleanup:
if (iFlags & ERR_TXT_MALLOCED)
{
LW_SAFE_FREE_STRING(pszData);
}
return dwError;
error:
goto cleanup;
}
DWORD
LsaGenerateRandomString(
PSTR pszBuffer,
size_t sBufferLen
)
{
DWORD dwError = ERROR_SUCCESS;
PBYTE pBuffer = NULL;
PBYTE pClassBuffer = NULL;
DWORD i = 0;
DWORD iClass = 0;
CHAR iChar = 0;
DWORD iLcCount = 0;
DWORD iUcCount = 0;
DWORD iDigitsCount = 0;
DWORD iPunctCount = 0;
dwError = LwAllocateMemory(sizeof(pBuffer[0]) * sBufferLen,
OUT_PPVOID(&pBuffer));
BAIL_ON_LSA_ERROR(dwError);
dwError = LwAllocateMemory(sizeof(pClassBuffer[0]) * sBufferLen,
OUT_PPVOID(&pClassBuffer));
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaRandBytes(pBuffer, sBufferLen);
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaRandBytes((unsigned char*)pClassBuffer, (int)sBufferLen);
BAIL_ON_LSA_ERROR(dwError);
for (i = 0; i < sBufferLen-1; i++)
{
/*
* Check for missing character class,
* and force selection of the missing class.
* The two missing classes will be at the end of
* the string, which may be a password weakness
* issue.
*/
if (i >= sBufferLen-3)
{
if (iLcCount == 0)
{
iClass = 0;
}
else if (iUcCount == 0)
{
iClass = 1;
}
else if (iDigitsCount == 0)
{
iClass = 2;
}
else if (iPunctCount == 0)
{
iClass = 3;
}
}
else
{
iClass = pClassBuffer[i] % 4;
}
switch (iClass)
{
case 0:
iChar = RandomCharsLc[
pBuffer[i] % (sizeof(RandomCharsLc) - 1)];
iLcCount++;
break;
case 1:
iChar = RandomCharsUc[
pBuffer[i] % (sizeof(RandomCharsUc) - 1)];
iUcCount++;
break;
case 2:
iChar = RandomCharsDigits[
pBuffer[i] % (sizeof(RandomCharsDigits) - 1)];
iDigitsCount++;
break;
case 3:
iChar = RandomCharsPunct[
pBuffer[i] % (sizeof(RandomCharsPunct) - 1)];
iPunctCount++;
break;
}
pszBuffer[i] = iChar;
}
pszBuffer[sBufferLen-1] = '\0';
cleanup:
LW_SECURE_FREE_MEMORY(pBuffer, sBufferLen);
LW_SECURE_FREE_MEMORY(pClassBuffer, sBufferLen);
return dwError;
error:
memset(pszBuffer, 0, sizeof(pszBuffer[0]) * sBufferLen);
goto cleanup;
}
static
NTSTATUS
LsaCreateMachineAccount(
PWSTR pwszDCName,
LW_PIO_CREDS pCreds,
PWSTR pwszMachineAccountName,
PWSTR pwszMachinePassword,
DWORD dwJoinFlags,
PWSTR *ppwszDomainName,
PSID *ppDomainSid
)
{
const DWORD dwConnAccess = SAMR_ACCESS_OPEN_DOMAIN |
SAMR_ACCESS_ENUM_DOMAINS;
const DWORD dwDomainAccess = DOMAIN_ACCESS_ENUM_ACCOUNTS |
DOMAIN_ACCESS_OPEN_ACCOUNT |
DOMAIN_ACCESS_LOOKUP_INFO_2 |
DOMAIN_ACCESS_CREATE_USER;
const DWORD dwUserAccess = USER_ACCESS_GET_ATTRIBUTES |
USER_ACCESS_SET_ATTRIBUTES |
USER_ACCESS_SET_PASSWORD;
NTSTATUS ntStatus = STATUS_SUCCESS;
DWORD dwError = ERROR_SUCCESS;
unsigned32 rpcStatus = 0;
SAMR_BINDING hSamrBinding = NULL;
CONNECT_HANDLE hConnect = NULL;
rpc_transport_info_handle_t hTransportInfo = NULL;
DWORD dwProtSeq = 0;
PBYTE pSessionKey = NULL;
DWORD dwSessionKeyLen = 0;
unsigned16 sessionKeyLen = 0;
PSID pBuiltinSid = NULL;
DWORD dwResume = 0;
DWORD dwSize = 256;
PWSTR *ppwszDomainNames = NULL;
DWORD i = 0;
PWSTR pwszDomainName = NULL;
DWORD dwNumEntries = 0;
PSID pSid = NULL;
PSID pDomainSid = NULL;
DOMAIN_HANDLE hDomain = NULL;
BOOLEAN bNewAccount = FALSE;
PDWORD pdwRids = NULL;
PDWORD pdwTypes = NULL;
ACCOUNT_HANDLE hUser = NULL;
DWORD dwUserAccessGranted = 0;
DWORD dwRid = 0;
DWORD dwLevel = 0;
UserInfo *pInfo = NULL;
DWORD dwFlagsEnable = 0;
DWORD dwFlagsDisable = 0;
UserInfo Info;
size_t sMachinePasswordLen = 0;
UserInfo PassInfo;
PWSTR pwszMachineName = NULL;
PUNICODE_STRING pFullName = NULL;
memset(&Info, 0, sizeof(Info));
memset(&PassInfo, 0, sizeof(PassInfo));
ntStatus = SamrInitBindingDefault(&hSamrBinding,
pwszDCName,
pCreds);
BAIL_ON_NT_STATUS(ntStatus);
ntStatus = SamrConnect2(hSamrBinding,
pwszDCName,
dwConnAccess,
&hConnect);
BAIL_ON_NT_STATUS(ntStatus);
rpc_binding_inq_transport_info(hSamrBinding,
&hTransportInfo,
&rpcStatus);
if (rpcStatus)
{
ntStatus = LwRpcStatusToNtStatus(rpcStatus);
BAIL_ON_NT_STATUS(ntStatus);
}
rpc_binding_inq_prot_seq(hSamrBinding,
(unsigned32*)&dwProtSeq,
&rpcStatus);
if (rpcStatus)
{
ntStatus = LwRpcStatusToNtStatus(rpcStatus);
BAIL_ON_NT_STATUS(ntStatus);
}
if (dwProtSeq == rpc_c_protseq_id_ncacn_np)
{
rpc_smb_transport_info_inq_session_key(
hTransportInfo,
(unsigned char**)&pSessionKey,
&sessionKeyLen);
dwSessionKeyLen = (DWORD)sessionKeyLen;
}
else
{
ntStatus = STATUS_INVALID_CONNECTION;
BAIL_ON_NT_STATUS(ntStatus);
}
dwError = LwAllocateWellKnownSid(WinBuiltinDomainSid,
NULL,
&pBuiltinSid,
NULL);
BAIL_ON_LSA_ERROR(dwError);
do
{
ntStatus = SamrEnumDomains(hSamrBinding,
hConnect,
&dwResume,
dwSize,
&ppwszDomainNames,
&dwNumEntries);
BAIL_ON_NT_STATUS(ntStatus);
if (ntStatus != STATUS_SUCCESS &&
ntStatus != STATUS_MORE_ENTRIES)
{
BAIL_ON_NT_STATUS(ntStatus);
}
for (i = 0; pDomainSid == NULL && i < dwNumEntries; i++)
{
ntStatus = SamrLookupDomain(hSamrBinding,
hConnect,
ppwszDomainNames[i],
&pSid);
BAIL_ON_NT_STATUS(ntStatus);
if (!RtlEqualSid(pSid, pBuiltinSid))
{
dwError = LwAllocateWc16String(&pwszDomainName,
ppwszDomainNames[i]);
BAIL_ON_LSA_ERROR(dwError);
ntStatus = RtlDuplicateSid(&pDomainSid, pSid);
BAIL_ON_NT_STATUS(ntStatus);
}
SamrFreeMemory(pSid);
pSid = NULL;
}
if (ppwszDomainNames)
{
SamrFreeMemory(ppwszDomainNames);
ppwszDomainNames = NULL;
}
}
while (ntStatus == STATUS_MORE_ENTRIES);
ntStatus = SamrOpenDomain(hSamrBinding,
hConnect,
dwDomainAccess,
pDomainSid,
&hDomain);
BAIL_ON_NT_STATUS(ntStatus);
/* for start, let's assume the account already exists */
bNewAccount = FALSE;
ntStatus = SamrLookupNames(hSamrBinding,
hDomain,
1,
&pwszMachineAccountName,
&pdwRids,
&pdwTypes,
NULL);
if (ntStatus == STATUS_NONE_MAPPED)
{
if (!(dwJoinFlags & LSAJOIN_ACCT_CREATE)) goto error;
ntStatus = SamrCreateUser2(hSamrBinding,
hDomain,
pwszMachineAccountName,
ACB_WSTRUST,
dwUserAccess,
&hUser,
&dwUserAccessGranted,
&dwRid);
BAIL_ON_NT_STATUS(ntStatus);
bNewAccount = TRUE;
}
else if (ntStatus == STATUS_SUCCESS &&
!(dwJoinFlags & LSAJOIN_DOMAIN_JOIN_IF_JOINED))
{
BAIL_ON_LSA_ERROR(NERR_SetupAlreadyJoined);
}
else if (ntStatus == STATUS_SUCCESS)
{
ntStatus = SamrOpenUser(hSamrBinding,
hDomain,
dwUserAccess,
pdwRids[0],
&hUser);
BAIL_ON_NT_STATUS(ntStatus);
}
else
{
BAIL_ON_NT_STATUS(ntStatus);
}
/*
* Flip ACB_DISABLED flag - this way password timeout counter
* gets restarted
*/
dwLevel = 16;
ntStatus = SamrQueryUserInfo(hSamrBinding,
hUser,
dwLevel,
&pInfo);
BAIL_ON_NT_STATUS(ntStatus);
dwFlagsEnable = pInfo->info16.account_flags & (~ACB_DISABLED);
dwFlagsDisable = pInfo->info16.account_flags | ACB_DISABLED;
Info.info16.account_flags = dwFlagsEnable;
ntStatus = SamrSetUserInfo2(hSamrBinding,
hUser,
dwLevel,
&Info);
BAIL_ON_NT_STATUS(ntStatus);
Info.info16.account_flags = dwFlagsDisable;
ntStatus = SamrSetUserInfo2(hSamrBinding,
hUser,
dwLevel,
&Info);
BAIL_ON_NT_STATUS(ntStatus);
Info.info16.account_flags = dwFlagsEnable;
ntStatus = SamrSetUserInfo2(hSamrBinding,
hUser,
dwLevel,
&Info);
BAIL_ON_NT_STATUS(ntStatus);
dwError = LwWc16sLen(pwszMachinePassword,
&sMachinePasswordLen);
BAIL_ON_LSA_ERROR(dwError);
if (bNewAccount)
{
UserInfo25 *pInfo25 = &PassInfo.info25;
ntStatus = LsaEncryptPasswordBufferEx(pInfo25->password.data,
sizeof(pInfo25->password.data),
pwszMachinePassword,
sMachinePasswordLen,
pSessionKey,
dwSessionKeyLen);
BAIL_ON_NT_STATUS(ntStatus);
dwError = LwAllocateWc16String(&pwszMachineName,
pwszMachineAccountName);
BAIL_ON_LSA_ERROR(dwError);
pwszMachineName[sMachinePasswordLen - 1] = '\0';
pInfo25->info.account_flags = ACB_WSTRUST;
pFullName = &pInfo25->info.full_name;
dwError = LwAllocateUnicodeStringFromWc16String(
pFullName,
pwszMachineName);
BAIL_ON_LSA_ERROR(dwError);
pInfo25->info.fields_present = SAMR_FIELD_FULL_NAME |
SAMR_FIELD_ACCT_FLAGS |
SAMR_FIELD_PASSWORD;
dwLevel = 25;
}
else
{
UserInfo26 *pInfo26 = &PassInfo.info26;
ntStatus = LsaEncryptPasswordBufferEx(pInfo26->password.data,
sizeof(pInfo26->password.data),
pwszMachinePassword,
sMachinePasswordLen,
pSessionKey,
dwSessionKeyLen);
BAIL_ON_NT_STATUS(ntStatus);
pInfo26->password_len = sMachinePasswordLen;
dwLevel = 26;
}
ntStatus = SamrSetUserInfo2(hSamrBinding,
hUser,
dwLevel,
&PassInfo);
BAIL_ON_NT_STATUS(ntStatus);
*ppwszDomainName = pwszDomainName;
*ppDomainSid = pDomainSid;
cleanup:
if (hSamrBinding && hUser)
{
SamrClose(hSamrBinding, hUser);
}
if (hSamrBinding && hDomain)
{
SamrClose(hSamrBinding, hDomain);
}
if (hSamrBinding && hConnect)
{
SamrClose(hSamrBinding, hConnect);
}
if (hSamrBinding)
{
SamrFreeBinding(&hSamrBinding);
}
if (pFullName)
{
LwFreeUnicodeString(pFullName);
}
if (pInfo)
{
SamrFreeMemory(pInfo);
}
if (pdwRids)
{
SamrFreeMemory(pdwRids);
}
if (pdwTypes)
{
SamrFreeMemory(pdwTypes);
}
if (ppwszDomainNames)
{
SamrFreeMemory(ppwszDomainNames);
}
LW_SAFE_FREE_MEMORY(pBuiltinSid);
LW_SAFE_FREE_MEMORY(pwszMachineName);
if (ntStatus == STATUS_SUCCESS &&
dwError != ERROR_SUCCESS)
{
ntStatus = LwWin32ErrorToNtStatus(dwError);
}
return ntStatus;
error:
LW_SAFE_FREE_MEMORY(pwszDomainName);
RTL_FREE(&pDomainSid);
*ppwszDomainName = NULL;
*ppDomainSid = NULL;
goto cleanup;
}
static
NTSTATUS
LsaEncryptPasswordBufferEx(
PBYTE pPasswordBuffer,
DWORD dwPasswordBufferSize,
PWSTR pwszPassword,
DWORD dwPasswordLen,
PBYTE pSessionKey,
DWORD dwSessionKeyLen
)
{
NTSTATUS ntStatus = STATUS_SUCCESS;
DWORD dwError = ERROR_SUCCESS;
MD5_CTX ctx;
RC4_KEY rc4_key;
BYTE InitValue[16] = {0};
BYTE DigestedSessKey[16] = {0};
BYTE PasswordBuffer[532] = {0};
BAIL_ON_INVALID_POINTER(pPasswordBuffer);
BAIL_ON_INVALID_POINTER(pwszPassword);
BAIL_ON_INVALID_POINTER(pSessionKey);
// We require the first 16 bytes of the session key for the MD5 hash
if (dwSessionKeyLen < 16)
{
dwError = ERROR_INSUFFICIENT_BUFFER;
BAIL_ON_LSA_ERROR(dwError);
}
if (dwPasswordBufferSize < sizeof(PasswordBuffer))
{
dwError = ERROR_INSUFFICIENT_BUFFER;
BAIL_ON_LSA_ERROR(dwError);
}
memset(&ctx, 0, sizeof(ctx));
memset(&rc4_key, 0, sizeof(rc4_key));
ntStatus = LsaEncodePasswordBuffer(pwszPassword,
PasswordBuffer,
sizeof(PasswordBuffer));
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaRandBytes((unsigned char*)InitValue, sizeof(InitValue));
BAIL_ON_LSA_ERROR(dwError);
MD5_Init(&ctx);
MD5_Update(&ctx, InitValue, 16);
MD5_Update(&ctx, pSessionKey, dwSessionKeyLen > 16 ? 16 : dwSessionKeyLen);
MD5_Final(DigestedSessKey, &ctx);
LSA_LOG_DEBUG("RC4_KEY structure is using %d bytes", sizeof(rc4_key));
RC4_set_key(&rc4_key, 16, (unsigned char*)DigestedSessKey);
RC4(&rc4_key, 516, PasswordBuffer, PasswordBuffer);
memcpy((PVOID)&PasswordBuffer[516], InitValue, 16);
memcpy(pPasswordBuffer, PasswordBuffer, sizeof(PasswordBuffer));
cleanup:
memset(PasswordBuffer, 0, sizeof(PasswordBuffer));
if (ntStatus == STATUS_SUCCESS &&
dwError != ERROR_SUCCESS)
{
ntStatus = LwWin32ErrorToNtStatus(dwError);
}
return ntStatus;
error:
goto cleanup;
}
static
NTSTATUS
LsaEncodePasswordBuffer(
IN PCWSTR pwszPassword,
OUT PBYTE pBlob,
IN DWORD dwBlobSize
)
{
NTSTATUS ntStatus = STATUS_SUCCESS;
DWORD dwError = ERROR_SUCCESS;
size_t sPasswordLen = 0;
DWORD dwPasswordSize = 0;
PWSTR pwszPasswordLE = NULL;
BYTE PasswordBlob[516] = {0};
BYTE BlobInit[512] = {0};
DWORD iByte = 0;
BAIL_ON_INVALID_POINTER(pwszPassword);
BAIL_ON_INVALID_POINTER(pBlob);
if (dwBlobSize < sizeof(PasswordBlob))
{
dwError = ERROR_INSUFFICIENT_BUFFER;
BAIL_ON_LSA_ERROR(dwError);
}
dwError = LwWc16sLen(pwszPassword, &sPasswordLen);
BAIL_ON_LSA_ERROR(dwError);
/*
* Sanity check - password cannot be longer than the buffer size
*/
if ((sPasswordLen * sizeof(pwszPassword[0])) >
(sizeof(PasswordBlob) - sizeof(dwPasswordSize)))
{
dwError = ERROR_INVALID_PASSWORD;
BAIL_ON_LSA_ERROR(dwError);
}
/* size doesn't include terminating zero here */
dwPasswordSize = sPasswordLen * sizeof(pwszPassword[0]);
/*
* Make sure encoded password is 2-byte little-endian
*/
dwError = LwAllocateMemory(dwPasswordSize + sizeof(pwszPassword[0]),
OUT_PPVOID(&pwszPasswordLE));
BAIL_ON_LSA_ERROR(dwError);
wc16stowc16les(pwszPasswordLE, pwszPassword, sPasswordLen);
/*
* Encode the password length (in bytes) in the last 4 bytes
* as little-endian number
*/
iByte = sizeof(PasswordBlob);
PasswordBlob[--iByte] = (BYTE)((dwPasswordSize >> 24) & 0xff);
PasswordBlob[--iByte] = (BYTE)((dwPasswordSize >> 16) & 0xff);
PasswordBlob[--iByte] = (BYTE)((dwPasswordSize >> 8) & 0xff);
PasswordBlob[--iByte] = (BYTE)((dwPasswordSize) & 0xff);
/*
* Copy the password and the initial random bytes
*/
iByte -= dwPasswordSize;
memcpy(&(PasswordBlob[iByte]), pwszPasswordLE, dwPasswordSize);
/*
* Fill the rest of the buffer with (pseudo) random mess
* to increase security.
*/
dwError = LsaRandBytes((unsigned char*)BlobInit, iByte);
BAIL_ON_LSA_ERROR(dwError);
memcpy(PasswordBlob, BlobInit, iByte);
memcpy(pBlob, PasswordBlob, sizeof(PasswordBlob));
cleanup:
memset(PasswordBlob, 0, sizeof(PasswordBlob));
LW_SECURE_FREE_WSTRING(pwszPasswordLE);
if (ntStatus == STATUS_SUCCESS &&
dwError != ERROR_SUCCESS)
{
ntStatus = LwWin32ErrorToNtStatus(dwError);
}
return ntStatus;
error:
if (pBlob)
{
memset(pBlob, 0, dwBlobSize);
}
goto cleanup;
}
static
DWORD
LsaSaveMachinePassword(
PCWSTR pwszMachineName,
PCWSTR pwszMachineAccountName,
PCWSTR pwszMachineDnsDomain,
PCWSTR pwszDomainName,
PCWSTR pwszDnsDomainName,
PCWSTR pwszDCName,
PCWSTR pwszSidStr,
PCWSTR pwszPassword,
PSTR pszServicePrincipalNameList
)
{
DWORD dwError = ERROR_SUCCESS;
PWSTR pwszAccount = NULL;
PWSTR pwszDomain = NULL;
PWSTR pwszAdDnsDomainNameLc = NULL;
PWSTR pwszAdDnsDomainNameUc = NULL;
PWSTR pwszMachDnsDomainNameLc = NULL;
PWSTR pwszSid = NULL;
PWSTR pwszHostnameLc = NULL;
PWSTR pwszPass = NULL;
LSA_MACHINE_PASSWORD_INFO_W passwordInfo = { { 0 } };
size_t sPassLen = 0;
DWORD dwKvno = 0;
PWSTR pwszBaseDn = NULL;
PWSTR pwszSalt = NULL;
/* various forms of principal name for keytab */
PWSTR pwszPrincipal = NULL;
PWSTR pwszFqdn = NULL;
PWSTR pwszServiceClass = NULL;
PWSTR principalName = NULL;
PSTR pszSpn = NULL;
PSTR pszServicePrincipalListSave = NULL;
PSTR pszTmpServicePrincipalList = NULL;
BOOLEAN bIsServiceClass = FALSE;
dwError = LwAllocateWc16String(&pwszAccount,
pwszMachineAccountName);
BAIL_ON_LSA_ERROR(dwError);
dwError = LwAllocateWc16String(&pwszDomain,
pwszDomainName);
BAIL_ON_LSA_ERROR(dwError);
dwError = LwAllocateWc16String(&pwszAdDnsDomainNameLc,
pwszDnsDomainName);
BAIL_ON_LSA_ERROR(dwError);
LwWc16sToLower(pwszAdDnsDomainNameLc);
dwError = LwAllocateWc16String(&pwszAdDnsDomainNameUc,
pwszDnsDomainName);
BAIL_ON_LSA_ERROR(dwError);
LwWc16sToUpper(pwszAdDnsDomainNameUc);
dwError = LwAllocateWc16String(&pwszMachDnsDomainNameLc,
pwszMachineDnsDomain);
BAIL_ON_LSA_ERROR(dwError);
LwWc16sToLower(pwszMachDnsDomainNameLc);
dwError = LwAllocateWc16String(&pwszSid,
pwszSidStr);
BAIL_ON_LSA_ERROR(dwError);
dwError = LwAllocateWc16String(&pwszHostnameLc,
pwszMachineName);
BAIL_ON_LSA_ERROR(dwError);
LwWc16sToLower(pwszHostnameLc);
dwError = LwAllocateWc16sPrintfW(
&pwszFqdn,
L"%ws.%ws",
pwszHostnameLc,
pwszMachDnsDomainNameLc);
BAIL_ON_LSA_ERROR(dwError);
dwError = LwAllocateWc16String(&pwszPass,
pwszPassword);
BAIL_ON_LSA_ERROR(dwError);
/*
* Find the current key version number for machine account
*/
dwError = KtKrb5FormatPrincipalW(pwszAccount,
pwszAdDnsDomainNameUc,
&pwszPrincipal);
BAIL_ON_LSA_ERROR(dwError);
KtLdapSetSaslMaxBufSize(LsaSrvSaslMaxBufSize());
/* Get the directory base naming context first */
dwError = KtLdapGetBaseDnW(pwszDCName, &pwszBaseDn);
BAIL_ON_LSA_ERROR(dwError);
dwError = KtLdapGetKeyVersionW(pwszDCName,
pwszBaseDn,
pwszPrincipal,
&dwKvno);
if (dwError == ERROR_FILE_NOT_FOUND)
{
/*
* This is probably win2k DC we're talking to, because it doesn't
* store kvno in directory. In such case return default key version
*/
dwKvno = 0;
dwError = ERROR_SUCCESS;
}
else
{
BAIL_ON_LSA_ERROR(dwError);
}
/*
* Store the machine password
*/
passwordInfo.Account.DnsDomainName = pwszAdDnsDomainNameUc;
passwordInfo.Account.NetbiosDomainName = pwszDomain;
passwordInfo.Account.DomainSid = pwszSid;
passwordInfo.Account.SamAccountName = pwszAccount;
passwordInfo.Account.AccountFlags = LSA_MACHINE_ACCOUNT_TYPE_WORKSTATION;
passwordInfo.Account.KeyVersionNumber = dwKvno;
passwordInfo.Account.Fqdn = pwszFqdn;
passwordInfo.Account.LastChangeTime = 0;
passwordInfo.Password = pwszPass;
dwError = LsaPstoreSetPasswordInfoW(&passwordInfo);
BAIL_ON_LSA_ERROR(dwError);
dwError = LwWc16sLen(pwszPass, &sPassLen);
BAIL_ON_LSA_ERROR(dwError);
dwError = KtKrb5GetSaltingPrincipalW(pwszMachineName,
pwszAccount,
pwszMachineDnsDomain,
pwszAdDnsDomainNameUc,
pwszDCName,
pwszBaseDn,
&pwszSalt);
BAIL_ON_LSA_ERROR(dwError);
if (pwszSalt == NULL)
{
dwError = LwAllocateWc16String(&pwszSalt, pwszPrincipal);
BAIL_ON_LSA_ERROR(dwError);
}
/*
* Update keytab records with various forms of machine principal
*/
// MACHINE$@DOMAIN.NET
dwError = LsaSavePrincipalKey(
pwszAccount,
pwszPass,
sPassLen,
pwszAdDnsDomainNameUc,
pwszSalt,
pwszDCName,
dwKvno);
BAIL_ON_LSA_ERROR(dwError);
dwError = LwStrDupOrNull(pszServicePrincipalNameList, &pszTmpServicePrincipalList);
BAIL_ON_LSA_ERROR(dwError);
pszSpn = strtok_r(pszTmpServicePrincipalList, ",", &pszServicePrincipalListSave);
while (pszSpn)
{
if (pwszServiceClass)
LW_SAFE_FREE_MEMORY(pwszServiceClass);
GroomSpn(&pszSpn, &bIsServiceClass);
LSA_LOG_VERBOSE("Generating keytab entry for %s", pszSpn);
dwError = LwMbsToWc16s(pszSpn, &pwszServiceClass);
BAIL_ON_LSA_ERROR(dwError);
if (!bIsServiceClass)
{
// Add pszSpn as is.
dwError = LwAllocateWc16sPrintfW(&principalName, L"%ws", pwszServiceClass);
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaSavePrincipalKey(
principalName,
pwszPass,
sPassLen,
pwszAdDnsDomainNameUc,
pwszSalt,
pwszDCName,
dwKvno);
BAIL_ON_LSA_ERROR(dwError);
LW_SAFE_FREE_MEMORY(principalName);
}
else
{
// serviceclass/MACHINE@DOMAIN.NET
dwError = LsaBuildPrincipalName(
&principalName,
pwszServiceClass,
pwszMachineName,
TRUE,
NULL,
FALSE);
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaSavePrincipalKey(
principalName,
pwszPass,
sPassLen,
pwszAdDnsDomainNameUc,
pwszSalt,
pwszDCName,
dwKvno);
BAIL_ON_LSA_ERROR(dwError);
LW_SAFE_FREE_MEMORY(principalName);
// serviceclass/machine@DOMAIN.NET
dwError = LsaBuildPrincipalName(
&principalName,
pwszServiceClass,
pwszMachineName,
FALSE,
NULL,
FALSE);
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaSavePrincipalKey(
principalName,
pwszPass,
sPassLen,
pwszAdDnsDomainNameUc,
pwszSalt,
pwszDCName,
dwKvno);
BAIL_ON_LSA_ERROR(dwError);
LW_SAFE_FREE_MEMORY(principalName);
// serviceclass/MACHINE.DOMAIN.NET@DOMAIN.NET
dwError = LsaBuildPrincipalName(
&principalName,
pwszServiceClass,
pwszMachineName,
TRUE,
pwszMachineDnsDomain,
TRUE);
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaSavePrincipalKey(
principalName,
pwszPass,
sPassLen,
pwszAdDnsDomainNameUc,
pwszSalt,
pwszDCName,
dwKvno);
BAIL_ON_LSA_ERROR(dwError);
LW_SAFE_FREE_MEMORY(principalName);
// serviceclass/machine.domain.net@DOMAIN.NET
dwError = LsaBuildPrincipalName(
&principalName,
pwszServiceClass,
pwszMachineName,
FALSE,
pwszMachineDnsDomain,
FALSE);
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaSavePrincipalKey(
principalName,
pwszPass,
sPassLen,
pwszAdDnsDomainNameUc,
pwszSalt,
pwszDCName,
dwKvno);
BAIL_ON_LSA_ERROR(dwError);
LW_SAFE_FREE_MEMORY(principalName);
// serviceclass/MACHINE.domain.net@DOMAIN.NET
dwError = LsaBuildPrincipalName(
&principalName,
pwszServiceClass,
pwszMachineName,
TRUE,
pwszMachineDnsDomain,
FALSE);
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaSavePrincipalKey(
principalName,
pwszPass,
sPassLen,
pwszAdDnsDomainNameUc,
pwszSalt,
pwszDCName,
dwKvno);
BAIL_ON_LSA_ERROR(dwError);
LW_SAFE_FREE_MEMORY(principalName);
// serviceclass/machine.DOMAIN.NET@DOMAIN.NET
dwError = LsaBuildPrincipalName(
&principalName,
pwszServiceClass,
pwszMachineName,
FALSE,
pwszMachineDnsDomain,
TRUE);
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaSavePrincipalKey(
principalName,
pwszPass,
sPassLen,
pwszAdDnsDomainNameUc,
pwszSalt,
pwszDCName,
dwKvno);
BAIL_ON_LSA_ERROR(dwError);
LW_SAFE_FREE_MEMORY(principalName);
}
pszSpn = strtok_r(NULL, ",", &pszServicePrincipalListSave);
}
cleanup:
LW_SAFE_FREE_MEMORY(principalName);
LW_SAFE_FREE_MEMORY(pwszBaseDn);
LW_SAFE_FREE_MEMORY(pwszSalt);
LW_SAFE_FREE_MEMORY(pwszDomain);
LW_SAFE_FREE_MEMORY(pwszAdDnsDomainNameLc);
LW_SAFE_FREE_MEMORY(pwszAdDnsDomainNameUc);
LW_SAFE_FREE_MEMORY(pwszMachDnsDomainNameLc);
LW_SAFE_FREE_MEMORY(pwszSid);
LW_SAFE_FREE_MEMORY(pwszHostnameLc);
LW_SAFE_FREE_MEMORY(pwszPass);
LW_SAFE_FREE_MEMORY(pwszAccount);
LW_SAFE_FREE_MEMORY(pwszPrincipal);
LW_SAFE_FREE_MEMORY(pwszFqdn);
LW_SAFE_FREE_MEMORY(pwszServiceClass);
LW_SAFE_FREE_STRING(pszTmpServicePrincipalList);
return dwError;
error:
goto cleanup;
}
////////////////////////////////////////////////////////////////////////
static
DWORD
LsaBuildPrincipalName(
OUT PWSTR *ppPrincipalName,
IN PCWSTR InstanceName,
IN PCWSTR HostName,
IN BOOLEAN UpperCaseHostName,
IN OPTIONAL PCWSTR RealmName,
IN OPTIONAL BOOLEAN UpperCaseRealmName
)
{
DWORD dwError= ERROR_SUCCESS;
PWSTR hostName = NULL;
PWSTR realmName = NULL;
PWSTR principalName = NULL;
dwError = LwAllocateWc16String(&hostName, HostName);
BAIL_ON_LSA_ERROR(dwError);
if (UpperCaseHostName)
{
LwWc16sToUpper(hostName);
}
else
{
LwWc16sToLower(hostName);
}
if (RealmName)
{
dwError = LwAllocateWc16String(&realmName, RealmName);
BAIL_ON_LSA_ERROR(dwError);
if (UpperCaseRealmName)
{
LwWc16sToUpper(realmName);
}
else
{
LwWc16sToLower(realmName);
}
}
if (realmName)
{
dwError = LwAllocateWc16sPrintfW(
&principalName,
L"%ws/%ws.%ws",
InstanceName,
hostName,
realmName);
BAIL_ON_LSA_ERROR(dwError);
}
else
{
dwError = LwAllocateWc16sPrintfW(
&principalName,
L"%ws/%ws",
InstanceName,
hostName);
BAIL_ON_LSA_ERROR(dwError);
}
*ppPrincipalName = principalName;
error:
if (dwError != ERROR_SUCCESS)
{
LW_SAFE_FREE_MEMORY(principalName);
}
LW_SAFE_FREE_MEMORY(hostName);
LW_SAFE_FREE_MEMORY(realmName);
return dwError;
}
////////////////////////////////////////////////////////////////////////
static
DWORD
LsaSavePrincipalKey(
PCWSTR pwszName,
PCWSTR pwszPassword,
DWORD dwPasswordLen,
PCWSTR pwszRealm,
PCWSTR pwszSalt,
PCWSTR pwszDCName,
DWORD dwKvno
)
{
DWORD dwError = ERROR_SUCCESS;
PWSTR pwszPrincipal = NULL;
BAIL_ON_INVALID_POINTER(pwszName);
BAIL_ON_INVALID_POINTER(pwszPassword);
BAIL_ON_INVALID_POINTER(pwszDCName);
dwError = KtKrb5FormatPrincipalW(pwszName,
pwszRealm,
&pwszPrincipal);
BAIL_ON_LSA_ERROR(dwError);
dwError = KtKrb5AddKeyW(pwszPrincipal,
(PVOID)pwszPassword,
dwPasswordLen,
NULL,
pwszSalt,
pwszDCName,
dwKvno);
BAIL_ON_LSA_ERROR(dwError);
cleanup:
LW_SAFE_FREE_MEMORY(pwszPrincipal);
return dwError;
error:
goto cleanup;
}
static
DWORD
LsaDirectoryConnect(
PCWSTR pDomain,
LDAP** ppLdConn,
PWSTR* ppDefaultContext
)
{
DWORD dwError = ERROR_SUCCESS;
int lderr = LDAP_SUCCESS;
LDAP *pLdConn = NULL;
// Do not free
LDAPMessage *pInfo = NULL;
LDAPMessage *pRes = NULL;
PWSTR pAttributeName = NULL;
PWSTR* ppAttributeValue = NULL;
PWSTR pDefaultContext = NULL;
BAIL_ON_INVALID_POINTER(pDomain);
BAIL_ON_INVALID_POINTER(ppLdConn);
BAIL_ON_INVALID_POINTER(ppDefaultContext);
dwError = LdapInitConnection(&pLdConn, pDomain, FALSE);
BAIL_ON_LSA_ERROR(dwError);
lderr = LdapGetDirectoryInfo(&pInfo, &pRes, pLdConn);
BAIL_ON_LDAP_ERROR(lderr);
dwError = LwMbsToWc16s("defaultNamingContext",
&pAttributeName);
BAIL_ON_LSA_ERROR(dwError);
ppAttributeValue = LdapAttributeGet(pLdConn, pInfo, pAttributeName, NULL);
if (ppAttributeValue == NULL) {
/* TODO: find more descriptive error code */
lderr = LDAP_NO_SUCH_ATTRIBUTE;
BAIL_ON_LDAP_ERROR(lderr);
}
dwError = LwAllocateWc16String(&pDefaultContext, ppAttributeValue[0]);
BAIL_ON_LSA_ERROR(dwError);
*ppLdConn = pLdConn;
*ppDefaultContext = pDefaultContext;
cleanup:
LW_SAFE_FREE_MEMORY(pAttributeName);
if (ppAttributeValue)
{
LdapAttributeValueFree(ppAttributeValue);
}
if (pRes)
{
LdapMessageFree(pRes);
}
if (dwError == ERROR_SUCCESS &&
lderr != 0)
{
dwError = LwMapLdapErrorToLwError(lderr);
}
return dwError;
error:
if (pLdConn)
{
LdapCloseConnection(pLdConn);
}
LW_SAFE_FREE_MEMORY(pDefaultContext);
*ppLdConn = NULL;
*ppDefaultContext = NULL;
goto cleanup;
}
static
DWORD
LsaDirectoryDisconnect(
LDAP *ldconn
)
{
int lderr = LdapCloseConnection(ldconn);
return LwMapLdapErrorToLwError(lderr);
}
static
DWORD
LsaMachAcctCreate(
LDAP *ld,
const wchar16_t *machine_name,
const wchar16_t *machacct_name,
const wchar16_t *ou,
BOOLEAN move,
BOOLEAN exists
)
{
DWORD dwError = ERROR_SUCCESS;
int lderr = LDAP_SUCCESS;
LDAPMessage *machacct = NULL;
LDAPMessage *res = NULL;
LDAPMessage *info = NULL;
wchar16_t *dn_context_name = NULL;
wchar16_t **dn_context_val = NULL;
wchar16_t *dn_name = NULL;
wchar16_t **dn_val = NULL;
BAIL_ON_INVALID_POINTER(ld);
BAIL_ON_INVALID_POINTER(machine_name);
BAIL_ON_INVALID_POINTER(machacct_name);
BAIL_ON_INVALID_POINTER(ou);
if (exists == FALSE)
{
lderr = LdapMachAcctCreate(ld, machine_name, machacct_name, ou);
BAIL_ON_LDAP_ERROR(lderr);
}
else if (move)
{
lderr = LdapGetDirectoryInfo(&info, &res, ld);
BAIL_ON_LDAP_ERROR(lderr);
dwError = LwMbsToWc16s("defaultNamingContext",
&dn_context_name);
BAIL_ON_LSA_ERROR(dwError);
dn_context_val = LdapAttributeGet(ld, info, dn_context_name, NULL);
if (dn_context_val == NULL) {
/* TODO: find more descriptive error code */
lderr = LDAP_NO_SUCH_ATTRIBUTE;
goto error;
}
lderr = LdapMachAcctSearch(&machacct, ld, machacct_name, dn_context_val[0]);
// If the machine account with this sAMAccountName doesn't exist then we have a naming conflict
if (lderr == LDAP_NO_SUCH_OBJECT) lderr = LDAP_ALREADY_EXISTS;
BAIL_ON_LDAP_ERROR(lderr);
dwError = LwMbsToWc16s("distinguishedName", &dn_name);
BAIL_ON_LSA_ERROR(dwError);
dn_val = LdapAttributeGet(ld, machacct, dn_name, NULL);
if (dn_val == NULL) {
dwError = LW_ERROR_LDAP_INSUFFICIENT_ACCESS;
goto error;
}
lderr = LdapMachAcctMove(ld, dn_val[0], machine_name, ou);
BAIL_ON_LDAP_ERROR(lderr);
}
cleanup:
LW_SAFE_FREE_MEMORY(dn_context_name);
LW_SAFE_FREE_MEMORY(dn_name);
if (res)
{
LdapMessageFree(res);
}
if (machacct)
{
LdapMessageFree(machacct);
}
if (dn_context_val) {
LdapAttributeValueFree(dn_context_val);
}
if (dn_val) {
LdapAttributeValueFree(dn_val);
}
if (dwError == ERROR_SUCCESS && lderr != 0)
{
dwError = LwMapLdapErrorToLwError(lderr);
if (dwError == LW_ERROR_UNKNOWN && move)
{
/* provide a more useful error if possible */
dwError = LW_ERROR_LDAP_RENAME_FAILED;
}
}
return dwError;
error:
goto cleanup;
}
static
DWORD
LsaMachDnsNameSearch(
LDAP *ldconn,
const wchar16_t *fqdn,
const wchar16_t *machname,
const wchar16_t *dn_context,
wchar16_t **samacct
)
{
DWORD dwError = ERROR_SUCCESS;
int lderr = LDAP_SUCCESS;
LDAPMessage *res = NULL;
wchar16_t *samacct_attr_name = NULL;
wchar16_t **samacct_attr_val = NULL;
BAIL_ON_INVALID_POINTER(ldconn);
BAIL_ON_INVALID_POINTER(fqdn);
BAIL_ON_INVALID_POINTER(dn_context);
BAIL_ON_INVALID_POINTER(samacct);
*samacct = NULL;
// Attempt to find the computer account using the CN and FQDN (improve performance for pre-staged accounts and re-joining)
lderr = LdapMachDnsNameSearch(
&res,
ldconn,
fqdn,
machname,
dn_context);
if (lderr != LDAP_SUCCESS) {
// Couldn't find using the CN so try the old dNSHostName search
lderr = LdapMachDnsNameSearch(
&res,
ldconn,
fqdn,
NULL,
dn_context);
}
BAIL_ON_LDAP_ERROR(lderr);
dwError = LwMbsToWc16s("sAMAccountName",
&samacct_attr_name);
BAIL_ON_LSA_ERROR(dwError);
samacct_attr_val = LdapAttributeGet(ldconn, res, samacct_attr_name, NULL);
if (!samacct_attr_val) {
lderr = LDAP_NO_SUCH_ATTRIBUTE;
BAIL_ON_LDAP_ERROR(lderr);
}
dwError = LwAllocateWc16String(samacct, samacct_attr_val[0]);
BAIL_ON_LSA_ERROR(dwError);
cleanup:
LW_SAFE_FREE_MEMORY(samacct_attr_name);
LdapAttributeValueFree(samacct_attr_val);
if (res)
{
LdapMessageFree(res);
}
if (dwError == ERROR_SUCCESS &&
lderr != 0)
{
dwError = LwMapLdapErrorToLwError(lderr);
}
return dwError;
error:
*samacct = NULL;
goto cleanup;
}
static
DWORD
LsaMachAcctSearch(
LDAP *ldconn,
const wchar16_t *name,
const wchar16_t *dn_context,
wchar16_t **pDn,
wchar16_t **pDnsName
)
{
DWORD dwError = ERROR_SUCCESS;
int lderr = LDAP_SUCCESS;
LDAPMessage *res = NULL;
wchar16_t *dn_attr_name = NULL;
wchar16_t **dn_attr_val = NULL;
wchar16_t *dns_name_attr_name = NULL;
wchar16_t **dns_name_attr_val = NULL;
wchar16_t *dn = NULL;
wchar16_t *dnsName = NULL;
BAIL_ON_INVALID_POINTER(ldconn);
BAIL_ON_INVALID_POINTER(name);
BAIL_ON_INVALID_POINTER(dn_context);
lderr = LdapMachAcctSearch(&res, ldconn, name, dn_context);
BAIL_ON_LDAP_ERROR(lderr);
if (pDn)
{
dwError = LwMbsToWc16s("distinguishedName", &dn_attr_name);
BAIL_ON_LSA_ERROR(dwError);
dn_attr_val = LdapAttributeGet(ldconn, res, dn_attr_name, NULL);
if (!dn_attr_val) {
lderr = LDAP_NO_SUCH_ATTRIBUTE;
BAIL_ON_LDAP_ERROR(lderr);
}
dwError = LwAllocateWc16String(&dn, dn_attr_val[0]);
BAIL_ON_LSA_ERROR(dwError);
}
if (pDnsName)
{
dwError = LwMbsToWc16s("dNSHostName", &dns_name_attr_name);
BAIL_ON_LSA_ERROR(dwError);
dns_name_attr_val = LdapAttributeGet(
ldconn,
res,
dns_name_attr_name,
NULL);
if (dns_name_attr_val) {
dwError = LwAllocateWc16String(&dnsName, dns_name_attr_val[0]);
BAIL_ON_LSA_ERROR(dwError);
}
}
cleanup:
if (pDn)
{
*pDn = dn;
}
if (pDnsName)
{
*pDnsName = dnsName;
}
LW_SAFE_FREE_MEMORY(dn_attr_name);
LdapAttributeValueFree(dn_attr_val);
LW_SAFE_FREE_MEMORY(dns_name_attr_name);
LdapAttributeValueFree(dns_name_attr_val);
if (res) {
LdapMessageFree(res);
}
if (dwError == ERROR_SUCCESS &&
lderr != 0)
{
dwError = LwMapLdapErrorToLwError(lderr);
}
return dwError;
error:
LW_SAFE_FREE_MEMORY(dn);
LW_SAFE_FREE_MEMORY(dnsName);
goto cleanup;
}
static
DWORD
LsaMachAcctSetAttribute(
LDAP *ldconn,
const wchar16_t *dn,
const wchar16_t *attr_name,
const wchar16_t **attr_val,
int new
)
{
int lderr = LDAP_SUCCESS;
lderr = LdapMachAcctSetAttribute(ldconn, dn, attr_name, attr_val, new);
return LwMapLdapErrorToLwError(lderr);
}
DWORD
LsaGetDcName(
const wchar16_t *DnsDomainName,
BOOLEAN Force,
wchar16_t** DomainControllerName
)
{
DWORD dwError = 0;
wchar16_t *domain_controller_name = NULL;
char *dns_domain_name_mbs = NULL;
DWORD get_dc_name_flags = 0;
PLWNET_DC_INFO pDC = NULL;
if (Force)
{
get_dc_name_flags |= DS_FORCE_REDISCOVERY;
}
dwError = LwWc16sToMbs(DnsDomainName, &dns_domain_name_mbs);
BAIL_ON_LSA_ERROR(dwError);
dwError = LWNetGetDCName(NULL, dns_domain_name_mbs, NULL, get_dc_name_flags, &pDC);
BAIL_ON_LSA_ERROR(dwError);
dwError = LwMbsToWc16s(pDC->pszDomainControllerName,
&domain_controller_name);
BAIL_ON_LSA_ERROR(dwError)
cleanup:
LW_SAFE_FREE_MEMORY(dns_domain_name_mbs);
LWNET_SAFE_FREE_DC_INFO(pDC);
if (dwError)
{
LW_SAFE_FREE_MEMORY(domain_controller_name);
}
*DomainControllerName = domain_controller_name;
// ISSUE-2008/07/14-dalmeida -- Need to do error code conversion
return dwError;
error:
goto cleanup;
}
DWORD
LsaGetRwDcName(
const wchar16_t *DnsDomainName,
BOOLEAN Force,
wchar16_t** DomainControllerName
)
{
DWORD dwError = 0;
wchar16_t *domain_controller_name = NULL;
char *dns_domain_name_mbs = NULL;
DWORD get_dc_name_flags = DS_WRITABLE_REQUIRED;
PLWNET_DC_INFO pDC = NULL;
if (Force)
{
get_dc_name_flags |= DS_FORCE_REDISCOVERY;
}
dwError = LwWc16sToMbs(DnsDomainName, &dns_domain_name_mbs);
BAIL_ON_LSA_ERROR(dwError);
dwError = LWNetGetDCName(NULL, dns_domain_name_mbs, NULL, get_dc_name_flags, &pDC);
BAIL_ON_LSA_ERROR(dwError);
dwError = LwMbsToWc16s(pDC->pszDomainControllerName,
&domain_controller_name);
BAIL_ON_LSA_ERROR(dwError)
cleanup:
LW_SAFE_FREE_MEMORY(dns_domain_name_mbs);
LWNET_SAFE_FREE_DC_INFO(pDC);
if (dwError)
{
LW_SAFE_FREE_MEMORY(domain_controller_name);
}
*DomainControllerName = domain_controller_name;
// ISSUE-2008/07/14-dalmeida -- Need to do error code conversion
return dwError;
error:
goto cleanup;
}
DWORD
LsaEnableDomainGroupMembership(
PCSTR pszDomainName,
PCSTR pszDomainSID
)
{
return LsaChangeDomainGroupMembership(pszDomainName,
pszDomainSID,
TRUE);
}
DWORD
LsaChangeDomainGroupMembership(
IN PCSTR pszDomainName,
IN PCSTR pszDomainSID,
IN BOOLEAN bEnable
)
{
DWORD dwError = ERROR_SUCCESS;
NTSTATUS ntStatus = STATUS_SUCCESS;
PSID pDomainSid = NULL;
PSID pBuiltinAdminsSid = NULL;
PSID pBuiltinUsersSid = NULL;
PSID pDomainAdminsSid = NULL;
PSID pDomainUsersSid = NULL;
PSTR pszBuiltinAdminsSid = NULL;
PSTR pszBuiltinUsersSid = NULL;
PSTR pszDomainAdminsSid = NULL;
PSTR pszDomainUsersSid = NULL;
LSA_GROUP_MOD_INFO_2 adminsMods = {0};
LSA_GROUP_MOD_INFO_2 usersMods = {0};
PSTR pszTargetProvider = NULL;
HANDLE hConnection = NULL;
ntStatus = RtlAllocateSidFromCString(
&pDomainSid,
pszDomainSID);
BAIL_ON_NT_STATUS(ntStatus);
dwError = LwAllocateWellKnownSid(WinBuiltinAdministratorsSid,
NULL,
&pBuiltinAdminsSid,
NULL);
BAIL_ON_LSA_ERROR(dwError);
dwError = LwAllocateWellKnownSid(WinBuiltinUsersSid,
NULL,
&pBuiltinUsersSid,
NULL);
BAIL_ON_LSA_ERROR(dwError);
dwError = LwAllocateWellKnownSid(WinAccountDomainAdminsSid,
pDomainSid,
&pDomainAdminsSid,
NULL);
BAIL_ON_LSA_ERROR(dwError);
dwError = LwAllocateWellKnownSid(WinAccountDomainUsersSid,
pDomainSid,
&pDomainUsersSid,
NULL);
BAIL_ON_LSA_ERROR(dwError);
ntStatus = RtlAllocateCStringFromSid(
&pszBuiltinAdminsSid,
pBuiltinAdminsSid);
BAIL_ON_NT_STATUS(ntStatus);
ntStatus = RtlAllocateCStringFromSid(
&pszBuiltinUsersSid,
pBuiltinUsersSid);
BAIL_ON_NT_STATUS(ntStatus);
ntStatus = RtlAllocateCStringFromSid(
&pszDomainAdminsSid,
pDomainAdminsSid);
BAIL_ON_NT_STATUS(ntStatus);
ntStatus = RtlAllocateCStringFromSid(
&pszDomainUsersSid,
pDomainUsersSid);
BAIL_ON_NT_STATUS(ntStatus);
adminsMods.pszSid = pszBuiltinAdminsSid;
if (bEnable)
{
adminsMods.actions.bAddMembers = TRUE;
adminsMods.dwAddMembersNum = 1;
adminsMods.ppszAddMembers = &pszDomainAdminsSid;
}
else
{
adminsMods.actions.bRemoveMembers = TRUE;
adminsMods.dwRemoveMembersNum = 1;
adminsMods.ppszRemoveMembers = &pszDomainAdminsSid;
}
usersMods.pszSid = pszBuiltinUsersSid;
if (bEnable)
{
usersMods.actions.bAddMembers = TRUE;
usersMods.dwAddMembersNum = 1;
usersMods.ppszAddMembers = &pszDomainUsersSid;
}
else
{
usersMods.actions.bRemoveMembers = TRUE;
usersMods.dwRemoveMembersNum = 1;
usersMods.ppszRemoveMembers = &pszDomainUsersSid;
}
dwError = LwAllocateStringPrintf(
&pszTargetProvider,
":%s",
pszDomainName);
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaSrvOpenServer(0, 0, getpid(), &hConnection);
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaSrvModifyGroup2(
hConnection,
pszTargetProvider,
&adminsMods);
if ((bEnable && (dwError == ERROR_MEMBER_IN_ALIAS ||
dwError == ERROR_MEMBER_IN_GROUP)) ||
(!bEnable && (dwError == ERROR_MEMBER_NOT_IN_ALIAS ||
dwError == ERROR_MEMBER_NOT_IN_GROUP)))
{
dwError = 0;
}
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaSrvModifyGroup2(
hConnection,
pszTargetProvider,
&usersMods);
if ((bEnable && (dwError == ERROR_MEMBER_IN_ALIAS ||
dwError == ERROR_MEMBER_IN_GROUP)) ||
(!bEnable && (dwError == ERROR_MEMBER_NOT_IN_ALIAS ||
dwError == ERROR_MEMBER_NOT_IN_GROUP)))
{
dwError = 0;
}
BAIL_ON_LSA_ERROR(dwError);
error:
LW_SAFE_FREE_MEMORY(pDomainSid);
LW_SAFE_FREE_MEMORY(pBuiltinAdminsSid);
LW_SAFE_FREE_MEMORY(pBuiltinUsersSid);
LW_SAFE_FREE_MEMORY(pDomainAdminsSid);
LW_SAFE_FREE_MEMORY(pDomainUsersSid);
LW_SAFE_FREE_MEMORY(pszBuiltinAdminsSid);
LW_SAFE_FREE_MEMORY(pszBuiltinUsersSid);
LW_SAFE_FREE_MEMORY(pszDomainAdminsSid);
LW_SAFE_FREE_MEMORY(pszDomainUsersSid);
LW_SAFE_FREE_MEMORY(pszTargetProvider);
if (hConnection)
{
LsaSrvCloseServer(hConnection);
}
if (dwError == ERROR_SUCCESS &&
ntStatus != STATUS_SUCCESS)
{
dwError = LwNtStatusToWin32Error(ntStatus);
}
return dwError;
}
DWORD
LsaMachineChangePassword(
IN OPTIONAL PCSTR pszDnsDomainName,
IN PSTR pszServicePrincipalNameList
)
{
DWORD dwError = ERROR_SUCCESS;
PWSTR pwszDnsDomainName = NULL;
PWSTR pwszDCName = NULL;
size_t sDCNameLen = 0;
PLSA_MACHINE_PASSWORD_INFO_W pPasswordInfo = NULL;
PWSTR pwszUserName = NULL;
PWSTR pwszOldPassword = NULL;
WCHAR wszNewPassword[MACHPASS_LEN+1];
PWSTR pwszHostname = NULL;
PCWSTR pwszFqdnSuffix = NULL;
int i = 0;
memset(wszNewPassword, 0, sizeof(wszNewPassword));
if (pszDnsDomainName)
{
dwError = LwMbsToWc16s(pszDnsDomainName, &pwszDnsDomainName);
BAIL_ON_LSA_ERROR(dwError);
}
dwError = LsaPstoreGetPasswordInfoW(pwszDnsDomainName, &pPasswordInfo);
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaGetDcName(pPasswordInfo->Account.DnsDomainName, FALSE,
&pwszDCName);
BAIL_ON_LSA_ERROR(dwError);
pwszUserName = pPasswordInfo->Account.SamAccountName;
pwszOldPassword = pPasswordInfo->Password;
dwError = LwAllocateWc16String(&pwszHostname, pPasswordInfo->Account.Fqdn);
BAIL_ON_LSA_ERROR(dwError);
for (i = 0; pwszHostname[i]; i++)
{
if ('.' == pwszHostname[i])
{
pwszHostname[i] = 0;
pwszFqdnSuffix = &pwszHostname[i+1];
break;
}
}
LsaGenerateMachinePassword(
wszNewPassword,
sizeof(wszNewPassword)/sizeof(wszNewPassword[0]));
dwError = LwWc16sLen(pwszDCName, &sDCNameLen);
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaUserChangePassword(pwszDCName,
pwszUserName,
pwszOldPassword,
(PWSTR)wszNewPassword);
BAIL_ON_LSA_ERROR(dwError);
// TODO-2010/01/10-dalmeida -- Simplify this calling sequence
// by using keytab plugin in lsapstore...
dwError = LsaSaveMachinePassword(
pwszHostname,
pPasswordInfo->Account.SamAccountName,
pwszFqdnSuffix ? pwszFqdnSuffix : pPasswordInfo->Account.DnsDomainName,
pPasswordInfo->Account.NetbiosDomainName,
pPasswordInfo->Account.DnsDomainName,
pwszDCName,
pPasswordInfo->Account.DomainSid,
wszNewPassword,
pszServicePrincipalNameList);
BAIL_ON_LSA_ERROR(dwError);
error:
LW_SAFE_FREE_MEMORY(pwszDCName);
LW_SAFE_FREE_MEMORY(pwszHostname);
LSA_PSTORE_FREE_PASSWORD_INFO_W(&pPasswordInfo);
LW_SAFE_FREE_MEMORY(pwszDnsDomainName);
return dwError;
}
DWORD
LsaUserChangePassword(
PWSTR pwszDCName,
PWSTR pwszUserName,
PWSTR pwszOldPassword,
PWSTR pwszNewPassword
)
{
NTSTATUS ntStatus = STATUS_SUCCESS;
DWORD dwError = ERROR_SUCCESS;
SAMR_BINDING hSamrBinding = NULL;
size_t sOldPasswordLen = 0;
size_t sNewPasswordLen = 0;
BYTE OldNtHash[16] = {0};
BYTE NewNtHash[16] = {0};
BYTE NtPasswordBuffer[516] = {0};
BYTE NtVerHash[16] = {0};
RC4_KEY RC4Key;
PIO_CREDS pCreds = NULL;
ntStatus = LwIoGetActiveCreds(NULL, &pCreds);
BAIL_ON_NT_STATUS(ntStatus);
ntStatus = SamrInitBindingDefault(&hSamrBinding, pwszDCName, pCreds);
BAIL_ON_NT_STATUS(ntStatus);
dwError = LwWc16sLen(pwszOldPassword, &sOldPasswordLen);
BAIL_ON_LSA_ERROR(dwError);
dwError = LwWc16sLen(pwszNewPassword, &sNewPasswordLen);
BAIL_ON_LSA_ERROR(dwError);
/* prepare NT password hashes */
dwError = LsaGetNtPasswordHash(pwszOldPassword,
OldNtHash,
sizeof(OldNtHash));
BAIL_ON_LSA_ERROR(dwError);
dwError = LsaGetNtPasswordHash(pwszNewPassword,
NewNtHash,
sizeof(NewNtHash));
BAIL_ON_LSA_ERROR(dwError);
/* encode password buffer */
dwError = LsaEncodePasswordBuffer(pwszNewPassword,
NtPasswordBuffer,
sizeof(NtPasswordBuffer));
BAIL_ON_LSA_ERROR(dwError);
RC4_set_key(&RC4Key, 16, (unsigned char*)OldNtHash);
RC4(&RC4Key, sizeof(NtPasswordBuffer), NtPasswordBuffer, NtPasswordBuffer);
/* encode NT verifier */
dwError = LsaEncryptNtHashVerifier(NewNtHash, sizeof(NewNtHash),
OldNtHash, sizeof(OldNtHash),
NtVerHash, sizeof(NtVerHash));
BAIL_ON_LSA_ERROR(dwError);
ntStatus = SamrChangePasswordUser2(hSamrBinding,
pwszDCName,
pwszUserName,
NtPasswordBuffer,
NtVerHash,
0,
NULL,
NULL);
BAIL_ON_NT_STATUS(ntStatus);
cleanup:
if (hSamrBinding)
{
SamrFreeBinding(&hSamrBinding);
}
memset(OldNtHash, 0, sizeof(OldNtHash));
memset(NewNtHash, 0, sizeof(NewNtHash));
memset(NtPasswordBuffer, 0, sizeof(NtPasswordBuffer));
if (pCreds)
{
LwIoDeleteCreds(pCreds);
}
if (dwError == ERROR_SUCCESS &&
ntStatus != STATUS_SUCCESS)
{
dwError = NtStatusToWin32Error(ntStatus);
}
return dwError;
error:
goto cleanup;
}
static
DWORD
LsaGetNtPasswordHash(
IN PCWSTR pwszPassword,
OUT PBYTE pNtHash,
IN DWORD dwNtHashSize
)
{
DWORD dwError = ERROR_SUCCESS;
size_t sPasswordLen = 0;
PWSTR pwszPasswordLE = NULL;
BYTE Hash[16] = {0};
BAIL_ON_INVALID_POINTER(pwszPassword);
BAIL_ON_INVALID_POINTER(pNtHash);
if (dwNtHashSize < sizeof(Hash))
{
dwError = ERROR_INSUFFICIENT_BUFFER;
BAIL_ON_LSA_ERROR(dwError);
}
dwError = LwWc16sLen(pwszPassword, &sPasswordLen);
BAIL_ON_LSA_ERROR(dwError);
/*
* Make sure the password is 2-byte little-endian
*/
dwError = LwAllocateMemory((sPasswordLen + 1) * sizeof(pwszPasswordLE[0]),
OUT_PPVOID(&pwszPasswordLE));
BAIL_ON_LSA_ERROR(dwError);
wc16stowc16les(pwszPasswordLE, pwszPassword, sPasswordLen);
MD4((PBYTE)pwszPasswordLE,
sPasswordLen * sizeof(pwszPasswordLE[0]),
Hash);
memcpy(pNtHash, Hash, sizeof(Hash));
cleanup:
LW_SECURE_FREE_WSTRING(pwszPasswordLE);
memset(Hash, 0, sizeof(Hash));
return dwError;
error:
memset(pNtHash, 0, dwNtHashSize);
goto cleanup;
}
static
DWORD
LsaEncryptNtHashVerifier(
IN PBYTE pNewNtHash,
IN DWORD dwNewNtHashLen,
IN PBYTE pOldNtHash,
IN DWORD dwOldNtHashLen,
OUT PBYTE pNtVerifier,
IN DWORD dwNtVerifierSize
)
{
DWORD dwError = ERROR_SUCCESS;
DES_cblock KeyBlockLo;
DES_cblock KeyBlockHi;
DES_key_schedule KeyLo;
DES_key_schedule KeyHi;
BYTE Verifier[16] = {0};
BAIL_ON_INVALID_POINTER(pNewNtHash);
BAIL_ON_INVALID_POINTER(pOldNtHash);
BAIL_ON_INVALID_POINTER(pNtVerifier);
if (dwNtVerifierSize < sizeof(Verifier))
{
dwError = ERROR_INSUFFICIENT_BUFFER;
BAIL_ON_LSA_ERROR(dwError);
}
memset(&KeyBlockLo, 0, sizeof(KeyBlockLo));
memset(&KeyBlockHi, 0, sizeof(KeyBlockHi));
memset(&KeyLo, 0, sizeof(KeyLo));
memset(&KeyHi, 0, sizeof(KeyHi));
dwError = LsaPrepareDesKey(&pNewNtHash[0],
(PBYTE)KeyBlockLo);
BAIL_ON_LSA_ERROR(dwError);
DES_set_odd_parity(&KeyBlockLo);
DES_set_key_unchecked(&KeyBlockLo, &KeyLo);
dwError = LsaPrepareDesKey(&pNewNtHash[7],
(PBYTE)KeyBlockHi);
BAIL_ON_LSA_ERROR(dwError);
DES_set_odd_parity(&KeyBlockHi);
DES_set_key_unchecked(&KeyBlockHi, &KeyHi);
DES_ecb_encrypt((DES_cblock*)&pOldNtHash[0],
(DES_cblock*)&Verifier[0],
&KeyLo,
DES_ENCRYPT);
DES_ecb_encrypt((DES_cblock*)&pOldNtHash[8],
(DES_cblock*)&Verifier[8],
&KeyHi,
DES_ENCRYPT);
memcpy(pNtVerifier, Verifier, sizeof(Verifier));
cleanup:
memset(&KeyBlockLo, 0, sizeof(KeyBlockLo));
memset(&KeyBlockHi, 0, sizeof(KeyBlockHi));
memset(&KeyLo, 0, sizeof(KeyLo));
memset(&KeyHi, 0, sizeof(KeyHi));
return dwError;
error:
goto cleanup;
}
static
DWORD
LsaPrepareDesKey(
IN PBYTE pInput,
OUT PBYTE pOutput
)
{
DWORD dwError = ERROR_SUCCESS;
DWORD i = 0;
BAIL_ON_INVALID_POINTER(pInput);
BAIL_ON_INVALID_POINTER(pOutput);
/*
* Expand the input 7x8 bits so that each 7 bits are
* appended with 1 bit space for parity bit and yield
* 8x8 bits ready to become a DES key
*/
pOutput[0] = pInput[0] >> 1;
pOutput[1] = ((pInput[0]&0x01) << 6) | (pInput[1] >> 2);
pOutput[2] = ((pInput[1]&0x03) << 5) | (pInput[2] >> 3);
pOutput[3] = ((pInput[2]&0x07) << 4) | (pInput[3] >> 4);
pOutput[4] = ((pInput[3]&0x0F) << 3) | (pInput[4] >> 5);
pOutput[5] = ((pInput[4]&0x1F) << 2) | (pInput[5] >> 6);
pOutput[6] = ((pInput[5]&0x3F) << 1) | (pInput[6] >> 7);
pOutput[7] = pInput[6]&0x7F;
for (i = 0; i < 8; i++)
{
pOutput[i] = pOutput[i] << 1;
}
cleanup:
return dwError;
error:
goto cleanup;
}
| 27.546033 | 126 | 0.577855 | [
"object"
] |
22d8a834ff86f6b8db1e0819cd58e85dca77d2f8 | 2,649 | h | C | src/components/store/hstore/src/region.h | ghsecuritylab/comanche | a8862eaed59045377874b95b120832a0cba42193 | [
"Apache-2.0"
] | 19 | 2017-10-03T16:01:49.000Z | 2021-06-07T10:21:46.000Z | src/components/store/hstore/src/region.h | dnbaker/comanche | 121cd0fa16e55d461b366e83511d3810ea2b11c9 | [
"Apache-2.0"
] | 25 | 2018-02-21T23:43:03.000Z | 2020-09-02T08:47:32.000Z | src/components/store/hstore/src/region.h | dnbaker/comanche | 121cd0fa16e55d461b366e83511d3810ea2b11c9 | [
"Apache-2.0"
] | 19 | 2017-10-24T17:41:40.000Z | 2022-02-22T02:17:18.000Z | /*
Copyright [2017-2019] [IBM Corporation]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef COMANCHE_HSTORE_NUPM_REGION_H
#define COMANCHE_HSTORE_NUPM_REGION_H
/* requires persist_data_t definition */
#include "persist_data.h"
#include <sys/uio.h>
#include <memory>
class Devdax_manager;
template <typename PersistData, typename Heap>
class region
{
static constexpr std::uint64_t magic_value = 0xc74892d72eed493a;
public:
using heap_type = Heap;
using persist_data_type = PersistData;
private:
std::uint64_t magic;
std::uint64_t _uuid;
heap_type _heap;
persist_data_type _persist_data;
public:
region(
std::uint64_t uuid_
, std::size_t size_
, std::size_t expected_obj_count
, unsigned numa_node_
)
: magic(0)
, _uuid(uuid_)
, _heap(this+1, size_ - sizeof(*this), numa_node_)
, _persist_data(expected_obj_count, typename PersistData::allocator_type(heap()))
{
magic = magic_value;
persister_nupm::persist(this, sizeof *this);
}
/* The "reanimate" constructor */
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Winit-self"
#pragma GCC diagnostic ignored "-Wuninitialized"
region(
const std::unique_ptr<Devdax_manager> & devdax_manager_
)
: magic(0)
, _uuid(this->_uuid)
, _heap(devdax_manager_)
, _persist_data(std::move(this->_persist_data))
{
magic = magic_value;
persister_nupm::persist(this, sizeof *this);
}
#pragma GCC diagnostic pop
heap_rc heap() { return heap_rc(&_heap); }
persist_data_type &persist_data() { return _persist_data; }
bool is_initialized() const noexcept { return magic == magic_value; }
void quiesce() { _heap.quiesce(); }
std::vector<::iovec> get_regions()
{
std::vector<::iovec> regions;
regions.push_back(_heap.region());
return regions;
}
auto grow(
const std::unique_ptr<Devdax_manager> & devdax_manager_
, std::size_t increment_
) -> std::size_t
{
return _heap.grow(devdax_manager_, _uuid, increment_);
}
/* region used by heap_cc follows */
};
#endif
| 27.884211 | 87 | 0.694224 | [
"vector"
] |
22ed730709c6262e685562c3c57ac65e625b5aed | 1,960 | h | C | c/vlink/elf64.h | mfkiwl/QNICE-FPGA-hyperRAM | aabc8291ac1e0c4666c51f84acddf599d7521e53 | [
"BSD-3-Clause"
] | 53 | 2016-04-12T07:22:49.000Z | 2022-03-25T09:24:48.000Z | c/vlink/elf64.h | mfkiwl/QNICE-FPGA-hyperRAM | aabc8291ac1e0c4666c51f84acddf599d7521e53 | [
"BSD-3-Clause"
] | 196 | 2020-06-05T04:59:50.000Z | 2021-03-13T21:27:11.000Z | c/vlink/elf64.h | mfkiwl/QNICE-FPGA-hyperRAM | aabc8291ac1e0c4666c51f84acddf599d7521e53 | [
"BSD-3-Clause"
] | 15 | 2017-07-31T11:26:56.000Z | 2022-02-22T14:22:46.000Z | /* $VER: vlink elf64.h V0.14 (24.06.11)
*
* This file is part of vlink, a portable linker for multiple
* object formats.
* Copyright (c) 1997-2011 Frank Wille
*
* vlink is freeware and part of the portable and retargetable ANSI C
* compiler vbcc, copyright (c) 1995-2011 by Volker Barthelmann.
* vlink may be freely redistributed as long as no modifications are
* made and nothing is charged for it. Non-commercial usage is allowed
* without any restrictions.
* EVERY PRODUCT OR PROGRAM DERIVED DIRECTLY FROM MY SOURCE MAY NOT BE
* SOLD COMMERCIALLY WITHOUT PERMISSION FROM THE AUTHOR.
*/
#include "elfcommon.h"
#include "elf64std.h"
struct ShdrNode {
struct node n;
struct Elf64_Shdr s;
};
#if 0
/* .stab compilation units */
struct StabCompUnit {
struct node n;
long nameidx;
unsigned long entries;
struct list stabs;
struct StrTabList strtab;
};
#endif
/* Prototypes from t_elf64.c */
void elf64_parse(struct GlobalVars *,struct LinkFile *,struct Elf64_Ehdr *,
uint8_t (*)(uint8_t,struct RelocInsert *));
void elf64_initdynlink(struct GlobalVars *);
struct Section *elf64_dyntable(struct GlobalVars *,unsigned long,unsigned long,
uint8_t,uint8_t,uint8_t,int);
struct Symbol *elf64_pltgotentry(struct GlobalVars *,struct Section *,DynArg,
uint8_t,unsigned long,unsigned long,int);
struct Symbol *elf64_bssentry(struct GlobalVars *,const char *,struct Symbol *);
void elf64_dynamicentry(struct GlobalVars *,uint64_t,uint64_t,struct Section *);
void elf64_dyncreate(struct GlobalVars *,const char *);
unsigned long elf64_headersize(struct GlobalVars *);
void elf64_writerelocs(struct GlobalVars *,FILE *);
void elf64_writeobject(struct GlobalVars *,FILE *,uint16_t,int8_t,
uint8_t (*)(struct Reloc *));
void elf64_writeexec(struct GlobalVars *,FILE *,uint16_t,int8_t,
uint8_t (*)(struct Reloc *));
| 34.385965 | 80 | 0.710204 | [
"object"
] |
22f50c1d56b180f70d71b544f13a095819f907a5 | 1,657 | h | C | lib/common_storage.h | MaximAxelrod/psa_trusted_storage_linux | 9c481a80d7871f59d0cc5a7df995b665d2b1615e | [
"Apache-2.0"
] | 4 | 2019-10-24T15:40:07.000Z | 2020-01-30T18:56:54.000Z | lib/common_storage.h | MaximAxelrod/psa_trusted_storage_linux | 9c481a80d7871f59d0cc5a7df995b665d2b1615e | [
"Apache-2.0"
] | 6 | 2019-09-27T16:21:19.000Z | 2020-06-11T05:56:47.000Z | lib/common_storage.h | MaximAxelrod/psa_trusted_storage_linux | 9c481a80d7871f59d0cc5a7df995b665d2b1615e | [
"Apache-2.0"
] | 3 | 2020-06-07T13:19:35.000Z | 2020-06-17T13:53:55.000Z | /*
* Copyright (c) 2019 Arm Limited and Contributors. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef PSA_COMMON_STORAGE_H
#define PSA_COMMON_STORAGE_H
#include "psa/error.h"
#include "psa/storage_common.h"
/* IHI0087-PS_-Storage_API_1.0.0.pdf specifies 0 to be an invalid uid value
* and should be treated as an error */
#define PSA_STORATE_UID_INVALID_VALUE 0
typedef enum
{
PSA_CS_API_ITS = 0, /* internal trusted storage api call*/
PSA_CS_API_PS, /* protected storage api call */
PSA_CS_API_MAX
} psa_cs_api_t;
/**
* Create and/or set a file object data associated with a provided UID.
*/
psa_status_t psa_cs_set( psa_storage_uid_t uid,
size_t data_length,
const void *p_data,
psa_storage_create_flags_t create_flags,
psa_cs_api_t api,
void *ex_data );
/**
* Retrieve data associated with a provided UID.
*/
psa_status_t psa_cs_get( psa_storage_uid_t uid,
size_t data_offset,
size_t data_size,
void *p_data,
size_t *p_data_length,
psa_cs_api_t api );
/**
* Retrieve the metadata about the provided UID.
*/
psa_status_t psa_cs_get_info(psa_storage_uid_t uid, struct psa_storage_info_t *p_info, psa_cs_api_t api );
/**
* Remove the provided uid and its associated data from the storage
*/
psa_status_t psa_cs_remove(psa_storage_uid_t uid, psa_cs_api_t api );
#endif /* PSA_COMMON_STORAGE_H */
| 29.589286 | 106 | 0.624623 | [
"object"
] |
22f975e6e4b77eb2ce2338590a035a57d6d68662 | 4,217 | c | C | ext/phalconplus/db/unitofwork/lastinsertid.zep.c | bullsoft/phalconplus | a57a6832d1cba1f7d3aff5ea36a1032aff541570 | [
"BSD-3-Clause"
] | 51 | 2015-05-21T06:09:29.000Z | 2022-03-04T14:29:14.000Z | ext/phalconplus/db/unitofwork/lastinsertid.zep.c | bullsoft/phalconplus | a57a6832d1cba1f7d3aff5ea36a1032aff541570 | [
"BSD-3-Clause"
] | 2 | 2019-04-17T01:43:41.000Z | 2020-05-13T00:45:42.000Z | ext/phalconplus/db/unitofwork/lastinsertid.zep.c | bullsoft/phalconplus | a57a6832d1cba1f7d3aff5ea36a1032aff541570 | [
"BSD-3-Clause"
] | 26 | 2015-05-19T01:43:24.000Z | 2022-03-04T09:54:58.000Z |
#ifdef HAVE_CONFIG_H
#include "../../../ext_config.h"
#endif
#include <php.h>
#include "../../../php_ext.h"
#include "../../../ext.h"
#include <Zend/zend_operators.h>
#include <Zend/zend_exceptions.h>
#include <Zend/zend_interfaces.h>
#include "kernel/main.h"
#include "kernel/object.h"
#include "kernel/memory.h"
#include "kernel/fcall.h"
#include "kernel/operators.h"
#include "kernel/array.h"
#include "kernel/exception.h"
#include "kernel/concat.h"
ZEPHIR_INIT_CLASS(PhalconPlus_Db_UnitOfWork_LastInsertId) {
ZEPHIR_REGISTER_CLASS_EX(PhalconPlus\\Db\\UnitOfWork, LastInsertId, phalconplus, db_unitofwork_lastinsertid, phalconplus_db_unitofwork_abstractvalue_ce, phalconplus_db_unitofwork_lastinsertid_method_entry, 0);
zend_declare_property_null(phalconplus_db_unitofwork_lastinsertid_ce, SL("model"), ZEND_ACC_PROTECTED);
zend_class_implements(phalconplus_db_unitofwork_lastinsertid_ce, 1, phalconplus_contracts_stringer_ce);
return SUCCESS;
}
PHP_METHOD(PhalconPlus_Db_UnitOfWork_LastInsertId, __construct) {
zval *model, model_sub;
zval *this_ptr = getThis();
ZVAL_UNDEF(&model_sub);
zephir_fetch_params_without_memory_grow(1, 0, &model);
zephir_update_property_zval(this_ptr, ZEND_STRL("model"), model);
}
PHP_METHOD(PhalconPlus_Db_UnitOfWork_LastInsertId, getValue) {
zend_bool _5$$3;
zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL;
zend_long ZEPHIR_LAST_CALL_STATUS;
zval *unitwork, unitwork_sub, className, _0, hash, _1, inserted, _2, _3, _8, _9, info$$3, _4$$3, _6$$3, _7$$4;
zval *this_ptr = getThis();
ZVAL_UNDEF(&unitwork_sub);
ZVAL_UNDEF(&className);
ZVAL_UNDEF(&_0);
ZVAL_UNDEF(&hash);
ZVAL_UNDEF(&_1);
ZVAL_UNDEF(&inserted);
ZVAL_UNDEF(&_2);
ZVAL_UNDEF(&_3);
ZVAL_UNDEF(&_8);
ZVAL_UNDEF(&_9);
ZVAL_UNDEF(&info$$3);
ZVAL_UNDEF(&_4$$3);
ZVAL_UNDEF(&_6$$3);
ZVAL_UNDEF(&_7$$4);
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 1, 0, &unitwork);
zephir_read_property(&_0, this_ptr, ZEND_STRL("model"), PH_NOISY_CC | PH_READONLY);
ZEPHIR_INIT_VAR(&className);
zephir_get_class(&className, &_0, 0);
zephir_read_property(&_1, this_ptr, ZEND_STRL("model"), PH_NOISY_CC | PH_READONLY);
ZEPHIR_CALL_FUNCTION(&hash, "spl_object_hash", NULL, 122, &_1);
zephir_check_call_status();
ZEPHIR_CALL_METHOD(&inserted, unitwork, "getinserted", NULL, 0);
zephir_check_call_status();
zephir_read_property(&_3, this_ptr, ZEND_STRL("model"), PH_NOISY_CC | PH_READONLY);
ZEPHIR_CALL_METHOD(&_2, &inserted, "contains", NULL, 0, &_3);
zephir_check_call_status();
if (zephir_is_true(&_2)) {
ZEPHIR_OBS_VAR(&info$$3);
ZEPHIR_OBS_VAR(&_4$$3);
zephir_read_property(&_4$$3, this_ptr, ZEND_STRL("model"), PH_NOISY_CC);
zephir_array_fetch(&info$$3, &inserted, &_4$$3, PH_NOISY, "phalconplus/Db/UnitOfWork/LastInsertId.zep", 22);
_5$$3 = zephir_array_isset_string(&info$$3, SL("last_insert_id"));
if (_5$$3) {
zephir_array_fetch_string(&_6$$3, &info$$3, SL("last_insert_id"), PH_NOISY | PH_READONLY, "phalconplus/Db/UnitOfWork/LastInsertId.zep", 23);
_5$$3 = ZEPHIR_GT_LONG(&_6$$3, 0);
}
if (_5$$3) {
zephir_array_fetch_string(&_7$$4, &info$$3, SL("last_insert_id"), PH_NOISY | PH_READONLY, "phalconplus/Db/UnitOfWork/LastInsertId.zep", 24);
RETURN_MM_LONG(zephir_get_intval(&_7$$4));
}
RETURN_MM_LONG(0);
}
ZEPHIR_INIT_VAR(&_8);
object_init_ex(&_8, phalconplus_base_exception_ce);
ZEPHIR_INIT_VAR(&_9);
ZEPHIR_CONCAT_SVSVS(&_9, "Object(", &hash, ") instance of ", &className, " not in SplObjectStorage");
ZEPHIR_CALL_METHOD(NULL, &_8, "__construct", NULL, 2, &_9);
zephir_check_call_status();
zephir_throw_exception_debug(&_8, "phalconplus/Db/UnitOfWork/LastInsertId.zep", 29);
ZEPHIR_MM_RESTORE();
return;
}
PHP_METHOD(PhalconPlus_Db_UnitOfWork_LastInsertId, __toString) {
zval _0, _1;
zephir_method_globals *ZEPHIR_METHOD_GLOBALS_PTR = NULL;
zend_long ZEPHIR_LAST_CALL_STATUS;
zval *this_ptr = getThis();
ZVAL_UNDEF(&_0);
ZVAL_UNDEF(&_1);
ZEPHIR_MM_GROW();
zephir_read_property(&_0, this_ptr, ZEND_STRL("model"), PH_NOISY_CC | PH_READONLY);
ZEPHIR_CALL_FUNCTION(&_1, "spl_object_hash", NULL, 122, &_0);
zephir_check_call_status();
ZEPHIR_CONCAT_SV(return_value, "LastInsertId: ", &_1);
RETURN_MM();
}
| 30.781022 | 210 | 0.750534 | [
"object",
"model"
] |
22fc4047394bc1dfca904b610ef921eb807ab005 | 1,106 | h | C | proj/alog/16. 3Sum Closest/16. 3Sum Closest.h | andy-sheng/leetcode | 1fa070036f31d0bd18a9a11a5c771641f3cd9a03 | [
"MIT"
] | null | null | null | proj/alog/16. 3Sum Closest/16. 3Sum Closest.h | andy-sheng/leetcode | 1fa070036f31d0bd18a9a11a5c771641f3cd9a03 | [
"MIT"
] | null | null | null | proj/alog/16. 3Sum Closest/16. 3Sum Closest.h | andy-sheng/leetcode | 1fa070036f31d0bd18a9a11a5c771641f3cd9a03 | [
"MIT"
] | null | null | null | //
// 16. 3Sum Closest.h
// leetcode
//
// Created by andysheng on 2021/8/21.
// Copyright © 2021 Andy. All rights reserved.
//
#ifndef _6__3Sum_Closest_h
#define _6__3Sum_Closest_h
namespace P16 {
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end());
int ret = nums[0] + nums[1] + nums[2];
for (int xPos = 0; xPos < (int)nums.size() - 2; ++xPos) {
if (nums[xPos] > 0 && nums[xPos] > target) break;
if (xPos > 0 && nums[xPos] == nums[xPos-1]) continue;
int yPos = xPos + 1;
int zPos = nums.size() - 1;
while (yPos < zPos) {
int sum = nums[xPos] + nums[yPos] + nums[zPos];
ret = abs(sum - target) < abs(ret - target) ? sum : ret;
if (ret == target) {
break;
} else if (sum > target) {
--zPos;
} else {
++yPos;
}
}
}
return ret;
}
};
}
#endif /* _6__3Sum_Closest_h */
| 26.333333 | 72 | 0.465642 | [
"vector"
] |
fe11e19c63985c4a06c960c5fbdf7aca55e5ba63 | 845 | h | C | medic.h | Sandalmoth/wollsey-public | 4d8d7170531b97640f817300184c16f43c42c2e5 | [
"Zlib"
] | null | null | null | medic.h | Sandalmoth/wollsey-public | 4d8d7170531b97640f817300184c16f43c42c2e5 | [
"Zlib"
] | null | null | null | medic.h | Sandalmoth/wollsey-public | 4d8d7170531b97640f817300184c16f43c42c2e5 | [
"Zlib"
] | null | null | null | #ifndef __MEDIC_H__
#define __MEDIC_H__
#include <string>
#include <map>
#include <iostream>
#include "drug.h"
#include "protocol.h"
class Medic {
public:
Medic() { }
Medic(const Medic &medic) {
drugs = medic.drugs;
}
void add_drug(std::string name, Drug drug);
void set_protocol(Protocol p);
void drop_protocol();
double get_fitness(gene::id id);
std::vector<std::pair<std::string, double>> get_drug_concentrations(int timestep) {
return protocol.get_drug_concentrations(timestep);
}
void reset() {
timestep = 0;
}
void advance() {
++timestep;
}
friend std::ostream &operator<<(std::ostream &out, const Medic &medic);
private:
int timestep = 0;
// Consider indexable datastructure to get rid of nlogn complexity.
std::map<std::string, Drug> drugs;
Protocol protocol;
};
#endif
| 16.9 | 85 | 0.67929 | [
"vector"
] |
fe2e8e59718942cca160c906a79b21f11ae537c2 | 3,973 | h | C | fatal/type/operation.h | juchem/fatal | fcb1b7b3905fe5b020f765278b3f3b5961683863 | [
"BSD-3-Clause"
] | null | null | null | fatal/type/operation.h | juchem/fatal | fcb1b7b3905fe5b020f765278b3f3b5961683863 | [
"BSD-3-Clause"
] | null | null | null | fatal/type/operation.h | juchem/fatal | fcb1b7b3905fe5b020f765278b3f3b5961683863 | [
"BSD-3-Clause"
] | 1 | 2019-06-15T07:38:13.000Z | 2019-06-15T07:38:13.000Z | /*
* Copyright (c) 2016, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#ifndef FATAL_INCLUDE_fatal_type_operation_h
#define FATAL_INCLUDE_fatal_type_operation_h
#include <fatal/type/cartesian_product.h>
#include <fatal/type/deprecated/flatten.h>
#include <fatal/type/deprecated/transform.h>
#include <fatal/type/size.h>
#include <fatal/type/slice.h>
////////////////////////////////////////
// IMPLEMENTATION FORWARD DECLARATION //
////////////////////////////////////////
namespace ftl {
namespace detail {
namespace operation_impl {
template <typename...> struct list;
namespace expand_recursive_map {
template <typename, typename...> struct breadth;
template <template <typename...> class, typename...> struct depth;
} // namespace expand_recursive_map {
} // namespace operation_impl {
} // namespace detail {
////////////
// expand //
////////////
// TODO: DOCUMENT
template <template <typename...> class T, typename U>
struct expand {
template <typename... UArgs>
using front = ftl::apply<T, U, UArgs...>;
template <typename... UArgs>
using back = ftl::apply<T, UArgs..., U>;
};
template <
template <typename...> class T,
template <typename...> class U,
typename... Args
>
struct expand<T, U<Args...>> {
template <typename... UArgs>
using front = ftl::apply<T, Args..., UArgs...>;
template <typename... UArgs>
using back = ftl::apply<T, UArgs..., Args...>;
};
//////////////////////////
// expand_recursive_map //
//////////////////////////
// TODO: DOCUMENT
template <
template <typename...> class Which,
template <typename...> class List,
template <typename...> class Row = List
>
struct expand_recursive_map {
template <typename T>
using apply = typename detail::operation_impl::expand_recursive_map::depth<
Which, T
>::template apply<detail::operation_impl::list<>, Row>::template apply<List>;
};
////////////////////////////
// IMPLEMENTATION DETAILS //
////////////////////////////
namespace detail {
namespace operation_impl {
template <typename... Args>
struct list {
template <template <typename...> class T>
using apply = ftl::apply<T, Args...>;
template <typename... Suffix>
using push_back = list<Args..., Suffix...>;
};
//////////////////////////
// expand_recursive_map //
//////////////////////////
namespace expand_recursive_map {
template <template <typename...> class Which, typename... Pairs>
struct depth<Which, Which<Pairs...>> {
template <
typename Results,
template <typename...> class Row,
typename... Prefix
>
using apply = typename breadth<list<Prefix...>, Pairs...>::template apply<
Which, Row, Results
>;
};
template <template <typename...> class Which, typename Terminal>
struct depth<Which, Terminal> {
template <
typename Results,
template <typename...> class Row,
typename... Prefix
>
using apply = typename Results::template push_back<
ftl::apply<Row, Prefix..., Terminal>
>;
};
template <typename... Prefix, typename Pair, typename... Siblings>
struct breadth<list<Prefix...>, Pair, Siblings...> {
template <
template <typename...> class Which,
template <typename...> class Row,
typename Results
>
using apply = typename breadth<list<Prefix...>, Siblings...>::template apply<
Which, Row, typename depth<Which, second<Pair>>::template apply<
Results, Row, Prefix..., first<Pair>
>
>;
};
template <typename... Prefix>
struct breadth<list<Prefix...>> {
template <
template <typename...> class,
template <typename...> class,
typename Results
>
using apply = Results;
};
} // namespace expand_recursive_map {
} // namespace operation_impl {
} // namespace detail {
} // namespace ftl {
#endif // FATAL_INCLUDE_fatal_type_operation_h
| 25.467949 | 79 | 0.640826 | [
"transform"
] |
fe3e3fb14b26f57c0547185adcacd0ce23952893 | 1,294 | h | C | include/anki/resource/Skeleton.h | galek/anki-3d-engine | 2b12968d8f2ca44d2aeb7480a4b8e63f7703ae75 | [
"BSD-3-Clause"
] | 1 | 2016-09-29T06:39:41.000Z | 2016-09-29T06:39:41.000Z | include/anki/resource/Skeleton.h | galek/anki-3d-engine | 2b12968d8f2ca44d2aeb7480a4b8e63f7703ae75 | [
"BSD-3-Clause"
] | null | null | null | include/anki/resource/Skeleton.h | galek/anki-3d-engine | 2b12968d8f2ca44d2aeb7480a4b8e63f7703ae75 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (C) 2014, Panagiotis Christopoulos Charitos.
// All rights reserved.
// Code licensed under the BSD License.
// http://www.anki3d.org/LICENSE
#ifndef ANKI_RESOURCE_SKELETON_H
#define ANKI_RESOURCE_SKELETON_H
#include "anki/resource/Common.h"
#include "anki/Math.h"
namespace anki {
/// Skeleton bone
struct Bone
{
friend class Skeleton; ///< For loading
public:
Bone(ResourceAllocator<U8>& alloc)
: m_name(alloc)
{}
const ResourceString& getName() const
{
return m_name;
}
const Mat4& getTransform() const
{
return m_transform;
}
private:
ResourceString m_name; ///< The name of the bone
static const U32 MAX_CHILDS_PER_BONE = 4; ///< Please dont change this
// see the class notes
Mat4 m_transform;
};
/// It contains the bones with their position and hierarchy
///
/// XML file format:
///
/// @code
/// <skeleton>
/// <bones>
/// <bone>
/// <name>X</name>
/// <transform></transform>
/// <bone>
/// ...
/// </bones>
/// </skeleton>
/// @endcode
class Skeleton
{
public:
/// Load file
void load(const CString& filename, ResourceInitializer& init);
/// @name Accessors
/// @{
const ResourceVector<Bone>& getBones() const
{
return m_bones;
}
/// @}
private:
ResourceVector<Bone> m_bones;
};
} // end namespace
#endif
| 16.379747 | 71 | 0.665379 | [
"transform"
] |
fe4fa5614c0ac1f001b883d4bf4f0d9a181f7e9d | 1,878 | h | C | include/tools/dnd/dataObjects/TTransitiveData.h | etrange02/Fux | 2f49bcd8ec82eb521092c9162e01c8b0d00222ab | [
"CECILL-B"
] | 2 | 2016-03-21T10:48:34.000Z | 2017-03-17T19:50:34.000Z | include/tools/dnd/dataObjects/TTransitiveData.h | etrange02/Fux | 2f49bcd8ec82eb521092c9162e01c8b0d00222ab | [
"CECILL-B"
] | null | null | null | include/tools/dnd/dataObjects/TTransitiveData.h | etrange02/Fux | 2f49bcd8ec82eb521092c9162e01c8b0d00222ab | [
"CECILL-B"
] | null | null | null | #ifndef TTRANSITIVEDATA_H
#define TTRANSITIVEDATA_H
#include <vector>
#include "tools/dnd/dataObjects/TransitiveData.h"
namespace dragAndDrop
{
template<typename T>
class TTransitiveData : public TransitiveData
{
public:
/** Default constructor */
TTransitiveData()
{
}
/** Default destructor */
virtual ~TTransitiveData()
{
}
/** Copy constructor
* \param other Object to copy from
*/
TTransitiveData(const TTransitiveData& other)
{
*this = other;
}
/** Assignment operator
* \param rhs Object to assign from
* \return A reference to this
*/
TTransitiveData& operator=(const TTransitiveData<T>& rhs)
{
if (this == &rhs)
return *this;
m_items = rhs.m_items;
return *this;
}
void setCopy()
{
setCopy(true);
}
void setCut()
{
setCopy(false);
}
const std::vector<T>& getItems() const
{
return m_items;
}
void add(const T& item)
{
m_items.push_back(item);
}
void add(const std::vector<T>& items)
{
m_items.insert(m_items.end(), items.begin(), items.end());
}
virtual wxArrayString getFilenames() const = 0;
virtual bool isEmpty() const
{
return m_items.empty();
}
protected:
private:
std::vector<T> m_items;
};
}
#endif // TTRANSITIVEDATA_H
| 22.094118 | 74 | 0.440895 | [
"object",
"vector"
] |
fe523793ad82ae3f954aa1f79c60ceb1205fa15b | 492 | h | C | Redaxe/src/rdxpch.h | 6Axel9/RedaxeEngine | 4c2f4d2be5244b1bad7bf60f48b48b3e15c015b0 | [
"Apache-2.0"
] | null | null | null | Redaxe/src/rdxpch.h | 6Axel9/RedaxeEngine | 4c2f4d2be5244b1bad7bf60f48b48b3e15c015b0 | [
"Apache-2.0"
] | null | null | null | Redaxe/src/rdxpch.h | 6Axel9/RedaxeEngine | 4c2f4d2be5244b1bad7bf60f48b48b3e15c015b0 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <functional>
#include <algorithm>
#include <iostream>
#include <utility>
#include <memory>
#include <chrono>
#include <unordered_map>
#include <unordered_set>
#include <sstream>
#include <string>
#include <vector>
#include <array>
#include <list>
#ifdef RDX_PLATFORM_WIN
#include <Windows.h>
#endif
#include "glad/glad.h"
#include "glfw/glfw3.h"
#include "spdlog/spdlog.h"
#include "imgui.h"
#include "glm.hpp"
#define Log spdlog
#define Gui ImGui
#define Math glm | 16.4 | 26 | 0.737805 | [
"vector"
] |
fe5bdabf128b4b486a796765b26e08dc389bd966 | 103,211 | c | C | PHY62XX_SDK_2.0.1/example/ble_central/simpleBleCentral/Source/simpleBLECentral.c | sentervip/phy62xBleSDk2.0.1 | edbb43c98d3f27a584a0026a5aac8197d7a219d0 | [
"Apache-2.0"
] | 1 | 2020-12-14T19:47:20.000Z | 2020-12-14T19:47:20.000Z | PHY62XX_SDK_2.0.1/example/ble_central/simpleBleCentral/Source/simpleBLECentral.c | sentervip/phy62xBleSDk2.0.1 | edbb43c98d3f27a584a0026a5aac8197d7a219d0 | [
"Apache-2.0"
] | null | null | null | PHY62XX_SDK_2.0.1/example/ble_central/simpleBleCentral/Source/simpleBLECentral.c | sentervip/phy62xBleSDk2.0.1 | edbb43c98d3f27a584a0026a5aac8197d7a219d0 | [
"Apache-2.0"
] | null | null | null | /**************************************************************************************************
Phyplus Microelectronics Limited confidential and proprietary.
All rights reserved.
IMPORTANT: All rights of this software belong to Phyplus Microelectronics
Limited ("Phyplus"). Your use of this Software is limited to those
specific rights granted under the terms of the business contract, the
confidential agreement, the non-disclosure agreement and any other forms
of agreements as a customer or a partner of Phyplus. You may not use this
Software unless you agree to abide by the terms of these agreements.
You acknowledge that the Software may not be modified, copied,
distributed or disclosed unless embedded on a Phyplus Bluetooth Low Energy
(BLE) integrated circuit, either as a product or is integrated into your
products. Other than for the aforementioned purposes, you may not use,
reproduce, copy, prepare derivative works of, modify, distribute, perform,
display or sell this Software and/or its documentation for any purposes.
YOU FURTHER ACKNOWLEDGE AND AGREE THAT THE SOFTWARE AND DOCUMENTATION ARE
PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, TITLE,
NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL
PHYPLUS OR ITS SUBSIDIARIES BE LIABLE OR OBLIGATED UNDER CONTRACT,
NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR OTHER
LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE
OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT
OF SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
**************************************************************************************************/
/*********************************************************************
* INCLUDES
*/
#include "bcomdef.h"
#include "OSAL.h"
#include "OSAL_PwrMgr.h"
#include "OSAL_bufmgr.h"
#include "gatt.h"
#include "ll.h"
#include "ll_common.h"
#include "hci.h"
#include "gapgattserver.h"
#include "gattservapp.h"
#include "central.h"
#include "gapbondmgr.h"
#include "simpleGATTprofile_ota.h"
#include "simpleBLECentral.h"
#include "timer.h"
#include "log.h"
#include "ll_def.h"
#include "global_config.h"
#include "flash.h"
#include "rflib.h"
/*********************************************************************
* MACROS
*/
// Length of bd addr as a string
#define B_ADDR_STR_LEN 15
/*********************************************************************
* CONSTANTS
*/
// Maximum number of scan responses
#define DEFAULT_MAX_SCAN_RES 30
// Scan duration in ms
#define DEFAULT_SCAN_DURATION 5000
// Discovey mode (limited, general, all)
#define DEFAULT_DISCOVERY_MODE DEVDISC_MODE_ALL
// TRUE to use active scan
#define DEFAULT_DISCOVERY_ACTIVE_SCAN TRUE
// TRUE to use white list during discovery
#define DEFAULT_DISCOVERY_WHITE_LIST FALSE
// TRUE to use high scan duty cycle when creating link
#define DEFAULT_LINK_HIGH_DUTY_CYCLE FALSE
// TRUE to use white list when creating link
#define DEFAULT_LINK_WHITE_LIST FALSE
// Default RSSI polling period in ms
#define DEFAULT_RSSI_PERIOD 1000
// Whether to enable automatic parameter update request when a connection is formed
#define DEFAULT_ENABLE_UPDATE_REQUEST FALSE
// Minimum connection interval (units of 1.25ms) if automatic parameter update request is enabled
#define DEFAULT_UPDATE_MIN_CONN_INTERVAL 10
// Maximum connection interval (units of 1.25ms) if automatic parameter update request is enabled
#define DEFAULT_UPDATE_MAX_CONN_INTERVAL 300
// Slave latency to use if automatic parameter update request is enabled
#define DEFAULT_UPDATE_SLAVE_LATENCY 0
// Supervision timeout value (units of 10ms) if automatic parameter update request is enabled
#define DEFAULT_UPDATE_CONN_TIMEOUT 400
// Default passcode
#define DEFAULT_PASSCODE 0//19655
// Default GAP pairing mode
#define DEFAULT_PAIRING_MODE GAPBOND_PAIRING_MODE_NO_PAIRING//GAPBOND_PAIRING_MODE_WAIT_FOR_REQ
// Default MITM mode (TRUE to require passcode or OOB when pairing)
#define DEFAULT_MITM_MODE FALSE
// Default bonding mode, TRUE to bond
#define DEFAULT_BONDING_MODE FALSE //TRUE
// Default GAP bonding I/O capabilities
#define DEFAULT_IO_CAPABILITIES GAPBOND_IO_CAP_DISPLAY_ONLY
// Default service discovery timer delay in ms
#define DEFAULT_SVC_DISCOVERY_DELAY 1000
// TRUE to filter discovery results on desired service UUID
#define DEFAULT_DEV_DISC_BY_SVC_UUID TRUE
// Application states
enum
{
BLE_STATE_IDLE,
BLE_STATE_CONNECTING,
BLE_STATE_CONNECTED,
BLE_STATE_DISCONNECTING
};
// Discovery states
enum
{
BLE_DISC_STATE_IDLE, // Idle
BLE_DISC_STATE_SVC, // Service discovery
BLE_DISC_STATE_CHAR // Characteristic discovery
};
// add by zhufei.zhang 2018.10.25
#define PRIMARY_SERVICE_RES 10//0xFFFF
#define Characteristic_LEN 20
#define Characteristic_ValueIndex 1
#define Characteristic_NotifyIndex 2
#define Central_Test_ToDoList 6
/*********************************************************************
* TYPEDEFS
*/
// add by zhufei.zhang 2018.10.25
// Advertising and Scan Response Data
typedef struct
{
uint8_t Type;
uint8_t Len;
uint8_t Value[ATT_UUID_SIZE];
}SimpleADVServiceUUIDs;
typedef struct
{
uint8_t Type;
uint8_t Length;
uint8_t Value[31]; // Max PDU = 31
}SimpleADVLoaclName;
typedef struct{
uint16_t ConnMin;
uint16_t ConnMax;
}SimpleADVSlaveInterval;
typedef struct
{
uint8_t Type;
uint8_t Len;
uint8_t Value[ATT_UUID_SIZE];
}SimpleADVServiceSolicitation;
typedef struct
{
uint8_t Length;
uint8_t Value[31]; // Max PDU = 31
}SimpleADVServiceDATA;
typedef struct
{
uint8_t Length;
uint8_t Value[31]; // Max PDU = 31
}SimpleADVManufactureDATA;
typedef struct
{
uint8_t AddrType;
uint8_t addr[B_ADDR_LEN];
bool RSP_ReadFlag;
int8 rssi;
int8 TxPower;
uint8_t Flags;
SimpleADVServiceUUIDs UUID;
SimpleADVLoaclName LocalName;
uint8_t OOB_Data;
uint8_t SM_TK_Value;
SimpleADVSlaveInterval ConnIntervalRange;
SimpleADVServiceSolicitation ServiceSolicitation;
SimpleADVServiceDATA ServiceData;
SimpleADVManufactureDATA ManufactureData;
}SimpleClientADV_ScanData;
// Service and Characteristic
typedef struct
{
uint16_t charStartHandle;
uint16_t charUuid;
uint8_t UUID_Len;
uint8_t UUID[ATT_UUID_SIZE];
uint8_t Properties;
}SimpleCharacteristic;
typedef struct
{
// Service Info , User Don't Care
uint8_t Attribute_Data_Len;
uint16_t Attribute_StartHandle;
uint16_t End_Group_Handle;
// User Care
// Caculate UUID Len
uint8_t UUID_Len;
uint8_t UUID[ATT_UUID_SIZE];
// Characteristic
uint8_t CharacNum;
SimpleCharacteristic Characteristic[Characteristic_LEN];
}SimpleGATTReadGroupRsp;
typedef struct
{
// Primary Service Num
uint8_t PrimaryServiceCnt;
// Primary Service Characteristic Index
uint8_t PrimaryCharacIndex;
// Characteristic Find Index
uint8_t CharacFindIndex;
SimpleGATTReadGroupRsp ServerGroupService[PRIMARY_SERVICE_RES];
}SimpleGattScanServer;
typedef struct
{
uint32 toDoTick;
uint16 toDoEvt;
}ctvToDoList_t;
typedef struct
{
uint8 mtu;
uint8 pduLen;
uint8 pduLenSla;
uint8 phyMode;
uint8 phyModeSla;
uint8 connIntv;
uint8 latency;
uint8 notfIntv;
uint8 notfPktNum;
uint32 testCnt;
ctvToDoList_t ctvToDoList[Central_Test_ToDoList];
}centralTestVector_t;
typedef struct
{
uint32 cnt;
uint32 miss;
uint32 err;
uint32 isDone;
}ntfTest_t;
/*********************************************************************
* GLOBAL VARIABLES
*/
/*********************************************************************
* EXTERNAL VARIABLES
*/
extern uint32 g_osal_mem_allo_cnt;
extern uint32 g_osal_mem_free_cnt;
extern l2capSARDbugCnt_t g_sarDbgCnt;
extern llGlobalStatistics_t g_pmCounters;
/*********************************************************************
* EXTERNAL FUNCTIONS
*/
//extern void dbg_time_log(void);
//extern void osal_memory_statics(void *ptr,uint32* uBlkCnt,uint32* uBlkSize);
/*********************************************************************
* LOCAL VARIABLES
*/
// Task ID for internal task/event processing
static uint8 simpleBLETaskId;
// GAP GATT Attributes
static const uint8 simpleBLEDeviceName[GAP_DEVICE_NAME_LEN] = "Simple BLE Central";
// Number of scan results and scan result index
static uint8 simpleBLEScanRes;
static uint8 simpleBLEScanIdx;
// Scanning state
static uint8 simpleBLEScanning = FALSE;
// RSSI polling state
static uint8 simpleBLERssi = FALSE;
// Connection handle of current connection
static uint16 simpleBLEConnHandle = GAP_CONNHANDLE_INIT;
// Application state
static uint8 simpleBLEState = BLE_STATE_IDLE;
// Discovery state
static uint8 simpleBLEDiscState = BLE_DISC_STATE_IDLE;
//// Discovered service start and end handle
//static uint16 simpleBLESvcStartHdl = 0;
//static uint16 simpleBLESvcEndHdl = 0;
//// Discovered characteristic handle
//static uint16 simpleBLECharHdl = 0;
// Value to write
static uint8 simpleBLECharVal = 0;
//// Value read/write toggle
//static bool simpleBLEDoWrite = FALSE;
//// GATT read/write procedure state
//static bool simpleBLEProcedureInProgress = FALSE;
static gapDevRec_t simpleBlePeerTarget;
//static bool simBlePeerConnFlg=FALSE;
static uint8_t advDataFilterCnt;
static uint16 connIntv = 30;
static uint16 connLatency = 4;
static uint16 connTimeOut = 500;
static uint32 connEventCnt = 0;
static uint16 dleTxOctets=251;
static uint16 dleTxTime=2120;
static uint8 phyModeCtrl=0x01;
static uint16 dleTxOctetsSlave=251;
static uint16 dleTxTimeSlave=2120;
static uint8 phyModeCtrlSlave=0x01;
// add by zhufei.zhang 2018.10.25
static SimpleGattScanServer SimpleClientInfo;
static SimpleClientADV_ScanData simpleBLEDevList[DEFAULT_MAX_SCAN_RES];
#define RWN_TEST_VAL_LEN 20
static uint8 rwnTestCnt=0;
static uint8 rwnTestVal[RWN_TEST_VAL_LEN];
ntfTest_t ntfTest;
static uint16 mstWtCnt=0;
#define WTNR_TEST_VAL_LEN 251
uint8 wtnrTestVal[WTNR_TEST_VAL_LEN];
static uint8 slaCtrlCmd=0;
static uint16 wtnrInertvl=0;
//===================================================================
//mtu: ATT MTU Size [23 - 247]
//DLE: date length extion, pdu length in octect [27-255]
//phy: PHY MODE 1-> BLE_1M, 2->BLE_2M
//connIntv: ble connection interval, unit 5ms
//notfIntv: slave notify interval, 0x80 -> notfiy at connection event end,
// other value, notify interval uint is notfIntv[6:0]*5ms
//notfPkt: notifty packet number for each notify interval
//testTime: test vector mode contrl counter, whenc testTime=mstWtCnt,
// shift to next test vector in the table
enum{
NULL_TO_DO = 0x00,
CHAN_MAP = 0x01,
SLA_1M,
SLA_2M,
SLA_ANY,
MST_1M,
MST_2M,
MST_ANY,
SLA_HCLK48_32KRC,
SLA_HCLK48_32KXTAL,
SLA_HCLK16_32KRC,
SLA_HCLK16_32KXTAL,
SLA_HCLK64_32KRC,
SLA_HCLK64_32KXTAL,
SLA_CHECK_PER
};
static centralTestVector_t centralTestVectorTbl[]=
{
#if(CFG_A1_SLA_TEST==1)
//{ 23, 0, 0, 1, 0, 6, 50, 0x50, 8, 500, 200,CHAN_MAP, 300,SLA_HCLK16_32KRC, 400,SLA_CHECK_PER},
//{ 23, 0, 0, 1, 0, 6, 50, 0x50, 8, 500, 200,CHAN_MAP, 300,SLA_HCLK16_32KXTAL, 400,SLA_CHECK_PER},
//{ 23, 0, 0, 1, 0, 6, 50, 0x50, 8, 500, 200,CHAN_MAP, 300,SLA_HCLK48_32KRC, 400,SLA_CHECK_PER},
//{ 23, 0, 0, 1, 0, 6, 50, 0x50, 8, 500, 200,CHAN_MAP, 300,SLA_HCLK48_32KXTAL, 400,SLA_CHECK_PER},
{ 23, 0, 0, 1, 0, 3, 0, 0x80, 5, 10000, 500,CHAN_MAP, 9500,SLA_HCLK16_32KRC, 9800,SLA_CHECK_PER},
{ 23, 0, 0, 1, 0, 3, 0, 0x80, 5, 10000, 500,CHAN_MAP, 9500,SLA_HCLK48_32KXTAL, 9800,SLA_CHECK_PER},
{ 23, 0, 0, 1, 0, 3, 0, 0x80, 5, 10000, 500,CHAN_MAP, 9500,SLA_HCLK48_32KRC, 9800,SLA_CHECK_PER},
{ 23, 0, 0, 1, 0, 3, 0, 0x80, 5, 10000, 500,CHAN_MAP, 9500,SLA_HCLK16_32KXTAL, 9800,SLA_CHECK_PER},
{ 23, 0, 0, 1, 0, 10, 0, 0x80, 5, 5000, 500,CHAN_MAP, 4500,SLA_HCLK16_32KRC, 4800,SLA_CHECK_PER},
{ 23, 0, 0, 1, 0, 10, 0, 0x80, 5, 5000, 500,CHAN_MAP, 4500,SLA_HCLK48_32KXTAL, 4800,SLA_CHECK_PER},
{ 23, 0, 0, 1, 0, 10, 0, 0x80, 5, 5000, 500,CHAN_MAP, 4500,SLA_HCLK48_32KRC, 4800,SLA_CHECK_PER},
{ 23, 0, 0, 1, 0, 10, 0, 0x80, 5, 5000, 500,CHAN_MAP, 4500,SLA_HCLK16_32KXTAL, 4800,SLA_CHECK_PER},
{ 23, 0, 0, 1, 0, 6, 50, 0x50, 8, 3000, 500,CHAN_MAP, 2500,SLA_HCLK16_32KRC, 2800,SLA_CHECK_PER},
{ 23, 0, 0, 1, 0, 6, 50, 0x50, 8, 3000, 500,CHAN_MAP, 2500,SLA_HCLK48_32KXTAL, 2800,SLA_CHECK_PER},
{ 23, 0, 0, 1, 0, 6, 50, 0x50, 8, 3000, 500,CHAN_MAP, 2500,SLA_HCLK48_32KRC, 2800,SLA_CHECK_PER},
{ 23, 0, 0, 1, 0, 6, 50, 0x50, 8, 3000, 500,CHAN_MAP, 2500,SLA_HCLK16_32KXTAL, 2800,SLA_CHECK_PER},
{ 23, 0, 0, 1, 0, 6, 50, 0x7f, 3, 3000, 500,CHAN_MAP, 2500,SLA_HCLK16_32KRC, 2800,SLA_CHECK_PER},
{ 23, 0, 0, 1, 0, 6, 50, 0x7f, 3, 3000, 500,CHAN_MAP, 2500,SLA_HCLK48_32KXTAL, 2800,SLA_CHECK_PER},
{ 23, 0, 0, 1, 0, 6, 50, 0x7f, 3, 3000, 500,CHAN_MAP, 2500,SLA_HCLK48_32KRC, 2800,SLA_CHECK_PER},
{ 23, 0, 0, 1, 0, 6, 50, 0x7f, 3, 3000, 500,CHAN_MAP, 2500,SLA_HCLK16_32KXTAL, 2800,SLA_CHECK_PER},
{ 23, 0, 0, 1, 0, 100, 0, 0x80, 5, 3000, 500,CHAN_MAP, 2500,SLA_HCLK16_32KRC, 2800,SLA_CHECK_PER},
{ 23, 0, 0, 1, 0, 100, 0, 0x80, 5, 3000, 500,CHAN_MAP, 2500,SLA_HCLK48_32KXTAL, 2800,SLA_CHECK_PER},
{ 23, 0, 0, 1, 0, 100, 0, 0x80, 5, 3000, 500,CHAN_MAP, 2500,SLA_HCLK48_32KRC, 2800,SLA_CHECK_PER},
{ 23, 0, 0, 1, 0, 100, 0, 0x80, 5, 3000, 500,CHAN_MAP, 2500,SLA_HCLK16_32KXTAL, 2800,SLA_CHECK_PER},
#else
//{239, 251, 251, 1, 1, 10, 0, 0x80, 7, 10000, 1000,CHAN_MAP, 2500,SLA_1M, 5000,SLA_2M },
//{247, 60, 80, 1, 1, 10, 0, 0x80, 7, 10000, 1000,CHAN_MAP, 2500,SLA_1M, 5000,SLA_2M },
//{247, 80, 60, 1, 1, 10, 0, 0x80, 7, 10000, 1000,CHAN_MAP, 2500,SLA_1M, 5000,SLA_2M },
//{247, 128, 80, 1, 1, 10, 0, 0x80, 7, 10000, 1000,CHAN_MAP, 2500,MST_2M, 5000,SLA_1M },
//{239, 251, 251, 1, 1, 10, 0, 0x80, 7, 10000, 1000,CHAN_MAP, 2500,SLA_1M, 5000,SLA_2M },
//{247, 60, 80, 1, 1, 10, 0, 0x80, 7, 10000, 1000,CHAN_MAP, 2500,SLA_1M, 5000,SLA_2M },
//{247, 80, 60, 1, 1, 10, 0, 0x80, 7, 10000, 1000,CHAN_MAP, 2500,SLA_1M, 5000,SLA_2M },
//{247, 128, 80, 1, 1, 10, 0, 0x80, 7, 10000, 1000,CHAN_MAP, 2500,MST_2M, 5000,SLA_1M },
//{239, 251, 251, 1, 1, 10, 0, 0x80, 7, 10000, 1000,CHAN_MAP, 2500,SLA_1M, 5000,SLA_2M },
//{247, 60, 80, 1, 1, 10, 0, 0x80, 7, 10000, 1000,CHAN_MAP, 2500,SLA_1M, 5000,SLA_2M },
//{247, 80, 60, 1, 1, 10, 0, 0x80, 7, 10000, 1000,CHAN_MAP, 2500,SLA_1M, 5000,SLA_2M },
//{247, 128, 80, 1, 1, 10, 0, 0x80, 7, 10000, 1000,CHAN_MAP, 2500,MST_2M, 5000,SLA_1M },
//{239, 251, 251, 1, 1, 10, 0, 0x80, 7, 10000, 1000,CHAN_MAP, 2500,SLA_1M, 5000,SLA_2M },
//{247, 60, 80, 1, 1, 10, 0, 0x80, 7, 10000, 1000,CHAN_MAP, 2500,SLA_1M, 5000,SLA_2M },
//{247, 80, 60, 1, 1, 10, 0, 0x80, 7, 10000, 1000,CHAN_MAP, 2500,SLA_1M, 5000,SLA_2M },
//{247, 128, 80, 1, 1, 10, 0, 0x80, 7, 10000, 1000,CHAN_MAP, 2500,MST_2M, 5000,SLA_1M },
//{185, 200, 200, 2, 0, 5, 0, 0x80, 8, 10000, 1000,CHAN_MAP, 3000,SLA_2M, 4000,MST_2M },
//{ 23, 0, 0, 2, 0, 10, 0, 0x80, 7, 10000, 1000,CHAN_MAP, 3000,MST_2M, 4000,MST_ANY},
//{ 23, 0, 0, 1, 0, 10, 0, 0x80, 7, 10000, 1000,CHAN_MAP, 3000,MST_1M, 4000,MST_1M},
////mtu, dleM, dleS, phyM,phyS,connIntv, latency,notfIntv,notfPkt,testTime,toDoList0, toDoList1, toDoList2,
//{247, 0, 0, 1, 1, 10, 0, 0x80, 7, 500, 200,SLA_2M, 300,SLA_1M, 400,SLA_ANY},
//{247, 0, 0, 1, 1, 10, 0, 0x80, 7, 500, 200,SLA_2M, 300,SLA_1M, 400,SLA_ANY},
//{247, 0, 0, 1, 1, 10, 0, 0x80, 7, 500, 200,SLA_2M, 300,SLA_1M, 400,SLA_ANY},
//{247, 0, 0, 1, 1, 10, 0, 0x80, 7, 500, 200,SLA_2M, 300,SLA_1M, 400,SLA_ANY},
//{247, 0, 0, 1, 1, 10, 0, 0x80, 7, 500, 200,SLA_2M, 300,SLA_1M, 400,SLA_ANY},
//{247, 0, 0, 1, 1, 10, 0, 0x80, 7, 500, 200,SLA_2M, 300,SLA_1M, 400,SLA_ANY},
//{185, 200, 200, 2, 0, 5, 0, 0x80, 8, 500, 200,CHAN_MAP, 300,SLA_2M, 400,MST_2M },
//{185, 200, 200, 2, 0, 10, 0, 0x80, 8, 500, 200,CHAN_MAP, 300,SLA_2M, 400,MST_2M },
//{ 23, 0, 0, 1, 2, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,MST_1M, 400,MST_ANY},
//{ 80, 0, 0, 1, 2, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_ANY},
//{128, 70, 50, 1, 1, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,MST_1M, 400,SLA_ANY},
//{128, 50, 70, 1, 1, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,MST_1M, 400,SLA_ANY},
//{128, 132, 132, 1, 1, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,MST_1M, 400,SLA_ANY},
//{239, 80, 60, 1, 1, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_2M },
//{239, 60, 80, 1, 1, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_2M },
//{239, 251, 251, 1, 1, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_2M },
//{247, 60, 80, 1, 1, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_2M },
//{247, 80, 60, 1, 1, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_2M },
//{247, 128, 80, 1, 1, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 80, 128, 1, 1, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 251, 80, 1, 1, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 80, 251, 1, 1, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 251, 128, 1, 1, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 128, 251, 1, 1, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 251, 251, 1, 1, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{ 23, 0, 0, 1, 2, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,MST_1M, 400,MST_ANY},
//{ 80, 0, 0, 1, 2, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_ANY},
//{128, 70, 50, 1, 1, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,MST_1M, 400,SLA_ANY},
//{128, 50, 70, 1, 1, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,MST_1M, 400,SLA_ANY},
//{128, 132, 132, 1, 1, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,MST_1M, 400,SLA_ANY},
//{239, 80, 60, 1, 1, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_2M },
//{239, 60, 80, 1, 1, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_2M },
//{239, 251, 251, 1, 1, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_2M },
//{247, 60, 80, 1, 1, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_2M },
//{247, 80, 60, 1, 1, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_2M },
//{247, 128, 80, 1, 1, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 80, 128, 1, 1, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 251, 80, 1, 1, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 80, 251, 1, 1, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 251, 128, 1, 1, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 128, 251, 1, 1, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 251, 251, 1, 1, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
////---------------------------------------------------------------5------2--------------3------------4----------
//{ 23, 0, 0, 2, 0, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,MST_1M, 400,MST_ANY},
//{ 80, 0, 0, 2, 0, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_ANY},
//{128, 70, 50, 2, 0, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,MST_1M, 400,SLA_ANY},
//{128, 50, 70, 2, 0, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,MST_1M, 400,SLA_ANY},
//{128, 132, 132, 2, 0, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,MST_1M, 400,SLA_ANY},
//{239, 80, 60, 2, 0, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_2M },
//{239, 60, 80, 2, 0, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_2M },
//{239, 251, 251, 2, 0, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_2M },
//{247, 60, 80, 2, 0, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_2M },
//{247, 80, 60, 2, 0, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_2M },
//{247, 128, 80, 2, 0, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 80, 128, 2, 0, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 251, 80, 2, 0, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 80, 251, 2, 0, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 251, 128, 2, 0, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 128, 251, 2, 0, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 251, 251, 2, 0, 10, 0, 0x80, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{ 23, 0, 0, 2, 0, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,MST_1M, 400,MST_ANY},
//{ 80, 0, 0, 2, 0, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_ANY},
//{128, 70, 50, 2, 0, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,MST_1M, 400,SLA_ANY},
//{128, 50, 70, 2, 0, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,MST_1M, 400,SLA_ANY},
//{128, 132, 132, 2, 0, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,MST_1M, 400,SLA_ANY},
//{239, 80, 60, 2, 0, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_2M },
//{239, 60, 80, 2, 0, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_2M },
//{239, 251, 251, 2, 0, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_2M },
//{247, 60, 80, 2, 0, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_2M },
//{247, 80, 60, 2, 0, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,SLA_1M, 400,SLA_2M },
//{247, 128, 80, 2, 0, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 80, 128, 2, 0, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 251, 80, 2, 0, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 80, 251, 2, 0, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 251, 128, 2, 0, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 128, 251, 2, 0, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
//{247, 251, 251, 2, 0, 10, 0, 0x60, 7, 500, 200,CHAN_MAP, 300,MST_2M, 400,SLA_1M },
////mtu, dleM, dleS, phyM, phyS, connIntv, latency, notfIntv, notfPkt, testTime, toDoList0, toDoList1, toDoList2, toDoList3, toDoList4, toDoList5
{ 247, 251, 251, 1, 1, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK16_32KRC, 9800,SLA_CHECK_PER},
{ 247, 251, 251, 1, 1, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK16_32KXTAL, 9800,SLA_CHECK_PER},
{ 247, 251, 251, 1, 1, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK48_32KRC, 9800,SLA_CHECK_PER},
{ 247, 251, 251, 1, 1, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK48_32KXTAL, 9800,SLA_CHECK_PER},
{ 247, 251, 251, 1, 1, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK64_32KRC, 9800,SLA_CHECK_PER},
{ 247, 251, 251, 1, 1, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK64_32KXTAL, 9800,SLA_CHECK_PER},
{ 247, 100, 200, 1, 1, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK16_32KRC, 9800,SLA_CHECK_PER},
{ 247, 100, 200, 1, 1, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK16_32KXTAL, 9800,SLA_CHECK_PER},
{ 247, 100, 200, 1, 1, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK48_32KRC, 9800,SLA_CHECK_PER},
{ 247, 100, 200, 1, 1, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK48_32KXTAL, 9800,SLA_CHECK_PER},
{ 247, 100, 200, 1, 1, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK64_32KRC, 9800,SLA_CHECK_PER},
{ 247, 100, 200, 1, 1, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK64_32KXTAL, 9800,SLA_CHECK_PER},
{ 128, 70, 50, 1, 1, 200, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK16_32KRC, 9800,SLA_CHECK_PER},
{ 128, 70, 50, 1, 1, 200, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK16_32KXTAL, 9800,SLA_CHECK_PER},
{ 128, 70, 50, 1, 1, 200, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK48_32KRC, 9800,SLA_CHECK_PER},
{ 128, 70, 50, 1, 1, 200, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK48_32KXTAL, 9800,SLA_CHECK_PER},
{ 128, 70, 50, 1, 1, 200, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK64_32KRC, 9800,SLA_CHECK_PER},
{ 128, 70, 50, 1, 1, 200, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK64_32KXTAL, 9800,SLA_CHECK_PER},
// -------------------------------------1---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// -------------------------------------1---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// -------------------------------------1---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// -------------------------------------1---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
{ 247, 251, 251, 2, 0, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK16_32KRC, 9800,SLA_CHECK_PER},
{ 247, 251, 251, 2, 0, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK16_32KXTAL, 9800,SLA_CHECK_PER},
{ 247, 251, 251, 2, 0, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK48_32KRC, 9800,SLA_CHECK_PER},
{ 247, 251, 251, 2, 0, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK48_32KXTAL, 9800,SLA_CHECK_PER},
{ 247, 251, 251, 2, 0, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK64_32KRC, 9800,SLA_CHECK_PER},
{ 247, 251, 251, 2, 0, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK64_32KXTAL, 9800,SLA_CHECK_PER},
{ 247, 100, 200, 2, 0, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK16_32KRC, 9800,SLA_CHECK_PER},
{ 247, 100, 200, 2, 0, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK16_32KXTAL, 9800,SLA_CHECK_PER},
{ 247, 100, 200, 2, 0, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK48_32KRC, 9800,SLA_CHECK_PER},
{ 247, 100, 200, 2, 0, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK48_32KXTAL, 9800,SLA_CHECK_PER},
{ 247, 100, 200, 2, 0, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK64_32KRC, 9800,SLA_CHECK_PER},
{ 247, 100, 200, 2, 0, 10, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK64_32KXTAL, 9800,SLA_CHECK_PER},
{ 128, 70, 50, 2, 0, 200, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK16_32KRC, 9800,SLA_CHECK_PER},
{ 128, 70, 50, 2, 0, 200, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK16_32KXTAL, 9800,SLA_CHECK_PER},
{ 128, 70, 50, 2, 0, 200, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK48_32KRC, 9800,SLA_CHECK_PER},
{ 128, 70, 50, 2, 0, 200, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK48_32KXTAL, 9800,SLA_CHECK_PER},
{ 128, 70, 50, 2, 0, 200, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK64_32KRC, 9800,SLA_CHECK_PER},
{ 128, 70, 50, 2, 0, 200, 0, 0x80, 8, 10000, 500,CHAN_MAP, 1000,SLA_2M, 3000,SLA_1M, 5000,SLA_ANY, 7000,SLA_HCLK64_32KXTAL, 9800,SLA_CHECK_PER},
#endif
};
static uint16 cTVIdx=0;
static uint16 cTVErrCnt = 0;
/*********************************************************************
* LOCAL FUNCTIONS
*/
static void simpleBLECentralProcessGATTMsg( gattMsgEvent_t *pMsg );
static void simpleBLECentralRssiCB( uint16 connHandle, int8 rssi );
static void simpleBLECentralEventCB( gapCentralRoleEvent_t *pEvent );
static void simpleBLECentralPasscodeCB( uint8 *deviceAddr, uint16 connectionHandle,
uint8 uiInputs, uint8 uiOutputs );
static void simpleBLECentralPairStateCB( uint16 connHandle, uint8 state, uint8 status );
static void simpleBLECentral_HandleKeys( uint8 shift, uint8 keys );
static void simpleBLECentral_ProcessOSALMsg( osal_event_hdr_t *pMsg );
static void simpleBLEGATTDiscoveryEvent( gattMsgEvent_t *pMsg );
static void simpleBLECentralStartDiscoveryService( void );
static bool simpleBLEFindSvcUuid( uint16 uuid, uint8 *pData, uint8 dataLen );
static void simpleBLEAddDeviceInfo( gapCentralRoleEvent_t *pEvent );
char *bdAddr2Str ( uint8 *pAddr );
static uint8_t simpleBLECentral_AdvDataFilterCBack(void);
// add by zhufei.zhang
static void simpleBLEAnalysisADVDATA(uint8 Index,gapDeviceInfoEvent_t *pData);
static void simpleBLECentral_CharacteristicTest(void);
static void simpleBLECentral_DiscoverDevice(void);
static void simpleBLECentral_LinkDevice(void);
static void simpleBLECentral_ReadWriteNotifyTest(void);
static void centralTestVectorProcess(void);
/*********************************************************************
* PROFILE CALLBACKS
*/
// GAP Role Callbacks
static const gapCentralRoleCB_t simpleBLERoleCB =
{
simpleBLECentralRssiCB, // RSSI callback
simpleBLECentralEventCB // Event callback
};
// Bond Manager Callbacks
static const gapBondCBs_t simpleBLEBondCB =
{
simpleBLECentralPasscodeCB,
simpleBLECentralPairStateCB
};
/*********************************************************************
* PUBLIC FUNCTIONS
*/
/*********************************************************************
* @fn SimpleBLECentral_Init
*
* @brief Initialization function for the Simple BLE Central App Task.
* This is called during initialization and should contain
* any application specific initialization (ie. hardware
* initialization/setup, table initialization, power up
* notification).
*
* @param task_id - the ID assigned by OSAL. This ID should be
* used to send messages and set timers.
*
* @return none
*/
void SimpleBLECentral_Init( uint8 task_id )
{
simpleBLETaskId = task_id;
// Setup Central Profile
{
uint8 scanRes = DEFAULT_MAX_SCAN_RES;
GAPCentralRole_SetParameter ( GAPCENTRALROLE_MAX_SCAN_RES, sizeof( uint8 ), &scanRes );
}
// Setup GAP
GAP_SetParamValue( TGAP_GEN_DISC_SCAN, DEFAULT_SCAN_DURATION );
GAP_SetParamValue( TGAP_LIM_DISC_SCAN, DEFAULT_SCAN_DURATION );
GAP_SetParamValue( TGAP_CONN_EST_INT_MIN, 30 ); // * 1.25ms // 30
GAP_SetParamValue( TGAP_CONN_EST_INT_MAX, 40 );
GGS_SetParameter( GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, (uint8 *) simpleBLEDeviceName );
// Setup the GAP Bond Manager
{
uint32 passkey = DEFAULT_PASSCODE;
uint8 pairMode = GAPBOND_PAIRING_MODE_NO_PAIRING;//GAPBOND_PAIRING_MODE_INITIATE;//DEFAULT_PAIRING_MODE; // GAPBOND_PAIRING_MODE_NO_PAIRING
uint8 mitm = DEFAULT_MITM_MODE;
uint8 ioCap = DEFAULT_IO_CAPABILITIES;
uint8 bonding = DEFAULT_BONDING_MODE;
GAPBondMgr_SetParameter( GAPBOND_DEFAULT_PASSCODE, sizeof( uint32 ), &passkey );
GAPBondMgr_SetParameter( GAPBOND_PAIRING_MODE, sizeof( uint8 ), &pairMode );
GAPBondMgr_SetParameter( GAPBOND_MITM_PROTECTION, sizeof( uint8 ), &mitm );
GAPBondMgr_SetParameter( GAPBOND_IO_CAPABILITIES, sizeof( uint8 ), &ioCap );
GAPBondMgr_SetParameter( GAPBOND_BONDING_ENABLED, sizeof( uint8 ), &bonding );
}
for(uint8 i=0;i<RWN_TEST_VAL_LEN-1;i++)
rwnTestVal[i]=i;
for(uint8 i=0;i<WTNR_TEST_VAL_LEN-1;i++)
wtnrTestVal[i]=i;
//
// Initialize GATT Client
VOID GATT_InitClient();
// Register to receive incoming ATT Indications/Notifications
GATT_RegisterForInd( simpleBLETaskId );
// Initialize GATT attributes
GGS_AddService( GATT_ALL_SERVICES ); // GAP
GATTServApp_AddService( GATT_ALL_SERVICES ); // GATT attributes
// Setup a delayed profile startup
osal_set_event( simpleBLETaskId, START_DEVICE_EVT );
AT_LOG("[PEER ADDR]");
for(int i=0;i<6;i++)
{
simpleBlePeerTarget.addr[i]=ReadFlash(0x11004008+i);
AT_LOG("%02x",simpleBlePeerTarget.addr[i]);
}
AT_LOG("\n");
// dbg_time_log();
HCI_LE_AddWhiteListCmd(LL_DEV_ADDR_TYPE_PUBLIC,simpleBlePeerTarget.addr);
// simpleBlePeerTarget.addr[5]=0x62;
// simpleBlePeerTarget.addr[4]=0x02;
// simpleBlePeerTarget.addr[3]=0xA1;
// simpleBlePeerTarget.addr[2]=0x0C;
// simpleBlePeerTarget.addr[1]=0x02;
// simpleBlePeerTarget.addr[0]=0x08;
}
//void SimpleBLECentral_SendTestMessage(uint16 connHandle)
//{
//#if 0
// uint8 *buf;
// bStatus_t status;
//
// attExchangeMTUReq_t *pReq, req;
//
// pReq = &req;
//
// pReq->clientRxMTU = 0x0017;
//
// status = attSendMsg( connHandle, ATT_BuildExchangeMTUReq, ATT_EXCHANGE_MTU_REQ, (uint8 *)pReq );
// if (status == bleMemAllocError)
// LOG("===>bleMemAllocError!!!\r\n");
//#else
//// l2capPacket_t pkt;
//// uint8 *buf;
//// uint8 status;
////
//// // Allocate space for the message
//// buf = (uint8 *)L2CAP_bm_alloc( g_ATT_MTU_SIZE );
//// if ( buf != NULL )
//// {
//// uint8 *pBuf = buf;
//// uint16 len = g_ATT_MTU_SIZE;
//// // Create an L2CAP packet
//// pkt.CID = L2CAP_CID_GENERIC;
//// pkt.pPayload = buf;
//// pkt.len = len;
////
//// // Send the packet over the ATT fixed channel
//// status = L2CAP_SendData( connHandle, &pkt );
//// if ( status != SUCCESS )
//// {
//// // free the buffer
//// osal_bm_free( buf );
//// }
//// }
//
//// GATT_WriteNoRsp(connHandle, attWriteReq_t * pReq)
//
//#endif
//}
/*********************************************************************
* @fn SimpleBLECentral_ProcessEvent
*
* @brief Simple BLE Central Application Task event processor. This function
* is called to process all events for the task. Events
* include timers, messages and any other user defined events.
*
* @param task_id - The OSAL assigned task ID.
* @param events - events to process. This is a bit map and can
* contain more than one event.
*
* @return events not processed
*/
uint16 SimpleBLECentral_ProcessEvent( uint8 task_id, uint16 events )
{
VOID task_id; // OSAL required parameter that isn't used in this function
if ( events & SYS_EVENT_MSG )
{
uint8 *pMsg;
if ( (pMsg = osal_msg_receive( simpleBLETaskId )) != NULL )
{
simpleBLECentral_ProcessOSALMsg( (osal_event_hdr_t *)pMsg );
// Release the OSAL message
VOID osal_msg_deallocate( pMsg );
}
// return unprocessed events
return (events ^ SYS_EVENT_MSG);
}
if ( events & START_DEVICE_EVT )
{
// Start the Device
VOID GAPCentralRole_StartDevice( (gapCentralRoleCB_t *) &simpleBLERoleCB );
// Register with bond manager after starting device
GAPBondMgr_Register( (gapBondCBs_t *) &simpleBLEBondCB );
return ( events ^ START_DEVICE_EVT );
}
if( events & CENTRAL_INIT_DONE_EVT)
{
LOG("BLE as central Init Done \r\n");
simpleBLECentral_DiscoverDevice();
return ( events ^ CENTRAL_INIT_DONE_EVT );
}
if ( events & CENTRAL_DISCOVER_DEVDONE_EVT )
{
LOG("CENTRAL_DISCOVER_DEVDONE_EVT \n");
simpleBLECentral_LinkDevice();
return ( events ^ CENTRAL_DISCOVER_DEVDONE_EVT );
}
if ( events & START_DISCOVERY_SERVICE_EVT )
{
simpleBLECentralStartDiscoveryService( );
return ( events ^ START_DISCOVERY_SERVICE_EVT );
}
// add by zhufei.zhang
if( events & START_CHAR_DATA_TEST )
{
simpleBLECentral_CharacteristicTest();
return ( events ^ START_CHAR_DATA_TEST);
}
if ( events & SBC_CANCEL_CONN )
{
if (simpleBLEState != BLE_STATE_CONNECTED) // not connected
{
GAPCentralRole_TerminateLink( simpleBLEConnHandle );
LOG("Establish Link Time Out.\r\n");
}
return ( events ^ SBC_CANCEL_CONN );
}
if ( events & SBC_TERMINATED_CONN )
{
if (simpleBLEState == BLE_STATE_CONNECTED) // not connected
{
GAPCentralRole_TerminateLink( simpleBLEConnHandle);
}
LOG("Terminated Link .s%d d%d\r\n",simpleBLEState,simpleBLEConnHandle);
return ( events ^ SBC_TERMINATED_CONN );
}
if ( events & UPD_CHAN_MAP_EVENT )
{
//uint8 chanMap[5] = {0xFF, 0xFF, 0x77, 0x3F, 0x1F};// {0x1F, 0x37, 0x37, 0x37, 0x1F};
uint8 chanMap[5] = {0xFF, 0xFF, 0xFF, 0xFF, 0x1F};
if (simpleBLEConnHandle != GAP_CONNHANDLE_INIT)
{
HCI_LE_SetHostChanClassificationCmd(chanMap );
AT_LOG("CHAN MAP\r\n");
}
return ( events ^ UPD_CHAN_MAP_EVENT );
}
if ( events & UPD_CONN_PARAM )
{
if (simpleBLEConnHandle != GAP_CONNHANDLE_INIT)
{
connIntv=((connIntv+DEFAULT_UPDATE_MIN_CONN_INTERVAL)%DEFAULT_UPDATE_MAX_CONN_INTERVAL);
connLatency = (connTimeOut/(connIntv<<2));
AT_LOG("UPD[ %2d %2d %2d %2d]\r\n",connIntv,connIntv,connLatency,connTimeOut);
GAPCentralRole_UpdateLink(simpleBLEConnHandle,connIntv,connIntv,connLatency,connTimeOut);
//LL_PLUS_PerStatus_NotifyEvent(simpleBLETaskId, PER_STATS_EVT,600);
}
return ( events ^ UPD_CONN_PARAM );
}
if ( events & UPD_DATA_LENGTH_EVT )
{
if (simpleBLEConnHandle != GAP_CONNHANDLE_INIT)
{
HCI_LE_SetDataLengthCmd(simpleBLEConnHandle,dleTxOctets,dleTxTime );
AT_LOG("DLE[ %2d %2d ]\r\n",dleTxOctets,dleTxTime);
}
return ( events ^ UPD_DATA_LENGTH_EVT );
}
if ( events & UPD_PHY_MODE_EVT )
{
if (simpleBLEConnHandle != GAP_CONNHANDLE_INIT)
{
uint8 allPhy= 0x00;
uint8 txPhy = phyModeCtrl;
uint8 rxPhy = phyModeCtrl;
uint16 phyOption = 0x00;
HCI_LE_SetPhyMode(simpleBLEConnHandle,allPhy,txPhy,rxPhy,phyOption );
AT_LOG("PHY[ %2d %2d %2d]\r\n",allPhy,txPhy,rxPhy);
}
return ( events ^ UPD_PHY_MODE_EVT );
}
if ( events & SBC_READ_WRITE_TEST_EVT )
{
simpleBLECentral_ReadWriteNotifyTest();
return ( events ^ SBC_READ_WRITE_TEST_EVT );
}
if ( events & SLA_DATA_LENGTH_EVT )
{
if (simpleBLEConnHandle != GAP_CONNHANDLE_INIT)
{
attWriteReq_t *pReq;
pReq = osal_mem_alloc(sizeof(attWriteReq_t));
pReq->sig = FALSE;
pReq->cmd = TRUE;
pReq->handle = 0x2d;
pReq->len = 3;
rwnTestVal[0]=0x03;
rwnTestVal[1]=dleTxOctetsSlave;
rwnTestVal[2]=0;
osal_memcpy(pReq->value, rwnTestVal, pReq->len );
bStatus_t status = GATT_WriteNoRsp(simpleBLEConnHandle, pReq);
osal_mem_free(pReq);
if(status!=SUCCESS)
{
osal_start_timerEx(simpleBLETaskId, SLA_DATA_LENGTH_EVT, 20);
// AT_LOG("SLA DLE[ %2x ]\r\n",status);
}
else
{
AT_LOG("SLA DLE[ %2x %2d ]\r\n",status,dleTxOctetsSlave);
}
}
return ( events ^ SLA_DATA_LENGTH_EVT );
}
if ( events & SLA_PHY_MODE_EVT )
{
if (simpleBLEConnHandle != GAP_CONNHANDLE_INIT)
{
if(slaCtrlCmd==SLA_1M || slaCtrlCmd== SLA_2M || slaCtrlCmd==SLA_ANY)
{
uint8 allPhy= 0x00;
uint8 txPhy = phyModeCtrlSlave;
uint8 rxPhy = phyModeCtrlSlave;
// uint16 phyOption = 0x00;
attWriteReq_t *pReq;
pReq = osal_mem_alloc(sizeof(attWriteReq_t));
pReq->sig = FALSE;
pReq->cmd = TRUE;
pReq->handle = 0x2d;
pReq->len = 4;
rwnTestVal[0]=0x05;
rwnTestVal[1]=allPhy;
rwnTestVal[2]=txPhy;
rwnTestVal[3]=0;
osal_memcpy(pReq->value, rwnTestVal, pReq->len );
bStatus_t status = GATT_WriteNoRsp(simpleBLEConnHandle, pReq);
osal_mem_free(pReq);
if(status!=SUCCESS)
{
osal_start_timerEx(simpleBLETaskId, SLA_PHY_MODE_EVT, 20);
// AT_LOG("SLA PHY[ %02x ]\r\n",status);
}
else
{
AT_LOG("SLA PHY[ %02x %2d %2d %2d]\r\n",status,allPhy,txPhy,rxPhy);
}
}
else if( slaCtrlCmd==SLA_HCLK16_32KRC ||
slaCtrlCmd==SLA_HCLK16_32KXTAL ||
slaCtrlCmd==SLA_HCLK48_32KRC ||
slaCtrlCmd==SLA_HCLK48_32KXTAL ||
slaCtrlCmd==SLA_HCLK64_32KRC ||
slaCtrlCmd==SLA_HCLK64_32KXTAL)
{
uint8 slaHclk,sla32k;
//slaHclk = (slaCtrlCmd == SLA_HCLK16_32KRC || slaCtrlCmd == SLA_HCLK16_32KXTAL ) ? 0x02:0x03;//16M or 48M
//sla32k = (slaCtrlCmd == SLA_HCLK16_32KRC || slaCtrlCmd == SLA_HCLK48_32KRC ) ? 0x01:0x00;//RC or xtal
slaHclk = (slaCtrlCmd == SLA_HCLK16_32KRC || slaCtrlCmd == SLA_HCLK16_32KXTAL ) ? SYS_CLK_XTAL_16M: \
((slaCtrlCmd == SLA_HCLK48_32KRC || slaCtrlCmd == SLA_HCLK48_32KXTAL ) ? SYS_CLK_DLL_48M:SYS_CLK_DLL_64M);//16M or 48M or 64M
sla32k = ( slaCtrlCmd == SLA_HCLK16_32KRC || \
slaCtrlCmd == SLA_HCLK48_32KRC || \
slaCtrlCmd == SLA_HCLK64_32KRC) ? 0x01:0x00;//RC or xtal
attWriteReq_t *pReq;
pReq = osal_mem_alloc(sizeof(attWriteReq_t));
pReq->sig = FALSE;
pReq->cmd = TRUE;
pReq->handle = 0x2d;
pReq->len = 3;
rwnTestVal[0]=0xfc;
rwnTestVal[1]=slaHclk;
rwnTestVal[2]=sla32k;
osal_memcpy(pReq->value, rwnTestVal, pReq->len );
bStatus_t status = GATT_WriteNoRsp(simpleBLEConnHandle, pReq);
osal_mem_free(pReq);
if(status!=SUCCESS)
{
osal_start_timerEx(simpleBLETaskId, SLA_PHY_MODE_EVT, 20);
// AT_LOG("SLA PHY[ %02x ]\r\n",status);
}
else
{
AT_LOG("SLA CLK[ %02x %2d %2d]\r\n",status,sla32k,slaHclk);
}
}
else if(slaCtrlCmd==SLA_CHECK_PER)
{
attWriteReq_t *pReq;
pReq = osal_mem_alloc(sizeof(attWriteReq_t));
pReq->sig = FALSE;
pReq->cmd = TRUE;
pReq->handle = 0x2d;
pReq->len = 1;
rwnTestVal[0]=0xfd;
osal_memcpy(pReq->value, rwnTestVal, pReq->len );
bStatus_t status = GATT_WriteNoRsp(simpleBLEConnHandle, pReq);
osal_mem_free(pReq);
if(status!=SUCCESS)
{
osal_start_timerEx(simpleBLETaskId, SLA_PHY_MODE_EVT, 20);
// AT_LOG("SLA PHY[ %02x ]\r\n",status);
}
else
{
AT_LOG("SLA PER CHECK[ %02x]\r\n",status);
}
}
}
return ( events ^ SLA_PHY_MODE_EVT );
}
if ( events & SBC_PERIODIC_EVT )
{
attWriteReq_t pReq;
uint32_t T0;
pReq.sig = FALSE;
pReq.cmd = TRUE;
pReq.handle = 0x34;
pReq.len =ATT_GetCurrentMTUSize()-3;
for(int i=0;i<centralTestVectorTbl[cTVIdx].notfPktNum;i++)
{
T0 = read_current_fine_time();
osal_memcpy(pReq.value,wtnrTestVal,pReq.len );
pReq.value[0] = HI_UINT16(mstWtCnt);
pReq.value[1] = LO_UINT16(mstWtCnt);
pReq.value[2] = HI_UINT16(cTVIdx);
pReq.value[3] = LO_UINT16(cTVIdx);
pReq.value[pReq.len-2] = HI_UINT16(mstWtCnt);
pReq.value[pReq.len-1] = LO_UINT16(mstWtCnt);
bStatus_t status = GATT_WriteNoRsp(simpleBLEConnHandle, &pReq);
if(status==SUCCESS)
{
LOG("[WTNR_TX] %02x %x L%d %dus \n",status,mstWtCnt,pReq.len,read_current_fine_time()-T0);
mstWtCnt++;
centralTestVectorProcess();
}
else
{
//only log the bleTimeOut for Gatt process
if(status==0x17)
AT_LOG("[WTNR_TX ERR] %02x %x L%d %dus \n",status,mstWtCnt,pReq.len,read_current_fine_time()-T0);
break;
}
}
if( wtnrInertvl>0
&& simpleBLEConnHandle != GAP_CONNHANDLE_INIT)
{
osal_start_timerEx(simpleBLETaskId, SBC_PERIODIC_EVT,wtnrInertvl);
}
else
{
osal_stop_timerEx(simpleBLETaskId, SBC_PERIODIC_EVT);
}
uint32 uOS_size,uOS_cnt;
// osal_memory_statics(NULL, &uOS_cnt,&uOS_size);
// AT_LOG("%d %d [%04x %04x] \n",mstWtCnt, ntfTest.cnt,uOS_cnt,uOS_size);
return ( events ^ SBC_PERIODIC_EVT );
}
// Discard unknown events
return 0;
}
/*********************************************************************
* @fn simpleBLECentral_ProcessOSALMsg
*
* @brief Process an incoming task message.
*
* @param pMsg - message to process
*
* @return none
*/
static void simpleBLECentral_ProcessOSALMsg( osal_event_hdr_t *pMsg )
{
switch ( pMsg->event )
{
case GATT_MSG_EVENT:
simpleBLECentralProcessGATTMsg( (gattMsgEvent_t *) pMsg );
break;
}
}
/*********************************************************************
* @fn simpleBLECentralProcessGATTMsg
*
* @brief Process GATT messages
*
* @return none
*/
static void simpleBLECentralProcessGATTMsg( gattMsgEvent_t *pMsg )
{
if ( simpleBLEState != BLE_STATE_CONNECTED )
{
// In case a GATT message came after a connection has dropped,
// ignore the message
return;
}
if(pMsg->hdr.status==bleTimeout)
{
AT_LOG("[GATT TO] %x\n",pMsg->method);
return;
}
// LOG("simpleBLECentralProcessGATTMsg pMsg->method 0x%02X,pMsg->msg.errorRsp.reqOpcode 0x%02X\r\n",pMsg->method,pMsg->msg.errorRsp.reqOpcode);
if ( ( pMsg->method == ATT_READ_RSP ) ||
( ( pMsg->method == ATT_ERROR_RSP ) &&
( pMsg->msg.errorRsp.reqOpcode == ATT_READ_REQ ) ) )
{
if ( pMsg->method == ATT_ERROR_RSP )
{
//uint8 status = pMsg->msg.errorRsp.errCode;
LOG( "Read Error %d\r\n", pMsg->msg.errorRsp.errCode );
}
else
{
// After a successful read, display the read value
//uint8 valueRead = pMsg->msg.readRsp.value[0];
LOG( "Read rsp Len : %d\r\n", pMsg->msg.readRsp.len);
if(pMsg->msg.readRsp.len>20)
{
for(unsigned char i = 0;i < 10; i++)
{
LOG( "0x%02X,", pMsg->msg.readRsp.value[i]);
}
LOG("<--->");
for(unsigned char i = pMsg->msg.readRsp.len-10;i < pMsg->msg.readRsp.len; i++)
{
LOG( "0x%02X,", pMsg->msg.readRsp.value[i]);
}
LOG("\r\n");
}
else
{
for(unsigned char i = 0;i < pMsg->msg.readRsp.len; i++)
{
LOG( "0x%02X,", pMsg->msg.readRsp.value[i]);
}
LOG("\r\n");
}
}
// osal_start_timerEx( simpleBLETaskId, START_CHAR_DATA_TEST,100 );
// simpleBLEProcedureInProgress = FALSE;
}
else if ( ( pMsg->method == ATT_WRITE_RSP ) ||
( ( pMsg->method == ATT_ERROR_RSP ) &&
( pMsg->msg.errorRsp.reqOpcode == ATT_WRITE_REQ ) ) )
{
if ( pMsg->method == ATT_ERROR_RSP )
{
//uint8 status = pMsg->msg.errorRsp.errCode;
LOG( "Write Error: %d\r\n", pMsg->msg.errorRsp.errCode );
}
else
{
// After a succesful write, display the value that was written and increment value
LOG( "Write sent: %d\r\n", simpleBLECharVal++);
}
//osal_start_timerEx( simpleBLETaskId, START_CHAR_DATA_TEST,100 );
// simpleBLEProcedureInProgress = FALSE;
}
else if( pMsg->method == ATT_HANDLE_VALUE_NOTI ||
( ( pMsg->method == ATT_ERROR_RSP ) &&
( pMsg->msg.errorRsp.reqOpcode == ATT_HANDLE_VALUE_NOTI ) ) )
{
if ( pMsg->method == ATT_ERROR_RSP ||
pMsg->msg.handleValueNoti.len > ATT_GetCurrentMTUSize()-3 )
{
//uint8 status = pMsg->msg.errorRsp.errCode;
LOG( "Ntf Error: %d\r\n", pMsg->msg.errorRsp.errCode );
}
else
{
// LOG( "Read Ntf Len : %d\r\n", pMsg->msg.handleValueNoti.len);
//
// if(pMsg->msg.handleValueNoti.len>20)
// {
// for(unsigned char i = 0;i < 10; i++)
// {
// LOG( "0x%02X,", pMsg->msg.handleValueNoti.value[i]);
// }
//
// LOG("<--->");
// for(unsigned char i = pMsg->msg.handleValueNoti.len-10;i < pMsg->msg.handleValueNoti.len; i++)
// {
// LOG( "0x%02X,", pMsg->msg.handleValueNoti.value[i]);
// }
// }
// else
// {
// for(unsigned char i = 0;i < pMsg->msg.handleValueNoti.len; i++)
// {
// LOG( "0x%02X,", pMsg->msg.handleValueNoti.value[i]);
// }
// }
//
// LOG("\r\n");
uint8 *pCurValue = (uint8 *)pMsg->msg.handleValueNoti.value;
uint8 len = pMsg->msg.handleValueNoti.len;
uint16 cntHead=BUILD_UINT16(pCurValue[1], pCurValue[0]);
uint16 cntTail=BUILD_UINT16(pCurValue[len-1], pCurValue[len-2]);
#if(CFG_A1_SLA_TEST==1)
cntTail = cntHead;
#endif
if(cntHead!=cntTail)
{
AT_LOG("[NOTF_RX ERR] pktErr %x %x\n",cntHead,cntTail);
ntfTest.err++;
}
else
{
if(cntHead!=ntfTest.cnt)
{
if((0x00ff&&(cntHead-ntfTest.cnt))>100 )
{
AT_LOG("[NOTF_RX ERR] miss Seq %x %x\n",cntHead,ntfTest.cnt);
ntfTest.miss++;
}
}
LOG("[NOTF_RX] L%3d %x %x\n",len,cntHead,ntfTest.cnt);
ntfTest.cnt=cntHead+1;
if(g_pmCounters.ll_hci_buffer_alloc_err_cnt>0)
{
AT_LOG("[LL_ALOC ERR] %d\n",g_pmCounters.ll_hci_buffer_alloc_err_cnt);
g_pmCounters.ll_hci_buffer_alloc_err_cnt=0;
}
if(ntfTest.cnt==100)
{
if(centralTestVectorTbl[cTVIdx].notfIntv&0x80)
{
wtnrInertvl = 0;
HCI_PPLUS_ConnEventDoneNoticeCmd(simpleBLETaskId, SBC_PERIODIC_EVT);
}
else
{
wtnrInertvl = 5*centralTestVectorTbl[cTVIdx].notfIntv;
osal_start_timerEx(simpleBLETaskId, SBC_PERIODIC_EVT,wtnrInertvl);
}
}
}
}
}
else //if ( simpleBLEDiscState != BLE_DISC_STATE_IDLE )
{
simpleBLEGATTDiscoveryEvent( pMsg );
}
}
/*********************************************************************
* @fn simpleBLECentralRssiCB
*
* @brief RSSI callback.
*
* @param connHandle - connection handle
* @param rssi - RSSI
*
* @return none
*/
static void simpleBLECentralRssiCB( uint16 connHandle, int8 rssi )
{
LOG( "RSSI -dB: %d\r\n", (uint8) (-rssi) );
}
/*********************************************************************
* @fn simpleBLECentralEventCB
*
* @brief Central event callback function.
*
* @param pEvent - pointer to event structure
*
* @return none
*/
static void simpleBLECentralEventCB( gapCentralRoleEvent_t *pEvent )
{
// static int try_num = 0;
switch ( pEvent->gap.opcode )
{
case GAP_DEVICE_INIT_DONE_EVENT:
{
osal_set_event(simpleBLETaskId,CENTRAL_INIT_DONE_EVT);
}
break;
case GAP_DEVICE_INFO_EVENT:
{
// only save connectable adv
if (pEvent->deviceInfo.eventType != GAP_ADRPT_ADV_IND
&& pEvent->deviceInfo.eventType != GAP_ADRPT_ADV_DIRECT_IND
&& pEvent->deviceInfo.eventType != GAP_ADRPT_SCAN_RSP)
break;
simpleBLEAddDeviceInfo( pEvent );
// LOG( "GAP_DEVICE_INFO_EVENT\n");
}
break;
case GAP_DEVICE_DISCOVERY_EVENT:
{
// discovery complete
// initialize scan index to last device
simpleBLEScanIdx = simpleBLEScanRes;
for(unsigned i = 0; i < simpleBLEScanRes ; i++)
{
LOG( "Devices Found: %d/%d\n", i+1,simpleBLEScanRes );
if( simpleBLEDevList[i].LocalName.Type )
{
LOG("simpleBLEDevList.LocalName.Type 0x%02X, Value:",simpleBLEDevList[i].LocalName.Type);
char name[31];
osal_memcpy(name,simpleBLEDevList[i].LocalName.Value,31);
LOG(name);
LOG("\n");
}
LOG("simpleBLEDevList.Flags %d\n",simpleBLEDevList[i].Flags);
LOG("simpleBLEDevList.AddrType 0x%02X,MAC Address Value: 0x%02X,0x%02X,\
0x%02X,0x%02X,0x%02X,0x%02X\n",simpleBLEDevList[i].AddrType,\
simpleBLEDevList[i].addr[0],\
simpleBLEDevList[i].addr[1],\
simpleBLEDevList[i].addr[2],\
simpleBLEDevList[i].addr[3],\
simpleBLEDevList[i].addr[4],\
simpleBLEDevList[i].addr[5]);
LOG("simpleBLEDevList.rssi %d\n",simpleBLEDevList[i].rssi);
LOG("simpleBLEDevList.TxPower %d\n",simpleBLEDevList[i].TxPower);
if( simpleBLEDevList[i].UUID.Type )
{
LOG("simpleBLEDevList.UUID.Type %d\n",simpleBLEDevList[i].UUID.Type);
for(unsigned char j=0;j<simpleBLEDevList[i].UUID.Len;j++)
LOG("0x%02X,",simpleBLEDevList[i].UUID.Value[j]);
LOG("\n");
}
if( simpleBLEDevList[i].ConnIntervalRange.ConnMin != 0)
{
LOG("simpleBLEDevList.ConnIntervalRange.ConnMin 0x%04X,Max 0x%04X\n",\
simpleBLEDevList[i].ConnIntervalRange.ConnMin,simpleBLEDevList[i].ConnIntervalRange.ConnMax);
}
if( simpleBLEDevList[i].ManufactureData.Length )
{
LOG("simpleBLEDevList.ManufactureData Data :");
for(unsigned char k = 0; k< simpleBLEDevList[i].ManufactureData.Length;k++)
LOG("0x%02X,",simpleBLEDevList[i].ManufactureData.Value[k]);
LOG("\n");
}
LOG("\r\n\r\n");
}
osal_set_event(simpleBLETaskId,CENTRAL_DISCOVER_DEVDONE_EVT);
}
break;
case GAP_LINK_ESTABLISHED_EVENT:
{
AT_LOG("\n== GAP_LINK_ESTABLISHED_EVENT ==\r\n");
if ( pEvent->gap.hdr.status == SUCCESS )
{
simpleBLEState = BLE_STATE_CONNECTED;
simpleBLEConnHandle = pEvent->linkCmpl.connectionHandle;
// LOG("simpleBLEConnHandle 0x%04X \r\n",simpleBLEConnHandle);
// // stop cancel init timer
// osal_stop_timerEx(simpleBLETaskId, SBC_CANCEL_CONN);
HCI_PPLUS_ConnEventDoneNoticeCmd(simpleBLETaskId, NULL);
//-------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------
//
AT_LOG("[TVEC] #%d mtu%d dle%d %d phy%d %d conn %d %d notf %d %d cnt%d\n", cTVIdx,
centralTestVectorTbl[cTVIdx].mtu,
centralTestVectorTbl[cTVIdx].pduLen,centralTestVectorTbl[cTVIdx].pduLenSla,
centralTestVectorTbl[cTVIdx].phyMode,centralTestVectorTbl[cTVIdx].phyModeSla,
centralTestVectorTbl[cTVIdx].connIntv,centralTestVectorTbl[cTVIdx].latency,
centralTestVectorTbl[cTVIdx].notfIntv,centralTestVectorTbl[cTVIdx].notfPktNum,
centralTestVectorTbl[cTVIdx].testCnt);
//----------------------------------------------------------------
//for Char Read/Write Notify Test
mstWtCnt = 0;
rwnTestCnt = 0;
ntfTest.isDone = 0;
ntfTest.cnt = 0;
wtnrInertvl = 0;
//--------------------------------------------------------------------------------------
//MTU Size Exchange
if(centralTestVectorTbl[cTVIdx].mtu>23)
{
ATT_SetMTUSizeMax(centralTestVectorTbl[cTVIdx].mtu);
attExchangeMTUReq_t pReq;
pReq.clientRxMTU = centralTestVectorTbl[cTVIdx].mtu;
uint8 status =GATT_ExchangeMTU(simpleBLEConnHandle,&pReq, simpleBLETaskId);
LOG( "[MTU Req]%d %d\n",status,pReq.clientRxMTU);
}
else
{
ATT_SetMTUSizeMax(23);
}
//-------------------------------------------------------------------------------------
// DLE
llInitFeatureSetDLE(FALSE);
if(centralTestVectorTbl[cTVIdx].pduLen>27)
{
llInitFeatureSetDLE(TRUE);
dleTxOctets = centralTestVectorTbl[cTVIdx].pduLen;
dleTxTime = (dleTxOctets+14)<<3;
osal_start_timerEx( simpleBLETaskId, UPD_DATA_LENGTH_EVT , 100 );
}
if(centralTestVectorTbl[cTVIdx].pduLenSla>27)
{
llInitFeatureSetDLE(TRUE);
dleTxOctetsSlave = centralTestVectorTbl[cTVIdx].pduLenSla;
dleTxTimeSlave = (dleTxOctetsSlave+14)<<3;
osal_start_timerEx( simpleBLETaskId, SLA_DATA_LENGTH_EVT , 200 );
}
//-------------------------------------------------------------------------------------
//phy update
HCI_LE_SetDefaultPhyMode(0,0x03,0x01,0x01);
llInitFeatureSet2MPHY(FALSE);
if(centralTestVectorTbl[cTVIdx].phyMode==0x02)
{
llInitFeatureSet2MPHY(TRUE);
HCI_LE_SetDefaultPhyMode(0,0x00,0x03,0x03);
phyModeCtrl = centralTestVectorTbl[cTVIdx].phyMode;
osal_start_timerEx( simpleBLETaskId, UPD_PHY_MODE_EVT , 300 );
}
if(centralTestVectorTbl[cTVIdx].phyModeSla>0)
{
llInitFeatureSet2MPHY(TRUE);
HCI_LE_SetDefaultPhyMode(0,0x00,0x03,0x03);
phyModeCtrlSlave = centralTestVectorTbl[cTVIdx].phyModeSla;
osal_start_timerEx( simpleBLETaskId, SLA_PHY_MODE_EVT , 400 );
}
HCI_LE_ReadRemoteUsedFeaturesCmd(simpleBLEConnHandle);
HCI_ReadRemoteVersionInfoCmd(simpleBLEConnHandle);
osal_start_timerEx( simpleBLETaskId, START_DISCOVERY_SERVICE_EVT, \
DEFAULT_SVC_DISCOVERY_DELAY );
//osal_start_timerEx( simpleBLETaskId, UPD_DATA_LENGTH_EVT , 50 * 1000 );
// osal_start_timerEx( simpleBLETaskId, UPD_CHAN_MAP_EVENT , 30 * 1000 );
// osal_start_timerEx( simpleBLETaskId, UPD_CONN_PARAM , 40 * 1000 );
}
else if(pEvent->gap.hdr.status==LL_STATUS_WARNING_WAITING_LLIRQ)
{
AT_LOG( "[WAITING LL_IRQ]. " );
AT_LOG( "Reason: 0x%02x\r\n", pEvent->gap.hdr.status);
GAPCentralRole_EstablishLink( DEFAULT_LINK_HIGH_DUTY_CYCLE,\
DEFAULT_LINK_WHITE_LIST,\
simpleBlePeerTarget.addrType, \
simpleBlePeerTarget.addr );
}
else
{
simpleBLEState = BLE_STATE_IDLE;
simpleBLEConnHandle = GAP_CONNHANDLE_INIT;
simpleBLEDiscState = BLE_DISC_STATE_IDLE;
osal_start_timerEx( simpleBLETaskId, CENTRAL_INIT_DONE_EVT, \
1000 );
}
// osal_start_timerEx(simpleBLETaskId, SBC_SEND_RAW_DATA, 40* 1000);
// osal_start_reload_timer(simpleBLETaskId, SBC_SEND_RAW_DATA, 8);
}
break;
case GAP_LINK_TERMINATED_EVENT:
{
simpleBLEState = BLE_STATE_IDLE;
simpleBLEConnHandle = GAP_CONNHANDLE_INIT;
simpleBLEDiscState = BLE_DISC_STATE_IDLE;
uint32 uOS_size,uOS_cnt;
// osal_memory_statics(NULL, &uOS_cnt,&uOS_size);
AT_LOG("[TVEC] %08x DISC.R[0x%2x][%04x %04x]\n",getMcuPrecisionCount(),pEvent->linkTerminate.reason,uOS_cnt,uOS_size);
check_PerStatsProcess();
AT_LOG("[PMCNT] rdErr %d rstErr %d trgErr %d\n",g_pmCounters.ll_rfifo_read_err,g_pmCounters.ll_rfifo_rst_err,g_pmCounters.ll_trigger_err);
// Terminate Link , memset SimpleGattScanServer structure
osal_memset(&SimpleClientInfo,0,sizeof(SimpleGattScanServer));
osal_memset(simpleBLEDevList,0,sizeof(SimpleClientADV_ScanData)*DEFAULT_MAX_SCAN_RES);
osal_start_timerEx( simpleBLETaskId, CENTRAL_INIT_DONE_EVT, \
10*1000 );
}
break;
case GAP_LINK_PARAM_UPDATE_EVENT:
{
LOG( "Server Request for Param Update\r\n");
}
break;
default:
LOG(" simpleBLECentralEventCB --> pEvent->gap.opcode: 0x%02X\r\n", pEvent->gap.opcode);
break;
}
}
/*********************************************************************
* @fn pairStateCB
*
* @brief Pairing state callback.
*
* @return none
*/
static void simpleBLECentralPairStateCB( uint16 connHandle, uint8 state, uint8 status )
{
LOG("simpleBLECentralPairStateCB in param state 0x%02X,status 0x%02X\r\n",state,status);
if ( state == GAPBOND_PAIRING_STATE_STARTED )
{
LOG( "Pairing started\n" );
}
else if ( state == GAPBOND_PAIRING_STATE_COMPLETE )
{
if ( status == SUCCESS )
{
LOG( "Pairing success\n" );
}
else
{
LOG( "Pairing fail\n" );
}
}
else if ( state == GAPBOND_PAIRING_STATE_BONDED )
{
if ( status == SUCCESS )
{
LOG( "Bonding success\n" );
}
}
}
/*********************************************************************
* @fn simpleBLECentralPasscodeCB
*
* @brief Passcode callback.
*
* @return none
*/
static void simpleBLECentralPasscodeCB( uint8 *deviceAddr, uint16 connectionHandle,
uint8 uiInputs, uint8 uiOutputs )
{
LOG("simpleBLECentralPasscodeCB\r\n");
#if (HAL_LCD == TRUE)
uint32 passcode;
uint8 str[7];
// Create random passcode
LL_Rand( ((uint8 *) &passcode), sizeof( uint32 ));
passcode %= 1000000;
// Display passcode to user
if ( uiOutputs != 0 )
{
LCD_WRITE_STRING( "Passcode:", HAL_LCD_LINE_1 );
LCD_WRITE_STRING( (char *) _ltoa(passcode, str, 10), HAL_LCD_LINE_2 );
}
// Send passcode response
GAPBondMgr_PasscodeRsp( connectionHandle, SUCCESS, passcode );
#endif
}
/*********************************************************************
* @fn simpleBLECentralStartDiscoveryService
*
* @brief Start service discovery.
*
* @return none
*/
static void simpleBLECentralStartDiscoveryService( void )
{
LOG("==>simpleBLECentralStartDiscoveryService\r\n");
// add by zhufei.zhang 2018.10.25
// before start discovery , memset the variable
osal_memset(&SimpleClientInfo,0,sizeof(SimpleGattScanServer));
uint8 uuid[ATT_BT_UUID_SIZE] = { LO_UINT16(SIMPLEPROFILE_SERV_UUID),
HI_UINT16(SIMPLEPROFILE_SERV_UUID) };
simpleBLEDiscState = BLE_DISC_STATE_SVC;
// Discovery simple BLE service
GATT_DiscAllPrimaryServices(simpleBLEConnHandle,simpleBLETaskId);
}
/*********************************************************************
* @fn simpleBLEGATTDiscoveryEvent
*
* @brief Process GATT discovery event
*
* @return none
*/
static void simpleBLEGATTDiscoveryEvent( gattMsgEvent_t *pMsg )
{
attReadByTypeReq_t req;
if ( simpleBLEDiscState == BLE_DISC_STATE_SVC )
{
// add by zhufei.zhang 2018/10/24
if( ( pMsg->method == ATT_READ_BY_GRP_TYPE_RSP) &&
( pMsg->msg.readByGrpTypeRsp.numGrps > 0 ) )
{
for(unsigned char i = 0 ; i < pMsg->msg.readByGrpTypeRsp.numGrps;i++)
{
// Current Attribute LEN
SimpleClientInfo.ServerGroupService[SimpleClientInfo.PrimaryServiceCnt].Attribute_Data_Len = \
pMsg->msg.readByGrpTypeRsp.len;
// Current Attribute Handle
SimpleClientInfo.ServerGroupService[SimpleClientInfo.PrimaryServiceCnt].Attribute_StartHandle = \
BUILD_UINT16( pMsg->msg.readByGrpTypeRsp.dataList[pMsg->msg.readByGrpTypeRsp.len * i], \
pMsg->msg.readByGrpTypeRsp.dataList[pMsg->msg.readByGrpTypeRsp.len * i + 1]);
// Current Attribute End Group Handle
SimpleClientInfo.ServerGroupService[SimpleClientInfo.PrimaryServiceCnt].End_Group_Handle = \
BUILD_UINT16( pMsg->msg.readByGrpTypeRsp.dataList[pMsg->msg.readByGrpTypeRsp.len * i+2], \
pMsg->msg.readByGrpTypeRsp.dataList[pMsg->msg.readByGrpTypeRsp.len * i + 3]);
// Caculate Primary Service UUID Length
SimpleClientInfo.ServerGroupService[SimpleClientInfo.PrimaryServiceCnt].UUID_Len = \
pMsg->msg.readByGrpTypeRsp.len - 4;
// Copy UUID
osal_memcpy(SimpleClientInfo.ServerGroupService[SimpleClientInfo.PrimaryServiceCnt].UUID,\
&(pMsg->msg.readByGrpTypeRsp.dataList[pMsg->msg.readByGrpTypeRsp.len * i + 4]),\
SimpleClientInfo.ServerGroupService[SimpleClientInfo.PrimaryServiceCnt].UUID_Len);
// Primary Service Count Index ++
SimpleClientInfo.PrimaryServiceCnt++;
}
}
else if ( ( pMsg->method == ATT_READ_BY_GRP_TYPE_RSP &&
pMsg->hdr.status == bleProcedureComplete ) ||
( pMsg->method == ATT_ERROR_RSP ) )
{
// Primary Service Discover OK , Prepare Discover Characteristic
simpleBLEDiscState = BLE_DISC_STATE_CHAR;
if( SimpleClientInfo.PrimaryServiceCnt > 0 )
{
// Characteristic Find Index Init
SimpleClientInfo.PrimaryCharacIndex = 0;
SimpleClientInfo.CharacFindIndex = 0;
GATT_DiscAllChars( simpleBLEConnHandle,
SimpleClientInfo.ServerGroupService[SimpleClientInfo.PrimaryCharacIndex].Attribute_StartHandle,\
SimpleClientInfo.ServerGroupService[SimpleClientInfo.PrimaryCharacIndex].End_Group_Handle,
simpleBLETaskId );
}
}
}
else if ( simpleBLEDiscState == BLE_DISC_STATE_CHAR )
{
// Characteristic found, store handle
if ( pMsg->method == ATT_READ_BY_TYPE_RSP &&
pMsg->msg.readByTypeRsp.numPairs > 0 )
{
// Iterate through all three pairs found.
for(unsigned char i = 0; i < pMsg->msg.readByTypeRsp.numPairs ; i++)
{
// Extract the starting handle, ending handle, and UUID of the current characteristic.
// characteristic Handle
SimpleClientInfo.ServerGroupService[SimpleClientInfo.PrimaryCharacIndex].Characteristic[SimpleClientInfo.CharacFindIndex].charStartHandle = \
BUILD_UINT16( pMsg->msg.readByTypeRsp.dataList[pMsg->msg.readByTypeRsp.len * i], \
pMsg->msg.readByTypeRsp.dataList[pMsg->msg.readByTypeRsp.len * i + 1]);
// Characteristic Properties
SimpleClientInfo.ServerGroupService[SimpleClientInfo.PrimaryCharacIndex].Characteristic[SimpleClientInfo.CharacFindIndex].Properties = \
pMsg->msg.readByTypeRsp.dataList[pMsg->msg.readByTypeRsp.len * i + 2];
// Characteristic UUID
SimpleClientInfo.ServerGroupService[SimpleClientInfo.PrimaryCharacIndex].Characteristic[SimpleClientInfo.CharacFindIndex].charUuid = \
BUILD_UINT16( pMsg->msg.readByTypeRsp.dataList[pMsg->msg.readByTypeRsp.len * i + 5], \
pMsg->msg.readByTypeRsp.dataList[pMsg->msg.readByTypeRsp.len * i + 6]);
SimpleClientInfo.CharacFindIndex++;
}
}
else if(( pMsg->method == ATT_READ_BY_TYPE_RSP &&
pMsg->hdr.status == bleProcedureComplete ) ||
( pMsg->method == ATT_ERROR_RSP ))
{
SimpleClientInfo.ServerGroupService[SimpleClientInfo.PrimaryCharacIndex].CharacNum = \
SimpleClientInfo.CharacFindIndex;
SimpleClientInfo.CharacFindIndex = 0;
LOG(" Service 0x%02X%02X Characteristic Find Success \r\n",\
SimpleClientInfo.ServerGroupService[SimpleClientInfo.PrimaryCharacIndex].UUID[1],\
SimpleClientInfo.ServerGroupService[SimpleClientInfo.PrimaryCharacIndex].UUID[0]);
for(unsigned char i = 0; i< SimpleClientInfo.ServerGroupService[SimpleClientInfo.PrimaryCharacIndex].CharacNum; i++)
{
LOG("Chars found handle is is:0x%04X,Properties is: 0x%02X,uuid is:0x%04X\r\n", \
SimpleClientInfo.ServerGroupService[SimpleClientInfo.PrimaryCharacIndex].Characteristic[i].charStartHandle,\
SimpleClientInfo.ServerGroupService[SimpleClientInfo.PrimaryCharacIndex].Characteristic[i].Properties,\
SimpleClientInfo.ServerGroupService[SimpleClientInfo.PrimaryCharacIndex].Characteristic[i].charUuid);
}
if(++SimpleClientInfo.PrimaryCharacIndex < SimpleClientInfo.PrimaryServiceCnt)
{
GATT_DiscAllChars( simpleBLEConnHandle,
SimpleClientInfo.ServerGroupService[SimpleClientInfo.PrimaryCharacIndex].Attribute_StartHandle,\
SimpleClientInfo.ServerGroupService[SimpleClientInfo.PrimaryCharacIndex].End_Group_Handle,
simpleBLETaskId );
}
else
{
LOG("All Characteristic Discover Success \r\n");
simpleBLEDiscState = BLE_DISC_STATE_IDLE;
//osal_start_timerEx( simpleBLETaskId, START_CHAR_DATA_TEST,100 );
osal_start_timerEx( simpleBLETaskId, SBC_READ_WRITE_TEST_EVT,100 );
}
}
}
else
{
LOG("simpleBLEDiscState = BLE_DISC_STATE_IDLE \r\n");
}
}
/*********************************************************************
* @fn simpleBLECentral_CharacteristicTest
*
* @brief Send Data To BLE Server
*
* @return none
*/
static void simpleBLECentral_CharacteristicTest(void)
{
attWriteReq_t *pReq;
attReadReq_t *pReqread;
uint8 Val[20] = {0x00,0xC8,0x14};
static uint8_t PrimaryServiceCnt = 0;
static uint8_t PrimaryCharacIndex = 0;
static uint8_t Properties = 0;
static uint8_t SameCharacBusy = FALSE;
if( PrimaryServiceCnt >= SimpleClientInfo.PrimaryServiceCnt )
return;
if( !SameCharacBusy )
{
if( PrimaryServiceCnt < SimpleClientInfo.PrimaryServiceCnt )
{
if( PrimaryCharacIndex < SimpleClientInfo.ServerGroupService[PrimaryServiceCnt].CharacNum )
{
Properties = SimpleClientInfo.ServerGroupService[PrimaryServiceCnt].Characteristic[PrimaryCharacIndex].Properties;
// LOG("Should Update Properties Value \r\n");
SameCharacBusy = TRUE;
}
else
{
PrimaryServiceCnt++;
PrimaryCharacIndex = 0;
osal_start_timerEx( simpleBLETaskId, START_CHAR_DATA_TEST,100 );
return;
}
}
}
LOG("Service UUID : 0x%02X%02X, Characteristic UUID:0x%04X ,PrimaryServiceCnt %d,PrimaryCharacIndex %d,Properties 0x%02X\r\n",\
SimpleClientInfo.ServerGroupService[PrimaryServiceCnt].UUID[1],\
SimpleClientInfo.ServerGroupService[PrimaryServiceCnt].UUID[0],\
SimpleClientInfo.ServerGroupService[PrimaryServiceCnt].Characteristic[PrimaryCharacIndex].charUuid,PrimaryServiceCnt,PrimaryCharacIndex,Properties);
if( ( Properties & GATT_PROP_BCAST ) || \
( Properties & GATT_PROP_WRITE_NO_RSP ) || \
( Properties & GATT_PROP_INDICATE ) || \
( Properties & GATT_PROP_AUTHEN ) || \
( Properties & GATT_PROP_EXTENDED ))
{
LOG("Come Here \r\n");
Properties &= ~( GATT_PROP_BCAST | GATT_PROP_WRITE_NO_RSP | GATT_PROP_INDICATE | GATT_PROP_AUTHEN | \
GATT_PROP_EXTENDED);
osal_start_timerEx( simpleBLETaskId, START_CHAR_DATA_TEST,100 );
}
else if( Properties & GATT_PROP_READ )
{
Properties &= ~GATT_PROP_READ;
pReqread = osal_mem_alloc(sizeof(attReadReq_t));
pReqread->handle = SimpleClientInfo.ServerGroupService[PrimaryServiceCnt].\
Characteristic[PrimaryCharacIndex].charStartHandle + Characteristic_ValueIndex;
bStatus_t status = GATT_ReadCharValue( simpleBLEConnHandle, pReqread, simpleBLETaskId );
if(status == SUCCESS)
{
LOG("GATT_ReadCharDesc success \r\n");
}
else
{
LOG("GATT_ReadCharDesc ERROR %d\r\n",status);
}
osal_mem_free(pReqread);
}
else if( Properties & GATT_PROP_WRITE )
{
Properties &= ~GATT_PROP_WRITE;
pReq = osal_mem_alloc(sizeof(attWriteReq_t));
osal_memcpy(pReq->value, Val, 3);
pReq->sig = 0;
pReq->cmd = 0;
pReq->handle = SimpleClientInfo.ServerGroupService[PrimaryServiceCnt].\
Characteristic[PrimaryCharacIndex].charStartHandle + Characteristic_ValueIndex;
if( PrimaryServiceCnt == 3 && PrimaryCharacIndex == 0 )
pReq->len = 16;
else if( PrimaryServiceCnt == 3 && (PrimaryCharacIndex > 0 && PrimaryCharacIndex < 3) )
pReq->len = 2;
else if( PrimaryServiceCnt == 3 && PrimaryCharacIndex == 3 )
pReq->len = 1;
else
pReq->len = 3;
bStatus_t status = GATT_WriteCharValue(simpleBLEConnHandle, pReq, simpleBLETaskId);
if(status == SUCCESS)
{
LOG("GATT_WriteCharValue success \r\n");
}
else
{
LOG("GATT_WriteCharValue ERROR %d\r\n",status);
}
osal_mem_free(pReq);
}
else if( Properties & GATT_PROP_NOTIFY )
{
Properties &= ~GATT_PROP_NOTIFY;
pReq = osal_mem_alloc(sizeof(attWriteReq_t));
pReq->sig = 0;
pReq->cmd = 0;
pReq->handle = SimpleClientInfo.ServerGroupService[PrimaryServiceCnt].\
Characteristic[PrimaryCharacIndex].charStartHandle + Characteristic_NotifyIndex;
pReq->len = 2;
pReq->value[0] = (unsigned char)(GATT_CLIENT_CFG_NOTIFY);
pReq->value[1] = (unsigned char)(GATT_CLIENT_CFG_NOTIFY >> 8);
bStatus_t status = GATT_WriteCharValue(simpleBLEConnHandle, pReq, simpleBLETaskId);
if(status == SUCCESS)
{
LOG("GATT_WriteCharValue Notify success \r\n");
}
else
{
LOG("GATT_WriteCharValue Notify ERROR %d\r\n",status);
}
osal_mem_free(pReq);
}
else
{
PrimaryCharacIndex++;
SameCharacBusy = FALSE;
osal_start_timerEx( simpleBLETaskId, START_CHAR_DATA_TEST,100 );
}
}
/*********************************************************************
* @fn simpleBLEFindSvcUuid
*
* @brief Find a given UUID in an advertiser's service UUID list.
*
* @return TRUE if service UUID found
*/
static bool simpleBLEFindSvcUuid( uint16 uuid, uint8 *pData, uint8 dataLen )
{
uint8 adLen;
uint8 adType;
uint8 *pEnd;
LOG("simpleBLEFindSvcUuid\r\n");
pEnd = pData + dataLen - 1;
// While end of data not reached
while ( pData < pEnd )
{
// Get length of next AD item
adLen = *pData++;
LOG("==>adLen = %d ", adLen);
if ( adLen > 0 )
{
adType = *pData;
LOG("adType = %d ", adType);
// If AD type is for 16-bit service UUID
if ( adType == GAP_ADTYPE_16BIT_MORE || adType == GAP_ADTYPE_16BIT_COMPLETE )
{
pData++;
adLen--;
// For each UUID in list
while ( adLen >= 2 && pData < pEnd )
{
// Check for match
if ( pData[0] == LO_UINT16(uuid) && pData[1] == HI_UINT16(uuid) )
{
// Match found
return TRUE;
}
// Go to next
pData += 2;
adLen -= 2;
}
// Handle possible erroneous extra byte in UUID list
if ( adLen == 1 )
{
pData++;
}
}
else
{
// Go to next item
pData += adLen;
}
}
LOG("\r\n");
}
// Match not found
return FALSE;
}
/*********************************************************************
* @fn simpleBLEAddDeviceInfo
*
* @brief Add a device to the device discovery result list
*
* @return none
*/
static void simpleBLEAddDeviceInfo( gapCentralRoleEvent_t *pEvent )
{
const uint8_t ZeroBuf[B_ADDR_LEN]={0,0,0,0,0,0};
uint8_t Addr_Index=0;
if( ( pEvent->deviceInfo.opcode != GAP_DEVICE_INFO_EVENT ) || \
( simpleBLEScanRes >= DEFAULT_MAX_SCAN_RES))
return;
// retrieve the ADDR Index
for(uint8_t i=0;i < DEFAULT_MAX_SCAN_RES;i++)
{
if( ( osal_memcmp( simpleBLEDevList[i].addr, ZeroBuf , B_ADDR_LEN ) ) || \
( osal_memcmp( pEvent->deviceInfo.addr, simpleBLEDevList[i].addr , B_ADDR_LEN )))
{
Addr_Index = i;
break;
}
}
if( Addr_Index < simpleBLEScanRes)
{
// update simpleBLEDevList[Addr_Index]
simpleBLEDevList[Addr_Index].rssi = pEvent->deviceInfo.rssi;
if( !simpleBLEDevList[Addr_Index].RSP_ReadFlag )
{
if( pEvent->deviceInfo.eventType == GAP_ADRPT_SCAN_RSP )
{
// Analysis Scan RSP data
simpleBLEAnalysisADVDATA(Addr_Index, &(pEvent->deviceInfo));
simpleBLEDevList[Addr_Index].RSP_ReadFlag = TRUE;
}
}
}
else
{
// first commit simpleBLEDevList[Addr_Index]
simpleBLEDevList[Addr_Index].rssi = pEvent->deviceInfo.rssi;
// Mac Address Type
simpleBLEDevList[Addr_Index].AddrType = pEvent->deviceInfo.addrType;
// Mac Address
osal_memcpy( simpleBLEDevList[Addr_Index].addr, pEvent->deviceInfo.addr, B_ADDR_LEN );
if( pEvent->deviceInfo.eventType == GAP_ADRPT_ADV_IND )
{
// Analysis Adv data
simpleBLEAnalysisADVDATA(Addr_Index, &(pEvent->deviceInfo));
}
// Increment scan result count
simpleBLEScanRes++;
}
}
/*********************************************************************
* @fn simpleBLEAnalysisADVDATA
*
* @brief Analysis received Advertising data and SCAN RSP Data
*
* @return none
*/
static void simpleBLEAnalysisADVDATA(uint8 Index,gapDeviceInfoEvent_t *pData)
{
int8 DataLength;
int8 New_ADStructIndex = 0;
int8 AD_Length = 0;
uint8_t AD_Type;
DataLength = pData->dataLen;
while(DataLength)
{
New_ADStructIndex += AD_Length;
// DATA FORMAT : Length + AD Type + AD Data
AD_Length = pData->pEvtData[pData->dataLen - DataLength];
AD_Type = pData->pEvtData[New_ADStructIndex+1];
if(AD_Length<2 || AD_Length>0x1f)
{
AT_LOG("[AD_TYPE] ERR %02x %02x\n",AD_Type,AD_Length);
break;
}
switch(AD_Type)
{
case GAP_ADTYPE_FLAGS:
simpleBLEDevList[Index].Flags = pData->pEvtData[New_ADStructIndex+2];
break;
case GAP_ADTYPE_16BIT_MORE:
case GAP_ADTYPE_16BIT_COMPLETE:
case GAP_ADTYPE_32BIT_MORE:
case GAP_ADTYPE_32BIT_COMPLETE:
case GAP_ADTYPE_128BIT_MORE:
case GAP_ADTYPE_128BIT_COMPLETE:
simpleBLEDevList[Index].UUID.Type = AD_Type;
while( AD_Length - 1 - simpleBLEDevList[Index].UUID.Len)
{
if( ( AD_Type == GAP_ADTYPE_16BIT_MORE) || ( AD_Type == GAP_ADTYPE_16BIT_COMPLETE))
{
simpleBLEDevList[Index].UUID.Len += ATT_BT_UUID_SIZE;
}
else if( ( AD_Type == GAP_ADTYPE_32BIT_MORE) || ( AD_Type == GAP_ADTYPE_32BIT_COMPLETE))
{
simpleBLEDevList[Index].UUID.Len += ATT_BT_UUID_SIZE<<1;
}
else
{
simpleBLEDevList[Index].UUID.Len += ATT_UUID_SIZE;
}
if(AD_Length< 1 + simpleBLEDevList[Index].UUID.Len)
{
AT_LOG("[AD_TYPE] ERR %02x %02x\n",AD_Type,AD_Length);
break;
}
}
osal_memcpy( simpleBLEDevList[Index].UUID.Value,\
&(pData->pEvtData[New_ADStructIndex+2]),\
simpleBLEDevList[Index].UUID.Len);
break;
case GAP_ADTYPE_LOCAL_NAME_SHORT:
case GAP_ADTYPE_LOCAL_NAME_COMPLETE:
simpleBLEDevList[Index].LocalName.Type = AD_Type;
simpleBLEDevList[Index].LocalName.Length = AD_Length - 2;
osal_memcpy( simpleBLEDevList[Index].LocalName.Value,&(pData->pEvtData[New_ADStructIndex+2]),\
simpleBLEDevList[Index].LocalName.Length);
break;
case GAP_ADTYPE_POWER_LEVEL:
simpleBLEDevList[Index].TxPower = pData->pEvtData[New_ADStructIndex+2];
break;
case GAP_ADTYPE_OOB_CLASS_OF_DEVICE:
case GAP_ADTYPE_OOB_SIMPLE_PAIRING_HASHC:
case GAP_ADTYPE_OOB_SIMPLE_PAIRING_RANDR:
break;
case GAP_ADTYPE_SM_TK:
break;
case GAP_ADTYPE_SM_OOB_FLAG:
break;
case GAP_ADTYPE_SLAVE_CONN_INTERVAL_RANGE:
simpleBLEDevList[Index].ConnIntervalRange.ConnMin = BUILD_UINT16(pData->pEvtData[New_ADStructIndex+2],\
pData->pEvtData[New_ADStructIndex+3]);
simpleBLEDevList[Index].ConnIntervalRange.ConnMax = BUILD_UINT16(pData->pEvtData[New_ADStructIndex+4],\
pData->pEvtData[New_ADStructIndex+5]);
break;
case GAP_ADTYPE_SIGNED_DATA:
break;
case GAP_ADTYPE_SERVICES_LIST_16BIT:
case GAP_ADTYPE_SERVICES_LIST_128BIT:
simpleBLEDevList[Index].ServiceSolicitation.Type = AD_Type;
if( AD_Type == GAP_ADTYPE_SERVICES_LIST_16BIT)
simpleBLEDevList[Index].ServiceSolicitation.Len = ATT_BT_UUID_SIZE;
else
simpleBLEDevList[Index].ServiceSolicitation.Len = ATT_UUID_SIZE;
osal_memcpy( simpleBLEDevList[Index].ServiceSolicitation.Value,\
&(pData->pEvtData[New_ADStructIndex+2]),\
simpleBLEDevList[Index].ServiceSolicitation.Len);
break;
case GAP_ADTYPE_SERVICE_DATA:
break;
case GAP_ADTYPE_APPEARANCE:
break;
case GAP_ADTYPE_MANUFACTURER_SPECIFIC:
simpleBLEDevList[Index].ManufactureData.Length = AD_Length - 1;
osal_memcpy(simpleBLEDevList[Index].ManufactureData.Value,&(pData->pEvtData[New_ADStructIndex+2]),\
simpleBLEDevList[Index].ManufactureData.Length);
break;
default:
break;
}
AD_Length++;
DataLength -= AD_Length;
}
}
/*********************************************************************
* @fn bdAddr2Str
*
* @brief Convert Bluetooth address to string
*
* @return none
*/
char *bdAddr2Str( uint8 *pAddr )
{
uint8 i;
char hex[] = "0123456789ABCDEF";
static char str[B_ADDR_STR_LEN];
char *pStr = str;
// *pStr++ = '0';
// *pStr++ = 'x';
// Start from end of addr
pAddr += B_ADDR_LEN;
for ( i = B_ADDR_LEN; i > 0; i-- )
{
*pStr++ = hex[*--pAddr >> 4];
*pStr++ = hex[*pAddr & 0x0F];
}
*pStr = 0;
return str;
}
uint8_t simpleBLECentral_AdvDataFilterCBack(void)
{
uint8_t* advData;
advData=LL_PLUS_GetAdvDataExtendData();
if(advData[11]==0x4c && advData[12]==0x00)
{
advDataFilterCnt++;
LL_PLUS_SetScanRequestData(1, &advDataFilterCnt);
return 1;
}
else
{
return 0;
}
}
/*********************************************************************
* @fn simpleBLECentral_HandleKeys
*
* @brief Handles all key events for this device.
*
* @param shift - true if in shift/alt.
* @param keys - bit field for key events. Valid entries:
* HAL_KEY_SW_2
* HAL_KEY_SW_1
*
* @return none
*/
//uint8 gStatus;
//static void simpleBLECentral_HandleKeys( uint8 shift, uint8 keys )
//{
// (void)shift; // Intentionally unreferenced parameter
// if ( keys & HAL_KEY_UP )
// {
// // Start or stop discovery
// if ( simpleBLEState != BLE_STATE_CONNECTED )
// {
// if ( !simpleBLEScanning )
// {
// simpleBLEScanning = TRUE;
// simpleBLEScanRes = 0;
//
// LCD_WRITE_STRING( "Discovering...", HAL_LCD_LINE_1 );
// LCD_WRITE_STRING( "", HAL_LCD_LINE_2 );
//
// GAPCentralRole_StartDiscovery( DEFAULT_DISCOVERY_MODE,
// DEFAULT_DISCOVERY_ACTIVE_SCAN,
// DEFAULT_DISCOVERY_WHITE_LIST );
// }
// else
// {
// GAPCentralRole_CancelDiscovery();
// }
// }
// else if ( simpleBLEState == BLE_STATE_CONNECTED &&
// simpleBLECharHdl != 0 &&
// simpleBLEProcedureInProgress == FALSE )
// {
// uint8 status;
//
// // Do a read or write as long as no other read or write is in progress
// if ( simpleBLEDoWrite )
// {
// // Do a write
// attWriteReq_t req;
//
// req.handle = simpleBLECharHdl;
// req.len = 1;
// req.value[0] = simpleBLECharVal;
// req.sig = 0;
// req.cmd = 0;
// status = GATT_WriteCharValue( simpleBLEConnHandle, &req, simpleBLETaskId );
// }
// else
// {
// // Do a read
// attReadReq_t req;
//
// req.handle = simpleBLECharHdl;
// status = GATT_ReadCharValue( simpleBLEConnHandle, &req, simpleBLETaskId );
// }
//
// if ( status == SUCCESS )
// {
// simpleBLEProcedureInProgress = TRUE;
// simpleBLEDoWrite = !simpleBLEDoWrite;
// }
// }
// }
// if ( keys & HAL_KEY_LEFT )
// {
// // Display discovery results
// if ( !simpleBLEScanning && simpleBLEScanRes > 0 )
// {
// // Increment index of current result (with wraparound)
// simpleBLEScanIdx++;
// if ( simpleBLEScanIdx >= simpleBLEScanRes )
// {
// simpleBLEScanIdx = 0;
// }
//
// LCD_WRITE_STRING_VALUE( "Device", simpleBLEScanIdx + 1,
// 10, HAL_LCD_LINE_1 );
// LCD_WRITE_STRING( bdAddr2Str( simpleBLEDevList[simpleBLEScanIdx].addr ),
// HAL_LCD_LINE_2 );
// }
// }
// if ( keys & HAL_KEY_RIGHT )
// {
// // Connection update
// if ( simpleBLEState == BLE_STATE_CONNECTED )
// {
// GAPCentralRole_UpdateLink( simpleBLEConnHandle,
// DEFAULT_UPDATE_MIN_CONN_INTERVAL,
// DEFAULT_UPDATE_MAX_CONN_INTERVAL,
// DEFAULT_UPDATE_SLAVE_LATENCY,
// DEFAULT_UPDATE_CONN_TIMEOUT );
// }
// }
//
static void simpleBLECentral_DiscoverDevice(void)
{
// led_disp(LED_ALL_OFF);
// led_disp(LED_RED);
simpleBLEScanRes = simpleBLEScanIdx = 0;
osal_memset(simpleBLEDevList,0,sizeof(SimpleClientADV_ScanData)*DEFAULT_MAX_SCAN_RES);
// osal_memset(ll_buf.rx_adv_desc,0,sizeof(llLinkBuf_t));
// hal_gpio_pull_set(GPIO_P15,PULL_DOWN);
//LOG("Link Layer interrupt mask register 0x%08X\n",read_reg(0x4003100c));
//write_reg(0x4003100c,0);
//LOG("Link Layer interrupt mask register 0x%08X\n",read_reg(0x4003100c));
// GAP_SetParamValue(TGAP_GEN_DISC_SCAN_INT ,23);
// GAP_SetParamValue(TGAP_GEN_DISC_SCAN_WIND ,16);
bStatus_t stu = GAPCentralRole_StartDiscovery( DEFAULT_DISCOVERY_MODE,
TRUE/*DEFAULT_DISCOVERY_ACTIVE_SCAN*/, // passive scan
FALSE/*DEFAULT_DISCOVERY_WHITE_LIST*/ );
AT_LOG("simpleBLECentral_DiscoverDevice Return Value :%d\n",stu);
}
static void simpleBLECentral_LinkDevice(void)
{
int8 Index=-1;
LOG("simpleBLECentral_LinkDevice simpleBLEScanRes: %d\n",simpleBLEScanRes);
if ( simpleBLEScanRes > 0 )
{
for(uint8_t i = 0; i< simpleBLEScanRes;i++)
{
if(osal_memcmp(simpleBLEDevList[i].addr,simpleBlePeerTarget.addr, B_ADDR_LEN))
{
Index = i;
break;
}
}
}
// Index=-1;
AT_LOG("simpleBLEScanRes %d,Index %d\r\n",simpleBLEScanRes,Index);
if( Index >= 0)
{
AT_LOG("Start EstablishLink \r\n");
simpleBLEState = BLE_STATE_CONNECTING;
// Note: if the peer addrType is not PUBLIC, the MSB of peerAddr will be adjusted by function gapAddAddrAdj()
GAPCentralRole_EstablishLink( DEFAULT_LINK_HIGH_DUTY_CYCLE,\
DEFAULT_LINK_WHITE_LIST,\
simpleBLEDevList[Index].AddrType, \
simpleBLEDevList[Index].addr );
}
else
{
AT_LOG("simpleBlePeerTarget Device Not found \r\n");
osal_start_timerEx( simpleBLETaskId, CENTRAL_INIT_DONE_EVT, \
2*1000 );
}
}
static void simpleBLECentral_ReadWriteNotifyTest(void)
{
attWriteReq_t *pReq;
attReadReq_t *pReqread;
if(rwnTestCnt==0)
{
pReqread = osal_mem_alloc(sizeof(attReadReq_t));
pReqread->handle = 0x2d;
bStatus_t status = GATT_ReadCharValue( simpleBLEConnHandle, pReqread, simpleBLETaskId );
osal_mem_free(pReqread);
}
else if(rwnTestCnt==1)
{
pReq = osal_mem_alloc(sizeof(attWriteReq_t));
pReq->sig = 0;
pReq->cmd = TRUE;
pReq->handle = 0x2d;
pReq->len = 5;
rwnTestVal[0]=0x01;
rwnTestVal[1]=centralTestVectorTbl[cTVIdx].connIntv;
rwnTestVal[2]=centralTestVectorTbl[cTVIdx].connIntv;
rwnTestVal[3]=centralTestVectorTbl[cTVIdx].latency;
rwnTestVal[4]=0x05;
osal_memcpy(pReq->value, rwnTestVal, pReq->len );
bStatus_t status = GATT_WriteNoRsp(simpleBLEConnHandle, pReq);
osal_mem_free(pReq);
}
else if(rwnTestCnt==2)
{
pReqread = osal_mem_alloc(sizeof(attReadReq_t));
pReqread->handle = 0x2d;
bStatus_t status = GATT_ReadCharValue( simpleBLEConnHandle, pReqread , simpleBLETaskId);
osal_mem_free(pReqread);
}
else if(rwnTestCnt==3)
{
pReq = osal_mem_alloc(sizeof(attWriteReq_t));
pReq->sig = 0;
pReq->cmd = TRUE;
pReq->handle = 0x2d;
pReq->len = 5;
rwnTestVal[0]=0x00;
rwnTestVal[1]=centralTestVectorTbl[cTVIdx].notfIntv;
rwnTestVal[2]=centralTestVectorTbl[cTVIdx].notfPktNum;
rwnTestVal[3]=0x00;
rwnTestVal[4]=0x00;
osal_memcpy(pReq->value, rwnTestVal, pReq->len );
bStatus_t status = GATT_WriteNoRsp(simpleBLEConnHandle, pReq);
osal_mem_free(pReq);
}
else if(rwnTestCnt==4)
{
pReq = osal_mem_alloc(sizeof(attWriteReq_t));
pReq->sig = 0;
pReq->cmd = TRUE;
pReq->handle = 0x31;
pReq->len = 2;
pReq->value[0] = (unsigned char)(GATT_CLIENT_CFG_NOTIFY);
pReq->value[1] = (unsigned char)(GATT_CLIENT_CFG_NOTIFY >> 8);
bStatus_t status = GATT_WriteNoRsp(simpleBLEConnHandle, pReq);
osal_mem_free(pReq);
}
if(rwnTestCnt<4)
{
rwnTestCnt++;
osal_start_timerEx( simpleBLETaskId, SBC_READ_WRITE_TEST_EVT, 2000 );
}
}
void centralTestVectorProcess(void)
{
uint32 uOS_size,uOS_cnt;
for(int i=0;i<Central_Test_ToDoList;i++)
{
if( centralTestVectorTbl[cTVIdx].ctvToDoList[i].toDoTick>0
&& centralTestVectorTbl[cTVIdx].ctvToDoList[i].toDoTick==mstWtCnt
&& centralTestVectorTbl[cTVIdx].ctvToDoList[i].toDoEvt!=NULL_TO_DO)
{
slaCtrlCmd=centralTestVectorTbl[cTVIdx].ctvToDoList[i].toDoEvt;
switch ( centralTestVectorTbl[cTVIdx].ctvToDoList[i].toDoEvt )
{
case CHAN_MAP:
osal_set_event(simpleBLETaskId, UPD_CHAN_MAP_EVENT);
break;
case SLA_1M:
phyModeCtrlSlave=0x01;
osal_set_event(simpleBLETaskId, SLA_PHY_MODE_EVT);
break;
case SLA_2M:
phyModeCtrlSlave=0x02;
osal_set_event(simpleBLETaskId, SLA_PHY_MODE_EVT);
break;
case SLA_ANY:
phyModeCtrlSlave=0x03;
osal_set_event(simpleBLETaskId, SLA_PHY_MODE_EVT);
break;
case SLA_HCLK16_32KRC:
case SLA_HCLK16_32KXTAL:
case SLA_HCLK48_32KRC:
case SLA_HCLK48_32KXTAL:
case SLA_HCLK64_32KRC:
case SLA_HCLK64_32KXTAL:
case SLA_CHECK_PER:
osal_set_event(simpleBLETaskId, SLA_PHY_MODE_EVT);
break;
case MST_1M:
phyModeCtrl=0x01;
osal_set_event(simpleBLETaskId, UPD_PHY_MODE_EVT);
break;
case MST_2M:
phyModeCtrl=0x02;
osal_set_event(simpleBLETaskId, UPD_PHY_MODE_EVT);
break;
case MST_ANY:
phyModeCtrl=0x03;
osal_set_event(simpleBLETaskId, UPD_PHY_MODE_EVT);
break;
}
//osal_memory_statics(NULL, &uOS_cnt,&uOS_size);
AT_LOG("[TVEC] %d toDoList %d %4x [%04x %04x] \n",i,centralTestVectorTbl[cTVIdx].ctvToDoList[i].toDoTick,
centralTestVectorTbl[cTVIdx].ctvToDoList[i].toDoEvt,
uOS_cnt,uOS_size);
}
}
if(mstWtCnt >=centralTestVectorTbl[cTVIdx].testCnt &&
ntfTest.isDone==0)
{
//osal_memory_statics(NULL, &uOS_cnt,&uOS_size);
HCI_PPLUS_ConnEventDoneNoticeCmd(simpleBLETaskId, NULL);
AT_LOG("[TVEC] %08x case %3d/%d[cnt %6d miss %2d err %2d] [%04x %04x]\n",getMcuPrecisionCount()
,cTVIdx
,sizeof(centralTestVectorTbl)/sizeof(centralTestVector_t)
,ntfTest.cnt,ntfTest.miss,ntfTest.err
,uOS_cnt,uOS_size);
if(ntfTest.miss>0 || ntfTest.err>0)
cTVErrCnt++;
AT_LOG ("[TVEC] mAloc[ll%4x r%4x s%4x] SAR[r%4x %4x %4x %4x s%4x %4x %4x %4x ]\n"
,g_pmCounters.ll_hci_buffer_alloc_err_cnt
,g_sarDbgCnt.resssambleMemAlocErr
,g_sarDbgCnt.segmentMemAlocErr
,g_sarDbgCnt.reassembleInCnt
,g_sarDbgCnt.reassembleOutCnt
,g_sarDbgCnt.reassembleErrInComp
,g_sarDbgCnt.reassembleErrIdx
,g_sarDbgCnt.segmentInCnt
,g_sarDbgCnt.segmentOutCnt
,g_sarDbgCnt.segmentErrCnt
,g_sarDbgCnt.segmentSentToLinkLayerErr);
ntfTest.cnt=0;
ntfTest.miss=0;
ntfTest.err=0;
ntfTest.isDone=1;
osal_memset(&g_sarDbgCnt,0,sizeof(g_sarDbgCnt));
cTVIdx++;
if(cTVIdx==(sizeof(centralTestVectorTbl)/sizeof(centralTestVector_t)))
{
AT_LOG("[TVEC] %08x >>>>>>>>> ALL CASE FINISHED Total %d Err %d <<<<<<<<<\n",getMcuPrecisionCount(),cTVIdx,cTVErrCnt);
cTVIdx=0;
// while(1){};
}
if (simpleBLEState == BLE_STATE_CONNECTED) // not connected
{
GAPCentralRole_TerminateLink( simpleBLEConnHandle);
}
AT_LOG("Terminated Link .s%d d%d\r\n",simpleBLEState,simpleBLEConnHandle);
}
return;
}
/*********************************************************************
*********************************************************************/
| 38.626871 | 212 | 0.567856 | [
"vector",
"3d"
] |
fe5ce3acaf986a1520e6ae7a16c8c66e61277b97 | 91,745 | c | C | base/fs/remotefs/dfs/dfsserver/serverfilter/dfsinit.c | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | base/fs/remotefs/dfs/dfsserver/serverfilter/dfsinit.c | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | base/fs/remotefs/dfs/dfsserver/serverfilter/dfsinit.c | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z |
//
// Copyright (C) 2000, Microsoft Corporation
//
// File: dfsinit.c
//
// Contents: Driver initialization routine for the Dfs server.
//
// Classes: None
//
// Functions: DriverEntry -- Entry point for driver
//
//-----------------------------------------------------------------------------
#include <ntifs.h>
#include <limits.h>
#include <windef.h>
#include <dfsprefix.h>
#include <..\..\lib\prefix\prefix.h>
#include <DfsReferralData.h>
#include "dfsheader.h"
#include "DfsInit.h"
#include "midatlax.h"
#include "rxcontx.h"
#include "dfsumr.h"
#include "umrx.h"
#include "DfsUmrCtrl.h"
#include "DfsUmrRequests.h"
#include <dfsfsctl.h>
#define _NTDDK_
#include "stdarg.h"
#include "wmikm.h"
#include <wmistr.h>
#include <evntrace.h>
#include <wmiumkm.h>
#include "dfswmi.h"
#define WPP_BIT_CLI_DRV 0x01
#define WPP_LEVEL_FLAGS_LOGGER(lvl,flags) WPP_LEVEL_LOGGER(flags)
#define WPP_LEVEL_FLAGS_ENABLED(lvl, flags) (WPP_LEVEL_ENABLED(flags) && WPP_CONTROL(WPP_BIT_CLI_DRV ).Level >= lvl)
#define WPP_LEVEL_ERROR_FLAGS_LOGGER(lvl, error, flags) WPP_LEVEL_LOGGER(flags)
#define WPP_LEVEL_ERROR_FLAGS_ENABLED(lvl, error, flags) \
((!NT_SUCCESS(error) || WPP_LEVEL_ENABLED(flags)) && WPP_CONTROL(WPP_BIT_CLI_DRV ).Level >= lvl)
#include "dfsinit.tmh"
DFS_GLOBAL_DATA DfsGlobalData;
//prefix table
DFS_PREFIX_TABLE *pPrefixTable = NULL;
BOOL gfRundownPrefixCompleted = FALSE;
BOOLEAN DfsDebugAttachToFsRecognizer = FALSE;
WCHAR gDummyData = 0;
extern POBJECT_TYPE *IoFileObjectType;
extern PUMRX_ENGINE g_pUMRxEngine;
#ifndef ClearFlag
#define ClearFlag(_F,_SF) ((_F) &= ~(_SF))
#endif
#define DFSFILTER_INIT_DEVICECREATED 0x00000001
#define DFSFILTER_INIT_REGCHANGE 0x00000002
#define DFSFILTER_INIT_SYMLINK 0x00000004
NTSTATUS
DfsCheckReparse(
PUNICODE_STRING pParent,
PUNICODE_STRING pName );
NTSTATUS
DfsFilterCreateCheck(
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp,
IN PVOID Context);
NTSTATUS
DfsCheckDfsShare(
IN PVOID InputBuffer,
IN ULONG InputBufferLength,
PIRP Irp,
IN OUT PIO_STATUS_BLOCK pIoStatusBlock);
//
// Buffer size for local names on the stack
//
#define MAX_DEVNAME_LENGTH 128
DWORD DFSInitilizationStatus = 0;
NTSTATUS
DriverEntry(
IN PDRIVER_OBJECT DriverObject,
IN PUNICODE_STRING RegistryPath);
#if defined (DEBUG)
VOID
DriverUnload (
IN PDRIVER_OBJECT DriverObject );
#endif
VOID
DfsInitUnwind(
IN PDRIVER_OBJECT DriverObject);
VOID
DfsFsNotification (
IN PDEVICE_OBJECT DeviceObject,
IN BOOLEAN FsActive );
NTSTATUS
DfsAttachToFileSystemDevice (
IN PDEVICE_OBJECT DeviceObject );
VOID
DfsDetachFromFileSystemDevice (
IN PDEVICE_OBJECT DeviceObject );
NTSTATUS
DfsEnumerateFileSystemVolumes (
IN PDEVICE_OBJECT FSDeviceObject );
NTSTATUS
DfsAttachToMountedDevice (
IN PDEVICE_OBJECT DeviceObject,
IN PDEVICE_OBJECT DfsFilterDeviceObject,
IN PDEVICE_OBJECT DiskDeviceObject );
VOID
DfsGetObjectName (
IN PVOID Object,
IN OUT PUNICODE_STRING Name );
NTSTATUS
DfsMountCompletion (
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp,
IN PVOID Context );
NTSTATUS
DfsLoadFsCompletion (
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp,
IN PVOID Context );
BOOLEAN
DfsAttachedToDevice (
PDEVICE_OBJECT DeviceObject,
PDEVICE_OBJECT *AttachedDeviceObject OPTIONAL);
NTSTATUS
DfsPassThrough (
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp );
NTSTATUS
DfsFilterCreate(
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp);
NTSTATUS
DfsHandlePrivateOpen(IN PIRP Irp);
NTSTATUS
DfsFilterCleanupClose(
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp);
NTSTATUS
DfsHandlePrivateFsControl (
IN PDEVICE_OBJECT DeviceObject,
IN ULONG IoControlCode,
IN PVOID InputBuffer OPTIONAL,
IN ULONG InputBufferLength,
OUT PVOID OutputBuffer OPTIONAL,
IN ULONG OutputBufferLength,
OUT PIO_STATUS_BLOCK IoStatus,
IN PIRP Irp );
NTSTATUS
DfsFilterFsControl(
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp);
NTSTATUS
DfsFsctrlIsShareInDfs(
IN PVOID InputBuffer,
IN ULONG InputBufferLength);
NTSTATUS
DfsAttachToFileSystem (
IN PWSTR UserDeviceName);
NTSTATUS
DfsDetachFromFileSystem (
IN PWSTR UserDeviceName);
NTSTATUS
DfsHandleAttachToFs(PVOID InputBuffer,
ULONG InputBufferSize);
NTSTATUS
DfsHandleDetachFromFs(PVOID InputBuffer,
ULONG InputBufferLength);
NTSTATUS
DfsGetDeviceObjectFromName (
IN PUNICODE_STRING DeviceName,
OUT PDEVICE_OBJECT *DeviceObject
);
NTSTATUS
DfsRunDownPrefixTable(void);
NTSTATUS
DfsHandlePrivateCleanupClose(IN PIRP Irp);
void
DfsPrefixRundownFunction(PVOID pEntry);
#ifdef ALLOC_PRAGMA
#pragma alloc_text( INIT, DriverEntry)
#if defined (DEBUG)
#pragma alloc_text( PAGE, DriverUnload)
#endif
#pragma alloc_text( PAGE, DfsInitUnwind)
#pragma alloc_text( PAGE, DfsFsNotification )
#pragma alloc_text( PAGE, DfsAttachToFileSystemDevice )
#pragma alloc_text( PAGE, DfsDetachFromFileSystemDevice )
#pragma alloc_text( PAGE, DfsEnumerateFileSystemVolumes )
#pragma alloc_text( PAGE, DfsAttachToMountedDevice )
#pragma alloc_text( PAGE, DfsGetObjectName )
#pragma alloc_text( PAGE, DfsMountCompletion )
#pragma alloc_text( PAGE, DfsLoadFsCompletion )
#pragma alloc_text( PAGE, DfsAttachedToDevice )
#pragma alloc_text( PAGE, DfsFilterCreate )
#pragma alloc_text( PAGE, DfsFilterCleanupClose )
#pragma alloc_text( PAGE, DfsFilterFsControl )
#pragma alloc_text( PAGE, DfsHandlePrivateFsControl )
#pragma alloc_text( PAGE, DfsFsctrlIsShareInDfs )
#pragma alloc_text( PAGE, DfsGetDeviceObjectFromName)
#pragma alloc_text( PAGE, DfsAttachToFileSystem)
#pragma alloc_text( PAGE, DfsDetachFromFileSystem)
#pragma alloc_text( PAGE, DfsHandleAttachToFs)
#pragma alloc_text( PAGE, DfsHandleDetachFromFs)
#pragma alloc_text( PAGE, DfsHandlePrivateCleanupClose)
#pragma alloc_text( PAGE, DfsHandlePrivateOpen)
#pragma alloc_text( PAGE, DfsRunDownPrefixTable)
#pragma alloc_text( PAGE, DfsPrefixRundownFunction)
#endif // ALLOC_PRAGMA
//+-------------------------------------------------------------------
//
// Function: DriverEntry, main entry point
//
// Synopsis: This is the initialization routine for the DFS file system
// device driver. This routine creates the device object for
// the FileSystem device and performs all other driver
// initialization.
//
// Arguments: [DriverObject] -- Pointer to driver object created by the
// system.
//
// Returns: [NTSTATUS] - The function value is the final status from
// the initialization operation.
//
//--------------------------------------------------------------------
NTSTATUS
DriverEntry(
IN PDRIVER_OBJECT DriverObject,
IN PUNICODE_STRING RegistryPath )
{
NTSTATUS Status = STATUS_SUCCESS;
UNICODE_STRING NameString;
OBJECT_ATTRIBUTES ObjectAttributes;
ULONG i = 0;
WPP_INIT_TRACING(DriverObject, RegistryPath);
//
// Create the filesystem device object.
//
RtlInitUnicodeString( &NameString, DFS_FILTER_NAME );
Status = IoCreateDevice( DriverObject,
0,
&NameString,
FILE_DEVICE_DISK_FILE_SYSTEM,
FILE_DEVICE_SECURE_OPEN,
FALSE,
&DfsGlobalData.pFilterControlDeviceObject);
if ( !NT_SUCCESS( Status ) ) {
DbgPrint("Driverentry IoCreateDevice failed %X\n", Status);
return Status;
}
DfsGlobalData.pFilterDriverObject = DriverObject;
ExInitializeResourceLite( &DfsGlobalData.Resource );
InitializeListHead( &DfsGlobalData.DfsVolumeList);
#if defined (DEBUG)
DriverObject->DriverUnload = DriverUnload;
#endif
try
{
//
// Initialize the driver object with this driver's entry points.
// Most are simply passed through to some other device driver.
//
for (i = 0; i <= IRP_MJ_MAXIMUM_FUNCTION; i++) {
DriverObject->MajorFunction[i] = DfsPassThrough;
}
DriverObject->MajorFunction[IRP_MJ_CREATE] = DfsFilterCreate;
DriverObject->MajorFunction[IRP_MJ_FILE_SYSTEM_CONTROL] = DfsFilterFsControl;
DriverObject->MajorFunction[IRP_MJ_CLEANUP] = DfsFilterCleanupClose;
DriverObject->MajorFunction[IRP_MJ_CLOSE] = DfsFilterCleanupClose;
DriverObject->FastIoDispatch = &DfsFastIoDispatch;
Status = IoRegisterFsRegistrationChange( DriverObject,
DfsFsNotification );
if (NT_SUCCESS (Status)) {
DFSInitilizationStatus |= DFSFILTER_INIT_REGCHANGE;
Status = DfsInitializeUmrResources();
}
}
finally
{
if (Status != STATUS_SUCCESS)
{
DbgPrint("Driverentry status not success %X\n", Status);
DfsInitUnwind(DriverObject);
}
}
DfsGlobalData.CurrentProcessPointer = (PVOID)PsGetCurrentProcess();
DfsGlobalData.IsDC = FALSE;
DfsGlobalData.ServiceProcess = NULL;
DfsGlobalData.Started = FALSE;
ClearFlag( DfsGlobalData.pFilterControlDeviceObject->Flags, DO_DEVICE_INITIALIZING );
return STATUS_SUCCESS;
}
VOID
DfsInitUnwind(IN PDRIVER_OBJECT DriverObject)
{
NTSTATUS Status = STATUS_SUCCESS;
UNICODE_STRING UserModeDeviceName;
PAGED_CODE();
if(DFSInitilizationStatus & DFSFILTER_INIT_REGCHANGE)
{
IoUnregisterFsRegistrationChange( DriverObject, DfsFsNotification );
}
IoDeleteDevice ( DfsGlobalData.pFilterControlDeviceObject );
}
#if defined (DEBUG)
/*++
Routine Description:
This routine is called when a driver can be unloaded. This performs all of
the necessary cleanup for unloading the driver from memory. Note that an
error can not be returned from this routine.
When a request is made to unload a driver the IO System will cache that
information and not actually call this routine until the following states
have occurred:
- All device objects which belong to this filter are at the top of their
respective attachment chains.
- All handle counts for all device objects which belong to this filter have
gone to zero.
WARNING: Microsoft does not officially support the unloading of File
System Filter Drivers. This is an example of how to unload
your driver if you would like to use it during development.
This should not be made available in production code.
Arguments:
DriverObject - Driver object for this module
Return Value:
None.
--*/
VOID
DriverUnload (
IN PDRIVER_OBJECT DriverObject )
{
PDFS_FILTER_DEVICE_EXTENSION devExt;
PFAST_IO_DISPATCH fastIoDispatch;
NTSTATUS status;
ULONG numDevices;
ULONG i;
LARGE_INTEGER interval;
# define DEVOBJ_LIST_SIZE 64
PDEVICE_OBJECT devList[DEVOBJ_LIST_SIZE];
ASSERT(DriverObject == DfsGlobalData.pFilterDriverObject);
//
// Log we are unloading
//
DbgPrint( "SFILTER: Unloading driver (%p)\n",DriverObject);
//
// Don't get anymore file system change notifications
//
IoUnregisterFsRegistrationChange( DriverObject, DfsFsNotification );
//
// This is the loop that will go through all of the devices we are attached
// to and detach from them. Since we don't know how many there are and
// we don't want to allocate memory (because we can't return an error)
// we will free them in chunks using a local array on the stack.
//
for (;;) {
//
// Get what device objects we can for this driver. Quit if there
// are not any more.
//
status = IoEnumerateDeviceObjectList(
DriverObject,
devList,
sizeof(devList),
&numDevices);
if (numDevices <= 0) {
break;
}
numDevices = min( numDevices, DEVOBJ_LIST_SIZE );
//
// First go through the list and detach each of the devices.
// Our control device object does not have a DeviceExtension and
// is not attached to anything so don't detach it.
//
for (i=0; i < numDevices; i++) {
devExt = devList[i]->DeviceExtension;
if (NULL != devExt) {
IoDetachDevice( devExt->pAttachedToDeviceObject );
}
}
//
// The IO Manager does not currently add a refrence count to a device
// object for each outstanding IRP. This means there is no way to
// know if there are any outstanding IRPs on the given device.
// We are going to wait for a reonsable amount of time for pending
// irps to complete.
//
// WARNING: This does not work 100% of the time and the driver may be
// unloaded before all IRPs are completed during high stress
// situations. The system will fault if this occurs. This
// is a sample of how to do this during testing. This is
// not recommended for production code.
//
interval.QuadPart = -5 * (10 * 1000 * 1000); //delay 5 seconds
KeDelayExecutionThread( KernelMode, FALSE, &interval );
//
// Now go back through the list and delete the device objects.
//
for (i=0; i < numDevices; i++) {
//
// See if this is our control device object. If not then cleanup
// the device extension. If so then clear the global pointer
// that refrences it.
//
if (NULL == devList[i]->DeviceExtension) {
ASSERT(devList[i] == DfsGlobalData.pFilterControlDeviceObject);
DfsGlobalData.pFilterControlDeviceObject = NULL;
}
//
// Delete the device object, remove refrence counts added by
// IoEnumerateDeviceObjectList. Note that the delete does
// not actually occur until the refrence count goes to zero.
//
IoDeleteDevice( devList[i] );
ObDereferenceObject( devList[i] );
}
}
//
// Free our FastIO table
//
fastIoDispatch = DriverObject->FastIoDispatch;
DriverObject->FastIoDispatch = NULL;
DfsDeInitializeUmrResources();
}
#endif
//+-------------------------------------------------------------------------
//
// Function: DfsFsNotification
//
// Arguments:
// DeviceObject - Pointer to the file system's device object.
//
// FsActive - Boolean indicating whether the file system has registered
// (TRUE) or unregistered (FALSE) itself as an active file system.
//
//
// Returns: NONE
//
// Description:
// This routine is invoked whenever a file system has either registered or
// unregistered itself as an active file system.
//
// For the former case, this routine creates a device object and attaches it
// to the specified file system's device object. This allows this driver
// to filter all requests to that file system. Specifically we are looking
// for MOUNT requests so we can attach to newly mounted volumes.
//
// For the latter case, this file system's device object is located,
// detached, and deleted. This removes this file system as a filter for
// the specified file system.
//--------------------------------------------------------------------------
VOID
DfsFsNotification (
IN PDEVICE_OBJECT DeviceObject,
IN BOOLEAN FsActive )
{
PAGED_CODE();
DFS_TRACE_LOW(KUMR_DETAIL, "DfsFsNotification %p, %x\n",
DeviceObject, FsActive);
//
// Handle attaching/detaching from the given file system.
//
if (FsActive) {
DfsAttachToFileSystemDevice( DeviceObject );
} else {
DfsDetachFromFileSystemDevice( DeviceObject );
}
}
/*++
Routine Description:
This will attach to the given file system device object. We attach to
these devices so we will know when new volumes are mounted.
Arguments:
DeviceObject - The device to attach to
Name - An already initialized unicode string used to retrieve names.
This is passed in to reduce the number of strings buffers on
the stack.
Return Value:
Status of the operation
--*/
NTSTATUS
DfsAttachToFileSystemDevice (
IN PDEVICE_OBJECT DeviceObject )
{
PDEVICE_OBJECT newDeviceObject;
PDEVICE_OBJECT attachedToDevObj;
PDFS_FILTER_DEVICE_EXTENSION devExt;
UNICODE_STRING fsrecName;
NTSTATUS status;
WCHAR nameBuffer[MAX_DEVNAME_LENGTH];
UNICODE_STRING Name;
RtlInitEmptyUnicodeString( &Name, nameBuffer, sizeof(nameBuffer));
PAGED_CODE();
//
// See if this is a file system type we care about. If not, return.
//
if (!IS_DESIRED_DEVICE_TYPE(DeviceObject->DeviceType)) {
return STATUS_SUCCESS;
}
//
// See if we should attach to recognizers or not
//
if (!DfsDebugAttachToFsRecognizer) {
//
// See if this is one of the standard Microsoft file system recognizer
// devices (see if this device is in the FS_REC driver). If so skip it.
// We no longer attach to file system recognizer devices, we simply wait
// for the real file system driver to load.
//
RtlInitUnicodeString( &fsrecName, L"\\FileSystem\\Fs_Rec" );
DfsGetObjectName( DeviceObject->DriverObject, &Name );
if (RtlCompareUnicodeString( &Name, &fsrecName, TRUE ) == 0) {
return STATUS_SUCCESS;
}
}
//
// We want to attach to this file system. Create a new device object we
// can attach with.
//
status = IoCreateDevice( DfsGlobalData.pFilterDriverObject,
sizeof( DFS_FILTER_DEVICE_EXTENSION ),
NULL,
DeviceObject->DeviceType,
0,
FALSE,
&newDeviceObject );
if (!NT_SUCCESS( status )) {
return status;
}
//
// Do the attachment
//
attachedToDevObj = IoAttachDeviceToDeviceStack( newDeviceObject, DeviceObject );
if (attachedToDevObj == NULL) {
status = STATUS_INSUFFICIENT_RESOURCES;
goto ErrorCleanupDevice;
}
//
// Finish initializing our device extension
//
devExt = newDeviceObject->DeviceExtension;
devExt->pAttachedToDeviceObject = attachedToDevObj;
devExt->pThisDeviceObject = newDeviceObject;
devExt->Attached = TRUE;
ClearFlag( newDeviceObject->Flags, DO_DEVICE_INITIALIZING );
#if 0
//
// Enumerate all the mounted devices that currently
// exist for this file system and attach to them.
//
status = DfsEnumerateFileSystemVolumes( DeviceObject );
if (!NT_SUCCESS( status )) {
goto ErrorCleanupAttachment;
}
#endif
return STATUS_SUCCESS;
/////////////////////////////////////////////////////////////////////
// Cleanup error handling
/////////////////////////////////////////////////////////////////////
ErrorCleanupDevice:
IoDeleteDevice( newDeviceObject );
DFS_TRACE_LOW(KUMR_DETAIL, "attach to file system device %p dfs object %p, status %x\n",
DeviceObject,
newDeviceObject,
status);
return status;
}
/*++
Routine Description:
Given a base file system device object, this will scan up the attachment
chain looking for our attached device object. If found it will detach
us from the chain.
Arguments:
DeviceObject - The file system device to detach from.
Return Value:
--*/
VOID
DfsDetachFromFileSystemDevice (
IN PDEVICE_OBJECT DeviceObject )
{
PDEVICE_OBJECT ourAttachedDevice;
PDFS_FILTER_DEVICE_EXTENSION devExt;
PAGED_CODE();
//
// Skip the base file system device object (since it can't be us)
//
DFS_TRACE_LOW(KUMR_DETAIL, "detach from File system device %p\n",
DeviceObject);
ourAttachedDevice = DeviceObject->AttachedDevice;
while (NULL != ourAttachedDevice) {
if (IS_MY_DEVICE_OBJECT( ourAttachedDevice )) {
devExt = ourAttachedDevice->DeviceExtension;
//
// Detach us from the object just below us
// Cleanup and delete the object
//
IoDetachDevice( DeviceObject );
IoDeleteDevice( ourAttachedDevice );
return;
}
//
// Look at the next device up in the attachment chain
//
DeviceObject = ourAttachedDevice;
ourAttachedDevice = ourAttachedDevice->AttachedDevice;
}
}
/*++
Routine Description:
This routine will return the name of the given object.
If a name can not be found an empty string will be returned.
Arguments:
Object - The object whose name we want
Name - A unicode string that is already initialized with a buffer that
receives the name of the object.
Return Value:
None
--*/
VOID
DfsGetObjectName (
IN PVOID Object,
IN OUT PUNICODE_STRING Name )
{
NTSTATUS status;
CHAR nibuf[512]; //buffer that receives NAME information and name
POBJECT_NAME_INFORMATION nameInfo = (POBJECT_NAME_INFORMATION)nibuf;
ULONG retLength;
status = ObQueryNameString( Object, nameInfo, sizeof(nibuf), &retLength);
Name->Length = 0;
if (NT_SUCCESS( status )) {
RtlCopyUnicodeString( Name, &nameInfo->Name );
}
}
/*++
Routine Description:
This routine is invoked for the completion of a mount request. This
simply re-syncs back to the dispatch routine so the operation can be
completed.
Arguments:
DeviceObject - Pointer to this driver's device object that was attached to
the file system device object
Irp - Pointer to the IRP that was just completed.
Context - Pointer to the event to syncwith
--*/
NTSTATUS
DfsCompleteMountRequest(
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp,
IN PVOID Context )
{
PIO_STACK_LOCATION pIrpSp = IoGetCurrentIrpStackLocation( Irp );
PDEVICE_OBJECT pDiskDeviceObject;
DFS_TRACE_HIGH( KUMR_DETAIL, "Processing mount complete %p, %p\n", DeviceObject, Context);
ASSERT(IS_MY_DEVICE_OBJECT( DeviceObject ));
if (NT_SUCCESS( Irp->IoStatus.Status))
{
pDiskDeviceObject = Context;
if ((pDiskDeviceObject->Vpb != NULL) &&
(pDiskDeviceObject->Vpb->DeviceObject != NULL)) {
DfsReattachToMountedVolume( pDiskDeviceObject->Vpb->DeviceObject,
pDiskDeviceObject );
}
}
//
// If pending was returned, then propogate it to the caller.
//
if (Irp->PendingReturned) {
IoMarkIrpPending( Irp );
}
DFS_TRACE_HIGH( KUMR_DETAIL, "Processing mount complete done\n");
return( STATUS_SUCCESS );
}
/*++
Routine Description:
This routine is invoked for the completion of a LoadFileSystem request.
This simply re-syncs back to the dispatch routine so the operation can be
completed.
Arguments:
DeviceObject - Pointer to this driver's device object.
Irp - Pointer to the I/O Request Packet representing the file system
driver load request.
Context - Pointer to the event to syncwith
Return Value:
The function value for this routine is always success.
--*/
NTSTATUS
DfsLoadFsCompletion (
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp,
IN PVOID Context )
{
PKEVENT event = Context;
UNREFERENCED_PARAMETER( DeviceObject );
UNREFERENCED_PARAMETER( Irp );
ASSERT(IS_MY_DEVICE_OBJECT( DeviceObject ));
//
// If an event routine is defined, signal it
//
KeSetEvent(event, IO_NO_INCREMENT, FALSE);
return STATUS_MORE_PROCESSING_REQUIRED;
}
/*++
Routine Description:
This walks down the attachment chain looking for a device object that
belongs to this driver.
Arguments:
DeviceObject - The device chain we want to look through
Return Value:
TRUE if we are attached, FALSE if not
--*/
BOOLEAN
DfsAttachedToDevice (
PDEVICE_OBJECT DeviceObject,
PDEVICE_OBJECT *AttachedDeviceObject OPTIONAL )
{
PDEVICE_OBJECT currentDevObj;
PDEVICE_OBJECT nextDevObj;
currentDevObj = IoGetAttachedDeviceReference( DeviceObject );
//
// CurrentDevObj has the top of the attachment chain. Scan
// down the list to find our device object.
do {
if (IS_MY_DEVICE_OBJECT( currentDevObj ))
{
//
// We have found that we are already attached. If we are
// returning the device object we are attached to then leave the
// refrence on it. If not then remove the refrence.
//
if (AttachedDeviceObject != NULL)
{
*AttachedDeviceObject = currentDevObj;
}
else
{
ObDereferenceObject( currentDevObj );
}
return TRUE;
}
//
// Get the next attached object. This puts a reference on
// the device object.
//
nextDevObj = IoGetLowerDeviceObject( currentDevObj );
//
// Dereference our current device object, before
// moving to the next one.
//
ObDereferenceObject( currentDevObj );
currentDevObj = nextDevObj;
} while (NULL != currentDevObj);
return FALSE;
}
/*++
Routine Description:
This routine is the main dispatch routine for the general purpose file
system driver. It simply passes requests onto the next driver in the
stack, which is presumably a disk file system.
Arguments:
DeviceObject - Pointer to the device object for this driver.
Irp - Pointer to the request packet representing the I/O request.
Return Value:
The function value is the status of the operation.
Note:
A note to filter file system implementers:
This routine actually "passes" through the request by taking this
driver out of the IRP stack. If the driver would like to pass the
I/O request through, but then also see the result, then rather than
taking itself out of the loop it could keep itself in by copying the
caller's parameters to the next stack location and then set its own
completion routine.
Hence, instead of calling:
IoSkipCurrentIrpStackLocation( Irp );
You could instead call:
IoCopyCurrentIrpStackLocationToNext( Irp );
IoSetCompletionRoutine( Irp, NULL, NULL, FALSE, FALSE, FALSE );
This example actually NULLs out the caller's I/O completion routine, but
this driver could set its own completion routine so that it would be
notified when the request was completed (see SfCreate for an example of
this).
--*/
NTSTATUS
DfsPassThrough (
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp )
{
VALIDATE_IRQL(Irp);
//
// If this is for our control device object, fail the operation
//
if (IS_MY_CONTROL_DEVICE_OBJECT(DeviceObject)) {
Irp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST;
Irp->IoStatus.Information = 0;
IoCompleteRequest( Irp, IO_NO_INCREMENT );
return STATUS_INVALID_DEVICE_REQUEST;
}
ASSERT(IS_MY_DEVICE_OBJECT( DeviceObject ));
//
// Get this driver out of the driver stack and get to the next driver as
// quickly as possible.
//
IoSkipCurrentIrpStackLocation( Irp );
//
// Call the appropriate file system driver with the request.
//
return IoCallDriver( ((PDFS_FILTER_DEVICE_EXTENSION) DeviceObject->DeviceExtension)->pAttachedToDeviceObject, Irp );
}
NTSTATUS
DfsHandlePrivateOpen(IN PIRP Irp)
{
NTSTATUS Status = STATUS_SUCCESS;
PIO_STACK_LOCATION pIrpSp = NULL;
LONG TheSame = 0;
UNICODE_STRING TermPath;
PAGED_CODE();
VALIDATE_IRQL(Irp);
pIrpSp = IoGetCurrentIrpStackLocation( Irp );
if(pIrpSp->FileObject->FileName.Length == 0)
{
return Status;
}
RtlInitUnicodeString( &TermPath, DFSFILTER_PROCESS_TERMINATION_FILEPATH);
TheSame = RtlCompareUnicodeString( &pIrpSp->FileObject->FileName, &TermPath, TRUE );
if(TheSame == 0)
{
FsRtlEnterFileSystem();
ACQUIRE_GLOBAL_LOCK();
if(DfsGlobalData.ServiceProcess == NULL)
{
DfsGlobalData.ServiceProcess = IoGetCurrentProcess();
}
else
{
Status = STATUS_ACCESS_DENIED;
DFS_TRACE_ERROR_HIGH(Status, KUMR_DETAIL, "DfsHandlePrivateOpen %x\n", Status);
}
RELEASE_GLOBAL_LOCK();
FsRtlExitFileSystem();
}
return Status;
}
/*++
Routine Description:
This function filters create/open operations. It simply establishes an
I/O completion routine to be invoked if the operation was successful.
Arguments:
DeviceObject - Pointer to the target device object of the create/open.
Irp - Pointer to the I/O Request Packet that represents the operation.
Return Value:
The function value is the status of the call to the file system's entry
point.
--*/
NTSTATUS
DfsFilterCreate (
IN PDEVICE_OBJECT pDeviceObject,
IN PIRP pIrp)
{
NTSTATUS Status = STATUS_SUCCESS;
PIO_STACK_LOCATION pIrpSp = NULL;
KEVENT WaitEvent;
PAGED_CODE();
VALIDATE_IRQL(Irp);
//
// If this is for our control device object, return success
//
if (IS_MY_CONTROL_DEVICE_OBJECT(pDeviceObject))
{
pIrpSp = IoGetCurrentIrpStackLocation( pIrp );
Status = DfsHandlePrivateOpen(pIrp);
pIrp->IoStatus.Status = Status;
if(Status == STATUS_SUCCESS)
{
pIrp->IoStatus.Information = FILE_OPENED;
}
else
{
pIrp->IoStatus.Information = 0;
}
IoCompleteRequest( pIrp, IO_NO_INCREMENT );
return Status;
}
ASSERT(IS_MY_DEVICE_OBJECT( pDeviceObject ));
//
// Get a pointer to the current stack location in the IRP. This is where
// the function codes and parameters are stored.
//
pIrpSp = IoGetCurrentIrpStackLocation( pIrp );
//
// If the the file is not being opened with FILE_OPEN_REPARSE_POINT
// then set a completion routine
//
if (!(pIrpSp->Parameters.Create.Options & FILE_OPEN_REPARSE_POINT))
{
KeInitializeEvent(&WaitEvent, SynchronizationEvent, FALSE);
//
// Copy the stack and set our Completion routine
//
IoCopyCurrentIrpStackLocationToNext( pIrp );
IoSetCompletionRoutine (pIrp,
DfsFilterCreateCheck,
&WaitEvent,
TRUE, // Call on success
TRUE, // fail
TRUE) ; // and on cancel
Status = IoCallDriver( ((PDFS_FILTER_DEVICE_EXTENSION) pDeviceObject->DeviceExtension)->pAttachedToDeviceObject, pIrp );
if(Status == STATUS_PENDING)
{
//
// We wait for the event to be set by the
// completion routine.
// 555624, Since we wait here, we do not propagate IRP pending
// flag in the completion routine.
//
KeWaitForSingleObject( &WaitEvent,
UserRequest,
KernelMode,
FALSE,
(PLARGE_INTEGER) NULL );
}
Status = pIrp->IoStatus.Status;
//
// This IRP never completed. Complete it now
//
IoCompleteRequest(pIrp,
IO_NO_INCREMENT);
}
else {
//
// Don't put us on the stack then call the next driver
//
IoSkipCurrentIrpStackLocation( pIrp );
Status = IoCallDriver( ((PDFS_FILTER_DEVICE_EXTENSION) pDeviceObject->DeviceExtension)->pAttachedToDeviceObject, pIrp );
}
return Status;
}
/*++
Routine Description:
This completion routine will be called by the I/O manager when an
file create request has been completed by a filtered driver. If the
returned code is a reparse error and it is a DFS reparse point then
we must set up for returning PATH_NOT_COVERED.
Arguments:
DeviceObject - Pointer to the device object (filter's) for this request
Irp - Pointer to the Irp that is being completed
Context - Driver defined context -
Return Value:
STATUS_SUCCESS - Recall is complete
STATUS_MORE_PROCESSING_REQUIRED - Open request was sent back to file system
--*/
NTSTATUS
DfsFilterCreateCheck(
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp,
IN PVOID Context)
{
PREPARSE_DATA_BUFFER pHdr;
PKEVENT pEvent = Context;
if (Irp->IoStatus.Status == STATUS_REPARSE) {
pHdr = (PREPARSE_DATA_BUFFER) Irp->Tail.Overlay.AuxiliaryBuffer;
//
// The REPARSE_DATA_BUFFER can be legally null for IO_REMOUNTs.
//
if ((pHdr != NULL) && (pHdr->ReparseTag == IO_REPARSE_TAG_DFS)) {
//DbgPrint("Reparse Tag is DFS: returning path not covered\n");
Irp->IoStatus.Status = STATUS_PATH_NOT_COVERED;
}
}
//
// Propogate the IRP pending flag.
//
// 555624, do not propagate IRP pending since DFS is
// synchronizing on this call.
// if (Irp->PendingReturned) {
// IoMarkIrpPending( Irp );
// }
KeSetEvent(pEvent, IO_NO_INCREMENT, FALSE);
//
// This packet would be completed by RsCreate
//
return(STATUS_MORE_PROCESSING_REQUIRED);
}
NTSTATUS
DfsIsServiceAttached(void)
{
NTSTATUS Status = STATUS_SUCCESS;
DFS_TRACE_LOW(KUMR_DETAIL, "DfsIsServiceAttached\n");
ExAcquireResourceSharedLite(&DfsGlobalData.Resource, TRUE);
if(DfsGlobalData.ServiceProcess != IoGetCurrentProcess())
{
Status = STATUS_ACCESS_DENIED;
}
ExReleaseResourceLite(&DfsGlobalData.Resource);
DFS_TRACE_LOW(KUMR_DETAIL, "DfsIsServiceAttached Status = %x\n", Status );
return Status;
}
void
DfsPrefixRundownFunction (PVOID pEntry)
{
PWSTR VolumeName = (PWSTR) pEntry;
if(VolumeName != NULL)
{
DfsDetachFromFileSystem(VolumeName);
ExFreePool(pEntry);
}
return;
}
NTSTATUS
DfsRunDownPrefixTable(void)
{
NTSTATUS Status = STATUS_SUCCESS;
if(pPrefixTable == NULL)
{
return Status;
}
DfsDismantlePrefixTable(pPrefixTable, DfsPrefixRundownFunction);
DfsDereferencePrefixTable(pPrefixTable);
pPrefixTable = NULL;
gfRundownPrefixCompleted = TRUE;
return Status;
}
NTSTATUS
DfsHandlePrivateCleanupClose(IN PIRP Irp)
{
NTSTATUS Status = STATUS_SUCCESS;
PIO_STACK_LOCATION pIrpSp = NULL;
LONG TheSame = 0;
UNICODE_STRING TermPath;
PAGED_CODE();
VALIDATE_IRQL(Irp);
pIrpSp = IoGetCurrentIrpStackLocation( Irp );
if(pIrpSp->FileObject->FileName.Length == 0)
{
return Status;
}
RtlInitUnicodeString( &TermPath, DFSFILTER_PROCESS_TERMINATION_FILEPATH);
TheSame = RtlCompareUnicodeString( &pIrpSp->FileObject->FileName, &TermPath, TRUE );
if(TheSame == 0)
{
if(g_pUMRxEngine)
{
UMRxEngineCompleteQueuedRequests( g_pUMRxEngine,
STATUS_CANCELLED,
TRUE);
}
FsRtlEnterFileSystem();
ACQUIRE_GLOBAL_LOCK();
if( pPrefixTable)
{
DfsRunDownPrefixTable();
}
DfsGlobalData.ServiceProcess = NULL;
DfsGlobalData.Started = FALSE;
RELEASE_GLOBAL_LOCK();
FsRtlExitFileSystem();
}
return Status;
}
/*++
Routine Description:
This routine is invoked whenever a cleanup or a close request is to be
processed.
Arguments:
DeviceObject - Pointer to the device object for this driver.
Irp - Pointer to the request packet representing the I/O request.
Return Value:
The function value is the status of the operation.
Note:
See notes for SfPassThrough for this routine.
--*/
NTSTATUS
DfsFilterCleanupClose (
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp)
{
PAGED_CODE();
VALIDATE_IRQL(Irp);
//
// If this is for our control device object, return success
//
if (IS_MY_CONTROL_DEVICE_OBJECT(DeviceObject))
{
DfsHandlePrivateCleanupClose(Irp);
Irp->IoStatus.Status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
IoCompleteRequest( Irp, IO_NO_INCREMENT );
return STATUS_SUCCESS;
}
ASSERT(IS_MY_DEVICE_OBJECT( DeviceObject ));
//
// Get this driver out of the driver stack and get to the next driver as
// quickly as possible.
//
IoSkipCurrentIrpStackLocation( Irp );
//
// Now call the appropriate file system driver with the request.
//
return IoCallDriver( ((PDFS_FILTER_DEVICE_EXTENSION) DeviceObject->DeviceExtension)->pAttachedToDeviceObject, Irp );
}
NTSTATUS
DfsFsctrlIsShareInDfs(
IN PVOID InputBuffer,
IN ULONG InputBufferLength)
{
PDFS_IS_SHARE_IN_DFS_ARG arg = (PDFS_IS_SHARE_IN_DFS_ARG) InputBuffer;
NTSTATUS Status = STATUS_SUCCESS;
PVOID pDummyData = NULL; //not used
BOOLEAN NotUsed = FALSE; //not used
UNICODE_STRING Suffix; //not used
UNICODE_STRING ShareName;
KPROCESSOR_MODE PreviousMode;
DFS_TRACE_LOW(KUMR_DETAIL, "Fsctrl is share in DFS\n");
ExAcquireResourceSharedLite(&DfsGlobalData.Resource, TRUE);
RtlInitUnicodeString(&ShareName, NULL);
//
// This can only be called from Kernel mode.
//
PreviousMode = ExGetPreviousMode();
if (PreviousMode != KernelMode)
{
Status = STATUS_INVALID_PARAMETER;
goto Exit;
}
//
// Verify the buffer is at least of size DFS_IS_SHARE_IN_DFS_ARG
//
if (InputBufferLength < sizeof(DFS_IS_SHARE_IN_DFS_ARG))
{
Status = STATUS_INVALID_PARAMETER;
goto Exit;
}
if(pPrefixTable == NULL)
{
Status = STATUS_NO_SUCH_DEVICE;
goto Exit;
}
if (DfsGlobalData.CurrentProcessPointer != (PVOID)PsGetCurrentProcess())
{
Status = STATUS_INVALID_PARAMETER;
goto Exit;
}
ShareName = arg->ShareName;
if(ShareName.Buffer != NULL)
{
Status = DfsFindUnicodePrefix(pPrefixTable,
&ShareName,
&Suffix,
&pDummyData);
if(Status == STATUS_SUCCESS)
{
arg->ShareType = DFS_SHARE_TYPE_DFS_VOLUME;
arg->ShareType |= DFS_SHARE_TYPE_ROOT;
}
else
{
Status = STATUS_NO_SUCH_DEVICE;
}
}
else
{
RtlInitUnicodeString(&ShareName, NULL);
Status = STATUS_INVALID_USER_BUFFER;
}
Exit:
ExReleaseResourceLite(&DfsGlobalData.Resource);
DFS_TRACE_LOW(KUMR_DETAIL, "DfsFsctrlIsShareInDfs for shareName %wZ, Status %x\n",
&ShareName, Status );
return( Status );
}
#define UNICODE_PATH_SEP L'\\'
#define UNICODE_PATH_SEP_STR L"\\"
BOOLEAN
DfsConcatenateFilePath (
IN PUNICODE_STRING Dest,
IN PWSTR RemainingPath,
IN USHORT Length
) {
PWSTR OutBuf = (PWSTR)&(((PCHAR)Dest->Buffer)[Dest->Length]);
if (Dest->Length > 0) {
ASSERT(OutBuf[-1] != UNICODE_NULL);
}
if (Dest->Length > 0 && OutBuf[-1] != UNICODE_PATH_SEP) {
*OutBuf++ = UNICODE_PATH_SEP;
Dest->Length += sizeof (WCHAR);
}
if (Length > 0 && *RemainingPath == UNICODE_PATH_SEP) {
RemainingPath++;
Length -= sizeof (WCHAR);
}
ASSERT(Dest->MaximumLength >= (USHORT)(Dest->Length + Length));
if (Length > 0) {
RtlMoveMemory(OutBuf, RemainingPath, Length);
Dest->Length += Length;
}
return TRUE;
}
void
RemoveLastComponent(
PUNICODE_STRING Prefix,
PUNICODE_STRING newPrefix,
BOOL StripTrailingSlahes
)
{
PWCHAR pwch;
USHORT i=0;
*newPrefix = *Prefix;
pwch = newPrefix->Buffer;
pwch += (Prefix->Length/sizeof(WCHAR)) - 1;
while ((*pwch != UNICODE_PATH_SEP) && (pwch != newPrefix->Buffer))
{
i += sizeof(WCHAR);
pwch--;
}
newPrefix->Length = newPrefix->Length - i;
if(StripTrailingSlahes)
{
while ((*pwch == UNICODE_PATH_SEP) && (pwch != newPrefix->Buffer))
{
newPrefix->Length -= sizeof(WCHAR);
pwch--;
}
}
}
NTSTATUS
DfspFormPrefix(
IN PUNICODE_STRING ParentPath,
IN PUNICODE_STRING DfsPathName,
IN OUT PUNICODE_STRING Prefix)
{
NTSTATUS Status = STATUS_SUCCESS;
ULONG SizeRequired = 0;
//
// RtlAppend below expects this to be zero
// in order for the logic to work.
//
Prefix->Length = 0;
SizeRequired = sizeof(UNICODE_PATH_SEP) +
ParentPath->Length +
sizeof(UNICODE_PATH_SEP) +
DfsPathName->Length;
if (SizeRequired > MAXUSHORT)
{
Status = STATUS_INSUFFICIENT_RESOURCES;
return Status;
}
if (SizeRequired > Prefix->MaximumLength)
{
Prefix->MaximumLength = (USHORT)SizeRequired;
Prefix->Buffer = ExAllocatePoolWithTag(NonPagedPool, SizeRequired, ' sfD');
}
if (Prefix->Buffer != NULL)
{
RtlAppendUnicodeToString(
Prefix,
UNICODE_PATH_SEP_STR);
if (ParentPath->Length > 0)
{
DfsConcatenateFilePath(
Prefix,
ParentPath->Buffer,
(USHORT) (ParentPath->Length));
}
DfsConcatenateFilePath(
Prefix,
DfsPathName->Buffer,
DfsPathName->Length);
Status = STATUS_SUCCESS;
}
else
{
Status = STATUS_INSUFFICIENT_RESOURCES;
}
return Status;
}
NTSTATUS
DfsGetPathComponentsPriv(
PUNICODE_STRING pName,
PUNICODE_STRING pServerName,
PUNICODE_STRING pShareName,
PUNICODE_STRING pRemaining)
{
USHORT i = 0, j;
DFSSTATUS Status = STATUS_INVALID_PARAMETER;
RtlInitUnicodeString(pServerName, NULL);
if (pShareName) RtlInitUnicodeString(pShareName, NULL);
if (pRemaining) RtlInitUnicodeString(pRemaining, NULL);
for (; i < pName->Length/sizeof(WCHAR); i++) {
if (pName->Buffer[i] != UNICODE_PATH_SEP) {
break;
}
}
for (j = i; j < pName->Length/sizeof(WCHAR); j++) {
if (pName->Buffer[j] == UNICODE_PATH_SEP) {
break;
}
}
if (j != i) {
pServerName->Buffer = &pName->Buffer[i];
pServerName->Length = (USHORT)((j - i) * sizeof(WCHAR));
pServerName->MaximumLength = pServerName->Length;
Status = STATUS_SUCCESS;
}
for (i = j; i < pName->Length/sizeof(WCHAR); i++) {
if (pName->Buffer[i] != UNICODE_PATH_SEP) {
break;
}
}
for (j = i; j < pName->Length/sizeof(WCHAR); j++) {
if (pName->Buffer[j] == UNICODE_PATH_SEP) {
break;
}
}
if ((pShareName) && (j != i)) {
pShareName->Buffer = &pName->Buffer[i];
pShareName->Length = (USHORT)((j - i) * sizeof(WCHAR));
pShareName->MaximumLength = pShareName->Length;
}
for (i = j; i < pName->Length/sizeof(WCHAR); i++) {
if (pName->Buffer[i] != UNICODE_PATH_SEP) {
break;
}
}
j = pName->Length/sizeof(WCHAR);
if (pRemaining)
{
pRemaining->Buffer = &pName->Buffer[i];
}
if ((pRemaining) && (j != i)) {
pRemaining->Length = (USHORT)((j - i) * sizeof(WCHAR));
pRemaining->MaximumLength = pRemaining->Length;
}
return Status;
}
NTSTATUS
DfsFsctrlTranslatePath(
IN PVOID InputBuffer,
IN ULONG InputBufferLength)
{
NTSTATUS Status = STATUS_SUCCESS;
PDFS_TRANSLATE_PATH_ARG arg = (PDFS_TRANSLATE_PATH_ARG) InputBuffer;
WCHAR nameBuffer[MAX_PATH];
UNICODE_STRING prefix;
UNICODE_STRING ServerName;
UNICODE_STRING ShareName;
UNICODE_STRING RemainingName;
UNICODE_STRING LastComponent;
KPROCESSOR_MODE PreviousMode;
DFS_TRACE_LOW(KUMR_DETAIL, "Fsctrl translate path\n");
PreviousMode = ExGetPreviousMode();
if (PreviousMode != KernelMode) {
Status = STATUS_INVALID_PARAMETER;
return Status;
}
if(InputBufferLength < sizeof(DFS_TRANSLATE_PATH_ARG))
{
Status = STATUS_INVALID_USER_BUFFER;
return Status;
}
RtlZeroMemory( &prefix, sizeof(prefix) );
prefix.Length = 0;
prefix.MaximumLength = sizeof( nameBuffer );
prefix.Buffer = nameBuffer;
Status = DfspFormPrefix(
&arg->ParentPathName,
&arg->DfsPathName,
&prefix);
DFS_TRACE_LOW(KUMR_DETAIL, "Fsctrl translate path: arg->DfsPathName is %wZ\n",
&arg->DfsPathName);
if (NT_SUCCESS(Status))
{
DFS_TRACE_LOW(KUMR_DETAIL, "Fsctrl translate path: Total Path is %wZ\n",
&prefix);
if (arg->Flags & DFS_TRANSLATE_STRIP_LAST_COMPONENT)
{
LastComponent = prefix;
RemoveLastComponent(&LastComponent, &prefix, FALSE);
LastComponent.Length -= prefix.Length;
LastComponent.MaximumLength -= prefix.Length;
LastComponent.Buffer += (prefix.Length / sizeof(WCHAR));
DFS_TRACE_LOW(KUMR_DETAIL, "Fsctrl translate path: new Total Path is %wZ, LastComp is %wZ\n",
&prefix, &LastComponent);
}
DfsGetPathComponentsPriv(&prefix, &ServerName, &ShareName, &RemainingName);
DFS_TRACE_LOW(KUMR_DETAIL, "Fsctrl translate path: TotalPath is %wZ, RemainingName is %wZ\n",
&prefix, &RemainingName);
Status = DfsCheckReparse( &arg->SubDirectory,
&RemainingName );
//
// For DfsPathName which is relative to some parent
// path, we don't need to adjust the DfsPathName
//
if (arg->ParentPathName.Length == 0)
{
if (arg->Flags & DFS_TRANSLATE_STRIP_LAST_COMPONENT)
{
if (RemainingName.Length == 0)
{
RemainingName.Buffer = LastComponent.Buffer;
}
RemainingName.Length += LastComponent.Length;
}
arg->DfsPathName.Length = RemainingName.Length;
if (RemainingName.Length > 0)
{
RtlMoveMemory(
arg->DfsPathName.Buffer,
RemainingName.Buffer,
RemainingName.Length);
}
arg->DfsPathName.Buffer[
arg->DfsPathName.Length/sizeof(WCHAR)] = UNICODE_NULL;
}
}
if (prefix.Buffer != NULL && prefix.Buffer != nameBuffer)
{
ExFreePool( prefix.Buffer );
}
DFS_TRACE_LOW(KUMR_DETAIL, "Fsctrl translate path Parent Path %wZ, DfsPathName %wZ, Status %x\n",
&arg->ParentPathName, &arg->DfsPathName, Status);
return Status;
}
//+-------------------------------------------------------------------------
//
// Function: DfsCheckParse - check if the path crosses a dfs link.
//
// Arguments:
// PUNICODE_STRING pParent - the shared out directory.
// PUNICODE_STRING pName - the directory hierarchy relative to parent.
//
// Returns: Status
// ERROR_PATH_NOT_COVERED - if link
// ERROR_SUCCESS - otherwise.
//
// Description: This routine currently opens the passed in file, and
// returns the open status if it is PATH_NOT_COVERED.
// Otherwise it return STATUS_SUCCESS.
//
//
// This should not have been necessary. When the server
// gets a query path from the client, it calls DFS to
// see if this is a link. however, in this new dfs, we
// use reparse points, so this mechanism of the server
// querying DFS should not be necessary. The server should
// get STATUS_PATH_NOT_COVERED during the query path, and
// return that to the client.
//
// It turns out that the server (including an io manager api)
// do a create file with FILE_OPEN_REPARSE_POINT when getting
// the file attributes. This completely bypasses the DFS
// mechanism of returning STATUS_PATH_NOT_COVERED, so the
// query path actually succeeds even for links!
// This results in the client coming in with a findfirst
// which fails, and for some reason that failure does not
// result in the DFS on the client attempting to get
// referrals.
//
// All of the above needs investigation and fixing.
// This code will work in the meanwhile. Its not very
// effective on performance to have this code.
//
//--------------------------------------------------------------------------
NTSTATUS
DfsCheckReparse(
PUNICODE_STRING pParent,
PUNICODE_STRING pName )
{
OBJECT_ATTRIBUTES ObjectAttributes;
NTSTATUS Status;
HANDLE ParentHandle, Handle;
IO_STATUS_BLOCK IoStatus;
InitializeObjectAttributes(
&ObjectAttributes,
pParent,
OBJ_CASE_INSENSITIVE,
NULL,
NULL);
Status = ZwCreateFile( &ParentHandle,
FILE_READ_ATTRIBUTES,
&ObjectAttributes,
&IoStatus,
NULL,
FILE_ATTRIBUTE_NORMAL,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
FILE_OPEN,
FILE_SYNCHRONOUS_IO_NONALERT,
NULL,
0);
if (Status == STATUS_SUCCESS)
{
InitializeObjectAttributes(
&ObjectAttributes,
pName,
OBJ_CASE_INSENSITIVE,
ParentHandle,
NULL);
Status = ZwCreateFile( &Handle,
FILE_READ_ATTRIBUTES,
&ObjectAttributes,
&IoStatus,
NULL,
FILE_ATTRIBUTE_NORMAL,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
FILE_OPEN,
FILE_SYNCHRONOUS_IO_NONALERT,
NULL,
0);
ZwClose( ParentHandle );
}
DFS_TRACE_LOW(KUMR_DETAIL, "DfsCheckreparse for ParentName %wZ, pName %wZ, Status %x\n",
pParent, pName, Status );
if (Status == STATUS_SUCCESS)
{
ZwClose(Handle);
}
else if (Status != STATUS_PATH_NOT_COVERED)
{
Status = STATUS_SUCCESS;
}
return Status;
}
NTSTATUS
DfsInitializeDriver( IN PVOID InputBuffer,
IN ULONG InputBufferLength)
{
NTSTATUS Status = STATUS_SUCCESS;
PDFS_FILTER_STARTUP_INFO pStartupInfo = (PDFS_FILTER_STARTUP_INFO) InputBuffer;
PAGED_CODE();
ACQUIRE_GLOBAL_LOCK();
if(DfsGlobalData.ServiceProcess != IoGetCurrentProcess())
{
Status = STATUS_ACCESS_DENIED;
DFS_TRACE_ERROR_HIGH(Status, KUMR_DETAIL, "DfsInitializeDriver service not attached %x\n", Status);
goto Exit;
}
if(DfsGlobalData.Started == TRUE)
{
Status = STATUS_ACCESS_DENIED;
DFS_TRACE_ERROR_HIGH(Status, KUMR_DETAIL, "DfsInitializeDriver service already started %x\n", Status);
goto Exit;
}
DfsGlobalData.Started = TRUE;
//see if the raw inputs are valid
if( (InputBuffer == NULL) ||
(InputBufferLength <= 0) ||
(InputBufferLength < sizeof(DFS_FILTER_STARTUP_INFO)))
{
Status = STATUS_INVALID_PARAMETER;
DFS_TRACE_ERROR_HIGH(Status, KUMR_DETAIL, "DfsInitializeDriver buffer length checks failed %x\n", Status);
goto Exit;
}
if(!pPrefixTable)
{
DfsGlobalData.IsDC = pStartupInfo->IsDC;
Status = DfsInitializePrefixTable(&pPrefixTable, FALSE, NULL);
if (Status == STATUS_SUCCESS)
{
Status = DfsStartupUMRx();
DFS_TRACE_LOW(KUMR_DETAIL, "DfsInitializeDriver - DfsStartupUMRx returned Status %x\n", Status);
}
}
gfRundownPrefixCompleted = FALSE;
Exit:
RELEASE_GLOBAL_LOCK();
DFS_TRACE_LOW(KUMR_DETAIL, "DfsInitializeDriver returned Status %x\n", Status);
return Status;
}
NTSTATUS
DfsDeInitializeDriver( IN PVOID InputBuffer,
IN ULONG InputBufferLength)
{
NTSTATUS Status = STATUS_SUCCESS;
Status = DfsIsServiceAttached();
if(Status == STATUS_SUCCESS)
{
Status = DfsTeardownUMRx();
ACQUIRE_GLOBAL_LOCK();
Status = DfsRunDownPrefixTable();
RELEASE_GLOBAL_LOCK();
}
return Status;
}
/*++
Routine Description:
This routine is invoked whenever an I/O Request Packet (IRP) w/a major
function code of IRP_MJ_FILE_SYSTEM_CONTROL is encountered for the DFS device.
Arguments:
DeviceObject - Pointer to the device object for this driver.
Irp - Pointer to the request packet representing the I/O request.
Return Value:
The function value is the status of the operation.
--*/
NTSTATUS
DfsHandlePrivateFsControl (
IN PDEVICE_OBJECT DeviceObject,
IN ULONG IoControlCode,
IN PVOID InputBuffer OPTIONAL,
IN ULONG InputBufferLength,
OUT PVOID OutputBuffer OPTIONAL,
IN ULONG OutputBufferLength,
OUT PIO_STATUS_BLOCK IoStatus,
IN PIRP Irp )
{
NTSTATUS Status = STATUS_INVALID_DEVICE_REQUEST;
PAGED_CODE();
DFS_TRACE_LOW(KUMR_DETAIL, "Handle Fs control, code: %x\n",
IoControlCode);
//
// Need to disable Kernel APC delivery
//
FsRtlEnterFileSystem();
IoStatus->Information = 0;
switch(IoControlCode)
{
case DFSFILTER_START_UMRX:
Status = DfsInitializeDriver(InputBuffer,
InputBufferLength);
break;
case DFSFILTER_STOP_UMRX:
Status = DfsDeInitializeDriver(InputBuffer,
InputBufferLength);
break;
case DFSFILTER_PROCESS_UMRXPACKET:
if(DfsIsServiceAttached() == STATUS_SUCCESS)
{
Status = DfsProcessUMRxPacket(
InputBuffer,
InputBufferLength,
OutputBuffer,
OutputBufferLength,
IoStatus);
}
break;
case FSCTL_DFS_GET_REFERRALS:
Status = DfsFsctrlGetReferrals(
InputBuffer,
InputBufferLength,
OutputBuffer,
OutputBufferLength,
Irp,
IoStatus);
break;
case FSCTL_DFS_REPORT_INCONSISTENCY:
Status = STATUS_SUCCESS;
break;
case FSCTL_DFS_TRANSLATE_PATH:
Status = DfsFsctrlTranslatePath(InputBuffer, InputBufferLength);
break;
case FSCTL_DFS_IS_ROOT:
Status = STATUS_SUCCESS;
break;
case FSCTL_DFS_IS_SHARE_IN_DFS:
Status = DfsFsctrlIsShareInDfs(InputBuffer,InputBufferLength );
break;
case FSCTL_DFS_FIND_SHARE:
Status = DfsCheckDfsShare( InputBuffer,
InputBufferLength,
Irp,
IoStatus );
break;
case DFSFILTER_ATTACH_FILESYSTEM:
Status = DfsHandleAttachToFs(InputBuffer, InputBufferLength);
break;
case DFSFILTER_DETACH_FILESYSTEM:
Status = DfsHandleDetachFromFs(InputBuffer, InputBufferLength);
break;
case FSCTL_DFS_START_DFS:
Status = STATUS_SUCCESS;
break;
case FSCTL_DFS_STOP_DFS:
Status = STATUS_SUCCESS;
break;
case FSCTL_DFS_GET_VERSION:
if (OutputBuffer != NULL &&
OutputBufferLength >= sizeof(DFS_GET_VERSION_ARG))
{
PDFS_GET_VERSION_ARG parg =
(PDFS_GET_VERSION_ARG) OutputBuffer;
parg->Version = 2;
Status = STATUS_SUCCESS;
IoStatus->Information = sizeof(DFS_GET_VERSION_ARG);
}
else
{
Status = STATUS_INVALID_PARAMETER;
}
break;
default:
break;
}
IoStatus->Status = Status;
if(Irp != NULL)
{
IoCompleteRequest( Irp, IO_NO_INCREMENT );
}
//
// Re-enable Kernel APC delivery now.
//
FsRtlExitFileSystem();
DFS_TRACE_LOW(KUMR_DETAIL, "Handle Fs control, code: %x, Status %x\n",
IoControlCode, Status);
return Status;
}
/*++
Routine Description:
This routine is invoked whenever an I/O Request Packet (IRP) w/a major
function code of IRP_MJ_FILE_SYSTEM_CONTROL is encountered. For most
IRPs of this type, the packet is simply passed through. However, for
some requests, special processing is required.
Arguments:
DeviceObject - Pointer to the device object for this driver.
Irp - Pointer to the request packet representing the I/O request.
Return Value:
The function value is the status of the operation.
--*/
NTSTATUS
DfsFilterFsControl (
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp )
{
NTSTATUS status = STATUS_SUCCESS;
ULONG Operation = 0;
ULONG OutputBufferLength = 0;
ULONG InputBufferLength = 0;
PVOID InputBuffer = NULL;
PVOID OutputBuffer = NULL;
PDFS_FILTER_DEVICE_EXTENSION devExt = DeviceObject->DeviceExtension;
PDEVICE_OBJECT newDeviceObject = NULL;
PDFS_FILTER_DEVICE_EXTENSION newDevExt = NULL;
PIO_STACK_LOCATION irpSp = IoGetCurrentIrpStackLocation( Irp );
PVPB vpb;
KEVENT waitEvent;
PAGED_CODE();
VALIDATE_IRQL(Irp);
//
// If this is for our control device object
//
if (IS_MY_CONTROL_DEVICE_OBJECT(DeviceObject))
{
Operation = irpSp->Parameters.FileSystemControl.FsControlCode;
InputBufferLength = irpSp->Parameters.FileSystemControl.InputBufferLength;
OutputBufferLength = irpSp->Parameters.FileSystemControl.OutputBufferLength;
InputBuffer = Irp->AssociatedIrp.SystemBuffer;
OutputBuffer = Irp->AssociatedIrp.SystemBuffer;
status = DfsHandlePrivateFsControl (DeviceObject,
Operation,
InputBuffer,
InputBufferLength,
OutputBuffer,
OutputBufferLength,
&Irp->IoStatus,
Irp );
return status;
}
ASSERT(IS_MY_DEVICE_OBJECT( DeviceObject ));
//
// Begin by determining the minor function code for this file system control
// function.
//
if ((irpSp->MinorFunction == IRP_MN_MOUNT_VOLUME))
{
//
// We are processing a MOUNT/VERIFY request being directed to
// another File System to which we have attached our own
// Attach File System Object. We setup a completion routine
// and forward the request.
//
IoCopyCurrentIrpStackLocationToNext( Irp );
//
// We want to pass the real device to our completion routine
// so we can attach to the proper remounted device.
IoSetCompletionRoutine(
Irp,
DfsCompleteMountRequest,
irpSp->Parameters.MountVolume.Vpb->RealDevice,
TRUE,
TRUE,
TRUE);
//
// Call the underlying file system via its file system device
//
status = IoCallDriver( devExt->pAttachedToDeviceObject, Irp );
DFS_TRACE_ERROR_HIGH(status, KUMR_DETAIL, "Mount Request processed\n");
return status;
} else if (irpSp->MinorFunction == IRP_MN_LOAD_FILE_SYSTEM) {
//
// This is a "load file system" request being sent to a file system
// recognizer device object.
//
// NOTE: Since we no longer are attaching to the standard
// Microsoft file system recognizers (see
// SfAttachToFileSystemDevice) we will normally never execute
// this code. However, there might be 3rd party file systems
// which have their own recognizer which may still trigger this
// IRP.
//
//
// Set a completion routine so we can delete the device object when
// the load is complete.
//
KeInitializeEvent( &waitEvent, SynchronizationEvent, FALSE );
IoCopyCurrentIrpStackLocationToNext( Irp );
IoSetCompletionRoutine( Irp,
DfsLoadFsCompletion,
&waitEvent,
TRUE,
TRUE,
TRUE );
//
// Detach from the file system recognizer device object.
//
IoDetachDevice( devExt->pAttachedToDeviceObject );
//
// Call the driver
//
status = IoCallDriver( devExt->pAttachedToDeviceObject, Irp );
//
// Wait for the completion routine to be called
//
if (STATUS_PENDING == status) {
NTSTATUS localStatus = KeWaitForSingleObject(&waitEvent, Executive, KernelMode, FALSE, NULL);
ASSERT(STATUS_SUCCESS == localStatus);
}
DbgPrint( "DFSFILTER: Detaching from recognizer status=%08x\n",
Irp->IoStatus.Status );
//
// Check status of the operation
//
if (!NT_SUCCESS( Irp->IoStatus.Status )) {
//
// The load was not successful. Simply reattach to the recognizer
// driver in case it ever figures out how to get the driver loaded
// on a subsequent call.
//
IoAttachDeviceToDeviceStack( DeviceObject, devExt->pAttachedToDeviceObject );
} else {
//
// The load was successful, delete the Device object
//
IoDeleteDevice( DeviceObject );
}
//
// Continue processing the operation
//
status = Irp->IoStatus.Status;
IoCompleteRequest( Irp, IO_NO_INCREMENT );
return status;
} else {
//
// Simply pass this file system control request through.
//
IoSkipCurrentIrpStackLocation( Irp );
}
//
// Any special processing has been completed, so simply pass the request
// along to the next driver.
//
return IoCallDriver( devExt->pAttachedToDeviceObject, Irp );
}
NTSTATUS
DfsGetDeviceObjectFromName (
IN PUNICODE_STRING DeviceName,
OUT PDEVICE_OBJECT *DeviceObject
)
{
NTSTATUS Status = STATUS_SUCCESS;
HANDLE fileHandle = NULL;
PFILE_OBJECT volumeFileObject = NULL;
PDEVICE_OBJECT nextDeviceObject =NULL;
OBJECT_ATTRIBUTES objectAttributes;
IO_STATUS_BLOCK openStatus;
InitializeObjectAttributes( &objectAttributes,
DeviceName,
OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
NULL,
NULL);
//
// open the file object for the given device
//
Status = ZwCreateFile( &fileHandle,
SYNCHRONIZE|FILE_READ_DATA,
&objectAttributes,
&openStatus,
NULL,
0,
FILE_SHARE_READ|FILE_SHARE_WRITE,
FILE_OPEN,
FILE_SYNCHRONOUS_IO_NONALERT,
NULL,
0);
if(!NT_SUCCESS( Status )) {
DFS_TRACE_ERROR_HIGH(Status, KUMR_DETAIL, "DfsGetDeviceObjectFromName ZwCreateFile failed %x\n", Status);
return Status;
}
//
// get a pointer to the volumes file object
//
Status = ObReferenceObjectByHandle( fileHandle,
FILE_READ_DATA,
*IoFileObjectType,
KernelMode,
&volumeFileObject,
NULL);
if(!NT_SUCCESS( Status ))
{
ZwClose( fileHandle );
DFS_TRACE_ERROR_HIGH(Status, KUMR_DETAIL, "DfsGetDeviceObjectFromName ObReferenceObjectByHandle failed %x\n", Status);
return Status;
}
//
// Get the device object we want to attach to (parent device object in chain)
//
nextDeviceObject = IoGetRelatedDeviceObject( volumeFileObject );
if (nextDeviceObject == NULL) {
ObDereferenceObject( volumeFileObject );
ZwClose( fileHandle );
Status = STATUS_NO_SUCH_DEVICE;
DFS_TRACE_ERROR_HIGH(Status, KUMR_DETAIL, "DfsGetDeviceObjectFromName IoGetRelatedDeviceObject failed %x\n", Status);
return STATUS_NO_SUCH_DEVICE;
}
ObDereferenceObject( volumeFileObject );
ZwClose( fileHandle );
ASSERT( NULL != DeviceObject );
ObReferenceObject( nextDeviceObject );
*DeviceObject = nextDeviceObject;
return STATUS_SUCCESS;
}
LPWSTR DfsDeviceString = L"\\??\\x:\\";
NTSTATUS
DfsAttachToFileSystem (
IN PWSTR UserDeviceName )
{
NTSTATUS Status = STATUS_SUCCESS;
PDEVICE_OBJECT NextDeviceObject = NULL;
PDEVICE_OBJECT DiskDeviceObject = NULL;
PDEVICE_OBJECT DfsDeviceObject = NULL;
PDEVICE_OBJECT BaseFileSystemDeviceObject = NULL;
PDFS_FILTER_DEVICE_EXTENSION pDeviceExt = NULL;
PDFS_VOLUME_INFORMATION pDfsVolume;
UNICODE_STRING DeviceName;
DFS_TRACE_LOW(KUMR_DETAIL, "DfsAttachToFileSystem %ws\n",
UserDeviceName);
RtlInitUnicodeString( &DeviceName, UserDeviceName );
DeviceName.Length = wcslen(DfsDeviceString) * sizeof(WCHAR);
Status = DfsGetDeviceObjectFromName (&DeviceName, &NextDeviceObject);
if (!NT_SUCCESS( Status ))
{
DFS_TRACE_ERROR_HIGH(Status, KUMR_DETAIL, "DfsAttachToFileSystem DfsGetDeviceObjectFromName failed %x\n", Status);
return Status;
}
if(!DfsAttachedToDevice(NextDeviceObject, &DfsDeviceObject))
{
//
// We want to attach to this file system. Create a new device object we
// can attach with.
//
Status = IoCreateDevice( DfsGlobalData.pFilterDriverObject,
sizeof( DFS_FILTER_DEVICE_EXTENSION ),
NULL,
NextDeviceObject->DeviceType,
0,
FALSE,
&DfsDeviceObject );
if (!NT_SUCCESS( Status ))
{
DFS_TRACE_ERROR_HIGH(Status, KUMR_DETAIL, "DfsAttachToFileSystem IoCreateDevice failed %x\n", Status);
return Status;
}
//
// Get the disk device object associated with this file system
// device object. Only try to attach if we have a disk device object.
// It may not have a disk device object for the following reasons:
// - It is a control device object for a driver
// - There is no media in the device.
//
// We first have to get the base file system device object. After
// using it we remove the refrence by the call.
//
BaseFileSystemDeviceObject = IoGetDeviceAttachmentBaseRef( NextDeviceObject );
Status = IoGetDiskDeviceObject( BaseFileSystemDeviceObject, &DiskDeviceObject );
ObDereferenceObject( BaseFileSystemDeviceObject );
if (NT_SUCCESS(Status)) {
ObDereferenceObject( DiskDeviceObject );
Status = DfsGetDfsVolume( &DeviceName,
&pDfsVolume );
}
if (NT_SUCCESS(Status))
{
pDeviceExt = DfsDeviceObject->DeviceExtension;
//
// Call the routine to attach to a mounted device.
//
Status = IoAttachDeviceToDeviceStackSafe( DfsDeviceObject,
NextDeviceObject,
&pDeviceExt->pAttachedToDeviceObject );
if (NT_SUCCESS(Status))
{
pDeviceExt->Attached = TRUE;
pDeviceExt->pDfsVolume = pDfsVolume;
pDeviceExt->pThisDeviceObject = DfsDeviceObject;
InterlockedIncrement(&pDfsVolume->RefCount);
pDfsVolume->DiskDeviceObject = DiskDeviceObject;
//
// We are done initializing this device object, so
// clear the DO_DEVICE_OBJECT_INITIALIZING flag.
//
ClearFlag( DfsDeviceObject->Flags, DO_DEVICE_INITIALIZING );
}
}
if (!NT_SUCCESS(Status))
{
IoDeleteDevice( DfsDeviceObject);
}
}
else
{
pDeviceExt = DfsDeviceObject->DeviceExtension;
pDfsVolume = pDeviceExt->pDfsVolume;
if (pDfsVolume != NULL) {
InterlockedIncrement(&pDfsVolume->RefCount);
}
}
ObDereferenceObject( NextDeviceObject );
DFS_TRACE_LOW(KUMR_DETAIL, "DfsAttachToFileSystem %ws, Status %x\n",
UserDeviceName, Status);
return Status;
}
NTSTATUS
DfsDetachFromFileSystem (
IN PWSTR UserDeviceName
)
{
NTSTATUS Status = STATUS_SUCCESS;
PDEVICE_OBJECT DeviceObject = NULL;
PDFS_VOLUME_INFORMATION pDfsVolume;
PDFS_FILTER_DEVICE_EXTENSION Devext = NULL;
UNICODE_STRING DeviceName;
ACQUIRE_GLOBAL_LOCK();
DFS_TRACE_LOW(KUMR_DETAIL, "DfsDetachFromFileSystem %ws\n",
UserDeviceName);
RtlInitUnicodeString( &DeviceName, UserDeviceName );
DeviceName.Length = wcslen(DfsDeviceString) * sizeof(WCHAR);
Status = DfsFindDfsVolumeByName( &DeviceName, &pDfsVolume);
if (NT_SUCCESS( Status ))
{
InterlockedDecrement(&pDfsVolume->RefCount);
}
RELEASE_GLOBAL_LOCK();
DFS_TRACE_LOW(KUMR_DETAIL, "DfsDetachFromFileSystem %ws, Status %x\n",
UserDeviceName, Status);
return Status;
}
NTSTATUS
DfsFindAndRemovePrefixEntry(PWSTR ShareString)
{
NTSTATUS Status = STATUS_SUCCESS;
PWSTR VolumeName = NULL;
PWSTR OldValue = NULL;
UNICODE_STRING ShareName;
UNICODE_STRING Suffix;
RtlInitUnicodeString(&ShareName, ShareString);
Status = DfsRemoveFromPrefixTableEx(pPrefixTable,
&ShareName,
(PVOID)VolumeName,
&OldValue);
if(OldValue)
{
ExFreePool(OldValue);
}
return Status;
}
VOID
DfsDetachFilterDevice(
PDEVICE_OBJECT DfsDevice,
PDEVICE_OBJECT TargetDevice)
{
PDFS_FILTER_DEVICE_EXTENSION pDeviceExt = NULL;
FsRtlEnterFileSystem();
ACQUIRE_GLOBAL_LOCK();
pDeviceExt = DfsDevice->DeviceExtension;
IoDetachDevice(TargetDevice);
pDeviceExt->Attached = FALSE;
if (pDeviceExt->pDfsVolume)
{
pDeviceExt->pDfsVolume = NULL;
}
IoDeleteDevice(DfsDevice);
RELEASE_GLOBAL_LOCK();
FsRtlExitFileSystem();
}
NTSTATUS
DfsHandleAttachToFs(PVOID InputBuffer, ULONG InputBufferLength)
{
NTSTATUS Status = STATUS_SUCCESS;
NTSTATUS DummyStatus = STATUS_SUCCESS;
PWSTR DeviceName = NULL;
BOOL ShareInserted = FALSE;
PDFS_ATTACH_PATH_BUFFER pAttachBuffer = (PDFS_ATTACH_PATH_BUFFER)InputBuffer;
UNICODE_STRING ShareName ;
UNICODE_STRING VolumeName;
DFS_TRACE_LOW(KUMR_DETAIL, "Dfshandleattachtofs\n");
ACQUIRE_GLOBAL_LOCK();
RtlInitUnicodeString(&ShareName, NULL);
RtlInitUnicodeString(&VolumeName, NULL);
if(DfsGlobalData.ServiceProcess != IoGetCurrentProcess())
{
Status = STATUS_ACCESS_DENIED;
DFS_TRACE_ERROR_HIGH(Status, KUMR_DETAIL, "DfsHandleAttachToFs - unauthorized process %x\n", Status);
goto Exit;
}
//see if the raw inputs are valid
if( (InputBuffer == NULL) ||
(InputBufferLength <= 0) ||
(InputBufferLength < sizeof(DFS_ATTACH_PATH_BUFFER)) ||
(pPrefixTable == NULL))
{
Status = STATUS_INVALID_PARAMETER;
DFS_TRACE_ERROR_HIGH(Status, KUMR_DETAIL, "DfsHandleAttachToFs buffer length checks failed %x\n", Status);
goto Exit;
}
//get the real inputs
VolumeName.Buffer = pAttachBuffer->PathNameBuffer;
VolumeName.Length = VolumeName.MaximumLength = (USHORT) pAttachBuffer->VolumeNameLength;
ShareName.Buffer = VolumeName.Buffer + (pAttachBuffer->VolumeNameLength / sizeof(WCHAR));
ShareName.Length= ShareName.MaximumLength = (USHORT) pAttachBuffer->ShareNameLength;
// Now see if the embedded inputs are valid
if ( (pAttachBuffer->VolumeNameLength > InputBufferLength) ||
(pAttachBuffer->ShareNameLength > InputBufferLength) ||
(pAttachBuffer->ShareNameLength < sizeof(WCHAR)) ||
((FIELD_OFFSET(DFS_ATTACH_PATH_BUFFER,PathNameBuffer) +
pAttachBuffer->VolumeNameLength +
pAttachBuffer->ShareNameLength) > InputBufferLength))
{
Status = STATUS_INVALID_PARAMETER;
DFS_TRACE_ERROR_HIGH(Status, KUMR_DETAIL, "DfsHandleAttachToFs embedded inputs failed %x\n", Status);
goto Exit;
}
DeviceName = ExAllocatePool( NonPagedPool, VolumeName.Length + sizeof(WCHAR) );
if (DeviceName == NULL)
{
Status = STATUS_INSUFFICIENT_RESOURCES;
DFS_TRACE_ERROR_HIGH(Status, KUMR_DETAIL, "DfsHandleAttachToFs pool allocate failed %x\n", Status);
goto Exit;
}
if(VolumeName.Length != 0)
{
RtlCopyMemory( DeviceName, VolumeName.Buffer, VolumeName.Length );
}
DeviceName[VolumeName.Length / sizeof(WCHAR)] = UNICODE_NULL;
Status = DfsInsertInPrefixTable(pPrefixTable,
&ShareName,
(PVOID)DeviceName);
if(Status != STATUS_SUCCESS)
{
DFS_TRACE_ERROR_HIGH(Status, KUMR_DETAIL, "DfsHandleAttachToFs DfsInsertInPrefixTable2 returned error %x\n", Status);
goto Exit;
}
ShareInserted = TRUE;
if(VolumeName.Length != 0)
{
Status = DfsAttachToFileSystem (DeviceName);
if(Status != STATUS_SUCCESS)
{
DFS_TRACE_ERROR_HIGH(Status, KUMR_DETAIL, "DfsHandleAttachToFs DfsAttachToFileSystem returned error %x\n", Status);
}
}
Exit:
if(Status != STATUS_SUCCESS)
{
if(ShareInserted)
{
DummyStatus = DfsRemoveFromPrefixTable(pPrefixTable,
&ShareName,
(PVOID)DeviceName);
}
if (DeviceName != NULL)
{
ExFreePool( DeviceName );
}
}
RELEASE_GLOBAL_LOCK();
DFS_TRACE_LOW(KUMR_DETAIL, "Dfshandleattachtofs, Share %wZ, Volume %wZ, Status %x\n",
&ShareName, &VolumeName, Status);
return Status;
}
NTSTATUS
DfsHandleDetachFromFs(PVOID InputBuffer, ULONG InputBufferLength)
{
NTSTATUS Status = STATUS_SUCCESS;
NTSTATUS DummyStatus = STATUS_SUCCESS;
PWSTR DeviceName = NULL;
PWSTR OldValue = NULL;
PDFS_ATTACH_PATH_BUFFER pAttachBuffer = (PDFS_ATTACH_PATH_BUFFER)InputBuffer;
UNICODE_STRING ShareName ;
UNICODE_STRING VolumeName;
DFS_TRACE_LOW(KUMR_DETAIL, "Dfshandledetachfromfs\n");
ACQUIRE_GLOBAL_LOCK();
RtlInitUnicodeString(&ShareName, NULL);
RtlInitUnicodeString(&VolumeName, NULL);
if(DfsGlobalData.ServiceProcess != IoGetCurrentProcess())
{
Status = STATUS_ACCESS_DENIED;
DFS_TRACE_ERROR_HIGH(Status, KUMR_DETAIL, "DfsHandleDetachFromFs - unauthorized process %x\n", Status);
goto Exit;
}
//see if the raw inputs are valid
if( (InputBuffer == NULL) ||
(InputBufferLength <= 0) ||
(InputBufferLength < sizeof(DFS_ATTACH_PATH_BUFFER)) ||
(pPrefixTable == NULL))
{
Status = STATUS_INVALID_PARAMETER;
goto Exit;
}
//get the real inputs
VolumeName.Buffer = pAttachBuffer->PathNameBuffer;
VolumeName.Length = VolumeName.MaximumLength = (USHORT) pAttachBuffer->VolumeNameLength;
ShareName.Buffer = VolumeName.Buffer + (pAttachBuffer->VolumeNameLength / sizeof(WCHAR));
ShareName.Length= ShareName.MaximumLength = (USHORT) pAttachBuffer->ShareNameLength;
// Now see if the embedded inputs are valid
if ( (pAttachBuffer->VolumeNameLength > InputBufferLength) ||
(pAttachBuffer->ShareNameLength > InputBufferLength) ||
(pAttachBuffer->ShareNameLength < sizeof(WCHAR)) ||
((FIELD_OFFSET(DFS_ATTACH_PATH_BUFFER,PathNameBuffer) +
pAttachBuffer->VolumeNameLength +
pAttachBuffer->ShareNameLength) > InputBufferLength))
{
Status = STATUS_INVALID_PARAMETER;
goto Exit;
}
DeviceName = ExAllocatePool( NonPagedPool, VolumeName.Length + sizeof(WCHAR) );
if (DeviceName == NULL)
{
Status = STATUS_INSUFFICIENT_RESOURCES;
goto Exit;
}
if(VolumeName.Length != 0)
{
RtlCopyMemory( DeviceName, VolumeName.Buffer, VolumeName.Length );
}
DeviceName[VolumeName.Length / sizeof(WCHAR)] = UNICODE_NULL;
VolumeName.Buffer = DeviceName;
if(VolumeName.Length != 0)
{
Status = DfsDetachFromFileSystem (VolumeName.Buffer);
}
DFS_TRACE_LOW(KUMR_DETAIL, "Detach for %wZ, Status %x\n",
&VolumeName, Status );
Status = DfsRemoveFromPrefixTableEx(pPrefixTable,
&ShareName,
NULL,
&OldValue);
if(OldValue != NULL)
{
ExFreePool(OldValue);
}
Exit:
if (DeviceName != NULL)
{
ExFreePool( DeviceName );
}
RELEASE_GLOBAL_LOCK();
return Status;
}
NTSTATUS
DfsFindDfsVolumeByName(
PUNICODE_STRING pDeviceName,
PDFS_VOLUME_INFORMATION *ppDfsVolume)
{
NTSTATUS Status = STATUS_OBJECT_NAME_NOT_FOUND;
PLIST_ENTRY pListHead, pListNext;
PDFS_VOLUME_INFORMATION pDfsVolume;
*ppDfsVolume = NULL;
pListHead = &DfsGlobalData.DfsVolumeList;
pListNext = pListHead->Flink;
while (pListNext != pListHead)
{
pDfsVolume = CONTAINING_RECORD( pListNext,
DFS_VOLUME_INFORMATION,
VolumeList );
if (RtlCompareUnicodeString(pDeviceName,
&pDfsVolume->VolumeName,
TRUE) == 0) {
*ppDfsVolume = pDfsVolume;
Status = STATUS_SUCCESS;
break;
}
pListNext = pListNext->Flink;
}
return Status;
}
VOID
DfsReattachToMountedVolume(
PDEVICE_OBJECT pTargetDevice,
PDEVICE_OBJECT pDiskDevice )
{
PDEVICE_OBJECT DfsDeviceObject = NULL;
PDFS_FILTER_DEVICE_EXTENSION pDeviceExt = NULL;
PDFS_VOLUME_INFORMATION pDfsVolume = NULL;
NTSTATUS Status = STATUS_SUCCESS;
FsRtlEnterFileSystem();
ACQUIRE_GLOBAL_LOCK();
Status = DfsFindDfsVolumeByDiskDeviceObject( pDiskDevice,
&pDfsVolume );
if (Status == STATUS_SUCCESS)
{
Status = IoCreateDevice( DfsGlobalData.pFilterDriverObject,
sizeof( DFS_FILTER_DEVICE_EXTENSION ),
NULL,
pTargetDevice->DeviceType,
0,
FALSE,
&DfsDeviceObject );
if (NT_SUCCESS(Status))
{
pDeviceExt = DfsDeviceObject->DeviceExtension;
Status = IoAttachDeviceToDeviceStackSafe( DfsDeviceObject,
pTargetDevice,
&pDeviceExt->pAttachedToDeviceObject );
if (NT_SUCCESS(Status))
{
pDeviceExt->pDfsVolume = pDfsVolume;
pDeviceExt->Attached = TRUE;
pDeviceExt->pThisDeviceObject = DfsDeviceObject;
ClearFlag( DfsDeviceObject->Flags, DO_DEVICE_INITIALIZING );
}
else
{
IoDeleteDevice( DfsDeviceObject);
}
}
}
RELEASE_GLOBAL_LOCK();
FsRtlExitFileSystem();
return NOTHING;
}
NTSTATUS
DfsFindDfsVolumeByDiskDeviceObject(
PDEVICE_OBJECT pDiskDeviceObject,
PDFS_VOLUME_INFORMATION *ppDfsVolume )
{
NTSTATUS Status = STATUS_OBJECT_NAME_NOT_FOUND;
PLIST_ENTRY pListHead, pListNext;
PDFS_VOLUME_INFORMATION pDfsVolume;
*ppDfsVolume = NULL;
pListHead = &DfsGlobalData.DfsVolumeList;
pListNext = pListHead->Flink;
while (pListNext != pListHead)
{
pDfsVolume = CONTAINING_RECORD( pListNext,
DFS_VOLUME_INFORMATION,
VolumeList );
if (pDfsVolume->DiskDeviceObject == pDiskDeviceObject) {
*ppDfsVolume = pDfsVolume;
Status = STATUS_SUCCESS;
break;
}
pListNext = pListNext->Flink;
}
return Status;
}
NTSTATUS
DfsGetDfsVolume(
PUNICODE_STRING pName,
PDFS_VOLUME_INFORMATION *ppDfsVolume)
{
NTSTATUS Status;
PDFS_VOLUME_INFORMATION pDfsVolume;
Status = DfsFindDfsVolumeByName( pName, ppDfsVolume );
if (!NT_SUCCESS(Status))
{
pDfsVolume = ExAllocatePoolWithTag( PagedPool,
sizeof(DFS_VOLUME_INFORMATION) + pName->Length,
' sfD');
if (pDfsVolume == NULL) {
Status = STATUS_INSUFFICIENT_RESOURCES;
}
else
{
Status = STATUS_SUCCESS;
RtlZeroMemory( pDfsVolume, sizeof(DFS_VOLUME_INFORMATION) + pName->Length );
pDfsVolume->VolumeName.Buffer = (LPWSTR)(pDfsVolume + 1);
pDfsVolume->VolumeName.Length =
pDfsVolume->VolumeName.MaximumLength = pName->Length;
RtlCopyMemory(pDfsVolume->VolumeName.Buffer,
pName->Buffer,
pName->Length);
InsertHeadList(&DfsGlobalData.DfsVolumeList, &pDfsVolume->VolumeList);
*ppDfsVolume = pDfsVolume;
}
}
return Status;
}
#define DEFAULT_CHECK_SHARE_BUFFER_SIZE 4096
NTSTATUS
DfsCheckDfsShare(
IN PVOID InputBuffer,
IN ULONG InputBufferLength,
PIRP Irp,
IN OUT PIO_STATUS_BLOCK pIoStatusBlock)
{
PDFS_FIND_SHARE_ARG ShareArg = (PDFS_FIND_SHARE_ARG)InputBuffer;
UNICODE_STRING ShareName;
PREPLICA_DATA_INFO pRep = NULL;
DWORD AllocSize = 0;
NTSTATUS Status = STATUS_SUCCESS;
LPWSTR NameContextString = L"\\UnknownNameContext\\";
UNICODE_STRING NameContext;
ULONG BufferLength;
PVOID UseBuffer;
KPROCESSOR_MODE PreviousMode;
DFS_TRACE_LOW(KUMR_DETAIL, "FSCTL_DFS_FIND_SHARE\n");
PreviousMode = ExGetPreviousMode();
if (PreviousMode != KernelMode) {
Status = STATUS_INVALID_PARAMETER;
return Status;
}
RtlInitUnicodeString(&NameContext, NameContextString);
if (InputBufferLength < sizeof(DFS_FIND_SHARE_ARG) ||
(DfsGlobalData.CurrentProcessPointer != (PVOID)PsGetCurrentProcess()))
{
Status = STATUS_INVALID_PARAMETER;
return Status;
}
BufferLength = DEFAULT_CHECK_SHARE_BUFFER_SIZE;
UseBuffer = ExAllocatePoolWithTag( PagedPool,
BufferLength,
'xsfD' );
if (UseBuffer == NULL)
{
Status = STATUS_INSUFFICIENT_RESOURCES;
return Status;
}
ShareName = ShareArg->ShareName;
//get the size of the allocation
AllocSize = sizeof(REPLICA_DATA_INFO) + NameContext.Length + ShareName.Length + sizeof(WCHAR);
pRep = (PREPLICA_DATA_INFO) ExAllocatePoolWithTag( NonPagedPool,
AllocSize,
'xsfD');
if(pRep == NULL)
{
ExFreePool( UseBuffer );
Status = STATUS_INSUFFICIENT_RESOURCES;
return Status;
}
//zero the memory
RtlZeroMemory(pRep, AllocSize);
//setup the structure
pRep->MaxReferralLevel = 3;
pRep->Flags = DFS_OLDDFS_SERVER;
pRep->CostLimit = ULONG_MAX;
pRep->NumReplicasToReturn = 1000;
pRep->LinkNameLength = NameContext.Length + ShareName.Length + sizeof(WCHAR);
RtlCopyMemory(pRep->LinkName, NameContext.Buffer, NameContext.Length );
RtlCopyMemory((PVOID)((ULONG_PTR)(pRep->LinkName) + NameContext.Length),
ShareName.Buffer,
ShareName.Length );
//make the request to usermode
Status = DfsGetReplicaInformation((PVOID) pRep,
AllocSize,
UseBuffer,
BufferLength,
Irp,
pIoStatusBlock);
ExFreePool(UseBuffer);
ExFreePool (pRep);
if (Status == STATUS_SUCCESS)
{
Status = STATUS_PATH_NOT_COVERED;
}
else
{
Status = STATUS_BAD_NETWORK_NAME;
}
return Status;
}
| 27.734281 | 129 | 0.582299 | [
"object"
] |
b980d22ffa62b60bd3e6dee1bd7e3e61a673c4d7 | 2,160 | h | C | access_lib.h | luobolong/ACL | 5d53bbec74709fdd8be0f08bc22b894bd72a6bdd | [
"MIT"
] | null | null | null | access_lib.h | luobolong/ACL | 5d53bbec74709fdd8be0f08bc22b894bd72a6bdd | [
"MIT"
] | null | null | null | access_lib.h | luobolong/ACL | 5d53bbec74709fdd8be0f08bc22b894bd72a6bdd | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <regex>
#include <sstream>
#include <map>
#include <stdlib.h>
using namespace std;
string arg1, arg2, arg3, arg4; // 命令参数
string u, p, g; // 用户名 密码 组名
fstream myAudit; // 日志文件 记录系统中各种动作和事件
string whosLoggedIn; // 当前已登录用户
vector<string> instructions; // 指令数组
map<string, vector<string> > permissions; // 文件-用户权限字典
map<string, vector<string> > usergroups; // 用户-用户组字典
map<string, string> UAC; // 用户-UAC状态字典
map<string, string> userMap; // 用户-密码字典
bool isLoggedIn = false; // 是否有用户登录
bool wrongUsername, wrongPassword;
bool isFirstRun = true;
bool processTestCase(string testname);
int checkSetup(vector<string> instructions);
int checkCommand(string username);
int checkPassword(string password);
void login(string username, string password);
void logout();
bool groupExists(string groupname);
bool userExists(string username);
bool createUser(string username, string password);
bool createGroup(string groupname);
bool deleteUser(string username);
bool deleteGroup(string groupname);
vector<string> getUserGroup(string username);
bool isAdmin(string username);
bool isOwner(string filename, string username);
bool addToGroup(string username, string groupname);
bool fileExist(string filename);
void createFile(string filename);
bool strncasecmp(string s1, string s2);
bool canContinue(string answer);
bool contains(string s1, string s2);
void setUAC(string username, string permissions);
string getUAC(string username);
string getUACString(string username);
void setPermissions(string filename);
void writeFile(string filename, string text);
void readFile(string filename);
void executeFile(string filename);
bool canWrite(string userPermissions);
bool canRead(string userPermissions);
bool canExecute(string userPermissions);
string getPermissions(string filename, string username);
void editPermissions(string filename, string newPermissions);
void replacePermissions(string filename, string newPermissions);
void denyPermissions(string filename, string newPermissions);
void log(string text);
void programExecute(string filename);
bool isRestrictedName(string filename);
| 34.285714 | 64 | 0.796296 | [
"vector"
] |
b98203dfb29d602dcadfd608e1b52667ab82a77e | 25,422 | c | C | samwise/src/sam_buf.c | dreadworks/samwise | e4922d89d8be8b2875bf3f6717359e6cd6993286 | [
"MIT"
] | null | null | null | samwise/src/sam_buf.c | dreadworks/samwise | e4922d89d8be8b2875bf3f6717359e6cd6993286 | [
"MIT"
] | null | null | null | samwise/src/sam_buf.c | dreadworks/samwise | e4922d89d8be8b2875bf3f6717359e6cd6993286 | [
"MIT"
] | null | null | null | /* =========================================================================
sam_buf - Persists messages
This Source Code Form is subject to the terms of the MIT
License. If a copy of the MIT License was not distributed with
this file, You can obtain one at http://opensource.org/licenses/MIT
=========================================================================
*/
/**
@brief Persists messages
@file sam_buf.c
The samwise buffer encapsulates all persistence layer related
operations. Underneath, a Berkeley DB storage engine is used to
write message temporarily to a database file. The buffer accepts
storage requests to persist a message, demultiplexes
acknowledgements arriving from one or more messaging backends and
resends messages based on the configuration file.
<code>
sam_buf | sam_buf actor
-----------------------
PIPE: sam_buf spawns its actor internally
REQ/REP: storage requests
sam_buf_actor | libsam actor
----------------------------
PSH/PLL: resending publishing requests
be[i] | sam_buf actor
---------------------
PSH/PLL: acknowledgements
Topology:
--------
libsam sam_buf
actor o | o
PULL ^ | ^ REQ
\ PIPE |
PUSH \ | v REP
o | o
sam_buf actor o <-------- o be[i]
| PULL PUSH
|
-------------
| Berkeley DB |
| *.db file |
-------------
</code>
*/
#include "../include/sam_prelude.h"
/*
* HANDLE DEFINITIONS
*/
/// State object maintained by the actor
typedef struct state_t {
// data to be restored after restart
int seq; ///< used to assign unique message id's
int last_stored; ///< used to decide if it's a premature ack
int tombstone_zone; ///< to skip tombstones upon re-send
sam_db_t *db; ///< storage engine
zsock_t *in; ///< for arriving acknowledgements
zsock_t *out; ///< for re-publishing
zsock_t *store_sock; ///< for (internal) storage requests
int tries; ///< maximum number of retries for a message
uint64_t interval; ///< how often messages are being tried again
uint64_t threshold; ///< at which point messages are tried again
sam_stat_handle_t *stat;
} state_t;
/// buf instance wrapping the buffer
struct sam_buf_t {
zsock_t *store_sock; ///< for (internal) storage requests
zactor_t *actor; ///< maintaining the event loop
};
/*
* RECORD DEFINITIONS
*/
/// used to define how to read record_header_t.content
typedef enum {
RECORD = 0x10, // arbitrary value, prevents false positives
RECORD_ACK,
RECORD_TOMBSTONE
} record_type_t;
/// Meta information stored for every record
typedef struct record_t {
record_type_t type; ///< either record or tombstone
union {
/// header stored for messages (encoded message gets appended)
struct {
int prev; ///< previous tombstone
uint64_t be_acks; ///< mask containing backend ids
int acks_remaining; ///< may be negative for early acks
int64_t ts; ///< insertion time
int tries; ///< total number of retries
} record; ///< if type == RECORD
/// data stored for tombstones
struct {
int prev; ///< previous tombstone or NULL
int next; ///< next record/tombstone
} tombstone; ///< if type == TOMBSTONE
} c;
} record_t;
// --------------------------------------------------------------------------
/// Create a unique, sortable message id. Order determines message
/// age. Older keys must have smaller keys.
static int
create_msg_id (
state_t *state)
{
return state->seq += 1;
}
// --------------------------------------------------------------------------
/// Delete a database record and all its tombstones.
static int
del (
state_t *state)
{
assert (state);
int rc, curr_key, prev_key;
rc = curr_key = prev_key = 0;
sam_db_t *db = state->db;
do {
// determine previous tombstone - if any
record_t *header;
sam_db_get_val (db, NULL, (void **) &header);
if (header->type == RECORD) {
prev_key = header->c.record.prev;
}
else if (header->type == RECORD_TOMBSTONE) {
prev_key = header->c.tombstone.prev;
}
else if (header->type == RECORD_ACK) {
prev_key = 0;
}
else {
sam_log_errorf ("unexpected record type: 0x%x", header->type);
assert (false);
}
sam_db_del (db);
// prepare next round
if (prev_key) {
curr_key = prev_key;
rc = sam_db_get (db, &prev_key);
if (rc != SAM_DB_OK) {
// either DB_NOTFOUND or an error, abort
// deletion regardless; errors are handled
// one level up via rc
prev_key = 0;
}
}
} while (prev_key);
return rc;
}
// --------------------------------------------------------------------------
/// Creates a new tombstone record.
static int
insert_tombstone (
state_t *state,
int prev,
int *position)
{
sam_db_t *db = state->db;
size_t size = sizeof (record_t);
int next = sam_db_get_key (db);
record_t tombstone;
memset (&tombstone, 0, size);
sam_log_tracef ("creating tombstone: %d | %d", prev, *position, next);
tombstone.type = RECORD_TOMBSTONE;
tombstone.c.tombstone.prev = prev;
tombstone.c.tombstone.next = next;
// write new key
sam_db_set_key (db, position);
state->tombstone_zone = *position;
// write new data
return sam_db_put (db, size, (void *) &tombstone);
}
// --------------------------------------------------------------------------
/// Decrements the try-counter and returns a non-zero value for
/// to-be-discarded messages.
static int
update_record_tries (
state_t *state,
record_t *header)
{
header->c.record.tries -= 1;
if (!header->c.record.tries) {
sam_log_tracef (
"discarding message '%d'", sam_db_get_key (state->db));
del (state);
sam_stat (state->stat, "buf.discarded messages", 1);
return -1;
}
return 0;
}
// --------------------------------------------------------------------------
/// Checks if the record is inside the bounds of messages to be re-sent.
static int
resend_condition (
state_t *state,
record_t *header)
{
assert (header);
if (header->type == RECORD) {
int64_t eps = zclock_mono () - header->c.record.ts;
return ((int64_t) state->threshold < eps)? 0: -1;
}
return 0;
}
// --------------------------------------------------------------------------
/// Takes a database record, reconstruct the message and sends a copy
/// it via output channel.
static int
resend_message (
state_t *state)
{
record_t *header;
size_t record_size;
sam_db_t *db = state->db;
sam_db_get_val (db, &record_size, (void **) &header);
size_t header_size = sizeof (record_t);
// decode message
size_t msg_size = record_size - header_size;
byte *encoded_msg = (byte *) header + header_size;
sam_msg_t *msg = sam_msg_decode (encoded_msg, msg_size);
if (msg == NULL) {
sam_log_error ("could not decode stored message");
return -1;
}
// wrap backend acknowledgments
uint64_t be_acks = header->c.record.be_acks;
zframe_t *id_frame = zframe_new (&be_acks, sizeof (be_acks));
int msg_id = sam_db_get_key (db);
int count = header->c.record.acks_remaining;
sam_log_tracef ("re-sending msg '%d'", msg_id);
zsock_send (state->out, "ifip", msg_id, id_frame, count, msg);
zframe_destroy (&id_frame);
return 0;
}
// --------------------------------------------------------------------------
/// Determines how much space is needed to store a record in a
/// continuous block of memory. If the sam_msg is null, just the space
/// for the header is considered.
static void
record_size (
size_t *total_size,
size_t *header_size,
sam_msg_t *msg)
{
*header_size = sizeof (record_t);
if (msg) {
*total_size = *header_size + sam_msg_encoded_size (msg);
}
else {
*total_size = *header_size;
}
sam_log_tracef (
"determined record size: %d (header: %d)",
*total_size, *header_size);
}
// --------------------------------------------------------------------------
/// Create a fresh database record based on a sam_msg enclosed
/// publishing request.
static int
create_record_store (
state_t *state,
sam_msg_t *msg,
int count)
{
size_t size, header_size;
record_size (&size, &header_size, msg);
byte *record;
record = malloc (size);
if (!record) {
return -1;
}
sam_db_t *db = state->db;
sam_log_tracef (
"creating record for msg '%d'", sam_db_get_key (db));
// set header data
record_t *header = (record_t *) record;
header->type = RECORD;
header->c.record.prev = 0;
header->c.record.acks_remaining = count;
header->c.record.be_acks = 0;
header->c.record.ts = zclock_mono ();
header->c.record.tries = state->tries;
// set content data
byte *content = record + header_size;
sam_msg_encode (msg, &content);
state->last_stored += 1;
sam_db_ret_t ret = sam_db_put (db, size, record);
free (record);
return ret;
}
// --------------------------------------------------------------------------
/// If an acknowledgement already created a database record, this
/// function is used to either delete the record if only one
/// acknowledgment suffices or update the meta information and append
/// the encoded messages.
static int
update_record_store (
state_t *state,
sam_msg_t *msg,
int count)
{
int rc = 0;
size_t total_size, header_size;
record_size (&total_size, &header_size, msg);
sam_db_t *db = state->db;
record_t *header;
sam_db_get_val (db, NULL, (void **) &header);
assert (header->type == RECORD_ACK);
sam_log_tracef (
"ack already there, %d arrived already",
header->c.record.acks_remaining * -1);
header->c.record.acks_remaining += count;
// remove if there are no outstanding acks
if (!header->c.record.acks_remaining) {
rc = del (state);
}
// add encoded message to the record
else {
byte *record = malloc (total_size);
if (!record) {
return -1;
}
// copy header
byte
*header_cpy = memmove (record, header, header_size),
*content = record + header_size;
assert (header_cpy);
sam_msg_encode (msg, &content);
rc = sam_db_put (db, total_size, record);
}
return rc;
}
// --------------------------------------------------------------------------
/// Create a new database record just containing meta information and
/// no payload.
static int
create_record_ack (
state_t *state,
uint64_t backend_id)
{
record_t record;
record.type = RECORD_ACK;
record.c.record.acks_remaining = -1;
record.c.record.be_acks = backend_id;
sam_log_tracef (
"created record (ack) '%d'", sam_db_get_key (state->db));
return sam_db_put (state->db, sizeof (record_t), (void *) &record);
}
// --------------------------------------------------------------------------
/// This function updates a record with the newly arrived
/// acknowledgment. It gets ignored when the origin was a backend that
/// already sent an acknowledgment (a highly unlikely case). If not,
/// the backend gets added to the list of backends that already
/// acknowledged the message. If enough backends confirmed, then the
/// record and all its tombstones gets deleted. Otherwise it's updated.
static int
update_record_ack (
state_t *state,
uint64_t backend_id)
{
sam_db_t *db = state->db;
int rc = 0;
// skip all tombstones up to the record
record_t *header;
sam_db_get_val (db, NULL, (void **) &header);
while (header->type == RECORD_TOMBSTONE) {
int new_id = header->c.tombstone.next;
sam_log_tracef ("following tombstone chain to '%d'", new_id);
if (sam_db_get (db, &new_id)) {
return -1;
}
sam_db_get_val (db, NULL, (void **) &header);
if (new_id == header->c.tombstone.next) {
// TODO, was not able to reproduce this error occured when
// the daemon crashed with a lot of data in the
// database. Upon restart, data was malformed
sam_log_error ("malformed data, exiting.");
exit (2);
}
}
// if ack arrives multiple times, do nothing
// -> redundancy guarantee applies only to distinct acks
if (header->c.record.be_acks & backend_id) {
sam_log_trace ("backend already confirmed, ignoring ack");
return rc;
}
header->c.record.be_acks ^= backend_id;
header->c.record.acks_remaining -= 1;
// enough acks arrived, delete record
if (!header->c.record.acks_remaining) {
del (state);
}
// not enough acks, update record
else {
sam_log_tracef (
"updating '%d', acks remaining: %d",
sam_db_get_key (db),
header->c.record.acks_remaining);
header->type = RECORD;
rc = sam_db_update (db, SAM_DB_CURRENT);
}
return rc;
}
// --------------------------------------------------------------------------
/// Handles an acknowledgement. If there's already a record in the
/// database, the record is updated or deleted based on the
/// "remaining_acks" header field. If the encountered record is a tombstone,
/// it's reference is followed until the record is found.
///
/// @see update_record_ack
///
/// If there's no record in the database, then the ack arrived before
/// the save () finished. In this case a new record is created just
/// containing meta information.
///
/// @see create_record_ack
///
static int
handle_ack (
state_t *state,
uint64_t backend_id,
int ack_id)
{
sam_db_t *db = state->db;
if (sam_db_begin (db)) {
return -1;
}
int rc = sam_db_get (db, &ack_id);
// record already there, update data
if (rc == SAM_DB_OK) {
rc = update_record_ack (state, backend_id);
}
// record not yet there, create db entry
else if (rc == SAM_DB_NOTFOUND) {
if (ack_id < state->last_stored) {
sam_log_tracef ("ignoring late ack '%d'", ack_id);
rc = 0;
} else {
rc = create_record_ack (state, backend_id);
}
}
else {
rc = -1;
}
sam_db_end (db, (rc)? true: false);
return rc;
}
// --------------------------------------------------------------------------
/// Handles a request sent internally to save the message to the store.
static int
handle_storage_req (
zloop_t *loop UU,
zsock_t *store_sock,
void *args)
{
state_t *state = args;
sam_db_t *db = state->db;
int count;
sam_msg_t *msg;
sam_log_trace ("recv () storage request");
zsock_recv (store_sock, "ip", &count, &msg);
int msg_id = create_msg_id (state);
assert (msg_id >= 0);
sam_log_tracef ("handling storage request for '%d'", msg_id);
// position of this call handles what guarantee
// is promised to the publishing client. See #66
zsock_send (store_sock, "i", msg_id);
if (sam_db_begin (db)) {
return -1;
}
sam_db_ret_t ret = sam_db_get (db, &msg_id);
int rc = -1;
// record already there (ack arrived early), update data (this is
// not possible with the current implementation, but I leave it
// for the future where the whole system may act more asynchronously)
if (ret == SAM_DB_OK) {
rc = update_record_store (state, msg, count);
}
// record not yet there, create db entry
else if (ret == SAM_DB_NOTFOUND) {
// key was already set by get ()
rc = create_record_store (state, msg, count);
sam_stat (state->stat, "buf.created records", 1);
}
sam_db_end (db, (rc)? true: false);
sam_msg_destroy (&msg);
return rc;
}
// --------------------------------------------------------------------------
/// Demultiplexes acknowledgements arriving on the push/pull
/// connection wiring the messaging backends to the buffer.
///
/// @see ack
static int
handle_backend_req (
zloop_t *loop UU,
zsock_t *pll,
void *args)
{
state_t *state = args;
int rc = 0;
zframe_t *id_frame;
uint64_t be_id = 0;
int msg_id = -1;
zsock_recv (pll, "fi", &id_frame, &msg_id);
be_id = *(uint64_t *) zframe_data (id_frame);
assert (id_frame);
assert (be_id > 0);
assert (msg_id >= 0);
zframe_destroy (&id_frame);
sam_log_tracef (
"ack from '%" PRIu64 "' for msg: '%d'",
be_id, msg_id);
rc = handle_ack (state, be_id, msg_id);
sam_stat (state->stat, "buf.acknowledgments", 1);
return rc;
}
// --------------------------------------------------------------------------
/// Checks in a fixed interval if messages need to be re-sent.
static int
handle_resend (
zloop_t *loop UU,
int timer_id UU,
void *args)
{
sam_log_trace ("re-send cycle triggered");
state_t *state = args;
sam_db_t *db = state->db;
sam_db_begin (db);
int first_requeued_key = 0; // can never be zero
sam_db_ret_t rc = SAM_DB_NOTFOUND;
// skip tombstones if there are any
if (state->tombstone_zone) {
rc = sam_db_get (db, &state->tombstone_zone);
} else {
rc = sam_db_sibling (db, SAM_DB_NEXT);
}
record_t *header;
if (!rc) {
sam_db_get_val (db, NULL, (void **) &header);
}
while (
!rc && // there's another item
!resend_condition (state, header) && // check threshold
first_requeued_key != sam_db_get_key (db)) { // don't send requeued
int cur_id = sam_db_get_key (db);
sam_db_get_val (db, NULL, (void **) &header);
// if early acks are reached, no record can follow
if (header->type == RECORD_ACK) {
break;
}
// skip tombstones
if (header->type == RECORD_TOMBSTONE) {
rc = sam_db_sibling (db, SAM_DB_NEXT);
continue;
}
// decrement tries
assert (header->type == RECORD);
if (update_record_tries (state, header)) {
rc = sam_db_sibling (db, SAM_DB_NEXT);
continue;
}
// update record
// cursor gets positioned to the new records location
int new_id = create_msg_id (state);
if (!first_requeued_key) {
first_requeued_key = new_id;
}
sam_db_set_key (db, &new_id);
int prev_id = header->c.record.prev;
header->c.record.ts = zclock_mono ();
header->c.record.prev = cur_id;
if (sam_db_update (db, SAM_DB_KEY)) {
rc = -1;
break;
}
state->last_stored += 1;
sam_log_tracef (
"requeued message '%d' (formerly '%d')", new_id, cur_id);
// resend message
// use current dbop state to read the message
if (resend_message (state)) {
rc = -1;
break;
}
// create tombstone
// resets cursor position
if (insert_tombstone (state, prev_id, &cur_id)) {
rc = -1;
break;
}
sam_stat (state->stat, "buf.re-sent messages", 1);
rc = sam_db_sibling (db, SAM_DB_NEXT);
}
if (rc == SAM_DB_NOTFOUND) {
rc = 0;
}
sam_db_end (db, (rc)? true: false);
return rc;
}
// --------------------------------------------------------------------------
/// The internally started actor. Listens to storage requests and
/// acknowledgments arriving from the backends.
static void
actor (
zsock_t *pipe,
void *args)
{
sam_log_info ("starting actor");
state_t *state = args;
zloop_t *loop = zloop_new ();
zloop_reader (loop, state->store_sock, handle_storage_req, state);
zloop_reader (loop, state->in, handle_backend_req, state);
zloop_reader (loop, pipe, sam_gen_handle_pipe, NULL);
// is a uint64_t -> size_t conversion okay?
zloop_timer (loop, state->interval, 0, handle_resend, state);
sam_log_info ("starting poll loop");
zsock_signal (pipe, 0);
zloop_start (loop);
// tear down
sam_log_trace ("destroying loop");
zloop_destroy (&loop);
// database
sam_db_destroy (&state->db);
// clean up
zsock_destroy (&state->in);
zsock_destroy (&state->out);
zsock_destroy (&state->store_sock);
sam_stat_handle_destroy (&state->stat);
free (state);
}
// --------------------------------------------------------------------------
/// If records are saved in the db, the global sequence number and
/// last_stored property must be set accordingly.
int
sam_db_restore (
state_t *state)
{
state->seq = 0;
state->last_stored = 0;
state->tombstone_zone = 0;
sam_db_t *db = state->db;
if (sam_db_begin (db)) {
return -1;
}
int rc = sam_db_sibling (db, SAM_DB_PREV);
if (rc && rc == SAM_DB_NOTFOUND) {
rc = 0;
}
// there are records in the db, update seq and last_stored
else if (!rc) {
state->seq = sam_db_get_key (db);
record_t *header;
sam_db_get_val (db, NULL, (void **) &header);
if (header->type == RECORD) {
state->last_stored = state->seq;
}
// find RECORD with highest key
else {
do {
rc = sam_db_sibling (db, SAM_DB_PREV);
if (rc == SAM_DB_NOTFOUND) {
state->last_stored = 0;
rc = 0;
break;
}
else if (!rc) {
sam_db_get_val (db, NULL, (void **) &header);
if (header->type == RECORD) {
state->last_stored = sam_db_get_key (db);
break;
}
}
} while (rc);
}
}
sam_db_end (db, (rc)? true: false);
sam_log_infof (
"restored state; seq: %d, last_stored: %d",
state->seq, state->last_stored);
return rc;
}
// --------------------------------------------------------------------------
/// Create a sam buf instance.
sam_buf_t *
sam_buf_new (
sam_cfg_t *cfg,
zsock_t **in,
zsock_t **out)
{
assert (cfg);
assert (*in);
assert (*out);
char *actor_endpoint = "inproc://sam_buf";
sam_buf_t *self = malloc (sizeof (sam_buf_t));
state_t *state = malloc (sizeof (state_t));
assert (self);
assert (state);
if (sam_cfg_buf_retry_count (cfg, &state->tries) ||
sam_cfg_buf_retry_interval (cfg, &state->interval) ||
sam_cfg_buf_retry_threshold (cfg, &state->threshold)) {
sam_log_error ("could not initialize the buffer");
goto abort;
}
// create db
zconfig_t *db_conf;
const char *db_conf_path = "db/bdb";
if (sam_cfg_get (cfg, db_conf_path, &db_conf)) {
sam_log_errorf ("could not load db config (%s)", db_conf_path);
goto abort;
}
state->db = sam_db_new (db_conf);
if (state->db == NULL) {
sam_log_error ("could not load database");
goto abort;
}
// set sockets, change ownership
state->in = *in;
*in = NULL;
state->out = *out;
*out = NULL;
// storage
state->store_sock = zsock_new_rep (actor_endpoint);
self->store_sock = zsock_new_req (actor_endpoint);
assert (state->store_sock);
assert (self->store_sock);
// restore state
if (sam_db_restore (state)) {
goto abort;
}
state->stat = sam_stat_handle_new ();
// spawn actor
self->actor = zactor_new (actor, state);
sam_log_info ("created buffer instance");
return self;
abort:
if (state->db) {
sam_db_destroy (&state->db);
}
free (self);
free (state);
return NULL;
}
// --------------------------------------------------------------------------
/// Destroy a sam buf instance.
void
sam_buf_destroy (
sam_buf_t **self)
{
assert (*self);
sam_log_info ("destroying buffer instance");
zsock_destroy (&(*self)->store_sock);
zactor_destroy (&(*self)->actor);
free (*self);
*self = NULL;
}
// --------------------------------------------------------------------------
/// Save a message, get a message id as the receipt.
int
sam_buf_save (
sam_buf_t *self,
sam_msg_t *msg,
int count)
{
assert (self);
zsock_send (self->store_sock, "ip", count, msg);
int msg_id;
zsock_recv (self->store_sock, "i", &msg_id);
return msg_id;
}
| 25.472946 | 78 | 0.548973 | [
"object"
] |
b99564a3ace1dc71673b7329d75763e60cd7d708 | 3,711 | h | C | kgl_genomics/kgl_parser/kgl_variant_factory_1000_impl.h | kellerberrin/OSM_Gene_Cpp | 4ec4d1244f3f1b16213cf05f0056d8e5f85d68c4 | [
"MIT"
] | 1 | 2021-04-09T16:24:06.000Z | 2021-04-09T16:24:06.000Z | kgl_genomics/kgl_parser/kgl_variant_factory_1000_impl.h | kellerberrin/KGL_Gene | f8e6c14b8b2009d82d692b28354561b5f0513c5e | [
"MIT"
] | null | null | null | kgl_genomics/kgl_parser/kgl_variant_factory_1000_impl.h | kellerberrin/KGL_Gene | f8e6c14b8b2009d82d692b28354561b5f0513c5e | [
"MIT"
] | null | null | null | //
// Created by kellerberrin on 27/6/20.
//
#ifndef KGL_VARIANT_FACTORY_1000_IMPL_H
#define KGL_VARIANT_FACTORY_1000_IMPL_H
#include "kel_utility.h"
#include "kgl_variant_db_population.h"
#include "kgl_variant_factory_readvcf_impl.h"
#include "kgl_variant_factory_record_vcf_impl.h"
#include "kgl_variant_factory_vcf_parse_info.h"
namespace kellerberrin::genome { // organization level namespace
class Genome1000VCFImpl : public VCFReaderMT {
public:
Genome1000VCFImpl(const std::shared_ptr<PopulationDB> vcf_population_ptr,
const std::shared_ptr<const GenomeReference> genome_db_ptr,
const ContigAliasMap& contig_alias_map,
const EvidenceInfoSet& evidence_map) : evidence_factory_(evidence_map),
contig_alias_map_(contig_alias_map),
diploid_population_ptr_(vcf_population_ptr),
genome_db_ptr_(genome_db_ptr) {}
~Genome1000VCFImpl() override = default;
void ProcessVCFRecord(size_t vcf_record_count, const VcfRecord& vcf_record) override;
void processVCFHeader(const VcfHeaderInfo& header_info) override;
void readParseVCFImpl(const std::string &vcf_file_name);
private:
EvidenceFactory evidence_factory_;
ContigAliasMap contig_alias_map_;
// Processes the record in a try/catch block.
void ParseRecord(size_t vcf_record_count, const VcfRecord& record);
// Progress counters.
mutable size_t abstract_variant_count_{0};
size_t actual_variant_count_{0};
size_t variant_count_{0};
constexpr static const size_t VARIANT_REPORT_INTERVAL_{10000};
constexpr static const size_t MINIMUM_GENOTYPE_SIZE_{3};
constexpr static const size_t REFERENCE_VARIANT_INDEX_{0};
constexpr static const char* ALT_REFERENCE_VARIANT_INDICATOR_{"-"};
constexpr static const char* REFERENCE_VARIANT_INDICATOR_{"."};
constexpr static const char PHASE_MARKER_ {'|'};
constexpr static const char MULTIPLE_ALT_SEPARATOR_{','};
constexpr static const char ABSTRACT_ALT_BRACKET_{'<'};
constexpr static const char* PASSED_FILTERS_{"PASS"};
constexpr static const char* NULL_IDENTIFIER_{"."};
constexpr static const char GT_SEPARATOR_{':'};
const std::shared_ptr<PopulationDB> diploid_population_ptr_; // Diploid phased variants.
const std::shared_ptr<const GenomeReference> genome_db_ptr_; // read access only.
// mutex to lock the structure for multiple thread access by parsers.
mutable std::mutex add_variant_mutex_;
bool addThreadSafeVariant(const std::shared_ptr<const Variant>& variant_ptr, const std::vector<GenomeId_t>& genome_vector) const;
// Calculates alternate indexes for the two phases (.first = A, .second = B).
std::pair<size_t, size_t> alternateIndex(const std::string& contig,
const std::string& genotype,
const std::vector<std::string>& alt_vector) const;
// Adds variants to a vector of genomes.
void addVariants( const std::map<size_t, std::vector<GenomeId_t>>& phase_map,
const ContigId_t& contig,
VariantPhase phase,
ContigOffset_t offset,
bool passedFilters,
const std::shared_ptr<const DataMemoryBlock>& info_evidence_ptr,
const std::string& reference,
const std::string& identifier,
const std::vector<std::string>& alt_vector,
size_t vcf_record_count);
};
} // end namespace
#endif //KGL_VARIANT_FACTORY_1000_IMPL_H
| 38.257732 | 131 | 0.686338 | [
"vector"
] |
b99a6a7ef99e1e66edb429ca27bd69b2e2ac526c | 4,729 | h | C | Engine/AI/NavMesh.h | mariofv/LittleEngine | 38ecfdf6041a24f304c679ee3b6b589ba2040e48 | [
"MIT"
] | 9 | 2020-04-05T07:44:38.000Z | 2022-01-12T02:07:14.000Z | Engine/AI/NavMesh.h | mariofv/LittleEngine | 38ecfdf6041a24f304c679ee3b6b589ba2040e48 | [
"MIT"
] | 105 | 2020-03-13T19:12:23.000Z | 2020-12-02T23:41:15.000Z | Engine/AI/NavMesh.h | mariofv/LittleEngine | 38ecfdf6041a24f304c679ee3b6b589ba2040e48 | [
"MIT"
] | 1 | 2021-04-24T16:11:49.000Z | 2021-04-24T16:11:49.000Z | #ifndef _NAVMESH_H_
#define _NAVMESH_H_
#include "AI/SampleDebugDraw.h"
#include "AI/DebugDrawGL.h"
#include "Helper/Timer.h"
#include <MathGeoLib.h>
#include <pcg_basic.h>
#include <recast/Detour/DetourNavMesh.h>
#include <recast/Recast/Recast.h>
#include <vector>
class DetourNavMesh;
class dtNavMeshQuery;
class dtNavMesh;
class PanelNavMesh;
struct dtMeshTile;
enum PathMode
{
FOLLOW_PATH,
STRAIGHT_PATH
};
enum DrawMode
{
DRAWMODE_NAVMESH,
DRAWMODE_NAVMESH_TRANS,
DRAWMODE_NAVMESH_BVTREE,
DRAWMODE_NAVMESH_NODES,
DRAWMODE_NAVMESH_INVIS,
DRAWMODE_MESH,
DRAWMODE_VOXELS,
DRAWMODE_VOXELS_WALKABLE,
DRAWMODE_COMPACT,
DRAWMODE_COMPACT_DISTANCE,
DRAWMODE_COMPACT_REGIONS,
DRAWMODE_REGION_CONNECTIONS,
DRAWMODE_RAW_CONTOURS,
DRAWMODE_BOTH_CONTOURS,
DRAWMODE_CONTOURS,
DRAWMODE_POLYMESH,
DRAWMODE_POLYMESH_DETAIL,
MAX_DRAWMODE
};
enum SamplePartitionType
{
SAMPLE_PARTITION_WATERSHED,
SAMPLE_PARTITION_MONOTONE,
SAMPLE_PARTITION_LAYERS,
};
enum SamplePolyFlags
{
SAMPLE_POLYFLAGS_WALK = 0x01, // Ability to walk (ground, grass, road)
SAMPLE_POLYFLAGS_SWIM = 0x02, // Ability to swim (water)
SAMPLE_POLYFLAGS_DOOR = 0x04, // Ability to move through doors
SAMPLE_POLYFLAGS_JUMP = 0x08, // Ability to jump
SAMPLE_POLYFLAGS_DISABLED = 0x10, // Disabled polygon
SAMPLE_POLYFLAGS_ALL = 0xffff // All abilities
};
class NavMesh
{
public:
NavMesh();
~NavMesh();
bool CleanUp();
bool Update();
bool CreateNavMesh();
void RenderNavMesh(ComponentCamera& camera);
void InitAABB();
bool FindPath(float3& start, float3& end, std::vector<float3>& path, PathMode path_mode);
bool IsPointWalkable(float3 & target_position);
bool FindNextPolyByDirection(float3& position, float3& next_position);
void SaveNavMesh(unsigned char* nav_data, unsigned int nav_data_size) const;
void LoadNavMesh();
inline SampleDebugDraw& GetDebugDraw() { return m_dd; }
private:
void GetVerticesScene();
void GetIndicesScene();
void GetNormalsScene();
bool GetSteerTarget(dtNavMeshQuery* navQuery, const float* startPos, const float* endPos,
const float minTargetDist,
const dtPolyRef* path, const int pathSize,
float* steerPos, unsigned char& steerPosFlag, dtPolyRef& steerPosRef,
float* outPoints = 0, int* outPointCount = 0);
inline bool InRange(const float* v1, const float* v2, const float r, const float h);
int FixUpShortcuts(dtPolyRef* path, int npath, dtNavMeshQuery* nav_query);
int FixUpCorridor(dtPolyRef* path, const int npath, const int max_path,
const dtPolyRef* visited, const int nvisited);
float DistancePtLine2d(const float* pt, const float* p, const float* q) const;
void drawMeshTile(SampleDebugDraw* dd, const dtNavMesh& mesh, const dtNavMeshQuery* query,
const dtMeshTile* tile, unsigned char flags);
void duDebugDrawNavMesh(SampleDebugDraw* dd, const dtNavMesh& mesh, unsigned char flags);
void duDebugDrawNavMeshWithClosedList(SampleDebugDraw* dd, const dtNavMesh& mesh, const dtNavMeshQuery& query, unsigned char flags);
public:
uint64_t mesh_floor_uuid;
protected:
unsigned char* m_triareas = nullptr;
rcHeightfield* m_solid = nullptr;
rcCompactHeightfield* m_chf = nullptr;
rcContourSet* m_cset = nullptr;
rcPolyMesh* m_pmesh = nullptr;
rcConfig m_cfg;
rcPolyMeshDetail* m_dmesh = nullptr;
DrawMode m_drawMode;
// Variables of NavMesh (modified by UI)
float cell_width = 0.20f;
float cell_height = 1.0f;
float walkable_slope_angle = 50.0f;
float agent_height = 2.0f;
float agent_max_climb = 0.09f;
float agent_radius = 0.6f;
float edge_max_len = 12.0f;
float edge_max_error = 1.3f;
int region_min_size = 8;
int region_merge_size = 20;
float verts_per_poly = 6;
float detail_sample_distance = 6;
float detail_sample_max_error = 1;
const float texScale = 1.f / ((cell_width * cell_height) / 10.f);
private:
rcContext* m_ctx;
//If true there are memory leaks but it should be only for debugging
bool keep_inter_results = false;
bool filter_low_hanging_obstacles = true;
bool filter_ledge_spans = true;
bool filter_walkable_low_height_spans = true;
SamplePartitionType partition_type = SAMPLE_PARTITION_WATERSHED;
//Data
std::vector<float> verts_vec;
std::vector<int> tris_vec;
std::vector<float> normals_vec;
std::vector<bool> unwalkable_verts;
char* navmesh_read_data = nullptr;
int ntris = 0;
AABB global_AABB;
bool is_mesh_computed = false;
dtNavMeshQuery* nav_query = nullptr;
dtNavMesh* nav_mesh = nullptr;
unsigned char nav_mesh_draw_flags;
//PathMode path_mode = PathMode::FOLLOW_PATH;
static const int MAX_POLYS = 256;
static const int MAX_SMOOTH = 2048;
///TEST
SampleDebugDraw m_dd;
Timer navmesh_timer;
float time_to_build = 0.0f;
friend PanelNavMesh;
};
#endif // _NAVMESH_H_ | 25.701087 | 133 | 0.775428 | [
"mesh",
"vector"
] |
b9abfd3536682a63a1658f669a4d503cd11d2958 | 1,031 | h | C | compiler/blockoptioninteger.h | UnnamedCompany/UnnamedSoftware | 3251dc9844f35622f616fd3d5a40cb8c89ac0b28 | [
"MIT"
] | 4 | 2016-02-18T00:48:10.000Z | 2016-03-02T23:41:54.000Z | compiler/blockoptioninteger.h | UnnamedCompany/UnnamedSoftware | 3251dc9844f35622f616fd3d5a40cb8c89ac0b28 | [
"MIT"
] | null | null | null | compiler/blockoptioninteger.h | UnnamedCompany/UnnamedSoftware | 3251dc9844f35622f616fd3d5a40cb8c89ac0b28 | [
"MIT"
] | 1 | 2016-02-29T18:13:34.000Z | 2016-02-29T18:13:34.000Z | #ifndef BLOCKOPTIONINTEGER_H
#define BLOCKOPTIONINTEGER_H
#include "blockoption.h"
#include <QString>
#include "blockoptioncontrol.h"
#include <QJsonValue>
/**
* A BlockOptionInteger is a BlockOption that selects from a range of integers.
*/
class BlockOptionInteger : public BlockOption {
public:
/**
* Construct a BlockOptionInteger.
* @param displayName the display name
* @param defaultValue the default value
* @param minimum the minimum value
* @param maximum the maximum value
*/
explicit BlockOptionInteger(QString displayName, QString defaultValue, int minimum, int maximum);
/**
* Create the BlockOptionControl for controlling this option.
* The returned object will be a BlockOptionControlInteger.
* @return A pointer to the heap-allocated control object.
*/
virtual BlockOptionControl *makeControl() const override;
virtual QJsonValue toJson() const override;
private:
int m_minimum;
int m_maximum;
};
#endif // BLOCKOPTIONINTEGER_H
| 27.131579 | 101 | 0.728419 | [
"object"
] |
b9c8b187bdfc5a83ce3b2463db414b28cbadea6a | 527 | h | C | proj2/Wheeled.h | in2rd/umuc-cmis115 | 9d8b55d149fc5c8cae6c3eafd308322062481224 | [
"Apache-2.0"
] | null | null | null | proj2/Wheeled.h | in2rd/umuc-cmis115 | 9d8b55d149fc5c8cae6c3eafd308322062481224 | [
"Apache-2.0"
] | null | null | null | proj2/Wheeled.h | in2rd/umuc-cmis115 | 9d8b55d149fc5c8cae6c3eafd308322062481224 | [
"Apache-2.0"
] | null | null | null | //
// Ian Nelson
// CMIS115
// Project 2
// Puran Nebhnani
//
// Wheeled.h
//
// Created by Ian Nelson on 7/8/14
#import <Foundation/Foundation.h>
/**
* Class interface for Wheeled
*
* @inherits NSObject
*/
@interface Wheeled: NSObject {
@private int speed;
@private int wheels;
}
// Speed/wheels properties
@property (readwrite, assign) int speed;
@property (readwrite, assign) int wheels;
// Definition to start Wheeled object.
- (void) start;
// Definition to stop Wheeled object.
- (void) stop;
@end
| 15.969697 | 41 | 0.671727 | [
"object"
] |
b9d5284bcb042bde3e8cfa79275424768c643412 | 19,561 | c | C | openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/libnl/1_3.4.0-r0/libnl-3.4.0/lib/route/link/ipgre.c | sotaoverride/backup | ca53a10b72295387ef4948a9289cb78ab70bc449 | [
"Apache-2.0"
] | null | null | null | openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/libnl/1_3.4.0-r0/libnl-3.4.0/lib/route/link/ipgre.c | sotaoverride/backup | ca53a10b72295387ef4948a9289cb78ab70bc449 | [
"Apache-2.0"
] | null | null | null | openbmc/build/tmp/deploy/sdk/witherspoon-2019-08-08/sysroots/armv6-openbmc-linux-gnueabi/usr/src/debug/libnl/1_3.4.0-r0/libnl-3.4.0/lib/route/link/ipgre.c | sotaoverride/backup | ca53a10b72295387ef4948a9289cb78ab70bc449 | [
"Apache-2.0"
] | null | null | null | /*
* lib/route/link/ipgre.c IPGRE Link Info
*
* 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 version 2.1
* of the License.
*
* Copyright (c) 2014 Susant Sahani <susant@redhat.com>
*/
/**
* @ingroup link
* @defgroup ipgre IPGRE
* ipgre link module
*
* @details
* \b Link Type Name: "ipgre"
*
* @route_doc{link_ipgre, IPGRE Documentation}
*
* @{
*/
#include <linux/if_tunnel.h>
#include <netlink-private/netlink.h>
#include <netlink-private/route/link/api.h>
#include <netlink/attr.h>
#include <netlink/netlink.h>
#include <netlink/object.h>
#include <netlink/route/link/ipgre.h>
#include <netlink/route/rtnl.h>
#include <netlink/utils.h>
#define IPGRE_ATTR_LINK (1 << 0)
#define IPGRE_ATTR_IFLAGS (1 << 1)
#define IPGRE_ATTR_OFLAGS (1 << 2)
#define IPGRE_ATTR_IKEY (1 << 3)
#define IPGRE_ATTR_OKEY (1 << 4)
#define IPGRE_ATTR_LOCAL (1 << 5)
#define IPGRE_ATTR_REMOTE (1 << 6)
#define IPGRE_ATTR_TTL (1 << 7)
#define IPGRE_ATTR_TOS (1 << 8)
#define IPGRE_ATTR_PMTUDISC (1 << 9)
struct ipgre_info
{
uint8_t ttl;
uint8_t tos;
uint8_t pmtudisc;
uint16_t iflags;
uint16_t oflags;
uint32_t ikey;
uint32_t okey;
uint32_t link;
uint32_t local;
uint32_t remote;
uint32_t ipgre_mask;
};
static struct nla_policy ipgre_policy[IFLA_GRE_MAX + 1] = {
[IFLA_GRE_LINK] = {.type = NLA_U32},
[IFLA_GRE_IFLAGS] = {.type = NLA_U16},
[IFLA_GRE_OFLAGS] = {.type = NLA_U16},
[IFLA_GRE_IKEY] = {.type = NLA_U32},
[IFLA_GRE_OKEY] = {.type = NLA_U32},
[IFLA_GRE_LOCAL] = {.type = NLA_U32},
[IFLA_GRE_REMOTE] = {.type = NLA_U32},
[IFLA_GRE_TTL] = {.type = NLA_U8},
[IFLA_GRE_TOS] = {.type = NLA_U8},
[IFLA_GRE_PMTUDISC] = {.type = NLA_U8},
};
static int ipgre_alloc(struct rtnl_link* link)
{
struct ipgre_info* ipgre;
if (link->l_info)
memset(link->l_info, 0, sizeof(*ipgre));
else
{
ipgre = calloc(1, sizeof(*ipgre));
if (!ipgre)
return -NLE_NOMEM;
link->l_info = ipgre;
}
return 0;
}
static int ipgre_parse(struct rtnl_link* link, struct nlattr* data,
struct nlattr* xstats)
{
struct nlattr* tb[IFLA_IPTUN_MAX + 1];
struct ipgre_info* ipgre;
int err;
NL_DBG(3, "Parsing IPGRE link info\n");
err = nla_parse_nested(tb, IFLA_GRE_MAX, data, ipgre_policy);
if (err < 0)
goto errout;
err = ipgre_alloc(link);
if (err < 0)
goto errout;
ipgre = link->l_info;
if (tb[IFLA_GRE_LINK])
{
ipgre->link = nla_get_u32(tb[IFLA_GRE_LINK]);
ipgre->ipgre_mask |= IPGRE_ATTR_LINK;
}
if (tb[IFLA_GRE_IFLAGS])
{
ipgre->iflags = nla_get_u16(tb[IFLA_GRE_IFLAGS]);
ipgre->ipgre_mask |= IPGRE_ATTR_IFLAGS;
}
if (tb[IFLA_GRE_OFLAGS])
{
ipgre->oflags = nla_get_u16(tb[IFLA_GRE_OFLAGS]);
ipgre->ipgre_mask |= IPGRE_ATTR_OFLAGS;
}
if (tb[IFLA_GRE_IKEY])
{
ipgre->ikey = nla_get_u32(tb[IFLA_GRE_IKEY]);
ipgre->ipgre_mask |= IPGRE_ATTR_IKEY;
}
if (tb[IFLA_GRE_OKEY])
{
ipgre->okey = nla_get_u32(tb[IFLA_GRE_OKEY]);
ipgre->ipgre_mask |= IPGRE_ATTR_OKEY;
}
if (tb[IFLA_GRE_LOCAL])
{
ipgre->local = nla_get_u32(tb[IFLA_GRE_LOCAL]);
ipgre->ipgre_mask |= IPGRE_ATTR_LOCAL;
}
if (tb[IFLA_GRE_REMOTE])
{
ipgre->remote = nla_get_u32(tb[IFLA_GRE_REMOTE]);
ipgre->ipgre_mask |= IPGRE_ATTR_REMOTE;
}
if (tb[IFLA_GRE_TTL])
{
ipgre->ttl = nla_get_u8(tb[IFLA_GRE_TTL]);
ipgre->ipgre_mask |= IPGRE_ATTR_TTL;
}
if (tb[IFLA_GRE_TOS])
{
ipgre->tos = nla_get_u8(tb[IFLA_GRE_TOS]);
ipgre->ipgre_mask |= IPGRE_ATTR_TOS;
}
if (tb[IFLA_GRE_PMTUDISC])
{
ipgre->pmtudisc = nla_get_u8(tb[IFLA_GRE_PMTUDISC]);
ipgre->ipgre_mask |= IPGRE_ATTR_PMTUDISC;
}
err = 0;
errout:
return err;
}
static int ipgre_put_attrs(struct nl_msg* msg, struct rtnl_link* link)
{
struct ipgre_info* ipgre = link->l_info;
struct nlattr* data;
data = nla_nest_start(msg, IFLA_INFO_DATA);
if (!data)
return -NLE_MSGSIZE;
if (ipgre->ipgre_mask & IPGRE_ATTR_LINK)
NLA_PUT_U32(msg, IFLA_GRE_LINK, ipgre->link);
if (ipgre->ipgre_mask & IFLA_GRE_IFLAGS)
NLA_PUT_U16(msg, IFLA_GRE_IFLAGS, ipgre->iflags);
if (ipgre->ipgre_mask & IFLA_GRE_OFLAGS)
NLA_PUT_U16(msg, IFLA_GRE_OFLAGS, ipgre->oflags);
if (ipgre->ipgre_mask & IPGRE_ATTR_IKEY)
NLA_PUT_U32(msg, IFLA_GRE_IKEY, ipgre->ikey);
if (ipgre->ipgre_mask & IPGRE_ATTR_OKEY)
NLA_PUT_U32(msg, IFLA_GRE_OKEY, ipgre->okey);
if (ipgre->ipgre_mask & IPGRE_ATTR_LOCAL)
NLA_PUT_U32(msg, IFLA_GRE_LOCAL, ipgre->local);
if (ipgre->ipgre_mask & IPGRE_ATTR_REMOTE)
NLA_PUT_U32(msg, IFLA_GRE_REMOTE, ipgre->remote);
if (ipgre->ipgre_mask & IPGRE_ATTR_TTL)
NLA_PUT_U8(msg, IFLA_GRE_TTL, ipgre->ttl);
if (ipgre->ipgre_mask & IPGRE_ATTR_TOS)
NLA_PUT_U8(msg, IFLA_GRE_TOS, ipgre->tos);
if (ipgre->ipgre_mask & IPGRE_ATTR_PMTUDISC)
NLA_PUT_U8(msg, IFLA_GRE_PMTUDISC, ipgre->pmtudisc);
nla_nest_end(msg, data);
nla_put_failure:
return 0;
}
static void ipgre_free(struct rtnl_link* link)
{
struct ipgre_info* ipgre = link->l_info;
free(ipgre);
link->l_info = NULL;
}
static void ipgre_dump_line(struct rtnl_link* link, struct nl_dump_params* p)
{
nl_dump(p, "ipgre : %s", link->l_name);
}
static void ipgre_dump_details(struct rtnl_link* link, struct nl_dump_params* p)
{
struct ipgre_info* ipgre = link->l_info;
char *name, addr[INET_ADDRSTRLEN];
struct rtnl_link* parent;
if (ipgre->ipgre_mask & IPGRE_ATTR_LINK)
{
nl_dump(p, " link ");
name = NULL;
parent = link_lookup(link->ce_cache, ipgre->link);
if (parent)
name = rtnl_link_get_name(parent);
if (name)
nl_dump_line(p, "%s\n", name);
else
nl_dump_line(p, "%u\n", ipgre->link);
}
if (ipgre->ipgre_mask & IPGRE_ATTR_IFLAGS)
{
nl_dump(p, " iflags ");
nl_dump_line(p, "%x\n", ipgre->iflags);
}
if (ipgre->ipgre_mask & IPGRE_ATTR_OFLAGS)
{
nl_dump(p, " oflags ");
nl_dump_line(p, "%x\n", ipgre->oflags);
}
if (ipgre->ipgre_mask & IPGRE_ATTR_IKEY)
{
nl_dump(p, " ikey ");
nl_dump_line(p, "%x\n", ipgre->ikey);
}
if (ipgre->ipgre_mask & IPGRE_ATTR_OKEY)
{
nl_dump(p, " okey ");
nl_dump_line(p, "%x\n", ipgre->okey);
}
if (ipgre->ipgre_mask & IPGRE_ATTR_LOCAL)
{
nl_dump(p, " local ");
if (inet_ntop(AF_INET, &ipgre->local, addr, sizeof(addr)))
nl_dump_line(p, "%s\n", addr);
else
nl_dump_line(p, "%#x\n", ntohs(ipgre->local));
}
if (ipgre->ipgre_mask & IPGRE_ATTR_REMOTE)
{
nl_dump(p, " remote ");
if (inet_ntop(AF_INET, &ipgre->remote, addr, sizeof(addr)))
nl_dump_line(p, "%s\n", addr);
else
nl_dump_line(p, "%#x\n", ntohs(ipgre->remote));
}
if (ipgre->ipgre_mask & IPGRE_ATTR_TTL)
{
nl_dump(p, " ttl ");
nl_dump_line(p, "%u\n", ipgre->ttl);
}
if (ipgre->ipgre_mask & IPGRE_ATTR_TOS)
{
nl_dump(p, " tos ");
nl_dump_line(p, "%u\n", ipgre->tos);
}
if (ipgre->ipgre_mask & IPGRE_ATTR_PMTUDISC)
{
nl_dump(p, " pmtudisc ");
nl_dump_line(p, "enabled (%#x)\n", ipgre->pmtudisc);
}
}
static int ipgre_clone(struct rtnl_link* dst, struct rtnl_link* src)
{
struct ipgre_info *ipgre_dst, *ipgre_src = src->l_info;
int err;
dst->l_info = NULL;
err = rtnl_link_set_type(dst, "gre");
if (err < 0)
return err;
ipgre_dst = dst->l_info;
if (!ipgre_dst || !ipgre_src)
BUG();
memcpy(ipgre_dst, ipgre_src, sizeof(struct ipgre_info));
return 0;
}
static int ipgretap_clone(struct rtnl_link* dst, struct rtnl_link* src)
{
struct ipgre_info *ipgre_dst, *ipgre_src = src->l_info;
int err;
dst->l_info = NULL;
err = rtnl_link_set_type(dst, "gretap");
if (err < 0)
return err;
ipgre_dst = dst->l_info;
if (!ipgre_dst || !ipgre_src)
BUG();
memcpy(ipgre_dst, ipgre_src, sizeof(struct ipgre_info));
return 0;
}
static struct rtnl_link_info_ops ipgre_info_ops = {
.io_name = "gre",
.io_alloc = ipgre_alloc,
.io_parse = ipgre_parse,
.io_dump =
{
[NL_DUMP_LINE] = ipgre_dump_line,
[NL_DUMP_DETAILS] = ipgre_dump_details,
},
.io_clone = ipgre_clone,
.io_put_attrs = ipgre_put_attrs,
.io_free = ipgre_free,
};
static struct rtnl_link_info_ops ipgretap_info_ops = {
.io_name = "gretap",
.io_alloc = ipgre_alloc,
.io_parse = ipgre_parse,
.io_dump =
{
[NL_DUMP_LINE] = ipgre_dump_line,
[NL_DUMP_DETAILS] = ipgre_dump_details,
},
.io_clone = ipgretap_clone,
.io_put_attrs = ipgre_put_attrs,
.io_free = ipgre_free,
};
#define IS_IPGRE_LINK_ASSERT(link) \
if ((link)->l_info_ops != &ipgre_info_ops && \
(link)->l_info_ops != &ipgretap_info_ops) \
{ \
APPBUG("Link is not a ipgre link. set type \"gre/gretap\" first."); \
return -NLE_OPNOTSUPP; \
}
struct rtnl_link* rtnl_link_ipgre_alloc(void)
{
struct rtnl_link* link;
int err;
link = rtnl_link_alloc();
if (!link)
return NULL;
err = rtnl_link_set_type(link, "gre");
if (err < 0)
{
rtnl_link_put(link);
return NULL;
}
return link;
}
/**
* Check if link is a IPGRE link
* @arg link Link object
*
* @return True if link is a IPGRE link, otherwise 0 is returned.
*/
int rtnl_link_is_ipgre(struct rtnl_link* link)
{
return link->l_info_ops && !strcmp(link->l_info_ops->io_name, "gre");
}
/**
* Create a new IPGRE tunnel device
* @arg sock netlink socket
* @arg name name of the tunnel deviceL
*
* Creates a new ipip tunnel device in the kernel
* @return 0 on success or a negative error code
*/
int rtnl_link_ipgre_add(struct nl_sock* sk, const char* name)
{
struct rtnl_link* link;
int err;
link = rtnl_link_ipgre_alloc();
if (!link)
return -NLE_NOMEM;
if (name)
rtnl_link_set_name(link, name);
err = rtnl_link_add(sk, link, NLM_F_CREATE);
rtnl_link_put(link);
return err;
}
struct rtnl_link* rtnl_link_ipgretap_alloc(void)
{
struct rtnl_link* link;
int err;
link = rtnl_link_alloc();
if (!link)
return NULL;
err = rtnl_link_set_type(link, "gretap");
if (err < 0)
{
rtnl_link_put(link);
return NULL;
}
return link;
}
/**
* Check if link is a IPGRETAP link
* @arg link Link object
*
* @return True if link is a IPGRETAP link, otherwise 0 is returned.
*/
int rtnl_link_is_ipgretap(struct rtnl_link* link)
{
return link->l_info_ops && !strcmp(link->l_info_ops->io_name, "gretap");
}
/**
* Create a new IPGRETAP tunnel device
* @arg sock netlink socket
* @arg name name of the tunnel deviceL
*
* Creates a new IPGRETAP tunnel device in the kernel
* @return 0 on success or a negative error code
*/
int rtnl_link_ipgretap_add(struct nl_sock* sk, const char* name)
{
struct rtnl_link* link;
int err;
link = rtnl_link_ipgretap_alloc();
if (!link)
return -NLE_NOMEM;
if (name)
rtnl_link_set_name(link, name);
err = rtnl_link_add(sk, link, NLM_F_CREATE);
rtnl_link_put(link);
return err;
}
/**
* Set IPGRE tunnel interface index
* @arg link Link object
* @arg index interface index
*
* @return 0 on success or a negative error code
*/
int rtnl_link_ipgre_set_link(struct rtnl_link* link, uint32_t index)
{
struct ipgre_info* ipgre = link->l_info;
IS_IPGRE_LINK_ASSERT(link);
ipgre->link = index;
ipgre->ipgre_mask |= IPGRE_ATTR_LINK;
return 0;
}
/**
* Get IPGRE tunnel interface index
* @arg link Link object
*
* @return interface index
*/
uint32_t rtnl_link_ipgre_get_link(struct rtnl_link* link)
{
struct ipgre_info* ipgre = link->l_info;
IS_IPGRE_LINK_ASSERT(link);
return ipgre->link;
}
/**
* Set IPGRE tunnel set iflags
* @arg link Link object
* @arg iflags gre iflags
*
* @return 0 on success or a negative error code
*/
int rtnl_link_ipgre_set_iflags(struct rtnl_link* link, uint16_t iflags)
{
struct ipgre_info* ipgre = link->l_info;
IS_IPGRE_LINK_ASSERT(link);
ipgre->iflags = iflags;
ipgre->ipgre_mask |= IPGRE_ATTR_IFLAGS;
return 0;
}
/**
* Get IPGRE tunnel iflags
* @arg link Link object
*
* @return iflags
*/
uint16_t rtnl_link_ipgre_get_iflags(struct rtnl_link* link)
{
struct ipgre_info* ipgre = link->l_info;
IS_IPGRE_LINK_ASSERT(link);
return ipgre->iflags;
}
/**
* Set IPGRE tunnel set oflags
* @arg link Link object
* @arg iflags gre oflags
*
* @return 0 on success or a negative error code
*/
int rtnl_link_ipgre_set_oflags(struct rtnl_link* link, uint16_t oflags)
{
struct ipgre_info* ipgre = link->l_info;
IS_IPGRE_LINK_ASSERT(link);
ipgre->oflags = oflags;
ipgre->ipgre_mask |= IPGRE_ATTR_OFLAGS;
return 0;
}
/**
* Get IPGRE tunnel oflags
* @arg link Link object
*
* @return oflags
*/
uint16_t rtnl_link_ipgre_get_oflags(struct rtnl_link* link)
{
struct ipgre_info* ipgre = link->l_info;
IS_IPGRE_LINK_ASSERT(link);
return ipgre->oflags;
}
/**
* Set IPGRE tunnel set ikey
* @arg link Link object
* @arg ikey gre ikey
*
* @return 0 on success or a negative error code
*/
int rtnl_link_ipgre_set_ikey(struct rtnl_link* link, uint32_t ikey)
{
struct ipgre_info* ipgre = link->l_info;
IS_IPGRE_LINK_ASSERT(link);
ipgre->ikey = ikey;
ipgre->ipgre_mask |= IPGRE_ATTR_IKEY;
return 0;
}
/**
* Get IPGRE tunnel ikey
* @arg link Link object
*
* @return ikey
*/
uint32_t rtnl_link_ipgre_get_ikey(struct rtnl_link* link)
{
struct ipgre_info* ipgre = link->l_info;
IS_IPGRE_LINK_ASSERT(link);
return ipgre->ikey;
}
/**
* Set IPGRE tunnel set okey
* @arg link Link object
* @arg okey gre okey
*
* @return 0 on success or a negative error code
*/
int rtnl_link_ipgre_set_okey(struct rtnl_link* link, uint32_t okey)
{
struct ipgre_info* ipgre = link->l_info;
IS_IPGRE_LINK_ASSERT(link);
ipgre->okey = okey;
ipgre->ipgre_mask |= IPGRE_ATTR_OKEY;
return 0;
}
/**
* Get IPGRE tunnel okey
* @arg link Link object
*
* @return okey value
*/
uint32_t rtnl_link_ipgre_get_okey(struct rtnl_link* link)
{
struct ipgre_info* ipgre = link->l_info;
IS_IPGRE_LINK_ASSERT(link);
return ipgre->okey;
}
/**
* Set IPGRE tunnel local address
* @arg link Link object
* @arg addr local address
*
* @return 0 on success or a negative error code
*/
int rtnl_link_ipgre_set_local(struct rtnl_link* link, uint32_t addr)
{
struct ipgre_info* ipgre = link->l_info;
IS_IPGRE_LINK_ASSERT(link);
ipgre->local = addr;
ipgre->ipgre_mask |= IPGRE_ATTR_LOCAL;
return 0;
}
/**
* Get IPGRE tunnel local address
* @arg link Link object
*
* @return local address
*/
uint32_t rtnl_link_ipgre_get_local(struct rtnl_link* link)
{
struct ipgre_info* ipgre = link->l_info;
IS_IPGRE_LINK_ASSERT(link);
return ipgre->local;
}
/**
* Set IPGRE tunnel remote address
* @arg link Link object
* @arg remote remote address
*
* @return 0 on success or a negative error code
*/
int rtnl_link_ipgre_set_remote(struct rtnl_link* link, uint32_t remote)
{
struct ipgre_info* ipgre = link->l_info;
IS_IPGRE_LINK_ASSERT(link);
ipgre->remote = remote;
ipgre->ipgre_mask |= IPGRE_ATTR_REMOTE;
return 0;
}
/**
* Get IPGRE tunnel remote address
* @arg link Link object
*
* @return remote address on success or a negative error code
*/
uint32_t rtnl_link_ipgre_get_remote(struct rtnl_link* link)
{
struct ipgre_info* ipgre = link->l_info;
IS_IPGRE_LINK_ASSERT(link);
return ipgre->remote;
}
/**
* Set IPGRE tunnel ttl
* @arg link Link object
* @arg ttl tunnel ttl
*
* @return 0 on success or a negative error code
*/
int rtnl_link_ipgre_set_ttl(struct rtnl_link* link, uint8_t ttl)
{
struct ipgre_info* ipgre = link->l_info;
IS_IPGRE_LINK_ASSERT(link);
ipgre->ttl = ttl;
ipgre->ipgre_mask |= IPGRE_ATTR_TTL;
return 0;
}
/**
* Set IPGRE tunnel ttl
* @arg link Link object
*
* @return ttl value
*/
uint8_t rtnl_link_ipgre_get_ttl(struct rtnl_link* link)
{
struct ipgre_info* ipgre = link->l_info;
IS_IPGRE_LINK_ASSERT(link);
return ipgre->ttl;
}
/**
* Set IPGRE tunnel tos
* @arg link Link object
* @arg tos tunnel tos
*
* @return 0 on success or a negative error code
*/
int rtnl_link_ipgre_set_tos(struct rtnl_link* link, uint8_t tos)
{
struct ipgre_info* ipgre = link->l_info;
IS_IPGRE_LINK_ASSERT(link);
ipgre->tos = tos;
ipgre->ipgre_mask |= IPGRE_ATTR_TOS;
return 0;
}
/**
* Get IPGRE tunnel tos
* @arg link Link object
*
* @return tos value
*/
uint8_t rtnl_link_ipgre_get_tos(struct rtnl_link* link)
{
struct ipgre_info* ipgre = link->l_info;
IS_IPGRE_LINK_ASSERT(link);
return ipgre->tos;
}
/**
* Set IPGRE tunnel path MTU discovery
* @arg link Link object
* @arg pmtudisc path MTU discovery
*
* @return 0 on success or a negative error code
*/
int rtnl_link_ipgre_set_pmtudisc(struct rtnl_link* link, uint8_t pmtudisc)
{
struct ipgre_info* ipgre = link->l_info;
IS_IPGRE_LINK_ASSERT(link);
ipgre->pmtudisc = pmtudisc;
ipgre->ipgre_mask |= IPGRE_ATTR_PMTUDISC;
return 0;
}
/**
* Get IPGRE path MTU discovery
* @arg link Link object
*
* @return pmtudisc value
*/
uint8_t rtnl_link_ipgre_get_pmtudisc(struct rtnl_link* link)
{
struct ipgre_info* ipgre = link->l_info;
IS_IPGRE_LINK_ASSERT(link);
return ipgre->pmtudisc;
}
/* Function prototype for ABI-preserving wrapper (not in public header) to avoid
* GCC warning about missing prototype. */
uint8_t rtnl_link_get_pmtudisc(struct rtnl_link* link);
uint8_t rtnl_link_get_pmtudisc(struct rtnl_link* link)
{
/* rtnl_link_ipgre_get_pmtudisc() was wrongly named. Keep this
* to preserve ABI. */
return rtnl_link_ipgre_get_pmtudisc(link);
}
static void __init ipgre_init(void)
{
rtnl_link_register_info(&ipgre_info_ops);
rtnl_link_register_info(&ipgretap_info_ops);
}
static void __exit ipgre_exit(void)
{
rtnl_link_unregister_info(&ipgre_info_ops);
rtnl_link_unregister_info(&ipgretap_info_ops);
}
| 22.509781 | 80 | 0.627115 | [
"object"
] |
b9d9e88aa8502cdb8721c8135bf51c7761efdf86 | 6,420 | h | C | DJTableViewVM/Classes/AdvanceCells/InputCells/DJTableViewVMTextFieldRow.h | Dokay/DJTableViewVM | 11d44476d9bed15d0d07625b6f25a87878d7d4d7 | [
"MIT"
] | 16 | 2016-06-12T09:22:22.000Z | 2021-07-31T07:35:35.000Z | DJTableViewVM/Classes/AdvanceCells/InputCells/DJTableViewVMTextFieldRow.h | Dokay/DJTableViewVM | 11d44476d9bed15d0d07625b6f25a87878d7d4d7 | [
"MIT"
] | null | null | null | DJTableViewVM/Classes/AdvanceCells/InputCells/DJTableViewVMTextFieldRow.h | Dokay/DJTableViewVM | 11d44476d9bed15d0d07625b6f25a87878d7d4d7 | [
"MIT"
] | 3 | 2016-06-12T09:31:37.000Z | 2017-11-27T05:39:34.000Z | //
// DJTableViewVMTextFieldRow.h
// DJComponentTableViewVM
//
// Created by Dokay on 2017/3/1.
// Copyright © 2017年 dj226. All rights reserved.
//
#import "DJTableViewVMRow.h"
#import "DJInputRowProtocol.h"
NS_ASSUME_NONNULL_BEGIN
@interface DJTableViewVMTextFieldRow : DJTableViewVMRow<DJInputRowProtocol>
//@property (nonatomic, assign) BOOL enabled;//whether cell is edit enable.default is YES.
@property (nonatomic, assign) UITableViewScrollPosition focusScrollPosition;//scrollPosition for cell be focus while input.default is UITableViewScrollPositionBottom.it works when keyboardManageEnabled in DJTableViewVM set YES.
@property (nullable, nonatomic, strong) UIColor *toolbarTintColor;
@property (nonatomic, assign) NSUInteger charactersMaxCount;//max characters can input.default is 0,means has no restrict.
@property (nonatomic, assign) CGFloat textFiledLeftMargin;//left margin for textFiled.default is 0.
#pragma mark - UITextInputTraits properties
@property(nonatomic) UITextAutocapitalizationType autocapitalizationType; // default is UITextAutocapitalizationTypeSentences
@property(nonatomic) UITextAutocorrectionType autocorrectionType; // default is UITextAutocorrectionTypeDefault
@property(nonatomic) UITextSpellCheckingType spellCheckingType NS_AVAILABLE_IOS(5_0); // default is UITextSpellCheckingTypeDefault;
@property(nonatomic) UIKeyboardType keyboardType; // default is UIKeyboardTypeDefault
@property(nonatomic) UIKeyboardAppearance keyboardAppearance; // default is UIKeyboardAppearanceDefault
@property(nonatomic) UIReturnKeyType returnKeyType; // default is UIReturnKeyDefault (See note under UIReturnKeyType enum)
@property(nonatomic) BOOL enablesReturnKeyAutomatically; // default is NO (when YES, will automatically disable return key when text widget has zero-length contents, and will automatically enable when text widget has non-zero-length contents)
@property(nonatomic,getter=isSecureTextEntry) BOOL secureTextEntry; // default is NO
#pragma mark - UITextField properties
@property(nullable, nonatomic,copy) NSString *text; // default is nil
@property(nullable, nonatomic,copy) NSAttributedString *attributedText NS_AVAILABLE_IOS(6_0); // default is nil
@property(nullable, nonatomic,strong) UIColor *textColor; // default is nil. use opaque black
@property(nullable, nonatomic,strong) UIFont *font; // default is nil. use system font 12 pt
@property(nonatomic) NSTextAlignment textAlignment; // default is NSLeftTextAlignment
@property(nonatomic) UITextBorderStyle borderStyle; // default is UITextBorderStyleNone. If set to UITextBorderStyleRoundedRect, custom background images are ignored.
@property(nonatomic,copy) NSDictionary<NSString *, id> *defaultTextAttributes NS_AVAILABLE_IOS(7_0); // applies attributes to the full range of text. Unset attributes act like default values.
@property(nullable, nonatomic,copy) NSString *placeholder; // default is nil. string is drawn 70% gray
@property(nullable, nonatomic,copy) NSAttributedString *attributedPlaceholder NS_AVAILABLE_IOS(6_0); // default is nil
@property(nonatomic) BOOL clearsOnBeginEditing; // default is NO which moves cursor to location clicked. if YES, all text cleared
@property(nonatomic) BOOL adjustsFontSizeToFitWidth; // default is NO. if YES, text will shrink to minFontSize along baseline
@property(nonatomic) CGFloat minimumFontSize; // default is 0.0. actual min may be pinned to something readable. used if adjustsFontSizeToFitWidth is YES
@property(nullable, nonatomic,strong) UIImage *background; // default is nil. draw in border rect. image should be stretchable
@property(nullable, nonatomic,strong) UIImage *disabledBackground; // default is nil. ignored if background not set. image should be stretchable
@property(nonatomic) UITextFieldViewMode clearButtonMode; // sets when the clear button shows up. default is UITextFieldViewModeNever
@property(nullable, nonatomic,strong) UIView *leftView; // e.g. magnifying glass
@property(nonatomic) UITextFieldViewMode leftViewMode; // sets when the left view shows up. default is UITextFieldViewModeNever
@property(nullable, nonatomic,strong) UIView *rightView; // e.g. bookmarks button
@property(nonatomic) UITextFieldViewMode rightViewMode; // sets when the right view shows up. default is UITextFieldViewModeNever
// Presented when object becomes first responder. If set to nil, reverts to following responder chain. If
// set while first responder, will not take effect until reloadInputViews is called.
@property (nullable, readwrite, strong) UIView *inputView;
@property (nullable, nonatomic, strong) UIView *inputAccessoryView;
@property (nonatomic, assign) BOOL showInputAccessoryView;
@property(nonatomic) BOOL clearsOnInsertion NS_AVAILABLE_IOS(6_0); // defaults to NO. if YES, the selection UI is hidden, and inserting text will replace the contents of the field. changing the selection will automatically set this to NO.
#pragma mark - actions
@property (nonatomic, copy) void (^textChanged)(DJTableViewVMTextFieldRow *rowVM);
@property (nonatomic, copy) void (^didBeginEditing)(DJTableViewVMTextFieldRow *rowVM);
@property (nonatomic, copy) void (^didEndEditing)(DJTableViewVMTextFieldRow *rowVM);
@property (nonatomic, copy) void (^maxCountInputMore)(DJTableViewVMTextFieldRow *rowVM);
@property (nonatomic, copy) void (^didEndEditingWithReason)(DJTableViewVMTextFieldRow *rowVM,UITextFieldDidEndEditingReason reason) NS_AVAILABLE_IOS(10_0);
@property (nonatomic, copy) BOOL (^shouldReturn)(DJTableViewVMTextFieldRow *rowVM);
@property (nonatomic, copy) BOOL (^shouldBeginEditing)(DJTableViewVMTextFieldRow *rowVM);
@property (nonatomic, copy) BOOL (^shouldEndEditing)(DJTableViewVMTextFieldRow *rowVM);
@property (nonatomic, copy) BOOL (^shouldChangeCharacterInRange)(DJTableViewVMTextFieldRow *rowVM, NSRange range, NSString *replacementString);
@property (nonatomic, copy) BOOL (^shouldClear)(DJTableViewVMTextFieldRow *rowVM);
@end
NS_ASSUME_NONNULL_END
| 81.265823 | 259 | 0.756854 | [
"object"
] |
b9db15fcf1e16cae3ca48f7926d16982224ddef0 | 7,885 | c | C | btmux/btech/btpr/pqueue.c | murrayma/btmux | 3519fdbfb9d5d27b4ce8e46ee16796961f1a0bfa | [
"ClArtistic",
"Naumen",
"Condor-1.1",
"MS-PL"
] | 2 | 2021-11-04T01:27:46.000Z | 2022-03-31T01:04:17.000Z | btmux/btech/btpr/pqueue.c | murrayma/btmux | 3519fdbfb9d5d27b4ce8e46ee16796961f1a0bfa | [
"ClArtistic",
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2019-02-14T00:37:44.000Z | 2019-02-15T22:02:21.000Z | btmux/btech/btpr/pqueue.c | murrayma/btmux | 3519fdbfb9d5d27b4ce8e46ee16796961f1a0bfa | [
"ClArtistic",
"Naumen",
"Condor-1.1",
"MS-PL"
] | 1 | 2020-04-12T12:39:54.000Z | 2020-04-12T12:39:54.000Z | /*
* Implements a binary heap-based priority queue. Heaps make it easy to answer
* the question, "What's the smallest/largest item in my heap?" but they're
* completely useless for ordered traversal, since a smaller item can be in
* either the left or right branch of the binary heap.
*
* As it turns out, I'm using a priority queue to re-implement the muxevent
* system, which relies on libevent to execute events in order and doesn't sort
* its lists at all, so it's all good.
*
* This implementation works a lot like the qsort() library function and
* friends: You need to tell it how big your items are, and you need to provide
* a comparison function.
*
* Items are stored in the heap. Values passed to bt_pqueue_add_item() are
* copied into the heap. Values are also copied in the heap during swap
* operations. Item sizes should thus be kept as small as possible. The
* upshot, though, is that we get really good cache locality.
*/
#include <stdlib.h>
#include <string.h>
#include "pqueue.h"
#undef bt_pq_nitems
#undef bt_pq_peek_top
#undef bt_pq_get_item
#include <assert.h>
#define MIN_MIN_NITEMS 1 /* 16 for production code? */
#define ITEM_SIZE (pq->item_size)
#define ITEM_STRIDE ITEM_SIZE
/*
* These macros rely on the queue being called "pq".
*/
#define ITEM(i) (pq->heap + (i) * ITEM_STRIDE)
#define CONST_ITEM(i) ((const bt_pq_item_t *)ITEM(i))
#define ITEM_IDX(p) (((p) - pq->heap) / ITEM_STRIDE)
#define HAS_ITEM(i) ((i) < pq->nitems)
#define PARENT(i) ((i - 1) >> 1)
#define LEFT(i) (((i) << 1) + 1)
#define RIGHT(i) (((i) << 1) + 2)
#define SET_ITEM(i,v) (memcpy(ITEM(i), (const bt_pq_item_t *)(v), ITEM_SIZE))
#define COPY_ITEM(i,j) (memcpy(ITEM(i), CONST_ITEM(j), ITEM_SIZE))
/* Heap size = 2^k * ITEM_SIZE. */
static int
grow_heap(bt_pq_t *pq, int new_nitems)
{
char *tmp_heap;
size_t tmp_size;
/* Try to grow by one step. */
/* FIXME: Handle overflow. */
if (pq->heap_size >= (new_nitems * ITEM_SIZE))
return 1;
tmp_size = pq->heap_size << 1;
if (!(tmp_heap = (char *)realloc(pq->heap, tmp_size)))
return 0; /* XXX */
pq->heap = tmp_heap;
pq->heap_size = tmp_size;
return 1;
}
static void
shrink_heap(bt_pq_t *pq, int new_nitems)
{
char *tmp_heap;
size_t tmp_size;
/* Try to shrink by two steps (to add some hysteresis). */
tmp_size = pq->heap_size >> 2;
if (tmp_size < (new_nitems * ITEM_SIZE)) {
/* Can't shrink by two steps. */
return;
}
/* Only actually shrink by one step. */
tmp_size = pq->heap_size >> 1;
if (tmp_size < (pq->min_nitems * ITEM_SIZE)) {
/* Shrinking would violate min_nitems. */
return;
}
/* Reallocate. */
if (!(tmp_heap = (char *)realloc(pq->heap, tmp_size)))
return; /* no problem */
pq->heap = tmp_heap;
pq->heap_size = tmp_size;
}
bt_pq_t *
bt_pq_create(int min_nitems, size_t item_size, bt_comp_func_t item_comp_func)
{
bt_pq_t *pq;
int tmp_nitems;
/* Initialize priority queue object. */
if (!(pq = (bt_pq_t *)malloc(sizeof(bt_pq_t))))
return NULL;
pq->nitems = 0;
pq->comp_func = item_comp_func;
ITEM_SIZE = item_size; /* force a compile time error when ITEM_SIZE
isn't an lvalue */
if (min_nitems < MIN_MIN_NITEMS)
/* Keep the user from shooting us in the foot. */
min_nitems = MIN_MIN_NITEMS;
pq->min_nitems = min_nitems;
/* Initialize heap. */
tmp_nitems = 1;
while (tmp_nitems < min_nitems)
/* FIXME: Handle overflow. */
tmp_nitems <<= 1;
pq->heap_size = tmp_nitems * ITEM_SIZE;
if (!(pq->heap = (char *)malloc(pq->heap_size))) {
free(pq);
return NULL;
}
return pq;
}
void
bt_pq_destroy(bt_pq_t *pq)
{
free(pq->heap);
free(pq);
}
/* Find the smallest among this node and its children to bubble here. */
typedef enum {
BUBBLE_NONE = 0,
BUBBLE_LEFT = -1,
BUBBLE_RIGHT = 1,
} bubble_t;
static bubble_t
choose_bubble_down(bt_pq_t *pq, const bt_pq_item_t *root_item, int root_ii)
{
const int left_ii = LEFT(root_ii);
const int right_ii = RIGHT(root_ii);
if (!HAS_ITEM(left_ii)) {
/* No children. */
return BUBBLE_NONE;
}
if (pq->comp_func(root_item, CONST_ITEM(left_ii)) <= 0) {
/* <=LEFT, maybe >RIGHT. */
if (!HAS_ITEM(right_ii)) {
/* <=LEFT. */
return BUBBLE_NONE;
}
if (pq->comp_func(root_item, CONST_ITEM(right_ii)) <= 0) {
/* <=LEFT and <=RIGHT. */
return BUBBLE_NONE;
} else {
/* >RIGHT. */
return BUBBLE_RIGHT;
}
} else {
/* >LEFT. Is LEFT or RIGHT smaller? */
if (!HAS_ITEM(right_ii)) {
/* >LEFT. */
return BUBBLE_LEFT;
}
if (pq->comp_func(CONST_ITEM(left_ii),
CONST_ITEM(right_ii)) < 0) {
/* LEFT < RIGHT. */
return BUBBLE_LEFT;
} else {
/* LEFT >= RIGHT. */
return BUBBLE_RIGHT;
}
}
}
/*
* Bubble down:
*
* 1) If this > L, bubble down left.
* If this > R, bubble down right.
* If this > L and this > R, bubble down smaller of L and R.
* 2) Otherwise done.
* 3) Repeat from step 1 at new position.
*/
static void
bubble_down(bt_pq_t *pq, const bt_pq_item_t *this_item, int this_ii)
{
for (;;) {
switch (choose_bubble_down(pq, this_item, this_ii)) {
case BUBBLE_LEFT:
COPY_ITEM(this_ii, LEFT(this_ii));
this_ii = LEFT(this_ii);
break;
case BUBBLE_RIGHT:
COPY_ITEM(this_ii, RIGHT(this_ii));
this_ii = RIGHT(this_ii);
break;
default:
SET_ITEM(this_ii, this_item);
return;
}
}
}
/*
* Bubble up:
*
* 1) If this < V, bubble up.
* 2) Otherwise done.
* 3) Repeat from step 1 at new position.
*/
static void
bubble_up(bt_pq_t *pq, const bt_pq_item_t *this_item, int this_ii)
{
int parent_ii;
for (;;) {
assert(this_ii >= 0);
if (this_ii == 0) {
/* No parent. */
SET_ITEM(this_ii, this_item);
return;
}
parent_ii = PARENT(this_ii);
if (pq->comp_func(this_item, CONST_ITEM(parent_ii)) < 0) {
/* <PARENT. */
COPY_ITEM(this_ii, parent_ii);
this_ii = parent_ii;
} else {
/* >=PARENT. */
SET_ITEM(this_ii, this_item);
return;
}
}
}
/* item_value is copied into the heap. */
int
bt_pq_add_item(bt_pq_t *pq, const bt_pq_item_t *item_value)
{
int this_ii;
/* Add item to heap.
*
* 1) Add this item as last leaf in heap.
* 2) This item has no children. If it is smaller than its parent,
* bubble up.
*/
/* Grow heap if necessary. */
if (!grow_heap(pq, pq->nitems + 1))
return 0;
this_ii = pq->nitems++;
/* Bubble up. */
bubble_up(pq, item_value, this_ii);
return 1;
}
/* item is inside the heap. */
int
bt_pq_remove_item(bt_pq_t *pq, const bt_pq_item_t *item)
{
int this_ii, root_ii;
/* Remove item from heap.
*
* 1) Replace this item with last leaf in heap.
* 2) This leaf generally has no particular relationship with the new
* parent/children, as it may come from a separate subheap.
*
* If P <= this, then bubble down (and only down).
* If this < P, then bubble up (and only up).
*/
root_ii = ITEM_IDX(item);
if (root_ii < 0 || !HAS_ITEM(root_ii)) {
/* Item isn't in this heap. */
return 0;
}
assert(pq->nitems > 0);
this_ii = --pq->nitems;
/* Bubble last leaf into position. */
if (root_ii == this_ii) {
/* Last leaf was removed item. */
} else if (root_ii != 0
&& pq->comp_func(ITEM(this_ii), ITEM(PARENT(root_ii))) < 0) {
/* Bubble up. */
bubble_up(pq, ITEM(this_ii), root_ii);
} else {
/* Bubble down. */
bubble_down(pq, ITEM(this_ii), root_ii);
}
/* Shrink heap if necessary. */
shrink_heap(pq, pq->nitems);
return 1;
}
int
bt_pq_nitems(const bt_pq_t *pq)
{
return pq->nitems;
}
bt_pq_item_t *
bt_pq_peek_top(const bt_pq_t *pq)
{
return ITEM(0);
}
/* This isn't fast for heaps in general, but it's a convenient operation for
* this particular implementation. Don't rely on it if the implementation is
* going to change in the future.
*/
bt_pq_item_t *
bt_pq_get_item(const bt_pq_t *pq, int ii)
{
return ITEM(ii);
}
| 22.086835 | 79 | 0.648954 | [
"object"
] |
0271e5f693ef9ef206a1e60a8856192adaf371c1 | 969 | h | C | source/apps/demos/nckDemo_ShadowsProjector.h | nczeroshift/nctoolkit | c9f0be533843d52036ec45200512ac54c1faeb11 | [
"MIT"
] | 2 | 2016-10-16T22:26:01.000Z | 2022-03-29T14:32:15.000Z | source/apps/demos/nckDemo_ShadowsProjector.h | nczeroshift/nctoolkit | c9f0be533843d52036ec45200512ac54c1faeb11 | [
"MIT"
] | 1 | 2015-12-08T00:27:10.000Z | 2016-10-30T21:59:50.000Z | source/apps/demos/nckDemo_ShadowsProjector.h | nczeroshift/nctoolkit | c9f0be533843d52036ec45200512ac54c1faeb11 | [
"MIT"
] | 2 | 2016-07-18T21:42:10.000Z | 2019-12-16T01:33:20.000Z |
/**
* NCtoolKit © 2007-2017 Luís F.Loureiro, under zlib software license.
* https://github.com/nczeroshift/nctoolkit
*/
#ifndef _NCK_DEMO_SHADOWSPROJECTOR_H_
#define _NCK_DEMO_SHADOWSPROJECTOR_H_
#include "../nckDemo.h"
class Demo_ShadowsProjector : public Demo{
public:
Demo_ShadowsProjector(Core::Window * wnd, Graph::Device * dev);
~Demo_ShadowsProjector();
void Load();
void Render(float dt);
void UpdateWndEvents();
std::vector<std::string> GetKeywords();
std::string GetDescription();
private:
int bufferSize;
Scene::Compound_Base * scene;
Scene::Camera * camera;
Scene::Lamp * lamp;
Graph::RTManager * rtShadow, *rtDirect;
Graph::Texture2D * texShadow, * texColor, * texPosition, * texNormal;
Math::Mat44 lampProjViewMat;
Math::Mat44 lampViewMat;
Graph::Program * program, *depth, *display, *sampler;
float time;
};
Demo * CreateDemo_ShadowsProjector(Core::Window * wnd, Graph::Device * dev);
#endif
| 22.534884 | 76 | 0.71001 | [
"render",
"vector"
] |
027ba7c055f6a8c7d96183547a0f9f18623a2e81 | 1,531 | h | C | src/cpp/SUNCGMetadata.h | SiyuanQi/human-centric-scene-synthesis | 6f2215d07052426f0f4a27b8ca71844ea5d347c4 | [
"MIT"
] | 77 | 2018-02-25T00:59:18.000Z | 2022-03-27T15:55:21.000Z | src/cpp/SUNCGMetadata.h | Pandinosaurus/human-centric-scene-synthesis | 6f2215d07052426f0f4a27b8ca71844ea5d347c4 | [
"MIT"
] | 4 | 2018-03-05T12:54:27.000Z | 2018-09-10T14:56:59.000Z | src/cpp/SUNCGMetadata.h | Pandinosaurus/human-centric-scene-synthesis | 6f2215d07052426f0f4a27b8ca71844ea5d347c4 | [
"MIT"
] | 15 | 2018-02-23T21:19:39.000Z | 2022-01-01T12:21:32.000Z | //
// Created by siyuan on 1/20/17.
//
#ifndef CVPR2018_SUNCGMETADATA_H
#define CVPR2018_SUNCGMETADATA_H
#include <fstream>
#include <vector>
#include <algorithm>
#include <boost/tokenizer.hpp>
#include "helper.h"
namespace ub = boost::numeric::ublas;
namespace FurnitureArranger {
class SUNCGMetadata {
public:
SUNCGMetadata();
void read_metadata(std::string metadataPath);
void read_models(std::string metadataPath);
void read_model_category_mapping(std::string metadataPath);
ub::vector<double> get_min_piont(std::string modelID) const;
ub::vector<double> get_dims(std::string modelID) const;
std::string get_category(std::string modelID) const;
std::string get_coarse_category(std::string modelID) const;
std::string get_coarse_category_from_fine(std::string fineCategory) const;
static ub::vector<double> string_to_vector(std::string inputString, std::string delim);
private:
std::vector<std::string> modelsId;
std::vector<ub::vector<double>> modelsMinPoint;
std::vector<ub::vector<double>> modelsMaxPoint;
std::vector<ub::vector<double>> modelsAlignedDims;
std::vector<std::string> categoryModelId;
std::vector<std::string> categoryFineGrainedClass;
std::vector<std::string> categoryCoarseGrainedClass;
int find_model_index(std::string modelID) const;
int find_category_index(std::string modelID) const;
};
}
#endif //CVPR2018_SUNCGMETADATA_H
| 29.442308 | 95 | 0.701502 | [
"vector"
] |
029b882358f8b429be8a768c677df41e3539ca03 | 4,439 | h | C | uuv_gazebo_plugins/uuv_gazebo_plugins/include/uuv_gazebo_plugins/UmbilicalModel.h | oKermorgant/Plankton | ce21579792122b05d27f147ab66f515001ccb733 | [
"Apache-2.0",
"BSD-3-Clause"
] | 79 | 2020-09-30T22:19:07.000Z | 2022-03-27T12:30:58.000Z | uuv_gazebo_plugins/uuv_gazebo_plugins/include/uuv_gazebo_plugins/UmbilicalModel.h | oKermorgant/Plankton | ce21579792122b05d27f147ab66f515001ccb733 | [
"Apache-2.0",
"BSD-3-Clause"
] | 17 | 2020-10-05T01:01:49.000Z | 2022-03-04T13:58:53.000Z | uuv_gazebo_plugins/uuv_gazebo_plugins/include/uuv_gazebo_plugins/UmbilicalModel.h | oKermorgant/Plankton | ce21579792122b05d27f147ab66f515001ccb733 | [
"Apache-2.0",
"BSD-3-Clause"
] | 22 | 2020-10-27T14:42:48.000Z | 2022-03-25T10:41:51.000Z | // Copyright (c) 2020 The Plankton Authors.
// All rights reserved.
//
// This source code is derived from UUV Simulator
// (https://github.com/uuvsimulator/uuv_simulator)
// Copyright (c) 2016-2019 The UUV Simulator Authors
// licensed under the Apache license, Version 2.0
// cf. 3rd-party-licenses.txt file in the root directory of this source tree.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// \file UmbilicalModel.hh
/// \brief Various umbilical models.
#ifndef __UUV_GAZEBO_PLUGINS_UMBILICAL_MODEL_HH__
#define __UUV_GAZEBO_PLUGINS_UMBILICAL_MODEL_HH__
#include <string>
#include <map>
#include <gazebo/gazebo.hh>
#include <gazebo/common/UpdateInfo.hh>
#include <gazebo/physics/Link.hh>
#include <gazebo/physics/Model.hh>
#include <sdf/sdf.hh>
namespace gazebo
{
class UmbilicalModel
{
/// \brief Protected constructor: Use the factory instead
protected: UmbilicalModel() {}
/// \brief Destructor.
public: virtual ~UmbilicalModel() {}
/// \brief Initialize model.
public: virtual void Init();
/// \brief Update Umbilical (and apply forces)
public: virtual void OnUpdate(const common::UpdateInfo &_info,
const ignition::math::Vector3d& _flow) = 0;
/// \brief Gazebo model to which this umbilical belongs.
protected: physics::ModelPtr model;
/// \brief Moving connector link of this umbilical.
protected: physics::LinkPtr connector;
};
/// \brief Function pointer to create a certain conversion function.
typedef UmbilicalModel* (*UmbilicalModelCreator)(sdf::ElementPtr,
physics::ModelPtr);
/// \brief Factory singleton class that creates an UmbilicalModel from sdf.
class UmbilicalModelFactory
{
/// \brief Create a ConversionFunction object according to its sdf Description
public: UmbilicalModel* CreateUmbilicalModel(sdf::ElementPtr _sdf,
physics::ModelPtr _model);
/// \brief Return the singleton instance of this factory.
public: static UmbilicalModelFactory& GetInstance();
/// \brief Register an UmbilicalModel class with its creator.
public: bool RegisterCreator(const std::string& _identifier,
UmbilicalModelCreator _creator);
/// \brief Constructor is private since this is a singleton.
private: UmbilicalModelFactory() {}
/// \brief Map of each registered identifiers to its corresponding creator
private: std::map<std::string, UmbilicalModelCreator> creators_;
};
/// Use the following macro within a ThrusterDynamics declaration:
#define REGISTER_UMBILICALMODEL(type) \
static const bool registeredWithFactory
/// Use the following macro before a ThrusterDynamics's definition:
#define REGISTER_UMBILICALMODEL_CREATOR(type, creator) \
const bool type::registeredWithFactory = \
UmbilicalModelFactory::GetInstance().RegisterCreator( \
type::IDENTIFIER, creator);
class UmbilicalModelBerg : public UmbilicalModel
{
/// \brief Protected constructor: Use the factory instead
protected: UmbilicalModelBerg(sdf::ElementPtr _sdf,
physics::ModelPtr _model);
/// \brief Create UmbilicalModel according to its description.
public: static UmbilicalModel* create(sdf::ElementPtr _sdf,
physics::ModelPtr _model);
/// \brief Update Umbilical (and apply forces)
public: virtual void OnUpdate(const common::UpdateInfo &_info,
const ignition::math::Vector3d& _flow);
/// \brief Register this UmbilicalModel function with the factory.
private: REGISTER_UMBILICALMODEL(UmbilicalModelBerg);
/// \brief The unique identifier of this UmbilicalModel.
private: static const std::string IDENTIFIER;
/// \brief Umbilical diameter.
private: double diameter;
/// \brief Water density.
private: double rho;
};
}
#endif // __UUV_GAZEBO_PLUGINS_UMBILICAL_MODEL_HH__
| 35.798387 | 80 | 0.716378 | [
"object",
"model"
] |
02aa3c02c0ff5282817234afd6d4f143460c7e96 | 111 | h | C | python2c/c_utils/Char.h | mkturkcan/Neuropiler | 5caf0546d8194f4485ccae46d71b2eec2eaa3b50 | [
"BSD-3-Clause"
] | 5 | 2015-12-13T05:50:44.000Z | 2022-01-17T17:51:38.000Z | python2c/c_utils/Char.h | mkturkcan/Neuropiler | 5caf0546d8194f4485ccae46d71b2eec2eaa3b50 | [
"BSD-3-Clause"
] | null | null | null | python2c/c_utils/Char.h | mkturkcan/Neuropiler | 5caf0546d8194f4485ccae46d71b2eec2eaa3b50 | [
"BSD-3-Clause"
] | 3 | 2020-03-20T14:29:59.000Z | 2021-09-18T06:24:24.000Z | #ifndef __CHAR
#define __CHAR
// Char general
Object *new_Char(char c);
void destroy_Char(Object *c);
#endif | 12.333333 | 29 | 0.738739 | [
"object"
] |
02b7ea8bcf36182e46ffe0dcf3b1211f6fa5a91d | 103,368 | h | C | GBA/files/scene_Voyoger.h | H5L0/GBA_Raytracing | 9644b55b9442cddc88ca315fe6ef20f2a189f64b | [
"MIT"
] | 3 | 2020-03-10T23:21:39.000Z | 2020-07-01T17:13:05.000Z | GBA/files/scene_Voyoger.h | H5L0/GBA_Raytracing | 9644b55b9442cddc88ca315fe6ef20f2a189f64b | [
"MIT"
] | null | null | null | GBA/files/scene_Voyoger.h | H5L0/GBA_Raytracing | 9644b55b9442cddc88ca315fe6ef20f2a189f64b | [
"MIT"
] | null | null | null | #pragma once
const int scene_Voyoger[] = {
0x00000029,0x0000002B,//场景全部物体数量
0x0000002C,0x00000029,//Transform、Children数量
0x00000056,//数据安排信息计数
0xFFFFFFFF,0x00000001,0x00000000,0x00000001,
0xFFFFFFFF,0x00000002,0x00000002,0x00000003,
0xFFFFFFFF,0x00000003,0x00000004,0x00000005,
0xFFFFFFFF,0x00000004,0x00000006,0x00000007,
0xFFFFFFFF,0x00000005,0x00000008,0x00000009,
0xFFFFFFFF,0x00000006,0x0000000A,0x0000000B,
0xFFFFFFFF,0x00000007,0x0000000C,0x0000000D,
0xFFFFFFFF,0x00000008,0x0000000E,0x0000000F,
0xFFFFFFFF,0x00000009,0x00000010,0x00000011,
0xFFFFFFFF,0x0000000A,0x00000012,0x00000013,
0xFFFFFFFF,0x0000000B,0x00000014,0x00000015,
0xFFFFFFFF,0x0000000C,0x00000016,0x00000017,
0xFFFFFFFF,0x0000000D,0x00000018,0x00000019,
0xFFFFFFFF,0x0000000E,0x0000001A,0x0000001B,
0xFFFFFFFF,0x0000000F,0x0000001C,0x0000001D,
0xFFFFFFFF,0x00000010,0x0000001E,0x0000001F,
0xFFFFFFFF,0x00000011,0x00000020,0x00000021,
0xFFFFFFFF,0x00000012,0x00000022,0x00000023,
0xFFFFFFFF,0x00000013,0x00000024,0x00000025,
0xFFFFFFFF,0x00000014,0x00000026,0x00000027,
0xFFFFFFFF,0x00000015,0x00000028,0x00000029,
0xFFFFFFFF,0x00000016,0x0000002A,0x0000002B,
0xFFFFFFFF,0x00000017,0x0000002C,0x0000002D,
0xFFFFFFFF,0x00000018,0x0000002E,0x0000002F,
0xFFFFFFFF,0x00000019,0x00000030,0x00000031,
0xFFFFFFFF,0x0000001A,0x00000032,0x00000033,
0xFFFFFFFF,0x0000001B,0x00000034,0x00000035,
0xFFFFFFFF,0x0000001C,0x00000036,0x00000037,
0xFFFFFFFF,0x0000001D,0x00000038,0x00000039,
0xFFFFFFFF,0x0000001E,0x0000003A,0x0000003B,
0xFFFFFFFF,0x0000001F,0x0000003C,0x0000003D,
0xFFFFFFFF,0x00000020,0x0000003E,0x0000003F,
0xFFFFFFFF,0x00000021,0x00000040,0x00000041,
0xFFFFFFFF,0x00000022,0x00000042,0x00000043,
0xFFFFFFFF,0x00000023,0x00000044,0x00000045,
0xFFFFFFFF,0x00000024,0x00000046,0x00000047,
0xFFFFFFFF,0x00000025,0x00000048,0x00000049,
0xFFFFFFFF,0x00000026,0x0000004A,0x0000004B,
0xFFFFFFFF,0x00000027,0x0000004C,0x0000004D,
0xFFFFFFFF,0x00000028,0x0000004E,0x0000004F,
0xFFFFFFFF,0x00000029,0x00000050,0x00000051,
0xFFFFFFFF,0x0000002A,0x00000052,0x00000053,
0xFFFFFFFF,0x0000002B,0x00000054,0x00000055,//实体
0x00000000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000029,0x00152053,0xFFED8800,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0xFFEF92A6,0xFFCF6BBC,0x00000000,0x00100000,
0x00000000,0x00000000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0xFFFFE26F,0xFFCF6BBC,
0xFFEF3B3F,0x00100000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00113C79,0xFFCF6BBC,0x00000144,0x00100000,
0x00000000,0x00000000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x000089BD,0xFFCF6BBC,
0x0010C5A1,0x00100000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFEFB1EF,0xFFECEC6F,0x00100000,
0x00000000,0x00000000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF6CE87,
0xFFE17140,0x00100000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFFD9F5C,0x002854C8,0x00100000,
0x00000000,0x00000000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFFD9F5C,
0x0050586A,0x00100000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x0004F934,0x00027E39,0x0050586A,0x00100000,
0x00000000,0x00000000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0xFFFCDFF8,0xFFFC392F,
0x0050586A,0x00100000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0x00017787,0x003C3B08,0x00100000,
0x00000000,0x00000000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0xFFF6FE82,0xFFF82405,
0x0050586A,0x00100000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0xFFEEE0A2,0xFFF8F69C,0x00505D77,0x00100000,
0x00000000,0x00000000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0xFFFFFFFB,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0x0022F224,0x00000000,0x00100000,
0x00000000,0x00000000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0x0024F4C8,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFFCEA21,0x00000000,0x00100000,
0x00000000,0x00000000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0xFFEFD4B4,0xFFD0BEAE,
0x0000FEA3,0x00100000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0xFFEFD4B4,0xFFD0BEAE,0xFFFF030D,0x00100000,
0x00000000,0x00000000,0x00000000,0x00000000,
0xFFF00001,0x00000000,0xFFFEE3CC,0xFFD0BEAE,
0xFFEF7D4D,0x00100000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x0000DF61,0xFFD0BEAE,0xFFEF7D4D,0x00100000,
0x00000000,0x00000000,0x00000000,0x00000000,
0xFFF00001,0x00000000,0x0010FA6B,0xFFD0BEAE,
0xFFFF02A1,0x00100000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x0010FA6B,0xFFD0BEAE,0x0000FE37,0x00100000,
0x00000000,0x00000000,0x00000000,0x00000000,
0xFFF00001,0x00000000,0x00018860,0xFFD0BEAE,
0x00108393,0x00100000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0xFFFF8CCB,0xFFD0BEAE,0x00108393,0x00100000,
0x00000000,0x00000000,0x00000000,0x00000000,
0xFFF00001,0x00000000,0x00000000,0xFFF1F869,
0xFFE94C3F,0x00100000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFDE7D47,0xFFDA774C,0x00100000,
0x00000000,0x00000000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFDE7D47,
0xFFCDB01B,0x00100000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFDE7D47,0xFFC10630,0x00100000,
0x00000000,0x00000000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF7F9B3,
0x004CE628,0x00100000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0xFFF0221A,0xFFF04287,0x004A263E,0x00100000,
0x00000000,0x00000000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0xFFF0221A,0xFFF04287,
0x004C5F1F,0x00100000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF49472,0x00000000,0x00100000,
0x00000000,0x00000000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x0014338F,0xFFF62249,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x001053D9,0xFFF62249,0xFFF41C16,0x00100000,
0x00000000,0x00000000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00007B59,0xFFD70DD4,
0x0014EC3F,0x00100000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00107E97,0x0003158F,0x00000000,0x00100000,
0x00000000,0x00000000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0xFFF80305,0x0003158F,
0x000E3DF3,0x00100000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0xFFF7D27D,0x0003158F,0xFFF19C02,0x00100000,
0x00000000,0x00000000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF24C47,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00319999,0xFF59C28F,0xFF71999A,0x00100000,
0x00000000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0xFF133333,0x009E6666,
0xFF933333,0x000859B9,0x0000B9ED,0xFFF25F0D,
0x00073373,0x000D5685,0x00051F77,0x00000000,//变换信息
0x00000001,0x00000002,0x00000003,0x00000004,
0x00000005,0x00000006,0x00000007,0x00000008,
0x00000009,0x0000000A,0x0000000B,0x0000000C,
0x0000000D,0x0000000E,0x0000000F,0x00000010,
0x00000011,0x00000012,0x00000013,0x00000014,
0x00000015,0x00000016,0x00000017,0x00000018,
0x00000019,0x0000001A,0x0000001B,0x0000001C,
0x0000001D,0x0000001E,0x0000001F,0x00000020,
0x00000021,0x00000022,0x00000023,0x00000024,
0x00000025,0x00000026,0x00000027,0x00000028,
0x00000029,//子对象列表
0x0000A003,0x000002B0,0x0000B001,0x00000540,
0x0000A003,0x00000554,0x0000B001,0x000007E4,
0x0000A003,0x000007F8,0x0000B001,0x00000A88,
0x0000A003,0x00000A9C,0x0000B001,0x00000D2C,
0x0000A003,0x00000D40,0x0000B001,0x00000FD0,
0x0000A003,0x00000FE4,0x0000B001,0x00001274,
0x0000A003,0x00001288,0x0000B001,0x00001518,
0x0000A003,0x0000152C,0x0000B001,0x000017BC,
0x0000A003,0x000017D0,0x0000B001,0x00001A60,
0x0000A003,0x00001A74,0x0000B001,0x00001D04,
0x0000A003,0x00001D18,0x0000B001,0x000020F8,
0x0000A003,0x0000210C,0x0000B001,0x0000239C,
0x0000A003,0x000023B0,0x0000B001,0x00002640,
0x0000A003,0x00002654,0x0000B001,0x000028E4,
0x0000A003,0x000028F8,0x0000B001,0x0000380C,
0x0000A003,0x00003820,0x0000B001,0x00003E40,
0x0000A003,0x00003E54,0x0000B001,0x0000412C,
0x0000A003,0x00004140,0x0000B001,0x00004418,
0x0000A003,0x0000442C,0x0000B001,0x00004578,
0x0000A003,0x0000458C,0x0000B001,0x000046D8,
0x0000A003,0x000046EC,0x0000B001,0x00004838,
0x0000A003,0x0000484C,0x0000B001,0x00004998,
0x0000A003,0x000049AC,0x0000B001,0x00004AF8,
0x0000A003,0x00004B0C,0x0000B001,0x00004C58,
0x0000A003,0x00004C6C,0x0000B001,0x00004DB8,
0x0000A003,0x00004DCC,0x0000B001,0x00004F18,
0x0000A003,0x00004F2C,0x0000B001,0x00005234,
0x0000A003,0x00005248,0x0000B001,0x00005670,
0x0000A003,0x00005684,0x0000B001,0x00005AAC,
0x0000A003,0x00005AC0,0x0000B001,0x00006128,
0x0000A003,0x0000613C,0x0000B001,0x00006444,
0x0000A003,0x00006458,0x0000B001,0x000067D8,
0x0000A003,0x000067EC,0x0000B001,0x00006AF4,
0x0000A000,0x00006B08,0x0000B001,0x00006B0C,
0x0000A003,0x00006B20,0x0000B001,0x00006CD8,
0x0000A003,0x00006CEC,0x0000B001,0x00006EA4,
0x0000A003,0x00006EB8,0x0000B001,0x00006F2C,
0x0000A003,0x00006F40,0x0000B001,0x000070F8,
0x0000A003,0x0000710C,0x0000B001,0x000072C4,
0x0000A003,0x000072D8,0x0000B001,0x00007490,
0x0000A003,0x000074A4,0x0000B001,0x000081CC,
0x0000A000,0x000081E0,0x0000B000,0x000081E4,
0x0000A002,0x000081EC,0x0000B000,0x000081F8,//数据安排信息
0x000C0018,0x00000018,0x00000000,0x00051EB8,
0xFFFC0000,0x00000000,0xFFFAE148,0x00040000,
0x00000000,0x00051EB8,0x00040000,0x00000000,
0xFFFAE148,0xFFFC0000,0x0000CCCC,0x00051EB8,
0xFFFC0000,0x0000CCCC,0xFFFAE148,0x0003FFFF,
0x0000CCCC,0xFFFAE148,0xFFFC0000,0x0000CCCC,
0x00051EB8,0x0003FFFF,0x00000000,0x00051EB8,
0xFFFC0000,0x0000CCCC,0xFFFAE148,0xFFFC0000,
0x00000000,0xFFFAE148,0xFFFC0000,0x0000CCCC,
0x00051EB8,0xFFFC0000,0x00000000,0xFFFAE148,
0xFFFC0000,0x0000CCCC,0xFFFAE148,0x0003FFFF,
0x00000000,0xFFFAE148,0x00040000,0x0000CCCC,
0xFFFAE148,0xFFFC0000,0x00000000,0xFFFAE148,
0x00040000,0x0000CCCC,0x00051EB8,0x0003FFFF,
0x00000000,0x00051EB8,0x00040000,0x0000CCCC,
0xFFFAE148,0x0003FFFF,0x00000000,0x00051EB8,
0x00040000,0x0000CCCC,0x00051EB8,0xFFFC0000,
0x00000000,0x00051EB8,0xFFFC0000,0x0000CCCC,
0x00051EB8,0x0003FFFF,0x00010000,0x00010002,
0x00030000,0x00050004,0x00050006,0x00070004,
0x00090008,0x0009000A,0x000B0008,0x000D000C,
0x000D000E,0x000F000C,0x00110010,0x00110012,
0x00130010,0x00150014,0x00150016,0x00170014,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x027903B2,0x030000E8,0x03000200,0x00000000,
0x00000000,0x000C0018,0x00000018,0x00019999,
0xFFFCCCCD,0x00000000,0xFFFE6667,0x00033333,
0x00000000,0x00019999,0x00033333,0x00000000,
0xFFFE6667,0xFFFCCCCD,0x00000000,0x00019999,
0xFFFCCCCD,0x00019999,0xFFFE6667,0x00033333,
0x00019999,0xFFFE6667,0xFFFCCCCD,0x00019999,
0x00019999,0x00033333,0x00019999,0x00019999,
0xFFFCCCCD,0x00000000,0xFFFE6667,0xFFFCCCCD,
0x00019999,0xFFFE6667,0xFFFCCCCD,0x00000000,
0x00019999,0xFFFCCCCD,0x00019999,0xFFFE6667,
0xFFFCCCCD,0x00000000,0xFFFE6667,0x00033333,
0x00019999,0xFFFE6667,0x00033333,0x00000000,
0xFFFE6667,0xFFFCCCCD,0x00019999,0xFFFE6667,
0x00033333,0x00000000,0x00019999,0x00033333,
0x00019999,0x00019999,0x00033333,0x00000000,
0xFFFE6667,0x00033333,0x00019999,0x00019999,
0x00033333,0x00000000,0x00019999,0xFFFCCCCD,
0x00019999,0x00019999,0xFFFCCCCD,0x00000000,
0x00019999,0x00033333,0x00019999,0x00010000,
0x00010002,0x00030000,0x00050004,0x00050006,
0x00070004,0x00090008,0x0009000A,0x000B0008,
0x000D000C,0x000D000E,0x000F000C,0x00110010,
0x00110012,0x00130010,0x00150014,0x00150016,
0x00170014,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00900090,0x02000090,0x020000CC,
0x00000000,0x00000000,0x000C0018,0x00000018,
0xFFFCCCCD,0xFFFE6667,0x00000000,0x00033333,
0x00019999,0x00000000,0x00033333,0xFFFE6667,
0x00000000,0xFFFCCCCD,0x00019999,0x00000000,
0xFFFCCCCD,0xFFFE6667,0x00019999,0x00033333,
0x00019999,0x00019999,0xFFFCCCCD,0x00019999,
0x00019999,0x00033333,0xFFFE6667,0x00019999,
0xFFFCCCCD,0xFFFE6667,0x00000000,0xFFFCCCCD,
0x00019999,0x00019999,0xFFFCCCCD,0x00019999,
0x00000000,0xFFFCCCCD,0xFFFE6667,0x00019999,
0xFFFCCCCD,0x00019999,0x00000000,0x00033333,
0x00019999,0x00019999,0x00033333,0x00019999,
0x00000000,0xFFFCCCCD,0x00019999,0x00019999,
0x00033333,0x00019999,0x00000000,0x00033333,
0xFFFE6667,0x00019999,0x00033333,0xFFFE6667,
0x00000000,0x00033333,0x00019999,0x00019999,
0x00033333,0xFFFE6667,0x00000000,0xFFFCCCCD,
0xFFFE6667,0x00019999,0xFFFCCCCD,0xFFFE6667,
0x00000000,0x00033333,0xFFFE6667,0x00019999,
0x00010000,0x00010002,0x00030000,0x00050004,
0x00050006,0x00070004,0x00090008,0x0009000A,
0x000B0008,0x000D000C,0x000D000E,0x000F000C,
0x00110010,0x00110012,0x00130010,0x00150014,
0x00150016,0x00170014,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00900090,0x02000090,
0x020000CC,0x00000000,0x00000000,0x000C0018,
0x00000018,0xFFFE6667,0x00033333,0x00000000,
0x00019999,0xFFFCCCCD,0x00000000,0xFFFE6667,
0xFFFCCCCD,0x00000000,0x00019999,0x00033333,
0x00000000,0xFFFE6667,0x00033333,0x00019999,
0x00019999,0xFFFCCCCD,0x00019999,0x00019999,
0x00033333,0x00019999,0xFFFE6667,0xFFFCCCCD,
0x00019999,0xFFFE6667,0x00033333,0x00000000,
0x00019999,0x00033333,0x00019999,0x00019999,
0x00033333,0x00000000,0xFFFE6667,0x00033333,
0x00019999,0x00019999,0x00033333,0x00000000,
0x00019999,0xFFFCCCCD,0x00019999,0x00019999,
0xFFFCCCCD,0x00000000,0x00019999,0x00033333,
0x00019999,0x00019999,0xFFFCCCCD,0x00000000,
0xFFFE6667,0xFFFCCCCD,0x00019999,0xFFFE6667,
0xFFFCCCCD,0x00000000,0x00019999,0xFFFCCCCD,
0x00019999,0xFFFE6667,0xFFFCCCCD,0x00000000,
0xFFFE6667,0x00033333,0x00019999,0xFFFE6667,
0x00033333,0x00000000,0xFFFE6667,0xFFFCCCCD,
0x00019999,0x00010000,0x00010002,0x00030000,
0x00050004,0x00050006,0x00070004,0x00090008,
0x0009000A,0x000B0008,0x000D000C,0x000D000E,
0x000F000C,0x00110010,0x00110012,0x00130010,
0x00150014,0x00150016,0x00170014,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0x00900090,
0x02000090,0x020000CC,0x00000000,0x00000000,
0x000C0018,0x00000018,0x00033333,0x00019999,
0x00000000,0xFFFCCCCD,0xFFFE6667,0x00000000,
0xFFFCCCCD,0x00019999,0x00000000,0x00033333,
0xFFFE6667,0x00000000,0x00033333,0x00019999,
0x00019999,0xFFFCCCCD,0xFFFE6667,0x00019999,
0x00033333,0xFFFE6667,0x00019999,0xFFFCCCCD,
0x00019999,0x00019999,0x00033333,0x00019999,
0x00000000,0x00033333,0xFFFE6667,0x00019999,
0x00033333,0xFFFE6667,0x00000000,0x00033333,
0x00019999,0x00019999,0x00033333,0xFFFE6667,
0x00000000,0xFFFCCCCD,0xFFFE6667,0x00019999,
0xFFFCCCCD,0xFFFE6667,0x00000000,0x00033333,
0xFFFE6667,0x00019999,0xFFFCCCCD,0xFFFE6667,
0x00000000,0xFFFCCCCD,0x00019999,0x00019999,
0xFFFCCCCD,0x00019999,0x00000000,0xFFFCCCCD,
0xFFFE6667,0x00019999,0xFFFCCCCD,0x00019999,
0x00000000,0x00033333,0x00019999,0x00019999,
0x00033333,0x00019999,0x00000000,0xFFFCCCCD,
0x00019999,0x00019999,0x00010000,0x00010002,
0x00030000,0x00050004,0x00050006,0x00070004,
0x00090008,0x0009000A,0x000B0008,0x000D000C,
0x000D000E,0x000F000C,0x00110010,0x00110012,
0x00130010,0x00150014,0x00150016,0x00170014,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00900090,0x02000090,0x020000CC,0x00000000,
0x00000000,0x000C0018,0x00000018,0x0004CCCC,
0xFFFD78EF,0x000414A1,0xFFFB3334,0xFFFD78EF,
0x000414A1,0x0004CCCC,0x00028711,0xFFFBEB5F,
0xFFFB3334,0x00028711,0xFFFBEB5F,0xFFFB3334,
0x00069BB2,0xFFFE7270,0xFFFB3334,0x00018D90,
0x00069BB2,0x0004CCCC,0x00069BB2,0xFFFE7270,
0x0004CCCC,0x00018D90,0x00069BB2,0xFFFB3334,
0x00028711,0xFFFBEB5F,0xFFFB3334,0x00069BB2,
0xFFFE7270,0x0004CCCC,0x00028711,0xFFFBEB5F,
0x0004CCCC,0x00069BB2,0xFFFE7270,0xFFFB3334,
0xFFFD78EF,0x000414A1,0xFFFB3334,0x00018D90,
0x00069BB2,0xFFFB3334,0x00028711,0xFFFBEB5F,
0xFFFB3334,0x00069BB2,0xFFFE7270,0x0004CCCC,
0xFFFD78EF,0x000414A1,0x0004CCCC,0x00018D90,
0x00069BB2,0xFFFB3334,0xFFFD78EF,0x000414A1,
0xFFFB3334,0x00018D90,0x00069BB2,0x0004CCCC,
0x00028711,0xFFFBEB5F,0x0004CCCC,0x00069BB2,
0xFFFE7270,0x0004CCCC,0xFFFD78EF,0x000414A1,
0x0004CCCC,0x00018D90,0x00069BB2,0x00010000,
0x00030002,0x00010002,0x00050004,0x00070006,
0x00050006,0x00090008,0x000B000A,0x0009000A,
0x000D000C,0x000F000E,0x000D000E,0x00110010,
0x00130012,0x00110012,0x00150014,0x00170016,
0x00150016,0x00000000,0xFFF265E6,0xFFF7931D,
0x00000000,0xFFF265E6,0xFFF7931D,0x00000000,
0xFFF265E6,0xFFF7931D,0x00000000,0xFFF265E6,
0xFFF7931D,0x00000000,0x000D9A1A,0x00086CE3,
0x00000000,0x000D9A1A,0x00086CE3,0x00000000,
0x000D9A1A,0x00086CE3,0x00000000,0x000D9A1A,
0x00086CE3,0x00000000,0x00086CE3,0xFFF265E6,
0x00000000,0x00086CE3,0xFFF265E6,0x00000000,
0x00086CE3,0xFFF265E6,0x00000000,0x00086CE3,
0xFFF265E6,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0x00000000,0xFFF7931D,0x000D9A1A,
0x00000000,0xFFF7931D,0x000D9A1A,0x00000000,
0xFFF7931D,0x000D9A1A,0x00000000,0xFFF7931D,
0x000D9A1A,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00900090,0x02000090,0x020000CC,
0x00000000,0x00000000,0x000C0018,0x00000018,
0x00028F5C,0x0001591A,0xFFFDD2DE,0xFFFD70A4,
0xFFFEA6E6,0x00022D22,0xFFFD70A4,0x0001591A,
0xFFFDD2DE,0x00028F5C,0xFFFEA6E6,0x00022D22,
0x0001494B,0x00A3E6A7,0x006402B7,0xFFFEB6B5,
0x00A28BD9,0x00663299,0x0001494B,0x00A28BD9,
0x00663299,0xFFFEB6B5,0x00A3E6A7,0x006402B7,
0x00028F5C,0x0001591A,0xFFFDD2DE,0xFFFEB6B5,
0x00A3E6A7,0x006402B7,0x0001494B,0x00A3E6A7,
0x006402B7,0xFFFD70A4,0x0001591A,0xFFFDD2DE,
0xFFFD70A4,0x0001591A,0xFFFDD2DE,0xFFFEB6B5,
0x00A28BD9,0x00663299,0xFFFEB6B5,0x00A3E6A7,
0x006402B7,0xFFFD70A4,0xFFFEA6E6,0x00022D22,
0xFFFD70A4,0xFFFEA6E6,0x00022D22,0x0001494B,
0x00A28BD9,0x00663299,0xFFFEB6B5,0x00A28BD9,
0x00663299,0x00028F5C,0xFFFEA6E6,0x00022D22,
0x00028F5C,0xFFFEA6E6,0x00022D22,0x0001494B,
0x00A3E6A7,0x006402B7,0x0001494B,0x00A28BD9,
0x00663299,0x00028F5C,0x0001591A,0xFFFDD2DE,
0x00010000,0x00010002,0x00030000,0x00050004,
0x00050006,0x00070004,0x00090008,0x0009000A,
0x000B0008,0x000D000C,0x000D000E,0x000F000C,
0x00110010,0x00110012,0x00130010,0x00150014,
0x00150016,0x00170014,0x00000000,0xFFF265E6,
0xFFF7931D,0x00000000,0xFFF265E6,0xFFF7931D,
0x00000000,0xFFF265E6,0xFFF7931D,0x00000000,
0xFFF265E6,0xFFF7931D,0x00000000,0x000D9A1A,
0x00086CE3,0x00000000,0x000D9A1A,0x00086CE3,
0x00000000,0x000D9A1A,0x00086CE3,0x00000000,
0x000D9A1A,0x00086CE3,0x00000000,0x000883F0,
0xFFF27448,0x00000000,0x000883F0,0xFFF27448,
0x00000000,0x000883F0,0xFFF27448,0x00000000,
0x000883F0,0xFFF27448,0xFFF00017,0x00001719,
0x00000E4E,0xFFF00017,0x00001719,0x00000E4E,
0xFFF00017,0x00001719,0x00000E4E,0xFFF00017,
0x00001719,0x00000E4E,0x00000000,0xFFF7AA43,
0x000DA855,0x00000000,0xFFF7AA43,0x000DA855,
0x00000000,0xFFF7AA43,0x000DA855,0x00000000,
0xFFF7AA43,0x000DA855,0x000FFFE9,0x00001719,
0x00000E4E,0x000FFFE9,0x00001719,0x00000E4E,
0x000FFFE9,0x00001719,0x00000E4E,0x000FFFE9,
0x00001719,0x00000E4E,0x027903B2,0x030000E8,
0x03000200,0x00000000,0x00000000,0x000C0018,
0x00000018,0x0002E147,0x00000000,0xFFFD1EB9,
0xFFFD1EB9,0x00000000,0x0002E147,0x0002E147,
0x00000000,0x0002E147,0xFFFD1EB9,0x00000000,
0xFFFD1EB9,0x0002E147,0xFFD66667,0xFFFD1EB8,
0xFFFD1EB9,0xFFD66667,0x0002E147,0xFFFD1EB9,
0xFFD66667,0xFFFD1EB8,0x0002E147,0xFFD66667,
0x0002E147,0x0002E147,0x00000000,0xFFFD1EB9,
0xFFFD1EB9,0xFFD66667,0xFFFD1EB8,0xFFFD1EB9,
0x00000000,0xFFFD1EB9,0x0002E147,0xFFD66667,
0xFFFD1EB8,0xFFFD1EB9,0x00000000,0xFFFD1EB9,
0xFFFD1EB9,0xFFD66667,0x0002E147,0xFFFD1EB9,
0x00000000,0x0002E147,0xFFFD1EB9,0xFFD66667,
0xFFFD1EB8,0xFFFD1EB9,0x00000000,0x0002E147,
0x0002E147,0xFFD66667,0x0002E147,0x0002E147,
0x00000000,0x0002E147,0xFFFD1EB9,0xFFD66667,
0x0002E147,0x0002E147,0x00000000,0x0002E147,
0x0002E147,0xFFD66667,0xFFFD1EB8,0x0002E147,
0x00000000,0xFFFD1EB9,0x0002E147,0xFFD66667,
0x0002E147,0x00010000,0x00010002,0x00030000,
0x00050004,0x00050006,0x00070004,0x00090008,
0x0009000A,0x000B0008,0x000D000C,0x000D000E,
0x000F000C,0x00110010,0x00110012,0x00130010,
0x00150014,0x00150016,0x00170014,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x027903B2,
0x030000E8,0x03000200,0x00000000,0x00000000,
0x000C0018,0x00000018,0x00026666,0x00000000,
0xFFFD999A,0xFFFD999A,0x00000000,0x00026666,
0x00026666,0x00000000,0x00026666,0xFFFD999A,
0x00000000,0xFFFD999A,0x00026666,0xFFF66667,
0xFFFD999A,0xFFFD999A,0xFFF66667,0x00026666,
0xFFFD999A,0xFFF66667,0xFFFD999A,0x00026666,
0xFFF66667,0x00026666,0x00026666,0x00000000,
0xFFFD999A,0xFFFD999A,0xFFF66667,0xFFFD999A,
0xFFFD999A,0x00000000,0xFFFD999A,0x00026666,
0xFFF66667,0xFFFD999A,0xFFFD999A,0x00000000,
0xFFFD999A,0xFFFD999A,0xFFF66667,0x00026666,
0xFFFD999A,0x00000000,0x00026666,0xFFFD999A,
0xFFF66667,0xFFFD999A,0xFFFD999A,0x00000000,
0x00026666,0x00026666,0xFFF66667,0x00026666,
0x00026666,0x00000000,0x00026666,0xFFFD999A,
0xFFF66667,0x00026666,0x00026666,0x00000000,
0x00026666,0x00026666,0xFFF66667,0xFFFD999A,
0x00026666,0x00000000,0xFFFD999A,0x00026666,
0xFFF66667,0x00026666,0x00010000,0x00010002,
0x00030000,0x00050004,0x00050006,0x00070004,
0x00090008,0x0009000A,0x000B0008,0x000D000C,
0x000D000E,0x000F000C,0x00110010,0x00110012,
0x00130010,0x00150014,0x00150016,0x00170014,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x04000400,0x02000400,0x02000266,0x00000000,
0x00000000,0x000C0018,0x00000018,0x00000000,
0xFFFCE148,0xFFFE28F6,0x00000000,0x00031EB8,
0x0001D70A,0x00000000,0xFFFCE148,0x0001D70A,
0x00000000,0x00031EB8,0xFFFE28F6,0xFFF3AE15,
0xFFFCE148,0xFFFE28F6,0xFFF3AE15,0x00031EB8,
0x0001D70A,0xFFF3AE15,0x00031EB8,0xFFFE28F6,
0xFFF3AE15,0xFFFCE148,0x0001D70A,0x00000000,
0xFFFCE148,0xFFFE28F6,0xFFF3AE15,0x00031EB8,
0xFFFE28F6,0x00000000,0x00031EB8,0xFFFE28F6,
0xFFF3AE15,0xFFFCE148,0xFFFE28F6,0x00000000,
0x00031EB8,0xFFFE28F6,0xFFF3AE15,0x00031EB8,
0x0001D70A,0x00000000,0x00031EB8,0x0001D70A,
0xFFF3AE15,0x00031EB8,0xFFFE28F6,0x00000000,
0x00031EB8,0x0001D70A,0xFFF3AE15,0xFFFCE148,
0x0001D70A,0x00000000,0xFFFCE148,0x0001D70A,
0xFFF3AE15,0x00031EB8,0x0001D70A,0x00000000,
0xFFFCE148,0x0001D70A,0xFFF3AE15,0xFFFCE148,
0xFFFE28F6,0x00000000,0xFFFCE148,0xFFFE28F6,
0xFFF3AE15,0xFFFCE148,0x0001D70A,0x00010000,
0x00010002,0x00030000,0x00050004,0x00050006,
0x00070004,0x00090008,0x0009000A,0x000B0008,
0x000D000C,0x000D000E,0x000F000C,0x00110010,
0x00110012,0x00130010,0x00150014,0x00150016,
0x00170014,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x04000400,0x02000400,0x02000000,
0x00000000,0x00000000,0x00140024,0x00000024,
0x00000000,0xFFF970A4,0xFFFA1BD0,0x00000000,
0x00068F5C,0x0008CCCC,0x00000000,0xFFF970A4,
0x0008CCCC,0x00000000,0x0003A6BF,0xFFF73334,
0x00000000,0xFFFC5941,0xFFF73334,0x00000000,
0x00068F5C,0xFFFA1BD0,0xFFF970A4,0xFFFC5941,
0xFFF73334,0xFFF970A4,0x00068F5C,0xFFFA1BD0,
0xFFF970A4,0x0003A6BF,0xFFF73334,0xFFF970A4,
0x00068F5C,0x0008CCCC,0xFFF970A4,0xFFF970A4,
0x0008CCCC,0xFFF970A4,0xFFF970A4,0xFFFA1BD0,
0x00000000,0xFFFC5941,0xFFF73334,0xFFF970A4,
0x0003A6BF,0xFFF73334,0x00000000,0x0003A6BF,
0xFFF73334,0xFFF970A4,0xFFFC5941,0xFFF73334,
0x00000000,0x00068F5C,0xFFFA1BD0,0xFFF970A4,
0x00068F5C,0x0008CCCC,0x00000000,0x00068F5C,
0x0008CCCC,0xFFF970A4,0x00068F5C,0xFFFA1BD0,
0x00000000,0x00068F5C,0x0008CCCC,0xFFF970A4,
0xFFF970A4,0x0008CCCC,0x00000000,0xFFF970A4,
0x0008CCCC,0xFFF970A4,0x00068F5C,0x0008CCCC,
0x00000000,0xFFF970A4,0x0008CCCC,0xFFF970A4,
0xFFF970A4,0xFFFA1BD0,0x00000000,0xFFF970A4,
0xFFFA1BD0,0xFFF970A4,0xFFF970A4,0x0008CCCC,
0x00000000,0x0003A6BF,0xFFF73334,0xFFF970A4,
0x00068F5C,0xFFFA1BD0,0x00000000,0x00068F5C,
0xFFFA1BD0,0xFFF970A4,0x0003A6BF,0xFFF73334,
0xFFF970A4,0xFFFC5941,0xFFF73334,0x00000000,
0xFFF970A4,0xFFFA1BD0,0xFFF970A4,0xFFF970A4,
0xFFFA1BD0,0x00000000,0xFFFC5941,0xFFF73334,
0x00010000,0x00000002,0x00010003,0x00030004,
0x00010000,0x00050003,0x00070006,0x00060008,
0x00070009,0x000A0006,0x000B0009,0x0006000A,
0x000D000C,0x000D000E,0x000F000C,0x00110010,
0x00110012,0x00130010,0x00150014,0x00150016,
0x00170014,0x00190018,0x0019001A,0x001B0018,
0x001D001C,0x001D001E,0x001F001C,0x00210020,
0x00210022,0x00230020,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0x000B504F,
0xFFF4AFB1,0x00000000,0x000B504F,0xFFF4AFB1,
0x00000000,0x000B504F,0xFFF4AFB1,0x00000000,
0x000B504F,0xFFF4AFB1,0x00000000,0xFFF4AFB1,
0xFFF4AFB1,0x00000000,0xFFF4AFB1,0xFFF4AFB1,
0x00000000,0xFFF4AFB1,0xFFF4AFB1,0x00000000,
0xFFF4AFB1,0xFFF4AFB1,0x02780118,0x02E70400,
0x02E700DB,0x00000000,0x00000000,0x000C0018,
0x00000018,0x00033333,0xFFFCCCCD,0x00000000,
0xFFFCCCCD,0x00033333,0x00000000,0x00033333,
0x00033333,0x00000000,0xFFFCCCCD,0xFFFCCCCD,
0x00000000,0x00033333,0xFFFCCCCD,0x00019999,
0xFFFCCCCD,0x00033333,0x00019999,0xFFFCCCCD,
0xFFFCCCCD,0x00019999,0x00033333,0x00033333,
0x00019999,0x00033333,0xFFFCCCCD,0x00000000,
0xFFFCCCCD,0xFFFCCCCD,0x00019999,0xFFFCCCCD,
0xFFFCCCCD,0x00000000,0x00033333,0xFFFCCCCD,
0x00019999,0xFFFCCCCD,0xFFFCCCCD,0x00000000,
0xFFFCCCCD,0x00033333,0x00019999,0xFFFCCCCD,
0x00033333,0x00000000,0xFFFCCCCD,0xFFFCCCCD,
0x00019999,0xFFFCCCCD,0x00033333,0x00000000,
0x00033333,0x00033333,0x00019999,0x00033333,
0x00033333,0x00000000,0xFFFCCCCD,0x00033333,
0x00019999,0x00033333,0x00033333,0x00000000,
0x00033333,0xFFFCCCCD,0x00019999,0x00033333,
0xFFFCCCCD,0x00000000,0x00033333,0x00033333,
0x00019999,0x00010000,0x00010002,0x00030000,
0x00050004,0x00050006,0x00070004,0x00090008,
0x0009000A,0x000B0008,0x000D000C,0x000D000E,
0x000F000C,0x00110010,0x00110012,0x00130010,
0x00150014,0x00150016,0x00170014,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x04000400,
0x02000400,0x02000000,0x00000000,0x00000000,
0x000C0018,0x00000018,0x00000000,0xFFFD41A4,
0xFFFE28F6,0x00000000,0x0004C984,0x0001D70A,
0x00000000,0xFFFB367C,0x0001D70A,0x00000000,
0x0002BE5C,0xFFFE28F6,0xFFF3AE15,0xFFFD41A4,
0xFFFE28F6,0xFFF3AE15,0x0004C984,0x0001D70A,
0xFFF3AE15,0x0002BE5C,0xFFFE28F6,0xFFF3AE15,
0xFFFB367C,0x0001D70A,0x00000000,0xFFFD41A4,
0xFFFE28F6,0xFFF3AE15,0x0002BE5C,0xFFFE28F6,
0x00000000,0x0002BE5C,0xFFFE28F6,0xFFF3AE15,
0xFFFD41A4,0xFFFE28F6,0x00000000,0x0002BE5C,
0xFFFE28F6,0xFFF3AE15,0x0004C984,0x0001D70A,
0x00000000,0x0004C984,0x0001D70A,0xFFF3AE15,
0x0002BE5C,0xFFFE28F6,0x00000000,0x0004C984,
0x0001D70A,0xFFF3AE15,0xFFFB367C,0x0001D70A,
0x00000000,0xFFFB367C,0x0001D70A,0xFFF3AE15,
0x0004C984,0x0001D70A,0x00000000,0xFFFB367C,
0x0001D70A,0xFFF3AE15,0xFFFD41A4,0xFFFE28F6,
0x00000000,0xFFFD41A4,0xFFFE28F6,0xFFF3AE15,
0xFFFB367C,0x0001D70A,0x00010000,0x00010002,
0x00030000,0x00050004,0x00050006,0x00070004,
0x00090008,0x0009000A,0x000B0008,0x000D000C,
0x000D000E,0x000F000C,0x00110010,0x00110012,
0x00130010,0x00150014,0x00150016,0x00170014,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x000DFCE7,0xFFF83B72,0x00000000,
0x000DFCE7,0xFFF83B72,0x00000000,0x000DFCE7,
0xFFF83B72,0x00000000,0x000DFCE7,0xFFF83B72,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0xFFF20319,0xFFF83B72,0x00000000,
0xFFF2031A,0xFFF83B72,0x00000000,0xFFF20319,
0xFFF83B72,0x00000000,0xFFF2031A,0xFFF83B72,
0x04000400,0x02000400,0x02000266,0x00000000,
0x00000000,0x000C0018,0x00000018,0x00032BB6,
0xFFFA48AD,0x00000000,0xFFFCD44A,0x0005B753,
0x00000000,0x00032BB6,0x0005B753,0x00000000,
0xFFFCD44A,0xFFFA48AD,0x00000000,0x00032BB6,
0xFFFA48AD,0x00090933,0xFFFCD44A,0x0005B753,
0x00090933,0xFFFCD44A,0xFFFA48AD,0x00090933,
0x00032BB6,0x0005B753,0x00090933,0x00032BB6,
0xFFFA48AD,0x00000000,0xFFFCD44A,0xFFFA48AD,
0x00090933,0xFFFCD44A,0xFFFA48AD,0x00000000,
0x00032BB6,0xFFFA48AD,0x00090933,0xFFFCD44A,
0xFFFA48AD,0x00000000,0xFFFCD44A,0x0005B753,
0x00090933,0xFFFCD44A,0x0005B753,0x00000000,
0xFFFCD44A,0xFFFA48AD,0x00090933,0xFFFCD44A,
0x0005B753,0x00000000,0x00032BB6,0x0005B753,
0x00090933,0x00032BB6,0x0005B753,0x00000000,
0xFFFCD44A,0x0005B753,0x00090933,0x00032BB6,
0x0005B753,0x00000000,0x00032BB6,0xFFFA48AD,
0x00090933,0x00032BB6,0xFFFA48AD,0x00000000,
0x00032BB6,0x0005B753,0x00090933,0x00010000,
0x00010002,0x00030000,0x00050004,0x00050006,
0x00070004,0x00090008,0x0009000A,0x000B0008,
0x000D000C,0x000D000E,0x000F000C,0x00110010,
0x00110012,0x00130010,0x00150014,0x00150016,
0x00170014,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x04000400,0x02000400,0x02000000,
0x00000000,0x00000000,0x007E0081,0x00000081,
0xFFEF0789,0xFFEF078A,0xFFFA0960,0x00000000,
0xFFE80000,0xFFFA0960,0xFFF6D0CB,0xFFE9D3B0,
0xFFFA0960,0xFFE80000,0x00000000,0xFFFA0960,
0xFFE9D3AF,0xFFF6D0CC,0xFFFA0960,0x00180000,
0x00000000,0xFFFA0960,0x0010F877,0xFFEF078A,
0xFFFA0960,0x00092F35,0xFFE9D3B0,0xFFFA0960,
0x00162C51,0xFFF6D0CC,0xFFFA0960,0x00000000,
0x00180000,0xFFFA0960,0x0010F876,0x0010F876,
0xFFFA0960,0x00162C50,0x00092F35,0xFFFA0960,
0x00092F35,0x00162C50,0xFFFA0960,0xFFEF078A,
0x0010F876,0xFFFA0960,0xFFF6D0CB,0x00162C50,
0xFFFA0960,0xFFE9D3B0,0x00092F35,0xFFFA0960,
0x002C59AC,0x00125ED8,0x00106ECB,0x00000000,
0x00000000,0xFFFA62DC,0x00300121,0x00000000,
0x00106ECB,0x0021F1B9,0x0021F1B9,0x00106ECB,
0x002C59AD,0xFFEDA128,0x00106ECB,0x00125ED8,
0x002C59AC,0x00106ECB,0x0021F1BA,0xFFDE0E47,
0x00106ECB,0x00000000,0x00300121,0x00106ECB,
0x00125ED9,0xFFD3A654,0x00106ECB,0xFFEDA128,
0x002C59AC,0x00106ECB,0x00000000,0xFFCFFEDF,
0x00106ECB,0xFFDE0E47,0x0021F1B9,0x00106ECB,
0xFFEDA127,0xFFD3A654,0x00106ECB,0xFFD3A654,
0x00125ED8,0x00106ECB,0xFFDE0E46,0xFFDE0E47,
0x00106ECB,0xFFCFFEDF,0x00000000,0x00106ECB,
0xFFD3A653,0xFFEDA129,0x00106ECB,0xFFE80000,
0x00000000,0x00000000,0xFFD3A75F,0x00125E6A,
0x00100000,0xFFE9D3B0,0x00092F35,0x00000000,
0xFFD00000,0x00000000,0x00100000,0xFFDE0F13,
0x0021F0ED,0x00100000,0xFFE9D3AF,0xFFF6D0CC,
0x00000000,0xFFEF078A,0x0010F876,0x00000000,
0xFFD3A75E,0xFFEDA198,0x00100000,0xFFEDA196,
0x002C58A1,0x00100000,0xFFEF0789,0xFFEF078A,
0x00000000,0xFFF6D0CB,0x00162C50,0x00000000,
0xFFDE0F12,0xFFDE0F14,0x00100000,0x00000000,
0x00300000,0x00100000,0xFFF6D0CB,0xFFE9D3B0,
0x00000000,0x00000000,0x00180000,0x00000000,
0xFFEDA196,0xFFD3A75F,0x00100000,0x00125E6A,
0x002C58A1,0x00100000,0x00000000,0xFFE80000,
0x00000000,0x00092F35,0x00162C50,0x00000000,
0x00000000,0xFFD00000,0x00100000,0x0021F0ED,
0x0021F0ED,0x00100000,0x00092F35,0xFFE9D3B0,
0x00000000,0x0010F876,0x0010F876,0x00000000,
0x00125E6A,0xFFD3A75F,0x00100000,0x002C58A1,
0x00125E6A,0x00100000,0x0010F877,0xFFEF078A,
0x00000000,0x00162C50,0x00092F35,0x00000000,
0x0021F0EE,0xFFDE0F13,0x00100000,0x00300000,
0x00000000,0x00100000,0x00162C51,0xFFF6D0CC,
0x00000000,0x00180000,0x00000000,0x00000000,
0x002C58A2,0xFFEDA197,0x00100000,0x00162C50,
0x00092F35,0x00000000,0x0010F876,0x0010F876,
0xFFFA0960,0x0010F876,0x0010F876,0x00000000,
0x00162C50,0x00092F35,0xFFFA0960,0x00092F35,
0x00162C50,0xFFFA0960,0x00180000,0x00000000,
0x00000000,0x00092F35,0x00162C50,0x00000000,
0x00180000,0x00000000,0xFFFA0960,0x00000000,
0x00180000,0xFFFA0960,0x00162C51,0xFFF6D0CC,
0x00000000,0x00000000,0x00180000,0x00000000,
0x00162C51,0xFFF6D0CC,0xFFFA0960,0xFFF6D0CB,
0x00162C50,0xFFFA0960,0x0010F877,0xFFEF078A,
0x00000000,0xFFF6D0CB,0x00162C50,0x00000000,
0x0010F877,0xFFEF078A,0xFFFA0960,0xFFEF078A,
0x0010F876,0xFFFA0960,0x00092F35,0xFFE9D3B0,
0x00000000,0xFFEF078A,0x0010F876,0x00000000,
0x00092F35,0xFFE9D3B0,0xFFFA0960,0xFFE9D3B0,
0x00092F35,0xFFFA0960,0x00000000,0xFFE80000,
0x00000000,0xFFE9D3B0,0x00092F35,0x00000000,
0x00000000,0xFFE80000,0xFFFA0960,0xFFE80000,
0x00000000,0xFFFA0960,0xFFF6D0CB,0xFFE9D3B0,
0x00000000,0xFFE80000,0x00000000,0x00000000,
0xFFF6D0CB,0xFFE9D3B0,0xFFFA0960,0xFFE9D3AF,
0xFFF6D0CC,0xFFFA0960,0xFFEF0789,0xFFEF078A,
0x00000000,0xFFE9D3AF,0xFFF6D0CC,0x00000000,
0xFFEF0789,0xFFEF078A,0xFFFA0960,0xFFDE0F12,
0xFFDE0F14,0x00100000,0xFFD3A653,0xFFEDA129,
0x00106ECB,0xFFD3A75E,0xFFEDA198,0x00100000,
0xFFDE0E46,0xFFDE0E47,0x00106ECB,0xFFCFFEDF,
0x00000000,0x00106ECB,0xFFEDA196,0xFFD3A75F,
0x00100000,0xFFD00000,0x00000000,0x00100000,
0xFFEDA127,0xFFD3A654,0x00106ECB,0xFFD3A654,
0x00125ED8,0x00106ECB,0x00000000,0xFFD00000,
0x00100000,0xFFD3A75F,0x00125E6A,0x00100000,
0x00000000,0xFFCFFEDF,0x00106ECB,0xFFDE0E47,
0x0021F1B9,0x00106ECB,0x00125E6A,0xFFD3A75F,
0x00100000,0xFFDE0F13,0x0021F0ED,0x00100000,
0x00125ED9,0xFFD3A654,0x00106ECB,0xFFEDA128,
0x002C59AC,0x00106ECB,0x0021F0EE,0xFFDE0F13,
0x00100000,0xFFEDA196,0x002C58A1,0x00100000,
0x0021F1BA,0xFFDE0E47,0x00106ECB,0x00000000,
0x00300121,0x00106ECB,0x002C58A2,0xFFEDA197,
0x00100000,0x00000000,0x00300000,0x00100000,
0x002C59AD,0xFFEDA128,0x00106ECB,0x00125ED8,
0x002C59AC,0x00106ECB,0x00300000,0x00000000,
0x00100000,0x00125E6A,0x002C58A1,0x00100000,
0x00300121,0x00000000,0x00106ECB,0x0021F1B9,
0x0021F1B9,0x00106ECB,0x002C58A1,0x00125E6A,
0x00100000,0x0021F0ED,0x0021F0ED,0x00100000,
0x002C59AC,0x00125ED8,0x00106ECB,0x00010000,
0x00000002,0x00010003,0x00030004,0x00010000,
0x00050003,0x00050001,0x00010006,0x00070006,
0x00050006,0x00050008,0x00090003,0x00090005,
0x0005000A,0x000B000A,0x0009000A,0x0009000C,
0x000D0003,0x000D0009,0x000D000E,0x000F0003,
0x00110010,0x00130012,0x00100011,0x00110012,
0x00150014,0x00130011,0x00110014,0x00170016,
0x00150011,0x00110016,0x00190018,0x00170011,
0x00110018,0x001B001A,0x00190011,0x0011001A,
0x001D001C,0x001B0011,0x0011001C,0x001F001E,
0x001D0011,0x0011001E,0x00200020,0x001F0011,
0x00220021,0x00220023,0x00240021,0x00230025,
0x00260022,0x00210024,0x00250023,0x00240027,
0x00280026,0x00270029,0x002A0025,0x00260028,
0x00290027,0x0028002B,0x002C002A,0x002B002D,
0x002E0029,0x002A002C,0x002D002B,0x002C002F,
0x0030002E,0x002F0031,0x0032002D,0x002E0030,
0x0031002F,0x00300033,0x00340032,0x00330035,
0x00360031,0x00320034,0x00350033,0x00340037,
0x00380036,0x00370039,0x003A0035,0x00360038,
0x00390037,0x0038003B,0x003C003A,0x003B003D,
0x003E0039,0x003A003C,0x003D003B,0x003C003F,
0x0040003E,0x003F0040,0x003F003D,0x003E0040,
0x00420041,0x00420043,0x00440041,0x00430045,
0x00460042,0x00410044,0x00450043,0x00440047,
0x00480046,0x00470049,0x004A0045,0x00460048,
0x00490047,0x0048004B,0x004C004A,0x004B004D,
0x004E0049,0x004A004C,0x004D004B,0x004C004F,
0x0050004E,0x004F0051,0x0052004D,0x004E0050,
0x0051004F,0x00500053,0x00540052,0x00530055,
0x00560051,0x00520054,0x00550053,0x00540057,
0x00580056,0x00570059,0x005A0055,0x00560058,
0x00590057,0x0058005B,0x005C005A,0x005B005D,
0x005E0059,0x005A005C,0x005D005B,0x005C005F,
0x0060005E,0x005F0060,0x005F005D,0x005E0060,
0x00620061,0x00620063,0x00640061,0x00630065,
0x00660062,0x00610064,0x00650063,0x00640067,
0x00680066,0x00670069,0x006A0065,0x00660068,
0x00690067,0x0068006B,0x006C006A,0x006B006D,
0x006E0069,0x006A006C,0x006D006B,0x006C006F,
0x0070006E,0x006F0071,0x0072006D,0x006E0070,
0x0071006F,0x00700073,0x00740072,0x00730075,
0x00760071,0x00720074,0x00750073,0x00740077,
0x00780076,0x00770079,0x007A0075,0x00760078,
0x00790077,0x0078007B,0x007C007A,0x007B007D,
0x007E0079,0x007A007C,0x007D007B,0x007C007F,
0x0080007E,0x007F0080,0x007F007D,0x007E0080,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0xFFF9D4A7,0xFFFD71D0,0x000E8A37,0x00000000,
0x00000000,0x00100000,0xFFF95287,0x00000000,
0x000E8A37,0xFFFB4738,0xFFFB4738,0x000E8A37,
0xFFF9D4A7,0x00028E30,0x000E8A37,0xFFFD71D0,
0xFFF9D4A7,0x000E8A37,0xFFFB4738,0x0004B8C8,
0x000E8A37,0x00000000,0xFFF95287,0x000E8A37,
0xFFFD71D0,0x00062B59,0x000E8A37,0x00028E30,
0xFFF9D4A7,0x000E8A37,0x00000000,0x0006AD79,
0x000E8A37,0x0004B8C8,0xFFFB4738,0x000E8A37,
0x00028E30,0x00062B59,0x000E8A37,0x00062B59,
0xFFFD71D0,0x000E8A37,0x0004B8C8,0x0004B8C8,
0x000E8A37,0x0006AD79,0x00000000,0x000E8A37,
0x00062B59,0x00028E30,0x000E8A37,0xFFF71FF3,
0x00000000,0xFFF2AFEC,0xFFF7CCE6,0x0003657A,
0xFFF2AFEC,0xFFF7CCE6,0x0003657A,0xFFF2AFEC,
0xFFF71FF3,0x00000000,0xFFF2AFEC,0xFFF9B96B,
0x00064695,0xFFF2AFEC,0xFFF7CCE6,0xFFFC9A87,
0xFFF2AFEC,0xFFF9B96B,0x00064695,0xFFF2AFEC,
0xFFF7CCE6,0xFFFC9A87,0xFFF2AFEC,0xFFFC9A86,
0x0008331A,0xFFF2AFED,0xFFF9B96B,0xFFF9B96B,
0xFFF2AFEC,0xFFFC9A86,0x0008331A,0xFFF2AFEC,
0xFFF9B96B,0xFFF9B96B,0xFFF2AFEC,0x00000000,
0x0008E00D,0xFFF2AFEC,0xFFFC9A86,0xFFF7CCE6,
0xFFF2AFEC,0x00000000,0x0008E00D,0xFFF2AFEC,
0xFFFC9A86,0xFFF7CCE6,0xFFF2AFEC,0x0003657A,
0x0008331A,0xFFF2AFEC,0x00000000,0xFFF71FF3,
0xFFF2AFEC,0x0003657A,0x0008331A,0xFFF2AFEC,
0x00000000,0xFFF71FF3,0xFFF2AFEC,0x00064695,
0x00064695,0xFFF2AFEC,0x0003657A,0xFFF7CCE6,
0xFFF2AFEC,0x00064695,0x00064695,0xFFF2AFEC,
0x0003657A,0xFFF7CCE6,0xFFF2AFEC,0x0008331A,
0x0003657A,0xFFF2AFEC,0x00064695,0xFFF9B96B,
0xFFF2AFEC,0x0008331A,0x0003657A,0xFFF2AFEC,
0x00064695,0xFFF9B96B,0xFFF2AFEC,0x0008E00D,
0x00000000,0xFFF2AFEC,0x0008331A,0xFFFC9A87,
0xFFF2AFEC,0x0008E00D,0x00000000,0xFFF2AFEC,
0x0008331A,0xFFFC9A87,0xFFF2AFEC,0x000EC835,
0x00061F78,0x00000000,0x000B504F,0x000B504F,
0x00000000,0x000B504F,0x000B504F,0x00000000,
0x000EC835,0x00061F78,0x00000000,0x00061F78,
0x000EC835,0x00000000,0x00100000,0x00000000,
0x00000000,0x00061F78,0x000EC835,0x00000000,
0x00100000,0x00000000,0x00000000,0x00000000,
0x00100000,0x00000000,0x000EC836,0xFFF9E088,
0x00000000,0x00000000,0x00100000,0x00000000,
0x000EC836,0xFFF9E088,0x00000000,0xFFF9E088,
0x000EC835,0x00000000,0x000B504F,0xFFF4AFB1,
0x00000000,0xFFF9E088,0x000EC835,0x00000000,
0x000B504F,0xFFF4AFB1,0x00000000,0xFFF4AFB1,
0x000B504F,0x00000000,0x00061F78,0xFFF137CB,
0x00000000,0xFFF4AFB1,0x000B504F,0x00000000,
0x00061F78,0xFFF137CB,0x00000000,0xFFF137CB,
0x00061F78,0x00000000,0x00000000,0xFFF00000,
0x00000000,0xFFF137CB,0x00061F78,0x00000000,
0x00000000,0xFFF00000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF9E088,0xFFF137CB,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF9E088,0xFFF137CB,0x00000000,0xFFF137CA,
0xFFF9E088,0x00000000,0xFFF4AFB1,0xFFF4AFB1,
0x00000000,0xFFF137CA,0xFFF9E088,0x00000000,
0xFFF4AFB1,0xFFF4AFB1,0x00000000,0xFFF4AFD8,
0xFFF4AFD8,0xFFFFD64A,0xFFF137FD,0xFFF9E09C,
0xFFFFD641,0xFFF137FC,0xFFF9E09E,0xFFFFD641,
0xFFF4AFD8,0xFFF4AFD8,0xFFFFD64A,0xFFF00037,
0x00000000,0xFFFFD645,0xFFF9E09C,0xFFF137FD,
0xFFFFD646,0xFFF00037,0x00000000,0xFFFFD645,
0xFFF9E09D,0xFFF137FD,0xFFFFD646,0xFFF137FC,
0x00061F61,0xFFFFD64C,0x00000000,0xFFF00037,
0xFFFFD645,0xFFF137FD,0x00061F65,0xFFFFD64C,
0x00000000,0xFFF00037,0xFFFFD645,0xFFF4AFD8,
0x000B5028,0xFFFFD64A,0x00061F64,0xFFF137FD,
0xFFFFD646,0xFFF4AFD8,0x000B5028,0xFFFFD64A,
0x00061F63,0xFFF137FD,0xFFFFD646,0xFFF9E09D,
0x000EC803,0xFFFFD646,0x000B5028,0xFFF4AFD8,
0xFFFFD64A,0xFFF9E09C,0x000EC803,0xFFFFD646,
0x000B5029,0xFFF4AFD8,0xFFFFD64A,0x00000000,
0x000FFFC9,0xFFFFD645,0x000EC804,0xFFF9E09E,
0xFFFFD641,0x00000000,0x000FFFC9,0xFFFFD645,
0x000EC803,0xFFF9E09C,0xFFFFD641,0x00061F63,
0x000EC803,0xFFFFD646,0x000FFFC9,0x00000000,
0xFFFFD645,0x00061F64,0x000EC803,0xFFFFD646,
0x000FFFC9,0x00000000,0xFFFFD645,0x000B5028,
0x000B5028,0xFFFFD64A,0x000EC802,0x00061F66,
0xFFFFD64D,0x000B5028,0x000B5028,0xFFFFD64A,
0x000EC804,0x00061F61,0xFFFFD64D,0x04000400,
0x02000400,0x02000000,0x00000000,0x00000000,
0x00240038,0x00000038,0xFFFB851F,0x00000000,
0x00000000,0xFFF5C290,0x00000000,0x0003AE14,
0xFFF827DD,0x00069507,0x0003AE14,0xFFFC9171,
0x0002E133,0x00000000,0xFFFC9171,0x0002E133,
0x00000000,0xFFF827DD,0x00069507,0x0003AE14,
0xFFFE38CB,0x000A159D,0x0003AE14,0xFFFF38D9,
0x00046974,0x00000000,0xFFFF38D9,0x00046974,
0x00000000,0xFFFE38CB,0x000A159D,0x0003AE14,
0x00051EB8,0x0008DE3B,0x0003AE14,0x00023D70,
0x0003E13A,0x00000000,0x00023D70,0x0003E13A,
0x00000000,0x00051EB8,0x0008DE3B,0x0003AE14,
0x00099F59,0x00038095,0x0003AE14,0x000435B6,
0x00018841,0x00000000,0x000435B6,0x00018841,
0x00000000,0x00099F59,0x00038095,0x0003AE14,
0x00099F59,0xFFFC7F6A,0x0003AE14,0x000435B6,
0xFFFE77BF,0x00000000,0x000435B6,0xFFFE77BF,
0x00000000,0x00099F59,0xFFFC7F6A,0x0003AE14,
0x00051EB8,0xFFF721C5,0x0003AE14,0x00023D70,
0xFFFC1EC6,0x00000000,0x00023D70,0xFFFC1EC6,
0x00000000,0x00051EB8,0xFFF721C5,0x0003AE14,
0xFFFE38CB,0xFFF5EA63,0x0003AE14,0xFFFF38D9,
0xFFFB968C,0x00000000,0xFFFF38D9,0xFFFB968C,
0x00000000,0xFFFE38CB,0xFFF5EA63,0x0003AE14,
0xFFF827DD,0xFFF96AF9,0x0003AE14,0xFFFC9171,
0xFFFD1ECD,0x00000000,0xFFFC9171,0xFFFD1ECD,
0x00000000,0xFFF827DD,0xFFF96AF9,0x0003AE14,
0xFFF5C290,0x00000000,0x0003AE14,0xFFFB851F,
0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0xFFFB851F,0x00000000,0x00000000,
0xFFFC9171,0x0002E133,0x00000000,0xFFFF38D9,
0x00046974,0x00000000,0xFFFC9171,0xFFFD1ECD,
0x00000000,0x00023D70,0x0003E13A,0x00000000,
0xFFFF38D9,0xFFFB968C,0x00000000,0x000435B6,
0x00018841,0x00000000,0x00023D70,0xFFFC1EC6,
0x00000000,0x000435B6,0xFFFE77BF,0x00000000,
0x00000000,0x00000000,0x0003AE14,0xFFF827DD,
0x00069507,0x0003AE14,0xFFF5C290,0x00000000,
0x0003AE14,0xFFFE38CB,0x000A159D,0x0003AE14,
0xFFF827DD,0xFFF96AF9,0x0003AE14,0x00051EB8,
0x0008DE3B,0x0003AE14,0xFFFE38CB,0xFFF5EA63,
0x0003AE14,0x00099F59,0x00038095,0x0003AE14,
0x00051EB8,0xFFF721C5,0x0003AE14,0x00099F59,
0xFFFC7F6A,0x0003AE14,0x00010000,0x00000002,
0x00030002,0x00050004,0x00040006,0x00070006,
0x00090008,0x0008000A,0x000B000A,0x000D000C,
0x000C000E,0x000F000E,0x00110010,0x00100012,
0x00130012,0x00150014,0x00140016,0x00170016,
0x00190018,0x0018001A,0x001B001A,0x001D001C,
0x001C001E,0x001F001E,0x00210020,0x00200022,
0x00230022,0x00250024,0x00240026,0x00270026,
0x00280024,0x00240025,0x00290027,0x002A0024,
0x00240028,0x002B0029,0x002C0024,0x0024002A,
0x002D002B,0x002D0024,0x002E002C,0x0030002F,
0x0031002E,0x002E002F,0x00320030,0x0033002E,
0x002E0031,0x00340032,0x0035002E,0x002E0033,
0x00360034,0x0037002E,0x002E0035,0x00370036,
0xFFF78BEB,0x000313A9,0xFFF2C4BD,0xFFF78BEB,
0x000313A9,0xFFF2C4BD,0xFFF78BEB,0x000313A9,
0xFFF2C4BD,0xFFF78BEB,0x000313A9,0xFFF2C4BD,
0xFFFB8084,0x0007CA6E,0xFFF2C4BD,0xFFFB8084,
0x0007CA6E,0xFFF2C4BD,0xFFFB8084,0x0007CA6E,
0xFFF2C4BD,0xFFFB8084,0x0007CA6E,0xFFF2C4BD,
0x00018FE8,0x0008DBFB,0xFFF2C4BD,0x00018FE8,
0x0008DBFB,0xFFF2C4BD,0x00018FE8,0x0008DBFB,
0xFFF2C4BD,0x00018FE8,0x0008DBFB,0xFFF2C4BD,
0x0006E42D,0x0005C851,0xFFF2C4BD,0x0006E42D,
0x0005C852,0xFFF2C4BD,0x0006E42D,0x0005C851,
0xFFF2C4BD,0x0006E42D,0x0005C852,0xFFF2C4BD,
0x0008FEF8,0x00000000,0xFFF2C4BD,0x0008FEF8,
0x00000000,0xFFF2C4BD,0x0008FEF8,0x00000000,
0xFFF2C4BD,0x0008FEF8,0x00000000,0xFFF2C4BD,
0x0006E42D,0xFFFA37AE,0xFFF2C4BD,0x0006E42D,
0xFFFA37AE,0xFFF2C4BD,0x0006E42D,0xFFFA37AE,
0xFFF2C4BD,0x0006E42D,0xFFFA37AE,0xFFF2C4BD,
0x00018FE8,0xFFF72405,0xFFF2C4BD,0x00018FE8,
0xFFF72405,0xFFF2C4BD,0x00018FE8,0xFFF72405,
0xFFF2C4BD,0x00018FE8,0xFFF72405,0xFFF2C4BD,
0xFFFB8084,0xFFF83592,0xFFF2C4BD,0xFFFB8084,
0xFFF83592,0xFFF2C4BD,0xFFFB8084,0xFFF83592,
0xFFF2C4BD,0xFFFB8084,0xFFF83592,0xFFF2C4BD,
0xFFF78BEB,0xFFFCEC57,0xFFF2C4BD,0xFFF78BEB,
0xFFFCEC57,0xFFF2C4BD,0xFFF78BEB,0xFFFCEC57,
0xFFF2C4BD,0xFFF78BEB,0xFFFCEC57,0xFFF2C4BD,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x027903B2,0x030000E8,0x03000200,0x00000000,
0x00000000,0x0010001A,0x0000001A,0xFFFC28F6,
0x00000000,0x00000000,0xFFFF5C29,0x00000000,
0x0007851E,0x00000000,0x0000A3D7,0x0007851E,
0x00000000,0x0003D70A,0x00000000,0x00000000,
0x0003D70A,0x00000000,0x00000000,0x0000A3D7,
0x0007851E,0x0000A3D7,0x00000000,0x0007851E,
0x0003D70A,0x00000000,0x00000000,0x0003D70A,
0x00000000,0x00000000,0x0000A3D7,0x00000000,
0x0007851E,0x00000000,0xFFFF5C29,0x0007851E,
0x00000000,0xFFFC28F6,0x00000000,0x00000000,
0xFFFC28F6,0x00000000,0x00000000,0xFFFF5C29,
0x0007851E,0xFFFF5C29,0x00000000,0x0007851E,
0xFFFC28F6,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFFC28F6,0x00000000,
0x00000000,0x00000000,0x0003D70A,0x00000000,
0x0003D70A,0x00000000,0x00000000,0x00000000,
0xFFFC28F6,0x00000000,0x00000000,0x00000000,
0x0007851E,0x00000000,0x0000A3D7,0x0007851E,
0xFFFF5C29,0x00000000,0x0007851E,0x0000A3D7,
0x00000000,0x0007851E,0x00000000,0xFFFF5C29,
0x0007851E,0x00010000,0x00000002,0x00030002,
0x00050004,0x00040006,0x00070006,0x00090008,
0x0008000A,0x000B000A,0x000D000C,0x000C000E,
0x000F000E,0x00110010,0x00100012,0x00130012,
0x00140010,0x00100011,0x00140013,0x00160015,
0x00150017,0x00160018,0x00170015,0x00150019,
0x00180019,0xFFF52A87,0x000AD579,0x00049C33,
0xFFF52A87,0x000AD579,0x00049C33,0xFFF52A87,
0x000AD579,0x00049C33,0xFFF52A87,0x000AD579,
0x00049C33,0x000AD579,0x000AD579,0x00049C33,
0x000AD579,0x000AD579,0x00049C33,0x000AD579,
0x000AD579,0x00049C33,0x000AD579,0x000AD579,
0x00049C33,0x000AD579,0xFFF52A87,0x00049C33,
0x000AD579,0xFFF52A87,0x00049C33,0x000AD579,
0xFFF52A87,0x00049C33,0x000AD579,0xFFF52A87,
0x00049C33,0xFFF52A87,0xFFF52A87,0x00049C33,
0xFFF52A87,0xFFF52A87,0x00049C33,0xFFF52A87,
0xFFF52A87,0x00049C33,0xFFF52A87,0xFFF52A87,
0x00049C33,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x04000400,
0x02000400,0x02000266,0x00000000,0x00000000,
0x0010001A,0x0000001A,0xFFFC28F6,0x00000000,
0x00000000,0xFFFE147B,0x00000000,0x000A3D70,
0x00000000,0x0001EB85,0x000A3D70,0x00000000,
0x0003D70A,0x00000000,0x00000000,0x0003D70A,
0x00000000,0x00000000,0x0001EB85,0x000A3D70,
0x0001EB85,0x00000000,0x000A3D70,0x0003D70A,
0x00000000,0x00000000,0x0003D70A,0x00000000,
0x00000000,0x0001EB85,0x00000000,0x000A3D70,
0x00000000,0xFFFE147B,0x000A3D70,0x00000000,
0xFFFC28F6,0x00000000,0x00000000,0xFFFC28F6,
0x00000000,0x00000000,0xFFFE147B,0x000A3D70,
0xFFFE147B,0x00000000,0x000A3D70,0xFFFC28F6,
0x00000000,0x00000000,0x00000000,0x00000000,
0x00000000,0xFFFC28F6,0x00000000,0x00000000,
0x00000000,0x0003D70A,0x00000000,0x0003D70A,
0x00000000,0x00000000,0x00000000,0xFFFC28F6,
0x00000000,0x00000000,0x00000000,0x000A3D70,
0x00000000,0x0001EB85,0x000A3D70,0xFFFE147B,
0x00000000,0x000A3D70,0x0001EB85,0x00000000,
0x000A3D70,0x00000000,0xFFFE147B,0x000A3D70,
0x00010000,0x00000002,0x00030002,0x00050004,
0x00040006,0x00070006,0x00090008,0x0008000A,
0x000B000A,0x000D000C,0x000C000E,0x000F000E,
0x00110010,0x00100012,0x00130012,0x00140010,
0x00100011,0x00140013,0x00160015,0x00150017,
0x00160018,0x00170015,0x00150019,0x00180019,
0xFFF4C8D1,0x000B372F,0x00021A58,0xFFF4C8D1,
0x000B372F,0x00021A58,0xFFF4C8D1,0x000B372F,
0x00021A58,0xFFF4C8D1,0x000B372F,0x00021A58,
0x000B372F,0x000B372F,0x00021A58,0x000B372F,
0x000B372F,0x00021A58,0x000B372F,0x000B372F,
0x00021A58,0x000B372F,0x000B372F,0x00021A58,
0x000B372F,0xFFF4C8D1,0x00021A58,0x000B372F,
0xFFF4C8D1,0x00021A58,0x000B372F,0xFFF4C8D1,
0x00021A58,0x000B372F,0xFFF4C8D1,0x00021A58,
0xFFF4C8D1,0xFFF4C8D1,0x00021A58,0xFFF4C8D1,
0xFFF4C8D1,0x00021A58,0xFFF4C8D1,0xFFF4C8D1,
0x00021A58,0xFFF4C8D1,0xFFF4C8D1,0x00021A58,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x04000400,0x02000400,
0x02000266,0x00000000,0x00000000,0x0006000C,
0x0000000C,0x0001A3E6,0xFFF2F847,0x00199999,
0x00006666,0xFFFF4EA4,0x00000000,0x0002D719,
0xFFF246EA,0x00199999,0xFFFF3334,0x00000000,
0x00000000,0x0002D719,0xFFF246EA,0x00199999,
0x00006666,0x0000B15C,0x00000000,0x0002D719,
0xFFF3A9A4,0x00199999,0x00006666,0xFFFF4EA4,
0x00000000,0xFFFF3334,0x00000000,0x00000000,
0x0002D719,0xFFF3A9A4,0x00199999,0x00006666,
0x0000B15C,0x00000000,0x0001A3E6,0xFFF2F847,
0x00199999,0x00010000,0x00010002,0x00030000,
0x00050004,0x00050006,0x00070004,0x00090008,
0x0009000A,0x000B0008,0xFFF88E01,0xFFF31AB8,
0xFFFA255C,0xFFF88E01,0xFFF31AB8,0xFFFA255C,
0xFFF88E01,0xFFF31AB8,0xFFFA255C,0xFFF88E01,
0xFFF31AB8,0xFFFA255C,0x000FED84,0x00000000,
0xFFFE7B54,0x000FED84,0x00000000,0xFFFE7B54,
0x000FED84,0x00000000,0xFFFE7B54,0x000FED84,
0x00000000,0xFFFE7B54,0xFFF8CFCD,0x000C7352,
0x000705BB,0xFFF8CFCD,0x000C7352,0x000705BB,
0xFFF8CFCD,0x000C7352,0x000705BB,0xFFF8CFCD,
0x000C7352,0x000705BB,0x04000400,0x02000400,
0x02000266,0x00000000,0x00000000,0x0006000C,
0x0000000C,0x0001A3E5,0x000D07B9,0x0019999A,
0x00006666,0x0000B15C,0x00000000,0x0002D719,
0x000DB915,0x0019999A,0xFFFF3334,0x00000000,
0x00000000,0x0002D719,0x000DB915,0x0019999A,
0x00006666,0xFFFF4EA4,0x00000000,0x0002D719,
0x000C565C,0x0019999A,0x00006666,0x0000B15C,
0x00000000,0xFFFF3334,0x00000000,0x00000000,
0x0002D719,0x000C565C,0x0019999A,0x00006666,
0xFFFF4EA4,0x00000000,0x0001A3E5,0x000D07B9,
0x0019999A,0x00010000,0x00010002,0x00030000,
0x00050004,0x00050006,0x00070004,0x00090008,
0x0009000A,0x000B0008,0x000771FF,0xFFF31AB8,
0x0005DAA3,0x000771FF,0xFFF31AB8,0x0005DAA3,
0x000771FF,0xFFF31AB8,0x0005DAA3,0x000771FF,
0xFFF31AB8,0x0005DAA3,0xFFF0127C,0x00000000,
0x000184AC,0xFFF0127C,0x00000000,0x000184AC,
0xFFF0127C,0x00000000,0x000184AC,0xFFF0127C,
0x00000000,0x000184AC,0x00073033,0x000C7353,
0xFFF8FA46,0x00073033,0x000C7353,0xFFF8FA46,
0x00073033,0x000C7353,0xFFF8FA46,0x00073033,
0x000C7353,0xFFF8FA46,0x04000400,0x02000400,
0x02000266,0x00000000,0x00000000,0x0006000C,
0x0000000C,0xFFF2F847,0xFFFE5C1A,0x00199999,
0xFFFF4EA4,0xFFFF999A,0x00000000,0xFFF246EA,
0xFFFD28E7,0x00199999,0x00000000,0x0000CCCC,
0x00000000,0xFFF246EA,0xFFFD28E7,0x00199999,
0x0000B15C,0xFFFF999A,0x00000000,0xFFF3A9A4,
0xFFFD28E7,0x00199999,0xFFFF4EA4,0xFFFF999A,
0x00000000,0x00000000,0x0000CCCC,0x00000000,
0xFFF3A9A4,0xFFFD28E7,0x00199999,0x0000B15C,
0xFFFF999A,0x00000000,0xFFF2F847,0xFFFE5C1A,
0x00199999,0x00010000,0x00010002,0x00030000,
0x00050004,0x00050006,0x00070004,0x00090008,
0x0009000A,0x000B0008,0xFFF31AB8,0x000771FF,
0xFFFA255C,0xFFF31AB8,0x000771FF,0xFFFA255C,
0xFFF31AB8,0x000771FF,0xFFFA255C,0xFFF31AB8,
0x000771FF,0xFFFA255C,0x00000000,0xFFF0127C,
0xFFFE7B54,0x00000000,0xFFF0127C,0xFFFE7B54,
0x00000000,0xFFF0127C,0xFFFE7B54,0x00000000,
0xFFF0127C,0xFFFE7B54,0x000C7352,0x00073033,
0x000705BB,0x000C7352,0x00073033,0x000705BB,
0x000C7352,0x00073033,0x000705BB,0x000C7352,
0x00073033,0x000705BB,0x04000400,0x02000400,
0x02000266,0x00000000,0x00000000,0x0006000C,
0x0000000C,0x000D07B9,0xFFFE5C1A,0x0019999A,
0x0000B15C,0xFFFF999A,0x00000000,0x000DB915,
0xFFFD28E7,0x0019999A,0x00000000,0x0000CCCC,
0x00000000,0x000DB915,0xFFFD28E7,0x0019999A,
0xFFFF4EA4,0xFFFF999A,0x00000000,0x000C565C,
0xFFFD28E7,0x0019999A,0x0000B15C,0xFFFF999A,
0x00000000,0x00000000,0x0000CCCC,0x00000000,
0x000C565C,0xFFFD28E7,0x0019999A,0xFFFF4EA4,
0xFFFF999A,0x00000000,0x000D07B9,0xFFFE5C1A,
0x0019999A,0x00010000,0x00010002,0x00030000,
0x00050004,0x00050006,0x00070004,0x00090008,
0x0009000A,0x000B0008,0xFFF31AB8,0xFFF88E01,
0x0005DAA3,0xFFF31AB8,0xFFF88E01,0x0005DAA3,
0xFFF31AB8,0xFFF88E01,0x0005DAA3,0xFFF31AB8,
0xFFF88E01,0x0005DAA3,0x00000000,0x000FED84,
0x000184AC,0x00000000,0x000FED84,0x000184AC,
0x00000000,0x000FED84,0x000184AC,0x00000000,
0x000FED84,0x000184AC,0x000C7353,0xFFF8CFCD,
0xFFF8FA46,0x000C7353,0xFFF8CFCD,0xFFF8FA46,
0x000C7353,0xFFF8CFCD,0xFFF8FA46,0x000C7353,
0xFFF8CFCD,0xFFF8FA46,0x04000400,0x02000400,
0x02000266,0x00000000,0x00000000,0x0006000C,
0x0000000C,0xFFFE5C1A,0x000D07B9,0x00199999,
0xFFFF999A,0x0000B15C,0x00000000,0xFFFD28E7,
0x000DB916,0x00199999,0x0000CCCC,0x00000000,
0x00000000,0xFFFD28E7,0x000DB916,0x00199999,
0xFFFF999A,0xFFFF4EA4,0x00000000,0xFFFD28E7,
0x000C565C,0x00199999,0xFFFF999A,0x0000B15C,
0x00000000,0x0000CCCC,0x00000000,0x00000000,
0xFFFD28E7,0x000C565C,0x00199999,0xFFFF999A,
0xFFFF4EA4,0x00000000,0xFFFE5C1A,0x000D07B9,
0x00199999,0x00010000,0x00010002,0x00030000,
0x00050004,0x00050006,0x00070004,0x00090008,
0x0009000A,0x000B0008,0x000771FF,0x000CE548,
0xFFFA255C,0x000771FF,0x000CE548,0xFFFA255C,
0x000771FF,0x000CE548,0xFFFA255C,0x000771FF,
0x000CE548,0xFFFA255C,0xFFF0127C,0x00000000,
0xFFFE7B54,0xFFF0127C,0x00000000,0xFFFE7B54,
0xFFF0127C,0x00000000,0xFFFE7B54,0xFFF0127C,
0x00000000,0xFFFE7B54,0x00073033,0xFFF38CAD,
0x000705BB,0x00073033,0xFFF38CAE,0x000705BB,
0x00073033,0xFFF38CAD,0x000705BB,0x00073033,
0xFFF38CAE,0x000705BB,0x04000400,0x02000400,
0x02000266,0x00000000,0x00000000,0x0006000C,
0x0000000C,0xFFFE5C1A,0xFFF2F847,0x0019999A,
0xFFFF999A,0xFFFF4EA4,0x00000000,0xFFFD28E7,
0xFFF246EB,0x0019999A,0x0000CCCC,0x00000000,
0x00000000,0xFFFD28E7,0xFFF246EB,0x0019999A,
0xFFFF999A,0x0000B15C,0x00000000,0xFFFD28E7,
0xFFF3A9A4,0x0019999A,0xFFFF999A,0xFFFF4EA4,
0x00000000,0x0000CCCC,0x00000000,0x00000000,
0xFFFD28E7,0xFFF3A9A4,0x0019999A,0xFFFF999A,
0x0000B15C,0x00000000,0xFFFE5C1A,0xFFF2F847,
0x0019999A,0x00010000,0x00010002,0x00030000,
0x00050004,0x00050006,0x00070004,0x00090008,
0x0009000A,0x000B0008,0xFFF88E01,0x000CE548,
0x0005DAA3,0xFFF88E01,0x000CE548,0x0005DAA3,
0xFFF88E01,0x000CE548,0x0005DAA3,0xFFF88E01,
0x000CE548,0x0005DAA3,0x000FED84,0x00000000,
0x000184AC,0x000FED84,0x00000000,0x000184AC,
0x000FED84,0x00000000,0x000184AC,0x000FED84,
0x00000000,0x000184AC,0xFFF8CFCD,0xFFF38CAD,
0xFFF8FA46,0xFFF8CFCD,0xFFF38CAD,0xFFF8FA46,
0xFFF8CFCD,0xFFF38CAD,0xFFF8FA46,0xFFF8CFCD,
0xFFF38CAD,0xFFF8FA46,0x04000400,0x02000400,
0x02000266,0x00000000,0x00000000,0x0006000C,
0x0000000C,0x000D07B9,0x0001A3E6,0x00199999,
0x0000B15C,0x00006666,0x00000000,0x000DB916,
0x0002D719,0x00199999,0x00000000,0xFFFF3334,
0x00000000,0x000DB916,0x0002D719,0x00199999,
0xFFFF4EA4,0x00006666,0x00000000,0x000C565C,
0x0002D719,0x00199999,0x0000B15C,0x00006666,
0x00000000,0x00000000,0xFFFF3334,0x00000000,
0x000C565C,0x0002D719,0x00199999,0xFFFF4EA4,
0x00006666,0x00000000,0x000D07B9,0x0001A3E6,
0x00199999,0x00010000,0x00010002,0x00030000,
0x00050004,0x00050006,0x00070004,0x00090008,
0x0009000A,0x000B0008,0x000CE548,0xFFF88E01,
0xFFFA255C,0x000CE548,0xFFF88E01,0xFFFA255C,
0x000CE548,0xFFF88E01,0xFFFA255C,0x000CE548,
0xFFF88E01,0xFFFA255C,0x00000000,0x000FED84,
0xFFFE7B54,0x00000000,0x000FED84,0xFFFE7B54,
0x00000000,0x000FED84,0xFFFE7B54,0x00000000,
0x000FED84,0xFFFE7B54,0xFFF38CAE,0xFFF8CFCD,
0x000705BB,0xFFF38CAE,0xFFF8CFCC,0x000705BB,
0xFFF38CAE,0xFFF8CFCD,0x000705BB,0xFFF38CAE,
0xFFF8CFCC,0x000705BB,0x04000400,0x02000400,
0x02000266,0x00000000,0x00000000,0x0006000C,
0x0000000C,0xFFF2F847,0x0001A3E5,0x0019999A,
0xFFFF4EA4,0x00006666,0x00000000,0xFFF246EB,
0x0002D718,0x0019999A,0x00000000,0xFFFF3334,
0x00000000,0xFFF246EB,0x0002D718,0x0019999A,
0x0000B15C,0x00006666,0x00000000,0xFFF3A9A4,
0x0002D718,0x0019999A,0xFFFF4EA4,0x00006666,
0x00000000,0x00000000,0xFFFF3334,0x00000000,
0xFFF3A9A4,0x0002D718,0x0019999A,0x0000B15C,
0x00006666,0x00000000,0xFFF2F847,0x0001A3E5,
0x0019999A,0x00010000,0x00010002,0x00030000,
0x00050004,0x00050006,0x00070004,0x00090008,
0x0009000A,0x000B0008,0x000CE548,0x000771FF,
0x0005DAA3,0x000CE548,0x000771FF,0x0005DAA3,
0x000CE548,0x000771FF,0x0005DAA3,0x000CE548,
0x000771FF,0x0005DAA3,0x00000000,0xFFF0127C,
0x000184AC,0x00000000,0xFFF0127C,0x000184AC,
0x00000000,0xFFF0127C,0x000184AC,0x00000000,
0xFFF0127C,0x000184AC,0xFFF38CAD,0x00073033,
0xFFF8FA46,0xFFF38CAD,0x00073033,0xFFF8FA46,
0xFFF38CAD,0x00073033,0xFFF8FA46,0xFFF38CAD,
0x00073033,0xFFF8FA46,0x04000400,0x02000400,
0x02000266,0x00000000,0x00000000,0x0018001A,
0x0000001A,0x00000000,0x00000000,0x00000000,
0xFFFBD70B,0x00000000,0x00000000,0xFFFDEB86,
0x0001E5A8,0xFFFCEFF3,0x0002147A,0x0001E5A8,
0xFFFCEFF3,0xFFFDEB86,0xFFFE1A58,0x0003100D,
0x000428F5,0x00000000,0x00000000,0x0002147A,
0xFFFE1A58,0x0003100D,0x00000000,0x00082943,
0x00050E22,0xFFFDEB86,0x000A0EEC,0x0001FE14,
0xFFFBD70B,0x00082943,0x00050E22,0x0002147A,
0x000A0EEC,0x0001FE14,0xFFFDEB86,0x0006439A,
0x00081E2F,0x000428F5,0x00082943,0x00050E22,
0x0002147A,0x0006439A,0x00081E2F,0xFFFBD70B,
0x00000000,0x00000000,0xFFFBD70B,0x00082943,
0x00050E22,0xFFFDEB86,0x000A0EEC,0x0001FE14,
0xFFFDEB86,0x0001E5A8,0xFFFCEFF3,0xFFFDEB86,
0xFFFE1A58,0x0003100D,0x0002147A,0x000A0EEC,
0x0001FE14,0xFFFDEB86,0x0006439A,0x00081E2F,
0x0002147A,0x0001E5A8,0xFFFCEFF3,0x0002147A,
0xFFFE1A58,0x0003100D,0x000428F5,0x00082943,
0x00050E22,0x0002147A,0x0006439A,0x00081E2F,
0x000428F5,0x00000000,0x00000000,0x00010000,
0x00000002,0x00030002,0x00040000,0x00000001,
0x00050003,0x00060000,0x00000004,0x00060005,
0x00080007,0x00070009,0x0008000A,0x00090007,
0x0007000B,0x000A000C,0x000B0007,0x0007000D,
0x000C000D,0x000F000E,0x000E0010,0x00110010,
0x000F0012,0x0011000E,0x00130010,0x00140012,
0x0011000F,0x00150013,0x00140016,0x00150012,
0x00170013,0x00180016,0x00150014,0x00190017,
0x00180019,0x00190016,0x00180017,0x00000000,
0xFFF265E6,0xFFF7931D,0x00000000,0xFFF265E6,
0xFFF7931D,0x00000000,0xFFF265E6,0xFFF7931D,
0x00000000,0xFFF265E6,0xFFF7931D,0x00000000,
0xFFF265E6,0xFFF7931D,0x00000000,0xFFF265E6,
0xFFF7931D,0x00000000,0xFFF265E6,0xFFF7931D,
0x00000000,0x000D9A1A,0x00086CE3,0x00000000,
0x000D9A1A,0x00086CE3,0x00000000,0x000D9A1A,
0x00086CE3,0x00000000,0x000D9A1A,0x00086CE3,
0x00000000,0x000D9A1A,0x00086CE3,0x00000000,
0x000D9A1A,0x00086CE3,0x00000000,0x000D9A1A,
0x00086CE3,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF80001,
0x00074BEB,0xFFF43869,0xFFF80001,0x00074BEB,
0xFFF43869,0xFFF80001,0xFFF8B415,0x000BC797,
0x00080000,0x00074BEB,0xFFF43869,0xFFF80001,
0xFFF8B415,0x000BC797,0x0007FFFF,0x00074BEB,
0xFFF43869,0x0007FFFF,0xFFF8B415,0x000BC797,
0x00100000,0x00000000,0x00000000,0x0007FFFF,
0xFFF8B415,0x000BC797,0x00100000,0x00000000,
0x00000000,0x04000400,0x02000400,0x02000266,
0x00000000,0x00000000,0x00180026,0x00000026,
0xFFFB851F,0x00000000,0x00000000,0xFFFB851F,
0x000A3D70,0x00000000,0xFFFDC290,0x000A3D70,
0xFFFC1EC6,0xFFFDC290,0x00000000,0xFFFC1EC6,
0xFFFDC290,0x00000000,0xFFFC1EC6,0xFFFDC290,
0x000A3D70,0xFFFC1EC6,0x00023D70,0x000A3D70,
0xFFFC1EC6,0x00023D70,0x00000000,0xFFFC1EC6,
0x00023D70,0x00000000,0xFFFC1EC6,0x00023D70,
0x000A3D70,0xFFFC1EC6,0x00047AE1,0x000A3D70,
0x00000000,0x00047AE1,0x00000000,0x00000000,
0x00047AE1,0x00000000,0x00000000,0x00047AE1,
0x000A3D70,0x00000000,0x00023D70,0x000A3D70,
0x0003E13A,0x00023D70,0x00000000,0x0003E13A,
0x00023D70,0x00000000,0x0003E13A,0x00023D70,
0x000A3D70,0x0003E13A,0xFFFDC290,0x000A3D70,
0x0003E13A,0xFFFDC290,0x00000000,0x0003E13A,
0xFFFDC290,0x00000000,0x0003E13A,0xFFFDC290,
0x000A3D70,0x0003E13A,0xFFFB851F,0x000A3D70,
0x00000000,0xFFFB851F,0x00000000,0x00000000,
0x00000000,0x00000000,0x00000000,0xFFFB851F,
0x00000000,0x00000000,0xFFFDC290,0x00000000,
0xFFFC1EC6,0x00023D70,0x00000000,0xFFFC1EC6,
0xFFFDC290,0x00000000,0x0003E13A,0x00047AE1,
0x00000000,0x00000000,0x00023D70,0x00000000,
0x0003E13A,0x00000000,0x000A3D70,0x00000000,
0xFFFDC290,0x000A3D70,0xFFFC1EC6,0xFFFB851F,
0x000A3D70,0x00000000,0x00023D70,0x000A3D70,
0xFFFC1EC6,0xFFFDC290,0x000A3D70,0x0003E13A,
0x00047AE1,0x000A3D70,0x00000000,0x00023D70,
0x000A3D70,0x0003E13A,0x00010000,0x00000002,
0x00030002,0x00050004,0x00040006,0x00070006,
0x00090008,0x0008000A,0x000B000A,0x000D000C,
0x000C000E,0x000F000E,0x00110010,0x00100012,
0x00130012,0x00150014,0x00140016,0x00170016,
0x00190018,0x0018001A,0x001B001A,0x001C0018,
0x00180019,0x001D001B,0x001E0018,0x0018001C,
0x001E001D,0x0020001F,0x001F0021,0x00200022,
0x0021001F,0x001F0023,0x00220024,0x0023001F,
0x001F0025,0x00240025,0xFFF224C3,0x00000000,
0xFFF80000,0xFFF224C3,0x00000000,0xFFF80000,
0xFFF224C3,0x00000000,0xFFF80000,0xFFF224C3,
0x00000000,0xFFF80001,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x000DDB3D,0x00000000,
0xFFF80001,0x000DDB3D,0x00000000,0xFFF80001,
0x000DDB3D,0x00000000,0xFFF80001,0x000DDB3D,
0x00000000,0xFFF80001,0x000DDB3D,0x00000000,
0x00080000,0x000DDB3D,0x00000000,0x00080000,
0x000DDB3D,0x00000000,0x00080000,0x000DDB3D,
0x00000000,0x00080000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0xFFF224C3,0x00000000,
0x00080000,0xFFF224C3,0x00000000,0x00080000,
0xFFF224C3,0x00000000,0x00080000,0xFFF224C3,
0x00000000,0x00080000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x027903B2,0x030000E8,0x03000200,0x00000000,
0x00000000,0x00180026,0x00000026,0xFFFB851F,
0x00000000,0x00000000,0xFFFB851F,0x000A3D70,
0x00000000,0xFFFDC290,0x000A3D70,0xFFFC1EC6,
0xFFFDC290,0x00000000,0xFFFC1EC6,0xFFFDC290,
0x00000000,0xFFFC1EC6,0xFFFDC290,0x000A3D70,
0xFFFC1EC6,0x00023D70,0x000A3D70,0xFFFC1EC6,
0x00023D70,0x00000000,0xFFFC1EC6,0x00023D70,
0x00000000,0xFFFC1EC6,0x00023D70,0x000A3D70,
0xFFFC1EC6,0x00047AE1,0x000A3D70,0x00000000,
0x00047AE1,0x00000000,0x00000000,0x00047AE1,
0x00000000,0x00000000,0x00047AE1,0x000A3D70,
0x00000000,0x00023D70,0x000A3D70,0x0003E13A,
0x00023D70,0x00000000,0x0003E13A,0x00023D70,
0x00000000,0x0003E13A,0x00023D70,0x000A3D70,
0x0003E13A,0xFFFDC290,0x000A3D70,0x0003E13A,
0xFFFDC290,0x00000000,0x0003E13A,0xFFFDC290,
0x00000000,0x0003E13A,0xFFFDC290,0x000A3D70,
0x0003E13A,0xFFFB851F,0x000A3D70,0x00000000,
0xFFFB851F,0x00000000,0x00000000,0x00000000,
0x00000000,0x00000000,0xFFFB851F,0x00000000,
0x00000000,0xFFFDC290,0x00000000,0xFFFC1EC6,
0x00023D70,0x00000000,0xFFFC1EC6,0xFFFDC290,
0x00000000,0x0003E13A,0x00047AE1,0x00000000,
0x00000000,0x00023D70,0x00000000,0x0003E13A,
0x00000000,0x000A3D70,0x00000000,0xFFFDC290,
0x000A3D70,0xFFFC1EC6,0xFFFB851F,0x000A3D70,
0x00000000,0x00023D70,0x000A3D70,0xFFFC1EC6,
0xFFFDC290,0x000A3D70,0x0003E13A,0x00047AE1,
0x000A3D70,0x00000000,0x00023D70,0x000A3D70,
0x0003E13A,0x00010000,0x00000002,0x00030002,
0x00050004,0x00040006,0x00070006,0x00090008,
0x0008000A,0x000B000A,0x000D000C,0x000C000E,
0x000F000E,0x00110010,0x00100012,0x00130012,
0x00150014,0x00140016,0x00170016,0x00190018,
0x0018001A,0x001B001A,0x001C0018,0x00180019,
0x001D001B,0x001E0018,0x0018001C,0x001E001D,
0x0020001F,0x001F0021,0x00200022,0x0021001F,
0x001F0023,0x00220024,0x0023001F,0x001F0025,
0x00240025,0xFFF224C3,0x00000000,0xFFF80000,
0xFFF224C3,0x00000000,0xFFF80000,0xFFF224C3,
0x00000000,0xFFF80000,0xFFF224C3,0x00000000,
0xFFF80001,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x000DDB3D,0x00000000,0xFFF80001,
0x000DDB3D,0x00000000,0xFFF80001,0x000DDB3D,
0x00000000,0xFFF80001,0x000DDB3D,0x00000000,
0xFFF80001,0x000DDB3D,0x00000000,0x00080000,
0x000DDB3D,0x00000000,0x00080000,0x000DDB3D,
0x00000000,0x00080000,0x000DDB3D,0x00000000,
0x00080000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0xFFF224C3,0x00000000,0x00080000,
0xFFF224C3,0x00000000,0x00080000,0xFFF224C3,
0x00000000,0x00080000,0xFFF224C3,0x00000000,
0x00080000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x027903B2,
0x030000E8,0x03000200,0x00000000,0x00000000,
0x0020003C,0x0000003C,0xFFFB851F,0x00000000,
0x00000000,0xFFFDC290,0x000A3D70,0xFFFC1EC6,
0xFFFDC290,0x00000000,0xFFFC1EC6,0xFFFB851F,
0x000A3D70,0x00000000,0xFFFDC290,0x00000000,
0xFFFC1EC6,0x00023D70,0x000A3D70,0xFFFC1EC6,
0x00023D70,0x00000000,0xFFFC1EC6,0xFFFDC290,
0x000A3D70,0xFFFC1EC6,0x00023D70,0x00000000,
0xFFFC1EC6,0x00047AE1,0x000A3D70,0x00000000,
0x00047AE1,0x00000000,0x00000000,0x00023D70,
0x000A3D70,0xFFFC1EC6,0x00047AE1,0x00000000,
0x00000000,0x00023D70,0x000A3D70,0x0003E13A,
0x00023D70,0x00000000,0x0003E13A,0x00047AE1,
0x000A3D70,0x00000000,0x00023D70,0x00000000,
0x0003E13A,0xFFFDC290,0x000A3D70,0x0003E13A,
0xFFFDC290,0x00000000,0x0003E13A,0x00023D70,
0x000A3D70,0x0003E13A,0xFFFDC290,0x00000000,
0x0003E13A,0xFFFB851F,0x000A3D70,0x00000000,
0xFFFB851F,0x00000000,0x00000000,0xFFFDC290,
0x000A3D70,0x0003E13A,0x00023D70,0x00000000,
0x0003E13A,0x00023D70,0x00000000,0xFFFC1EC6,
0x00047AE1,0x00000000,0x00000000,0xFFFB851F,
0x00000000,0x00000000,0xFFFDC290,0x00000000,
0x0003E13A,0xFFFDC290,0x00000000,0xFFFC1EC6,
0xFFFB851F,0x000A3D70,0x00000000,0xFFFC431D,
0x000C1307,0xFFF9869F,0xFFFDC290,0x000A3D70,
0xFFFC1EC6,0xFFF88639,0x000C1307,0x00000000,
0xFFFDC290,0x000A3D70,0xFFFC1EC6,0x0003BCE3,
0x000C1307,0xFFF9869F,0x00023D70,0x000A3D70,
0xFFFC1EC6,0xFFFC431D,0x000C1307,0xFFF9869F,
0x00023D70,0x000A3D70,0xFFFC1EC6,0x000779C7,
0x000C1307,0x00000000,0x00047AE1,0x000A3D70,
0x00000000,0x0003BCE3,0x000C1307,0xFFF9869F,
0x00047AE1,0x000A3D70,0x00000000,0x0003BCE3,
0x000C1307,0x00067962,0x00023D70,0x000A3D70,
0x0003E13A,0x000779C7,0x000C1307,0x00000000,
0x00023D70,0x000A3D70,0x0003E13A,0xFFFC431D,
0x000C1307,0x00067962,0xFFFDC290,0x000A3D70,
0x0003E13A,0x0003BCE3,0x000C1307,0x00067962,
0xFFFDC290,0x000A3D70,0x0003E13A,0xFFF88639,
0x000C1307,0x00000000,0xFFFB851F,0x000A3D70,
0x00000000,0xFFFC431D,0x000C1307,0x00067962,
0xFFFC431D,0x000C1307,0xFFF9869F,0x000779C7,
0x000C1307,0x00000000,0x0003BCE3,0x000C1307,
0xFFF9869F,0xFFFC431D,0x000C1307,0x00067962,
0xFFF88639,0x000C1307,0x00000000,0x0003BCE3,
0x000C1307,0x00067962,0x00010000,0x00010002,
0x00030000,0x00050004,0x00050006,0x00070004,
0x00090008,0x0009000A,0x000B0008,0x000D000C,
0x000D000E,0x000F000C,0x00110010,0x00110012,
0x00130010,0x00150014,0x00150016,0x00170014,
0x00190018,0x0018001A,0x0019001B,0x001B001C,
0x00190018,0x001D001B,0x001F001E,0x001F0020,
0x0021001E,0x00230022,0x00230024,0x00250022,
0x00270026,0x00270028,0x00290026,0x002B002A,
0x002B002C,0x002D002A,0x002F002E,0x002F0030,
0x0031002E,0x00330032,0x00330034,0x00350032,
0x00370036,0x00360038,0x00370039,0x0039003A,
0x00370036,0x003B0039,0xFFF224C3,0x00000000,
0xFFF80000,0xFFF224C3,0x00000000,0xFFF80000,
0xFFF224C3,0x00000000,0xFFF80001,0xFFF224C3,
0x00000000,0xFFF80001,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x000DDB3D,0x00000000,
0xFFF80001,0x000DDB3D,0x00000000,0xFFF80001,
0x000DDB3D,0x00000000,0xFFF80001,0x000DDB3D,
0x00000000,0xFFF80001,0x000DDB3D,0x00000000,
0x00080000,0x000DDB3D,0x00000000,0x00080000,
0x000DDB3D,0x00000000,0x00080000,0x000DDB3D,
0x00000000,0x00080000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0xFFF224C3,0x00000000,
0x00080000,0xFFF224C3,0x00000000,0x00080000,
0xFFF224C3,0x00000000,0x00080000,0xFFF224C3,
0x00000000,0x00080000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0xFFF8001E,0xFFF2EF8A,0xFFFB61A8,0xFFF8001E,
0xFFF2EF8A,0xFFFB61A8,0xFFF8001E,0xFFF2EF8A,
0xFFFB61A7,0xFFF8001E,0xFFF2EF8A,0xFFFB61A8,
0x00000000,0xFFF2EF8A,0xFFF6C34F,0x00000000,
0xFFF2EF8A,0xFFF6C34F,0x00000000,0xFFF2EF8A,
0xFFF6C34F,0x00000000,0xFFF2EF8A,0xFFF6C34F,
0x0007FFE2,0xFFF2EF8A,0xFFFB61A7,0x0007FFE2,
0xFFF2EF8A,0xFFFB61A7,0x0007FFE2,0xFFF2EF8A,
0xFFFB61A7,0x0007FFE2,0xFFF2EF8A,0xFFFB61A7,
0x0007FFE2,0xFFF2EF8A,0x00049E58,0x0007FFE2,
0xFFF2EF8A,0x00049E58,0x0007FFE2,0xFFF2EF8A,
0x00049E58,0x0007FFE2,0xFFF2EF8A,0x00049E58,
0x00000000,0xFFF2EF8A,0x00093CB1,0x00000000,
0xFFF2EF89,0x00093CB1,0x00000000,0xFFF2EF89,
0x00093CB1,0x00000000,0xFFF2EF8A,0x00093CB1,
0xFFF8001E,0xFFF2EF8A,0x00049E58,0xFFF8001E,
0xFFF2EF8A,0x00049E58,0xFFF8001E,0xFFF2EF8A,
0x00049E58,0xFFF8001E,0xFFF2EF8A,0x00049E58,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x027903B2,0x030000E8,
0x03000200,0x00000000,0x00000000,0x0018001A,
0x0000001A,0x00000000,0x00000000,0x00000000,
0xFFFD999A,0x00000000,0x00000000,0xFFFECCCD,
0x00000000,0x00021416,0x00013333,0x00000000,
0x00021416,0xFFFECCCD,0x00000000,0xFFFDEBEA,
0x00026666,0x00000000,0x00000000,0x00013333,
0x00000000,0xFFFDEBEA,0x00000000,0xFFEE6667,
0x00000000,0xFFFECCCD,0xFFEE6667,0x00021415,
0xFFFD999A,0xFFEE6667,0x00000000,0x00013333,
0xFFEE6667,0x00021415,0xFFFECCCD,0xFFEE6667,
0xFFFDEBEA,0x00026666,0xFFEE6667,0x00000000,
0x00013333,0xFFEE6667,0xFFFDEBEA,0xFFFD999A,
0x00000000,0x00000000,0xFFFD999A,0xFFEE6667,
0x00000000,0xFFFECCCD,0xFFEE6667,0x00021415,
0xFFFECCCD,0x00000000,0x00021416,0xFFFECCCD,
0x00000000,0xFFFDEBEA,0x00013333,0xFFEE6667,
0x00021415,0xFFFECCCD,0xFFEE6667,0xFFFDEBEA,
0x00013333,0x00000000,0x00021416,0x00013333,
0x00000000,0xFFFDEBEA,0x00026666,0xFFEE6667,
0x00000000,0x00013333,0xFFEE6667,0xFFFDEBEA,
0x00026666,0x00000000,0x00000000,0x00010000,
0x00000002,0x00030002,0x00040000,0x00000001,
0x00050003,0x00060000,0x00000004,0x00060005,
0x00080007,0x00070009,0x0008000A,0x00090007,
0x0007000B,0x000A000C,0x000B0007,0x0007000D,
0x000C000D,0x000F000E,0x000E0010,0x00110010,
0x000F0012,0x0011000E,0x00130010,0x00140012,
0x0011000F,0x00150013,0x00140016,0x00150012,
0x00170013,0x00180016,0x00150014,0x00190017,
0x00180019,0x00190016,0x00180017,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF80001,
0x00000000,0x000DDB3D,0xFFF80001,0x00000000,
0x000DDB3D,0xFFF80001,0x00000000,0xFFF224C3,
0x00080000,0x00000000,0x000DDB3D,0xFFF80001,
0x00000000,0xFFF224C3,0x00080000,0x00000000,
0x000DDB3D,0x0007FFFF,0x00000000,0xFFF224C3,
0x00100000,0x00000000,0x00000000,0x0007FFFF,
0x00000000,0xFFF224C3,0x00100000,0x00000000,
0x00000000,0x027903B2,0x030000E8,0x03000200,
0x00000000,0x00000000,0x001C001E,0x0000001E,
0xFFFE3856,0x00000000,0xFFFA859D,0x0004A8F1,
0x00000000,0xFFFC9D47,0x0001C7AA,0x00000000,
0xFFFA859D,0xFFFA3D71,0x00000000,0x00000000,
0xFFFB570F,0x00000000,0xFFFC9D47,0x0004A8F1,
0x00000000,0x000362B9,0x0005C28F,0x00000000,
0x00000000,0xFFFE3856,0x00000000,0x00057A63,
0x0001C7AA,0x00000000,0x00057A63,0xFFFB570F,
0x00000000,0x000362B9,0xFFFA3D71,0x00000000,
0x00000000,0xFFFB570F,0xFFF33334,0x000362B9,
0xFFFB570F,0x00000000,0x000362B9,0xFFFA3D71,
0xFFF33334,0x00000000,0xFFFE3856,0xFFF33334,
0x00057A63,0xFFFB570F,0x00000000,0xFFFC9D47,
0xFFFE3856,0x00000000,0x00057A63,0xFFFB570F,
0xFFF33334,0xFFFC9D47,0x0001C7AA,0xFFF33334,
0x00057A63,0xFFFE3856,0x00000000,0xFFFA859D,
0x0001C7AA,0x00000000,0x00057A63,0xFFFE3856,
0xFFF33334,0xFFFA859D,0x0004A8F1,0xFFF33334,
0x000362B9,0x0001C7AA,0x00000000,0xFFFA859D,
0x0004A8F1,0x00000000,0x000362B9,0x0001C7AA,
0xFFF33334,0xFFFA859D,0x0005C28F,0xFFF33334,
0x00000000,0x0004A8F1,0x00000000,0xFFFC9D47,
0x0005C28F,0x00000000,0x00000000,0x0004A8F1,
0xFFF33334,0xFFFC9D47,0x00010000,0x00000002,
0x00010003,0x00030004,0x00010000,0x00050003,
0x00050001,0x00050006,0x00070003,0x00070005,
0x00070008,0x00090003,0x000B000A,0x000B000C,
0x000D000A,0x000C000E,0x000F000B,0x000A000D,
0x000E000C,0x000D0010,0x0011000F,0x00100012,
0x0013000E,0x000F0011,0x00120010,0x00110014,
0x00150013,0x00140016,0x00170012,0x00130015,
0x00160014,0x00150018,0x00190017,0x0018001A,
0x001B0016,0x00170019,0x001A0018,0x0019001C,
0x001D001B,0x001C001D,0x001C001A,0x001B001D,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF30E45,0x00000000,0x00096791,
0xFFF30E45,0x00000000,0x00096791,0xFFF00000,
0x00000000,0x00000000,0xFFFB0E45,0x00000000,
0x000F3787,0xFFF30E45,0x00000000,0xFFF6986F,
0xFFFB0E45,0x00000000,0x000F3787,0xFFF30E45,
0x00000000,0xFFF6986F,0x0004F1BB,0x00000000,
0x000F3787,0xFFFB0E45,0x00000000,0xFFF0C879,
0x0004F1BB,0x00000000,0x000F3787,0xFFFB0E45,
0x00000000,0xFFF0C879,0x000CF1BB,0x00000000,
0x00096791,0x0004F1BB,0x00000000,0xFFF0C879,
0x000CF1BB,0x00000000,0x00096791,0x0004F1BB,
0x00000000,0xFFF0C879,0x00100000,0x00000000,
0x00000000,0x000CF1BB,0x00000000,0xFFF6986F,
0x00100000,0x00000000,0x00000000,0x000CF1BB,
0x00000000,0xFFF6986F,0x027903B2,0x030000E8,
0x03000200,0x00000000,0x00000000,0x0018001A,
0x0000001A,0x00000000,0x00000000,0x00000000,
0xFFFEB852,0x00000000,0x00000000,0xFFFF5C29,
0x00000000,0x00011BC7,0x0000A3D7,0x00000000,
0x00011BC7,0xFFFF5C29,0x00000000,0xFFFEE439,
0x000147AE,0x00000000,0x00000000,0x0000A3D7,
0x00000000,0xFFFEE439,0x00000000,0xFFF33334,
0x00000000,0xFFFF5C29,0xFFF33334,0x00011BC7,
0xFFFEB852,0xFFF33334,0x00000000,0x0000A3D7,
0xFFF33334,0x00011BC7,0xFFFF5C29,0xFFF33334,
0xFFFEE439,0x000147AE,0xFFF33334,0x00000000,
0x0000A3D7,0xFFF33334,0xFFFEE439,0xFFFEB852,
0x00000000,0x00000000,0xFFFEB852,0xFFF33334,
0x00000000,0xFFFF5C29,0xFFF33334,0x00011BC7,
0xFFFF5C29,0x00000000,0x00011BC7,0xFFFF5C29,
0x00000000,0xFFFEE439,0x0000A3D7,0xFFF33334,
0x00011BC7,0xFFFF5C29,0xFFF33334,0xFFFEE439,
0x0000A3D7,0x00000000,0x00011BC7,0x0000A3D7,
0x00000000,0xFFFEE439,0x000147AE,0xFFF33334,
0x00000000,0x0000A3D7,0xFFF33334,0xFFFEE439,
0x000147AE,0x00000000,0x00000000,0x00010000,
0x00000002,0x00030002,0x00040000,0x00000001,
0x00050003,0x00060000,0x00000004,0x00060005,
0x00080007,0x00070009,0x0008000A,0x00090007,
0x0007000B,0x000A000C,0x000B0007,0x0007000D,
0x000C000D,0x000F000E,0x000E0010,0x00110010,
0x000F0012,0x0011000E,0x00130010,0x00140012,
0x0011000F,0x00150013,0x00140016,0x00150012,
0x00170013,0x00180016,0x00150014,0x00190017,
0x00180019,0x00190016,0x00180017,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF80001,
0x00000000,0x000DDB3D,0xFFF80001,0x00000000,
0x000DDB3D,0xFFF80001,0x00000000,0xFFF224C3,
0x00080000,0x00000000,0x000DDB3D,0xFFF80001,
0x00000000,0xFFF224C3,0x00080000,0x00000000,
0x000DDB3D,0x0007FFFF,0x00000000,0xFFF224C3,
0x00100000,0x00000000,0x00000000,0x00080000,
0x00000000,0xFFF224C3,0x00100000,0x00000000,
0x00000000,0x027903B2,0x030000E8,0x03000200,
0x00000000,0x00000000,0x000BD70A,0x027903B2,
0x030000E8,0x03000200,0x00000000,0x00000000,
0x00080010,0x00000010,0x00007F85,0x00060627,
0xFFFBF782,0x0002BE46,0x00009472,0x00041B82,
0x00033DCB,0xFFFFFE0C,0x00041B82,0x00000000,
0x00069C8E,0xFFFBF782,0x00033DCB,0xFFFFFE0C,
0x00041B82,0x00000000,0xFFFA8C58,0xFFFBF782,
0x0002BE46,0x00009472,0x00041B82,0x00007F85,
0xFFF9F5F1,0xFFFBF782,0x00000000,0x00057132,
0xFFFBF782,0x00033DCB,0xFFFFFE0C,0x00041B82,
0x0002BE46,0xFFFF6918,0x00041B82,0x00007F85,
0x00060627,0xFFFBF782,0x0002BE46,0xFFFF6918,
0x00041B82,0x00007F85,0xFFF9F5F1,0xFFFBF782,
0x00033DCB,0xFFFFFE0C,0x00041B82,0x00000000,
0xFFF960FC,0xFFFBF782,0x00010000,0x00010002,
0x00030000,0x00050004,0x00050006,0x00070004,
0x00090008,0x0009000A,0x000B0008,0x000D000C,
0x000D000E,0x000F000C,0x000BE9DC,0x000A19DC,
0x00037832,0x000BE9DC,0x000A19DC,0x00037832,
0x000BE9DC,0x000A19DC,0x00037832,0x000BE9DC,
0x000A19DC,0x00037832,0x0009D3EE,0x00085529,
0xFFF683A5,0x0009D3EE,0x00085529,0xFFF683A5,
0x0009D3EE,0x00085529,0xFFF683A5,0x0009D3EE,
0x00085529,0xFFF683A5,0x0009C7C1,0xFFF7A08C,
0xFFF68020,0x0009C7C1,0xFFF7A08C,0xFFF68020,
0x0009C7C1,0xFFF7A08C,0xFFF68020,0x0009C7C1,
0xFFF7A08D,0xFFF68020,0x000BDB12,0xFFF5D9B1,
0x00038667,0x000BDB12,0xFFF5D9B1,0x00038667,
0x000BDB12,0xFFF5D9B1,0x00038667,0x000BDB12,
0xFFF5D9B1,0x00038667,0x04000400,0x02000400,
0x02000000,0x00000000,0x00000000,0x00080010,
0x00000010,0xFFFCE69B,0x0005308A,0xFFFBF782,
0x0001E4DB,0x00021147,0x00041B82,0x0002A413,
0x0001E121,0x00041B82,0xFFFC2763,0x000560B1,
0xFFFBF782,0x0002A413,0x0001E121,0x00041B82,
0x00032BE5,0xFFFB90CD,0xFFFBF782,0x0001E4DB,
0x00021147,0x00041B82,0x0003EB1D,0xFFFB60A6,
0xFFFBF782,0xFFFCD589,0x00046D32,0xFFFBF782,
0x0002A413,0x0001E121,0x00041B82,0x00029301,
0x00011DC9,0x00041B82,0xFFFCE69B,0x0005308A,
0xFFFBF782,0x00029301,0x00011DC9,0x00041B82,
0x0003EB1D,0xFFFB60A6,0xFFFBF782,0x0002A413,
0x0001E121,0x00041B82,0x0003DA0B,0xFFFA9D4F,
0xFFFBF782,0x00010000,0x00010002,0x00030000,
0x00050004,0x00050006,0x00070004,0x00090008,
0x0009000A,0x000B0008,0x000D000C,0x000D000E,
0x000F000C,0x0003D06B,0x000F257D,0x00037832,
0x0003D06B,0x000F257D,0x00037832,0x0003D06B,
0x000F257D,0x00037832,0x0003D06B,0x000F257D,
0x00037832,0x0003257B,0x000C7EAB,0xFFF683A5,
0x0003257A,0x000C7EAB,0xFFF683A5,0x0003257B,
0x000C7EAB,0xFFF683A5,0x0003257A,0x000C7EAB,
0xFFF683A5,0x000CD36B,0xFFFEE112,0xFFF68020,
0x000CD36B,0xFFFEE113,0xFFF68020,0x000CD36B,
0xFFFEE113,0xFFF68020,0x000CD36B,0xFFFEE112,
0xFFF68020,0x000F8C30,0xFFFEA42F,0x00038667,
0x000F8C30,0xFFFEA42F,0x00038667,0x000F8C30,
0xFFFEA42F,0x00038667,0x000F8C30,0xFFFEA42F,
0x00038667,0x04000400,0x02000400,0x02000000,
0x00000000,0x00000000,0x00020004,0x00000004,
0x0006147A,0x0003A1FE,0x000607C1,0xFFF9EB86,
0x0003A1FE,0x000607C1,0x0006147A,0xFFFC5E02,
0xFFF9F83F,0xFFF9EB86,0xFFFC5E02,0xFFF9F83F,
0x00010000,0x00030002,0x00010002,0x00000000,
0xFFF24B77,0x0008419E,0x00000000,0xFFF24B77,
0x0008419E,0x00000000,0xFFF24B77,0x0008419E,
0x00000000,0xFFF24B77,0x0008419E,0x00900090,
0x02000090,0x020000CC,0x00000000,0x00000000,
0x00080010,0x00000010,0xFFFAD395,0x000E6F03,
0x00009FD6,0xFFF72078,0x00011F57,0x0021EFAE,
0xFFF7D646,0xFFFFFD9A,0x0021EFAE,0xFFFA1DC6,
0x000FD72E,0x00009FD6,0xFFF7D646,0xFFFFFD9A,
0x0021EFAE,0xFFFA1DC6,0xFFF2F3E7,0x00009FD6,
0xFFF72078,0x00011F57,0x0021EFAE,0xFFFAD395,
0xFFF18BBC,0x00009FD6,0xFFF7D646,0xFFFFFD9A,
0x0021EFAE,0xFFFA1DC6,0x000D0A50,0x00009FD6,
0xFFFAD395,0x000E6F03,0x00009FD6,0xFFF72078,
0xFFFEDEA5,0x0021EFAE,0xFFF72078,0xFFFEDEA5,
0x0021EFAE,0xFFFAD395,0xFFF18BBC,0x00009FD6,
0xFFF7D646,0xFFFFFD9A,0x0021EFAE,0xFFFA1DC6,
0xFFF02709,0x00009FD6,0x00010000,0x00010002,
0x00030000,0x00050004,0x00050006,0x00070004,
0x00090008,0x0009000A,0x000B0008,0x000D000C,
0x000D000E,0x000F000C,0x000DBE4A,0x0006F798,
0x00044F75,0x000CFA13,0x00081AFC,0x0004AE1B,
0x000CF53F,0x00082181,0x0004B02C,0x000DC1D8,
0x0006F1C5,0x00044D86,0x000D6B9A,0x00086290,
0xFFFDA2EF,0x000E2D3F,0x00072F64,0xFFFE2869,
0x000D671C,0x000868F3,0xFFFDA021,0x000E307C,
0x0007299F,0xFFFE2AE3,0x000D614E,0xFFF78F0B,
0xFFFD9BD5,0x000E255F,0xFFF8C2D6,0xFFFE21D3,
0x000E28A1,0xFFF8C894,0xFFFE244C,0x000D5CCA,
0xFFF788B2,0xFFFD990A,0x000CEFAD,0xFFF7D761,
0x0004B331,0x000DB612,0xFFF8FB59,0x00045472,
0x000CEAD4,0xFFF7D0E6,0x0004B53F,0x000DB9A4,
0xFFF90127,0x00045285,0x04000400,0x02000400,
0x02000266,0x00000000,0x00000000,0x00080010,
0x00000010,0x000F162F,0xFFFD437A,0x00009FD6,
0x0005689C,0x00071F89,0x0021EFAE,0x000412C8,
0x000712F5,0x0021EFAE,0x0010A900,0xFFFD2CD8,
0x00009FD6,0x000412C8,0x000712F5,0x0021EFAE,
0xFFF7A481,0x000B9E7B,0x00009FD6,0x0005689C,
0x00071F89,0x0021EFAE,0xFFF611B0,0x000BB51D,
0x00009FD6,0x000412C8,0x000712F5,0x0021EFAE,
0x000E3C2D,0xFFFE9347,0x00009FD6,0x000F162F,
0xFFFD437A,0x00009FD6,0x0003752D,0x00083FE2,
0x0021EFAE,0x0003752D,0x00083FE2,0x0021EFAE,
0xFFF611B0,0x000BB51D,0x00009FD6,0x000412C8,
0x000712F5,0x0021EFAE,0xFFF537AE,0x000D04EA,
0x00009FD6,0x00010000,0x00010002,0x00030000,
0x00050004,0x00050006,0x00070004,0x00090008,
0x0009000A,0x000B0008,0x000D000C,0x000D000E,
0x000F000C,0xFFFF297F,0xFFF09D46,0x00044F75,
0x000087F4,0xFFF0B582,0x0004AE1B,0x00009002,
0xFFF0B66E,0x0004B02C,0xFFFF22AD,0xFFF09D1C,
0x00044D86,0x00008D2D,0xFFF02F66,0xFFFDA2EF,
0xFFFF2257,0xFFF02149,0xFFFE2869,0x000094F4,
0xFFF03019,0xFFFDA021,0xFFFF1BB9,0xFFF0215D,
0xFFFE2AE3,0xFFF1FFE7,0xFFF8A214,0xFFFD9BD5,
0xFFF2A86E,0xFFF75E62,0xFFFE21D3,0xFFF2ABC6,
0xFFF758B1,0xFFFE244C,0xFFF1FCAA,0xFFF8A929,
0xFFFD990A,0xFFF2775D,0xFFF8E051,0x0004B331,
0xFFF31105,0xFFF7A285,0x00045472,0xFFF2742C,
0xFFF8E7C1,0x0004B53F,0xFFF31442,0xFFF79C87,
0x00045285,0x04000400,0x02000400,0x02000266,
0x00000000,0x00000000,0x00080010,0x00000010,
0xFFF6163C,0xFFF44D83,0x00009FD6,0x000376EC,
0xFFF7C120,0x0021EFAE,0x000416F1,0xFFF8EF72,
0x0021EFAE,0xFFF5393A,0xFFF2FBFB,0x00009FD6,
0x000416F1,0xFFF8EF72,0x0021EFAE,0x000E3DB9,
0x00016D9E,0x00009FD6,0x000376EC,0xFFF7C120,
0x0021EFAE,0x000F1ABC,0x0002BF26,0x00009FD6,
0x000416F1,0xFFF8EF72,0x0021EFAE,0xFFF7A60D,
0xFFF4626A,0x00009FD6,0xFFF6163C,0xFFF44D83,
0x00009FD6,0x00056A5B,0xFFF8E179,0x0021EFAE,
0x00056A5B,0xFFF8E179,0x0021EFAE,0x000F1ABC,
0x0002BF26,0x00009FD6,0x000416F1,0xFFF8EF72,
0x0021EFAE,0x0010AA8D,0x0002D40D,0x00009FD6,
0x00010000,0x00010002,0x00030000,0x00050004,
0x00050006,0x00070004,0x00090008,0x0009000A,
0x000B0008,0x000D000C,0x000D000E,0x000F000C,
0xFFF31837,0x00086B21,0x00044F75,0xFFF27DF9,
0x00072F81,0x0004AE1B,0xFFF27ABE,0x00072811,
0x0004B02C,0xFFF31B7C,0x0008711F,0x00044D86,
0xFFF20738,0x00076E09,0xFFFDA2EF,0xFFF2B06B,
0x0008AF53,0xFFFE2869,0xFFF203F0,0x000766F4,
0xFFFDA021,0xFFF2B3CB,0x0008B503,0xFFFE2AE3,
0x00009ECA,0x000FCEE1,0xFFFD9BD6,0xFFFF3234,
0x000FDEC8,0xFFFE21D3,0xFFFF2B9A,0x000FDEBB,
0xFFFE244C,0x0000A68B,0x000FCE25,0xFFFD990A,
0x000098F6,0x000F484E,0x0004B331,0xFFFF38EA,
0x000F6223,0x00045472,0x0000A0FF,0x000F475A,
0x0004B53F,0xFFFF321B,0x000F6254,0x00045285,
0x04000400,0x02000400,0x02000266,0x00000000,
0x00000000,0x00500078,0x00000078,0x00000000,
0x00119999,0x00000000,0xFFF5A7AD,0x000E3D1B,
0x00000000,0xFFF5A7AD,0x000E3D1B,0xFFF66667,
0x00000000,0x00119999,0xFFF66667,0x00000000,
0x00166666,0xFFF66667,0xFFF2D568,0x00121F3A,
0xFFF66667,0xFFF2D568,0x00121F3A,0x00000000,
0x00000000,0x00166666,0x00000000,0xFFF5A7AD,
0x000E3D1B,0x00000000,0xFFEF42EC,0x0005704E,
0x00000000,0xFFEF42EC,0x0005704E,0xFFF66667,
0xFFF5A7AD,0x000E3D1B,0xFFF66667,0xFFF2D568,
0x00121F3A,0xFFF66667,0xFFEAB243,0x0006EC06,
0xFFF66667,0xFFEAB243,0x0006EC06,0x00000000,
0xFFF2D568,0x00121F3A,0x00000000,0xFFEF42EC,
0x0005704E,0x00000000,0xFFEF42EC,0xFFFA8FB2,
0x00000000,0xFFEF42EC,0xFFFA8FB2,0xFFF66667,
0xFFEF42EC,0x0005704E,0xFFF66667,0xFFEAB243,
0x0006EC06,0xFFF66667,0xFFEAB243,0xFFF913FA,
0xFFF66667,0xFFEAB243,0xFFF913FA,0x00000000,
0xFFEAB243,0x0006EC06,0x00000000,0xFFEF42EC,
0xFFFA8FB2,0x00000000,0xFFF5A7AD,0xFFF1C2E5,
0x00000000,0xFFF5A7AD,0xFFF1C2E5,0xFFF66667,
0xFFEF42EC,0xFFFA8FB2,0xFFF66667,0xFFEAB243,
0xFFF913FA,0xFFF66667,0xFFF2D568,0xFFEDE0C6,
0xFFF66667,0xFFF2D568,0xFFEDE0C6,0x00000000,
0xFFEAB243,0xFFF913FA,0x00000000,0xFFF5A7AD,
0xFFF1C2E5,0x00000000,0x00000000,0xFFEE6667,
0x00000000,0x00000000,0xFFEE6667,0xFFF66667,
0xFFF5A7AD,0xFFF1C2E5,0xFFF66667,0xFFF2D568,
0xFFEDE0C6,0xFFF66667,0x00000000,0xFFE9999A,
0xFFF66667,0x00000000,0xFFE9999A,0x00000000,
0xFFF2D568,0xFFEDE0C6,0x00000000,0x00000000,
0xFFEE6667,0x00000000,0x000A5853,0xFFF1C2E5,
0x00000000,0x000A5853,0xFFF1C2E5,0xFFF66667,
0x00000000,0xFFEE6667,0xFFF66667,0x00000000,
0xFFE9999A,0xFFF66667,0x000D2A98,0xFFEDE0C6,
0xFFF66667,0x000D2A98,0xFFEDE0C6,0x00000000,
0x00000000,0xFFE9999A,0x00000000,0x000A5853,
0xFFF1C2E5,0x00000000,0x0010BD14,0xFFFA8FB2,
0x00000000,0x0010BD14,0xFFFA8FB2,0xFFF66667,
0x000A5853,0xFFF1C2E5,0xFFF66667,0x000D2A98,
0xFFEDE0C6,0xFFF66667,0x00154DBD,0xFFF913FA,
0xFFF66667,0x00154DBD,0xFFF913FA,0x00000000,
0x000D2A98,0xFFEDE0C6,0x00000000,0x0010BD14,
0xFFFA8FB2,0x00000000,0x0010BD14,0x0005704E,
0x00000000,0x0010BD14,0x0005704E,0xFFF66667,
0x0010BD14,0xFFFA8FB2,0xFFF66667,0x00154DBD,
0xFFF913FA,0xFFF66667,0x00154DBD,0x0006EC06,
0xFFF66667,0x00154DBD,0x0006EC06,0x00000000,
0x00154DBD,0xFFF913FA,0x00000000,0x0010BD14,
0x0005704E,0x00000000,0x000A5853,0x000E3D1B,
0x00000000,0x000A5853,0x000E3D1B,0xFFF66667,
0x0010BD14,0x0005704E,0xFFF66667,0x00154DBD,
0x0006EC06,0xFFF66667,0x000D2A98,0x00121F39,
0xFFF66667,0x000D2A98,0x00121F39,0x00000000,
0x00154DBD,0x0006EC06,0x00000000,0x000A5853,
0x000E3D1B,0x00000000,0x00000000,0x00119999,
0x00000000,0x00000000,0x00119999,0xFFF66667,
0x000A5853,0x000E3D1B,0xFFF66667,0x000D2A98,
0x00121F39,0xFFF66667,0x00000000,0x00166666,
0xFFF66667,0x00000000,0x00166666,0x00000000,
0x000D2A98,0x00121F39,0x00000000,0x00000000,
0x00119999,0xFFF66667,0xFFF2D568,0x00121F3A,
0xFFF66667,0x00000000,0x00166666,0xFFF66667,
0xFFF5A7AD,0x000E3D1B,0xFFF66667,0x000A5853,
0x000E3D1B,0xFFF66667,0xFFEAB243,0x0006EC06,
0xFFF66667,0x000D2A98,0x00121F39,0xFFF66667,
0xFFEF42EC,0x0005704E,0xFFF66667,0x0010BD14,
0x0005704E,0xFFF66667,0xFFEAB243,0xFFF913FA,
0xFFF66667,0x00154DBD,0x0006EC06,0xFFF66667,
0xFFEF42EC,0xFFFA8FB2,0xFFF66667,0x0010BD14,
0xFFFA8FB2,0xFFF66667,0xFFF2D568,0xFFEDE0C6,
0xFFF66667,0x00154DBD,0xFFF913FA,0xFFF66667,
0xFFF5A7AD,0xFFF1C2E5,0xFFF66667,0x000A5853,
0xFFF1C2E5,0xFFF66667,0x00000000,0xFFE9999A,
0xFFF66667,0x000D2A98,0xFFEDE0C6,0xFFF66667,
0x00000000,0xFFEE6667,0xFFF66667,0x00000000,
0x00166666,0x00000000,0xFFF2D568,0x00121F3A,
0x00000000,0xFFF5A7AD,0x000E3D1B,0x00000000,
0x00000000,0x00119999,0x00000000,0xFFEF42EC,
0x0005704E,0x00000000,0x000D2A98,0x00121F39,
0x00000000,0xFFEAB243,0x0006EC06,0x00000000,
0x000A5853,0x000E3D1B,0x00000000,0xFFEF42EC,
0xFFFA8FB2,0x00000000,0x00154DBD,0x0006EC06,
0x00000000,0xFFEAB243,0xFFF913FA,0x00000000,
0x0010BD14,0x0005704E,0x00000000,0xFFF5A7AD,
0xFFF1C2E5,0x00000000,0x00154DBD,0xFFF913FA,
0x00000000,0xFFF2D568,0xFFEDE0C6,0x00000000,
0x0010BD14,0xFFFA8FB2,0x00000000,0x00000000,
0xFFEE6667,0x00000000,0x000D2A98,0xFFEDE0C6,
0x00000000,0x00000000,0xFFE9999A,0x00000000,
0x000A5853,0xFFF1C2E5,0x00000000,0x00010000,
0x00000002,0x00030002,0x00050004,0x00040006,
0x00070006,0x00090008,0x0008000A,0x000B000A,
0x000D000C,0x000C000E,0x000F000E,0x00110010,
0x00100012,0x00130012,0x00150014,0x00140016,
0x00170016,0x00190018,0x0018001A,0x001B001A,
0x001D001C,0x001C001E,0x001F001E,0x00210020,
0x00200022,0x00230022,0x00250024,0x00240026,
0x00270026,0x00290028,0x0028002A,0x002B002A,
0x002D002C,0x002C002E,0x002F002E,0x00310030,
0x00300032,0x00330032,0x00350034,0x00340036,
0x00370036,0x00390038,0x0038003A,0x003B003A,
0x003D003C,0x003C003E,0x003F003E,0x00410040,
0x00400042,0x00430042,0x00450044,0x00440046,
0x00470046,0x00490048,0x0048004A,0x004B004A,
0x004D004C,0x004C004E,0x004F004E,0x00510050,
0x00500052,0x00510053,0x00500054,0x00530052,
0x00510055,0x00520054,0x00530056,0x00550057,
0x00540058,0x00570056,0x00550059,0x00560058,
0x0057005A,0x0059005B,0x0058005C,0x005B005A,
0x0059005D,0x005A005C,0x005B005E,0x005D005F,
0x005C0060,0x005F005E,0x005D0061,0x005E0060,
0x005F0062,0x00610063,0x00600063,0x00630062,
0x00610062,0x00650064,0x00640066,0x00670066,
0x00680065,0x00690066,0x00670064,0x006A0065,
0x00690068,0x006B0067,0x006C006A,0x006D0068,
0x006B0069,0x006E006A,0x006D006C,0x006F006B,
0x0070006E,0x0071006C,0x006F006D,0x0072006E,
0x00710070,0x0073006F,0x00740072,0x00750070,
0x00730071,0x00760072,0x00750074,0x00770073,
0x00750076,0x00760077,0x00740077,0x0004F1BB,
0xFFF0C879,0x00000000,0x0004F1BB,0xFFF0C879,
0x00000000,0x0004F1BB,0xFFF0C879,0x00000000,
0x0004F1BB,0xFFF0C879,0x00000000,0xFFFB0E45,
0x000F3787,0x00000000,0xFFFB0E45,0x000F3787,
0x00000000,0xFFFB0E45,0x000F3787,0x00000000,
0xFFFB0E45,0x000F3787,0x00000000,0x000CF1BB,
0xFFF6986F,0x00000000,0x000CF1BB,0xFFF6986F,
0x00000000,0x000CF1BB,0xFFF6986F,0x00000000,
0x000CF1BB,0xFFF6986F,0x00000000,0xFFF30E45,
0x00096791,0x00000000,0xFFF30E45,0x00096791,
0x00000000,0xFFF30E45,0x00096791,0x00000000,
0xFFF30E45,0x00096791,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0x000CF1BB,
0x00096791,0x00000000,0x000CF1BB,0x00096791,
0x00000000,0x000CF1BB,0x00096791,0x00000000,
0x000CF1BB,0x00096791,0x00000000,0xFFF30E45,
0xFFF6986F,0x00000000,0xFFF30E45,0xFFF6986F,
0x00000000,0xFFF30E45,0xFFF6986F,0x00000000,
0xFFF30E45,0xFFF6986F,0x00000000,0x0004F1BB,
0x000F3787,0x00000000,0x0004F1BB,0x000F3787,
0x00000000,0x0004F1BB,0x000F3787,0x00000000,
0x0004F1BB,0x000F3787,0x00000000,0xFFFB0E45,
0xFFF0C879,0x00000000,0xFFFB0E45,0xFFF0C879,
0x00000000,0xFFFB0E45,0xFFF0C879,0x00000000,
0xFFFB0E45,0xFFF0C879,0x00000000,0xFFFB0E45,
0x000F3787,0x00000000,0xFFFB0E45,0x000F3787,
0x00000000,0xFFFB0E45,0x000F3787,0x00000000,
0xFFFB0E45,0x000F3787,0x00000000,0x0004F1BB,
0xFFF0C879,0x00000000,0x0004F1BB,0xFFF0C879,
0x00000000,0x0004F1BB,0xFFF0C879,0x00000000,
0x0004F1BB,0xFFF0C879,0x00000000,0xFFF30E45,
0x00096791,0x00000000,0xFFF30E45,0x00096791,
0x00000000,0xFFF30E45,0x00096791,0x00000000,
0xFFF30E45,0x00096791,0x00000000,0x000CF1BB,
0xFFF6986F,0x00000000,0x000CF1BB,0xFFF6986F,
0x00000000,0x000CF1BB,0xFFF6986F,0x00000000,
0x000CF1BB,0xFFF6986F,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0xFFF30E45,
0xFFF6986F,0x00000000,0xFFF30E45,0xFFF6986F,
0x00000000,0xFFF30E45,0xFFF6986F,0x00000000,
0xFFF30E45,0xFFF6986F,0x00000000,0x000CF1BB,
0x00096791,0x00000000,0x000CF1BB,0x00096791,
0x00000000,0x000CF1BB,0x00096791,0x00000000,
0x000CF1BB,0x00096791,0x00000000,0xFFFB0E44,
0xFFF0C879,0x00000000,0xFFFB0E44,0xFFF0C879,
0x00000000,0xFFFB0E44,0xFFF0C879,0x00000000,
0xFFFB0E44,0xFFF0C879,0x00000000,0x0004F1BB,
0x000F3787,0x00000000,0x0004F1BC,0x000F3787,
0x00000000,0x0004F1BB,0x000F3787,0x00000000,
0x0004F1BC,0x000F3787,0x00000000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0xFFF00000,0x00000000,0x00000000,
0xFFF00000,0x00000000,0x00000000,0xFFF00000,
0x00000000,0x00000000,0xFFF00000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x00000000,
0x00000000,0x00100000,0x00000000,0x00000000,
0x00100000,0x00000000,0x00000000,0x00100000,
0x00000000,0x00000000,0x00100000,0x027903B2,
0x030000E8,0x03000200,0x00000000,0x00000000,
0x00033333,0x038702E7,0x000A0400,0x00100000,
0x00100000,0x00100000,0x03C60400,0x0001035B,
};
| 45.920924 | 53 | 0.86935 | [
"transform"
] |
02c459c8ac2a64a1559429a996335720413b70f7 | 8,505 | h | C | ocean/boundary_model.h | fraclipe/UnderSeaModelingLibrary | 52ef9dd03c7cbe548749e4527190afe7668ff4e7 | [
"BSD-2-Clause"
] | 1 | 2021-02-07T14:48:22.000Z | 2021-02-07T14:48:22.000Z | ocean/boundary_model.h | Wolframy-NUDT/UnderSeaModelingLibrary | 43365639b435841e1bf2297cf1ac575b8cf91932 | [
"BSD-2-Clause"
] | null | null | null | ocean/boundary_model.h | Wolframy-NUDT/UnderSeaModelingLibrary | 43365639b435841e1bf2297cf1ac575b8cf91932 | [
"BSD-2-Clause"
] | null | null | null | /**
* @file boundary_model.h
* Generic interface for the ocean's surface or bottom.
*/
#pragma once
#include <usml/ocean/reflect_loss_constant.h>
#include <usml/ocean/scattering_constant.h>
namespace usml {
namespace ocean {
using boost::numeric::ublas::vector;
/// @ingroup boundaries
/// @{
/**
* A "boundary model" computes the environmental parameters of
* the ocean's surface or bottom. The modeled properties include
* the depth, reflection properties, and reverberation scattering
* strength of the interface.
* This class implements a reflection loss model through delegation.
* The delegated model is defined separately and added to its host
* during/after construction. The host is defined as a reflect_loss_model
* subclass so that it's children can share the reflection loss model
* through this delegation.
*
* This implementation defines the unit normal using Cartesian coordinates
* in the \f$(\rho,\theta,\phi)\f$ directions relative to its location.
* Given this definition, the normal can be computed from the depth
* derivatives or slope angles using:
* \f[
* s_\theta = tan(\sigma_\theta) = \frac{1}{\rho} \frac{ \partial h }{ \partial \theta }
* \f]\f[
* s_\phi = tan(\sigma_\phi) = \frac{1}{\rho sin(\theta)} \frac{ \partial h }{ \partial \phi}
* \f]\f[
* n_\theta = - sin(\sigma_\theta) = - \frac{ s_\theta }{ \sqrt{ 1 + s_\theta^2 } }
* \f]\f[
* n_\phi = - sin(\sigma_\phi) = - \frac{ s_\phi }{ \sqrt{ 1 + s_\phi^2 } }
* \f]\f[
* n_\rho = \sqrt{ 1 - ( n_\theta^2 + n_\phi^2 ) }
* \f]
* where:
* - \f$ (\rho,\theta,\phi) \f$ = location at which normal is computed,
* - \f$ ( \frac{\partial h}{\partial \theta}, \frac{\partial h}{\partial \phi} ) \f$
* = depth derivative in the \f$(\rho,\theta)\f$ and \f$(\rho,\phi)\f$ planes (meters/radian),
* - \f$ ( s_\theta,s_\phi ) \f$
* = slope in the \f$(\rho,\theta)\f$ and \f$(\rho,\phi)\f$ planes (meters/meter),
* - \f$ ( \sigma_\theta,\sigma_\phi ) \f$
* = slope angle in the \f$(\rho,\theta)\f$ and \f$(\rho,\phi)\f$ planes (radians), and
* - \f$ ( n_\rho,n_\theta,n_\phi ) \f$
* = unit normal components in "rho","theta", and "phi" directions (meters).
*
* This definition of the unit normal saves processing time during
* reflection processing.
*/
class USML_DECLSPEC boundary_model : public reflect_loss_model, scattering_model {
//**************************************************
// height model
public:
/**
* Compute the height of the boundary and it's surface normal at
* a series of locations.
*
* @param location Location at which to compute boundary.
* @param rho Surface height in spherical earth coords (output).
* @param normal Unit normal relative to location (output).
* @param quick_interp Determines if you want a fast nearest or pchip interp
*/
virtual void height( const wposition& location,
matrix<double>* rho, wvector* normal=NULL, bool quick_interp=false ) = 0 ;
/**
* Compute the height of the boundary and it's surface normal at
* a single location. Often used during reflection processing.
*
* @param location Location at which to compute boundary.
* @param rho Surface height in spherical earth coords (output).
* @param normal Unit normal relative to location (output).
* @param quick_interp Determines if you want a fast nearest or pchip interp
*/
virtual void height( const wposition1& location,
double* rho, wvector1* normal=NULL, bool quick_interp=false ) = 0 ;
//**************************************************
// reflection loss model
/**
* Define a new reflection loss model.
*
* @param reflect_loss Reflection loss model.
*/
void reflect_loss( reflect_loss_model* reflect_loss ) {
if ( _reflect_loss ) delete _reflect_loss ;
_reflect_loss = reflect_loss ;
}
/**
* Computes the broadband reflection loss and phase change.
*
* @param location Location at which to compute attenuation.
* @param frequencies Frequencies over which to compute loss. (Hz)
* @param angle Grazing angle relative to the interface (radians).
* @param amplitude Change in ray strength in dB (output).
* @param phase Change in ray phase in dB (output).
*/
virtual void reflect_loss(
const wposition1& location,
const seq_vector& frequencies, double angle,
vector<double>* amplitude, vector<double>* phase=NULL )
{
_reflect_loss->reflect_loss( location,
frequencies, angle, amplitude, phase ) ;
}
//**************************************************
// reverberation scattering strength model
/**
* Define a new reverberation scattering strength model.
*
* @param scattering Scattering model for this boundary
*/
void scattering( scattering_model* scattering ) {
if( _scattering ) delete _scattering ;
_scattering = scattering ;
}
/**
* Computes the broadband scattering strength for a single location.
*
* @param location Location at which to compute attenuation.
* @param frequencies Frequencies over which to compute loss. (Hz)
* @param de_incident Depression incident angle (radians).
* @param de_scattered Depression scattered angle (radians).
* @param az_incident Azimuthal incident angle (radians).
* @param az_scattered Azimuthal scattered angle (radians).
* @param amplitude Reverberation scattering strength ratio (output).
*/
virtual void scattering( const wposition1& location,
const seq_vector& frequencies, double de_incident, double de_scattered,
double az_incident, double az_scattered, vector<double>* amplitude )
{
_scattering->scattering( location,
frequencies, de_incident, de_scattered,
az_incident, az_scattered, amplitude ) ;
}
/**
* Computes the broadband scattering strength for a collection of
* scattering angles from a common incoming ray. Each scattering
* has its own location, de_scattered, and az_scattered.
* The result is a broadband reverberation scattering strength for
* each scattering.
*
* @param location Location at which to compute attenuation.
* @param frequencies Frequencies over which to compute loss. (Hz)
* @param de_incident Depression incident angle (radians).
* @param de_scattered Depression scattered angle (radians).
* @param az_incident Azimuthal incident angle (radians).
* @param az_scattered Azimuthal scattered angle (radians).
* @param amplitude Reverberation scattering strength ratio (output).
*/
virtual void scattering( const wposition& location,
const seq_vector& frequencies, double de_incident, matrix<double> de_scattered,
double az_incident, matrix<double> az_scattered, matrix< vector<double> >* amplitude )
{
_scattering->scattering( location,
frequencies, de_incident, de_scattered,
az_incident, az_scattered, amplitude ) ;
}
//**************************************************
// initialization
/**
* Initialize reflection loss components for a boundary.
*
* @param reflect_loss Reflection loss model.
* @param scattering Reverberation scattering strength model.
*/
boundary_model( reflect_loss_model* reflect_loss=NULL,
scattering_model* scattering=NULL )
{
if ( reflect_loss ) {
_reflect_loss = reflect_loss ;
} else {
_reflect_loss = new reflect_loss_constant( 0.0, 0.0 ) ;
}
if ( scattering ) {
_scattering = scattering ;
} else {
_scattering = new scattering_constant() ;
}
}
/**
* Delete reflection loss model.
*/
virtual ~boundary_model() {
if ( _reflect_loss ) delete _reflect_loss ;
if ( _scattering ) delete _scattering ;
}
private:
/** Reference to the reflection loss model **/
reflect_loss_model* _reflect_loss ;
/** Reference to the scattering strength model **/
scattering_model* _scattering ;
};
/// @}
} // end of namespace ocean
} // end of namespace usml
| 38.310811 | 102 | 0.629394 | [
"vector",
"model"
] |
02c5f2b798e4c7f01833a9da379546b696c629fc | 241 | h | C | match.h | castrated/chadquest | f382cd1b1326ebcd8154a543ba868ae29de98dc7 | [
"CC0-1.0"
] | null | null | null | match.h | castrated/chadquest | f382cd1b1326ebcd8154a543ba868ae29de98dc7 | [
"CC0-1.0"
] | null | null | null | match.h | castrated/chadquest | f382cd1b1326ebcd8154a543ba868ae29de98dc7 | [
"CC0-1.0"
] | null | null | null | typedef struct param {
const char *tag;
OBJECT *object;
DISTANCE distance;
int count;
}PARAM;
extern PARAM params[]
#define paramByLetter(letter)(params+(letter)-'A')
extern int matchCommand(const char *src,const char *pattern);
| 24.1 | 61 | 0.726141 | [
"object"
] |
02ca75301868d2e087a1890fe6a48f3e14dbe592 | 669 | h | C | src/geometry.h | petterh/textedit | df59502fa5309834b2d2452af609ba6fb1dc97c2 | [
"MIT"
] | 6 | 2018-04-08T06:30:27.000Z | 2021-12-19T12:52:28.000Z | src/geometry.h | petterh/textedit | df59502fa5309834b2d2452af609ba6fb1dc97c2 | [
"MIT"
] | 32 | 2017-11-03T09:39:48.000Z | 2021-12-23T18:27:20.000Z | src/geometry.h | petterh/textedit | df59502fa5309834b2d2452af609ba6fb1dc97c2 | [
"MIT"
] | 1 | 2021-09-13T08:38:56.000Z | 2021-09-13T08:38:56.000Z | /*
* $Header: /Book/geometry.h 6 3.07.99 17:46 Oslph312 $
*/
#pragma once
class Point : public tagPOINT {
public:
Point( LONG _x = 0, LONG _y = 0 );
};
inline Point::Point( LONG _x, LONG _y ) {
x = _x;
y = _y;
}
class Rect : public tagRECT {
public:
Rect();
Rect( const RECT& rc );
LONG width( void ) const;
LONG height( void ) const;
};
inline Rect::Rect() {
left = top = right = bottom = 0;
}
inline Rect::Rect( const RECT& rc ) {
memcpy( this, &rc, sizeof *this );
}
inline LONG Rect::width( void ) const {
return right - left;
}
inline LONG Rect::height( void ) const {
return bottom - top;
}
// end of file
| 13.38 | 59 | 0.58296 | [
"geometry"
] |
02ca9f9a59575f8536ff3fec2406baaad74d599b | 1,941 | h | C | aegis/include/alibabacloud/aegis/model/DescribeStratetyDetailResult.h | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | aegis/include/alibabacloud/aegis/model/DescribeStratetyDetailResult.h | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | aegis/include/alibabacloud/aegis/model/DescribeStratetyDetailResult.h | sdk-team/aliyun-openapi-cpp-sdk | d0e92f6f33126dcdc7e40f60582304faf2c229b7 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud 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 ALIBABACLOUD_AEGIS_MODEL_DESCRIBESTRATETYDETAILRESULT_H_
#define ALIBABACLOUD_AEGIS_MODEL_DESCRIBESTRATETYDETAILRESULT_H_
#include <string>
#include <vector>
#include <utility>
#include <alibabacloud/core/ServiceResult.h>
#include <alibabacloud/aegis/AegisExport.h>
namespace AlibabaCloud
{
namespace Aegis
{
namespace Model
{
class ALIBABACLOUD_AEGIS_EXPORT DescribeStratetyDetailResult : public ServiceResult
{
public:
struct Strategy
{
struct RiskTypeWhiteListQueryResult
{
struct SubType
{
std::string typeName;
std::string alias;
bool on;
};
std::string typeName;
std::vector<RiskTypeWhiteListQueryResult::SubType> subTypes;
std::string alias;
bool on;
};
int cycleStartTime;
int type;
int cycleDays;
int id;
std::vector<RiskTypeWhiteListQueryResult> riskTypeWhiteListQueryResultList;
std::string name;
};
DescribeStratetyDetailResult();
explicit DescribeStratetyDetailResult(const std::string &payload);
~DescribeStratetyDetailResult();
Strategy getStrategy()const;
protected:
void parse(const std::string &payload);
private:
Strategy strategy_;
};
}
}
}
#endif // !ALIBABACLOUD_AEGIS_MODEL_DESCRIBESTRATETYDETAILRESULT_H_ | 26.589041 | 86 | 0.722308 | [
"vector",
"model"
] |
02cfff7d3dd351ed7b6c779f3539ea812e5c753e | 207 | h | C | MinosysScript/minosysscr_api.h | minosys-jp/minosys-script | f0bd8f6edd0246887edbf874ce93540a720386d2 | [
"BSD-2-Clause"
] | null | null | null | MinosysScript/minosysscr_api.h | minosys-jp/minosys-script | f0bd8f6edd0246887edbf874ce93540a720386d2 | [
"BSD-2-Clause"
] | null | null | null | MinosysScript/minosysscr_api.h | minosys-jp/minosys-script | f0bd8f6edd0246887edbf874ce93540a720386d2 | [
"BSD-2-Clause"
] | null | null | null | #ifndef MINOSYSSCR_API_H_
// int start(Var **, Engine *, const char *, vector<Var> *);
// 関数の実行
extern "C" int start(void **pret, void *engine, const char *fname, void *args);
#endif // MINOSYSSCR_API_H_
| 23 | 79 | 0.676329 | [
"vector"
] |
02d1976d97caf261ea158b16af65276ed22baa71 | 45,127 | c | C | plugins/medimax/math/imx_math.c | bsavelev/medipy | f0da3750a6979750d5f4c96aedc89ad5ae74545f | [
"CECILL-B"
] | null | null | null | plugins/medimax/math/imx_math.c | bsavelev/medipy | f0da3750a6979750d5f4c96aedc89ad5ae74545f | [
"CECILL-B"
] | null | null | null | plugins/medimax/math/imx_math.c | bsavelev/medipy | f0da3750a6979750d5f4c96aedc89ad5ae74545f | [
"CECILL-B"
] | 1 | 2022-03-04T05:47:08.000Z | 2022-03-04T05:47:08.000Z | /*************************************************************************
* MediPy - Copyright (C) Universite de Strasbourg, 2011
* Distributed under the terms of the CeCILL-B license, as published by
* the CEA-CNRS-INRIA. Refer to the LICENSE file or to
* http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
* for details.
************************************************************************/
/********************************************************************************
**/
/*! \file: imx_math.c
***
*** project: Imagix 2.01
***
***
*** \brief description: fcts math. FFT, convolution, etc...
***
*** Fonctions decrites dans "Numerical recipes in C"
***
***---------------------------------------------------------------------*/
#include <config.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "noyau/imagix.h"
#include "math/imx_math.h"
#define NR_END 1
static int FFTRADIX (double *Re, double *Im, unsigned int nTotal, unsigned int nPass, unsigned int nSpan, int iSign, int max_factors, int max_perm);
/*
Cette fonction initialise le generateur de nombres aleatoires a une valeur
a peu pres aleatoire.
Elle ne doit etre appelee qu'une seule fois, vers le debut du programme.
*/
void init_rand_seed(void)
{
// struct tm when;
time_t now, deadline;
unsigned short the_seed[3];
/* first set the random seed to the current date & time */
now = time(NULL);
srand((unsigned int) now);
#ifndef WIN32
srandom((unsigned int) now);
#endif
the_seed[0] = (unsigned short)now;
the_seed[1] = (unsigned short)now >> (sizeof(unsigned short)); // correction berst 16;
the_seed[2] = (unsigned short)now >> (sizeof(unsigned short)*2); // correction berst 32;
#if !defined( WIN32 ) && !defined( CYGWIN ) // CORRECTION RC
seed48(the_seed);
#endif
/* Usual UNIX implementations of time() only return a second count.
In order to add further randommess, we need to take the fraction of second
into account. To do so, we run rand() repeatedly until the clock has
incremented. */
// localtime_r(& now,& when);
/* wait from 1 through 2 seconds */
// when.tm_sec += 2; /* result is in the range [2,61] */
deadline = now+2;//mktime(&when);
while (difftime(deadline, time(0)) > 0)
{
rand();
#if !defined( WIN32 ) && !defined( CYGWIN ) // CORRECTION RC
random();
drand48();
#endif
}
}
void nrerror(char *msg)
{
fprintf(stderr, "%s\n", msg);
exit(1);
}
float *vectorF(long int nl, long int nh)
{
float *v;
v=(float*)malloc((size_t)((nh-nl+1+NR_END)*sizeof(float)));
if(!v)
return NULL;
return (float*)(v-nl+NR_END);
}
void free_vectorF(float *v, long int nl, long int nh)
{
free((char*)(v+nl-NR_END));
}
void four1(float *data, long unsigned int nn, int isign)
{
unsigned long n,mmax,m,j,istep,i;
double wtemp,wr,wpr,wpi,wi,theta; /*Double precision for the trigonometric recurrences. */
float tempr,tempi;
n=nn << 1;
j=1;
for (i=1;i<n;i+=2) /* This is the bit-reversal section of the routine. */
{
if (j > i)
{
SWAPF(data[j],data[i]); /* Exchange the two complex numbers. */
SWAPF(data[j+1],data[i+1]);
}
m=n >> 1;
while (m >= 2 && j > m)
{
j -= m;
m >>= 1;
}
j += m;
}
/* Here begins the Danielson-Lanczos section of the routine. */
mmax=2;
while (n > mmax) /* Outer loop executed log 2 nn times. */
{
istep=mmax << 1;
theta=isign*(6.28318530717959/mmax); /*Initialize the trigonometric recurrence. */
wtemp=sin(0.5*theta);
wpr = -2.0*wtemp*wtemp;
wpi=sin(theta);
wr=1.0;
wi=0.0;
for (m=1;m<mmax;m+=2) /* Here are the two nested inner loops. */
{
for (i=m;i<=n;i+=istep)
{
j=i+mmax; /* This is the Danielson-Lanczos formula: */
tempr=(float)(wr*data[j]-wi*data[j+1]);
tempi=(float)(wr*data[j+1]+wi*data[j]);
data[j]=data[i]-tempr;
data[j+1]=data[i+1]-tempi;
data[i] += tempr;
data[i+1] += tempi;
}
wr=(wtemp=wr)*wpr-wi*wpi+wr; /* Trigonometric recurrence. */
wi=wi*wpr+wtemp*wpi+wi;
}
mmax=istep;
}
}
/*
Donnes deux tableaux de float en entree (data1[1..n] et data2[1..n]), cette fonction appelle
four1() et retourne deux tableaux (complexes, fft1[1..2n] et fft2[1..2n]), chacun de longueur
n (dimension reelle 2*n), et qui contiennent la TF discrete des tableaux de donnees respectifs.
n DOIT etre un entier puissance de 2
*/
void twofft(float *data1, float *data2, float *fft1, float *fft2, long unsigned int n)
{
unsigned long nn3,nn2,jj,j;
float rep,rem,aip,aim;
nn3=1+(nn2=2+n+n);
for (j=1,jj=2;j<=n;j++,jj+=2) /* Pack the two real arrays into one complex array */
{
fft1[jj-1]=data1[j];
fft1[jj]=data2[j];
}
four1(fft1,n,1); /* Transform the complex array. */
fft2[1]=fft1[2];
fft1[2]=fft2[2]=0.0;
for (j=3;j<=n+1;j+=2)
{
rep=(float)(0.5*(fft1[j]+fft1[nn2-j])); /* Use symmetries to separate the two transforms */
rem=(float)(0.5*(fft1[j]-fft1[nn2-j]));
aip=(float)(0.5*(fft1[j+1]+fft1[nn3-j]));
aim=(float)(0.5*(fft1[j+1]-fft1[nn3-j]));
fft1[j]=rep; /* Ship them out in two complex arrays. */
fft1[j+1]=aim;
fft1[nn2-j]=rep;
fft1[nn3-j] = -aim;
fft2[j]=aip;
fft2[j+1] = -rem;
fft2[nn2-j]=aip;
fft2[nn3-j]=rem;
}
}
void convlv(float *data, long unsigned int n, float *respns, long unsigned int m, int isign, float *ans)
{
unsigned long i,no2;
float dum,mag2,*fft;
fft=vectorF(1,n<<1);
for (i=1;i<=(m-1)/2;i++) /* Put respns in array of length n. */
respns[n+1-i]=respns[m+1-i];
for (i=(m+3)/2;i<=n-(m-1)/2;i++) /* Pad with zeros. */
respns[i]=0.0;
twofft(data,respns,fft,ans,n); /* FFT both at once. */
no2=n>>1;
for (i=2;i<=n+2;i+=2)
{
if(isign == 1)
{
ans[i-1]=(fft[i-1]*(dum=ans[i-1])-fft[i]*ans[i])/no2; /* Multiply FFTs to convolve. */
ans[i]=(fft[i]*dum+fft[i-1]*ans[i])/no2;
}
else if(isign == -1)
{
if ((mag2=(float)(SQR(ans[i-1])+SQR(ans[i]))) == 0.0)
nrerror("Deconvolving at response zero in convlv");
ans[i-1]=(fft[i-1]*(dum=ans[i-1])+fft[i]*ans[i])/mag2/no2; /* Divide FFTs to deconvolve. */
ans[i]=(fft[i]*dum-fft[i-1]*ans[i])/mag2/no2;
}
else
nrerror("No meaning for isign in convlv");
}
ans[2]=ans[n+1]; /* Pack last element with rst for realft. */
realft(ans,n,-1); /* Inverse transform back to time domain. */
free_vectorF(fft,1,n<<1);
}
/*
Calculates the Fourier transform of a set of n real-valued data points. Replaces this data (which
is stored in array data[1..n]) by the positive frequency half of its complex Fourier transform.
The real-valued first and last components of the complex transform are returned as elements
data[1] and data[2], respectively. n must be a power of 2. This routine also calculates the
inverse transform of a complex data array if it is the transform of real data. (Result in this case
must be multiplied by 2/n.)
Calcule la TF d'un tableaux de n elements de type float. Remplace les donnees stockees dans data
par
*/
void realft(float *data, long unsigned int n, int isign)
{
unsigned long i,i1,i2,i3,i4,np3;
float c1=0.5,c2,h1r,h1i,h2r,h2i;
double wr,wi,wpr,wpi,wtemp,theta; /* Double precision for the trigonometric recurrences. */
theta=3.141592653589793/(double) (n>>1); /* Initialize the recurrence. */
if (isign == 1)
{
c2 = -0.5;
four1(data,n>>1,1); /* The forward transform is here. */
}
else
{
c2=0.5; /* Otherwise set up for an inverse transform. */
theta = -theta;
}
wtemp=sin(0.5*theta);
wpr = -2.0*wtemp*wtemp;
wpi=sin(theta);
wr=1.0+wpr;
wi=wpi;
np3=n+3;
for(i=2;i<=(n>>2);i++)
{
/* Case i=1 done separately below. */
i4=1+(i3=np3-(i2=1+(i1=i+i-1)));
h1r=c1*(data[i1]+data[i3]); /* The two separate transforms are separated out of data. */
h1i=c1*(data[i2]-data[i4]);
h2r = -c2*(data[i2]+data[i4]);
h2i=c2*(data[i1]-data[i3]);
data[i1]=(float)(h1r+wr*h2r-wi*h2i); /* Here they are recombined to form the true transform of the original real data. */
data[i2]=(float)(h1i+wr*h2i+wi*h2r);
data[i3]=(float)(h1r-wr*h2r+wi*h2i);
data[i4]=(float)(-h1i+wr*h2i+wi*h2r);
wr=(wtemp=wr)*wpr-wi*wpi+wr; /* The recurrence. */
wi=wi*wpr+wtemp*wpi+wi;
}
if (isign == 1)
{
data[1] = (h1r=data[1])+data[2]; /* Squeeze the first and last data together to get them all within the original array. */
data[2] = h1r-data[2];
}
else
{
data[1]=c1*((h1r=data[1])+data[2]);
data[2]=c1*(h1r-data[2]);
four1(data,n>>1,-1); /* This is the inverse transform for the case isign=-1. */
}
}
/*--------------------------------*-C-*---------------------------------*
* File:
* fftn.c
*
* Public:
* fft_free ();
* fftn / fftnf ();
*
* Private:
* fftradix / fftradixf ();
*
* Descript:
* multivariate complex Fourier transform, computed in place
* using mixed-radix Fast Fourier Transform algorithm.
*
* Fortran code by:
* RC Singleton, Stanford Research Institute, Sept. 1968
*
* translated by f2c (version 19950721).
*
* Revisions:
* 26 July 95 John Beale
* - added maxf and maxp as parameters to fftradix()
*
*
* - added fft_free() to provide some measure of control over
* allocation/deallocation.
*
* - added fftn() wrapper for multidimensional FFTs
*
* - use -DFFT_NOFLOAT or -DFFT_NODOUBLE to avoid compiling that
* precision. Note suffix `f' on the function names indicates
* float precision.
*
* - revised documentation
*
* 31 July 95 Mark Olesen <olesen@me.queensu.ca>
* - added GNU Public License
* - more cleanup
* - define SUN_BROKEN_REALLOC to use malloc() instead of realloc()
* on the first pass through, apparently needed for old libc
* - removed #error directive in favour of some code that simply
* won't compile (generate an error that way)
*
* 1 Aug 95 Mark Olesen <olesen@me.queensu.ca>
* - define FFT_RADIX4 to only have radix 2, radix 4 transforms
* - made fftradix /fftradixf () static scope, just use fftn()
* instead. If you have good ideas about fixing the factors
* in fftn() please do so.
*
* ======================================================================*
* NIST Guide to Available Math Software.
* Source for module FFT from package GO.
* Retrieved from NETLIB on Wed Jul 5 11:50:07 1995.
* ======================================================================*
*
*-----------------------------------------------------------------------*
*
* int fftn (int ndim, const int dims[], REAL Re[], REAL Im[],
* int iSign, double scaling);
*
* NDIM = the total number dimensions
* DIMS = a vector of array sizes
* if NDIM is zero then DIMS must be zero-terminated
*
* RE and IM hold the real and imaginary components of the data, and return
* the resulting real and imaginary Fourier coefficients. Multidimensional
* data *must* be allocated contiguously. There is no limit on the number
* of dimensions.
*
* ISIGN = the sign of the complex exponential (ie, forward or inverse FFT)
* the magnitude of ISIGN (normally 1) is used to determine the
* correct indexing increment (see below).
*
* SCALING = normalizing constant by which the final result is *divided*
* if SCALING == -1, normalize by total dimension of the transform
* if SCALING < -1, normalize by the square-root of the total dimension
*
* example:
* tri-variate transform with Re[n1][n2][n3], Im[n1][n2][n3]
*
* int dims[3] = {n1,n2,n3}
* fftn (3, dims, Re, Im, 1, scaling);
*
*-----------------------------------------------------------------------*
* int fftradix (REAL Re[], REAL Im[], size_t nTotal, size_t nPass,
* size_t nSpan, int iSign, size_t max_factors,
* size_t max_perm);
*
* RE, IM - see above documentation
*
* Although there is no limit on the number of dimensions, fftradix() must
* be called once for each dimension, but the calls may be in any order.
*
* NTOTAL = the total number of complex data values
* NPASS = the dimension of the current variable
* NSPAN/NPASS = the spacing of consecutive data values while indexing the
* current variable
* ISIGN - see above documentation
*
* example:
* tri-variate transform with Re[n1][n2][n3], Im[n1][n2][n3]
*
* fftradix (Re, Im, n1*n2*n3, n1, n1, 1, maxf, maxp);
* fftradix (Re, Im, n1*n2*n3, n2, n1*n2, 1, maxf, maxp);
* fftradix (Re, Im, n1*n2*n3, n3, n1*n2*n3, 1, maxf, maxp);
*
* single-variate transform,
* NTOTAL = N = NSPAN = (number of complex data values),
*
* fftradix (Re, Im, n, n, n, 1, maxf, maxp);
*
* The data can also be stored in a single array with alternating real and
* imaginary parts, the magnitude of ISIGN is changed to 2 to give correct
* indexing increment, and data [0] and data [1] used to pass the initial
* addresses for the sequences of real and imaginary values,
*
* example:
* REAL data [2*NTOTAL];
* fftradix ( &data[0], &data[1], NTOTAL, nPass, nSpan, 2, maxf, maxp);
*
* for temporary allocation:
*
* MAX_FACTORS >= the maximum prime factor of NPASS
* MAX_PERM >= the number of prime factors of NPASS. In addition,
* if the square-free portion K of NPASS has two or more prime
* factors, then MAX_PERM >= (K-1)
*
* storage in FACTOR for a maximum of 15 prime factors of NPASS. if NPASS
* has more than one square-free factor, the product of the square-free
* factors must be <= 210 array storage for maximum prime factor of 23 the
* following two constants should agree with the array dimensions.
*
*-----------------------------------------------------------------------*
*
* void fft_free (void);
*
* free-up allocated temporary storage after finished all the Fourier
* transforms.
*
*----------------------------------------------------------------------*/
#define size_t unsigned int
/* double precision routine
static int fftradix (double Re[], double Im[],
size_t nTotal, size_t nPass, size_t nSpan, int isign,
int max_factors, int max_perm);*/
/* float precision routine
static int fftradixf (float Re[], float Im[],
size_t nTotal, size_t nPass, size_t nSpan, int isign,
int max_factors, int max_perm);*/
/* parameters for memory management */
static size_t SpaceAlloced = 0;
static size_t MaxPermAlloced = 0;
/* temp space, (void *) since both float and double routines use it */
static void *Tmp0 = NULL; /* temp space for real part */
static void *Tmp1 = NULL; /* temp space for imaginary part */
static void *Tmp2 = NULL; /* temp space for Cosine values */
static void *Tmp3 = NULL; /* temp space for Sine values */
static int *Perm = NULL; /* Permutation vector */
#define NFACTOR 11
static int factor [NFACTOR];
void fft_free (void)
{
SpaceAlloced = MaxPermAlloced = 0;
if (Tmp0 != NULL) { free (Tmp0); Tmp0 = NULL; }
if (Tmp1 != NULL) { free (Tmp1); Tmp1 = NULL; }
if (Tmp2 != NULL) { free (Tmp2); Tmp2 = NULL; }
if (Tmp3 != NULL) { free (Tmp3); Tmp3 = NULL; }
if (Perm != NULL) { free (Perm); Perm = NULL; }
}
/*
*
*/
int fftn (int ndim, int *dims, double *Re, double *Im, int iSign)
{
size_t nSpan, nPass;
int ret, i , nTotal;
unsigned int max_factors,max_perm;
REAL scaling;
/*
* tally the number of elements in the data array
* and determine the number of dimensions
*/
nTotal = 1;
if (ndim && dims [0])
{
for (i = 0; i < ndim; i++)
{
if (dims [i] <= 0)
{
fputs ("Error: fftn () - dimension error\n", stderr);
fft_free (); /* free-up memory */
return -1;
}
nTotal *= dims [i];
}
}
else
{
ndim = 0;
for (i = 0; dims [i]; i++)
{
if (dims [i] <= 0)
{
fputs ("Error: fftn() - dimension error\n", stderr);
fft_free (); /* free-up memory */
return -1;
}
nTotal *= dims [i];
ndim++;
}
}
/* determine maximum number of factors and permuations */
#if 1
/*
* follow John Beale's example, just use the largest dimension and don't
* worry about excess allocation. May be someone else will do it?
*/
max_factors = max_perm = 1;
for (i = 0; i < ndim; i++)
{
nSpan = dims [i];
if (nSpan > max_factors) max_factors = nSpan;
if (nSpan > max_perm) max_perm = nSpan;
}
#endif
/* loop over the dimensions: */
nPass = 1;
for (i = 0; i < ndim; i++)
{
printf("passage %d\n", i);
nSpan = dims [i];
nPass *= nSpan;
ret = FFTRADIX (Re, Im, nTotal, nSpan, nPass, iSign,
max_factors, max_perm);
/* exit, clean-up already done */
if (ret)
return ret;
}
/* Divide through by the normalizing constant: */
if (iSign < 0) {
scaling = 1.0 / nTotal; /* multiply is often faster */
for (i = 0; i < nTotal; i += 1)
{
Re [i] *= scaling;
Im [i] *= scaling;
}
}
return 0;
}
/*
* singleton's mixed radix routine
*
* could move allocation out to fftn(), but leave it here so that it's
* possible to make this a standalone function
*/
static int FFTRADIX (double *Re, double *Im, unsigned int nTotal, unsigned int nPass, unsigned int nSpan, int iSign, int max_factors, int max_perm)
{
int ii, mfactor, kspan, ispan, inc;
int j, jc, jf, jj, k, k1, k2, k3, k4, kk, kt, nn, ns, nt;
REAL radf;
REAL c1, c2, c3, cd, aa, aj, ak, ajm, ajp, akm, akp;
REAL s1, s2, s3, sd, bb, bj, bk, bjm, bjp, bkm, bkp;
REAL *Rtmp = NULL; /* temp space for real part*/
REAL *Itmp = NULL; /* temp space for imaginary part */
REAL *Cos = NULL; /* Cosine values */
REAL *Sin = NULL; /* Sine values */
REAL s60 = SIN60; /* sin(60 deg) */
REAL c72 = COS72; /* cos(72 deg) */
REAL s72 = SIN72; /* sin(72 deg) */
REAL pi2 = M_PI; /* use PI first, 2 PI later */
/* gcc complains about k3 being uninitialized, but I can't find out where
* or why ... it looks okay to me.
*
* initialize to make gcc happy
*/
k3 = 0;
/* gcc complains about c2, c3, s2,s3 being uninitialized, but they're
* only used for the radix 4 case and only AFTER the (s1 == 0.0) pass
* through the loop at which point they will have been calculated.
*
* initialize to make gcc happy
*/
c2 = c3 = s2 = s3 = 0.0;
/* Parameter adjustments, was fortran so fix zero-offset */
Re--;
Im--;
if (nPass < 2)
return 0;
/* allocate storage */
if (SpaceAlloced < max_factors * sizeof (REAL))
{
#ifdef SUN_BROKEN_REALLOC
if (!SpaceAlloced) /* first time */
{
SpaceAlloced = max_factors * sizeof (REAL);
Tmp0 = (void *) malloc (SpaceAlloced);
Tmp1 = (void *) malloc (SpaceAlloced);
Tmp2 = (void *) malloc (SpaceAlloced);
Tmp3 = (void *) malloc (SpaceAlloced);
}
else
{
#endif
SpaceAlloced = max_factors * sizeof (REAL);
Tmp0 = (void *) realloc (Tmp0, SpaceAlloced);
Tmp1 = (void *) realloc (Tmp1, SpaceAlloced);
Tmp2 = (void *) realloc (Tmp2, SpaceAlloced);
Tmp3 = (void *) realloc (Tmp3, SpaceAlloced);
#ifdef SUN_BROKEN_REALLOC
}
#endif
}
else
{
/* allow full use of alloc'd space */
max_factors = SpaceAlloced / sizeof (REAL);
}
if ((int)MaxPermAlloced < max_perm)
{
#ifdef SUN_BROKEN_REALLOC
if (!MaxPermAlloced) /* first time */
Perm = (int *) malloc (max_perm * sizeof(int));
else
#endif
Perm = (int *) realloc (Perm, max_perm * sizeof(int));
MaxPermAlloced = max_perm;
}
else
{
/* allow full use of alloc'd space */
max_perm = MaxPermAlloced;
}
if (Tmp0 == NULL || Tmp1 == NULL || Tmp2 == NULL || Tmp3 == NULL
|| Perm == NULL)
goto Memory_Error_Label;
/* assign pointers */
Rtmp = (REAL *) Tmp0;
Itmp = (REAL *) Tmp1;
Cos = (REAL *) Tmp2;
Sin = (REAL *) Tmp3;
/*
* Function Body
*/
inc = iSign;
if (iSign < 0) {
s72 = -s72;
s60 = -s60;
pi2 = -pi2;
inc = -inc; /* absolute value */
}
/* adjust for strange increments */
nt = inc * nTotal;
ns = inc * nSpan;
kspan = ns;
nn = nt - inc;
jc = ns / nPass;
radf = pi2 * (double) jc;
pi2 *= 2.0; /* use 2 PI from here on */
ii = 0;
jf = 0;
/* determine the factors of n */
mfactor = 0;
k = nPass;
while (k % 16 == 0) {
mfactor++;
factor [mfactor - 1] = 4;
k /= 16;
}
j = 3;
jj = 9;
do {
while (k % jj == 0) {
mfactor++;
factor [mfactor - 1] = j;
k /= jj;
}
j += 2;
jj = j * j;
}
while (jj <= k);
if (k <= 4) {
kt = mfactor;
factor [mfactor] = k;
if (k != 1)
mfactor++;
}
else {
if (k - (k / 4 << 2) == 0) {
mfactor++;
factor [mfactor - 1] = 2;
k /= 4;
}
kt = mfactor;
j = 2;
do {
if (k % j == 0) {
mfactor++;
factor [mfactor - 1] = j;
k /= j;
}
j = ((j + 1) / 2 << 1) + 1;
} while (j <= k);
}
if (kt) {
j = kt;
do {
mfactor++;
factor [mfactor - 1] = factor [j - 1];
j--;
} while (j);
}
/* test that mfactors is in range */
if (mfactor > NFACTOR)
{
fputs ("Error: fftradix() - exceeded number of factors\n", stderr);
goto Memory_Error_Label;
}
/* compute fourier transform */
for (;;) {
sd = radf / (double) kspan;
cd = sin(sd);
cd = 2.0 * cd * cd;
sd = sin(sd + sd);
kk = 1;
ii++;
switch (factor [ii - 1]) {
case 2:
/* transform for factor of 2 (including rotation factor) */
kspan /= 2;
k1 = kspan + 2;
do {
do {
k2 = kk + kspan;
ak = Re [k2];
bk = Im [k2];
Re [k2] = Re [kk] - ak;
Im [k2] = Im [kk] - bk;
Re [kk] += ak;
Im [kk] += bk;
kk = k2 + kspan;
} while (kk <= nn);
kk -= nn;
} while (kk <= jc);
if (kk > kspan)
goto Permute_Results_Label; /* exit infinite loop */
do {
c1 = 1.0 - cd;
s1 = sd;
do {
do {
do {
k2 = kk + kspan;
ak = Re [kk] - Re [k2];
bk = Im [kk] - Im [k2];
Re [kk] += Re [k2];
Im [kk] += Im [k2];
Re [k2] = c1 * ak - s1 * bk;
Im [k2] = s1 * ak + c1 * bk;
kk = k2 + kspan;
} while (kk < nt);
k2 = kk - nt;
c1 = -c1;
kk = k1 - k2;
} while (kk > k2);
ak = c1 - (cd * c1 + sd * s1);
s1 = sd * c1 - cd * s1 + s1;
c1 = 2.0 - (ak * ak + s1 * s1);
s1 *= c1;
c1 *= ak;
kk += jc;
} while (kk < k2);
k1 += inc + inc;
kk = (k1 - kspan) / 2 + jc;
} while (kk <= jc + jc);
break;
case 4: /* transform for factor of 4 */
ispan = kspan;
kspan /= 4;
do {
c1 = 1.0;
s1 = 0.0;
do {
do {
k1 = kk + kspan;
k2 = k1 + kspan;
k3 = k2 + kspan;
akp = Re [kk] + Re [k2];
akm = Re [kk] - Re [k2];
ajp = Re [k1] + Re [k3];
ajm = Re [k1] - Re [k3];
bkp = Im [kk] + Im [k2];
bkm = Im [kk] - Im [k2];
bjp = Im [k1] + Im [k3];
bjm = Im [k1] - Im [k3];
Re [kk] = akp + ajp;
Im [kk] = bkp + bjp;
ajp = akp - ajp;
bjp = bkp - bjp;
if (iSign < 0) {
akp = akm + bjm;
bkp = bkm - ajm;
akm -= bjm;
bkm += ajm;
} else {
akp = akm - bjm;
bkp = bkm + ajm;
akm += bjm;
bkm -= ajm;
}
/* avoid useless multiplies */
if (s1 == 0.0) {
Re [k1] = akp;
Re [k2] = ajp;
Re [k3] = akm;
Im [k1] = bkp;
Im [k2] = bjp;
Im [k3] = bkm;
} else {
Re [k1] = akp * c1 - bkp * s1;
Re [k2] = ajp * c2 - bjp * s2;
Re [k3] = akm * c3 - bkm * s3;
Im [k1] = akp * s1 + bkp * c1;
Im [k2] = ajp * s2 + bjp * c2;
Im [k3] = akm * s3 + bkm * c3;
}
kk = k3 + kspan;
} while (kk <= nt);
c2 = c1 - (cd * c1 + sd * s1);
s1 = sd * c1 - cd * s1 + s1;
c1 = 2.0 - (c2 * c2 + s1 * s1);
s1 *= c1;
c1 *= c2;
/* values of c2, c3, s2, s3 that will get used next time */
c2 = c1 * c1 - s1 * s1;
s2 = 2.0 * c1 * s1;
c3 = c2 * c1 - s2 * s1;
s3 = c2 * s1 + s2 * c1;
kk = kk - nt + jc;
} while (kk <= kspan);
kk = kk - kspan + inc;
} while (kk <= jc);
if (kspan == jc)
goto Permute_Results_Label; /* exit infinite loop */
break;
default:
/* transform for odd factors */
#ifdef FFT_RADIX4
fputs ("Error: " FFTRADIXS "(): compiled for radix 2/4 only\n", stderr);
fft_free (); /* free-up memory */
return -1;
break;
#else /* FFT_RADIX4 */
k = factor [ii - 1];
ispan = kspan;
kspan /= k;
switch (k) {
case 3: /* transform for factor of 3 (optional code) */
do {
do {
k1 = kk + kspan;
k2 = k1 + kspan;
ak = Re [kk];
bk = Im [kk];
aj = Re [k1] + Re [k2];
bj = Im [k1] + Im [k2];
Re [kk] = ak + aj;
Im [kk] = bk + bj;
ak -= 0.5 * aj;
bk -= 0.5 * bj;
aj = (Re [k1] - Re [k2]) * s60;
bj = (Im [k1] - Im [k2]) * s60;
Re [k1] = ak - bj;
Re [k2] = ak + bj;
Im [k1] = bk + aj;
Im [k2] = bk - aj;
kk = k2 + kspan;
} while (kk < nn);
kk -= nn;
} while (kk <= kspan);
break;
case 5: /* transform for factor of 5 (optional code) */
c2 = c72 * c72 - s72 * s72;
s2 = 2.0 * c72 * s72;
do {
do {
k1 = kk + kspan;
k2 = k1 + kspan;
k3 = k2 + kspan;
k4 = k3 + kspan;
akp = Re [k1] + Re [k4];
akm = Re [k1] - Re [k4];
bkp = Im [k1] + Im [k4];
bkm = Im [k1] - Im [k4];
ajp = Re [k2] + Re [k3];
ajm = Re [k2] - Re [k3];
bjp = Im [k2] + Im [k3];
bjm = Im [k2] - Im [k3];
aa = Re [kk];
bb = Im [kk];
Re [kk] = aa + akp + ajp;
Im [kk] = bb + bkp + bjp;
ak = akp * c72 + ajp * c2 + aa;
bk = bkp * c72 + bjp * c2 + bb;
aj = akm * s72 + ajm * s2;
bj = bkm * s72 + bjm * s2;
Re [k1] = ak - bj;
Re [k4] = ak + bj;
Im [k1] = bk + aj;
Im [k4] = bk - aj;
ak = akp * c2 + ajp * c72 + aa;
bk = bkp * c2 + bjp * c72 + bb;
aj = akm * s2 - ajm * s72;
bj = bkm * s2 - bjm * s72;
Re [k2] = ak - bj;
Re [k3] = ak + bj;
Im [k2] = bk + aj;
Im [k3] = bk - aj;
kk = k4 + kspan;
} while (kk < nn);
kk -= nn;
} while (kk <= kspan);
break;
default:
if (k != jf) {
jf = k;
s1 = pi2 / (double) k;
c1 = cos(s1);
s1 = sin(s1);
if (jf > max_factors)
goto Memory_Error_Label;
Cos [jf - 1] = 1.0;
Sin [jf - 1] = 0.0;
j = 1;
do {
Cos [j - 1] = Cos [k - 1] * c1 + Sin [k - 1] * s1;
Sin [j - 1] = Cos [k - 1] * s1 - Sin [k - 1] * c1;
k--;
Cos [k - 1] = Cos [j - 1];
Sin [k - 1] = -Sin [j - 1];
j++;
} while (j < k);
}
do {
do {
k1 = kk;
k2 = kk + ispan;
ak = aa = Re [kk];
bk = bb = Im [kk];
j = 1;
k1 += kspan;
do {
k2 -= kspan;
j++;
Rtmp [j - 1] = Re [k1] + Re [k2];
ak += Rtmp [j - 1];
Itmp [j - 1] = Im [k1] + Im [k2];
bk += Itmp [j - 1];
j++;
Rtmp [j - 1] = Re [k1] - Re [k2];
Itmp [j - 1] = Im [k1] - Im [k2];
k1 += kspan;
} while (k1 < k2);
Re [kk] = ak;
Im [kk] = bk;
k1 = kk;
k2 = kk + ispan;
j = 1;
do {
k1 += kspan;
k2 -= kspan;
jj = j;
ak = aa;
bk = bb;
aj = 0.0;
bj = 0.0;
k = 1;
do {
k++;
ak += Rtmp [k - 1] * Cos [jj - 1];
bk += Itmp [k - 1] * Cos [jj - 1];
k++;
aj += Rtmp [k - 1] * Sin [jj - 1];
bj += Itmp [k - 1] * Sin [jj - 1];
jj += j;
if (jj > jf) {
jj -= jf;
}
} while (k < jf);
k = jf - j;
Re [k1] = ak - bj;
Im [k1] = bk + aj;
Re [k2] = ak + bj;
Im [k2] = bk - aj;
j++;
} while (j < k);
kk += ispan;
} while (kk <= nn);
kk -= nn;
} while (kk <= kspan);
break;
}
/* multiply by rotation factor (except for factors of 2 and 4) */
if (ii == mfactor)
goto Permute_Results_Label; /* exit infinite loop */
kk = jc + 1;
do {
c2 = 1.0 - cd;
s1 = sd;
do {
c1 = c2;
s2 = s1;
kk += kspan;
do {
do {
ak = Re [kk];
Re [kk] = c2 * ak - s2 * Im [kk];
Im [kk] = s2 * ak + c2 * Im [kk];
kk += ispan;
} while (kk <= nt);
ak = s1 * s2;
s2 = s1 * c2 + c1 * s2;
c2 = c1 * c2 - ak;
kk = kk - nt + kspan;
} while (kk <= ispan);
c2 = c1 - (cd * c1 + sd * s1);
s1 += sd * c1 - cd * s1;
c1 = 2.0 - (c2 * c2 + s1 * s1);
s1 *= c1;
c2 *= c1;
kk = kk - ispan + jc;
} while (kk <= kspan);
kk = kk - kspan + jc + inc;
} while (kk <= jc + jc);
break;
#endif /* FFT_RADIX4 */
}
}
/* permute the results to normal order---done in two stages */
/* permutation for square factors of n */
Permute_Results_Label:
Perm [0] = ns;
if (kt) {
k = kt + kt + 1;
if (mfactor < k)
k--;
j = 1;
Perm [k] = jc;
do {
Perm [j] = Perm [j - 1] / factor [j - 1];
Perm [k - 1] = Perm [k] * factor [j - 1];
j++;
k--;
} while (j < k);
k3 = Perm [k];
kspan = Perm [1];
kk = jc + 1;
k2 = kspan + 1;
j = 1;
if (nPass != nTotal) {
/* permutation for multivariate transform */
Permute_Multi_Label:
do {
do {
k = kk + jc;
do {
/* swap Re [kk] <> Re [k2], Im [kk] <> Im [k2] */
ak = Re [kk]; Re [kk] = Re [k2]; Re [k2] = ak;
bk = Im [kk]; Im [kk] = Im [k2]; Im [k2] = bk;
kk += inc;
k2 += inc;
} while (kk < k);
kk += ns - jc;
k2 += ns - jc;
} while (kk < nt);
k2 = k2 - nt + kspan;
kk = kk - nt + jc;
} while (k2 < ns);
do {
do {
k2 -= Perm [j - 1];
j++;
k2 = Perm [j] + k2;
} while (k2 > Perm [j - 1]);
j = 1;
do {
if (kk < k2)
goto Permute_Multi_Label;
kk += jc;
k2 += kspan;
} while (k2 < ns);
} while (kk < ns);
} else {
/* permutation for single-variate transform (optional code) */
Permute_Single_Label:
do {
/* swap Re [kk] <> Re [k2], Im [kk] <> Im [k2] */
ak = Re [kk]; Re [kk] = Re [k2]; Re [k2] = ak;
bk = Im [kk]; Im [kk] = Im [k2]; Im [k2] = bk;
kk += inc;
k2 += kspan;
} while (k2 < ns);
do {
do {
k2 -= Perm [j - 1];
j++;
k2 = Perm [j] + k2;
} while (k2 > Perm [j - 1]);
j = 1;
do {
if (kk < k2)
goto Permute_Single_Label;
kk += inc;
k2 += kspan;
} while (k2 < ns);
} while (kk < ns);
}
jc = k3;
}
if ((kt << 1) + 1 >= mfactor)
return 0;
ispan = Perm [kt];
/* permutation for square-free factors of n */
j = mfactor - kt;
factor [j] = 1;
do {
factor [j - 1] *= factor [j];
j--;
} while (j != kt);
kt++;
nn = factor [kt - 1] - 1;
if (nn > max_perm)
goto Memory_Error_Label;
j = jj = 0;
for (;;) {
k = kt + 1;
k2 = factor [kt - 1];
kk = factor [k - 1];
j++;
if (j > nn)
break; /* exit infinite loop */
jj += kk;
while (jj >= k2) {
jj -= k2;
k2 = kk;
k++;
kk = factor [k - 1];
jj += kk;
}
Perm [j - 1] = jj;
}
/* determine the permutation cycles of length greater than 1 */
j = 0;
for (;;) {
do {
j++;
kk = Perm [j - 1];
} while (kk < 0);
if (kk != j) {
do {
k = kk;
kk = Perm [k - 1];
Perm [k - 1] = -kk;
} while (kk != j);
k3 = kk;
} else {
Perm [j - 1] = -j;
if (j == nn)
break; /* exit infinite loop */
}
}
max_factors *= inc;
/* reorder a and b, following the permutation cycles */
for (;;) {
j = k3 + 1;
nt -= ispan;
ii = nt - inc + 1;
if (nt < 0)
break; /* exit infinite loop */
do {
do {
j--;
} while (Perm [j - 1] < 0);
jj = jc;
do {
kspan = jj;
if (jj > max_factors) {
kspan = max_factors;
}
jj -= kspan;
k = Perm [j - 1];
kk = jc * k + ii + jj;
k1 = kk + kspan;
k2 = 0;
do {
k2++;
Rtmp [k2 - 1] = Re [k1];
Itmp [k2 - 1] = Im [k1];
k1 -= inc;
} while (k1 != kk);
do {
k1 = kk + kspan;
k2 = k1 - jc * (k + Perm [k - 1]);
k = -Perm [k - 1];
do {
Re [k1] = Re [k2];
Im [k1] = Im [k2];
k1 -= inc;
k2 -= inc;
} while (k1 != kk);
kk = k2;
} while (k != j);
k1 = kk + kspan;
k2 = 0;
do {
k2++;
Re [k1] = Rtmp [k2 - 1];
Im [k1] = Itmp [k2 - 1];
k1 -= inc;
} while (k1 != kk);
} while (jj);
} while (j != 1);
}
return 0; /* exit point here */
/* alloc or other problem, do some clean-up */
Memory_Error_Label:
fputs ("Error: fftradix() - insufficient memory.\n", stderr);
fft_free (); /* free-up memory */
return -1;
}
/* _FFTN_C */
/* ---------------------- end-of-file (c source) ---------------------- */
void test_conv(void)
{
/* int id,k,n;
float *x;
float *vals;
float *ans,*resp;
n = 90*2;
x = (float*)malloc(sizeof(float)*n);
vals = (float*)malloc(sizeof(float)*n);
ans = (float*)malloc(sizeof(float)*n);
resp = (float*)malloc(sizeof(float)*n);
n /=2;
id=OpenGraph();
ClearGraph(id);
for(k=0 ; k<n ; k++)
{
x[k] = k+1;
}
for(k=0 ; k<30 ; k++)
{
vals[k] = 0.0;
}
for(k=30 ; k<60 ; k++)
{
vals[k] = 10.0;
}
for(k=60 ; k<90 ; k++)
{
vals[k] = 0.0;
}
for(k=0 ; k<n ; k++)
{
resp[k] = vals[k];
}
convlv(vals, n, resp, 45, 1, ans);
PLOT_LINE(id, x, ans, n, "X", "Y", "", "Test convolution");
return;*/
}
/**************************************************/
/*---------------------------------------------------------------------*/
/***********************************************************************
** -- init_simplex ()
**
** Preparation des tableaux necessaires au simplex
**
** Utilisation : donner a la fonction un pointeur fun sur une structure
** deja existante de type Parametre (la structure doit deja etre allouee)
**
** le nombre de points de la fonction dentree
**
** un pointeur sur un vertex (en fait un tableau de
** vertices deja alloue)
**
** le nombre de vertices
**
** le nombre de parametres a estimer dans chaque vertex
**
*************************************************************************/
void init_simplex (Param_simplex *fun, int nb_pts, Vertex *vtx, int nb_vtx, int nb_param)
{
int i;
/* Allocation memoire de la structure Parametre suivant le nb de pts de la courbe voulu */
fun->nb_point = nb_pts;
if ((fun->tab_val_in = (float *) malloc(nb_pts * sizeof(float))) == NULL) exit(-1);
if ((fun->tab_val_out = (float *) malloc(nb_pts * sizeof(float))) == NULL) exit(-1);
if ((fun->x = (float *) malloc(nb_pts * sizeof(float))) == NULL) exit(-1);
/* Allocation des tableaux des vertices */
for (i = 0 ; i < nb_vtx ; i++) {
vtx[i].nb_valeur_estimer = nb_param;
if ((vtx[i].valeur_estimer = (float *) malloc(vtx[i].nb_valeur_estimer * sizeof(float))) == NULL) exit(-2);
}
}
/***************************************************************************
** -- free_simplex()
**
** Libere les tableaux dynamiques utilises par le simplex
**
** Utilisation : A la fin de la routine simplex
**
** passer un pointeur sur les Parametre de la fonction a minimiser
**
** passer un tableau de vertices
**
** et le nombre de vertices de ce tableau
**
****************************************************************************/
void free_simplex(Param_simplex *fun, Vertex *vtx, int nb_vtx)
{
int i;
/* Liberation des courbes */
if (fun->tab_val_in) free(fun->tab_val_in);
if (fun->tab_val_out) free(fun->tab_val_out);
if (fun->x) free(fun->x);
/* Liberation des vertices */
for (i = 0 ; i < nb_vtx ; i++)
if (&vtx[i])
if (vtx[i].valeur_estimer) free(vtx[i].valeur_estimer);
}
/*********************************************************************
** -- swap_vtx()
**
** Echange les donnees de 2 vertices passes en arguments
**
**********************************************************************/
void swap_vtx(Vertex *v1, Vertex *v2)
{
float tmp;
int i;
for (i = 0 ; i < v1->nb_valeur_estimer ; i++) {
tmp = v1->valeur_estimer[i];
v1->valeur_estimer[i] = v2->valeur_estimer[i];
v2->valeur_estimer[i] = tmp;
}
tmp = v1->r;
v1->r = v2->r;
v2->r = tmp;
}
/***********************************************************************
** -- simplex_gen()
**
** A partir d'un panel de solutions donnees par lutilisateur, le simplex
** va rechercher une solution qui minimise la difference
**
** Utilisation :
**
** Il faut lui fournir des Parametres de fonction remplis, des vertices
** initialises avec les premieres valeurs , la fonction de minimisation,
** et le nombre de vtx
**
************************************************************************/
void simplex_gen(void (*function) (/* ??? */), Param_simplex f, Vertex *vtx, int nbv)
{
int t, i, j;
Vertex vtx_ref, vtx_ctr, vtx_exp, vtx_mid;
int dimension = vtx[0].nb_valeur_estimer;
int nb_vertices = nbv;
vtx_ref.nb_valeur_estimer = dimension;
vtx_ref.valeur_estimer = (float *) malloc(vtx_ref.nb_valeur_estimer * sizeof(float));
vtx_ctr.nb_valeur_estimer = dimension;
vtx_ctr.valeur_estimer = (float *) malloc(vtx_ctr.nb_valeur_estimer * sizeof(float));
vtx_exp.nb_valeur_estimer = dimension;
vtx_exp.valeur_estimer = (float *) malloc(vtx_exp.nb_valeur_estimer * sizeof(float));
vtx_mid.nb_valeur_estimer = dimension;
vtx_mid.valeur_estimer = (float *) malloc(vtx_mid.nb_valeur_estimer * sizeof(float));
for (j = 0 ; j < nb_vertices ; j++) (*function)(&vtx[j], f);
for (t = 0 ; t < 100 ; t++) {
/*
for (i = 0 ; i < nb_vertices ; i++)
printf("vtx[%d].r = %10.5f\n", i, vtx[i].r);
*/
/* Ordonner les vertices par resultat croissant ! */
for(i = 0 ; i < nb_vertices ; i++)
for (j = 0 ; j < nb_vertices - i -1; j++)
if (vtx[j].r > vtx[j+1].r) swap_vtx(&vtx[j], &vtx[j+1]);
/*
for (i = 0 ; i < nb_vertices ; i++)
printf("vtx[%d].r = %10.5f\n", i, vtx[i].r);
*/
/* Calcul du point de reflection */
for (j = 0 ; j < dimension ; j++) {
vtx_mid.valeur_estimer[j] = 0;
for (i = 0 ; i < nb_vertices ; i++) vtx_mid.valeur_estimer[j] += vtx[i].valeur_estimer[j];
vtx_mid.valeur_estimer[j] /= nb_vertices;
}
/*
printf("--------- mid vtx ----------\n");
for (i = 0 ; i < vtx[0].nb_valeur_estimer ; i++)
printf("vtx_mid.tab_valeur_estimer[%d] = %10.5f\n", i, vtx_mid.valeur_estimer[i]);
*/
/* Calcul du reflected vertex */
for (j = 0 ; j < dimension ; j++)
vtx_ref.valeur_estimer[j] = 2* vtx_mid.valeur_estimer[j] - vtx[nb_vertices-1].valeur_estimer[j];
(*function)(&vtx_ref, f);
/*
printf("--------- ref vtx ----------\n");
for (i = 0 ; i < vtx[0].nb_valeur_estimer ; i++)
printf("vtx_ref.tab_valeur_estimer[%d] = %10.5f\n", i, vtx_ref.valeur_estimer[i]);
printf("vtx_ref.r = %10.5f\n\n", vtx_ref.r);
*/
/* Si le reflected vertex a donne de meilleurs resultat
a la minimisation que le precedent meilleur */
if (vtx_ref.r < vtx[0].r) {
/* Calcul de l'expanded vertex */
for (j= 0 ; j < dimension ; j++)
vtx_exp.valeur_estimer[j] = 3 * vtx_mid.valeur_estimer[j] - 2 * vtx[nb_vertices-1].valeur_estimer[j];
(*function)(&vtx_exp, f);
/*
printf("--------- exp vtx ----------\n");
for (i = 0 ; i < vtx[0].nb_valeur_estimer ; i++)
printf("vtx_exp.tab_valeur_estimer[%d] = %10.5f\n", i, vtx_exp.valeur_estimer[i]);
printf("vtx_exp.r = %10.5f\n\n", vtx_exp.r);
*/
/* Si le nouveau vertex est meilleur que le reflected */
if (vtx_exp.r < vtx_ref.r) {
/* on place l'expanded vtx a la fin de la liste des vtx */
for (j = 0 ; j < dimension ; j++)
vtx[nb_vertices-1].valeur_estimer[j] = vtx_exp.valeur_estimer[j];
vtx[nb_vertices-1].r = vtx_exp.r;
}
else {
/* On place le ref vtx a la place du dernier vtx */
for (j = 0 ; j < dimension ; j++)
vtx[nb_vertices-1].valeur_estimer[j] = vtx_ref.valeur_estimer[j];
vtx[nb_vertices-1].r = vtx_ref.r;
}
}
/* le ref vtx est moins bon que le premier vtx */
else {
if (vtx_ref.r < vtx[nb_vertices-1].r) {
for (j = 0 ; j < dimension ; j++)
vtx[nb_vertices-1].valeur_estimer[j] = vtx_ref.valeur_estimer[j];
vtx[nb_vertices-1].r = vtx_ref.r;
}
else {
/* Calcul du vertex contracted */
for (j = 0 ; j < dimension ; j++)
vtx_ctr.valeur_estimer[j] = vtx_mid.valeur_estimer[j]/2 + vtx[nb_vertices-1].valeur_estimer[j]/2;
(*function)(&vtx_ctr, f);
/*
printf("--------- ctr vtx ----------\n");
for (i = 0 ; i < vtx[0].nb_valeur_estimer ; i++)
printf("vtx_ctr.tab_valeur_estimer[%d] = %10.5f\n", i, vtx_ctr.valeur_estimer[i]);
printf("vtx_ctr.r = %10.5f\n\n", vtx_ctr.r);
*/
if (vtx_ctr.r < vtx[nb_vertices-1].r) {
for (j = 0 ; j < dimension ; j++)
vtx[nb_vertices-1].valeur_estimer[j] = vtx_ctr.valeur_estimer[j];
vtx[nb_vertices-1].r = vtx_ctr.r;
}
else {
/* contracter tous les vertices sauf le meilleur (le premier !) */
for (i = 1; i < nb_vertices; i++) {
for (j = 0 ; j < dimension ; j++)
vtx[i].valeur_estimer[j] = (vtx[i].valeur_estimer[j] - vtx[0].valeur_estimer[j]) / 2;
}
}
}
}
}
free(vtx_ref.valeur_estimer);
free(vtx_ctr.valeur_estimer);
free(vtx_exp.valeur_estimer);
free(vtx_mid.valeur_estimer);
}
/***** Pour OTSU entre autre ****/
/********************************************************************/
/*!
** calcul de omega
**
** \param prob : distribution de proba.
** \param k1,k2 : \f$omega =\sum_{k1\le i \le k2}(prob[i]) \f$
** \retval omega
**
********************************************************************/
double calc_omega(double *prob, int k1, int k2)
{
int i;
double omega;
omega=0.0;
for(i=k1;i<=k2;i++)
omega+=prob[i];
return(omega);
}
/*******************************************
** -- ynist() ----------------------------
**
** Initialisation de l'histogramme (reso)
********************************************/
float ynist(float aminh, float amaxh, long int Nbpas)
{
float reso;
if (Nbpas<=0) return(0.0);
reso=(float) (amaxh-aminh)/(Nbpas);
return(reso);
}
/*******************************************
** -- ystog() ----------------------------
**
** Calcul du tableau ibuf pour l'histogramme
**
**
** Nbpas : Nombre max de points dans le tableau ibuf
**
********************************************/
int ystog(float *ibuf, long int Nbpas, float aminh, float reso, float valeur, float duree)
{
int i,NbpasM1;
NbpasM1=Nbpas-1;
i=(int)floor((valeur-aminh)/reso);
i=MINI(NbpasM1,MAXI(0,i));
ibuf[i]=ibuf[i]+duree;
return(1);
}
/********************************************************************/
/*!
** calcul de mu
**
** \param prob : distribution de proba.
** \param k1,k2 : \f$mu =(\sum_{k1\le i \le k2}(i*prob[i]))/omega \f$
** \retval mu
**
********************************************************************/
double calc_mu(double *prob, int k1, int k2)
{
int i;
double mu;
double omega;
mu=0.0;
omega=0.0;
omega=calc_omega(prob,k1,k2);
for(i=k1;i<=k2;i++)
mu+=(double)i*prob[i];
if(omega!=0.0)
mu/=omega;
else
mu=0.0;
return(mu);
}
/*-------------------- get_gaussian ---------------------*/
/*----------------------------------------------------------------------*/
/* Calculate a vectorial Gaussian mask with a standard deviation of sigma. */
/* Cut off when tails reach 1% of the maximum value. */
void get_gaussian(float s, float *y, int *len)
{
int r,i;
float gaussian_r;
r=1;
gaussian_r=1;
*len=0;
y[*len]=gaussian_r;
while(gaussian_r >= 0.01){
gaussian_r=(float)exp((double)(-0.5*(r*r)/(s*s)));
if (gaussian_r>=0.01){
for (i=*len;i>=0;i--) y[i+1]=y[i];
i=*len;
y[i+2]=gaussian_r;
y[0]=gaussian_r;
r=r+1;
*len=i+2;
}/*end if*/
}/*end while*/
}/*end get_gaussian*/
/*-------------------- get_derigaussian ---------------------*/
/*----------------------------------------------------------------------*/
/* Calculate a vectorial derivate of a Gaussian mask with a standar deviation */
/* of sigma. Cut off when tails reach 1% of the maximum value.*/
void get_derigaussian(float s, float *y, int *len)
{
int r,i/*,j*/;
float deriv_gaussian_r;
float max_val;
r=1;
max_val=0;
*len=0;
deriv_gaussian_r=max_val;
y[*len]=deriv_gaussian_r;
while (deriv_gaussian_r>=0.01*max_val){
deriv_gaussian_r=(float)(r/((s*s))*exp((double)(-0.5*(r*r)/(s*s))));
for(i=*len;i>=0;i--) y[i+1]=y[i];
i=*len;
y[i+2]= (- deriv_gaussian_r);
y[0]=deriv_gaussian_r;
r+=1;
*len=i+2;
if (deriv_gaussian_r > max_val) max_val=deriv_gaussian_r;
}/*end while*/
/* top = max_val;*/
}/*end get_derigaussian*/
| 26.100058 | 148 | 0.519977 | [
"vector",
"transform"
] |
02f11b70366b7fe414b4ee83a9b1f83d0c9fb336 | 2,159 | c | C | nitan/kungfu/skill/jinshe-jian/bak/suo.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | 1 | 2019-03-27T07:25:16.000Z | 2019-03-27T07:25:16.000Z | nitan/kungfu/skill/jinshe-jian/bak/suo.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | nitan/kungfu/skill/jinshe-jian/bak/suo.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | // This program is a part of NITAN MudLIB
// suo.c 鎖劍訣
#include <ansi.h>
inherit F_SSERVER;
int perform(object me)
{
string msg;
object weapon, weapon2, target;
int skill, ap, dp, damage;
if( !objectp(weapon=query_temp("weapon", me) )
|| query("id", weapon) != "jinshejian" )
return notify_fail("你沒用金蛇劍,不能使用絕招!\n");
if( query("dex", me)<20 || query("str", me)<20 )
return notify_fail("你的先天膂力身法孱弱, 不能使用「鎖劍訣」!\n");
me->clean_up_enemy();
target = me->select_opponent();
skill = me->query_skill("jinshe-jian", 1);
if( !(me->is_fighting() ))
return notify_fail("「鎖劍訣」只能對戰鬥中的對手使用。\n");
if( !objectp(weapon2=query_temp("weapon", target)) )
return notify_fail("對方沒有使用兵器,你用不了「鎖劍訣」。\n");
if( skill < 150)
return notify_fail("你的金蛇劍法等級不夠, 不能使用「鎖劍訣」!\n");
if( query("neili", me)<300 )
return notify_fail("你的內力不夠,無法運用「鎖劍訣」!\n");
msg = HIC "$N手中"YEL"金蛇劍"HIC"畫出一道金光,斜刺一拉,「鎖劍訣」!\n"
YEL "金蛇劍"HIC"劍尖倒鈎正好掛在$n的"+weapon2->name()+"上。\n";
message_combatd(msg, me, target);
damage = 100 + random(skill / 2);
ap=me->query_skill("sword")*3/2+query("level", me)*20+
me->query_skill("martial-cognize", 1);
dp=target->query_skill("parry")+query("level", target)*20+
target->query_skill("martial-cognize", 1);
if (ap / 2 + random(ap) > dp)
{
addn("neili", -50, me);
msg = "$n頓時覺得眼前金光一閃,手腕一振,手中";
msg += weapon2->name();
msg += "脱手飛出!\n" NOR;
me->start_busy(random(2));
target->receive_damage("qi", damage);
target->start_busy(2);
weapon2->move(environment(me));
}
else
{
addn("neili", -30, me);
msg = "$n急運內力,將手中" + weapon2->name()+ "斜斜順勢一送一搭,抽了回來。\n"NOR;
me->start_busy(3);
}
message_combatd(msg, me, target);
return 1;
} | 30.842857 | 76 | 0.496989 | [
"object"
] |
02f4f37a14f5bb2a03e1fcb8e1b5de5643241098 | 15,653 | c | C | src/body.c | stetre/moonchipmunk | 017d305dea7d1c76a20ccfa9435489c10df0bab3 | [
"MIT"
] | 11 | 2020-04-05T02:29:56.000Z | 2022-01-29T18:24:44.000Z | src/body.c | stetre/moonchipmunk | 017d305dea7d1c76a20ccfa9435489c10df0bab3 | [
"MIT"
] | 1 | 2022-03-27T22:17:43.000Z | 2022-03-27T22:42:34.000Z | src/body.c | stetre/moonchipmunk | 017d305dea7d1c76a20ccfa9435489c10df0bab3 | [
"MIT"
] | null | null | null | /* The MIT License (MIT)
*
* Copyright (c) 2020 Stefano Trettel
*
* Software repository: MoonChipmunk, https://github.com/stetre/moonchipmunk
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "internal.h"
static void removeconstraint(body_t *body, constraint_t *constraint, void *data)
{ cpSpaceRemoveConstraint((space_t*)data, constraint); (void)body; }
static void removeshape(body_t *body, shape_t *shape, void *data)
{ cpSpaceRemoveShape((space_t*)data, shape); (void)body; }
int freebody(lua_State *L, ud_t *ud)
{
space_t *space;
body_t *body = (body_t*)ud->handle;
if(!IsValid(ud)) return 0;
space = cpBodyGetSpace(body);
if(space && cpSpaceIsLocked(space)) return 0; /* leave it to post step */
// freechildren(L, _MT, ud);
if(!freeuserdata(L, ud, "body")) return 0;
if(!IsBorrowed(ud))
{
if(space)
{
if(cpSpaceIsLocked(space)) return failure(L, ERR_OPERATION);
/* Remove from the space all shapes and constraints connected to the body,
* and the body itself. */
cpBodyEachConstraint(body, removeconstraint, space);
cpBodyEachShape(body, removeshape, space);
cpSpaceRemoveBody(space, body);
}
cpBodyFree(body);
}
return 0;
}
int newbody(lua_State *L, body_t *body, int borrowed)
{
ud_t *ud;
ud = newuserdata(L, body, BODY_MT, "body");
ud->parent_ud = NULL;
ud->destructor = freebody;
if(borrowed) MarkBorrowed(ud);
return 1;
}
static int Create(lua_State *L)
{
double mass = luaL_checknumber(L, 1);
double moment = luaL_checknumber(L, 2);
body_t *body = cpBodyNew(mass, moment);
return newbody(L, body, 0);
}
static int CreateKinematic(lua_State *L)
{
body_t *body = cpBodyNewKinematic();
return newbody(L, body, 0);
}
static int CreateStatic(lua_State *L)
{
body_t *body = cpBodyNewStatic();
return newbody(L, body, 0);
}
#define F(Func, func) /* void func(body, double) */ \
static int Func(lua_State *L) \
{ \
body_t *body = checkbody(L, 1, NULL); \
double val = luaL_checknumber(L, 2); \
func(body, val); \
return 0; \
}
F(SetMass, cpBodySetMass)
F(SetMoment, cpBodySetMoment)
F(SetAngle, cpBodySetAngle)
F(SetAngularVelocity, cpBodySetAngularVelocity)
F(SetTorque, cpBodySetTorque)
F(UpdatePosition, cpBodyUpdatePosition)
#undef F
#define F(Func, func) /* double func(body) */ \
static int Func(lua_State *L) \
{ \
body_t *body = checkbody(L, 1, NULL); \
double val = func(body); \
lua_pushnumber(L, val); \
return 1; \
}
F(GetMass, cpBodyGetMass)
F(GetMoment, cpBodyGetMoment)
F(GetAngle, cpBodyGetAngle)
F(GetAngularVelocity, cpBodyGetAngularVelocity)
F(GetTorque, cpBodyGetTorque)
F(KineticEnergy, cpBodyKineticEnergy)
#undef F
static int IsSleeping(lua_State *L)
{
body_t *body = checkbody(L, 1, NULL);
int val = cpBodyIsSleeping(body);
lua_pushboolean(L, val);
return 1;
}
static int GetIdleTime(lua_State *L)
{
body_t *body = checkbody(L, 1, NULL);
lua_pushnumber(L, body->sleeping.idleTime);
return 1;
}
#define F(Func, func) /* void func(body, vec_t) */ \
static int Func(lua_State *L) \
{ \
vec_t val; \
body_t *body = checkbody(L, 1, NULL); \
checkvec(L, 2, &val); \
func(body, val); \
return 0; \
}
F(SetPosition, cpBodySetPosition)
F(SetCenterOfGravity, cpBodySetCenterOfGravity)
F(SetVelocity, cpBodySetVelocity)
F(SetForce, cpBodySetForce)
#undef F
#define F(Func, func) /* vec_t func(body) */ \
static int Func(lua_State *L) \
{ \
body_t *body = checkbody(L, 1, NULL); \
vec_t val = func(body); \
pushvec(L, &val); \
return 1; \
}
F(GetPosition, cpBodyGetPosition)
F(GetCenterOfGravity, cpBodyGetCenterOfGravity)
F(GetVelocity, cpBodyGetVelocity)
F(GetForce, cpBodyGetForce)
F(GetRotation, cpBodyGetRotation)
#undef F
#define F(Func, func) /* void func(body, vec_t, vec_t) */\
static int Func(lua_State *L) \
{ \
vec_t val1, val2; \
body_t *body = checkbody(L, 1, NULL); \
checkvec(L, 2, &val1); \
checkvec(L, 3, &val2); \
func(body, val1, val2); \
return 0; \
}
F(ApplyForceAtWorldPoint, cpBodyApplyForceAtWorldPoint)
F(ApplyForceAtLocalPoint, cpBodyApplyForceAtLocalPoint)
F(ApplyImpulseAtWorldPoint, cpBodyApplyImpulseAtWorldPoint)
F(ApplyImpulseAtLocalPoint, cpBodyApplyImpulseAtLocalPoint)
#undef F
#define F(Func, func) /* vec_t func(body, vec_t) */ \
static int Func(lua_State *L) \
{ \
vec_t val, res; \
body_t *body = checkbody(L, 1, NULL); \
checkvec(L, 2, &val); \
res = func(body, val); \
pushvec(L, &res); \
return 1; \
}
F(LocalToWorld, cpBodyLocalToWorld)
F(WorldToLocal, cpBodyWorldToLocal)
F(GetVelocityAtWorldPoint, cpBodyGetVelocityAtWorldPoint)
F(GetVelocityAtLocalPoint, cpBodyGetVelocityAtLocalPoint)
#undef F
static int Sleeep(lua_State *L)
{
body_t *body = checkbody(L, 1, NULL);
cpBodySleep(body);
return 0;
}
static int SleepWithGroup(lua_State *L)
{
body_t *body = checkbody(L, 1, NULL);
body_t *group = optbody(L, 2, NULL);
cpBodySleepWithGroup(body, group);
return 0;
}
static int Activate(lua_State *L)
{
body_t *body = checkbody(L, 1, NULL);
cpBodyActivate(body);
return 0;
}
static int ActivateStatic(lua_State *L)
{
body_t *body = checkbody(L, 1, NULL);
shape_t *filter = optshape(L, 2, NULL);
cpBodyActivateStatic(body, filter);
return 0;
}
static int GetSpace(lua_State *L)
{
body_t *body = checkbody(L, 1, NULL);
space_t * space = cpBodyGetSpace(body);
if(!space) lua_pushnil(L);
else pushspace(L, space);
return 1;
}
static int SetType(lua_State *L)
{
body_t *body = checkbody(L, 1, NULL);
cpBodyType type = checkbodytype(L, 2);
cpBodySetType(body, type);
return 0;
}
static int GetType(lua_State *L)
{
body_t *body = checkbody(L, 1, NULL);
cpBodyType type = cpBodyGetType(body);
pushbodytype(L, type);
return 1;
}
static int UpdateVelocity(lua_State *L)
{
vec_t gravity;
double damping, dt;
body_t *body = checkbody(L, 1, NULL);
checkvec(L, 2, &gravity);
damping = luaL_checknumber(L, 3);
dt = luaL_checknumber(L, 4);
cpBodyUpdateVelocity(body, gravity, damping, dt);
return 0;
}
#define F(Func, What, what) \
static void IteratorFunc##What(body_t *body, what##_t *what, void *data) \
{ \
lua_State *L = moonchipmunk_L; \
int top = lua_gettop(L); \
lua_pushvalue(L, 2); /* the function */ \
pushbody(L, body); \
push##what(L, what); \
(void)data; \
if(lua_pcall(L, 2, 0, 0) != LUA_OK) \
{ lua_error(L); return; } \
lua_settop(L, top); \
} \
static int Func(lua_State *L) \
{ \
body_t *body = checkbody(L, 1, NULL); \
if(!lua_isfunction(L, 2)) return argerror(L, 2, ERR_FUNCTION); \
cpBodyEach##What(body, IteratorFunc##What, NULL); \
return 0; \
}
F(EachShape, Shape, shape)
F(EachConstraint, Constraint, constraint)
#undef F
static void IteratorFuncArbiter(body_t *body, arbiter_t *arbiter, void *data)
{
lua_State *L = moonchipmunk_L;
int top = lua_gettop(L);
lua_pushvalue(L, 2); /* the function */
pushbody(L, body);
pusharbiter(L, arbiter);
(void)data;
if(lua_pcall(L, 2, 0, 0) != LUA_OK)
{ invalidatearbiter(L, arbiter); lua_error(L); return; }
invalidatearbiter(L, arbiter);
lua_settop(L, top);
}
static int EachArbiter(lua_State *L)
{
body_t *body = checkbody(L, 1, NULL);
if(!lua_isfunction(L, 2)) return argerror(L, 2, ERR_FUNCTION);
cpBodyEachArbiter(body, IteratorFuncArbiter, NULL);
return 0;
}
static void BodyVelocityFunc(body_t *body, vec_t gravity, double damping, double dt)
{
int rc;
lua_State *L = moonchipmunk_L;
ud_t *ud = userdata(body);
int top = lua_gettop(L);
lua_rawgeti(L, LUA_REGISTRYINDEX, ud->ref1);
pushbody(L, body);
pushvec(L, &gravity);
lua_pushnumber(L, damping);
lua_pushnumber(L, dt);
rc = lua_pcall(L, 4, 0, 0);
if(rc!=LUA_OK) lua_error(L);
lua_settop(L, top);
}
static int SetVelocityUpdateFunc(lua_State *L)
{
ud_t *ud;
body_t *body = checkbody(L, 1, &ud);
if(lua_isnoneornil(L, 2))
{
Unreference(L, ud->ref1);
cpBodySetVelocityUpdateFunc(body, cpBodyUpdateVelocity);
return 0;
}
if(!lua_isfunction(L, 2)) return argerror(L, 2, ERR_FUNCTION);
Reference(L, 2, ud->ref1);
cpBodySetVelocityUpdateFunc(body, BodyVelocityFunc);
return 0;
}
static void BodyPositionFunc(body_t *body, double dt)
{
int rc;
lua_State *L = moonchipmunk_L;
ud_t *ud = userdata(body);
int top = lua_gettop(L);
lua_rawgeti(L, LUA_REGISTRYINDEX, ud->ref2);
pushbody(L, body);
lua_pushnumber(L, dt);
rc = lua_pcall(L, 2, 0, 0);
if(rc!=LUA_OK) lua_error(L);
lua_settop(L, top);
}
static int SetPositionUpdateFunc(lua_State *L)
{
ud_t *ud;
body_t *body = checkbody(L, 1, &ud);
if(lua_isnoneornil(L, 2))
{
Unreference(L, ud->ref2);
cpBodySetPositionUpdateFunc(body, cpBodyUpdatePosition);
return 0;
}
if(!lua_isfunction(L, 2)) return argerror(L, 2, ERR_FUNCTION);
Reference(L, 2, ud->ref2);
cpBodySetPositionUpdateFunc(body, BodyPositionFunc);
return 0;
}
RAW_FUNC(body)
PARENT_FUNC(body)
DESTROY_FUNC(body)
static const struct luaL_Reg Methods[] =
{
{ "raw", Raw },
{ "parent", Parent },
{ "free", Destroy },
{ "set_mass", SetMass },
{ "set_moment", SetMoment },
{ "set_angle", SetAngle },
{ "set_angular_velocity", SetAngularVelocity },
{ "set_torque", SetTorque },
{ "update_position", UpdatePosition },
{ "get_mass", GetMass },
{ "get_moment", GetMoment },
{ "get_angle", GetAngle },
{ "get_angular_velocity", GetAngularVelocity },
{ "get_torque", GetTorque },
{ "kinetic_energy", KineticEnergy },
{ "is_sleeping", IsSleeping },
{ "get_idle_time", GetIdleTime },
{ "set_position", SetPosition },
{ "set_center_of_gravity", SetCenterOfGravity },
{ "set_velocity", SetVelocity },
{ "set_force", SetForce },
{ "get_position", GetPosition },
{ "get_center_of_gravity", GetCenterOfGravity },
{ "get_velocity", GetVelocity },
{ "get_force", GetForce },
{ "get_rotation", GetRotation },
{ "apply_force_at_world_point", ApplyForceAtWorldPoint },
{ "apply_force_at_local_point", ApplyForceAtLocalPoint },
{ "apply_impulse_at_world_point", ApplyImpulseAtWorldPoint },
{ "apply_impulse_at_local_point", ApplyImpulseAtLocalPoint },
{ "local_to_world", LocalToWorld },
{ "world_to_local", WorldToLocal },
{ "get_velocity_at_world_point", GetVelocityAtWorldPoint },
{ "get_velocity_at_local_point", GetVelocityAtLocalPoint },
{ "sleep", Sleeep },
{ "sleep_with_group", SleepWithGroup },
{ "activate", Activate },
{ "activate_static", ActivateStatic },
{ "get_space", GetSpace },
{ "set_type", SetType },
{ "get_type", GetType },
{ "update_velocity", UpdateVelocity },
{ "each_shape", EachShape },
{ "each_constraint", EachConstraint },
{ "each_arbiter", EachArbiter },
{ "set_velocity_update_func", SetVelocityUpdateFunc },
{ "set_position_update_func", SetPositionUpdateFunc },
{ NULL, NULL } /* sentinel */
};
static const struct luaL_Reg MetaMethods[] =
{
{ "__gc", Destroy },
{ NULL, NULL } /* sentinel */
};
static const struct luaL_Reg Functions[] =
{
{ "body_new", Create },
{ "body_new_kinematic", CreateKinematic },
{ "body_new_static", CreateStatic },
{ NULL, NULL } /* sentinel */
};
void moonchipmunk_open_body(lua_State *L)
{
udata_define(L, BODY_MT, Methods, MetaMethods);
luaL_setfuncs(L, Functions, 0);
}
#if 0
// void cpBodySetUserData(body_t *body, cpDataPointer userData);
// cpDataPointer cpBodyGetUserData(const body_t *body);
#endif
| 34.554084 | 86 | 0.551204 | [
"shape"
] |
02fb4c9c14beb3464ed8da3d7f3ed9773bbdf36c | 25,933 | c | C | src/ss_render_d3d9.c | snake5/sgs-sdl | b25bbcc06488bc847665c90458b477eca12e0f69 | [
"MIT"
] | 4 | 2017-08-29T11:13:41.000Z | 2019-12-19T18:02:26.000Z | src/ss_render_d3d9.c | snake5/sgs-sdl | b25bbcc06488bc847665c90458b477eca12e0f69 | [
"MIT"
] | null | null | null | src/ss_render_d3d9.c | snake5/sgs-sdl | b25bbcc06488bc847665c90458b477eca12e0f69 | [
"MIT"
] | 2 | 2020-07-02T11:22:28.000Z | 2021-05-29T21:33:45.000Z |
#include <d3d9.h>
#define D3DCALL( x, m ) (x)->lpVtbl->m( (x) )
#define D3DCALL_( x, m, ... ) (x)->lpVtbl->m( (x), __VA_ARGS__ )
#define SAFE_RELEASE( x ) if( x ){ D3DCALL( x, Release ); x = NULL; }
#include <SDL_syswm.h>
#define SS_TEXTURE_HANDLE_DATA IDirect3DBaseTexture9* base; IDirect3DTexture9* tex2d;
#define SS_TEXRSURF_HANDLE_DATA IDirect3DSurface9* surf;
#define SS_VERTEXFORMAT_HANDLE_DATA IDirect3DVertexDeclaration9* vdecl;
#define SS_RENDERER_OVERRIDE
#include "ss_main.h"
typedef IDirect3D9* WINAPI (*pfnDirect3DCreate9) (UINT SDKVersion);
static void* GD3D9_DLL = NULL;
static IDirect3D9* GD3D = NULL;
static void _ss_reset_states( IDirect3DDevice9* dev, int w, int h )
{
IDirect3DDevice9_SetTextureStageState( dev, 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
IDirect3DDevice9_SetTextureStageState( dev, 0, D3DTSS_ALPHAOP, D3DTOP_MODULATE );
IDirect3DDevice9_SetTextureStageState( dev, 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
IDirect3DDevice9_SetTextureStageState( dev, 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
IDirect3DDevice9_SetRenderState( dev, D3DRS_LIGHTING, 0 );
IDirect3DDevice9_SetRenderState( dev, D3DRS_CULLMODE, D3DCULL_NONE );
IDirect3DDevice9_SetRenderState( dev, D3DRS_ZENABLE, 0 );
IDirect3DDevice9_SetRenderState( dev, D3DRS_ALPHABLENDENABLE, 1 );
IDirect3DDevice9_SetRenderState( dev, D3DRS_SEPARATEALPHABLENDENABLE, 1 );
IDirect3DDevice9_SetRenderState( dev, D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
IDirect3DDevice9_SetRenderState( dev, D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
{
float wm[ 16 ] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };
float vm[ 16 ] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 100, 0, 0, 0, 1 };
float pm[ 16 ] = { 2.0f/(float)w, 0, 0, 0, 0, 2.0f/(float)h, 0, 0, 0, 0, 1.0f/999.0f, 1.0f/-999.0f, 0, 0, 0, 1 };
IDirect3DDevice9_SetTransform( dev, D3DTS_WORLD, (D3DMATRIX*) wm );
IDirect3DDevice9_SetTransform( dev, D3DTS_VIEW, (D3DMATRIX*) vm );
IDirect3DDevice9_SetTransform( dev, D3DTS_PROJECTION, (D3DMATRIX*) pm );
}
}
struct _SS_Renderer
{
SS_RENDERER_DATA
IDirect3DDevice9* d3ddev;
D3DPRESENT_PARAMETERS d3dpp;
IDirect3DSurface9* backbuf;
IDirect3DSurface9* dssurf;
SS_Texture* cur_rtt;
int width;
int height;
int bbwidth, bbheight, bbscale;
};
static void ss_ri_d3d9__resetviewport( SS_Renderer* R )
{
D3DVIEWPORT9 vp = { 0, 0, -1, -1, 0.0, 1.0 };
if( R->bbscale != SS_POSMODE_NONE )
{
vp.Width = SGS_MIN( R->bbwidth, R->width );
vp.Height = SGS_MIN( R->bbheight, R->height );
}
else
{
vp.Width = R->width;
vp.Height = R->height;
}
IDirect3DDevice9_SetViewport( R->d3ddev, &vp );
}
static void ss_ri_d3d9_init();
static void ss_ri_d3d9_free();
static int ss_ri_d3d9_available();
static SS_Renderer* ss_ri_d3d9_create( SDL_Window* window, uint32_t flags );
static void ss_ri_d3d9_destroy( SS_Renderer* R );
static void* ss_ri_d3d9_get_pointer( SS_Renderer* R, int which );
static void ss_ri_d3d9_modify( SS_Renderer* R, int* modlist );
static void ss_ri_d3d9_set_buffer_scale( SS_Renderer* R, int enable, int width, int height, int scalemode );
static void ss_ri_d3d9_set_current( SS_Renderer* R );
static void ss_ri_d3d9_poke_resource( SS_Renderer* R, sgs_VarObj* obj, int add );
static void ss_ri_d3d9_swap( SS_Renderer* R );
static void ss_ri_d3d9_clear( SS_Renderer* R, float* col4f );
static void ss_ri_d3d9_set_render_state( SS_Renderer* R, int which, int arg0, int arg1, int arg2, int arg3 );
static void ss_ri_d3d9_set_matrix( SS_Renderer* R, int which, float* data );
static void ss_ri_d3d9_set_rt( SS_Renderer* R, SS_Texture* T );
static int ss_ri_d3d9_create_texture_argb8( SS_Renderer* R, SS_Texture* T, SS_Image* I, uint32_t flags );
static int ss_ri_d3d9_create_texture_a8( SS_Renderer* R, SS_Texture* T, uint8_t* data, int width, int height, int pitch );
static int ss_ri_d3d9_create_texture_rnd( SS_Renderer* R, SS_Texture* T, int width, int height, uint32_t flags );
static int ss_ri_d3d9_destroy_texture( SS_Renderer* R, SS_Texture* T );
static int ss_ri_d3d9_apply_texture( SS_Renderer* R, SS_Texture* T );
static int ss_ri_d3d9_init_vertex_format( SS_Renderer* R, SS_VertexFormat* F );
static int ss_ri_d3d9_free_vertex_format( SS_Renderer* R, SS_VertexFormat* F );
static int ss_ri_d3d9_draw_basic_vertices( SS_Renderer* R, void* data, uint32_t count, int ptype );
static int ss_ri_d3d9_draw_ext( SS_Renderer* R, SS_VertexFormat* F, void* vdata, uint32_t vdsize, void* idata, uint32_t idsize, int i32, uint32_t start, uint32_t count, int ptype );
SS_RenderInterface GRI_D3D9 =
{
ss_ri_d3d9_init,
ss_ri_d3d9_free,
ss_ri_d3d9_available,
ss_ri_d3d9_create,
ss_ri_d3d9_destroy,
ss_ri_d3d9_get_pointer,
ss_ri_d3d9_modify,
ss_ri_d3d9_set_buffer_scale,
ss_ri_d3d9_set_current,
ss_ri_d3d9_poke_resource,
ss_ri_d3d9_swap,
ss_ri_d3d9_clear,
ss_ri_d3d9_set_render_state,
ss_ri_d3d9_set_matrix,
ss_ri_d3d9_set_rt,
ss_ri_d3d9_create_texture_argb8,
ss_ri_d3d9_create_texture_a8,
ss_ri_d3d9_create_texture_rnd,
ss_ri_d3d9_destroy_texture,
ss_ri_d3d9_apply_texture,
ss_ri_d3d9_init_vertex_format,
ss_ri_d3d9_free_vertex_format,
ss_ri_d3d9_draw_basic_vertices,
ss_ri_d3d9_draw_ext,
/* flags */
SS_RI_HALFPIXELOFFSET | SS_RI_COLOR_BGRA,
/* API */
"D3D9",
/* last error */
"no error",
};
static int _ssr_reset_device( SS_Renderer* R )
{
SGS_CTX = ss_GetContext();
D3DPRESENT_PARAMETERS npp;
SDL_Event event;
int i;
event.type = SDL_VIDEODEVICELOST;
ss_CreateSDLEvent( C, &event );
sgs_GlobalCall( C, "on_event", 1, 0 );
SAFE_RELEASE( R->backbuf );
SAFE_RELEASE( R->dssurf );
/* free all renderable textures */
for( i = 0; i < R->rsrc_table.size; ++i )
{
sgs_VarObj* obj = (sgs_VarObj*) R->rsrc_table.vars[ i ].val.data.P;
if( obj->iface == SS_Texture_iface )
{
SS_Texture* T = (SS_Texture*) obj->data;
if( T->flags & SS_TEXTURE_RENDER )
{
SAFE_RELEASE( T->rsh.surf );
SAFE_RELEASE( T->handle.tex2d );
}
}
}
/* reset */
npp = R->d3dpp;
if( FAILED( IDirect3DDevice9_Reset( R->d3ddev, &npp ) ) )
{
GRI_D3D9.last_error = "failed to reset the device";
goto fail;
}
_ss_reset_states( R->d3ddev, R->d3dpp.BackBufferWidth, R->d3dpp.BackBufferHeight );
R->cur_rtt = NULL;
/* --- */
if( FAILED( D3DCALL_( R->d3ddev, GetRenderTarget, 0, &R->backbuf ) ) )
{
GRI_D3D9.last_error = "failed to retrieve original backbuffer";
goto fail;
}
if( FAILED( D3DCALL_( R->d3ddev, GetDepthStencilSurface, &R->dssurf ) ) )
{
GRI_D3D9.last_error = "failed to retrieve original depth stencil surface";
goto fail;
}
/* recreate all renderable textures */
for( i = 0; i < R->rsrc_table.size; ++i )
{
sgs_VarObj* obj = (sgs_VarObj*) R->rsrc_table.vars[ i ].val.data.P;
if( obj->iface == SS_Texture_iface )
{
SS_Texture* T = (SS_Texture*) obj->data;
if( T->flags & SS_TEXTURE_RENDER )
{
HRESULT hr = IDirect3DDevice9_CreateTexture( R->d3ddev, T->width, T->height, 1,
D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &T->handle.tex2d, NULL );
if( T->handle.tex2d == NULL || FAILED(hr) )
{
R->iface->last_error = "could not create renderable texture";
goto fail;
}
hr = D3DCALL_( T->handle.tex2d, GetSurfaceLevel, 0, &T->rsh.surf );
if( T->rsh.surf == NULL || FAILED(hr) )
{
R->iface->last_error = "failed to retrieve render surface";
goto fail;
}
}
}
}
event.type = SDL_VIDEODEVICERESET;
ss_CreateSDLEvent( C, &event );
sgs_GlobalCall( C, "on_event", 1, 0 );
return 1;
fail:
return sgs_Msg( C, SGS_ERROR, GRI_D3D9.last_error );
}
static void ss_ri_d3d9_init()
{
GD3D9_DLL = SDL_LoadObject( "d3d9.dll" );
if( GD3D9_DLL )
{
pfnDirect3DCreate9 func = (pfnDirect3DCreate9) SDL_LoadFunction( GD3D9_DLL, "Direct3DCreate9" );
if( func )
GD3D = func( D3D_SDK_VERSION );
}
}
static void ss_ri_d3d9_free()
{
if( GD3D )
IDirect3DResource9_Release( GD3D );
if( GD3D9_DLL )
SDL_UnloadObject( GD3D9_DLL );
}
static int ss_ri_d3d9_available()
{
return !!GD3D;
}
static SS_Renderer* ss_ri_d3d9_create( SDL_Window* window, uint32_t flags )
{
int w, h, suc;
SDL_SysWMinfo sysinfo;
D3DPRESENT_PARAMETERS d3dpp;
IDirect3DDevice9* d3ddev;
SS_Renderer* R;
SGS_CTX = ss_GetContext();
SDL_GetWindowSize( window, &w, &h );
SDL_VERSION( &sysinfo.version );
if( SDL_GetWindowWMInfo( window, &sysinfo ) <= 0 )
{
GRI_D3D9.last_error = SDL_GetError();
return NULL;
}
ZeroMemory( &d3dpp, sizeof(d3dpp) );
d3dpp.Windowed = 1;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.EnableAutoDepthStencil = 1;
d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
d3dpp.hDeviceWindow = sysinfo.info.win.window;
d3dpp.BackBufferWidth = w;
d3dpp.BackBufferHeight = h;
d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE;
d3dpp.PresentationInterval = ( flags & SS_RENDERER_VSYNC ) ? D3DPRESENT_INTERVAL_ONE : D3DPRESENT_INTERVAL_IMMEDIATE;
suc = !FAILED( IDirect3D9_CreateDevice( GD3D,
D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, sysinfo.info.win.window,
D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_FPU_PRESERVE, &d3dpp, &d3ddev ) );
if( !suc )
{
GRI_D3D9.last_error = "failed to create the device";
return NULL;
}
_ss_reset_states( d3ddev, w, h );
R = (SS_Renderer*) malloc( sizeof(*R) );
R->iface = &GRI_D3D9;
R->window = window;
R->d3ddev = d3ddev;
R->d3dpp = d3dpp;
if( FAILED( D3DCALL_( R->d3ddev, GetRenderTarget, 0, &R->backbuf ) ) )
{
GRI_D3D9.last_error = "failed to retrieve original backbuffer";
return NULL;
}
if( FAILED( D3DCALL_( R->d3ddev, GetDepthStencilSurface, &R->dssurf ) ) )
{
GRI_D3D9.last_error = "failed to retrieve original depth stencil surface";
return NULL;
}
R->width = w;
R->height = h;
R->cur_rtt = NULL;
R->bbwidth = 0;
R->bbheight = 0;
R->bbscale = 0;
sgs_vht_init( &R->rsrc_table, C, 64, 64 );
R->destructing = 0;
sgs_CreateDict( C, &R->textures, 0 );
sgs_CreateDict( C, &R->fonts, 0 );
sgs_CreateDict( C, &R->rsdict, 0 );
sgs_PushString( C, "textures" );
sgs_SetIndex( C, R->rsdict, sgs_StackItem( C, -1 ), R->textures, 0 );
sgs_Pop( C, 1 );
sgs_PushString( C, "fonts" );
sgs_SetIndex( C, R->rsdict, sgs_StackItem( C, -1 ), R->fonts, 0 );
sgs_Pop( C, 1 );
IDirect3DDevice9_BeginScene( R->d3ddev );
return R;
}
static void ss_ri_d3d9_destroy( SS_Renderer* R )
{
int i;
SGS_CTX = ss_GetContext();
sgs_Release( C, &R->rsdict );
R->destructing = 1;
for( i = 0; i < R->rsrc_table.size; ++i )
{
sgs_VarObj* obj = (sgs_VarObj*) R->rsrc_table.vars[ i ].val.data.P;
sgs_ObjCallDtor( C, obj );
}
sgs_vht_free( &R->rsrc_table, C );
if( GCurRr == R )
{
GCurRr = NULL;
GCurRI = NULL;
}
SAFE_RELEASE( R->backbuf );
SAFE_RELEASE( R->dssurf );
IDirect3DResource9_Release( R->d3ddev );
free( R );
}
static void* ss_ri_d3d9_get_pointer( SS_Renderer* R, int which )
{
if( which == 0 ) return R->d3ddev;
return NULL;
}
static void ss_ri_d3d9_modify( SS_Renderer* R, int* modlist )
{
int w, h;
int resize = 0;
SDL_GetWindowSize( R->window, &w, &h );
while( *modlist )
{
if( *modlist == SS_RMOD_WIDTH ){ resize = 1; w = modlist[1]; R->width = w; }
else if( *modlist == SS_RMOD_HEIGHT ){ resize = 1; h = modlist[1]; R->height = h; }
modlist += 2;
}
if( resize )
{
R->d3dpp.BackBufferWidth = w;
R->d3dpp.BackBufferHeight = h;
_ssr_reset_device( R );
ss_ri_d3d9__resetviewport( R );
IDirect3DDevice9_BeginScene( R->d3ddev );
}
}
static void ss_ri_d3d9_set_buffer_scale( SS_Renderer* R, int enable, int width, int height, int scalemode )
{
R->bbwidth = enable ? width : 0;
R->bbheight = enable ? height : 0;
R->bbscale = enable ? scalemode : 0;
}
static void ss_ri_d3d9_set_current( SS_Renderer* R )
{
SGS_CTX = ss_GetContext();
sgs_SetGlobalByName( C, "_RND", R->rsdict );
}
static void ss_ri_d3d9_poke_resource( SS_Renderer* R, sgs_VarObj* obj, int add )
{
SGS_CTX = ss_GetContext();
sgs_Variable K = sgs_MakePtr( obj );
if( R->destructing )
return;
if( add )
sgs_vht_set( &R->rsrc_table, C, &K, &K );
else
sgs_vht_unset( &R->rsrc_table, C, &K );
}
static void ss_ri_d3d9_swap( SS_Renderer* R )
{
ss_ri_d3d9_set_rt( R, NULL );
IDirect3DDevice9_EndScene( R->d3ddev );
if( R->bbscale != SS_POSMODE_NONE )
{
int w = SGS_MIN( R->bbwidth, R->width );
int h = SGS_MIN( R->bbheight, R->height );
IDirect3DSurface9 *plain = NULL, *target = NULL;
if( !FAILED( IDirect3DDevice9_CreateOffscreenPlainSurface( R->d3ddev, R->width, R->height, D3DFMT_X8R8G8B8, D3DPOOL_SYSTEMMEM, &plain, NULL ) ) && plain &&
!FAILED( IDirect3DDevice9_CreateRenderTarget( R->d3ddev, w, h, D3DFMT_X8R8G8B8, D3DMULTISAMPLE_NONE, 0, 0, &target, NULL ) ) && target )
{
RECT srcrect = { 0, 0, w, h };
if( !FAILED( IDirect3DDevice9_GetRenderTargetData( R->d3ddev, R->backbuf, plain ) ) &&
!FAILED( IDirect3DDevice9_UpdateSurface( R->d3ddev, plain, &srcrect, target, NULL ) ) )
{
/* width factors */
float wf = 1, hf = 1, xoff, yoff;
float aspect = ( (float) w / (float) h ) / ( (float) R->width / (float) R->height );
switch( R->bbscale )
{
case SS_POSMODE_CROP:
if( aspect > 1 )
wf = aspect;
else
hf = 1 / aspect;
break;
case SS_POSMODE_FIT:
if( aspect > 1 )
hf = 1 / aspect;
else
wf = aspect;
break;
case SS_POSMODE_FITRND:
{
int wc = (int) floor( (float) R->width / (float) w );
int hc = (int) floor( (float) R->height / (float) h );
int cnt = SGS_MAX( 1, SGS_MIN( wc, hc ) );
wf = (float) w * cnt / (float) R->width;
hf = (float) h * cnt / (float) R->height;
}
break;
case SS_POSMODE_CENTER:
wf = (float) w / (float) R->width;
hf = (float) h / (float) R->height;
break;
default:
break;
}
xoff = ( 1 - wf ) / 2;
yoff = ( 1 - hf ) / 2;
{
D3DVIEWPORT9 fullvp = { 0, 0, R->width, R->height, -1, 1 };
RECT dstrect = { xoff * R->width, yoff * R->height, (xoff+wf) * R->width, (yoff+hf) * R->height };
IDirect3DDevice9_SetViewport( R->d3ddev, &fullvp );
IDirect3DDevice9_Clear( R->d3ddev, 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0, 1.0f, 0 );
IDirect3DDevice9_StretchRect( R->d3ddev, target, &srcrect, R->backbuf, &dstrect, D3DTEXF_POINT );
}
}
}
SAFE_RELEASE( plain );
SAFE_RELEASE( target );
}
if( IDirect3DDevice9_Present( R->d3ddev, NULL, NULL, NULL, NULL ) == D3DERR_DEVICELOST )
{
if( IDirect3DDevice9_TestCooperativeLevel( R->d3ddev ) == D3DERR_DEVICENOTRESET )
{
_ssr_reset_device( R );
}
}
IDirect3DDevice9_BeginScene( R->d3ddev );
ss_ri_d3d9_set_rt( R, NULL );
}
static void ss_ri_d3d9_clear( SS_Renderer* R, float* col4f )
{
uint32_t cc = 0;
uint32_t flags = 0;
if( col4f )
{
cc = (((uint8_t)(col4f[3]*255))<<24) | (((uint8_t)(col4f[0]*255))<<16) |
(((uint8_t)(col4f[1]*255))<<8) | (((uint8_t)(col4f[2]*255)));
flags = D3DCLEAR_TARGET;
}
if( !R->cur_rtt )
flags |= D3DCLEAR_ZBUFFER;
IDirect3DDevice9_Clear( R->d3ddev, 0, NULL, flags, cc, 1.0f, 0 );
}
static void ss_ri_d3d9_set_render_state( SS_Renderer* R, int which, int arg0, int arg1, int arg2, int arg3 )
{
if( which == SS_RS_BLENDFACTORS )
{
static const int blendfactors[] =
{
D3DBLEND_ZERO,
D3DBLEND_ONE,
D3DBLEND_SRCCOLOR,
D3DBLEND_INVSRCCOLOR,
D3DBLEND_SRCALPHA,
D3DBLEND_INVSRCALPHA,
D3DBLEND_DESTCOLOR,
D3DBLEND_INVDESTCOLOR,
D3DBLEND_DESTALPHA,
D3DBLEND_INVDESTALPHA,
D3DBLEND_SRCALPHASAT,
};
if( arg0 < 0 || arg0 >= SS_BLEND__COUNT ) arg0 = SS_BLEND_SRCALPHA;
if( arg1 < 0 || arg1 >= SS_BLEND__COUNT ) arg1 = SS_BLEND_INVSRCALPHA;
if( arg2 < 0 || arg2 >= SS_BLEND__COUNT ) arg2 = SS_BLEND_ONE;
if( arg3 < 0 || arg3 >= SS_BLEND__COUNT ) arg3 = SS_BLEND_ZERO;
IDirect3DDevice9_SetRenderState( R->d3ddev, D3DRS_SRCBLEND, blendfactors[ arg0 ] );
IDirect3DDevice9_SetRenderState( R->d3ddev, D3DRS_DESTBLEND, blendfactors[ arg1 ] );
IDirect3DDevice9_SetRenderState( R->d3ddev, D3DRS_SRCBLENDALPHA, blendfactors[ arg2 ] );
IDirect3DDevice9_SetRenderState( R->d3ddev, D3DRS_DESTBLENDALPHA, blendfactors[ arg3 ] );
}
else if( which == SS_RS_BLENDOP )
{
static const int blendfuncs[] =
{
D3DBLENDOP_ADD, D3DBLENDOP_SUBTRACT, D3DBLENDOP_REVSUBTRACT, D3DBLENDOP_MIN, D3DBLENDOP_MAX,
};
if( arg0 < 0 || arg0 >= SS_BLENDOP__COUNT ) arg0 = SS_BLENDOP_ADD;
IDirect3DDevice9_SetRenderState( R->d3ddev, D3DRS_BLENDOP, blendfuncs[ arg0 ] );
}
else if( which == SS_RS_CLIPENABLE )
{
IDirect3DDevice9_SetRenderState( R->d3ddev, D3DRS_SCISSORTESTENABLE, arg0 ? 1 : 0 );
}
else if( which == SS_RS_CLIPRECT )
{
/* x0 = arg0, y0 = arg1, x1 = arg2, y1 = arg3 */
RECT rect = { arg0, arg1, arg2, arg3 };
IDirect3DDevice9_SetScissorRect( R->d3ddev, &rect );
}
else if( which == SS_RS_VIEWPORT )
{
/* x0 = arg0, y0 = arg1, x1 = arg2, y1 = arg3 */
D3DVIEWPORT9 vp = { arg0, arg1, arg2 - arg0, arg3 - arg1, 0.0, 1.0 };
IDirect3DDevice9_SetViewport( R->d3ddev, &vp );
}
else if( which == SS_RS_CULLING )
{
IDirect3DDevice9_SetRenderState( R->d3ddev, D3DRS_CULLMODE, arg0 ? ( arg0 > 0 ? D3DCULL_CCW : D3DCULL_CW ) : D3DCULL_NONE );
}
else if( which == SS_RS_ZENABLE )
{
IDirect3DDevice9_SetRenderState( R->d3ddev, D3DRS_ZENABLE, arg0 );
}
}
static void ss_ri_d3d9_set_matrix( SS_Renderer* R, int which, float* mtx )
{
if( which == SS_RMAT_WORLD )
IDirect3DDevice9_SetTransform( R->d3ddev, D3DTS_WORLD, (D3DMATRIX*) mtx );
else if( which == SS_RMAT_VIEW )
IDirect3DDevice9_SetTransform( R->d3ddev, D3DTS_VIEW, (D3DMATRIX*) mtx );
else if( which == SS_RMAT_PROJ )
{
/* this solves the d3d9 texel->pixel mapping issue */
float w = R->bbwidth ? R->bbwidth : R->width;
float h = R->bbheight ? R->bbheight : R->height;
float mox[ 16 ];
if( w || h )
{
float mfx[ 16 ] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, w ? -1.0f / w : 0, h ? 1.0f / h : 0, 0, 1 };
SS_Mat4Multiply( (float(*)[4])mtx, (float(*)[4])mfx, (float(*)[4])mox );
}
else
memcpy( mox, mtx, sizeof(mox) );
IDirect3DDevice9_SetTransform( R->d3ddev, D3DTS_PROJECTION, (D3DMATRIX*) mox );
}
}
static void ss_ri_d3d9_set_rt( SS_Renderer* R, SS_Texture* T )
{
IDirect3DSurface9* surf = T ? T->rsh.surf : R->backbuf;
IDirect3DSurface9* dssurf = T ? NULL : R->dssurf;
R->cur_rtt = T;
D3DCALL_( R->d3ddev, SetRenderTarget, 0, surf );
D3DCALL_( R->d3ddev, SetDepthStencilSurface, dssurf );
if( !T )
ss_ri_d3d9__resetviewport( R );
}
static int ss_ri_d3d9_create_texture_argb8( SS_Renderer* R, SS_Texture* T, SS_Image* I, uint32_t flags )
{
HRESULT hr;
SGS_CTX = ss_GetContext();
int miplev = 1, i, y;
SS_Image* pdI = I, *pI;
IDirect3DTexture9* tex = NULL;
if( flags & SS_TEXTURE_MIPMAPS )
{
int sz = I->width > I->height ? I->width : I->height;
while( sz > 1 )
{
sz /= 2;
miplev++;
}
}
hr = IDirect3DDevice9_CreateTexture( R->d3ddev, I->width, I->height,
miplev, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &tex, NULL );
if( tex == NULL || FAILED(hr) )
return 0;
for( i = 0; i < miplev; ++i )
{
pI = pdI;
D3DLOCKED_RECT lr;
IDirect3DTexture9_LockRect( tex, i, &lr, NULL, D3DLOCK_DISCARD );
for( y = 0; y < pdI->height; ++y )
memcpy( ((uint8_t*)lr.pBits) + lr.Pitch * y, ((uint8_t*)pdI->data) + pdI->width * 4 * y, pdI->width * 4 );
IDirect3DTexture9_UnlockRect( tex, i );
if( i < miplev-1 )
pdI = ss_ImageDS2X( pdI, C );
if( pI != I )
ss_DeleteImage( pI, C );
}
T->renderer = R;
T->width = I->width;
T->height = I->height;
T->flags = flags;
T->handle.tex2d = tex;
return 1;
}
static int ss_ri_d3d9_create_texture_a8( SS_Renderer* R, SS_Texture* T, uint8_t* data, int width, int height, int pitch )
{
int x, y;
HRESULT hr;
D3DLOCKED_RECT lr;
IDirect3DTexture9* tex = NULL;
hr = IDirect3DDevice9_CreateTexture( R->d3ddev, width,
height, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &tex, NULL );
if( tex == NULL || FAILED(hr) )
return 0;
IDirect3DTexture9_LockRect( tex, 0, &lr, NULL, D3DLOCK_DISCARD );
for( y = 0; y < height; ++y )
{
for( x = 0; x < width; ++x )
{
int off = y * lr.Pitch + x * 4;
((uint8_t*)lr.pBits)[ off ] = 0xff;
((uint8_t*)lr.pBits)[ off + 1 ] = 0xff;
((uint8_t*)lr.pBits)[ off + 2 ] = 0xff;
((uint8_t*)lr.pBits)[ off + 3 ] = data[ x ];
}
data += pitch;
}
IDirect3DTexture9_UnlockRect( tex, 0 );
T->renderer = R;
T->width = width;
T->height = height;
T->flags = 0;
T->handle.tex2d = tex;
return 1;
}
static int ss_ri_d3d9_create_texture_rnd( SS_Renderer* R, SS_Texture* T, int width, int height, uint32_t flags )
{
HRESULT hr;
IDirect3DTexture9* tex = NULL;
hr = IDirect3DDevice9_CreateTexture( R->d3ddev, width,
height, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &tex, NULL );
if( tex == NULL || FAILED(hr) )
{
R->iface->last_error = "could not create renderable texture";
return 0;
}
hr = D3DCALL_( tex, GetSurfaceLevel, 0, &T->rsh.surf );
if( T->rsh.surf == NULL || FAILED(hr) )
{
R->iface->last_error = "failed to retrieve render surface";
return 0;
}
T->renderer = R;
T->width = width;
T->height = height;
T->flags = flags | SS_TEXTURE_RENDER;
T->handle.tex2d = tex;
return 1;
}
static int ss_ri_d3d9_destroy_texture( SS_Renderer* R, SS_Texture* T )
{
if( R->cur_rtt == T )
ss_ri_d3d9_set_rt( R, NULL );
SAFE_RELEASE( T->rsh.surf );
SAFE_RELEASE( T->handle.base );
return 1;
}
static int ss_ri_d3d9_apply_texture( SS_Renderer* R, SS_Texture* T )
{
IDirect3DDevice9_SetTexture( R->d3ddev, 0, T ? T->handle.base : NULL );
if( T )
{
int lin = !( T->flags & SS_TEXTURE_NOLERP );
int mip = ( T->flags & SS_TEXTURE_MIPMAPS );
int hr = ( T->flags & SS_TEXTURE_HREPEAT );
int vr = ( T->flags & SS_TEXTURE_VREPEAT );
IDirect3DDevice9_SetSamplerState( R->d3ddev, 0, D3DSAMP_MINFILTER, lin ? D3DTEXF_LINEAR : D3DTEXF_POINT );
IDirect3DDevice9_SetSamplerState( R->d3ddev, 0, D3DSAMP_MAGFILTER, lin ? D3DTEXF_LINEAR : D3DTEXF_POINT );
IDirect3DDevice9_SetSamplerState( R->d3ddev, 0, D3DSAMP_MIPFILTER, mip ? ( lin ? D3DTEXF_LINEAR : D3DTEXF_POINT ) : D3DTEXF_NONE );
IDirect3DDevice9_SetSamplerState( R->d3ddev, 0, D3DSAMP_ADDRESSU, hr ? D3DTADDRESS_WRAP : D3DTADDRESS_CLAMP );
IDirect3DDevice9_SetSamplerState( R->d3ddev, 0, D3DSAMP_ADDRESSV, vr ? D3DTADDRESS_WRAP : D3DTADDRESS_CLAMP );
}
return 1;
}
static int vd_make_typecount( int type, int count )
{
if( type == SS_RSET_FLOAT && count == 1 ) return D3DDECLTYPE_FLOAT1;
if( type == SS_RSET_FLOAT && count == 2 ) return D3DDECLTYPE_FLOAT2;
if( type == SS_RSET_FLOAT && count == 3 ) return D3DDECLTYPE_FLOAT3;
if( type == SS_RSET_FLOAT && count == 4 ) return D3DDECLTYPE_FLOAT4;
if( type == SS_RSET_BYTE && count == 4 ) return D3DDECLTYPE_D3DCOLOR;
return 0;
}
static int ss_ri_d3d9_init_vertex_format( SS_Renderer* R, SS_VertexFormat* F )
{
HRESULT hr;
D3DVERTEXELEMENT9 els[ 5 ] = { D3DDECL_END(), D3DDECL_END(),
D3DDECL_END(), D3DDECL_END(), D3DDECL_END() };
int i = 0;
if( F->P[0] )
{
D3DVERTEXELEMENT9 el = { 0, F->P[1], vd_make_typecount( F->P[2], F->P[3] ),
D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0 };
memcpy( els + i++, &el, sizeof(D3DVERTEXELEMENT9) );
}
if( F->T[0] )
{
D3DVERTEXELEMENT9 el = { 0, F->T[1], vd_make_typecount( F->T[2], F->T[3] ),
D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0 };
memcpy( els + i++, &el, sizeof(D3DVERTEXELEMENT9) );
}
if( F->C[0] )
{
D3DVERTEXELEMENT9 el = { 0, F->C[1], vd_make_typecount( F->C[2], F->C[3] ),
D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0 };
memcpy( els + i++, &el, sizeof(D3DVERTEXELEMENT9) );
}
if( F->N[0] )
{
D3DVERTEXELEMENT9 el = { 0, F->N[1], vd_make_typecount( F->N[2], F->N[3] ),
D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_NORMAL, 0 };
memcpy( els + i++, &el, sizeof(D3DVERTEXELEMENT9) );
}
F->handle.vdecl = NULL;
hr = IDirect3DDevice9_CreateVertexDeclaration( R->d3ddev, els, &F->handle.vdecl );
if( FAILED( hr ) || !F->handle.vdecl )
{
GRI_D3D9.last_error = "vertex declaration creation failed";
return 0;
}
return 1;
}
static int ss_ri_d3d9_free_vertex_format( SS_Renderer* R, SS_VertexFormat* F )
{
IDirect3DVertexDeclaration9_Release( F->handle.vdecl );
return 1;
}
static const int primtypes[] =
{
D3DPT_POINTLIST,
D3DPT_LINELIST,
D3DPT_LINESTRIP,
D3DPT_TRIANGLELIST,
D3DPT_TRIANGLEFAN,
D3DPT_TRIANGLESTRIP,
-10,
};
static int getprimitivecount( int mode, uint32_t vcount )
{
switch( mode )
{
case SS_PT_POINTS: return vcount;
case SS_PT_LINES: return vcount / 2;
case SS_PT_LINE_STRIP: return vcount - 1;
case SS_PT_TRIANGLES: return vcount / 3;
case SS_PT_TRIANGLE_FAN: return vcount - 2;
case SS_PT_TRIANGLE_STRIP: return vcount - 2;
}
return 0;
}
static int ss_ri_d3d9_draw_basic_vertices( SS_Renderer* R, void* data, uint32_t count, int ptype )
{
int mode;
char* Bptr = (char*) data;
if( ptype < 0 || ptype >= SS_PT__COUNT )
return 0;
mode = primtypes[ ptype ];
IDirect3DDevice9_SetFVF( R->d3ddev, D3DFVF_XYZ | D3DFVF_TEX1 | D3DFVF_DIFFUSE );
IDirect3DDevice9_DrawPrimitiveUP( R->d3ddev, mode,
getprimitivecount( ptype, count ),
Bptr, sizeof(SS_BasicVertex) );
return 1;
}
static int ss_ri_d3d9_draw_ext( SS_Renderer* R, SS_VertexFormat* F, void* vdata, uint32_t vdsize, void* idata, uint32_t idsize, int i32, uint32_t start, uint32_t count, int ptype )
{
int mode;
char* BVptr = (char*) vdata;
char* idcs = (char*) idata;
if( ptype < 0 || ptype >= SS_PT__COUNT )
return 0;
mode = primtypes[ ptype ];
IDirect3DDevice9_SetVertexDeclaration( R->d3ddev, F->handle.vdecl );
if( idcs )
IDirect3DDevice9_DrawIndexedPrimitiveUP( R->d3ddev, mode, 0, count,
getprimitivecount( ptype, count ), idcs + start * 2, D3DFMT_INDEX16,
BVptr, F->size );
else
{
IDirect3DDevice9_DrawPrimitiveUP( R->d3ddev, mode,
getprimitivecount( ptype, count ),
BVptr, F->size );
}
IDirect3DDevice9_SetVertexDeclaration( R->d3ddev, NULL );
return 1;
}
| 29.335973 | 181 | 0.683993 | [
"render"
] |
f31f45bd5f3e0029d164ca3ccb7ca641c0e2326b | 1,747 | c | C | src/spectralfunmode.c | aravindhk/Vides | 65d9ea9764ddf5f6ef40e869bd31387d0e3e378f | [
"BSD-4-Clause"
] | 2 | 2021-11-03T17:24:24.000Z | 2021-12-02T06:06:50.000Z | src/spectralfunmode.c | aravindhk/Vides | 65d9ea9764ddf5f6ef40e869bd31387d0e3e378f | [
"BSD-4-Clause"
] | null | null | null | src/spectralfunmode.c | aravindhk/Vides | 65d9ea9764ddf5f6ef40e869bd31387d0e3e378f | [
"BSD-4-Clause"
] | null | null | null | // ======================================================================
// Copyright (c) 2004-2010, G. Fiori, G. Iannaccone University of Pisa
//
// This file is released under the BSD license.
// See the file "license.txt" for information on usage and
// redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
// ======================================================================
/* ************************************************************** */
/* This subroutine compute the spectral function */
/* given the Green matrix, the gamma function */
/* and the order of the matrices (N),and stores the results */
/* in a double precision vector */
/* ************************************************************** */
#include "spectralfunmode.h"
double *spectralfunmode(complex **G,complex **gamma1,int N,int NReal,int *order)
{
double *SP,g1max,Gmax,**gamma1temp;
complex zero,**Gtemp;
complex **C;
complex **Tr,**TrReal,**GReal,**gamma1Real,**dummy;
int i,j,l;
SP=dvector(0,NReal-1);
zero.r=0;
zero.i=0;
Tr=cmatrix(0,N-1,0,N-1);
for (i=0;i<N;i++)
for (j=0;j<N;j++)
Tr[i][j]=complass(G[j][i].r,-G[j][i].i);
/* // I Anti-Transform G and Gdaga (Tr) and gamma1 */
/* TrReal=VAVdaga(Tr,NReal,N,order); */
/* GReal=VAVdaga(G,NReal,N,order); */
/* gamma1Real=VAVdaga(gamma1,NReal,N,order); */
C=cmatmul3(G,gamma1,Tr,N);
dummy=VAVdaga(C,NReal,N,order);
//I compute Spectralfunction=Diagonal{G*C}/(2*pi)
for (i=0;i<NReal;i++)
{
SP[i]=dummy[i][i].r/(2*pi);
}
cfree_cmatrix(C,0,N-1,0,N-1);
cfree_cmatrix(Tr,0,N-1,0,N-1);
cfree_cmatrix(dummy,0,NReal-1,0,NReal-1);
return SP;
}
| 34.94 | 80 | 0.510017 | [
"vector",
"transform"
] |
f3205207f50cc7e2eb2578a3045825298d6604dd | 9,047 | h | C | Toolbox/Common/UndoManager.h | rokups/Urho3D-Toolbox | 9d0a525e44b5883dbc617b5d29d5fb3640667eae | [
"MIT"
] | 5 | 2017-11-14T23:35:52.000Z | 2020-04-21T03:15:34.000Z | Toolbox/Common/UndoManager.h | rokups/Urho3D-Toolbox | 9d0a525e44b5883dbc617b5d29d5fb3640667eae | [
"MIT"
] | null | null | null | Toolbox/Common/UndoManager.h | rokups/Urho3D-Toolbox | 9d0a525e44b5883dbc617b5d29d5fb3640667eae | [
"MIT"
] | 4 | 2017-11-12T19:43:18.000Z | 2019-08-07T16:24:01.000Z | //
// Copyright (c) 2008-2017 the Urho3D project.
//
// 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 <Urho3D/Core/Object.h>
namespace Urho3D
{
class AttributeInspector;
class Gizmo;
class Scene;
namespace Undo
{
/// Abstract class for implementing various trackable states.
class State : public RefCounted
{
public:
/// Apply state saved in this object.
virtual void Apply() = 0;
/// Return true if state of this object matches state of specified object.
virtual bool Equals(State* other) const = 0;
/// Return string representation of current state.
virtual String ToString() const { return "State"; }
};
/// Tracks attribute values of Serializable item.
class AttributeState : public State
{
public:
/// Construct state consisting of single attribute.
AttributeState(Serializable* item, const String& name, const Variant& value);
/// Apply attributes if they are different and return true if operation was carried out.
void Apply() override;
/// Return true if state of this object matches state of specified object.
bool Equals(State* other) const override;
/// Return string representation of current state.
String ToString() const override;
/// Object that was modified.
SharedPtr<Serializable> item_;
/// Changed attribute name.
String name_;
/// Changed attribute value.
Variant value_;
};
/// Tracks UIElement parent state. Used for tracking adding and removing UIElements.
class ElementParentState : public State
{
public:
/// Construct item from the state and parent
ElementParentState(UIElement* item, UIElement* parent);
/// Set parent of the item if it is different and return true if operation was carried out.
void Apply() override;
/// Return true if state of this object matches state of specified object.
bool Equals(State* other) const override;
/// Return string representation of current state.
String ToString() const override;
/// UIElement whose state is saved.
SharedPtr<UIElement> item_;
/// Parent of item_ at the time when state was saved.
SharedPtr<UIElement> parent_;
/// Position at which item was inserted to parent's children list.
unsigned index_ = M_MAX_UNSIGNED;
};
/// Tracks Node parent state. Used for tracking adding and removing scene nodes.
class NodeParentState : public State
{
public:
/// Construct item from the state and parent
NodeParentState(Node* item, Node* parent);
/// Set parent of the item if it is different and return true if operation was carried out.
void Apply() override;
/// Return true if state of this object matches state of specified object.
bool Equals(State* other) const override;
/// Return string representation of current state.
String ToString() const override;
/// UIElement whose state is saved.
SharedPtr<Node> item_;
/// Parent of item_ at the time when state was saved.
SharedPtr<Node> parent_;
/// Position at which item was inserted to parent's children list.
unsigned index_ = M_MAX_UNSIGNED;
};
/// Tracks Component parent state. Used for tracking adding and removing components.
class ComponentParentState : public State
{
public:
/// Construct item from the state and parent
ComponentParentState(Component* item, Node* parent);
/// Set parent of the item if it is different and return true if operation was carried out.
void Apply() override;
/// Return true if state of this object matches state of specified object.
bool Equals(State* other) const override;
/// Return string representation of current state.
String ToString() const override;
/// UIElement whose state is saved.
SharedPtr<Component> item_;
/// Parent of item_ at the time when state was saved.
SharedPtr<Node> parent_;
/// ID of the component.
unsigned id_;
};
/// Tracks xml parent state. Used for tracking adding and removing xml elements to and from data files.
class XMLVariantState : public State
{
public:
/// Construct item from the state and parent
XMLVariantState(const XMLElement& item, const Variant& value);
/// Set parent of the item if it is different and return true if operation was carried out.
void Apply() override;
/// Return true if state of this object matches state of specified object.
bool Equals(State* other) const override;
/// Return string representation of current state.
String ToString() const override;
/// XMLElement whose state is saved.
XMLElement item_;
/// Value of XMLElement item.
Variant value_;
};
/// Tracks item parent state. Used for tracking adding and removing UIElements.
class XMLParentState : public State
{
public:
/// Construct item from the state and parent.
explicit XMLParentState(const XMLElement& item, const XMLElement& parent=XMLElement());
/// Set parent of the item if it is different and return true if operation was carried out.
void Apply() override;
/// Return true if state of this object matches state of specified object.
bool Equals(State* other) const override;
/// Return string representation of current state.
String ToString() const override;
/// XMLElement whose state is saved.
XMLElement item_;
/// Parent of XMLElement item.
XMLElement parent_;
};
/// A collection of states that are applied together.
class StateCollection
{
public:
/// Set parent of the item if it is different and return true if operation was carried out.
void Apply();
/// Return true if state of this object matches state of specified object.
bool Contains(State* other) const;
/// Append state to the collection if such state does not already exist.
bool PushUnique(const SharedPtr<State>& state);
/// List of states that should be applied together.
Vector<SharedPtr<State>> states_;
};
class Manager : public Object
{
URHO3D_OBJECT(Manager, Object);
public:
/// Construct.
explicit Manager(Context* ctx);
/// Go back in the state history.
void Undo();
/// Go forward in the state history.
void Redo();
/// Clear all tracked state.
void Clear();
/// Track changes performed by this scene.
void Connect(Scene* scene);
/// Track changes performed by this attribute inspector.
void Connect(AttributeInspector* inspector);
/// Track changes performed to UI hierarchy of this root element.
void Connect(UIElement* root);
/// Track changes performed by this gizmo.
void Connect(Gizmo* gizmo);
/// Track item state consisting of single attribute. Old value must be specified manually for tracking. Use when
/// item state has changed already, but old value is known. Use this only when it is not possible to make changes
/// tracked automatically.
void TrackState(Serializable* item, const String& name, const Variant& value, const Variant& oldValue);
/// Tracked XMLElement creation.
XMLElement XMLCreate(XMLElement& parent, const String& name);
/// Tracked XMLElement removal.
void XMLRemove(XMLElement& element);
/// Track XMLElement state.
void XMLSetVariantValue(XMLElement& element, const Variant& value);
protected:
/// Apply state going to specified direction in the state stack.
void ApplyStateFromStack(bool forward);
/// Track object state as old.
template<typename T, typename... Args>
void TrackBefore(Args...);
/// Track object state as new.
template<typename T, typename... Args>
void TrackAfter(Args...);
/// State stack
Vector<StateCollection> stack_;
/// Current state index, -1 when stack is empty.
int32_t index_ = -1;
/// Flag indicating that state tracking is suspended. For example when undo manager is restoring states.
bool trackingSuspended_ = false;
/// List of old object states.
Vector<SharedPtr<State>> previous_;
/// List of new object states.
Vector<SharedPtr<State>> next_;
};
}
}
| 36.62753 | 117 | 0.71626 | [
"object",
"vector"
] |
f32d9827469e42855848a7e1cb8c54d512c1e983 | 824 | h | C | logoscan/scanpix.h | emako/Delogo-Aviutl | 4b38303ea927e3f3e3b45bed6bfcf8135938aca2 | [
"MIT"
] | 1 | 2021-09-15T08:27:13.000Z | 2021-09-15T08:27:13.000Z | logoscan/scanpix.h | emako/Delogo-Aviutl | 4b38303ea927e3f3e3b45bed6bfcf8135938aca2 | [
"MIT"
] | null | null | null | logoscan/scanpix.h | emako/Delogo-Aviutl | 4b38303ea927e3f3e3b45bed6bfcf8135938aca2 | [
"MIT"
] | null | null | null | /*********************************************************************
* 構造体 SCAN_PIXEL
* 各ピクセルのロゴ色・不透明度解析用
*********************************************************************/
#ifndef ___SCANPIX_H
#define ___SCANPIX_H
#include <windows.h>
#include <vector>
#include "filter.h"
#include "logo.h"
#define SCAN_BUFFER_SIZE 1024
typedef struct {
char** compressed_datas;
int compressed_data_n;
int compressed_data_idx;
PIXEL_YC *buffer;
int buffer_idx;
} SCAN_PIXEL;
int AddSample(SCAN_PIXEL *sp, const PIXEL_YC& ycp);
int ClearSample(SCAN_PIXEL *sp);
int GetLGP(LOGO_PIXEL& lgp, const SCAN_PIXEL *sp, const short *lst_bgy, const short *lst_bgcb, const short *lst_bgcr);
int GetAB(double& A, double& B, int data_count, const short *lst_pixel, const short *lst_bg);
#endif
| 25.75 | 119 | 0.59466 | [
"vector"
] |
f336540e64c8e0e7b88c33950b03e05c44d061d5 | 2,573 | h | C | Node.h | dfranx/ShaderExpressionParser | 2f9cb3574732d111b6f3facacc52b3f3d65ab4bc | [
"MIT"
] | 4 | 2020-07-16T02:43:04.000Z | 2020-07-20T01:09:23.000Z | Node.h | sambsp/ShaderExpressionParser | 2f9cb3574732d111b6f3facacc52b3f3d65ab4bc | [
"MIT"
] | 1 | 2021-05-20T14:45:30.000Z | 2021-05-20T14:45:30.000Z | Node.h | sambsp/ShaderExpressionParser | 2f9cb3574732d111b6f3facacc52b3f3d65ab4bc | [
"MIT"
] | 6 | 2020-12-31T07:17:08.000Z | 2022-03-29T08:56:06.000Z | #pragma once
#include <vector>
namespace expr
{
enum class NodeType
{
None,
FloatLiteral,
IntegerLiteral,
BooleanLiteral,
Identifier,
BinaryExpression,
TernaryExpression,
UnaryExpression,
Cast,
FunctionCall,
MethodCall,
MemberAccess,
ArrayAccess
};
enum class ValueType
{
Float,
Float2,
Float3,
Float4,
Float2x2,
Float3x3,
Float4x4,
Float4x3,
Float4x2,
Int,
Int2,
Int3,
Int4,
Uint,
Uint2,
Uint3,
Uint4,
Bool,
Bool2,
Bool3,
Bool4,
};
class Node
{
public:
inline virtual NodeType GetNodeType() { return NodeType::None; }
};
class FloatLiteralNode : public Node
{
public:
inline virtual NodeType GetNodeType() { return NodeType::FloatLiteral; }
float Value;
};
class IntegerLiteralNode : public Node
{
public:
inline virtual NodeType GetNodeType() { return NodeType::IntegerLiteral; }
int Value;
};
class BooleanLiteralNode : public Node
{
public:
inline virtual NodeType GetNodeType() { return NodeType::BooleanLiteral; }
bool Value;
};
class IdentifierNode : public Node
{
public:
inline virtual NodeType GetNodeType() { return NodeType::Identifier; }
char Name[256];
};
class BinaryExpressionNode : public Node
{
public:
inline virtual NodeType GetNodeType() { return NodeType::BinaryExpression; }
int Operator;
Node *Left, *Right;
};
class TernaryExpressionNode : public Node
{
public:
inline virtual NodeType GetNodeType() { return NodeType::TernaryExpression; }
Node* Condition;
Node* OnTrue, * OnFalse;
};
class UnaryExpressionNode : public Node
{
public:
inline virtual NodeType GetNodeType() { return NodeType::UnaryExpression; }
int Operator;
Node* Child;
bool IsPost; // for ++ and --
};
class FunctionCallNode : public Node
{
public:
inline virtual NodeType GetNodeType() { return NodeType::FunctionCall; }
char Name[256];
std::vector<Node*> Arguments;
int TokenType;
};
class ArrayAccessNode : public Node
{
public:
inline virtual NodeType GetNodeType() { return NodeType::ArrayAccess; }
Node* Object;
std::vector<Node*> Indices;
};
class MemberAccessNode : public Node
{
public:
inline virtual NodeType GetNodeType() { return NodeType::MemberAccess; }
Node* Object;
char Field[256];
};
class MethodCallNode : public FunctionCallNode
{
public:
inline virtual NodeType GetNodeType() { return NodeType::MethodCall; }
Node* Object;
};
class CastNode : public Node
{
public:
inline virtual NodeType GetNodeType() { return NodeType::Cast; }
Node* Object;
int Type;
};
} | 19.059259 | 79 | 0.704625 | [
"object",
"vector"
] |
f33a60e88177a286397b7bc437e08240e7fd4894 | 3,049 | h | C | android/android_9/frameworks/native/libs/vr/libpdx/private/pdx/client_channel.h | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | null | null | null | android/android_9/frameworks/native/libs/vr/libpdx/private/pdx/client_channel.h | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | null | null | null | android/android_9/frameworks/native/libs/vr/libpdx/private/pdx/client_channel.h | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | null | null | null | #ifndef ANDROID_PDX_CLIENT_CHANNEL_H_
#define ANDROID_PDX_CLIENT_CHANNEL_H_
#include <vector>
#include <pdx/channel_handle.h>
#include <pdx/channel_parcelable.h>
#include <pdx/file_handle.h>
#include <pdx/status.h>
struct iovec;
namespace android {
namespace pdx {
class ClientChannel {
public:
virtual ~ClientChannel() = default;
// Returns a tag that uniquely identifies a specific underlying IPC transport.
virtual uint32_t GetIpcTag() const = 0;
virtual int event_fd() const = 0;
virtual Status<int> GetEventMask(int events) = 0;
struct EventSource {
int event_fd;
int event_mask;
};
// Returns a set of event-generating fds with and event mask for each. These
// fds are owned by the ClientChannel and must never be closed by the caller.
virtual std::vector<EventSource> GetEventSources() const = 0;
virtual LocalChannelHandle& GetChannelHandle() = 0;
virtual const LocalChannelHandle& GetChannelHandle() const = 0;
virtual void* AllocateTransactionState() = 0;
virtual void FreeTransactionState(void* state) = 0;
virtual Status<void> SendImpulse(int opcode, const void* buffer,
size_t length) = 0;
virtual Status<int> SendWithInt(void* transaction_state, int opcode,
const iovec* send_vector, size_t send_count,
const iovec* receive_vector,
size_t receive_count) = 0;
virtual Status<LocalHandle> SendWithFileHandle(
void* transaction_state, int opcode, const iovec* send_vector,
size_t send_count, const iovec* receive_vector, size_t receive_count) = 0;
virtual Status<LocalChannelHandle> SendWithChannelHandle(
void* transaction_state, int opcode, const iovec* send_vector,
size_t send_count, const iovec* receive_vector, size_t receive_count) = 0;
virtual FileReference PushFileHandle(void* transaction_state,
const LocalHandle& handle) = 0;
virtual FileReference PushFileHandle(void* transaction_state,
const BorrowedHandle& handle) = 0;
virtual ChannelReference PushChannelHandle(
void* transaction_state, const LocalChannelHandle& handle) = 0;
virtual ChannelReference PushChannelHandle(
void* transaction_state, const BorrowedChannelHandle& handle) = 0;
virtual bool GetFileHandle(void* transaction_state, FileReference ref,
LocalHandle* handle) const = 0;
virtual bool GetChannelHandle(void* transaction_state, ChannelReference ref,
LocalChannelHandle* handle) const = 0;
// Returns the internal state of the channel as a parcelable object. The
// ClientChannel is invalidated however, the channel is kept alive by the
// parcelable object and may be transferred to another process.
virtual std::unique_ptr<ChannelParcelable> TakeChannelParcelable() = 0;
};
} // namespace pdx
} // namespace android
#endif // ANDROID_PDX_CLIENT_CHANNEL_H_
| 39.597403 | 80 | 0.699574 | [
"object",
"vector"
] |
f3466da2788fb0058f5b2808d9fd23db5dfcc3d5 | 34,829 | h | C | BLE.h | drony/ESP32-BLECollector | 2b150cbf10b3802e50ea91aaaa4b3156600e1478 | [
"MIT"
] | 1 | 2019-03-01T10:53:18.000Z | 2019-03-01T10:53:18.000Z | BLE.h | drony/ESP32-BLECollector | 2b150cbf10b3802e50ea91aaaa4b3156600e1478 | [
"MIT"
] | null | null | null | BLE.h | drony/ESP32-BLECollector | 2b150cbf10b3802e50ea91aaaa4b3156600e1478 | [
"MIT"
] | null | null | null | /*
ESP32 BLE Collector - A BLE scanner with sqlite data persistence on the SD Card
Source: https://github.com/tobozo/ESP32-BLECollector
MIT License
Copyright (c) 2018 tobozo
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.
-----------------------------------------------------------------------------
*/
#define TICKS_TO_DELAY 1000
#if SKETCH_MODE==SKETCH_MODE_BUILD_NTP_UPDATER
class BLEScanUtils {
public:
void init() {
UI.init();
};
void scan() { };
};
#else
const char* processTemplateLong = "%s%d%s%d";
const char* processTemplateShort = "%s%d";
static char processMessage[20];
static bool onScanProcessed = true;
static bool onScanPopulated = true;
static bool onScanPropagated = true;
static bool onScanPostPopulated = true;
static bool onScanRendered = true;
static bool onScanDone = true;
static bool scanTaskRunning = false;
static bool scanTaskStopped = true;
static char* serialBuffer = NULL;
static char* tempBuffer = NULL;
#define SERIAL_BUFFER_SIZE 48
unsigned long lastheap = 0;
uint16_t lastscanduration = SCAN_DURATION;
char heapsign[5]; // unicode sign terminated
char scantimesign[5]; // unicode sign terminated
BLEScanResults bleresults;
BLEScan *pBLEScan;
BLEClient *pClient;
BLEAddress *pClientAddress = (BLEAddress*)calloc(1, sizeof(BLEAddress));
char* charBleAddress = (char*)calloc(17, sizeof(char));
std::string stdBLEAddress;
esp_ble_addr_type_t pClientType;
static uint16_t processedDevicesCount = 0;
bool foundDeviceToggler = true;
enum AfterScanSteps {
POPULATE = 0,
IFEXISTS = 1,
RENDER = 2,
PROPAGATE = 3
};
static BLEUUID timeServiceUUID((uint16_t)0x1805);
static BLEUUID timeCharacteristicUUID((uint16_t)0x2a2b);
typedef struct {
uint16_t year;
uint8_t month;
uint8_t day;
uint8_t hour;
uint8_t minutes;
uint8_t seconds;
uint8_t wday;
uint8_t fraction;
uint8_t adjust = 0;
} bt_time_t;
bt_time_t BLERemoteTime;// = calloc(0, sizeof(bt_time_t));
static void setBLETime() {
DateTime UTCTime = DateTime(BLERemoteTime.year, BLERemoteTime.month, BLERemoteTime.day, BLERemoteTime.hour, BLERemoteTime.minutes, BLERemoteTime.seconds);
DateTime LocalTime = UTCTime.unixtime() + timeZone*3600;
dumpTime("UTC:", UTCTime);
dumpTime("Local:", LocalTime);
setTime( LocalTime.unixtime() );
Serial.printf("[Heap: %06d] Time has been set to: %04d-%02d-%02d %02d:%02d:%02d\n",
freeheap,
LocalTime.year(),
LocalTime.month(),
LocalTime.day(),
LocalTime.hour(),
LocalTime.minute(),
LocalTime.second()
);
#if HAS_EXTERNAL_RTC
RTC.adjust(LocalTime);
#endif
logTimeActivity(SOURCE_BLE, LocalTime.unixtime() );
lastSyncDateTime = LocalTime;
HasBTTime = true;
DayChangeTrigger = true;
TimeIsSet = true;
timeHousekeeping();
}
static void TimeClientNotifyCallback( BLERemoteCharacteristic* pBLERemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify ) {
//pBLERemoteCharacteristic->getHandle();
memcpy( &BLERemoteTime, pData, length );
setBLETime();
};
static void BaseNotifyCallback(BLERemoteCharacteristic* pRemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify) {
Serial.printf("notifyCallback: %s %s handle: %02x value:", pRemoteCharacteristic->getRemoteService()->getClient()->getPeerAddress().toString().c_str(), pRemoteCharacteristic->getUUID().toString().c_str(), pRemoteCharacteristic->getHandle());
for(int i=0; i<length; i++)
Serial.printf(" %02x", pData[i]);
Serial.println();
}
class TimeClientCallback : public BLEClientCallbacks {
void onConnect(BLEClient* pC){
log_e("[Heap: %06d] Connect!!", freeheap);
}
void onDisconnect(BLEClient* pC) {
if( !HasBTTime ) {
foundTimeServer = false;
log_e("[Heap: %06d] Disconnect without time!!", freeheap);
// oh that's dirty
ESP.restart();
} else {
foundTimeServer = true;
log_e("[Heap: %06d] Disconnect with time!!", freeheap);
}
}
};
class FoundDeviceCallback: public BLEAdvertisedDeviceCallbacks {
void onResult(BLEAdvertisedDevice advertisedDevice) {
// TODO: add security
if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService( timeServiceUUID )) {
stdBLEAddress = advertisedDevice.getAddress().toString();
pClientType = advertisedDevice.getAddressType();
foundTimeServer = true;
if( foundTimeServer && (!TimeIsSet || ForceBleTime) ) {
scan_cursor = 0;
processedDevicesCount = 0;
onScanDone = true;
//ForceBleTime = false;
advertisedDevice.getScan()->stop();
// log_e("[Heap: %06d] Found TimeServer !!", freeheap);
return;
}
}
if( onScanDone ) return;
if( scan_cursor < MAX_DEVICES_PER_SCAN ) {
BLEDevHelper.store( BLEDevScanCache[scan_cursor], advertisedDevice );
//bool is_random = strcmp( BLEDevScanCache[scan_cursor]->ouiname, "[random]" ) == 0;
bool is_random = (BLEDevScanCache[scan_cursor]->addr_type == BLE_ADDR_TYPE_RANDOM || BLEDevScanCache[scan_cursor]->addr_type == BLE_ADDR_TYPE_RPA_RANDOM );
if( UI.filterVendors && is_random ) {
//TODO: scan_cursor++
log_w( "Filtering %s", BLEDevScanCache[scan_cursor]->address );
} else {
if( DB.hasPsram ) {
if( !is_random ) {
DB.getOUI( BLEDevScanCache[scan_cursor]->address, BLEDevScanCache[scan_cursor]->ouiname );
}
if( BLEDevScanCache[scan_cursor]->manufid > -1 ) {
DB.getVendor( BLEDevScanCache[scan_cursor]->manufid, BLEDevScanCache[scan_cursor]->manufname );
}
BLEDevScanCache[scan_cursor]->is_anonymous = BLEDevHelper.isAnonymous( BLEDevScanCache[scan_cursor] );
log_i( " stored and populated #%02d : %s", scan_cursor, advertisedDevice.toString().c_str());
} else {
log_i( " stored #%02d : %s", scan_cursor, advertisedDevice.toString().c_str());
}
scan_cursor++;
processedDevicesCount++;
}
if( scan_cursor == MAX_DEVICES_PER_SCAN ) {
onScanDone = true;
}
} else {
onScanDone = true;
}
if( onScanDone ) {
advertisedDevice.getScan()->stop();
scan_cursor = 0;
if( SCAN_DURATION-1 >= MIN_SCAN_DURATION ) {
SCAN_DURATION--;
}
}
foundDeviceToggler = !foundDeviceToggler;
if(foundDeviceToggler) {
UI.BLEStateIconSetColor(BLE_GREEN);
} else {
UI.BLEStateIconSetColor(BLE_DARKGREEN);
}
}
};
auto pDeviceCallback = new FoundDeviceCallback(); // collect/store BLE data
auto pTimeClientCallback = new TimeClientCallback();
struct SerialCallback {
SerialCallback(void (*f)(void *) = 0, void *d = 0)
: function(f), data(d) {}
void (*function)(void *);
void *data;
};
struct CommandTpl {
const char* command;
SerialCallback cb;
const char* description;
};
CommandTpl* SerialCommands;
uint16_t Csize = 0;
struct ToggleTpl {
const char *name;
bool &flag;
};
ToggleTpl* TogglableProps;
uint16_t Tsize = 0;
class BLEScanUtils {
public:
void init() {
BLEDevice::init("");
BLEDevice::setMTU(100);
pClient = BLEDevice::createClient();
pClient->setClientCallbacks( pTimeClientCallback );
UI.init(); // launch all UI tasks
DB.init(); // mount DB
WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector
getPrefs();
startScanCB();
startSerialTask();
}
static void startScanCB( void * param = NULL ) {
if( !scanTaskRunning ) {
log_d("Starting scan" );
xTaskCreatePinnedToCore(scanTask, "scanTask", 10000, NULL, 5, NULL, 1); /* last = Task Core */
while(scanTaskStopped) {
log_d("Waiting for scan to start...");
vTaskDelay(1000);
}
Serial.println("Scan started...");
}
}
static void stopScanCB( void * param = NULL) {
if( scanTaskRunning ) {
log_d("Stopping scan" );
scanTaskRunning = false;
BLEDevice::getScan()->stop();
while(!scanTaskStopped) {
log_d("Waiting for scan to stop...");
vTaskDelay(1000);
}
Serial.println("Scan stopped...");
}
}
static void restartCB( void * param = NULL ) {
DBneedsReplication = true;
DB.needsRestart = true;
stopScanCB();
}
#ifdef NEEDS_SDUPDATER
static void updateCB( void * param = NULL ) {
stopScanCB();
xTaskCreatePinnedToCore(loadNTPMenu, "loadNTPMenu", 16000, NULL, 5, NULL, 1); /* last = Task Core */
}
static void loadNTPMenu( void * param = NULL ) {
rollBackOrUpdateFromFS( BLE_FS, NTP_MENU_FILENAME );
ESP.restart();
}
#endif
static void resetCB( void * param = NULL ) {
DB.needsReset = true;
Serial.println("DB Scheduled for reset");
stopScanCB();
delay(100);
//startScanCB();
}
static void pruneCB( void * param = NULL ) {
DB.needsPruning = true;
Serial.println("DB Scheduled for pruning");
stopScanCB();
delay(1);
startScanCB();
}
static void toggleFilterCB( void * param = NULL ) {
UI.filterVendors = ! UI.filterVendors;
setPrefs();
Serial.printf("UI.filterVendors = %s\n", UI.filterVendors ? "true" : "false" );
}
static void startDumpCB( void * param = NULL ) {
DBneedsReplication = true;
bool scanWasRunning = scanTaskRunning;
if( scanTaskRunning ) stopScanCB();
while( DBneedsReplication ) {
delay(1000);
}
if( scanWasRunning ) startScanCB();
}
static void toggleEchoCB( void * param = NULL ) {
Out.serialEcho = !Out.serialEcho;
setPrefs();
Serial.printf("Out.serialEcho = %s\n", Out.serialEcho ? "true" : "false" );
}
static void rmFileCB( void * param = NULL ) {
xTaskCreatePinnedToCore(rmFileTask, "rmFileTask", 5000, param, 2, NULL, 1); /* last = Task Core */
}
static void rmFileTask( void * param = NULL ) {
// YOLO style
if( param != NULL ) {
if( BLE_FS.remove( (const char*)param ) ) {
Serial.printf("File %s deleted\n", param);
} else {
Serial.printf("File %s could not be deleted\n", param);
}
} else {
Serial.println("Nothing to delete");
}
vTaskDelete( NULL );
}
static void screenShowCB( void * param = NULL ) {
xTaskCreate(screenShowTask, "screenShowTask", 16000, param, 2, NULL);
}
static void screenShowTask( void * param = NULL ) {
UI.screenShow( param );
vTaskDelete(NULL);
}
static void screenShotCB( void * param = NULL ) {
xTaskCreate(screenShotTask, "screenShotTask", 16000, NULL, 2, NULL);
}
static void screenShotTask( void * param = NULL ) {
UI.screenShot();
vTaskDelete(NULL);
}
static void listDirCB( void * param = NULL ) {
xTaskCreatePinnedToCore(listDirTask, "listDirTask", 5000, NULL, 2, NULL, 1); /* last = Task Core */
}
static void listDirTask( void * param = NULL ) {
listDir(BLE_FS, "/", 0, DB.BLEMacsDbFSPath);
vTaskDelete( NULL );
}
static void toggleCB( void * param = NULL ) {
bool setbool = true;
if( param != NULL ) {
//
} else {
setbool = false;
Serial.println("\nCurrent property values:");
}
for( uint16_t i=0; i<Tsize; i++ ) {
if( setbool ) {
if( strcmp( TogglableProps[i].name, (const char*)param )==0 ) {
TogglableProps[i].flag = !TogglableProps[i].flag;
Serial.printf("Toggled flag %s to %s\n", TogglableProps[i].name, TogglableProps[i].flag ? "true" : "false");
}
} else {
Serial.printf(" %24s : [%s]\n", TogglableProps[i].name, TogglableProps[i].flag ? "true" : "false");
}
}
}
static void nullCB( void * param = NULL ) {
if( param != NULL ) {
Serial.printf("nullCB param: %s\n", param);
}
// zilch, niente, nada, que dalle, nothing
}
static void startSerialTask() {
serialBuffer = (char*)calloc( SERIAL_BUFFER_SIZE, sizeof(char) );
tempBuffer = (char*)calloc( SERIAL_BUFFER_SIZE, sizeof(char) );
xTaskCreatePinnedToCore(serialTask, "serialTask", 2048, NULL, 0, NULL, 0); /* last = Task Core */
}
static void serialTask( void * parameter ) {
CommandTpl Commands[] = {
{ "help", nullCB, "Print this list" },
{ "start", startScanCB, "Start/resume scan" },
{ "stop", stopScanCB, "Stop scan" },
{ "toggleFilter", toggleFilterCB, "Toggle vendor filter (persistent)" },
{ "toggleEcho", toggleEchoCB, "Toggle BLECards in serial console (persistent)" },
{ "dump", startDumpCB, "Dump returning BLE devices to the display and updates DB" },
{ "ls", listDirCB, "Show the SD root dir Content" },
{ "rm", rmFileCB, "Delete a file from the SD" },
{ "restart", restartCB, "Restart BLECollector" },
{ "bletime", startTimeClient,"Get time from another BLE Device" },
{ "screenshot", screenShotCB, "Make a screenshot and save it on the SD" },
{ "screenshow", screenShowCB, "Show a screenshot" },
{ "toggle", toggleCB, "toggle a bool value" },
#if HAS_GPS
{ "gpstime", setGPSTime, "sync time from GPS" },
#endif
#ifdef NEEDS_SDUPDATER
{ "update", updateCB, "Update time and DB files (requires pre-flashed NTPMenu.bin on the SD)" },
#endif
{ "resetDB", resetCB, "Hard Reset DB + forced restart" },
{ "pruneDB", pruneCB, "Soft Reset DB without restarting (hopefully)" },
};
SerialCommands = Commands;
Csize = (sizeof(Commands) / sizeof(Commands[0]));
ToggleTpl ToggleProps[] = {
{ "Out.serialEcho", Out.serialEcho },
{ "DB.needsReset", DB.needsReset },
{ "DBneedsReplication", DBneedsReplication },
{ "DB.needsPruning", DB.needsPruning },
{ "TimeIsSet", TimeIsSet },
{ "foundTimeServer", foundTimeServer },
{ "RTCisRunning", RTCisRunning },
{ "ForceBleTime", ForceBleTime },
{ "DayChangeTrigger", DayChangeTrigger },
{ "HourChangeTrigger", HourChangeTrigger }
};
TogglableProps = ToggleProps;
Tsize = (sizeof(ToggleProps) / sizeof(ToggleProps[0]));
if (resetReason != 12) { // HW Reset
runCommand( (char*)"help" );
runCommand( (char*)"toggle" );
runCommand( (char*)"ls" );
}
#if HAS_GPS
GPSInit();
#endif
static byte idx = 0;
char lf = '\n';
char cr = '\r';
char c;
while( 1 ) {
while (Serial.available() > 0) {
c = Serial.read();
if (c != cr && c!=lf) {
serialBuffer[idx] = c;
idx++;
if (idx >= SERIAL_BUFFER_SIZE) {
idx = SERIAL_BUFFER_SIZE - 1;
}
} else {
serialBuffer[idx] = '\0'; // null terminate
memcpy( tempBuffer, serialBuffer, idx+1 );
runCommand( tempBuffer );
idx = 0;
}
delay(1);
}
#if HAS_GPS
GPSRead();
#endif
delay(1);
}
}
static void runCommand( char* command ) {
if( isEmpty( command ) ) return;
if( strcmp( command, "help" ) == 0 ) {
Serial.println("\nAvailable Commands:\n");
for( uint16_t i=0; i<Csize; i++ ) {
Serial.printf(" %02d) %16s : %s\n", i+1, SerialCommands[i].command, SerialCommands[i].description);
}
Serial.println();
} else {
char *token;
char delim[2];
char *args;
bool has_args = false;
strncpy(delim," ",2); // strtok_r needs a null-terminated string
if( strstr(command, delim) ) {
// turn command into token/arg
token = strtok_r(command, delim, &args); // Search for command at start of buffer
if( token != NULL ) {
has_args = true;
//Serial.printf("[%s] Found arg for token '%s' : %s\n", command, token, args);
}
}
for( uint16_t i=0; i<Csize; i++ ) {
if( strcmp( SerialCommands[i].command, command )==0 ) {
if( has_args ) {
Serial.printf( "Running '%s %s' command\n", token, args );
SerialCommands[i].cb.function( args );
} else {
Serial.printf( "Running '%s' command\n", SerialCommands[i].command );
SerialCommands[i].cb.function( NULL );
}
//sprintf(command, "%s", "");
return;
}
}
Serial.printf( "Command '%s' not found\n", command );
}
}
static void startTimeClient( void * param) {
if( foundTimeServer ) {
stopScanCB();
xTaskCreatePinnedToCore(TimeClientTask, "TimeClientTask", 12000, NULL, 1, NULL, 0); /* last = Task Core */
} else {
Serial.println("Sorry, no time server available at the moment");
}
}
static void TimeClientTask( void * param ) {
HasBTTime = false;
log_e("[Heap: %06d] Will connect to address %s", freeheap, stdBLEAddress.c_str());
if( !pClient->connect( stdBLEAddress, pClientType ) ) {
log_e("[Heap: %06d] Failed to connect to address %s", freeheap, stdBLEAddress.c_str());
startScanCB();
vTaskDelete( NULL );
return;
}
/* std::map<std::string, BLERemoteService*>* pRemoteServices = pClient->getServices();
for(std::map<std::string, BLERemoteService*>::const_iterator pRemoteServiceIteration=pRemoteServices->begin(); pRemoteServiceIteration!=pRemoteServices->end(); ++pRemoteServiceIteration) {
(*pRemoteServiceIteration).first;
(*pRemoteServiceIteration).second;
} */
log_e("[Heap: %06d] Connected to address %s", freeheap, stdBLEAddress.c_str());
BLERemoteService* pRemoteService = pClient->getService( timeServiceUUID );
if (pRemoteService == nullptr) {
log_e("Failed to find our service UUID: %s", timeServiceUUID.toString().c_str());
pClient->disconnect();
startScanCB();
vTaskDelete( NULL );
return;
}
/* std::map<std::string, BLERemoteCharacteristic*>* pRemoteCharacteristics = pRemoteService->getCharacteristics();*/
BLERemoteCharacteristic* pRemoteCharacteristic = pRemoteService->getCharacteristic( timeCharacteristicUUID );
if (pRemoteCharacteristic == nullptr) {
log_e("Failed to find our characteristic timeCharacteristicUUID: %s, disconnecting", timeCharacteristicUUID.toString().c_str());
pClient->disconnect();
startScanCB();
vTaskDelete( NULL );
return;
}
log_e("[Heap: %06d] registering for notification", freeheap);
pRemoteCharacteristic->registerForNotify( TimeClientNotifyCallback );
TickType_t last_wake_time;
last_wake_time = xTaskGetTickCount();
log_e("[Heap: %06d] while connected", freeheap);
while(pClient->isConnected()) {
vTaskDelayUntil(&last_wake_time, TICKS_TO_DELAY/portTICK_PERIOD_MS);
if( HasBTTime ) {
pClient->disconnect();
}
}
log_e("[Heap: %06d] client disconnected", freeheap);
startScanCB();
vTaskDelete( NULL );
}
static void BaseClientTask( void * param ) {
BLEAdvertisedDevice advertisedDevice;
// https://twitter.com/wakwak_koba/
// https://github.com/wakwak-koba/ESP32_BLE_Arduino/commit/master
auto* pClient = BLEDevice::createClient();
if(pClient) {
if(pClient->connect(advertisedDevice.getAddress())) {
Serial.print(pClient->getPeerAddress().toString().c_str());
Serial.print(" ");
Serial.println(advertisedDevice.getName().c_str());
auto* pRemoteServiceMap = pClient->getServices();
for (auto itr : *pRemoteServiceMap) {
Serial.print(" ");
Serial.println(itr.second->toString().c_str());
std::map<uint16_t, BLERemoteCharacteristic*>* pCharacteristicMap = itr.second->getCharacteristicsByHandle();
for (auto itr : *pCharacteristicMap) {
Serial.print(" ");
Serial.print(itr.second->toString().c_str());
if(itr.second->canNotify()) {
//itr.second->registerForNotify( BaseNotifyCallback );
Serial.print(" can notify !!");
}
Serial.println();
auto* pDescriptorMap = itr.second->getDescriptors();
if(pDescriptorMap)
for (auto itr : *pDescriptorMap) {
Serial.print(" ");
Serial.println(itr.second->toString().c_str());
}
}
}
} else {
Serial.printf("connect to %s failed\n", advertisedDevice.getAddress().toString().c_str());
}
}
}
static void scanTask( void * parameter ) {
UI.update(); // run after-scan display stuff
DB.maintain();
scanTaskRunning = true;
scanTaskStopped = false;
pBLEScan = BLEDevice::getScan(); //create new scan
pBLEScan->setAdvertisedDeviceCallbacks( pDeviceCallback );
pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster
pBLEScan->setInterval(0x50); // 0x50
pBLEScan->setWindow(0x30); // 0x30
byte onAfterScanStep = 0;
while( scanTaskRunning ) {
if( onAfterScanSteps( onAfterScanStep, scan_cursor ) ) continue;
dumpStats("BeforeScan::");
onBeforeScan();
pBLEScan->start(SCAN_DURATION);
onAfterScan();
UI.update(); // run after-scan display stuff
DB.maintain();
dumpStats("AfterScan:::");
scan_rounds++;
}
scanTaskStopped = true;
vTaskDelete( NULL );
}
static bool onAfterScanSteps( byte &onAfterScanStep, uint16_t &scan_cursor ) {
switch( onAfterScanStep ) {
case POPULATE: // 0
onScanPopulate( scan_cursor ); // OUI / vendorname / isanonymous
onAfterScanStep++;
return true;
break;
case IFEXISTS: // 1
onScanIfExists( scan_cursor ); // exists + hits
onAfterScanStep++;
return true;
break;
case RENDER: // 2
onScanRender( scan_cursor ); // ui work
onAfterScanStep++;
return true;
break;
case PROPAGATE: // 3
onAfterScanStep = 0;
if( onScanPropagate( scan_cursor ) ) { // copy to DB / cache
scan_cursor++;
return true;
}
break;
default:
log_w("Exit flat loop on afterScanStep value : %d", onAfterScanStep);
onAfterScanStep = 0;
break;
}
return false;
}
static bool onScanPopulate( uint16_t _scan_cursor ) {
if( onScanPopulated ) {
log_v("%s", " onScanPopulated = true ");
return false;
}
if( _scan_cursor >= devicesCount) {
onScanPopulated = true;
log_d("%s", "done all");
return false;
}
if( isEmpty( BLEDevScanCache[_scan_cursor]->address ) ) {
log_w("empty addess");
return true; // end of cache
}
populate( BLEDevScanCache[_scan_cursor] );
return true;
}
static bool onScanIfExists( int _scan_cursor ) {
if( onScanPostPopulated ) {
log_v("onScanPostPopulated = true");
return false;
}
if( _scan_cursor >= devicesCount) {
log_d("done all");
onScanPostPopulated = true;
return false;
}
int deviceIndexIfExists = -1;
deviceIndexIfExists = getDeviceCacheIndex( BLEDevScanCache[_scan_cursor]->address );
if( deviceIndexIfExists > -1 ) {
inCacheCount++;
BLEDevRAMCache[deviceIndexIfExists]->hits++;
if( TimeIsSet ) {
if( BLEDevRAMCache[deviceIndexIfExists]->created_at.year() <= 1970 ) {
BLEDevRAMCache[deviceIndexIfExists]->created_at = nowDateTime;
}
BLEDevRAMCache[deviceIndexIfExists]->updated_at = nowDateTime;
}
BLEDevHelper.mergeItems( BLEDevScanCache[_scan_cursor], BLEDevRAMCache[deviceIndexIfExists] ); // merge scan data into existing psram cache
BLEDevHelper.copyItem( BLEDevRAMCache[deviceIndexIfExists], BLEDevScanCache[_scan_cursor] ); // copy back merged data for rendering
log_i( "Device %d / %s exists in cache, increased hits to %d", _scan_cursor, BLEDevScanCache[_scan_cursor]->address, BLEDevScanCache[_scan_cursor]->hits );
} else {
if( BLEDevScanCache[_scan_cursor]->is_anonymous ) {
// won't land in DB (won't be checked either) but will land in cache
uint16_t nextCacheIndex = BLEDevHelper.getNextCacheIndex( BLEDevRAMCache, BLEDevCacheIndex );
BLEDevHelper.reset( BLEDevRAMCache[nextCacheIndex] );
BLEDevScanCache[_scan_cursor]->hits++;
BLEDevHelper.copyItem( BLEDevScanCache[_scan_cursor], BLEDevRAMCache[nextCacheIndex] );
log_i( "Device %d / %s is anonymous, won't be inserted", _scan_cursor, BLEDevScanCache[_scan_cursor]->address, BLEDevScanCache[_scan_cursor]->hits );
} else {
deviceIndexIfExists = DB.deviceExists( BLEDevScanCache[_scan_cursor]->address ); // will load returning devices from DB if necessary
if(deviceIndexIfExists>-1) {
uint16_t nextCacheIndex = BLEDevHelper.getNextCacheIndex( BLEDevRAMCache, BLEDevCacheIndex );
BLEDevHelper.reset( BLEDevRAMCache[nextCacheIndex] );
BLEDevDBCache->hits++;
if( TimeIsSet ) {
if( BLEDevDBCache->created_at.year() <= 1970 ) {
BLEDevDBCache->created_at = nowDateTime;
}
BLEDevDBCache->updated_at = nowDateTime;
}
BLEDevHelper.mergeItems( BLEDevScanCache[_scan_cursor], BLEDevDBCache ); // merge scan data into BLEDevDBCache
BLEDevHelper.copyItem( BLEDevDBCache, BLEDevRAMCache[nextCacheIndex] ); // copy merged data to assigned psram cache
BLEDevHelper.copyItem( BLEDevDBCache, BLEDevScanCache[_scan_cursor] ); // copy back merged data for rendering
log_i( "Device %d / %s is already in DB, increased hits to %d", _scan_cursor, BLEDevScanCache[_scan_cursor]->address, BLEDevScanCache[_scan_cursor]->hits );
} else {
// will be inserted after rendering
BLEDevScanCache[_scan_cursor]->in_db = false;
log_i( "Device %d / %s is not in DB", _scan_cursor, BLEDevScanCache[_scan_cursor]->address );
}
}
}
return true;
}
static bool onScanRender( uint16_t _scan_cursor ) {
if( onScanRendered ) {
log_v("onScanRendered = true");
return false;
}
if( _scan_cursor >= devicesCount) {
log_d("done all");
onScanRendered = true;
return false;
}
UI.BLECardTheme.setTheme( IN_CACHE_ANON );
BLEDevTmp = BLEDevScanCache[_scan_cursor];
UI.printBLECard( BLEDevTmp ); // render
delay(1);
sprintf( processMessage, processTemplateLong, "Rendered ", _scan_cursor+1, " / ", devicesCount );
UI.headerStats( processMessage );
delay(1);
UI.cacheStats();
delay(1);
UI.footerStats();
delay(1);
return true;
}
static bool onScanPropagate( uint16_t &_scan_cursor ) {
if( onScanPropagated ) {
log_v("onScanPropagated = true");
return false;
}
if( _scan_cursor >= devicesCount) {
log_d("done all");
onScanPropagated = true;
_scan_cursor = 0;
return false;
}
//BLEDevScanCacheIndex = _scan_cursor;
if( isEmpty( BLEDevScanCache[_scan_cursor]->address ) ) {
return true;
}
if( BLEDevScanCache[_scan_cursor]->is_anonymous || BLEDevScanCache[_scan_cursor]->in_db ) { // don't DB-insert anon or duplicates
sprintf( processMessage, processTemplateLong, "Released ", _scan_cursor+1, " / ", devicesCount );
if( BLEDevScanCache[_scan_cursor]->is_anonymous ) AnonymousCacheHit++;
} else {
if( DB.insertBTDevice( BLEDevScanCache[_scan_cursor] ) == DBUtils::INSERTION_SUCCESS ) {
sprintf( processMessage, processTemplateLong, "Saved ", _scan_cursor+1, " / ", devicesCount );
log_d( "Device %d successfully inserted in DB", _scan_cursor );
entries++;
} else {
log_e( " [!!! BD INSERT FAIL !!!] Device %d could not be inserted", _scan_cursor );
sprintf( processMessage, processTemplateLong, "Failed ", _scan_cursor+1, " / ", devicesCount );
}
}
BLEDevHelper.reset( BLEDevScanCache[_scan_cursor] ); // discard
UI.headerStats( processMessage );
return true;
}
static void onBeforeScan() {
UI.headerStats(" Scan in progress");
UI.startBlink();
processedDevicesCount = 0;
devicesCount = 0;
scan_cursor = 0;
onScanProcessed = false;
onScanDone = false;
onScanPopulated = false;
onScanPropagated = false;
onScanPostPopulated = false;
onScanRendered = false;
foundTimeServer = false;
}
static void onAfterScan() {
UI.stopBlink();
if( foundTimeServer && (!TimeIsSet || ForceBleTime) ) {
UI.headerStats("BLE Time sync ...");
log_e("Launching BLE TimeClient Task");
xTaskCreatePinnedToCore(TimeClientTask, "TimeClientTask", 12000, NULL, 0, NULL, 0); /* last = Task Core */
ForceBleTime = false;
scanTaskRunning = false;
return;
}
UI.headerStats("Showing results ...");
devicesCount = processedDevicesCount;
BLEDevice::getScan()->clearResults();
if( devicesCount < MAX_DEVICES_PER_SCAN ) {
if( SCAN_DURATION+1 < MAX_SCAN_DURATION ) {
SCAN_DURATION++;
}
} else if( devicesCount > MAX_DEVICES_PER_SCAN ) {
if( SCAN_DURATION-1 >= MIN_SCAN_DURATION ) {
SCAN_DURATION--;
}
log_w("Cache overflow (%d results vs %d slots), truncating results...", devicesCount, MAX_DEVICES_PER_SCAN);
devicesCount = MAX_DEVICES_PER_SCAN;
} else {
// same amount
}
sessDevicesCount += devicesCount;
notInCacheCount = 0;
inCacheCount = 0;
onScanDone = true;
scan_cursor = 0;
}
static int getDeviceCacheIndex(const char* address) {
if( isEmpty( address ) ) return -1;
for(int i=0; i<BLEDEVCACHE_SIZE; i++) {
if( strcmp(address, BLEDevRAMCache[i]->address )==0 ) {
BLEDevCacheHit++;
log_v("[CACHE HIT] BLEDevCache ID #%s has %d cache hits", address, BLEDevRAMCache[i]->hits);
return i;
}
delay(1);
}
return -1;
}
// used for serial debugging
static void dumpStats(const char* prefixStr) {
if(lastheap > freeheap) {
// heap decreased
sprintf(heapsign, "%s", "↘");
} else if(lastheap < freeheap) {
// heap increased
sprintf(heapsign, "%s", "↗");
} else {
// heap unchanged
sprintf(heapsign, "%s", "⇉");
}
if(lastscanduration > SCAN_DURATION) {
sprintf(scantimesign, "%s", "↘");
} else if(lastscanduration < SCAN_DURATION) {
sprintf(scantimesign, "%s", "↗");
} else {
sprintf(scantimesign, "%s", "⇉");
}
lastheap = freeheap;
lastscanduration = SCAN_DURATION;
log_i("%s[Scan#%02d][%s][Duration%s%d][Processed:%d of %d][Heap%s%d / %d] [Cache hits][Screen:%d][BLEDevCards:%d][Anonymous:%d][Oui:%d][Vendor:%d]\n",
prefixStr,
scan_rounds,
hhmmssString,
scantimesign,
lastscanduration,
processedDevicesCount,
devicesCount,
heapsign,
lastheap,
freepsheap,
SelfCacheHit,
BLEDevCacheHit,
AnonymousCacheHit,
OuiCacheHit,
VendorCacheHit
);
}
private:
static void getPrefs() {
preferences.begin("BLEPrefs", true);
Out.serialEcho = preferences.getBool("serialEcho", true);
UI.filterVendors = preferences.getBool("filterVendors", false);
preferences.end();
}
static void setPrefs() {
preferences.begin("BLEPrefs", false);
preferences.putBool("serialEcho", Out.serialEcho);
preferences.putBool("filterVendors", UI.filterVendors );
preferences.end();
}
// completes unpopulated fields of a given entry by performing DB oui/vendor lookups
static void populate( BlueToothDevice *CacheItem ) {
if( strcmp( CacheItem->ouiname, "[unpopulated]" )==0 ){
log_d(" [populating OUI for %s]", CacheItem->address);
DB.getOUI( CacheItem->address, CacheItem->ouiname );
}
if( strcmp( CacheItem->manufname, "[unpopulated]" )==0 ) {
if( CacheItem->manufid!=-1 ) {
log_d(" [populating Vendor for :%d]", CacheItem->manufid );
DB.getVendor( CacheItem->manufid, CacheItem->manufname );
} else {
BLEDevHelper.set( CacheItem, "manufname", '\0');
}
}
CacheItem->is_anonymous = BLEDevHelper.isAnonymous( CacheItem );
log_d("[populated :%s]", CacheItem->address);
}
};
#endif
BLEScanUtils BLECollector;
| 35.685451 | 243 | 0.608114 | [
"render"
] |
f3486e475f85cbc5c3a315dd02b51ae9066c0f7b | 6,747 | c | C | src/CLState.c | taylor-santos/CLPathTracer | 2605ffb695e4272381b4f3663f194369993ef14d | [
"Unlicense"
] | 1 | 2020-04-21T22:42:42.000Z | 2020-04-21T22:42:42.000Z | src/CLState.c | taylor-santos/CLPathTracer | 2605ffb695e4272381b4f3663f194369993ef14d | [
"Unlicense"
] | null | null | null | src/CLState.c | taylor-santos/CLPathTracer | 2605ffb695e4272381b4f3663f194369993ef14d | [
"Unlicense"
] | null | null | null | #include <CL/cl_gl.h>
#include <math.h>
#include <GL/gl3w.h>
#include <GLFW/glfw3.h>
#include "error.h"
#include "camera.h"
#include "CLHandler.h"
#include "object.h"
#include "list.h"
#include "kd_tree.h"
typedef struct KernelArg {
size_t size;
void *arg_ptr;
unsigned int is_ptr: 1;
} KernelArg;
#define KernelArg(size, arg_ptr, is_ptr) ((KernelArg){ size, arg_ptr, is_ptr })
static struct {
cl_platform_id platform;
cl_device_id device;
cl_context context;
cl_program program;
cl_command_queue queue;
cl_kernel kernel;
cl_mem image;
cl_mem matrix;
cl_mem objects;
cl_int objcount;
kd kd;
cl_mem verts;
cl_mem norms;
cl_mem tris;
cl_mem triIndices;
cl_mem kdtree;
size_t treesize;
KernelArg *vec_args;
} State;
void
CLDeleteImage(void) {
HANDLE_ERR(clReleaseMemObject(State.image));
}
void
CLCreateImage(GLuint texture) {
cl_int err;
State.image = clCreateFromGLTexture(State.context,
CL_MEM_WRITE_ONLY,
GL_TEXTURE_2D,
0,
texture,
&err);
HANDLE_ERR(err);
}
static void
update_image(cl_command_queue queue, cl_mem *image, cl_kernel kernel) {
HANDLE_ERR(clEnqueueAcquireGLObjects(queue, 1, image, 0, 0, NULL));
}
long long unsigned int count = 0;
void
CLSetCameraMatrix(Matrix matrix) {
count++;
HANDLE_ERR(clEnqueueWriteBuffer(State.queue,
State.matrix,
CL_TRUE,
0,
sizeof(Matrix),
&matrix,
0,
NULL,
NULL));
}
static void
update_args(cl_kernel kernel) {
size_t count = vector_length(State.vec_args);
for (size_t i = 0; i < count; i++) {
HANDLE_ERR(clSetKernelArg(kernel,
i,
State.vec_args[i].size,
State.vec_args[i].arg_ptr));
}
}
static void
resize_buffer(cl_mem *buffer, size_t size) {
if (*buffer != 0) {
HANDLE_ERR(clReleaseMemObject(*buffer));
}
if (size == 0) {
*buffer = 0;
return;
}
*buffer = CLCreateBuffer(State.context, size);
}
void
CLSetObjects(Object *vec_objects, size_t size) {
if (size / sizeof(Object) != (size_t)State.objcount) {
resize_buffer(&State.objects, size);
State.objcount = size / sizeof(Object);
}
if (size == 0) {
return;
}
HANDLE_ERR(clEnqueueWriteBuffer(State.queue,
State.objects,
CL_TRUE,
0,
size,
vec_objects,
0,
NULL,
NULL));
}
void
CLSetMeshes(kd *models) {
size_t model_count = vector_length(models);
if (model_count == 0) {
return;
}
State.kd = models[0];
{
Vector4 *verts = State.kd.vert_vec;
size_t vertSize = list_size(verts);
resize_buffer(&State.verts, vertSize);
HANDLE_ERR(clEnqueueWriteBuffer(State.queue,
State.verts,
CL_TRUE,
0,
vertSize,
verts,
0,
NULL,
NULL));
}
{
Vector4 *norms = State.kd.norm_vec;
size_t normSize = list_size(norms);
if (normSize > 0) {
resize_buffer(&State.norms, normSize);
HANDLE_ERR(clEnqueueWriteBuffer(State.queue,
State.norms,
CL_TRUE,
0,
normSize,
norms,
0,
NULL,
NULL));
}
}
{
cl_int3 *tris = State.kd.tri_vec;
size_t triSize = list_size(tris);
resize_buffer(&State.tris, triSize);
HANDLE_ERR(clEnqueueWriteBuffer(State.queue,
State.tris,
CL_TRUE,
0,
triSize,
tris,
0,
NULL,
NULL));
}
{
int *triIndices = State.kd.tri_indices;
size_t triIndicesSize = list_size(triIndices);
resize_buffer(&State.triIndices, triIndicesSize);
HANDLE_ERR(clEnqueueWriteBuffer(State.queue,
State.triIndices,
CL_TRUE,
0,
triIndicesSize,
triIndices,
0,
NULL,
NULL));
}
{
size_t treesize = list_size(State.kd.node_vec);
resize_buffer(&State.kdtree, treesize);
HANDLE_ERR(clEnqueueWriteBuffer(State.queue,
State.kdtree,
CL_TRUE,
0,
treesize,
State.kd.node_vec,
0,
NULL,
NULL));
}
}
void
CLExecute(int width, int height) {
glFinish();
update_image(State.queue, &State.image, State.kernel);
update_args(State.kernel);
CLEnqueueKernel(2, (size_t[]){
width, height
}, NULL, State.queue, State.kernel);
clFinish(State.queue);
HANDLE_ERR(clEnqueueReleaseGLObjects(State.queue,
1,
&State.image,
0,
0,
NULL));
}
void
CLTerminate(void) {
delete_kd(State.kd);
delete_list(State.vec_args);
}
void
CLInit(const char *kernel_filename, const char *kernel_name) {
State.platform = CLGetPlatform();
State.device = CLGetDevice(State.platform);
State.context = CLCreateContext(State.platform, State.device);
State.program =
CLBuildProgram(kernel_filename, State.context, State.device);
State.queue = CLCreateQueue(State.context, State.device);
State.kernel = CLCreateKernel(kernel_name, State.program);
State.matrix = CLCreateBuffer(State.context, sizeof(Matrix));
State.vec_args = new_list(9 * sizeof(*State.vec_args));
vector_append(State.vec_args, KernelArg(
sizeof(cl_mem), &State.image, 0
));
vector_append(State.vec_args, KernelArg(
sizeof(cl_mem), &State.matrix, 0
));
vector_append(State.vec_args, KernelArg(
sizeof(cl_mem), &State.objects, 0
));
vector_append(State.vec_args, KernelArg(
sizeof(cl_int), &State.objcount, 1
));
vector_append(State.vec_args, KernelArg(
sizeof(cl_mem), &State.verts, 0
));
vector_append(State.vec_args, KernelArg(
sizeof(cl_mem), &State.norms, 0
));
vector_append(State.vec_args, KernelArg(
sizeof(cl_mem), &State.tris, 0
));
vector_append(State.vec_args, KernelArg(
sizeof(cl_mem), &State.triIndices, 0
));
vector_append(State.vec_args, KernelArg(
sizeof(cl_mem), &State.kdtree, 0
));
}
| 25.364662 | 79 | 0.55684 | [
"object"
] |
f3496a4d648ff30cf8b2afbc74625303c5cb45a9 | 59,194 | h | C | tf_opt/open_source/protocol_buffer_matchers.h | google-research/tf-opt | 0704531e1cd85b31e5e07051767f6f9608d090c4 | [
"Apache-2.0"
] | 23 | 2020-10-22T02:35:17.000Z | 2022-03-09T22:01:54.000Z | tf_opt/open_source/protocol_buffer_matchers.h | google-research/tf-opt | 0704531e1cd85b31e5e07051767f6f9608d090c4 | [
"Apache-2.0"
] | null | null | null | tf_opt/open_source/protocol_buffer_matchers.h | google-research/tf-opt | 0704531e1cd85b31e5e07051767f6f9608d090c4 | [
"Apache-2.0"
] | 6 | 2021-01-09T20:01:59.000Z | 2022-01-16T12:58:32.000Z | // Copyright 2021 The tf.opt Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// gMock matchers used to validate protocol buffer arguments. A fork of the
// official gmock protocol-buffer-matchers.h, from October 6th, 2020. See also
// b/135192747.
//
// WHAT THIS IS
// ============
//
// This library defines the matchers in the ::tfopt::testing namespace:
//
// EqualsProto(pb) The argument equals pb.
// EqualsInitializedProto(pb) The argument is initialized and equals pb.
// EquivToProto(pb) The argument is equivalent to pb.
// EquivToInitializedProto(pb) The argument is initialized and equivalent
// to pb.
// IsInitializedProto() The argument is an initialized protobuf.
//
// where:
//
// - pb can be either a protobuf value or a human-readable string
// representation of it.
// - When pb is a string, the matcher can optionally accept a
// template argument for the type of the protobuf,
// e.g. EqualsProto<Foo>("foo: 1").
// - "equals" is defined as the argument's Equals(pb) method returns true.
// - "equivalent to" is defined as the argument's Equivalent(pb) method
// returns true.
// - "initialized" means that the argument's IsInitialized() method returns
// true.
//
// These matchers can match either a protobuf value or a pointer to
// it. They make a copy of pb, and thus can out-live pb. When the
// match fails, the matchers print a detailed message (the value of
// the actual protobuf, the value of the expected protobuf, and which
// fields are different).
//
// This library also defines the following matcher transformer
// functions in the ::tfopt::testing::proto namespace:
//
// Approximately(m, margin, fraction)
// The same as m, except that it compares
// floating-point fields approximately (using
// google::protobuf::util::MessageDifferencer's APPROXIMATE
// comparison option). m can be any of the
// Equals* and EquivTo* protobuf matchers above. If margin
// is specified, floats and doubles will be considered
// approximately equal if they are within that margin, i.e.
// abs(expected - actual) <= margin. If fraction is
// specified, floats and doubles will be considered
// approximately equal if they are within a fraction of
// their magnitude, i.e. abs(expected - actual) <=
// fraction * max(abs(expected), abs(actual)). Two fields
// will be considered equal if they're within the fraction
// _or_ within the margin, so omitting or setting the
// fraction to 0.0 will only check against the margin.
// Similarly, setting the margin to 0.0 will only check
// using the fraction. If margin and fraction are omitted,
// MathLimits<T>::kStdError for that type (T=float or
// T=double) is used for both the margin and fraction.
// TreatingNaNsAsEqual(m)
// The same as m, except that treats floating-point fields
// that are NaN as equal. m can be any of the Equals* and
// EquivTo* protobuf matchers above.
// IgnoringFields(fields, m)
// The same as m, except the specified fields will be
// ignored when matching (using
// google::protobuf::util::MessageDifferencer::IgnoreField). fields is
// represented as a container or an initializer list of
// strings and each element is specified by their fully
// qualified names, i.e., the names corresponding to
// FieldDescriptor.full_name(). m can be
// any of the Equals* and EquivTo* protobuf matchers above.
// It can also be any of the transformer matchers listed
// here (e.g. Approximately, TreatingNaNsAsEqual) as long as
// the intent of the each concatenated matcher is mutually
// exclusive (e.g. using IgnoringFields in conjunction with
// Partially can have different results depending on whether
// the fields specified in IgnoringFields is part of the
// fields covered by Partially).
// IgnoringFieldPaths(field_paths, m)
// The same as m, except the specified fields will be
// ignored when matching. field_paths is represented as a
// container or an initializer list of strings and
// each element is specified by their path relative to the
// proto being matched by m. Paths can contain indices
// and/or extensions. Examples:
// Ignores field singular_field/repeated_field:
// singular_field
// repeated_field
// Ignores just the third repeated_field instance:
// repeated_field[2]
// Ignores some_field in singular_nested/repeated_nested:
// singular_nested.some_field
// repeated_nested.some_field
// Ignores some_field in instance 2 of repeated_nested:
// repeated_nested[2].some_field
// Ignores extension SomeExtension.msg of repeated_nested:
// repeated_nested.(package.SomeExtension.msg)
// Ignores subfield of extension:
// repeated_nested.(package.SomeExtension.msg).subfield
// If you are trying to ignore fields from a proto group,
// please note that the group name is converted to lower
// case. The same restrictions as for IgnoringFields apply.
// IgnoringRepeatedFieldOrdering(m)
// The same as m, except that it ignores the relative
// ordering of elements within each repeated field in m.
// See google::protobuf::util::MessageDifferencer::TreatAsSet() for
// more details.
// Partially(m)
// The same as m, except that only fields present in
// the expected protobuf are considered (using
// google::protobuf::util::MessageDifferencer's PARTIAL
// comparison option). m can be any of the
// Equals* and EquivTo* protobuf matchers above.
// WhenDeserialized(typed_pb_matcher)
// The string argument is a serialization of a
// protobuf that matches typed_pb_matcher.
// typed_pb_matcher can be an Equals* or EquivTo*
// protobuf matcher (possibly with Approximately()
// or Partially() modifiers) where the type of the
// protobuf is known at run time (e.g. it cannot
// be EqualsProto("...") as it's unclear what type
// the string represents).
// WhenDeserializedAs<PB>(pb_matcher)
// Like WhenDeserialized(), except that the type
// of the deserialized protobuf must be PB. Since
// the protobuf type is known, pb_matcher can be *any*
// valid protobuf matcher, including EqualsProto("...").
// WhenParsedFromProtoText(typed_pb_matcher)
// The string argument is a text-format of a
// protobuf that matches typed_pb_matcher.
// typed_pb_matcher can be an Equals* or EquivTo*
// protobuf matcher (possibly with Approximately()
// or Partially() modifiers) where the type of the
// protobuf is known at run time (e.g. it cannot
// be EqualsProto("...") as it's unclear what type
// the string represents).
// WhenParsedFromProtoTextAs<PB>(pb_matcher)
// Like WhenParsedFromProtoText(), except that the type of
// the parsed protobuf must be PB. Since the protobuf type
// is known, pb_matcher can be *any* valid protobuf matcher,
// including EqualsProto("...").
//
// Approximately(), TreatingNaNsAsEqual(), Partially(), IgnoringFields(), and
// IgnoringRepeatedFieldOrdering() can be combined (nested)
// and the composition order is irrelevant:
//
// Approximately(Partially(EquivToProto(pb)))
// and
// Partially(Approximately(EquivToProto(pb)))
// are the same thing.
//
// EXAMPLES
// ========
//
// using ::tf_opt::testing::EqualsProto;
// using ::tf_opt::testing::EquivToProto;
// using ::tf_opt::testing::proto::Approximately;
// using ::tf_opt::testing::proto::Partially;
// using ::tf_opt::testing::proto::WhenDeserialized;
// using ::tf_opt::testing::proto::WhenParsedFromProtoText;
// using ::tf_opt::testing::proto::WhenUnpacked;
//
// // my_pb.Equals(expected_pb).
// EXPECT_THAT(my_pb, EqualsProto(expected_pb));
//
// // my_pb is equivalent to a protobuf whose foo field is 1 and
// // whose bar field is "x".
// EXPECT_THAT(my_pb, EquivToProto(R"(foo: 1 # In-string comment
// bar: 'x')"));
//
// // my_pb is equal to expected_pb, comparing all floating-point
// // fields approximately.
// EXPECT_THAT(my_pb, Approximately(EqualsProto(expected_pb)));
//
// // my_pb is equivalent to expected_pb. A field is ignored in the
// // comparison if it's present in my_pb but not in expected_pb.
// EXPECT_THAT(my_pb, Partially(EquivToProto(expected_pb)));
//
// string data;
// my_pb.SerializeToString(&data);
// // data can be deserialized to a protobuf that equals expected_pb.
// EXPECT_THAT(data, WhenDeserialized(EqualsProto(expected_pb)));
// // The following line doesn't compile, as the matcher doesn't know
// // the type of the protobuf.
// // EXPECT_THAT(data, WhenDeserialized(EqualsProto("foo: 1")));
//
// string text = my_pb.DebugString();
// EXPECT_THAT(text, WhenParsedFromProtoText(EqualsProto(expected_pb)));
// // The following line doesn't compile, as the matcher doesn't know
// // the type of the protobuf.
// // EXPECT_THAT(text, WhenParsedFromProtoText(EqualsProto("foo: 1")));
#ifndef TF_OPT_OPEN_SOURCE_PROTOCOL_BUFFER_MATCHERS_H_
#define TF_OPT_OPEN_SOURCE_PROTOCOL_BUFFER_MATCHERS_H_
#include <initializer_list>
#include <iostream> // NOLINT
#include <memory>
#include <sstream> // NOLINT
#include <string> // NOLINT
#include <vector> // NOLINT
#include "ortools/base/logging.h"
#include "google/protobuf/io/zero_copy_stream.h"
#include "google/protobuf/io/zero_copy_stream_impl.h"
#include "google/protobuf/io/zero_copy_stream_impl_lite.h"
#include "google/protobuf/descriptor.h"
#include "google/protobuf/map.h"
#include "google/protobuf/message.h"
#include "google/protobuf/text_format.h"
#include "google/protobuf/util/field_comparator.h"
#include "google/protobuf/util/message_differencer.h"
#include "gmock/gmock.h"
#include "absl/memory/memory.h"
#include "absl/strings/cord.h"
#include "absl/strings/string_view.h"
namespace google {
namespace protobuf {
using GeneratedMessageBaseType = Message;
} // namespace protobuf
} // namespace google
namespace tf_opt {
namespace testing {
namespace internal {
// Utilities.
// How to compare two fields (equal vs. equivalent).
typedef google::protobuf::util::MessageDifferencer::MessageFieldComparison
ProtoFieldComparison;
// How to compare two floating-points (exact vs. approximate).
typedef google::protobuf::util::DefaultFieldComparator::FloatComparison
ProtoFloatComparison;
// How to compare repeated fields (whether the order of elements matters).
typedef google::protobuf::util::MessageDifferencer::RepeatedFieldComparison
RepeatedFieldComparison;
// Whether to compare all fields (full) or only fields present in the
// expected protobuf (partial).
typedef google::protobuf::util::MessageDifferencer::Scope ProtoComparisonScope;
const ProtoFieldComparison kProtoEqual =
google::protobuf::util::MessageDifferencer::EQUAL;
const ProtoFieldComparison kProtoEquiv =
google::protobuf::util::MessageDifferencer::EQUIVALENT;
const ProtoFloatComparison kProtoExact =
google::protobuf::util::DefaultFieldComparator::EXACT;
const ProtoFloatComparison kProtoApproximate =
google::protobuf::util::DefaultFieldComparator::APPROXIMATE;
const RepeatedFieldComparison kProtoCompareRepeatedFieldsRespectOrdering =
google::protobuf::util::MessageDifferencer::AS_LIST;
const RepeatedFieldComparison kProtoCompareRepeatedFieldsIgnoringOrdering =
google::protobuf::util::MessageDifferencer::AS_SET;
const ProtoComparisonScope kProtoFull = google::protobuf::util::MessageDifferencer::FULL;
const ProtoComparisonScope kProtoPartial =
google::protobuf::util::MessageDifferencer::PARTIAL;
// Options for comparing two protobufs.
struct ProtoComparison {
ProtoComparison()
: field_comp(kProtoEqual),
float_comp(kProtoExact),
treating_nan_as_equal(false),
has_custom_margin(false),
has_custom_fraction(false),
repeated_field_comp(kProtoCompareRepeatedFieldsRespectOrdering),
scope(kProtoFull),
float_margin(0.0),
float_fraction(0.0) {}
ProtoFieldComparison field_comp;
ProtoFloatComparison float_comp;
bool treating_nan_as_equal;
bool has_custom_margin; // only used when float_comp = APPROXIMATE
bool has_custom_fraction; // only used when float_comp = APPROXIMATE
RepeatedFieldComparison repeated_field_comp;
ProtoComparisonScope scope;
double float_margin; // only used when has_custom_margin is set.
double float_fraction; // only used when has_custom_fraction is set.
std::vector<std::string> ignore_fields;
std::vector<std::string> ignore_field_paths;
};
// Whether the protobuf must be initialized.
const bool kMustBeInitialized = true;
const bool kMayBeUninitialized = false;
// Parses the TextFormat representation of a protobuf, allowing required fields
// to be missing. Returns true iff successful.
bool ParsePartialFromAscii(absl::string_view pb_ascii, google::protobuf::Message* proto,
std::string* error_text);
// Returns a protobuf of type Proto by parsing the given TextFormat
// representation of it. Required fields can be missing, in which case the
// returned protobuf will not be fully initialized.
template <class Proto>
Proto MakePartialProtoFromAscii(absl::string_view str) {
Proto proto;
std::string error_text;
CHECK(ParsePartialFromAscii(str, &proto, &error_text))
<< "Failed to parse \"" << str << "\" as a "
<< proto.GetDescriptor()->full_name() << ":\n" << error_text;
return proto;
}
// Returns true iff p and q can be compared. Lite protos must share the same
// type name and full protos must share the same descriptor.
bool ProtoComparable(const google::protobuf::MessageLite& p,
const google::protobuf::MessageLite& q);
bool ProtoComparable(const google::protobuf::Message& p, const google::protobuf::Message& q);
// Returns true iff actual and expected are comparable and match. The
// comp argument specifies how the two are compared.
bool ProtoCompare(const ProtoComparison& comp,
const google::protobuf::MessageLite& actual,
const google::protobuf::MessageLite& expected);
bool ProtoCompare(const ProtoComparison& comp, const google::protobuf::Message& actual,
const google::protobuf::Message& expected);
// Overload for ProtoCompare where the expected message is specified as a text
// proto. If the text cannot be parsed as a message of the same type as the
// actual message, a CHECK failure will cause the test to fail and no subsequent
// tests will be run.
template <typename Proto>
inline bool ProtoCompare(const ProtoComparison& comp, const Proto& actual,
absl::string_view expected) {
return ProtoCompare(comp, actual, MakePartialProtoFromAscii<Proto>(expected));
}
// Describes the types of the expected and the actual protocol buffer.
std::string DescribeTypes(const google::protobuf::MessageLite& expected,
const google::protobuf::MessageLite& actual);
// Prints the protocol buffer pointed to by proto.
template <class MessageType>
std::string PrintProtoPointee(const MessageType* proto) {
if (proto == nullptr) return "";
return "which points to " + ::testing::PrintToString(*proto);
}
// Describes the differences between the two protocol buffers.
std::string DescribeDiff(const ProtoComparison& comp,
const google::protobuf::MessageLite& actual,
const google::protobuf::MessageLite& expected);
std::string DescribeDiff(const ProtoComparison& comp,
const google::protobuf::Message& actual,
const google::protobuf::Message& expected);
// Common code for implementing EqualsProto, EquivToProto,
// EqualsInitializedProto, and EquivToInitializedProto.
template <class MessageType>
class ProtoMatcherBaseImpl {
public:
ProtoMatcherBaseImpl(
bool must_be_initialized, // Must the argument be fully initialized?
const ProtoComparison& comp) // How to compare the two protobufs.
: must_be_initialized_(must_be_initialized), comp_(new auto(comp)) {}
ProtoMatcherBaseImpl(const ProtoMatcherBaseImpl& other)
: must_be_initialized_(other.must_be_initialized_),
comp_(new auto(*other.comp_)) {}
ProtoMatcherBaseImpl(ProtoMatcherBaseImpl&& other) noexcept = default;
virtual ~ProtoMatcherBaseImpl() {}
// Prints the expected protocol buffer.
virtual void PrintExpectedTo(::std::ostream* os) const = 0;
// Returns the expected value as a protobuf object; if the object
// cannot be created (e.g. in ProtoStringMatcher), explains why to
// 'listener' and returns NULL. The caller must call
// DeleteExpectedProto() on the returned value later.
virtual const MessageType* CreateExpectedProto(
const google::protobuf::MessageLite& arg, // For determining the type of the
// expected protobuf.
::testing::MatchResultListener* listener) const = 0;
// Deletes the given expected protobuf, which must be obtained from
// a call to CreateExpectedProto() earlier.
virtual void DeleteExpectedProto(
const google::protobuf::MessageLite* expected) const = 0;
// Makes this matcher compare floating-points approximately.
void SetCompareApproximately() { comp_->float_comp = kProtoApproximate; }
// Makes this matcher treating NaNs as equal when comparing floating-points.
void SetCompareTreatingNaNsAsEqual() { comp_->treating_nan_as_equal = true; }
// Makes this matcher ignore string elements specified by their fully
// qualified names, i.e., names corresponding to FieldDescriptor.full_name().
template <class Iterator>
void AddCompareIgnoringFields(Iterator first, Iterator last) {
comp_->ignore_fields.insert(comp_->ignore_fields.end(), first, last);
}
// Makes this matcher ignore string elements specified by their relative
// FieldPath.
template <class Iterator>
void AddCompareIgnoringFieldPaths(Iterator first, Iterator last) {
comp_->ignore_field_paths.insert(comp_->ignore_field_paths.end(), first,
last);
}
// Makes this matcher compare repeated fields ignoring ordering of elements.
void SetCompareRepeatedFieldsIgnoringOrdering() {
comp_->repeated_field_comp = kProtoCompareRepeatedFieldsIgnoringOrdering;
}
// Sets the margin of error for approximate floating point comparison.
void SetMargin(double margin) {
CHECK_GE(margin, 0.0) << "Using a negative margin for Approximately";
comp_->has_custom_margin = true;
comp_->float_margin = margin;
}
// Sets the relative fraction of error for approximate floating point
// comparison.
void SetFraction(double fraction) {
CHECK(0.0 <= fraction && fraction < 1.0) <<
"Fraction for Approximately must be >= 0.0 and < 1.0";
comp_->has_custom_fraction = true;
comp_->float_fraction = fraction;
}
// Makes this matcher compare protobufs partially.
void SetComparePartially() { comp_->scope = kProtoPartial; }
bool MatchAndExplain(const google::protobuf::MessageLite& arg,
::testing::MatchResultListener* listener) const {
return MatchAndExplain(arg, false, listener);
}
bool MatchAndExplain(const google::protobuf::MessageLite* arg,
::testing::MatchResultListener* listener) const {
return (arg != nullptr) && MatchAndExplain(*arg, true, listener);
}
// Describes the expected relation between the actual protobuf and
// the expected one.
void DescribeRelationToExpectedProto(::std::ostream* os) const {
if (comp_->repeated_field_comp ==
kProtoCompareRepeatedFieldsIgnoringOrdering) {
*os << "(ignoring repeated field ordering) ";
}
if (!comp_->ignore_fields.empty()) {
*os << "(ignoring fields: ";
absl::string_view sep = "";
for (size_t i = 0; i < comp_->ignore_fields.size(); ++i, sep = ", ")
*os << sep << comp_->ignore_fields[i];
*os << ") ";
}
if (comp_->float_comp == kProtoApproximate) {
*os << "approximately ";
if (comp_->has_custom_margin || comp_->has_custom_fraction) {
*os << "(";
if (comp_->has_custom_margin) {
std::stringstream ss;
ss << std::setprecision(std::numeric_limits<double>::digits10 + 2)
<< comp_->float_margin;
*os << "absolute error of float or double fields <= " << ss.str();
}
if (comp_->has_custom_margin && comp_->has_custom_fraction) {
*os << " or ";
}
if (comp_->has_custom_fraction) {
std::stringstream ss;
ss << std::setprecision(std::numeric_limits<double>::digits10 + 2)
<< comp_->float_fraction;
*os << "relative error of float or double fields <= " << ss.str();
}
*os << ") ";
}
}
*os << (comp_->scope == kProtoPartial ? "partially " : "")
<< (comp_->field_comp == kProtoEqual ? "equal" : "equivalent")
<< (comp_->treating_nan_as_equal ? " (treating NaNs as equal)" : "")
<< " to ";
PrintExpectedTo(os);
}
void DescribeTo(::std::ostream* os) const {
*os << "is " << (must_be_initialized_ ? "fully initialized and " : "");
DescribeRelationToExpectedProto(os);
}
void DescribeNegationTo(::std::ostream* os) const {
*os << "is " << (must_be_initialized_ ? "not fully initialized or " : "")
<< "not ";
DescribeRelationToExpectedProto(os);
}
bool must_be_initialized() const { return must_be_initialized_; }
const ProtoComparison& comp() const { return *comp_; }
private:
bool MatchAndExplain(const google::protobuf::MessageLite& arg,
bool is_matcher_for_pointer,
::testing::MatchResultListener* listener) const;
const bool must_be_initialized_;
std::unique_ptr<ProtoComparison> comp_;
};
template <class MessageType>
bool ProtoMatcherBaseImpl<MessageType>::MatchAndExplain(
const google::protobuf::MessageLite& arg,
bool is_matcher_for_pointer, // true iff this matcher is used to match
// a protobuf pointer.
::testing::MatchResultListener* listener) const {
const auto& casted_arg = dynamic_cast<const MessageType&>(arg);
if (must_be_initialized_ && !casted_arg.IsInitialized()) {
*listener << "which isn't fully initialized";
return false;
}
const MessageType* const expected = CreateExpectedProto(casted_arg, listener);
if (expected == nullptr) return false;
// Protobufs of different types cannot be compared.
const bool comparable = ProtoComparable(casted_arg, *expected);
const bool match = comparable && ProtoCompare(comp(), casted_arg, *expected);
// Explaining the match result is expensive. We don't want to waste
// time calculating an explanation if the listener isn't interested.
if (listener->IsInterested()) {
absl::string_view sep = "";
if (is_matcher_for_pointer) {
*listener << PrintProtoPointee(&casted_arg);
sep = ",\n";
}
if (!comparable) {
*listener << sep << DescribeTypes(*expected, casted_arg);
} else if (!match) {
*listener << sep << DescribeDiff(comp(), casted_arg, *expected);
}
}
DeleteExpectedProto(expected);
return match;
}
// ProtoMatcherBase must be defined here with a 'using' statement, because there
// is code in google3 which assumes that all proto matchers derive from a base
// class called ProtoMatcherBase.
// ProtoMatcherBaseImpl<GeneratedMessageType> (aka ProtoMatcherBase)
// |
// ProtoMatcherImpl<GeneratedMessageType>
// |
// ProtoMatcher
using ProtoMatcherBase = ProtoMatcherBaseImpl<google::protobuf::GeneratedMessageBaseType>;
// Returns a copy of the given proto2 message.
template <class MessageType>
inline MessageType* CloneProto2(const MessageType& src) {
MessageType* clone = src.New();
clone->CheckTypeAndMergeFrom(src);
return clone;
}
// Implements EqualsProto, EquivToProto, EqualsInitializedProto, and
// EquivToInitializedProto, where the matcher parameter is a protobuf.
template <class MessageType>
class ProtoMatcherImpl : public ProtoMatcherBaseImpl<MessageType> {
public:
using Proto = MessageType;
ProtoMatcherImpl(
const MessageType& expected, // The expected protobuf.
bool must_be_initialized, // Must the argument be fully initialized?
const ProtoComparison& comp) // How to compare the two protobufs.
: ProtoMatcherBaseImpl<MessageType>(must_be_initialized, comp),
expected_(CloneProto2(expected)) {
if (must_be_initialized) {
CHECK(expected.IsInitialized())
<< "The protocol buffer given to *InitializedProto() "
<< "must itself be initialized, but the following required fields "
<< "are missing: " << expected.InitializationErrorString() << ".";
}
}
void PrintExpectedTo(::std::ostream* os) const override {
*os << expected_->GetTypeName() << " ";
::testing::internal::UniversalPrint(*expected_, os);
}
const MessageType* CreateExpectedProto(
const google::protobuf::MessageLite& /* arg */,
::testing::MatchResultListener* /* listener */) const override {
return expected_.get();
}
void DeleteExpectedProto(
const google::protobuf::MessageLite* /* expected */) const override {}
const std::shared_ptr<const MessageType>& expected() const {
return expected_;
}
private:
const std::shared_ptr<const MessageType> expected_;
};
// ProtoMatcher must be defined as a class (no using statement here) for
// backwards compatibility with inherited classes. When defined with using
// statement, the inherited class must use a fully qualified class name with the
// template type to call the base class ctor - it seems that C++ does not (?)
// infer the base class type in ctor from the inheritenace (weird, but true).
class ProtoMatcher : public ProtoMatcherImpl<google::protobuf::GeneratedMessageBaseType> {
public:
ProtoMatcher(
const google::protobuf::GeneratedMessageBaseType&
expected, // The expected protobuf.
bool must_be_initialized, // Must the argument be fully initialized?
const ProtoComparison& comp) // How to compare the two protobufs.
: ProtoMatcherImpl(expected, must_be_initialized, comp) {}
};
class ProtoMatcherLite : public ProtoMatcherImpl<google::protobuf::MessageLite> {
public:
ProtoMatcherLite(
const google::protobuf::MessageLite& expected, // The expected protobuf.
bool must_be_initialized, // Must the argument be fully initialized?
const ProtoComparison& comp) // How to compare the two protobufs.
: ProtoMatcherImpl(expected, must_be_initialized, comp) {}
};
// Implements EqualsProto, EquivToProto, EqualsInitializedProto, and
// EquivToInitializedProto, where the matcher parameter is a string.
class ProtoStringMatcher : public ProtoMatcherBase {
public:
ProtoStringMatcher(
absl::string_view expected, // The text for the expected protobuf.
bool must_be_initialized, // Must the argument be fully initialized?
const ProtoComparison comp) // How to compare the two protobufs.
: ProtoMatcherBase(must_be_initialized, comp), expected_(expected) {}
// Parses the expected string as a protobuf of the same type as arg,
// and returns the parsed protobuf (or NULL when the parse fails).
// The caller must call DeleteExpectedProto() on the return value
// later.
const google::protobuf::Message* CreateExpectedProto(
const google::protobuf::MessageLite& arg,
::testing::MatchResultListener* listener) const override {
auto* expected_proto = dynamic_cast<google::protobuf::Message*>(arg.New());
// We don't insist that the expected string parses as an
// *initialized* protobuf. Otherwise EqualsProto("...") may
// wrongfully fail when the actual protobuf is not fully
// initialized. If the user wants to ensure that the actual
// protobuf is initialized, they should use
// EqualsInitializedProto("...") instead of EqualsProto("..."),
// and the MatchAndExplain() function in ProtoMatcherBase will
// enforce it.
std::string error_text;
if (ParsePartialFromAscii(expected_, expected_proto, &error_text)) {
return expected_proto;
} else {
delete expected_proto;
if (listener->IsInterested()) {
*listener << "where ";
PrintExpectedTo(listener->stream());
*listener << " doesn't parse as a " << arg.GetTypeName() << ":\n"
<< error_text;
}
return nullptr;
}
}
void DeleteExpectedProto(const google::protobuf::MessageLite* expected) const override {
delete expected;
}
void PrintExpectedTo(::std::ostream* os) const override {
*os << "<" << expected_ << ">";
}
private:
const std::string expected_;
};
using PolymorphicProtoMatcher = ::testing::PolymorphicMatcher<ProtoMatcher>;
using PolymorphicProtoMatcherLite =
::testing::PolymorphicMatcher<ProtoMatcherLite>;
// Enum representing the possible representations of protos as strings. Used
// to configure the adapter's behavior when converting the input string.
enum class ProtoStringFormat { kBinaryFormat, kTextFormat };
// Common code for implementing adapters that allow proto matchers to match
// strings (WhenDeserialized/WhenParsedFromProtoText).
template <class Proto>
class ProtoMatcherStringAdapter {
protected:
using InnerMatcher = ::testing::Matcher<const Proto&>;
ProtoMatcherStringAdapter(const InnerMatcher& proto_matcher,
const ProtoStringFormat input_format)
: proto_matcher_(proto_matcher), input_format_(input_format) {}
~ProtoMatcherStringAdapter() {}
private:
// Creates an empty protobuf with the expected type.
virtual Proto* MakeEmptyProto() const = 0;
// Type name of the expected protobuf.
virtual std::string ExpectedTypeName() const = 0;
// Name of the type argument given to
// WhenDeserializedAs<>()/WhenParsedFromProtoTextAs<>(), or "protobuf" for
// WhenDeserialized()/WhenParsedFromProtoText().
virtual std::string TypeArgName() const = 0;
// Deserializes or parses the string as a protobuf of the same type as the
// expected protobuf.
::std::unique_ptr<Proto> ToProto(
google::protobuf::io::ZeroCopyInputStream* input) const {
auto proto = absl::WrapUnique(this->MakeEmptyProto());
bool converted = false;
switch (input_format_) {
case ProtoStringFormat::kBinaryFormat:
// ParsePartialFromString() parses a serialized representation of a
// protobuf, allowing required fields to be missing. This means
// that we don't insist on the parsed protobuf being fully
// initialized. This allows the user to choose whether it should
// be initialized using EqualsProto vs EqualsInitializedProto, for
// example.
converted = proto->ParsePartialFromZeroCopyStream(input);
break;
case ProtoStringFormat::kTextFormat: {
google::protobuf::TextFormat::Parser parser;
parser.AllowPartialMessage(true);
converted = parser.Parse(input, proto.get());
break;
}
}
return converted ? std::move(proto) : nullptr;
}
// Gets the past tense of the verb describing the conversion. Used for
// describing the matcher and explaining matches.
std::string ConversionVerbPast() const {
switch (input_format_) {
case ProtoStringFormat::kBinaryFormat:
return "deserialized";
case ProtoStringFormat::kTextFormat:
return "parsed";
}
}
// Gets the present tense of the verb describing the conversion. Used for
// describing the matcher and explaining matches.
std::string ConversionVerbPresent() const {
switch (input_format_) {
case ProtoStringFormat::kBinaryFormat:
return "deserializes";
case ProtoStringFormat::kTextFormat:
return "parses";
}
}
public:
void DescribeTo(::std::ostream* os) const {
*os << "can be " << ConversionVerbPast() << " as a " << TypeArgName()
<< " that ";
proto_matcher_.DescribeTo(os);
}
void DescribeNegationTo(::std::ostream* os) const {
*os << "cannot be " << ConversionVerbPast() << " as a " << TypeArgName()
<< " that ";
proto_matcher_.DescribeTo(os);
}
bool MatchAndExplain(google::protobuf::io::ZeroCopyInputStream* arg,
::testing::MatchResultListener* listener) const {
// Deserializes the string arg as a protobuf of the same type as the
// expected protobuf.
::std::unique_ptr<const Proto> proto_arg = ToProto(arg);
if (!listener->IsInterested()) {
// No need to explain the match result.
return (proto_arg != nullptr) && proto_matcher_.Matches(*proto_arg);
}
::std::ostream* const os = listener->stream();
if (proto_arg == nullptr) {
*os << "which cannot be " << ConversionVerbPast() << " as a "
<< ExpectedTypeName();
return false;
}
*os << "which " << ConversionVerbPresent() << " to ";
::testing::internal::UniversalPrint(*proto_arg, os);
::testing::StringMatchResultListener inner_listener;
const bool match =
proto_matcher_.MatchAndExplain(*proto_arg, &inner_listener);
const std::string explain = inner_listener.str();
if (!explain.empty()) {
*os << ",\n" << explain;
}
return match;
}
bool MatchAndExplain(const absl::Cord& cord,
::testing::MatchResultListener* listener) const {
// TODO: it is better to use google::protobuf::io::CordInputStream, this is
// not available in open source proto yet.
return MatchAndExplain(std::string(cord), listener);
}
bool MatchAndExplain(absl::string_view sp,
::testing::MatchResultListener* listener) const {
google::protobuf::io::ArrayInputStream input(sp.data(), sp.size());
return MatchAndExplain(&input, listener);
}
private:
const InnerMatcher proto_matcher_;
const ProtoStringFormat input_format_;
};
// Implements WhenDeserialized(proto_matcher) and
// WhenParsedFromProtoText(proto_matcher).
class UntypedProtoMatcherStringAdapter final
: public ProtoMatcherStringAdapter<google::protobuf::GeneratedMessageBaseType> {
public:
UntypedProtoMatcherStringAdapter(const PolymorphicProtoMatcher& proto_matcher,
const ProtoStringFormat input_format)
: ProtoMatcherStringAdapter<google::protobuf::GeneratedMessageBaseType>(
proto_matcher, input_format),
expected_proto_(proto_matcher.impl().expected()) {}
private:
google::protobuf::GeneratedMessageBaseType* MakeEmptyProto() const override {
return expected_proto_->New();
}
std::string ExpectedTypeName() const override {
return expected_proto_->GetTypeName();
}
std::string TypeArgName() const override { return "protobuf"; }
// The expected protobuf specified in the inner matcher
// (proto_matcher_). We only need a std::shared_ptr to it instead of
// making a copy, as the expected protobuf will never be changed
// once created.
const std::shared_ptr<const google::protobuf::GeneratedMessageBaseType> expected_proto_;
};
// Implements WhenDeserializedAs<Proto>(proto_matcher) and
// WhenParsedFromProtoTextAs<Proto>(proto_matcher).
template <class Proto>
class TypedProtoMatcherStringAdapter final
: public ProtoMatcherStringAdapter<Proto> {
private:
using InnerMatcher = ::testing::Matcher<const Proto&>;
public:
TypedProtoMatcherStringAdapter(const InnerMatcher& inner_matcher,
const ProtoStringFormat input_format)
: ProtoMatcherStringAdapter<Proto>(inner_matcher, input_format) {}
private:
Proto* MakeEmptyProto() const override { return new Proto; }
std::string ExpectedTypeName() const override {
return Proto().GetTypeName();
}
std::string TypeArgName() const override { return ExpectedTypeName(); }
};
// Implements the IsInitializedProto matcher, which is used to verify that a
// protocol buffer is valid using the IsInitialized method.
class IsInitializedProtoMatcher {
public:
void DescribeTo(::std::ostream* os) const {
*os << "is a fully initialized protocol buffer";
}
void DescribeNegationTo(::std::ostream* os) const {
*os << "is not a fully initialized protocol buffer";
}
template <typename T>
bool MatchAndExplain(T& arg, // NOLINT
::testing::MatchResultListener* listener) const {
if (!arg.IsInitialized()) {
*listener << "which is missing the following required fields: "
<< arg.InitializationErrorString();
return false;
}
return true;
}
// It's critical for this overload to take a T* instead of a const
// T*. Otherwise the other version would be a better match when arg
// is a pointer to a non-const value.
template <typename T>
bool MatchAndExplain(T* arg, ::testing::MatchResultListener* listener) const {
if (listener->IsInterested() && arg != nullptr) {
*listener << PrintProtoPointee(arg);
}
if (arg == nullptr) {
*listener << "which is null";
return false;
} else if (!arg->IsInitialized()) {
*listener << ", which is missing the following required fields: "
<< arg->InitializationErrorString();
return false;
} else {
return true;
}
}
};
// Implements EqualsProto and EquivToProto for 2-tuple matchers.
class TupleProtoMatcher {
public:
explicit TupleProtoMatcher(const ProtoComparison& comp)
: comp_(new auto(comp)) {}
TupleProtoMatcher(const TupleProtoMatcher& other)
: comp_(new auto(*other.comp_)) {}
TupleProtoMatcher(TupleProtoMatcher&& other) = default;
template <typename T1, typename T2>
operator ::testing::Matcher<::testing::tuple<T1, T2>>() const {
return MakeMatcher(new Impl< ::testing::tuple<T1, T2> >(*comp_));
}
template <typename T1, typename T2>
operator ::testing::Matcher<const ::testing::tuple<T1, T2>&>() const {
return MakeMatcher(new Impl<const ::testing::tuple<T1, T2>&>(*comp_));
}
// Allows matcher transformers, e.g., Approximately(), Partially(), etc. to
// change the behavior of this 2-tuple matcher.
TupleProtoMatcher& mutable_impl() { return *this; }
// Makes this matcher compare floating-points approximately.
void SetCompareApproximately() { comp_->float_comp = kProtoApproximate; }
// Makes this matcher treating NaNs as equal when comparing floating-points.
void SetCompareTreatingNaNsAsEqual() { comp_->treating_nan_as_equal = true; }
// Makes this matcher ignore string elements specified by their fully
// qualified names, i.e., names corresponding to FieldDescriptor.full_name().
template <class Iterator>
void AddCompareIgnoringFields(Iterator first, Iterator last) {
comp_->ignore_fields.insert(comp_->ignore_fields.end(), first, last);
}
// Makes this matcher ignore string elements specified by their relative
// FieldPath.
template <class Iterator>
void AddCompareIgnoringFieldPaths(Iterator first, Iterator last) {
comp_->ignore_field_paths.insert(comp_->ignore_field_paths.end(), first,
last);
}
// Makes this matcher compare repeated fields ignoring ordering of elements.
void SetCompareRepeatedFieldsIgnoringOrdering() {
comp_->repeated_field_comp = kProtoCompareRepeatedFieldsIgnoringOrdering;
}
// Sets the margin of error for approximate floating point comparison.
void SetMargin(double margin) {
CHECK_GE(margin, 0.0) << "Using a negative margin for Approximately";
comp_->has_custom_margin = true;
comp_->float_margin = margin;
}
// Sets the relative fraction of error for approximate floating point
// comparison.
void SetFraction(double fraction) {
CHECK(0.0 <= fraction && fraction <= 1.0) <<
"Fraction for Relatively must be >= 0.0 and < 1.0";
comp_->has_custom_fraction = true;
comp_->float_fraction = fraction;
}
// Makes this matcher compares protobufs partially.
void SetComparePartially() { comp_->scope = kProtoPartial; }
private:
template <typename Tuple>
class Impl : public ::testing::MatcherInterface<Tuple> {
public:
explicit Impl(const ProtoComparison& comp) : comp_(comp) {}
bool MatchAndExplain(
Tuple args,
::testing::MatchResultListener* /* listener */) const override {
using ::testing::get;
return ProtoCompare(comp_, get<0>(args), get<1>(args));
}
void DescribeTo(::std::ostream* os) const override {
*os << (comp_.field_comp == kProtoEqual ? "are equal"
: "are equivalent");
}
void DescribeNegationTo(::std::ostream* os) const override {
*os << (comp_.field_comp == kProtoEqual ? "are not equal"
: "are not equivalent");
}
private:
const ProtoComparison comp_;
};
std::unique_ptr<ProtoComparison> comp_;
};
} // namespace internal
// Creates a polymorphic matcher that matches a 2-tuple where
// first.Equals(second) is true.
inline internal::TupleProtoMatcher EqualsProto() {
internal::ProtoComparison comp;
comp.field_comp = internal::kProtoEqual;
return internal::TupleProtoMatcher(comp);
}
// Creates a polymorphic matcher that matches a 2-tuple where
// first.Equivalent(second) is true.
inline internal::TupleProtoMatcher EquivToProto() {
internal::ProtoComparison comp;
comp.field_comp = internal::kProtoEquiv;
return internal::TupleProtoMatcher(comp);
}
// Constructs a matcher that matches the argument if
// argument.Equals(x) or argument->Equals(x) returns true.
inline internal::PolymorphicProtoMatcher EqualsProto(const google::protobuf::Message& x) {
internal::ProtoComparison comp;
comp.field_comp = internal::kProtoEqual;
return ::testing::MakePolymorphicMatcher(
internal::ProtoMatcher(x, internal::kMayBeUninitialized, comp));
}
inline internal::PolymorphicProtoMatcherLite EqualsProto(
const google::protobuf::MessageLite& x) {
internal::ProtoComparison comp;
comp.field_comp = internal::kProtoEqual;
return ::testing::MakePolymorphicMatcher(
internal::ProtoMatcherLite(x, internal::kMayBeUninitialized, comp));
}
inline ::testing::PolymorphicMatcher<internal::ProtoStringMatcher> EqualsProto(
absl::string_view x) {
internal::ProtoComparison comp;
comp.field_comp = internal::kProtoEqual;
return ::testing::MakePolymorphicMatcher(
internal::ProtoStringMatcher(x, internal::kMayBeUninitialized, comp));
}
template <class Proto>
inline internal::PolymorphicProtoMatcher EqualsProto(absl::string_view str) {
return EqualsProto(internal::MakePartialProtoFromAscii<Proto>(str));
}
// Constructs a matcher that matches the argument if
// argument.Equivalent(x) or argument->Equivalent(x) returns true.
inline internal::PolymorphicProtoMatcher EquivToProto(
const google::protobuf::Message& x) {
internal::ProtoComparison comp;
comp.field_comp = internal::kProtoEquiv;
return ::testing::MakePolymorphicMatcher(
internal::ProtoMatcher(x, internal::kMayBeUninitialized, comp));
}
inline ::testing::PolymorphicMatcher<internal::ProtoStringMatcher> EquivToProto(
absl::string_view x) {
internal::ProtoComparison comp;
comp.field_comp = internal::kProtoEquiv;
return ::testing::MakePolymorphicMatcher(
internal::ProtoStringMatcher(x, internal::kMayBeUninitialized, comp));
}
template <class Proto>
inline internal::PolymorphicProtoMatcher EquivToProto(absl::string_view str) {
return EquivToProto(internal::MakePartialProtoFromAscii<Proto>(str));
}
// Constructs a matcher that matches the argument if
// argument.IsInitialized() or argument->IsInitialized() returns true.
inline ::testing::PolymorphicMatcher<internal::IsInitializedProtoMatcher>
IsInitializedProto() {
return ::testing::MakePolymorphicMatcher(
internal::IsInitializedProtoMatcher());
}
// Constructs a matcher that matches an argument whose IsInitialized()
// and Equals(x) methods both return true. The argument can be either
// a protocol buffer or a pointer to it.
inline internal::PolymorphicProtoMatcher EqualsInitializedProto(
const google::protobuf::Message& x) {
internal::ProtoComparison comp;
comp.field_comp = internal::kProtoEqual;
return ::testing::MakePolymorphicMatcher(
internal::ProtoMatcher(x, internal::kMustBeInitialized, comp));
}
inline internal::PolymorphicProtoMatcherLite EqualsInitializedProto(
const google::protobuf::MessageLite& x) {
internal::ProtoComparison comp;
comp.field_comp = internal::kProtoEqual;
return ::testing::MakePolymorphicMatcher(
internal::ProtoMatcherLite(x, internal::kMustBeInitialized, comp));
}
inline ::testing::PolymorphicMatcher<internal::ProtoStringMatcher>
EqualsInitializedProto(absl::string_view x) {
internal::ProtoComparison comp;
comp.field_comp = internal::kProtoEqual;
return ::testing::MakePolymorphicMatcher(
internal::ProtoStringMatcher(x, internal::kMustBeInitialized, comp));
}
template <class Proto>
inline internal::PolymorphicProtoMatcher EqualsInitializedProto(
absl::string_view str) {
return EqualsInitializedProto(
internal::MakePartialProtoFromAscii<Proto>(str));
}
// Constructs a matcher that matches an argument whose IsInitialized()
// and Equivalent(x) methods both return true. The argument can be
// either a protocol buffer or a pointer to it.
inline internal::PolymorphicProtoMatcher
EquivToInitializedProto(const google::protobuf::Message& x) {
internal::ProtoComparison comp;
comp.field_comp = internal::kProtoEquiv;
return ::testing::MakePolymorphicMatcher(
internal::ProtoMatcher(x, internal::kMustBeInitialized, comp));
}
inline ::testing::PolymorphicMatcher<internal::ProtoStringMatcher>
EquivToInitializedProto(absl::string_view x) {
internal::ProtoComparison comp;
comp.field_comp = internal::kProtoEquiv;
return ::testing::MakePolymorphicMatcher(
internal::ProtoStringMatcher(x, internal::kMustBeInitialized, comp));
}
template <class Proto>
inline internal::PolymorphicProtoMatcher EquivToInitializedProto(
absl::string_view str) {
return EquivToInitializedProto(
internal::MakePartialProtoFromAscii<Proto>(str));
}
namespace proto {
// Approximately(m) returns a matcher that is the same as m, except
// that it compares floating-point fields approximately (using
// google::protobuf::util::MessageDifferencer's APPROXIMATE comparison option).
// The inner matcher m can be any of the Equals* and EquivTo* protobuf
// matchers above.
template <class InnerProtoMatcher>
inline InnerProtoMatcher Approximately(InnerProtoMatcher inner_proto_matcher) {
static_assert(sizeof(InnerProtoMatcher) != 0 &&
std::is_same<google::protobuf::GeneratedMessageBaseType,
google::protobuf::Message>::value,
"The Approximately() matcher requires full (non-lite) protos.");
inner_proto_matcher.mutable_impl().SetCompareApproximately();
return inner_proto_matcher;
}
// Alternative version of Approximately which takes an explicit margin of error.
template <class InnerProtoMatcher>
inline InnerProtoMatcher Approximately(InnerProtoMatcher inner_proto_matcher,
double margin) {
static_assert(sizeof(InnerProtoMatcher) != 0 &&
std::is_same<google::protobuf::GeneratedMessageBaseType,
google::protobuf::Message>::value,
"The Approximately() matcher requires full (non-lite) protos.");
inner_proto_matcher.mutable_impl().SetCompareApproximately();
inner_proto_matcher.mutable_impl().SetMargin(margin);
return inner_proto_matcher;
}
// Alternative version of Approximately which takes an explicit margin of error
// and a relative fraction of error and will match if either is satisfied.
template <class InnerProtoMatcher>
inline InnerProtoMatcher Approximately(InnerProtoMatcher inner_proto_matcher,
double margin, double fraction) {
static_assert(sizeof(InnerProtoMatcher) != 0 &&
std::is_same<google::protobuf::GeneratedMessageBaseType,
google::protobuf::Message>::value,
"The Approximately() matcher requires full (non-lite) protos.");
inner_proto_matcher.mutable_impl().SetCompareApproximately();
inner_proto_matcher.mutable_impl().SetMargin(margin);
inner_proto_matcher.mutable_impl().SetFraction(fraction);
return inner_proto_matcher;
}
// TreatingNaNsAsEqual(m) returns a matcher that is the same as m, except that
// it compares floating-point fields such that NaNs are equal.
// The inner matcher m can be any of the Equals* and EquivTo* protobuf matchers
// above.
template <class InnerProtoMatcher>
inline InnerProtoMatcher TreatingNaNsAsEqual(
InnerProtoMatcher inner_proto_matcher) {
static_assert(
sizeof(InnerProtoMatcher) != 0 &&
std::is_same<google::protobuf::GeneratedMessageBaseType,
google::protobuf::Message>::value,
"The TreatingNaNsAsEqual() matcher requires full (non-lite) protos.");
inner_proto_matcher.mutable_impl().SetCompareTreatingNaNsAsEqual();
return inner_proto_matcher;
}
// IgnoringFields(fields, m) returns a matcher that is the same as m, except the
// specified fields will be ignored when matching
// (using google::protobuf::util::MessageDifferencer::IgnoreField). Each element in fields
// are specified by their fully qualified names, i.e., the names corresponding
// to FieldDescriptor.full_name(). (e.g. testing.internal.FooProto2.member).
// m can be any of the Equals* and EquivTo* protobuf matchers above.
// It can also be any of the transformer matchers listed here (e.g.
// Approximately, TreatingNaNsAsEqual) as long as the intent of the each
// concatenated matcher is mutually exclusive (e.g. using IgnoringFields in
// conjunction with Partially can have different results depending on whether
// the fields specified in IgnoringFields is part of the fields covered by
// Partially).
template <class InnerProtoMatcher, class Container>
inline InnerProtoMatcher IgnoringFields(const Container& ignore_fields,
InnerProtoMatcher inner_proto_matcher) {
static_assert(
sizeof(InnerProtoMatcher) != 0 &&
std::is_same<google::protobuf::GeneratedMessageBaseType,
google::protobuf::Message>::value,
"The IgnoringFields() matcher requires full (non-lite) protos.");
inner_proto_matcher.mutable_impl().AddCompareIgnoringFields(
ignore_fields.begin(), ignore_fields.end());
return inner_proto_matcher;
}
// See top comment.
template <class InnerProtoMatcher, class Container>
inline InnerProtoMatcher IgnoringFieldPaths(
const Container& ignore_field_paths,
InnerProtoMatcher inner_proto_matcher) {
static_assert(
sizeof(InnerProtoMatcher) != 0 &&
std::is_same<google::protobuf::GeneratedMessageBaseType,
google::protobuf::Message>::value,
"The IgnoringFieldPaths() matcher requires full (non-lite) protos.");
inner_proto_matcher.mutable_impl().AddCompareIgnoringFieldPaths(
ignore_field_paths.begin(), ignore_field_paths.end());
return inner_proto_matcher;
}
#ifdef LANG_CXX11
template <class InnerProtoMatcher, class T>
inline InnerProtoMatcher IgnoringFields(std::initializer_list<T> il,
InnerProtoMatcher inner_proto_matcher) {
static_assert(
sizeof(InnerProtoMatcher) != 0 &&
std::is_same<google::protobuf::GeneratedMessageBaseType,
google::protobuf::Message>::value,
"The IgnoringFields() matcher requires full (non-lite) protos.");
inner_proto_matcher.mutable_impl().AddCompareIgnoringFields(
il.begin(), il.end());
return inner_proto_matcher;
}
template <class InnerProtoMatcher, class T>
inline InnerProtoMatcher IgnoringFieldPaths(
std::initializer_list<T> il, InnerProtoMatcher inner_proto_matcher) {
static_assert(
sizeof(InnerProtoMatcher) != 0 &&
std::is_same<google::protobuf::GeneratedMessageBaseType,
google::protobuf::Message>::value,
"The IgnoringFieldPaths() matcher requires full (non-lite) protos.");
inner_proto_matcher.mutable_impl().AddCompareIgnoringFieldPaths(il.begin(),
il.end());
return inner_proto_matcher;
}
#endif // LANG_CXX11
// IgnoringRepeatedFieldOrdering(m) returns a matcher that is the same as m,
// except that it ignores the relative ordering of elements within each repeated
// field in m. See google::protobuf::MessageDifferencer::TreatAsSet() for more details.
template <class InnerProtoMatcher>
inline InnerProtoMatcher IgnoringRepeatedFieldOrdering(
InnerProtoMatcher inner_proto_matcher) {
static_assert(sizeof(InnerProtoMatcher) != 0 &&
std::is_same<google::protobuf::GeneratedMessageBaseType,
google::protobuf::Message>::value,
"The IgnoringRepeatedFieldOrdering() matcher requires full "
"(non-lite) protos.");
inner_proto_matcher.mutable_impl().SetCompareRepeatedFieldsIgnoringOrdering();
return inner_proto_matcher;
}
// Partially(m) returns a matcher that is the same as m, except that
// only fields present in the expected protobuf are considered (using
// google::protobuf::util::MessageDifferencer's PARTIAL comparison option). For
// example, Partially(EqualsProto(p)) will ignore any field that's
// not set in p when comparing the protobufs. Repeated fields are not treated
// specially; extra or missing values will cause the test to fail. The inner
// matcher m can be any of the Equals* and EquivTo* protobuf matchers above.
template <class InnerProtoMatcher>
inline InnerProtoMatcher Partially(InnerProtoMatcher inner_proto_matcher) {
static_assert(sizeof(InnerProtoMatcher) != 0 &&
std::is_same<google::protobuf::GeneratedMessageBaseType,
google::protobuf::Message>::value,
"The Partially() matcher requires full (non-lite) protos.");
inner_proto_matcher.mutable_impl().SetComparePartially();
return inner_proto_matcher;
}
// WhenDeserialized(m) is a matcher that matches a string that can be
// deserialized as a protobuf that matches m. m must be a protobuf
// matcher where the expected protobuf type is known at run time.
inline ::testing::PolymorphicMatcher<internal::UntypedProtoMatcherStringAdapter>
WhenDeserialized(const internal::PolymorphicProtoMatcher& proto_matcher) {
return ::testing::MakePolymorphicMatcher(
internal::UntypedProtoMatcherStringAdapter(
proto_matcher, internal::ProtoStringFormat::kBinaryFormat));
}
// WhenDeserializedAs<Proto>(m) is a matcher that matches a string
// that can be deserialized as a protobuf of type Proto that matches
// m, which can be any valid protobuf matcher.
template <class Proto, class InnerMatcher>
::testing::PolymorphicMatcher<internal::TypedProtoMatcherStringAdapter<Proto>>
WhenDeserializedAs(const InnerMatcher& inner_matcher) {
return ::testing::MakePolymorphicMatcher(
internal::TypedProtoMatcherStringAdapter<Proto>(
::testing::SafeMatcherCast<const Proto&>(inner_matcher),
internal::ProtoStringFormat::kBinaryFormat));
}
// WhenParsedFromProtoText(m) is a matcher that matches a string that can be
// parsed as a text-format protobuf that matches m. m must be a protobuf matcher
// where the expected protobuf type is known at run time.
inline ::testing::PolymorphicMatcher<internal::UntypedProtoMatcherStringAdapter>
WhenParsedFromProtoText(
const internal::PolymorphicProtoMatcher& proto_matcher) {
return ::testing::MakePolymorphicMatcher(
internal::UntypedProtoMatcherStringAdapter(
proto_matcher, internal::ProtoStringFormat::kTextFormat));
}
// WhenParsedFromProtoTextAs<Proto>(m) is a matcher that matches a string that
// can be parsed as a text-format protobuf of type Proto that matches m, which
// can be any valid protobuf matcher.
template <class Proto, class InnerMatcher>
::testing::PolymorphicMatcher<internal::TypedProtoMatcherStringAdapter<Proto>>
WhenParsedFromProtoTextAs(const InnerMatcher& inner_matcher) {
return ::testing::MakePolymorphicMatcher(
internal::TypedProtoMatcherStringAdapter<Proto>(
::testing::SafeMatcherCast<const Proto&>(inner_matcher),
internal::ProtoStringFormat::kTextFormat));
}
} // namespace proto
} // namespace testing
} // namespace tf_opt
#endif // TF_OPT_OPEN_SOURCE_PROTOCOL_BUFFER_MATCHERS_H_
| 43.018895 | 93 | 0.69333 | [
"object",
"vector"
] |
f34b68af2024422a2cc9b7935c507c2bfaced43c | 94,474 | c | C | kmod/ipc/ipc_kmsg.c | Andromeda-OS/mach-loader-freebsd | 7941be37f41c80643910a105b3fe46041b6cc903 | [
"BSD-2-Clause"
] | 2 | 2021-04-19T13:27:40.000Z | 2021-08-29T06:13:32.000Z | kmod/ipc/ipc_kmsg.c | Andromeda-OS/mach-loader-freebsd | 7941be37f41c80643910a105b3fe46041b6cc903 | [
"BSD-2-Clause"
] | null | null | null | kmod/ipc/ipc_kmsg.c | Andromeda-OS/mach-loader-freebsd | 7941be37f41c80643910a105b3fe46041b6cc903 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright 1991-1998 by Open Software Foundation, Inc.
* All Rights Reserved
*
* Permission to use, copy, modify, and distribute this software and
* its documentation for any purpose and without fee is hereby granted,
* provided that the above copyright notice appears in all copies and
* that both the copyright notice and this permission notice appear in
* supporting documentation.
*
* OSF DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL OSF BE LIABLE FOR ANY SPECIAL, INDIRECT, OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN ACTION OF CONTRACT,
* NEGLIGENCE, OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* MkLinux
*/
/* CMU_HIST */
/*
* Revision 2.22.1.4 92/04/08 15:44:20 jeffreyh
* Temporary debugging logic.
* [92/04/06 dlb]
*
* Revision 2.22.1.3 92/03/03 16:18:34 jeffreyh
* Picked up changes from Joe's branch
* [92/03/03 10:08:49 jeffreyh]
*
* Eliminate keep_wired argument from vm_map_copyin().
* [92/02/21 10:12:26 dlb]
* Changes from TRUNK
* [92/02/26 11:41:33 jeffreyh]
*
* Revision 2.22.1.2.2.1 92/03/01 22:24:38 jsb
* Added use_page_lists logic to ipc_kmsg_copyin_compat.
*
* Revision 2.23 92/01/14 16:44:23 rpd
* Fixed ipc_kmsg_copyin, ipc_kmsg_copyout, etc
* to use copyinmap and copyoutmap for out-of-line ports.
* [91/12/16 rpd]
*
* Revision 2.22.1.2 92/02/21 11:23:22 jsb
* Moved ipc_kmsg_copyout_to_network to norma/ipc_output.c.
* Moved ipc_kmsg_uncopyout_to_network to norma/ipc_clean.c.
* [92/02/21 10:34:46 jsb]
*
* We no longer convert to network format directly from user format;
* this greatly simplifies kmsg cleaning issues. Added code to detect
* and recover from vm_map_convert_to_page_list failure.
* Streamlined and fixed ipc_kmsg_copyout_to_network.
* [92/02/21 09:01:52 jsb]
*
* Modified for new form of norma_ipc_send_port which returns uid.
* [92/02/20 17:11:17 jsb]
*
* Revision 2.22.1.1 92/01/03 16:34:59 jsb
* Mark out-of-line ports as COMPLEX_DATA.
* [92/01/02 13:53:15 jsb]
*
* In ipc_kmsg_uncopyout_to_network: don't process local or remote port.
* Do clear the migrate bit as well as the complex_{data,ports} bits.
* [91/12/31 11:42:07 jsb]
*
* Added ipc_kmsg_uncopyout_to_network().
* [91/12/29 21:05:29 jsb]
*
* Added support in ipc_kmsg_print for MACH_MSGH_BITS_MIGRATED.
* [91/12/26 19:49:16 jsb]
*
* Made clean_kmsg routines aware of norma uids.
* Cleaned up ipc_{msg,kmsg}_print. Corrected log.
* [91/12/24 13:59:49 jsb]
*
* Revision 2.22 91/12/15 10:37:53 jsb
* Improved ddb 'show kmsg' support.
*
* Revision 2.21 91/12/14 14:26:03 jsb
* Removed ipc_fields.h hack.
* Made ipc_kmsg_clean_{body,partial} aware of remote ports.
* They don't yet clean up remote ports, but at least they
* no longer pass port uids to ipc_object_destroy.
*
* Revision 2.20 91/12/13 13:51:58 jsb
* Use norma_ipc_copyin_page_list when sending to remote port.
*
* Revision 2.19 91/12/10 13:25:46 jsb
* Added ipc_kmsg_copyout_to_network, as required by ipc_kserver.c.
* Picked up vm_map_convert_to_page_list call changes from dlb.
* Changed NORMA_VM conditional for ipc_kmsg_copyout_to_kernel
* to NORMA_IPC.
* [91/12/10 11:20:36 jsb]
*
* Revision 2.18 91/11/14 16:55:57 rpd
* Picked up mysterious norma changes.
* [91/11/14 rpd]
*
* Revision 2.17 91/10/09 16:09:08 af
* Changed msgh_kind to msgh_seqno in ipc_msg_print.
* [91/10/05 rpd]
*
* Revision 2.16 91/08/28 11:13:20 jsb
* Changed msgh_kind to msgh_seqno.
* [91/08/09 rpd]
* Changed for new vm_map_copyout failure behavior.
* [91/08/03 rpd]
* Update page list discriminant logic to allow use of page list for
* kernel objects that do not require page stealing (devices).
* [91/07/31 15:00:55 dlb]b
*
* Add arg to vm_map_copyin_page_list.
* [91/07/30 14:10:38 dlb]
*
* Turn page lists on by default.
* [91/07/03 14:01:00 dlb]
* Renamed clport fields in struct ipc_port to ip_norma fields.
* Added checks for sending receive rights remotely.
* [91/08/15 08:22:20 jsb]
*
* Revision 2.15 91/08/03 18:18:16 jsb
* Added support for ddb commands ``show msg'' and ``show kmsg''.
* Made changes for elimination of intermediate clport structure.
* [91/07/27 22:25:06 jsb]
*
* Moved MACH_MSGH_BITS_COMPLEX_{PORTS,DATA} to mach/message.h.
* Removed complex_data_hint_xxx[] garbage.
* Adopted new vm_map_copy_t page_list technology.
* [91/07/04 13:09:45 jsb]
*
* Revision 2.14 91/07/01 08:24:34 jsb
* From David Black at OSF: generalized page list support.
* [91/06/29 16:29:29 jsb]
*
* Revision 2.13 91/06/17 15:46:04 jsb
* Renamed NORMA conditionals.
* [91/06/17 10:45:05 jsb]
*
* Revision 2.12 91/06/06 17:05:52 jsb
* More NORMA_IPC stuff. Cleanup will follow.
* [91/06/06 16:00:08 jsb]
*
* Revision 2.11 91/05/14 16:33:01 mrt
* Correcting copyright
*
* Revision 2.10 91/03/16 14:47:57 rpd
* Replaced ith_saved with ipc_kmsg_cache.
* [91/02/16 rpd]
*
* Revision 2.9 91/02/05 17:21:52 mrt
* Changed to new Mach copyright
* [91/02/01 15:45:30 mrt]
*
* Revision 2.8 91/01/08 15:13:49 rpd
* Added ipc_kmsg_free.
* [91/01/05 rpd]
* Optimized ipc_kmsg_copyout_object for send rights.
* [90/12/21 rpd]
* Changed to use new copyinmsg/copyoutmsg operations.
* Changed ipc_kmsg_get to check that the size is multiple of four.
* [90/12/05 rpd]
* Removed MACH_IPC_GENNOS.
* [90/11/08 rpd]
*
* Revision 2.7 90/11/05 14:28:36 rpd
* Changed ip_reference to ipc_port_reference.
* Changed ip_release to ipc_port_release.
* Use new io_reference and io_release.
* Use new ip_reference and ip_release.
* [90/10/29 rpd]
*
* Revision 2.6 90/09/09 14:31:50 rpd
* Fixed ipc_kmsg_copyin_compat to clear unused bits instead
* of returning an error when they are non-zero.
* [90/09/08 rpd]
*
* Revision 2.5 90/08/06 17:05:53 rpd
* Fixed ipc_kmsg_copyout_body to turn off msgt_deallocate
* for in-line data. It might be on if the compatibility mode
* generated the message.
*
* Fixed ipc_kmsg_copyin, ipc_kmsg_copyin_compat to check
* that msgt_name, msgt_size, msgt_number are zero
* in long-form type descriptors.
* [90/08/04 rpd]
*
* Fixed atomicity bug in ipc_kmsg_copyout_header,
* when the destination and reply ports are the same.
* [90/08/02 rpd]
*
* Revision 2.4 90/08/06 15:07:31 rwd
* Fixed ipc_kmsg_clean_partial to deallocate correctly
* the OOL memory in the last type spec.
* Removed debugging panic in ipc_kmsg_put.
* [90/06/21 rpd]
*
* Revision 2.3 90/06/19 22:58:03 rpd
* For debugging: added panic to ipc_kmsg_put.
* [90/06/04 rpd]
*
* Revision 2.2 90/06/02 14:50:05 rpd
* Changed ocurrences of inline; it is a gcc keyword.
* [90/06/02 rpd]
*
* For out-of-line memory, if length is zero allow any address.
* This is more compatible with old IPC.
* [90/04/23 rpd]
* Created for new IPC.
* [90/03/26 20:55:45 rpd]
*
* Revision 2.16.2.1 91/09/16 10:15:35 rpd
* Removed unused variables. Added <ipc/ipc_notify.h>.
* [91/09/02 rpd]
*
*/
/* CMU_ENDHIST */
/*
* Mach Operating System
* Copyright (c) 1991,1990,1989 Carnegie Mellon University
* All Rights Reserved.
*
* Permission to use, copy, modify and distribute this software and its
* documentation is hereby granted, provided that both the copyright
* notice and this permission notice appear in all copies of the
* software, derivative works or modified versions, and any portions
* thereof, and that both notices appear in supporting documentation.
*
* CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
* CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
* ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
*
* Carnegie Mellon requests users of this software to return to
*
* Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
* School of Computer Science
* Carnegie Mellon University
* Pittsburgh PA 15213-3890
*
* any improvements or extensions that they make and grant Carnegie Mellon
* the rights to redistribute these changes.
*/
/*
*/
/*
* File: ipc/ipc_kmsg.c
* Author: Rich Draves
* Date: 1989
*
* Operations on kernel messages.
*/
#include <sys/cdefs.h>
#include <sys/types.h>
#include <sys/param.h>
#include <sys/limits.h>
#include <sys/syslog.h>
#include <sys/proc.h>
#include <vm/vm.h>
#include <vm/vm_extern.h>
#include <vm/vm_kern.h>
#include <mach/kern_return.h>
#include <mach/message.h>
#include <mach/port.h>
#include <mach/ipc/port.h>
#include <mach/ipc/ipc_entry.h>
#include <mach/ipc/ipc_kmsg.h>
#include <mach/ipc/ipc_thread.h>
#include <mach/ipc/ipc_notify.h>
#include <mach/ipc/ipc_object.h>
#include <mach/ipc/ipc_space.h>
#include <mach/ipc/ipc_port.h>
#include <mach/ipc/ipc_right.h>
#include <mach/ipc/ipc_hash.h>
#include <mach/ipc/ipc_table.h>
#include <mach/sched_prim.h>
#include <mach/ipc_kobject.h>
#include <mach/thread.h>
#pragma pack(4)
typedef struct
{
mach_msg_bits_t msgh_bits;
mach_msg_size_t msgh_size;
mach_port_name_t msgh_remote_port;
mach_port_name_t msgh_local_port;
mach_port_name_t msgh_voucher_port;
mach_msg_id_t msgh_id;
} mach_msg_legacy_header_t;
typedef struct
{
mach_msg_legacy_header_t header;
mach_msg_body_t body;
} mach_msg_legacy_base_t;
typedef struct
{
mach_port_name_t name;
mach_msg_size_t pad1;
uint32_t pad2 : 16;
mach_msg_type_name_t disposition : 8;
mach_msg_descriptor_type_t type : 8;
} mach_msg_legacy_port_descriptor_t;
typedef union
{
mach_msg_legacy_port_descriptor_t port;
mach_msg_ool_descriptor32_t out_of_line32;
mach_msg_ool_ports_descriptor32_t ool_ports32;
mach_msg_type_descriptor_t type;
} mach_msg_legacy_descriptor_t;
#pragma pack()
#define LEGACY_HEADER_SIZE_DELTA ((mach_msg_size_t)(sizeof(mach_msg_header_t) - sizeof(mach_msg_legacy_header_t)))
extern vm_size_t ipc_kmsg_max_space;
extern vm_size_t ipc_kmsg_max_vm_space;
extern vm_size_t ipc_kmsg_max_body_space;
extern vm_size_t msg_ool_size_small;
#define MSG_OOL_SIZE_SMALL msg_ool_size_small
#define DESC_SIZE_ADJUSTMENT ((mach_msg_size_t)(sizeof(mach_msg_ool_descriptor64_t) - \
sizeof(mach_msg_ool_descriptor32_t)))
/*
* Forward declarations
*/
void ipc_kmsg_clean(
ipc_kmsg_t kmsg);
void ipc_kmsg_clean_body(
ipc_kmsg_t kmsg __unused,
mach_msg_type_number_t number,
mach_msg_descriptor_t *desc);
void ipc_kmsg_clean_partial(
ipc_kmsg_t kmsg,
mach_msg_type_number_t number,
mach_msg_descriptor_t *desc,
vm_offset_t paddr,
vm_size_t length);
mach_msg_return_t ipc_kmsg_copyin_body(
ipc_kmsg_t kmsg,
ipc_space_t space,
vm_map_t map);
void ikm_cache_init(void);
/*
* Routine: ipc_kmsg_alloc
* Purpose:
* Allocate a kernel message structure.
* Conditions:
* Nothing locked.
*/
ipc_kmsg_t
ipc_kmsg_alloc(
mach_msg_size_t msg_and_trailer_size)
{
mach_msg_size_t max_expanded_size;
ipc_kmsg_t kmsg;
int mflags;
mach_msg_size_t min_msg_size = 0;
if (msg_and_trailer_size > MAX_TRAILER_SIZE)
min_msg_size = msg_and_trailer_size - MAX_TRAILER_SIZE;
#ifdef INVARIANTS
mflags = M_NOWAIT|M_ZERO;
#else
mflags = M_NOWAIT;
#endif
/* compare against implementation upper limit for the body */
if (min_msg_size > ipc_kmsg_max_body_space) {
return IKM_NULL;
}
if (min_msg_size > sizeof(mach_msg_base_t)) {
mach_msg_size_t max_desc = (mach_msg_size_t)(((min_msg_size - sizeof(mach_msg_base_t)) /
sizeof(mach_msg_ool_descriptor32_t)) *
DESC_SIZE_ADJUSTMENT);
/* make sure expansion won't cause wrap */
if (msg_and_trailer_size > MACH_MSG_SIZE_MAX - max_desc) {
printf("expansion would cause wrap! - return IKM_NULL\n");
return IKM_NULL;
}
max_expanded_size = msg_and_trailer_size + max_desc;
} else
max_expanded_size = msg_and_trailer_size;
/* fudge factor */
kmsg = malloc(ikm_plus_overhead(max_expanded_size) + MAX_TRAILER_SIZE, M_MACH_IPC_KMSG, mflags);
if (kmsg != IKM_NULL) {
ikm_init(kmsg, max_expanded_size);
ikm_set_header(kmsg, msg_and_trailer_size);
}
return (kmsg);
}
/*
* Routine: ipc_kmsg_enqueue
* Purpose:
* Enqueue a kmsg.
*/
void
ipc_kmsg_enqueue(
ipc_kmsg_queue_t queue,
ipc_kmsg_t kmsg)
{
ipc_kmsg_enqueue_macro(queue, kmsg);
}
/*
* Routine: ipc_kmsg_dequeue
* Purpose:
* Dequeue and return a kmsg.
*/
ipc_kmsg_t
ipc_kmsg_dequeue(
ipc_kmsg_queue_t queue)
{
ipc_kmsg_t first;
first = ipc_kmsg_queue_first(queue);
if (first != IKM_NULL)
ipc_kmsg_rmqueue_first_macro(queue, first);
return first;
}
/*
* Routine: ipc_kmsg_rmqueue
* Purpose:
* Pull a kmsg out of a queue.
*/
void
ipc_kmsg_rmqueue(
ipc_kmsg_queue_t queue,
ipc_kmsg_t kmsg)
{
ipc_kmsg_t next, prev;
assert(queue->ikmq_base != IKM_NULL);
next = kmsg->ikm_next;
prev = kmsg->ikm_prev;
if (next == kmsg) {
assert(prev == kmsg);
assert(queue->ikmq_base == kmsg);
queue->ikmq_base = IKM_NULL;
} else {
if (queue->ikmq_base == kmsg)
queue->ikmq_base = next;
next->ikm_prev = prev;
prev->ikm_next = next;
}
/* XXX Temporary debug logic */
kmsg->ikm_next = IKM_BOGUS;
kmsg->ikm_prev = IKM_BOGUS;
}
/*
* Routine: ipc_kmsg_queue_next
* Purpose:
* Return the kmsg following the given kmsg.
* (Or IKM_NULL if it is the last one in the queue.)
*/
ipc_kmsg_t
ipc_kmsg_queue_next(
ipc_kmsg_queue_t queue,
ipc_kmsg_t kmsg)
{
ipc_kmsg_t next;
assert(queue->ikmq_base != IKM_NULL);
next = kmsg->ikm_next;
if (queue->ikmq_base == next)
next = IKM_NULL;
return next;
}
/*
* Routine: ipc_kmsg_delayed_destroy
* Purpose:
* Enqueues a kernel message for deferred destruction.
* Returns:
* Boolean indicator that the caller is responsible to reap
* deferred messages.
*/
static boolean_t
ipc_kmsg_delayed_destroy(
ipc_kmsg_t kmsg)
{
ipc_kmsg_queue_t queue = &(current_thread()->ith_messages);
boolean_t first = ipc_kmsg_queue_empty(queue);
ipc_kmsg_enqueue(queue, kmsg);
return first;
}
/*
* Routine: ipc_kmsg_reap_delayed
* Purpose:
* Destroys messages from the per-thread
* deferred free queue.
* Conditions:
* No locks held.
*/
static void
ipc_kmsg_reap_delayed(void)
{
ipc_kmsg_queue_t queue = &(current_thread()->ith_messages);
ipc_kmsg_t kmsg;
/*
* must leave kmsg in queue while cleaning it to assure
* no nested calls recurse into here.
*/
while ((kmsg = ipc_kmsg_queue_first(queue)) != IKM_NULL) {
ipc_kmsg_clean(kmsg);
ipc_kmsg_rmqueue(queue, kmsg);
ipc_kmsg_free(kmsg);
}
}
/*
* Routine: ipc_kmsg_destroy
* Purpose:
* Destroys a kernel message. Releases all rights,
* references, and memory held by the message.
* Frees the message.
* Conditions:
* No locks held.
*/
void
ipc_kmsg_destroy(ipc_kmsg_t kmsg)
{
/*
* ipc_kmsg_clean can cause more messages to be destroyed.
* Curtail recursion by queueing messages. If a message
* is already queued, then this is a recursive call.
*/
if (ipc_kmsg_delayed_destroy(kmsg))
ipc_kmsg_reap_delayed();
}
/*
* Routine: ipc_kmsg_clean_body
* Purpose:
* Cleans the body of a kernel message.
* Releases all rights, references, and memory.
*
* Conditions:
* No locks held.
*/
void
ipc_kmsg_clean_body(
ipc_kmsg_t kmsg __unused,
mach_msg_type_number_t number,
mach_msg_descriptor_t *saddr)
{
mach_msg_type_number_t i;
if ( number == 0 )
return;
for (i = 0; i < number; i++, saddr++ ) {
switch (saddr->type.type) {
case MACH_MSG_PORT_DESCRIPTOR: {
mach_msg_port_descriptor_t *dsc;
dsc = &saddr->port;
/*
* Destroy port rights carried in the message
*/
if (!IO_VALID((ipc_object_t) dsc->name))
continue;
ipc_object_destroy((ipc_object_t) dsc->name, dsc->disposition);
break;
}
case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
case MACH_MSG_OOL_DESCRIPTOR : {
mach_msg_ool_descriptor_t *dsc;
dsc = &saddr->out_of_line;
/*
* Destroy memory carried in the message
*/
if (dsc->size == 0) {
assert(dsc->address == (void *) 0);
} else {
if (dsc->copy == MACH_MSG_PHYSICAL_COPY &&
dsc->size < MSG_OOL_SIZE_SMALL) {
free(dsc->address, M_MACH_VM);
} else {
vm_map_copy_discard((vm_map_copy_t) dsc->address);
}
}
break;
}
case MACH_MSG_OOL_PORTS_DESCRIPTOR : {
ipc_object_t *objects;
mach_msg_type_number_t j;
mach_msg_ool_ports_descriptor_t *dsc;
dsc = &saddr->ool_ports;
objects = (ipc_object_t *) dsc->address;
if (dsc->count == 0) {
break;
}
assert(objects != (ipc_object_t *) 0);
/* destroy port rights carried in the message */
for (j = 0; j < dsc->count; j++) {
ipc_object_t object = objects[j];
if (!IO_VALID(object))
continue;
ipc_object_destroy(object, dsc->disposition);
}
/* destroy memory carried in the message */
assert(dsc->count != 0);
KFREE((vm_offset_t) dsc->address,
(vm_size_t) dsc->count * sizeof(mach_port_name_t),
rt);
break;
}
default : {
printf("cleanup: don't understand this type of descriptor\n");
}
}
}
}
/*
* Routine: ipc_kmsg_clean_partial
* Purpose:
* Cleans a partially-acquired kernel message.
* number is the index of the type descriptor
* in the body of the message that contained the error.
* If dolast, the memory and port rights in this last
* type spec are also cleaned. In that case, number
* specifies the number of port rights to clean.
* Conditions:
* Nothing locked.
*/
void
ipc_kmsg_clean_partial(
ipc_kmsg_t kmsg,
mach_msg_type_number_t number,
mach_msg_descriptor_t *desc,
vm_offset_t paddr,
vm_size_t length)
{
ipc_object_t object;
mach_msg_bits_t mbits = kmsg->ikm_header->msgh_bits;
object = (ipc_object_t) kmsg->ikm_header->msgh_remote_port;
assert(IO_VALID(object));
ipc_object_destroy(object, MACH_MSGH_BITS_REMOTE(mbits));
object = (ipc_object_t) kmsg->ikm_header->msgh_local_port;
if (IO_VALID(object))
ipc_object_destroy(object, MACH_MSGH_BITS_LOCAL(mbits));
if (paddr) {
free((void *)paddr, M_MACH_TMP);
}
ipc_kmsg_clean_body(kmsg, number, desc);
}
/*
* Routine: ipc_kmsg_clean
* Purpose:
* Cleans a kernel message. Releases all rights,
* references, and memory held by the message.
* Conditions:
* No locks held.
*/
void
ipc_kmsg_clean(
ipc_kmsg_t kmsg)
{
ipc_object_t object;
mach_msg_bits_t mbits;
mbits = kmsg->ikm_header->msgh_bits;
object = (ipc_object_t) kmsg->ikm_header->msgh_remote_port;
if (IO_VALID(object))
ipc_object_destroy(object, MACH_MSGH_BITS_REMOTE(mbits));
object = (ipc_object_t) kmsg->ikm_header->msgh_local_port;
if (IO_VALID(object))
ipc_object_destroy(object, MACH_MSGH_BITS_LOCAL(mbits));
if (mbits & MACH_MSGH_BITS_COMPLEX) {
mach_msg_body_t *body;
body = (mach_msg_body_t *) (kmsg->ikm_header + 1);
ipc_kmsg_clean_body(kmsg, body->msgh_descriptor_count,
(mach_msg_descriptor_t *)(body + 1));
}
}
/*
* Routine: ipc_kmsg_free
* Purpose:
* Free a kernel message buffer.
* Conditions:
* Nothing locked.
*/
void
ipc_kmsg_free(ipc_kmsg_t kmsg)
{
#ifdef notyet
if (kmsg->ikm_size <= IKM_SAVED_MSG_SIZE)
uma_zfree(ipc_kmsg_zone, kmsg);
else
#endif
free(kmsg, M_MACH_IPC_KMSG);
}
/*
* Routine: ipc_kmsg_get
* Purpose:
* Allocates a kernel message buffer.
* Copies a user message to the message buffer.
* Conditions:
* Nothing locked.
* Returns:
* MACH_MSG_SUCCESS Acquired a message buffer.
* MACH_SEND_MSG_TOO_SMALL Message smaller than a header.
* MACH_SEND_MSG_TOO_SMALL Message size not long-word multiple.
* MACH_SEND_NO_BUFFER Couldn't allocate a message buffer.
* MACH_SEND_INVALID_DATA Couldn't copy message data.
*/
mach_msg_return_t
ipc_kmsg_get(
mach_msg_header_t *msg,
mach_msg_size_t size,
ipc_kmsg_t *kmsgp,
ipc_space_t space)
{
mach_msg_size_t msg_and_trailer_size;
ipc_kmsg_t kmsg;
mach_msg_max_trailer_t *trailer;
mach_msg_legacy_base_t legacy_base;
mach_msg_size_t len_copied;
task_t task;
caddr_t msg_addr = (caddr_t)msg;
legacy_base.body.msgh_descriptor_count = 0;
if ((size < sizeof(mach_msg_legacy_header_t)) || (size & 3))
return MACH_SEND_MSG_TOO_SMALL;
if (size > ipc_kmsg_max_body_space)
return MACH_SEND_TOO_LARGE;
if(size == sizeof(mach_msg_legacy_header_t))
len_copied = sizeof(mach_msg_legacy_header_t);
else
len_copied = sizeof(mach_msg_legacy_base_t);
if (copyinmsg((char *) msg, (char *) &legacy_base, len_copied))
return MACH_SEND_INVALID_DATA;
msg_addr += sizeof(legacy_base.header);
#if defined(__LP64__)
size += LEGACY_HEADER_SIZE_DELTA;
#endif
msg_and_trailer_size = size + MAX_TRAILER_SIZE;
if ((kmsg = ipc_kmsg_alloc(msg_and_trailer_size)) == IKM_NULL)
return MACH_SEND_NO_BUFFER;
kmsg->ikm_header->msgh_size = size;
kmsg->ikm_header->msgh_bits = legacy_base.header.msgh_bits;
kmsg->ikm_header->msgh_remote_port = CAST_MACH_NAME_TO_PORT(legacy_base.header.msgh_remote_port);
kmsg->ikm_header->msgh_local_port = CAST_MACH_NAME_TO_PORT(legacy_base.header.msgh_local_port);
kmsg->ikm_header->msgh_voucher_port = legacy_base.header.msgh_voucher_port;
kmsg->ikm_header->msgh_id = legacy_base.header.msgh_id;
/* ipc_kmsg_print(kmsg);*/
if (copyinmsg(msg_addr, (caddr_t)(kmsg->ikm_header + 1), size - (mach_msg_size_t)sizeof(mach_msg_header_t))) {
ipc_kmsg_free(kmsg);
return MACH_SEND_INVALID_DATA;
}
/*
* I reserve for the trailer the largest space (MAX_TRAILER_SIZE)
* However, the internal size field of the trailer (msgh_trailer_size)
* is initialized to the minimum (sizeof(mach_msg_trailer_t)), to optimize
* the cases where no implicit data is requested.
*/
trailer = (mach_msg_max_trailer_t *) (((caddr_t)(kmsg->ikm_header)) + size);
task = current_task();
trailer->msgh_trailer_type = MACH_MSG_TRAILER_FORMAT_0;
trailer->msgh_trailer_size = MACH_MSG_TRAILER_MINIMUM_SIZE;
trailer->msgh_sender = task->sec_token;
trailer->msgh_audit = task->audit_token;
*kmsgp = kmsg;
return MACH_MSG_SUCCESS;
}
/*
* Routine: ipc_kmsg_get_from_kernel
* Purpose:
* Allocates a kernel message buffer.
* Copies a kernel message to the message buffer.
* Only resource errors are allowed.
* Conditions:
* Nothing locked.
* Ports in header are ipc_port_t.
* Returns:
* MACH_MSG_SUCCESS Acquired a message buffer.
* MACH_SEND_NO_BUFFER Couldn't allocate a message buffer.
*/
extern mach_msg_return_t
ipc_kmsg_get_from_kernel(
mach_msg_header_t *msg,
mach_msg_size_t size,
ipc_kmsg_t *kmsgp)
{
ipc_kmsg_t kmsg;
mach_msg_size_t msg_and_trailer_size;
mach_msg_max_trailer_t *trailer;
assert(size >= sizeof(mach_msg_header_t));
assert((size & 3) == 0);
/* round up for ikm_cache */
msg_and_trailer_size = size + MAX_TRAILER_SIZE;
if (msg_and_trailer_size < IKM_SAVED_MSG_SIZE)
msg_and_trailer_size = IKM_SAVED_MSG_SIZE;
assert(IP_VALID((ipc_port_t) msg->msgh_remote_port));
if ((kmsg = ipc_kmsg_alloc(msg_and_trailer_size)) == NULL)
return MACH_SEND_NO_BUFFER;
(void) memcpy((void *) kmsg->ikm_header, (const void *) msg, size);
kmsg->ikm_header->msgh_size = size;
/*
* I reserve for the trailer the largest space (MAX_TRAILER_SIZE)
* However, the internal size field of the trailer (msgh_trailer_size)
* is initialized to the minimum (sizeof(mach_msg_trailer_t)), to optimize
* the cases where no implicit data is requested.
*/
trailer = (mach_msg_max_trailer_t *) ((vm_offset_t)kmsg->ikm_header + size);
trailer->msgh_sender = KERNEL_SECURITY_TOKEN;
trailer->msgh_audit = KERNEL_AUDIT_TOKEN;
trailer->msgh_trailer_type = MACH_MSG_TRAILER_FORMAT_0;
trailer->msgh_trailer_size = MACH_MSG_TRAILER_MINIMUM_SIZE;
*kmsgp = kmsg;
return MACH_MSG_SUCCESS;
}
/*
* Routine: ipc_kmsg_put
* Purpose:
* Copies a message buffer to a user message.
* Copies only the specified number of bytes.
* Frees the message buffer.
* Conditions:
* Nothing locked. The message buffer must have clean
* header fields.
* Returns:
* MACH_MSG_SUCCESS Copied data out of message buffer.
* MACH_RCV_INVALID_DATA Couldn't copy to user message.
*/
mach_msg_return_t
ipc_kmsg_put(
mach_msg_header_t *msg,
ipc_kmsg_t kmsg,
mach_msg_size_t size)
{
mach_msg_return_t mr;
ikm_check_initialized(kmsg, kmsg->ikm_size);
MDPRINTF(("doing kmsg_put size=%d to addr=%p", size, msg));
#if defined(__LP64__)
if (current_task() != kernel_task) { /* don't if receiver expects fully-cooked in-kernel msg; ux_exception */
mach_msg_legacy_header_t *legacy_header =
(mach_msg_legacy_header_t *)((vm_offset_t)(kmsg->ikm_header) + LEGACY_HEADER_SIZE_DELTA);
mach_msg_bits_t bits = kmsg->ikm_header->msgh_bits;
mach_msg_size_t msg_size = kmsg->ikm_header->msgh_size;
mach_port_name_t remote_port = CAST_MACH_PORT_TO_NAME(kmsg->ikm_header->msgh_remote_port);
mach_port_name_t local_port = CAST_MACH_PORT_TO_NAME(kmsg->ikm_header->msgh_local_port);
mach_port_name_t voucher_port = kmsg->ikm_header->msgh_voucher_port;
mach_msg_id_t id = kmsg->ikm_header->msgh_id;
legacy_header->msgh_id = id;
legacy_header->msgh_local_port = local_port;
legacy_header->msgh_remote_port = remote_port;
legacy_header->msgh_voucher_port = voucher_port;
legacy_header->msgh_size = msg_size - LEGACY_HEADER_SIZE_DELTA;
legacy_header->msgh_bits = bits;
MDPRINTF((" msg_size=%d", msg_size));
size -= LEGACY_HEADER_SIZE_DELTA;
kmsg->ikm_header = (mach_msg_header_t *)legacy_header;
}
#endif
MDPRINTF(("\n"));
if (copyoutmsg((const char *) kmsg->ikm_header, (char *) msg, size))
mr = MACH_RCV_INVALID_DATA;
else
mr = MACH_MSG_SUCCESS;
ikm_free(kmsg);
return mr;
}
extern void kdb_backtrace(void);
/*
* Routine: ipc_kmsg_put_to_kernel
* Purpose:
* Copies a message buffer to a kernel message.
* Frees the message buffer.
* No errors allowed.
* Conditions:
* Nothing locked.
*/
void
ipc_kmsg_put_to_kernel(
mach_msg_header_t *msg,
ipc_kmsg_t kmsg,
mach_msg_size_t size)
{
(void) memcpy((void *) msg, (const void *) kmsg->ikm_header, size);
ikm_free(kmsg);
}
/*
* Routine: ipc_kmsg_copyin_header
* Purpose:
* "Copy-in" port rights in the header of a message.
* Operates atomically; if it doesn't succeed the
* message header and the space are left untouched.
* If it does succeed the remote/local port fields
* contain object pointers instead of port names,
* and the bits field is updated. The destination port
* will be a valid port pointer.
*
* The notify argument implements the MACH_SEND_CANCEL option.
* If it is not MACH_PORT_NULL, it should name a receive right.
* If the processing of the destination port would generate
* a port-deleted notification (because the right for the
* destination port is destroyed and it had a request for
* a dead-name notification registered), and the port-deleted
* notification would be sent to the named receive right,
* then it isn't sent and the send-once right for the notify
* port is quietly destroyed.
*
* Conditions:
* Nothing locked.
* Returns:
* MACH_MSG_SUCCESS Successful copyin.
* MACH_SEND_INVALID_HEADER
* Illegal value in the message header bits.
* MACH_SEND_INVALID_DEST The space is dead.
* MACH_SEND_INVALID_NOTIFY
* Notify is non-null and doesn't name a receive right.
* (Either KERN_INVALID_NAME or KERN_INVALID_RIGHT.)
* MACH_SEND_INVALID_DEST Can't copyin destination port.
* (Either KERN_INVALID_NAME or KERN_INVALID_RIGHT.)
* MACH_SEND_INVALID_REPLY Can't copyin reply port.
* (Either KERN_INVALID_NAME or KERN_INVALID_RIGHT.)
*/
mach_msg_return_t
ipc_kmsg_copyin_header(
ipc_kmsg_t kmsg,
ipc_space_t space,
mach_port_name_t notify_name)
{
mach_msg_header_t *msg = kmsg->ikm_header;
mach_msg_bits_t mbits = msg->msgh_bits &~ MACH_MSGH_BITS_CIRCULAR;
mach_msg_type_name_t dest_type = MACH_MSGH_BITS_REMOTE(mbits);
mach_msg_type_name_t reply_type = MACH_MSGH_BITS_LOCAL(mbits);
ipc_object_t dest_port, reply_port;
ipc_port_t dest_soright, reply_soright;
ipc_port_t notify_port;
kern_return_t kr;
dest_port = reply_port = NULL;
dest_soright = reply_soright = notify_port = NULL;
/* Here we know that the value is coming from userspace so the cast is safe
* because we've been passed a 32-bit name
*/
mach_port_name_t dest_name = CAST_MACH_PORT_TO_NAME(msg->msgh_remote_port);
mach_port_name_t reply_name = CAST_MACH_PORT_TO_NAME(msg->msgh_local_port);
if (!MACH_MSG_TYPE_PORT_ANY_SEND(dest_type))
return MACH_SEND_INVALID_HEADER;
if ((reply_type == 0) ?
(reply_name != MACH_PORT_NAME_NULL) :
!MACH_MSG_TYPE_PORT_ANY_SEND(reply_type))
return MACH_SEND_INVALID_HEADER;
is_write_lock(space);
if (!space->is_active) {
printf("space not active");
goto invalid_dest;
}
if (notify_name != MACH_PORT_NAME_NULL) {
ipc_entry_t entry;
if (((entry = ipc_entry_lookup(space, notify_name)) == IE_NULL) ||
((entry->ie_bits & MACH_PORT_TYPE_RECEIVE) == 0)) {
is_write_unlock(space);
return MACH_SEND_INVALID_NOTIFY;
}
notify_port = (ipc_port_t) entry->ie_object;
}
if (dest_name == reply_name) {
ipc_entry_t entry;
mach_port_name_t name = dest_name;
/*
* Destination and reply ports are the same!
* This is a little tedious to make atomic, because
* there are 25 combinations of dest_type/reply_type.
* However, most are easy. If either is move-sonce,
* then there must be an error. If either are
* make-send or make-sonce, then we must be looking
* at a receive right so the port can't die.
* The hard cases are the combinations of
* copy-send and make-send.
*/
entry = ipc_entry_lookup(space, name);
if (entry == IE_NULL) {
if (mach_debug_enable)
printf("name=%d not found\n", name);
goto invalid_dest;
}
assert(reply_type != 0); /* because name not null */
if (!ipc_right_copyin_check(space, name, entry, reply_type))
goto invalid_reply;
if ((dest_type == MACH_MSG_TYPE_MOVE_SEND_ONCE) ||
(reply_type == MACH_MSG_TYPE_MOVE_SEND_ONCE)) {
/*
* Why must there be an error? To get a valid
* destination, this entry must name a live
* port (not a dead name or dead port). However
* a successful move-sonce will destroy a
* live entry. Therefore the other copyin,
* whatever it is, would fail. We've already
* checked for reply port errors above,
* so report a destination error.
*/
if (mach_debug_enable)
printf("dest_type or reply_type is SEND_ONCE\n");
goto invalid_dest;
} else if ((dest_type == MACH_MSG_TYPE_MAKE_SEND) ||
(dest_type == MACH_MSG_TYPE_MAKE_SEND_ONCE) ||
(reply_type == MACH_MSG_TYPE_MAKE_SEND) ||
(reply_type == MACH_MSG_TYPE_MAKE_SEND_ONCE)) {
kr = ipc_right_copyin(space, name, entry,
dest_type, FALSE,
&dest_port, &dest_soright);
if (kr != KERN_SUCCESS) {
if (mach_debug_enable)
printf("ipc_right_copyin failed kr=%d %s:%d\n", kr, __FILE__, __LINE__);
goto invalid_dest;
}
/*
* Either dest or reply needs a receive right.
* We know the receive right is there, because
* of the copyin_check and copyin calls. Hence
* the port is not in danger of dying. If dest
* used the receive right, then the right needed
* by reply (and verified by copyin_check) will
* still be there.
*/
assert(IO_VALID(dest_port));
assert(entry->ie_bits & MACH_PORT_TYPE_RECEIVE);
assert(dest_soright == IP_NULL);
kr = ipc_right_copyin(space, name, entry,
reply_type, TRUE,
&reply_port, &reply_soright);
assert(kr == KERN_SUCCESS);
assert(reply_port == dest_port);
assert(entry->ie_bits & MACH_PORT_TYPE_RECEIVE);
assert(reply_soright == IP_NULL);
} else if ((dest_type == MACH_MSG_TYPE_COPY_SEND) &&
(reply_type == MACH_MSG_TYPE_COPY_SEND)) {
/*
* To make this atomic, just do one copy-send,
* and dup the send right we get out.
*/
kr = ipc_right_copyin(space, name, entry,
dest_type, FALSE,
&dest_port, &dest_soright);
if (kr != KERN_SUCCESS) {
if (mach_debug_enable)
printf("ipc_right_copyin failed kr=%d %s:%d\n", kr, __FILE__, __LINE__);
goto invalid_dest;
}
assert(entry->ie_bits & MACH_PORT_TYPE_SEND);
assert(dest_soright == IP_NULL);
/*
* It's OK if the port we got is dead now,
* so reply_port is IP_DEAD, because the msg
* won't go anywhere anyway.
*/
reply_port = (ipc_object_t)
ipc_port_copy_send((ipc_port_t) dest_port);
reply_soright = IP_NULL;
} else if ((dest_type == MACH_MSG_TYPE_MOVE_SEND) &&
(reply_type == MACH_MSG_TYPE_MOVE_SEND)) {
/*
* This is an easy case. Just use our
* handy-dandy special-purpose copyin call
* to get two send rights for the price of one.
*/
kr = ipc_right_copyin_two(space, name, entry,
&dest_port, &dest_soright);
if (kr != KERN_SUCCESS) {
printf("ipc_right_copyin_two failed kr=%d %s:%d\n", kr, __FILE__, __LINE__);
goto invalid_dest;
}
/* the entry might need to be deallocated */
if (IE_BITS_TYPE(entry->ie_bits) == MACH_PORT_TYPE_NONE) {
is_write_unlock(space);
ipc_entry_close(space, name);
is_write_lock(space);
}
reply_port = dest_port;
reply_soright = IP_NULL;
} else {
ipc_port_t soright;
assert(((dest_type == MACH_MSG_TYPE_COPY_SEND) &&
(reply_type == MACH_MSG_TYPE_MOVE_SEND)) ||
((dest_type == MACH_MSG_TYPE_MOVE_SEND) &&
(reply_type == MACH_MSG_TYPE_COPY_SEND)));
/*
* To make this atomic, just do a move-send,
* and dup the send right we get out.
*/
kr = ipc_right_copyin(space, name, entry,
MACH_MSG_TYPE_MOVE_SEND, FALSE,
&dest_port, &soright);
if (kr != KERN_SUCCESS) {
printf("ipc_right_copyin failed kr=%d %s:%d\n", kr, __FILE__, __LINE__);
goto invalid_dest;
}
/* the entry might need to be deallocated */
if (IE_BITS_TYPE(entry->ie_bits) == MACH_PORT_TYPE_NONE) {
is_write_unlock(space);
ipc_entry_close(space, name);
is_write_lock(space);
}
/*
* It's OK if the port we got is dead now,
* so reply_port is IP_DEAD, because the msg
* won't go anywhere anyway.
*/
reply_port = (ipc_object_t)
ipc_port_copy_send((ipc_port_t) dest_port);
if (dest_type == MACH_MSG_TYPE_MOVE_SEND) {
dest_soright = soright;
reply_soright = IP_NULL;
} else {
dest_soright = IP_NULL;
reply_soright = soright;
}
}
} else if (!MACH_PORT_NAME_VALID(reply_name)) {
ipc_entry_t entry;
/*
* No reply port! This is an easy case
* to make atomic. Just copyin the destination.
*/
entry = ipc_entry_lookup(space, dest_name);
if (entry == IE_NULL) {
if (mach_debug_enable)
printf("ipc_entry_lookup failed on dest_name=%d\n", dest_name);
goto invalid_dest;
}
kr = ipc_right_copyin(space, dest_name, entry,
dest_type, FALSE,
&dest_port, &dest_soright);
if (kr != KERN_SUCCESS) {
if (mach_debug_enable)
printf("ipc_right_copyin failed kr=%d %s:%d\n", kr, __FILE__, __LINE__);
goto invalid_dest;
}
/* the entry might need to be deallocated */
if (IE_BITS_TYPE(entry->ie_bits) == MACH_PORT_TYPE_NONE) {
is_write_unlock(space);
ipc_entry_close(space, dest_name);
is_write_lock(space);
}
reply_port = (ipc_object_t)CAST_MACH_NAME_TO_PORT(reply_name);
reply_soright = IP_NULL;
} else {
ipc_entry_t dest_entry, reply_entry;
ipc_port_t saved_reply;
/*
* This is the tough case to make atomic.
* The difficult problem is serializing with port death.
* At the time we copyin dest_port, it must be alive.
* If reply_port is alive when we copyin it, then
* we are OK, because we serialize before the death
* of both ports. Assume reply_port is dead at copyin.
* Then if dest_port dies/died after reply_port died,
* we are OK, because we serialize between the death
* of the two ports. So the bad case is when dest_port
* dies after its copyin, reply_port dies before its
* copyin, and dest_port dies before reply_port. Then
* the copyins operated as if dest_port was alive
* and reply_port was dead, which shouldn't have happened
* because they died in the other order.
*
* We handle the bad case by undoing the copyins
* (which is only possible because the ports are dead)
* and failing with MACH_SEND_INVALID_DEST, serializing
* after the death of the ports.
*
* Note that it is easy for a user task to tell if
* a copyin happened before or after a port died.
* For example, suppose both dest and reply are
* send-once rights (types are both move-sonce) and
* both rights have dead-name requests registered.
* If a port dies before copyin, a dead-name notification
* is generated and the dead name's urefs are incremented,
* and if the copyin happens first, a port-deleted
* notification is generated.
*
* Note that although the entries are different,
* dest_port and reply_port might still be the same.
*/
dest_entry = ipc_entry_lookup(space, dest_name);
if (dest_entry == IE_NULL) {
printf("ipc_entry_lookup failed on %d %s:%d\n", dest_name, __FILE__, __LINE__);
goto invalid_dest;
}
reply_entry = ipc_entry_lookup(space, reply_name);
if (reply_entry == IE_NULL)
goto invalid_reply;
assert(dest_entry != reply_entry); /* names are not equal */
assert(reply_type != 0); /* because reply_name not null */
if (ipc_right_copyin_check(space, reply_name, reply_entry,
reply_type) == FALSE)
goto invalid_reply;
kr = ipc_right_copyin(space, dest_name, dest_entry,
dest_type, FALSE,
&dest_port, &dest_soright);
if (kr != KERN_SUCCESS) {
printf("ipc_right_copyin failed kr=%d %s:%d\n", kr, __FILE__, __LINE__);
goto invalid_dest;
}
assert(IO_VALID(dest_port));
saved_reply = (ipc_port_t) reply_entry->ie_object;
/* might be IP_NULL, if this is a dead name */
if (saved_reply != IP_NULL)
ipc_port_reference(saved_reply);
kr = ipc_right_copyin(space, reply_name, reply_entry,
reply_type, TRUE,
&reply_port, &reply_soright);
assert(kr == KERN_SUCCESS);
if ((saved_reply != IP_NULL) && (reply_port == IO_DEAD)) {
ipc_port_t dest = (ipc_port_t) dest_port;
ipc_port_timestamp_t timestamp;
boolean_t must_undo;
/*
* The reply port died before copyin.
* Check if dest port died before reply.
*/
ip_lock(saved_reply);
assert(!ip_active(saved_reply));
timestamp = saved_reply->ip_timestamp;
ip_unlock(saved_reply);
ip_lock(dest);
must_undo = (!ip_active(dest) &&
IP_TIMESTAMP_ORDER(dest->ip_timestamp,
timestamp));
ip_unlock(dest);
if (must_undo) {
/*
* Our worst nightmares are realized.
* Both destination and reply ports
* are dead, but in the wrong order,
* so we must undo the copyins and
* possibly generate a dead-name notif.
*/
ipc_right_copyin_undo(
space, dest_name, dest_entry,
dest_type, dest_port,
dest_soright);
/* dest_entry may be deallocated now */
ipc_right_copyin_undo(
space, reply_name, reply_entry,
reply_type, reply_port,
reply_soright);
/* reply_entry may be deallocated now */
is_write_unlock(space);
if (dest_soright != IP_NULL)
ipc_notify_dead_name(dest_soright,
dest_name);
assert(reply_soright == IP_NULL);
ipc_port_release(saved_reply);
printf("%s:%d\n", __FUNCTION__, __LINE__);
return MACH_SEND_INVALID_DEST;
}
}
/* the entries might need to be deallocated */
if (IE_BITS_TYPE(reply_entry->ie_bits) == MACH_PORT_TYPE_NONE) {
is_write_unlock(space);
ipc_entry_close(space, reply_name);
is_write_lock(space);
}
if (IE_BITS_TYPE(dest_entry->ie_bits) == MACH_PORT_TYPE_NONE) {
is_write_unlock(space);
ipc_entry_close(space, dest_name);
is_write_lock(space);
}
if (saved_reply != IP_NULL)
ipc_port_release(saved_reply);
}
/*
* At this point, dest_port, reply_port,
* dest_soright, reply_soright are all initialized.
* Any defunct entries have been deallocated.
* The space is still write-locked, and we need to
* make the MACH_SEND_CANCEL check. The notify_port pointer
* is still usable, because the copyin code above won't ever
* deallocate a receive right, so its entry still exists
* and holds a ref. Note notify_port might even equal
* dest_port or reply_port.
*/
if ((notify_name != MACH_PORT_NAME_NULL) &&
(dest_soright == notify_port)) {
ipc_port_release_sonce(dest_soright);
dest_soright = IP_NULL;
}
is_write_unlock(space);
if (dest_soright != IP_NULL)
ipc_notify_port_deleted(dest_soright, dest_name);
if (reply_soright != IP_NULL)
ipc_notify_port_deleted(reply_soright, reply_name);
dest_type = ipc_object_copyin_type(dest_type);
reply_type = ipc_object_copyin_type(reply_type);
msg->msgh_bits = (MACH_MSGH_BITS_OTHER(mbits) |
MACH_MSGH_BITS(dest_type, reply_type));
msg->msgh_remote_port = (mach_port_t) dest_port;
msg->msgh_local_port = (mach_port_t) reply_port;
return MACH_MSG_SUCCESS;
invalid_dest:
is_write_unlock(space);
if (mach_debug_enable) {
kdb_backtrace();
printf("%s:%d - MACH_SEND_INVALID_DEST dest_name: 0x%x reply_name: 0x%x \n", curproc->p_comm, curproc->p_pid, dest_name, reply_name);
}
return MACH_SEND_INVALID_DEST;
invalid_reply:
is_write_unlock(space);
if (mach_debug_enable)
printf("%s:%d - MACH_SEND_INVALID_REPLY dest_name: 0x%x reply_name: 0x%x \n", curproc->p_comm, curproc->p_pid, dest_name, reply_name);
return MACH_SEND_INVALID_REPLY;
}
mach_msg_descriptor_t *ipc_kmsg_copyin_port_descriptor(
volatile mach_msg_port_descriptor_t *dsc,
mach_msg_legacy_port_descriptor_t *user_dsc,
ipc_space_t space,
ipc_object_t dest,
ipc_kmsg_t kmsg,
mach_msg_return_t *mr);
mach_msg_descriptor_t *
ipc_kmsg_copyin_port_descriptor(
volatile mach_msg_port_descriptor_t *dsc,
mach_msg_legacy_port_descriptor_t *user_dsc_in,
ipc_space_t space,
ipc_object_t dest,
ipc_kmsg_t kmsg,
mach_msg_return_t *mr)
{
volatile mach_msg_legacy_port_descriptor_t *user_dsc = user_dsc_in;
mach_msg_type_name_t user_disp;
mach_msg_type_name_t result_disp;
mach_port_name_t name;
ipc_object_t object;
user_disp = user_dsc->disposition;
result_disp = ipc_object_copyin_type(user_disp);
name = (mach_port_name_t)user_dsc->name;
if (MACH_PORT_NAME_VALID(name)) {
kern_return_t kr = ipc_object_copyin(space, name, user_disp, &object);
if (kr != KERN_SUCCESS) {
*mr = MACH_SEND_INVALID_RIGHT;
if (mach_debug_enable)
printf("MACH_SEND_INVALID_RIGHT: %s:%s:%d\n", __FUNCTION__, __FILE__, __LINE__);
return NULL;
}
if ((result_disp == MACH_MSG_TYPE_PORT_RECEIVE) &&
ipc_port_check_circularity((ipc_port_t) object,
(ipc_port_t) dest)) {
kmsg->ikm_header->msgh_bits |= MACH_MSGH_BITS_CIRCULAR;
}
dsc->name = (ipc_port_t) object;
} else {
dsc->name = CAST_MACH_NAME_TO_PORT(name);
}
dsc->disposition = result_disp;
dsc->type = MACH_MSG_PORT_DESCRIPTOR;
return (mach_msg_descriptor_t *)(user_dsc_in+1);
}
mach_msg_descriptor_t * ipc_kmsg_copyin_ool_descriptor(
mach_msg_ool_descriptor_t *dsc,
mach_msg_descriptor_t *user_dsc,
int is_64bit,
vm_offset_t *paddr,
vm_map_copy_t *copy,
vm_size_t *space_needed,
vm_map_t map,
mach_msg_return_t *mr);
mach_msg_descriptor_t *
ipc_kmsg_copyin_ool_descriptor(
mach_msg_ool_descriptor_t *dsc,
mach_msg_descriptor_t *user_dsc,
int is_64bit __unused,
vm_offset_t *paddr __unused,
vm_map_copy_t *copy,
vm_size_t *space_needed __unused,
vm_map_t map,
mach_msg_return_t *mr)
{
vm_size_t length;
boolean_t dealloc;
vm_offset_t addr;
mach_msg_copy_options_t copy_options;
mach_msg_descriptor_type_t dsc_type;
mach_msg_ool_descriptor_t *user_ool_dsc;
user_ool_dsc = (mach_msg_ool_descriptor_t *)user_dsc;
addr = (vm_offset_t)user_ool_dsc->address;
length = user_ool_dsc->size;
dealloc = user_ool_dsc->deallocate;
copy_options = user_ool_dsc->copy;
dsc_type = user_ool_dsc->type;
user_dsc = (mach_msg_descriptor_t *)(user_ool_dsc + 1);
dsc->size = length;
dsc->deallocate = dealloc;
dsc->copy = copy_options;
dsc->type = dsc_type;
if (length == 0) {
dsc->address = NULL;
}
else {
/*
* Make a virtual copy of the of the data if requested
* or if a physical copy was requested but the source
* is being deallocated. This is an invalid
* path if RT.
*/
if (vm_map_copyin(map, addr, length,
dealloc, copy) != KERN_SUCCESS) {
*mr = MACH_SEND_INVALID_MEMORY;
return NULL;
}
dsc->address = (void *) *copy;
}
return user_dsc;
}
mach_msg_descriptor_t * ipc_kmsg_copyin_ool_ports_descriptor(
mach_msg_ool_ports_descriptor_t *dsc,
mach_msg_descriptor_t *user_dsc,
int is_64bit,
vm_map_t map,
ipc_space_t space,
ipc_object_t dest,
ipc_kmsg_t kmsg,
mach_msg_return_t *mr);
mach_msg_descriptor_t *
ipc_kmsg_copyin_ool_ports_descriptor(
mach_msg_ool_ports_descriptor_t *dsc,
mach_msg_descriptor_t *user_dsc,
int is_64bit,
vm_map_t map,
ipc_space_t space,
ipc_object_t dest,
ipc_kmsg_t kmsg,
mach_msg_return_t *mr)
{
vm_size_t plength, pnlength;
kern_return_t kr;
boolean_t dealloc;
vm_offset_t addr;
mach_msg_copy_options_t copy_options;
mach_msg_descriptor_type_t typename;
mach_msg_type_name_t user_disp, result_disp;
ipc_object_t *objects;
void *data;
int count, j, iskernel;
mach_msg_ool_ports_descriptor_t *user_ool_dsc;
user_ool_dsc = (mach_msg_ool_ports_descriptor_t *)user_dsc;
addr = (vm_offset_t) user_ool_dsc->address;
count = user_ool_dsc->count;
dealloc = user_ool_dsc->deallocate;
copy_options = user_ool_dsc->copy;
/* this is really the type SEND, SEND_ONCE, etc. */
typename = user_ool_dsc->type;
user_disp = user_ool_dsc->disposition;
iskernel = (kmsg->ikm_header->msgh_remote_port->ip_receiver == ipc_space_kernel);
user_dsc = (mach_msg_descriptor_t *)(user_ool_dsc + 1);
dsc->deallocate = dealloc;
dsc->copy = copy_options;
dsc->type = typename;
dsc->count = count;
dsc->address = NULL;
result_disp = ipc_object_copyin_type(user_disp);
dsc->disposition = result_disp;
if (count == 0)
return user_dsc;
if (count > (INT_MAX / sizeof(mach_port_t))) {
*mr = MACH_SEND_TOO_LARGE;
return NULL;
}
plength = count * sizeof(mach_port_t);
pnlength = count * sizeof(mach_port_name_t);
data = malloc(plength, M_MACH_TMP, M_NOWAIT);
if (data == NULL) {
*mr = MACH_SEND_NO_BUFFER;
return NULL;
}
#ifdef __LP64__
mach_port_name_t *names = &((mach_port_name_t *)data)[count];
#else
mach_port_name_t *names = ((mach_port_name_t *)data);
#endif
if (copyinmap(map, addr, names, pnlength)) {
free(data, M_MACH_TMP);
*mr = MACH_SEND_INVALID_MEMORY;
return (NULL);
}
if (dsc->deallocate) {
(void) mach_vm_deallocate(map, addr, plength);
}
dsc->address = (void *) data;
objects = (ipc_object_t *) data;
for (j = 0; j < count; j++) {
mach_port_name_t name;
ipc_object_t object;
name = names[j];
if (!MACH_PORT_NAME_VALID(name)) {
objects[j] = (ipc_object_t)CAST_MACH_NAME_TO_PORT(name);
continue;
}
kr = ipc_object_copyin(space, name, user_disp, &object);
if (kr != KERN_SUCCESS) {
int k;
printf("right: %d failed %x user_disp: %d\n", name, kr, user_disp);
for(k = 0; k < j; k++) {
object = objects[k];
if (IPC_OBJECT_VALID(object))
ipc_object_destroy(object, result_disp);
}
free(data, M_MACH_TMP);
dsc->address = NULL;
*mr = MACH_SEND_INVALID_RIGHT;
return NULL;
}
if ((dsc->disposition == MACH_MSG_TYPE_PORT_RECEIVE) &&
ipc_port_check_circularity(
(ipc_port_t) object,
(ipc_port_t) dest))
kmsg->ikm_header->msgh_bits |= MACH_MSGH_BITS_CIRCULAR;
objects[j] = object;
}
return user_dsc;
}
/*
* Routine: ipc_kmsg_copyin_body
* Purpose:
* "Copy-in" port rights and out-of-line memory
* in the message body.
*
* In all failure cases, the message is left holding
* no rights or memory. However, the message buffer
* is not deallocated. If successful, the message
* contains a valid destination port.
* Conditions:
* Nothing locked.
* Returns:
* MACH_MSG_SUCCESS Successful copyin.
* MACH_SEND_INVALID_MEMORY Can't grab out-of-line memory.
* MACH_SEND_INVALID_RIGHT Can't copyin port right in body.
* MACH_SEND_INVALID_TYPE Bad type specification.
* MACH_SEND_MSG_TOO_SMALL Body is too small for types/data.
* MACH_SEND_INVALID_RT_OOL_SIZE OOL Buffer too large for RT
* MACH_MSG_INVALID_RT_DESCRIPTOR Dealloc and RT are incompatible
*/
#define KERN_DESC_SIZE 16
mach_msg_return_t
ipc_kmsg_copyin_body(
ipc_kmsg_t kmsg,
ipc_space_t space,
vm_map_t map)
{
ipc_object_t dest;
mach_msg_body_t *body;
mach_msg_descriptor_t *naddr, *daddr;
mach_msg_descriptor_t *user_addr, *kern_addr;
vm_map_copy_t copy = VM_MAP_COPY_NULL;
boolean_t complex;
int i, dsc_count, is_task_64bit;
vm_size_t space_needed = 0;
vm_offset_t paddr = 0;
kern_return_t mr = 0;
vm_size_t size, descriptor_size = 0;
/*
* Determine if the target is a kernel port.
*/
dest = (ipc_object_t) kmsg->ikm_header->msgh_remote_port;
body = (mach_msg_body_t *) (kmsg->ikm_header + 1);
naddr = (mach_msg_descriptor_t *) (body + 1);
dsc_count = body->msgh_descriptor_count;
if (dsc_count == 0)
return MACH_MSG_SUCCESS;
/*
* Make an initial pass to determine kernal VM space requirements for
* physical copies.
*/
#if defined(__LP64__)
is_task_64bit = 1;
#else
is_task_64bit = 0;
#endif
for (i = 0; i < dsc_count; i++) {
daddr = naddr;
#if defined(__LP64__)
switch (daddr->type.type) {
case MACH_MSG_OOL_DESCRIPTOR:
case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
case MACH_MSG_OOL_PORTS_DESCRIPTOR:
descriptor_size += 16;
naddr = (mach_msg_descriptor_t *)((vm_offset_t)daddr + 16);
break;
default:
descriptor_size += 12;
naddr = (mach_msg_descriptor_t *)((vm_offset_t)daddr + 12);
break;
}
#else
descriptor_size += 12;
naddr = (mach_msg_descriptor_t *)((vm_offset_t)daddr + 12);
#endif
/* make sure the message does not ask for more msg descriptors
* than the message can hold.
*/
if (naddr > (mach_msg_descriptor_t *)
((vm_offset_t)kmsg->ikm_header + kmsg->ikm_header->msgh_size)) {
ipc_kmsg_clean_partial(kmsg, 0, NULL, 0, 0);
mr = MACH_SEND_MSG_TOO_SMALL;
goto out;
}
switch (daddr->type.type) {
case MACH_MSG_OOL_DESCRIPTOR:
case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
#if defined(__LP64__)
size = ((mach_msg_ool_descriptor64_t *)daddr)->size;
#else
size = daddr->out_of_line.size;
#endif
if (daddr->out_of_line.copy != MACH_MSG_PHYSICAL_COPY &&
daddr->out_of_line.copy != MACH_MSG_VIRTUAL_COPY) {
ipc_kmsg_clean_partial(kmsg, 0, NULL, 0, 0);
mr = MACH_SEND_INVALID_TYPE;
goto out;
}
if ((size >= MSG_OOL_SIZE_SMALL) &&
(daddr->out_of_line.copy == MACH_MSG_PHYSICAL_COPY) &&
!(daddr->out_of_line.deallocate)) {
space_needed += size;
if (space_needed > ipc_kmsg_max_vm_space) {
ipc_kmsg_clean_partial(kmsg, 0, NULL, 0, 0);
mr = MACH_MSG_VM_KERNEL;
goto out;
}
}
}
}
if (space_needed > 8*1024*1024 /* XXX come up with a better define */) {
ipc_kmsg_clean_partial(kmsg, 0, NULL, 0, 0);
mr = MACH_MSG_VM_KERNEL;
goto out;
}
/* user_addr = just after base as it was copied in */
user_addr = (mach_msg_descriptor_t *)((vm_offset_t)kmsg->ikm_header + sizeof(mach_msg_base_t));
/* Shift the mach_msg_base_t down to make room for dsc_count*16bytes of descriptors */
if(descriptor_size != KERN_DESC_SIZE*dsc_count) {
vm_offset_t dsc_adjust = KERN_DESC_SIZE*dsc_count - descriptor_size;
memmove((char *)(((vm_offset_t)kmsg->ikm_header) - dsc_adjust), kmsg->ikm_header, sizeof(mach_msg_base_t));
kmsg->ikm_header = (mach_msg_header_t *)((vm_offset_t)kmsg->ikm_header - dsc_adjust);
/* Update the message size for the larger in-kernel representation */
kmsg->ikm_header->msgh_size += (mach_msg_size_t)dsc_adjust;
}
/* kern_addr = just after base after it has been (conditionally) moved */
kern_addr = (mach_msg_descriptor_t *)((vm_offset_t)kmsg->ikm_header + sizeof(mach_msg_base_t));
/* handle the OOL regions and port descriptors. */
for(i=0;i<dsc_count;i++) {
switch (user_addr->type.type) {
case MACH_MSG_PORT_DESCRIPTOR:
user_addr = ipc_kmsg_copyin_port_descriptor((mach_msg_port_descriptor_t *)kern_addr,
(mach_msg_legacy_port_descriptor_t *)user_addr, space, dest, kmsg, &mr);
kern_addr++;
complex = TRUE;
break;
case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
case MACH_MSG_OOL_DESCRIPTOR:
user_addr = ipc_kmsg_copyin_ool_descriptor((mach_msg_ool_descriptor_t *)kern_addr,
user_addr, is_task_64bit, &paddr, ©, &space_needed, map, &mr);
kern_addr++;
complex = TRUE;
break;
case MACH_MSG_OOL_PORTS_DESCRIPTOR:
user_addr = ipc_kmsg_copyin_ool_ports_descriptor((mach_msg_ool_ports_descriptor_t *)kern_addr,
user_addr, is_task_64bit, map, space, dest, kmsg, &mr);
kern_addr++;
complex = TRUE;
break;
default:
printf("bad descriptor type: %d idx: %d\n", user_addr->type.type, i);
/* Invalid descriptor */
mr = MACH_SEND_INVALID_TYPE;
break;
}
if (MACH_MSG_SUCCESS != mr) {
/* clean from start of message descriptors to i */
ipc_kmsg_clean_partial(kmsg, i,
(mach_msg_descriptor_t *)((mach_msg_base_t *)kmsg->ikm_header + 1),
0, 0);
goto out;
}
}
if (!complex)
kmsg->ikm_header->msgh_bits &= ~MACH_MSGH_BITS_COMPLEX;
out:
return (mr);
}
/*
* Routine: ipc_kmsg_copyin
* Purpose:
* "Copy-in" port rights and out-of-line memory
* in the message.
*
* In all failure cases, the message is left holding
* no rights or memory. However, the message buffer
* is not deallocated. If successful, the message
* contains a valid destination port.
* Conditions:
* Nothing locked.
* Returns:
* MACH_MSG_SUCCESS Successful copyin.
* MACH_SEND_INVALID_HEADER
* Illegal value in the message header bits.
* MACH_SEND_INVALID_NOTIFY Bad notify port.
* MACH_SEND_INVALID_DEST Can't copyin destination port.
* MACH_SEND_INVALID_REPLY Can't copyin reply port.
* MACH_SEND_INVALID_MEMORY Can't grab out-of-line memory.
* MACH_SEND_INVALID_RIGHT Can't copyin port right in body.
* MACH_SEND_INVALID_TYPE Bad type specification.
* MACH_SEND_MSG_TOO_SMALL Body is too small for types/data.
*/
mach_msg_return_t
ipc_kmsg_copyin(
ipc_kmsg_t kmsg,
ipc_space_t space,
vm_map_t map,
mach_port_name_t notify)
{
mach_msg_return_t mr;
mr = ipc_kmsg_copyin_header(kmsg, space, notify);
if (mr != MACH_MSG_SUCCESS) {
return mr;
}
if ((kmsg->ikm_header->msgh_bits & MACH_MSGH_BITS_COMPLEX) == 0)
return MACH_MSG_SUCCESS;
return( ipc_kmsg_copyin_body( kmsg, space, map) );
}
/*
* Routine: ipc_kmsg_copyin_from_kernel
* Purpose:
* "Copy-in" port rights and out-of-line memory
* in a message sent from the kernel.
*
* Because the message comes from the kernel,
* the implementation assumes there are no errors
* or peculiarities in the message.
*
* Returns TRUE if queueing the message
* would result in a circularity.
* Conditions:
* Nothing locked.
*/
void
ipc_kmsg_copyin_from_kernel(
ipc_kmsg_t kmsg)
{
mach_msg_bits_t bits = kmsg->ikm_header->msgh_bits;
mach_msg_type_name_t rname = MACH_MSGH_BITS_REMOTE(bits);
mach_msg_type_name_t lname = MACH_MSGH_BITS_LOCAL(bits);
ipc_object_t remote = (ipc_object_t) kmsg->ikm_header->msgh_remote_port;
ipc_object_t local = (ipc_object_t) kmsg->ikm_header->msgh_local_port;
/* translate the destination and reply ports */
ipc_object_copyin_from_kernel(remote, rname);
if (IO_VALID(local))
ipc_object_copyin_from_kernel(local, lname);
/*
* The common case is a complex message with no reply port,
* because that is what the memory_object interface uses.
*/
if (bits == (MACH_MSGH_BITS_COMPLEX |
MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0))) {
bits = (MACH_MSGH_BITS_COMPLEX |
MACH_MSGH_BITS(MACH_MSG_TYPE_PORT_SEND, 0));
kmsg->ikm_header->msgh_bits = bits;
} else {
bits = (MACH_MSGH_BITS_OTHER(bits) |
MACH_MSGH_BITS(ipc_object_copyin_type(rname),
ipc_object_copyin_type(lname)));
kmsg->ikm_header->msgh_bits = bits;
if ((bits & MACH_MSGH_BITS_COMPLEX) == 0)
return;
}
{
mach_msg_descriptor_t *saddr, *eaddr;
mach_msg_body_t *body;
body = (mach_msg_body_t *) (kmsg->ikm_header + 1);
saddr = (mach_msg_descriptor_t *) (body + 1);
eaddr = (mach_msg_descriptor_t *) saddr + body->msgh_descriptor_count;
for ( ; saddr < eaddr; saddr++) {
switch (saddr->type.type) {
case MACH_MSG_PORT_DESCRIPTOR: {
mach_msg_type_name_t name;
ipc_object_t object;
mach_msg_port_descriptor_t *dsc;
dsc = &saddr->port;
/* this is really the type SEND, SEND_ONCE, etc. */
name = dsc->disposition;
object = (ipc_object_t) dsc->name;
dsc->disposition = ipc_object_copyin_type(name);
if (!IO_VALID(object)) {
break;
}
ipc_object_copyin_from_kernel(object, name);
if ((dsc->disposition == MACH_MSG_TYPE_PORT_RECEIVE) &&
ipc_port_check_circularity((ipc_port_t) object,
(ipc_port_t) remote)) {
kmsg->ikm_header->msgh_bits |= MACH_MSGH_BITS_CIRCULAR;
}
break;
}
case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
case MACH_MSG_OOL_DESCRIPTOR: {
/*
* The sender should supply ready-made memory, i.e.
* a vm_map_copy_t, so we don't need to do anything.
*/
break;
}
case MACH_MSG_OOL_PORTS_DESCRIPTOR: {
ipc_object_t *objects;
int j;
mach_msg_type_name_t name;
mach_msg_ool_ports_descriptor_t *dsc;
dsc = &saddr->ool_ports;
/* this is really the type SEND, SEND_ONCE, etc. */
name = dsc->disposition;
dsc->disposition = ipc_object_copyin_type(name);
objects = (ipc_object_t *) dsc->address;
for ( j = 0; j < dsc->count; j++) {
ipc_object_t object = objects[j];
if (!IO_VALID(object))
continue;
ipc_object_copyin_from_kernel(object, name);
if ((dsc->disposition == MACH_MSG_TYPE_PORT_RECEIVE) &&
ipc_port_check_circularity(
(ipc_port_t) object,
(ipc_port_t) remote))
kmsg->ikm_header->msgh_bits |= MACH_MSGH_BITS_CIRCULAR;
}
break;
}
default: {
}
}
}
}
}
/*
* Routine: ipc_kmsg_copyout_header
* Purpose:
* "Copy-out" port rights in the header of a message.
* Operates atomically; if it doesn't succeed the
* message header and the space are left untouched.
* If it does succeed the remote/local port fields
* contain port names instead of object pointers,
* and the bits field is updated.
*
* The notify argument implements the MACH_RCV_NOTIFY option.
* If it is not MACH_PORT_NULL, it should name a receive right.
* If the process of receiving the reply port creates a
* new right in the receiving task, then the new right is
* automatically registered for a dead-name notification,
* with the notify port supplying the send-once right.
* Conditions:
* Nothing locked.
* Returns:
* MACH_MSG_SUCCESS Copied out port rights.
* MACH_RCV_INVALID_NOTIFY
* Notify is non-null and doesn't name a receive right.
* (Either KERN_INVALID_NAME or KERN_INVALID_RIGHT.)
* MACH_RCV_HEADER_ERROR|MACH_MSG_IPC_SPACE
* The space is dead.
* MACH_RCV_HEADER_ERROR|MACH_MSG_IPC_SPACE
* No room in space for another name.
* MACH_RCV_HEADER_ERROR|MACH_MSG_IPC_KERNEL
* Couldn't allocate memory for the reply port.
* MACH_RCV_HEADER_ERROR|MACH_MSG_IPC_KERNEL
* Couldn't allocate memory for the dead-name request.
*/
static mach_msg_return_t
ipc_kmsg_copyout_header(
mach_msg_header_t *msg,
ipc_space_t space,
mach_msg_option_t option __unused)
{
mach_msg_bits_t mbits = msg->msgh_bits;
ipc_port_t dest = (ipc_port_t) msg->msgh_remote_port;
assert(IP_VALID(dest));
{
mach_msg_type_name_t dest_type = MACH_MSGH_BITS_REMOTE(mbits);
mach_msg_type_name_t reply_type = MACH_MSGH_BITS_LOCAL(mbits);
ipc_port_t reply = (ipc_port_t) msg->msgh_local_port;
mach_port_name_t dest_name, reply_name;
if (IP_VALID(reply)) {
ipc_entry_t entry;
kern_return_t kr;
ipc_port_t notify_port = IP_NULL;
/*
* Handling notify (for MACH_RCV_NOTIFY) is tricky.
* The problem is atomically making a send-once right
* from the notify port and installing it for a
* dead-name request in the new entry, because this
* requires two port locks (on the notify port and
* the reply port). However, we can safely make
* and consume send-once rights for the notify port
* as long as we hold the space locked. This isn't
* an atomicity problem, because the only way
* to detect that a send-once right has been created
* and then consumed if it wasn't needed is by getting
* at the receive right to look at ip_sorights, and
* because the space is write-locked status calls can't
* lookup the notify port receive right. When we make
* the send-once right, we lock the notify port,
* so any status calls in progress will be done.
*/
is_write_lock(space);
for (;;) {
ipc_port_request_index_t request;
if (!space->is_active) {
is_write_unlock(space);
return (MACH_RCV_HEADER_ERROR|
MACH_MSG_IPC_SPACE);
}
if ((reply_type != MACH_MSG_TYPE_PORT_SEND_ONCE) &&
ipc_right_reverse(space, (ipc_object_t) reply,
&reply_name, &entry)) {
/* reply port is locked and active */
/*
* We don't need the notify_port
* send-once right, but we can't release
* it here because reply port is locked.
* Wait until after the copyout to
* release the notify port right.
*/
assert(entry->ie_bits &
MACH_PORT_TYPE_SEND_RECEIVE);
break;
}
ip_lock(reply);
if (!ip_active(reply)) {
ip_unlock(reply);
ip_release(reply);
ip_lock(dest);
is_write_unlock(space);
reply = IP_DEAD;
reply_name = MACH_PORT_NAME_DEAD;
goto copyout_dest;
}
ip_unlock(reply);
is_write_unlock(space);
reply_name = MACH_PORT_NAME_NULL;
kr = ipc_entry_get(space,
reply_type == MACH_MSG_TYPE_PORT_SEND_ONCE,
&reply_name, &entry);
if (kr != KERN_SUCCESS) {
if (kr == KERN_RESOURCE_SHORTAGE)
return (MACH_RCV_HEADER_ERROR|
MACH_MSG_IPC_KERNEL);
else
return (MACH_RCV_HEADER_ERROR|
MACH_MSG_IPC_SPACE);
}
assert(IE_BITS_TYPE(entry->ie_bits)
== MACH_PORT_TYPE_NONE);
assert(entry->ie_object == IO_NULL);
is_write_lock(space);
ip_lock(reply);
if (notify_port == IP_NULL) {
ip_reference(reply); /* hold onto the reply port */
/* not making dead name request */
entry->ie_object = (ipc_object_t) reply;
break;
}
kr = ipc_port_dnrequest(reply, reply_name,
notify_port, &request);
if (kr != KERN_SUCCESS) {
is_write_unlock(space);
ipc_entry_close(space, reply_name);
ip_lock(reply);
if (!ip_active(reply)) {
/* will fail next time around loop */
ip_unlock(reply);
is_write_lock(space);
continue;
}
kr = ipc_port_dngrow(reply, ITS_SIZE_NONE);
/* port is unlocked */
if (kr != KERN_SUCCESS)
return (MACH_RCV_HEADER_ERROR|
MACH_MSG_IPC_KERNEL);
is_write_lock(space);
continue;
}
is_write_lock(space);
ip_lock(reply);
ip_reference(reply); /* hold onto the reply port */
entry->ie_object = (ipc_object_t) reply;
entry->ie_request = request;
break;
}
/* space and reply port are locked and active */
ip_reference(reply); /* hold onto the reply port */
mtx_assert(&reply->port_comm.rcd_io_lock_data, MA_OWNED);
kr = ipc_right_copyout(space, reply_name, entry,
reply_type, (ipc_object_t) reply);
/* reply port is unlocked */
assert(kr == KERN_SUCCESS);
ip_lock(dest);
is_write_unlock(space);
} else {
/*
* No reply port! This is an easy case.
* We only need to have the space locked
* when checking notify and when locking
* the destination (to ensure atomicity).
*/
is_read_lock(space);
if (!space->is_active) {
is_read_unlock(space);
return MACH_RCV_HEADER_ERROR|MACH_MSG_IPC_SPACE;
}
ip_lock(dest);
is_read_unlock(space);
reply_name = CAST_MACH_PORT_TO_NAME(reply);
}
/*
* At this point, the space is unlocked and the destination
* port is locked. (Lock taken while space was locked.)
* reply_name is taken care of; we still need dest_name.
* We still hold a ref for reply (if it is valid).
*
* If the space holds receive rights for the destination,
* we return its name for the right. Otherwise the task
* managed to destroy or give away the receive right between
* receiving the message and this copyout. If the destination
* is dead, return MACH_PORT_DEAD, and if the receive right
* exists somewhere else (another space, in transit)
* return MACH_PORT_NULL.
*
* Making this copyout operation atomic with the previous
* copyout of the reply port is a bit tricky. If there was
* no real reply port (it wasn't IP_VALID) then this isn't
* an issue. If the reply port was dead at copyout time,
* then we are OK, because if dest is dead we serialize
* after the death of both ports and if dest is alive
* we serialize after reply died but before dest's (later) death.
* So assume reply was alive when we copied it out. If dest
* is alive, then we are OK because we serialize before
* the ports' deaths. So assume dest is dead when we look at it.
* If reply dies/died after dest, then we are OK because
* we serialize after dest died but before reply dies.
* So the hard case is when reply is alive at copyout,
* dest is dead at copyout, and reply died before dest died.
* In this case pretend that dest is still alive, so
* we serialize while both ports are alive.
*
* Because the space lock is held across the copyout of reply
* and locking dest, the receive right for dest can't move
* in or out of the space while the copyouts happen, so
* that isn't an atomicity problem. In the last hard case
* above, this implies that when dest is dead that the
* space couldn't have had receive rights for dest at
* the time reply was copied-out, so when we pretend
* that dest is still alive, we can return MACH_PORT_NULL.
*
* If dest == reply, then we have to make it look like
* either both copyouts happened before the port died,
* or both happened after the port died. This special
* case works naturally if the timestamp comparison
* is done correctly.
*/
copyout_dest:
if (ip_active(dest)) {
ipc_object_copyout_dest(space, (ipc_object_t) dest,
dest_type, &dest_name);
/* dest is unlocked */
} else {
ipc_port_timestamp_t timestamp;
timestamp = dest->ip_timestamp;
ip_unlock(dest);
ip_release(dest);
if (IP_VALID(reply)) {
ip_lock(reply);
if (ip_active(reply) ||
IP_TIMESTAMP_ORDER(timestamp,
reply->ip_timestamp))
dest_name = MACH_PORT_NAME_DEAD;
else
dest_name = MACH_PORT_NAME_NULL;
ip_unlock(reply);
} else
dest_name = MACH_PORT_NAME_DEAD;
}
if (IP_VALID(reply))
ipc_port_release(reply);
msg->msgh_bits = (MACH_MSGH_BITS_OTHER(mbits) |
MACH_MSGH_BITS(reply_type, dest_type));
msg->msgh_local_port = CAST_MACH_NAME_TO_PORT(dest_name);
msg->msgh_remote_port = CAST_MACH_NAME_TO_PORT(reply_name);
}
return MACH_MSG_SUCCESS;
}
/*
* Routine: ipc_kmsg_copyout_object
* Purpose:
* Copy-out a port right. Always returns a name,
* even for unsuccessful return codes. Always
* consumes the supplied object.
* Conditions:
* Nothing locked.
* Returns:
* MACH_MSG_SUCCESS The space acquired the right
* (name is valid) or the object is dead (MACH_PORT_DEAD).
* MACH_MSG_IPC_SPACE No room in space for the right,
* or the space is dead. (Name is MACH_PORT_NULL.)
* MACH_MSG_IPC_KERNEL Kernel resource shortage.
* (Name is MACH_PORT_NULL.)
*/
static mach_msg_return_t
ipc_kmsg_copyout_object(
ipc_space_t space,
ipc_object_t object,
mach_msg_type_name_t msgt_name,
mach_port_name_t *namep)
{
kern_return_t kr;
if (!IO_VALID(object)) {
*namep = CAST_MACH_PORT_TO_NAME(object);
return MACH_MSG_SUCCESS;
}
kr = ipc_object_copyout(space, object, msgt_name, namep);
if (kr != KERN_SUCCESS) {
if (msgt_name != 0) {
ipc_object_destroy(object, msgt_name);
if (kr == KERN_INVALID_CAPABILITY)
*namep = MACH_PORT_NAME_DEAD;
else {
*namep = MACH_PORT_NAME_NULL;
if (kr == KERN_RESOURCE_SHORTAGE)
return MACH_MSG_IPC_KERNEL;
else
return MACH_MSG_IPC_SPACE;
}
} else
return kr;
}
return MACH_MSG_SUCCESS;
}
static mach_msg_descriptor_t *
ipc_kmsg_copyout_port_descriptor(mach_msg_descriptor_t *dsc,
mach_msg_descriptor_t *dest_dsc,
ipc_space_t space,
kern_return_t *mr)
{
mach_port_t port;
mach_port_name_t name;
mach_msg_type_name_t disp;
/* Copyout port right carried in the message */
port = dsc->port.name;
disp = dsc->port.disposition;
*mr |= ipc_kmsg_copyout_object(space,
(ipc_object_t)port,
disp,
&name);
MDPRINTF(("ipc_kmsg_copyout_port_descriptor name is %d\n",name));
if(current_task() == kernel_task)
{
mach_msg_port_descriptor_t *user_dsc = (mach_msg_port_descriptor_t *)dest_dsc;
user_dsc--; // point to the start of this port descriptor
user_dsc->name = CAST_MACH_NAME_TO_PORT(name);
user_dsc->disposition = disp;
user_dsc->type = MACH_MSG_PORT_DESCRIPTOR;
dest_dsc = (mach_msg_descriptor_t *)user_dsc;
} else {
mach_msg_legacy_port_descriptor_t *user_dsc = (mach_msg_legacy_port_descriptor_t *)dest_dsc;
user_dsc--; // point to the start of this port descriptor
user_dsc->name = name;
user_dsc->disposition = disp;
user_dsc->type = MACH_MSG_PORT_DESCRIPTOR;
dest_dsc = (mach_msg_descriptor_t *)user_dsc;
}
return (mach_msg_descriptor_t *)dest_dsc;
}
static mach_msg_descriptor_t *
ipc_kmsg_copyout_ool_descriptor(mach_msg_ool_descriptor_t *dsc, mach_msg_descriptor_t *user_dsc, int is_lp64, vm_map_t map, mach_msg_return_t *mr)
{
vm_offset_t rcv_addr;
vm_map_copy_t map_copy;
mach_msg_copy_options_t copy_options;
mach_msg_size_t size;
kern_return_t kr;
mach_msg_ool_descriptor_t *user_ool_dsc;
//SKIP_PORT_DESCRIPTORS(sstart, send);
assert(dsc->copy != MACH_MSG_KALLOC_COPY_T);
assert(dsc->copy != MACH_MSG_PAGE_LIST_COPY_T);
copy_options = dsc->copy;
size = dsc->size;
rcv_addr = 0;
if ((map_copy = (vm_map_copy_t) dsc->address) != VM_MAP_COPY_NULL) {
/*
* Whether the data was virtually or physically
* copied we have a vm_map_copy_t for it.
* If there's an overwrite region specified
* overwrite it, otherwise do a virtual copy out.
*/
kr = vm_map_copyout(map, &rcv_addr, map_copy);
if (kr != KERN_SUCCESS) {
if (kr == KERN_RESOURCE_SHORTAGE)
*mr |= MACH_MSG_VM_KERNEL;
else
*mr |= MACH_MSG_VM_SPACE;
vm_map_copy_discard(map_copy);
dsc->address = NULL;
rcv_addr = 0;
size = 0;
}
} else {
size = 0;
}
/*
* Now update the descriptor as the user would see it.
* This may require expanding the descriptor to the user
* visible size. There is already space allocated for
* this in what naddr points to.
*/
user_ool_dsc = (mach_msg_ool_descriptor_t *)user_dsc;
user_ool_dsc--;
user_ool_dsc->address = (void *)rcv_addr;
user_ool_dsc->size = size;
user_ool_dsc->type = MACH_MSG_OOL_DESCRIPTOR;
user_ool_dsc->copy = copy_options;
user_ool_dsc->deallocate = (copy_options == MACH_MSG_VIRTUAL_COPY) ? TRUE : FALSE;
user_dsc = (mach_msg_descriptor_t *)user_ool_dsc;
return (user_dsc);
}
static mach_msg_descriptor_t *
ipc_kmsg_copyout_ool_ports_descriptor(mach_msg_ool_ports_descriptor_t *dsc,
mach_msg_descriptor_t *user_dsc,
int is_64bit __unused,
vm_map_t map,
ipc_space_t space,
ipc_kmsg_t kmsg,
mach_msg_return_t *mr)
{
vm_offset_t addr;
mach_port_t *objects;
mach_port_name_t *names;
mach_msg_type_number_t j, count;
mach_msg_type_name_t disp;
vm_size_t plength, pnlength;
mach_msg_ool_ports_descriptor_t *user_ool_dsc;
kern_return_t kr;
disp = dsc->disposition;
count = dsc->count;
plength = count * sizeof(mach_port_t);
pnlength = count * sizeof(mach_port_name_t);
if (plength != 0 && dsc->address != 0) {
/*
* Dynamically allocate the region
*/
dsc->copy = MACH_MSG_ALLOCATE;
if ((kr = mach_vm_allocate(map, &addr, pnlength, VM_FLAGS_ANYWHERE)) !=
KERN_SUCCESS) {
/* check that the memory has been freed */
ipc_kmsg_clean_body(kmsg, 1, (mach_msg_descriptor_t *)dsc);
dsc->address = 0;
if (kr == KERN_RESOURCE_SHORTAGE){
*mr |= MACH_MSG_VM_KERNEL;
} else {
*mr |= MACH_MSG_VM_SPACE;
}
}
if (addr != 0) {
objects = (mach_port_t *) dsc->address;
names = (mach_port_name_t *) dsc->address;
/* copyout port rights carried in the message */
for ( j = 0; j < count ; j++) {
ipc_object_t object = (ipc_object_t)objects[j];
*mr |= ipc_kmsg_copyout_object(space, object,
disp, &names[j]);
}
/* copyout to memory allocated above */
void *data = dsc->address;
if (copyoutmap(map, data, addr, pnlength) != KERN_SUCCESS)
*mr |= MACH_MSG_VM_SPACE;
free(data, M_MACH_TMP);
}
} else
addr = 0;
user_ool_dsc = (mach_msg_ool_ports_descriptor_t *)user_dsc;
user_ool_dsc--;
user_ool_dsc->address = (void *)addr;
user_ool_dsc->deallocate = TRUE;
user_ool_dsc->copy = MACH_MSG_VIRTUAL_COPY;
user_ool_dsc->type = MACH_MSG_OOL_PORTS_DESCRIPTOR;
user_ool_dsc->disposition = disp;
user_ool_dsc->count = count;
user_dsc = (mach_msg_descriptor_t *)user_ool_dsc;
return user_dsc;
}
/*
* Routine: ipc_kmsg_copyout_body
* Purpose:
* "Copy-out" port rights and out-of-line memory
* in the body of a message.
*
* The error codes are a combination of special bits.
* The copyout proceeds despite errors.
* Conditions:
* Nothing locked.
* Returns:
* MACH_MSG_SUCCESS Successful copyout.
* MACH_MSG_IPC_SPACE No room for port right in name space.
* MACH_MSG_VM_SPACE No room for memory in address space.
* MACH_MSG_IPC_KERNEL Resource shortage handling port right.
* MACH_MSG_VM_KERNEL Resource shortage handling memory.
* MACH_MSG_INVALID_RT_DESCRIPTOR Descriptor incompatible with RT
*/
static mach_msg_return_t
ipc_kmsg_copyout_body(
ipc_kmsg_t kmsg,
ipc_space_t space,
vm_map_t map,
mach_msg_body_t *slist)
{
mach_msg_body_t *body;
mach_msg_descriptor_t *kern_dsc, *user_dsc;
mach_msg_descriptor_t *saddr;
mach_msg_return_t mr = MACH_MSG_SUCCESS;
mach_msg_type_number_t dsc_count, sdsc_count;
int i;
body = (mach_msg_body_t *) (kmsg->ikm_header + 1);
dsc_count = body->msgh_descriptor_count;
kern_dsc = (mach_msg_descriptor_t *) (body + 1);
user_dsc = &kern_dsc[dsc_count];
/*
* Do scatter list setup
*/
if (slist != MACH_MSG_BODY_NULL) {
saddr = (mach_msg_descriptor_t *) (slist + 1);
sdsc_count = slist->msgh_descriptor_count;
}
else {
saddr = MACH_MSG_DESCRIPTOR_NULL;
sdsc_count = 0;
}
for (i = dsc_count-1; i >= 0; i--) {
switch (kern_dsc[i].type.type) {
case MACH_MSG_PORT_DESCRIPTOR:
user_dsc = ipc_kmsg_copyout_port_descriptor(kern_dsc + i, user_dsc, space, &mr);
break;
case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
case MACH_MSG_OOL_DESCRIPTOR:
/* ... */
user_dsc = ipc_kmsg_copyout_ool_descriptor(
(mach_msg_ool_descriptor_t *)&kern_dsc[i], user_dsc, TRUE, map, &mr);
break;
case MACH_MSG_OOL_PORTS_DESCRIPTOR:
/* ... */
user_dsc = ipc_kmsg_copyout_ool_ports_descriptor(
(mach_msg_ool_ports_descriptor_t *)&kern_dsc[i], user_dsc, TRUE, map, space, kmsg, &mr);
break;
default : {
panic("untyped or unsupported IPC copyout body: invalid message descriptor");
}
}
}
if(user_dsc != kern_dsc) {
vm_offset_t dsc_adjust = (vm_offset_t)user_dsc - (vm_offset_t)kern_dsc;
MDPRINTF(("dsc_adjust=%ld\n", dsc_adjust));
memmove((char *)((vm_offset_t)kmsg->ikm_header + dsc_adjust), kmsg->ikm_header, sizeof(mach_msg_base_t));
kmsg->ikm_header = (mach_msg_header_t *)((vm_offset_t)kmsg->ikm_header + dsc_adjust);
/* Update the message size for the smaller user representation */
kmsg->ikm_header->msgh_size -= (mach_msg_size_t)dsc_adjust;
}
return mr;
}
/*
* Routine: ipc_kmsg_copyout_size
* Purpose:
* Compute the size of the message as copied out to the given
* map. If the destination map's pointers are a different size
* than the kernel's, we have to allow for expansion/
* contraction of the descriptors as appropriate.
* Conditions:
* Nothing locked.
* Returns:
* size of the message as it would be received.
*/
mach_msg_size_t
ipc_kmsg_copyout_size(
ipc_kmsg_t kmsg,
vm_map_t map)
{
mach_msg_size_t send_size;
send_size = kmsg->ikm_header->msgh_size;
#ifdef notyet
boolean_t is_task_64bit = (map->max_offset > VM_MAX_ADDRESS);
#else
boolean_t is_task_64bit = TRUE;
#endif
#if defined(__LP64__)
send_size -= LEGACY_HEADER_SIZE_DELTA;
#endif
MDPRINTF(("ipc_kmsg_copyout_size() is_task_64bit=%d -> send_size=%d msgh_bits=0x%x delta=%d\n",
is_task_64bit, send_size, kmsg->ikm_header->msgh_bits, LEGACY_HEADER_SIZE_DELTA));
if (kmsg->ikm_header->msgh_bits & MACH_MSGH_BITS_COMPLEX) {
mach_msg_body_t *body;
mach_msg_descriptor_t *saddr, *eaddr;
body = (mach_msg_body_t *) (kmsg->ikm_header + 1);
saddr = (mach_msg_descriptor_t *) (body + 1);
eaddr = saddr + body->msgh_descriptor_count;
for ( ; saddr < eaddr; saddr++ ) {
switch (saddr->type.type) {
case MACH_MSG_OOL_DESCRIPTOR:
case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
case MACH_MSG_OOL_PORTS_DESCRIPTOR:
if(!is_task_64bit)
send_size -= DESC_SIZE_ADJUSTMENT;
break;
case MACH_MSG_PORT_DESCRIPTOR:
send_size -= DESC_SIZE_ADJUSTMENT;
break;
default:
break;
}
}
}
return send_size;
}
/*
* Routine: ipc_kmsg_copyout
* Purpose:
* "Copy-out" port rights and out-of-line memory
* in the message.
* Conditions:
* Nothing locked.
* Returns:
* MACH_MSG_SUCCESS Copied out all rights and memory.
* MACH_RCV_INVALID_NOTIFY Bad notify port.
* Rights and memory in the message are intact.
* MACH_RCV_HEADER_ERROR + special bits
* Rights and memory in the message are intact.
* MACH_RCV_BODY_ERROR + special bits
* The message header was successfully copied out.
* As much of the body was handled as possible.
*/
mach_msg_return_t
ipc_kmsg_copyout(
ipc_kmsg_t kmsg,
ipc_space_t space,
vm_map_t map,
mach_msg_body_t *slist,
mach_msg_option_t option __unused)
{
mach_msg_return_t mr;
mr = ipc_kmsg_copyout_header(kmsg->ikm_header, space, 0);
if (mr != MACH_MSG_SUCCESS)
return mr;
if (kmsg->ikm_header->msgh_bits & MACH_MSGH_BITS_COMPLEX) {
mr = ipc_kmsg_copyout_body(kmsg, space, map, slist);
if (mr != MACH_MSG_SUCCESS)
mr |= MACH_RCV_BODY_ERROR;
}
return mr;
}
/*
* Routine: ipc_kmsg_copyout_pseudo
* Purpose:
* Does a pseudo-copyout of the message.
* This is like a regular copyout, except
* that the ports in the header are handled
* as if they are in the body. They aren't reversed.
*
* The error codes are a combination of special bits.
* The copyout proceeds despite errors.
* Conditions:
* Nothing locked.
* Returns:
* MACH_MSG_SUCCESS Successful copyout.
* MACH_MSG_IPC_SPACE No room for port right in name space.
* MACH_MSG_VM_SPACE No room for memory in address space.
* MACH_MSG_IPC_KERNEL Resource shortage handling port right.
* MACH_MSG_VM_KERNEL Resource shortage handling memory.
*/
mach_msg_return_t
ipc_kmsg_copyout_pseudo(
ipc_kmsg_t kmsg,
ipc_space_t space,
vm_map_t map,
mach_msg_body_t *slist)
{
mach_msg_bits_t mbits = kmsg->ikm_header->msgh_bits;
ipc_object_t dest = (ipc_object_t) kmsg->ikm_header->msgh_remote_port;
ipc_object_t reply = (ipc_object_t) kmsg->ikm_header->msgh_local_port;
mach_msg_type_name_t dest_type = MACH_MSGH_BITS_REMOTE(mbits);
mach_msg_type_name_t reply_type = MACH_MSGH_BITS_LOCAL(mbits);
mach_port_name_t dest_name, reply_name;
mach_msg_return_t mr;
assert(IO_VALID(dest));
mr = (ipc_kmsg_copyout_object(space, dest, dest_type, &dest_name) |
ipc_kmsg_copyout_object(space, reply, reply_type, &reply_name));
kmsg->ikm_header->msgh_bits = mbits &~ MACH_MSGH_BITS_CIRCULAR;
kmsg->ikm_header->msgh_remote_port = CAST_MACH_NAME_TO_PORT(dest_name);
kmsg->ikm_header->msgh_local_port = CAST_MACH_NAME_TO_PORT(reply_name);
if (mbits & MACH_MSGH_BITS_COMPLEX) {
mr |= ipc_kmsg_copyout_body(kmsg, space, map, slist);
}
return mr;
}
/*
* Routine: ipc_kmsg_copyout_dest
* Purpose:
* Copies out the destination port in the message.
* Destroys all other rights and memory in the message.
* Conditions:
* Nothing locked.
*/
void
ipc_kmsg_copyout_dest(
ipc_kmsg_t kmsg,
ipc_space_t space)
{
mach_msg_bits_t mbits;
ipc_object_t dest;
ipc_object_t reply;
mach_msg_type_name_t dest_type;
mach_msg_type_name_t reply_type;
mach_port_name_t dest_name, reply_name;
mbits = kmsg->ikm_header->msgh_bits;
dest = (ipc_object_t) kmsg->ikm_header->msgh_remote_port;
reply = (ipc_object_t) kmsg->ikm_header->msgh_local_port;
dest_type = MACH_MSGH_BITS_REMOTE(mbits);
reply_type = MACH_MSGH_BITS_LOCAL(mbits);
assert(IO_VALID(dest));
io_lock(dest);
if (io_active(dest)) {
ipc_object_copyout_dest(space, dest, dest_type, &dest_name);
/* dest is unlocked */
} else {
io_unlock(dest);
io_release(dest);
dest_name = MACH_PORT_NAME_DEAD;
}
if (IO_VALID(reply)) {
ipc_object_destroy(reply, reply_type);
reply_name = MACH_PORT_NAME_NULL;
} else
reply_name = CAST_MACH_PORT_TO_NAME(reply);
kmsg->ikm_header->msgh_bits = (MACH_MSGH_BITS_OTHER(mbits) |
MACH_MSGH_BITS(reply_type, dest_type));
kmsg->ikm_header->msgh_local_port = CAST_MACH_NAME_TO_PORT(dest_name);
kmsg->ikm_header->msgh_remote_port = CAST_MACH_NAME_TO_PORT(reply_name);
if (mbits & MACH_MSGH_BITS_COMPLEX) {
mach_msg_body_t *body;
body = (mach_msg_body_t *) (kmsg->ikm_header + 1);
ipc_kmsg_clean_body(kmsg, body->msgh_descriptor_count, (mach_msg_descriptor_t *)(body + 1));
}
}
/*
* Routine: ipc_kmsg_check_scatter
* Purpose:
* Checks scatter and gather lists for consistency.
*
* Algorithm:
* The gather is assumed valid since it has been copied in.
* The scatter list has only been range checked.
* Gather list descriptors are sequentially paired with scatter
* list descriptors, with port descriptors in either list ignored.
* Descriptors are consistent if the type fileds match and size
* of the scatter descriptor is less than or equal to the
* size of the gather descriptor. A MACH_MSG_ALLOCATE copy
* strategy in a scatter descriptor matches any size in the
* corresponding gather descriptor assuming they are the same type.
* Either list may be larger than the other. During the
* subsequent copy out, excess scatter descriptors are ignored
* and excess gather descriptors default to dynamic allocation.
*
* In the case of a size error, a new scatter list is formed
* from the gather list copying only the size and type fields.
*
* Conditions:
* Nothing locked.
* Returns:
* MACH_MSG_SUCCESS Lists are consistent
* MACH_RCV_INVALID_TYPE Scatter type does not match
* gather type
* MACH_RCV_SCATTER_SMALL Scatter size less than gather
* size
*/
mach_msg_return_t
ipc_kmsg_check_scatter(
ipc_kmsg_t kmsg,
mach_msg_option_t option,
mach_msg_body_t **slistp,
mach_msg_size_t *sizep)
{
mach_msg_body_t *body;
mach_msg_descriptor_t *gstart, *gend;
mach_msg_descriptor_t *sstart, *send;
mach_msg_return_t mr = MACH_MSG_SUCCESS;
assert(*slistp != MACH_MSG_BODY_NULL);
assert(*sizep != 0);
body = (mach_msg_body_t *) (kmsg->ikm_header + 1);
gstart = (mach_msg_descriptor_t *) (body + 1);
gend = gstart + body->msgh_descriptor_count;
sstart = (mach_msg_descriptor_t *) (*slistp + 1);
send = sstart + (*slistp)->msgh_descriptor_count;
while (gstart < gend) {
mach_msg_descriptor_type_t g_type;
/*
* Skip port descriptors in gather list.
*/
g_type = gstart->type.type;
if (g_type != MACH_MSG_PORT_DESCRIPTOR) {
/*
* A scatter list with a 0 descriptor count is treated as an
* automatic size mismatch.
*/
if ((*slistp)->msgh_descriptor_count == 0) {
return(MACH_RCV_SCATTER_SMALL);
}
/*
* Skip port descriptors in scatter list.
*/
while (sstart < send) {
if (sstart->type.type != MACH_MSG_PORT_DESCRIPTOR)
break;
sstart++;
}
/*
* No more scatter descriptors, we're done
*/
if (sstart >= send) {
break;
}
/*
* Check type, copy and size fields
*/
if (g_type == MACH_MSG_OOL_DESCRIPTOR ||
g_type == MACH_MSG_OOL_VOLATILE_DESCRIPTOR) {
if (sstart->type.type != MACH_MSG_OOL_DESCRIPTOR &&
sstart->type.type != MACH_MSG_OOL_VOLATILE_DESCRIPTOR) {
return(MACH_RCV_INVALID_TYPE);
}
if (sstart->out_of_line.copy == MACH_MSG_OVERWRITE &&
gstart->out_of_line.size > sstart->out_of_line.size) {
return(MACH_RCV_SCATTER_SMALL);
}
}
else {
if (sstart->type.type != MACH_MSG_OOL_PORTS_DESCRIPTOR) {
return(MACH_RCV_INVALID_TYPE);
}
if (sstart->ool_ports.copy == MACH_MSG_OVERWRITE &&
gstart->ool_ports.count > sstart->ool_ports.count) {
return(MACH_RCV_SCATTER_SMALL);
}
}
sstart++;
}
gstart++;
}
return(mr);
}
/*
* Routine: ipc_kmsg_copyout_to_kernel
* Purpose:
* Copies out the destination and reply ports in the message.
* Leaves all other rights and memory in the message alone.
* Conditions:
* Nothing locked.
*
* Derived from ipc_kmsg_copyout_dest.
* Use by mach_msg_rpc_from_kernel (which used to use copyout_dest).
* We really do want to save rights and memory.
*/
void
ipc_kmsg_copyout_to_kernel(
ipc_kmsg_t kmsg,
ipc_space_t space)
{
ipc_object_t dest;
ipc_object_t reply;
mach_msg_type_name_t dest_type;
mach_msg_type_name_t reply_type;
mach_port_name_t dest_name, reply_name;
dest = (ipc_object_t) kmsg->ikm_header->msgh_remote_port;
reply = (ipc_object_t) kmsg->ikm_header->msgh_local_port;
dest_type = MACH_MSGH_BITS_REMOTE(kmsg->ikm_header->msgh_bits);
reply_type = MACH_MSGH_BITS_LOCAL(kmsg->ikm_header->msgh_bits);
assert(IO_VALID(dest));
io_lock(dest);
if (io_active(dest)) {
ipc_object_copyout_dest(space, dest, dest_type, &dest_name);
/* dest is unlocked */
} else {
io_unlock(dest);
io_release(dest);
dest_name = MACH_PORT_NAME_DEAD;
}
reply_name = CAST_MACH_PORT_TO_NAME(reply);
kmsg->ikm_header->msgh_bits =
(MACH_MSGH_BITS_OTHER(kmsg->ikm_header->msgh_bits) |
MACH_MSGH_BITS(reply_type, dest_type));
kmsg->ikm_header->msgh_local_port = CAST_MACH_NAME_TO_PORT(dest_name);
kmsg->ikm_header->msgh_remote_port = CAST_MACH_NAME_TO_PORT(reply_name);
}
#if MACH_KDB
#include <ddb/db_output.h>
#include <mach/ipc/ipc_print.h>
/*
* Forward declarations
*/
void ipc_msg_print_untyped(
mach_msg_body_t *body);
char * ipc_type_name(
int type_name,
boolean_t received);
void ipc_print_type_name(
int type_name);
char *
msgh_bit_decode(
mach_msg_bits_t bit);
char *
mm_copy_options_string(
mach_msg_copy_options_t option);
char *
ipc_type_name(
int type_name,
boolean_t received)
{
switch (type_name) {
case MACH_MSG_TYPE_PORT_NAME:
return "port_name";
case MACH_MSG_TYPE_MOVE_RECEIVE:
if (received) {
return "port_receive";
} else {
return "move_receive";
}
case MACH_MSG_TYPE_MOVE_SEND:
if (received) {
return "port_send";
} else {
return "move_send";
}
case MACH_MSG_TYPE_MOVE_SEND_ONCE:
if (received) {
return "port_send_once";
} else {
return "move_send_once";
}
case MACH_MSG_TYPE_COPY_SEND:
return "copy_send";
case MACH_MSG_TYPE_MAKE_SEND:
return "make_send";
case MACH_MSG_TYPE_MAKE_SEND_ONCE:
return "make_send_once";
default:
return (char *) 0;
}
}
void
ipc_print_type_name(
int type_name)
{
char *name = ipc_type_name(type_name, TRUE);
if (name) {
printf("%s", name);
} else {
printf("type%d", type_name);
}
}
/*
* ipc_kmsg_print [ debug ]
*/
void
ipc_kmsg_print(
ipc_kmsg_t kmsg)
{
iprintf("kmsg=0x%x\n", kmsg);
iprintf("ikm_next=0x%x, prev=0x%x, size=%d",
kmsg->ikm_next,
kmsg->ikm_prev,
kmsg->ikm_size);
printf("\n");
ipc_msg_print(kmsg->ikm_header);
}
char *
msgh_bit_decode(
mach_msg_bits_t bit)
{
switch (bit) {
case MACH_MSGH_BITS_COMPLEX: return "complex";
case MACH_MSGH_BITS_CIRCULAR: return "circular";
case MACH_MSGH_BITS_RTALLOC: return "rtalloc";
default: return (char *) 0;
}
}
/*
* ipc_msg_print [ debug ]
*/
void
ipc_msg_print(
mach_msg_header_t *msgh)
{
mach_msg_bits_t mbits;
unsigned int bit, i;
char *bit_name;
int needs_comma;
mbits = msgh->msgh_bits;
iprintf("msgh_bits=0x%x: l=0x%x,r=0x%x\n",
mbits,
MACH_MSGH_BITS_LOCAL(msgh->msgh_bits),
MACH_MSGH_BITS_REMOTE(msgh->msgh_bits));
mbits = MACH_MSGH_BITS_OTHER(mbits) & ~MACH_MSGH_BITS_UNUSED;
indent += 2;
if (mbits)
iprintf("decoded bits: ");
needs_comma = 0;
for (i = 0, bit = 1; i < sizeof(mbits) * 8; ++i, bit <<= 1) {
if ((mbits & bit) == 0)
continue;
bit_name = msgh_bit_decode((mach_msg_bits_t)bit);
if (bit_name)
printf("%s%s", needs_comma ? "," : "", bit_name);
else
printf("%sunknown(0x%x),", needs_comma ? "," : "", bit);
++needs_comma;
}
if (msgh->msgh_bits & MACH_MSGH_BITS_UNUSED) {
printf("%sunused=0x%x,", needs_comma ? "," : "",
msgh->msgh_bits & MACH_MSGH_BITS_UNUSED);
}
printf("\n");
indent -= 2;
needs_comma = 1;
if (msgh->msgh_remote_port) {
iprintf("remote=0x%x(", msgh->msgh_remote_port);
ipc_print_type_name(MACH_MSGH_BITS_REMOTE(msgh->msgh_bits));
printf(")");
} else {
iprintf("remote=null");
}
if (msgh->msgh_local_port) {
printf("%slocal=0x%x(", needs_comma ? "," : "",
msgh->msgh_local_port);
ipc_print_type_name(MACH_MSGH_BITS_LOCAL(msgh->msgh_bits));
printf(")\n");
} else {
printf("local=null\n");
}
iprintf("msgh_id=%d, size=%d\n",
msgh->msgh_id,
msgh->msgh_size);
if (mbits & MACH_MSGH_BITS_COMPLEX) {
ipc_msg_print_untyped((mach_msg_body_t *) (msgh + 1));
}
}
char *
mm_copy_options_string(
mach_msg_copy_options_t option)
{
char *name;
switch (option) {
case MACH_MSG_PHYSICAL_COPY:
name = "PHYSICAL";
break;
case MACH_MSG_VIRTUAL_COPY:
name = "VIRTUAL";
break;
case MACH_MSG_OVERWRITE:
name = "OVERWRITE";
break;
case MACH_MSG_ALLOCATE:
name = "ALLOCATE";
break;
case MACH_MSG_KALLOC_COPY_T:
name = "KALLOC_COPY_T";
break;
case MACH_MSG_PAGE_LIST_COPY_T:
name = "PAGE_LIST_COPY_T";
break;
default:
name = "unknown";
break;
}
return name;
}
void
ipc_msg_print_untyped(
mach_msg_body_t *body)
{
mach_msg_descriptor_t *saddr, *send;
mach_msg_descriptor_type_t type;
iprintf("%d descriptors %d: \n", body->msgh_descriptor_count);
saddr = (mach_msg_descriptor_t *) (body + 1);
send = saddr + body->msgh_descriptor_count;
for ( ; saddr < send; saddr++ ) {
type = saddr->type.type;
switch (type) {
case MACH_MSG_PORT_DESCRIPTOR: {
mach_msg_port_descriptor_t *dsc;
dsc = &saddr->port;
iprintf("-- PORT name = 0x%x disp = ", dsc->name);
ipc_print_type_name(dsc->disposition);
printf("\n");
break;
}
case MACH_MSG_OOL_VOLATILE_DESCRIPTOR:
case MACH_MSG_OOL_DESCRIPTOR: {
mach_msg_ool_descriptor_t *dsc;
dsc = &saddr->out_of_line;
iprintf("-- OOL%s addr = 0x%x size = 0x%x copy = %s %s\n",
type == MACH_MSG_OOL_DESCRIPTOR ? "" : " VOLATILE",
dsc->address, dsc->size,
mm_copy_options_string(dsc->copy),
dsc->deallocate ? "DEALLOC" : "");
break;
}
case MACH_MSG_OOL_PORTS_DESCRIPTOR : {
mach_msg_ool_ports_descriptor_t *dsc;
dsc = &saddr->ool_ports;
iprintf("-- OOL_PORTS addr = 0x%x count = 0x%x ",
dsc->address, dsc->count);
printf("disp = ");
ipc_print_type_name(dsc->disposition);
printf(" copy = %s %s\n",
mm_copy_options_string(dsc->copy),
dsc->deallocate ? "DEALLOC" : "");
break;
}
default: {
iprintf("-- UNKNOWN DESCRIPTOR 0x%x\n", type);
break;
}
}
}
}
#endif /* MACH_KDB */
| 28.38762 | 146 | 0.700627 | [
"object"
] |
f34c95a0cf34a65b5f0728f9b7cb1a1c32e003bd | 15,314 | h | C | Source/Shared/arcana/threading/coroutine.h | andrei-datcu/arcana.cpp | 3c4757cbee49b3272130bf8b72094c2c62fd36c5 | [
"MIT"
] | 65 | 2019-05-08T01:53:22.000Z | 2022-03-25T15:05:38.000Z | Source/Shared/arcana/threading/coroutine.h | andrei-datcu/arcana.cpp | 3c4757cbee49b3272130bf8b72094c2c62fd36c5 | [
"MIT"
] | 12 | 2019-08-13T03:18:30.000Z | 2022-01-03T20:12:24.000Z | Source/Shared/arcana/threading/coroutine.h | andrei-datcu/arcana.cpp | 3c4757cbee49b3272130bf8b72094c2c62fd36c5 | [
"MIT"
] | 18 | 2019-05-09T23:07:44.000Z | 2021-12-26T14:24:29.000Z | //
// Copyright (C) Microsoft Corporation. All rights reserved.
//
#pragma once
#ifdef __cpp_coroutines
#include <cassert>
#include <arcana/threading/task.h>
#include <experimental/coroutine>
#include <optional>
namespace arcana
{
namespace
{
expected<void, std::error_code> coroutine_success = expected<void, std::error_code>::make_valid();
}
namespace internal
{
class unobserved_error : public std::system_error
{
public:
unobserved_error(std::error_code error) : std::system_error(error) {}
};
inline void UnhandledException()
{
assert(false && "Unhandled exception. Arcana task returning functions should handle exceptions as arcana tasks do not support them.");
std::terminate();
}
template <typename ResultT>
inline void HandleCoroutineException(std::exception_ptr e, arcana::task_completion_source<ResultT, std::error_code>& taskCompletionSource)
{
try
{
std::rethrow_exception(std::move(e));
}
catch (const unobserved_error& error)
{
taskCompletionSource.complete(arcana::make_unexpected(error.code()));
}
catch (...)
{
UnhandledException();
}
}
template <typename ResultT>
inline void HandleCoroutineException(std::exception_ptr e, arcana::task_completion_source<ResultT, std::exception_ptr>& taskCompletionSource)
{
taskCompletionSource.complete(arcana::make_unexpected(e));
}
template <typename ResultT, typename ErrorT>
class base_promise_type
{
public:
auto get_return_object() { return m_taskCompletionSource.as_task(); }
std::experimental::suspend_never initial_suspend() { return {}; }
std::experimental::suspend_never final_suspend() { return {}; }
// TODO: Required by Clang 5-7 as it's built against a different version of the Coroutines TS (see https://clang.llvm.org/cxx_status.html). Remove once Clang updates to newer Coroutines TS.
#ifdef __clang__
void unhandled_exception() { UnhandledException(); }
#else
void set_exception(std::exception_ptr e) { HandleCoroutineException(std::move(e), m_taskCompletionSource); }
#endif
protected:
base_promise_type() = default;
base_promise_type(const base_promise_type&) = default;
~base_promise_type() = default;
arcana::task_completion_source<ResultT, ErrorT> m_taskCompletionSource;
};
template <typename ResultT, typename ErrorT>
class value_promise_type : public base_promise_type<ResultT, ErrorT>
{
public:
template <typename T>
void return_value(T&& result) { m_taskCompletionSource.complete(std::forward<T>(result)); }
};
template <typename ErrorT>
class void_promise_type : public base_promise_type<void, ErrorT>
{
public:
void return_void() { m_taskCompletionSource.complete(); }
};
}
// This enables generating a task<ResultT, ErrorT> return value from a coroutine. For example:
// task<int, std::error_code> DoSomethingAsync()
// {
// co_return 42;
// }
template <typename ResultT, typename ErrorT, typename... Args>
struct std::experimental::coroutine_traits<task<ResultT, ErrorT>, Args...>
{
using promise_type = arcana::internal::value_promise_type<ResultT, ErrorT>;
};
// This enables generating a task<void, std::exception_ptr> return value from a coroutine. For example:
// task<void, std::exception_ptr> DoSomethingAsync()
// {
// co_return;
// }
// NOTE: This is enabled for the std::exception_ptr case only, not std::error_code. This is because
// the promise_type can't have both a return_void and a return_value, which means it would not be
// able to support doing a co_return of an std::error_code. Because of this, we instead have to
// always co_return a value in the std::error_code case, and in the case of a task<void, std::error_code>
// coroutine that is successful, we have to return coroutine_success.
template <typename... Args>
struct std::experimental::coroutine_traits<task<void, std::exception_ptr>, Args...>
{
using promise_type = arcana::internal::void_promise_type<std::exception_ptr>;
};
// Microsoft's C++ standard library currently defines its own coroutine_traits for std::future.
// For other compilers we need to define our own, as defining this isn't currently part of the ISO C++ standard.
// _RESUMABLE_FUNCTIONS_SUPPORTED is the current macro used by the Microsoft C++ standard library to trigger definition of these traits.
#ifndef _RESUMABLE_FUNCTIONS_SUPPORTED
template <typename... Args>
struct std::experimental::coroutine_traits<std::future<void>, Args...>
{
class promise_type
{
public:
auto get_return_object() { return m_promise.get_future(); }
std::experimental::suspend_never initial_suspend() { return {}; }
std::experimental::suspend_never final_suspend() { return {}; }
// TODO: Replace this with set_exception once Clang updates to newer Coroutines TS.
void unhandled_exception() { arcana::internal::UnhandledException(); }
void return_void() { m_promise.set_value(); }
private:
std::promise<void> m_promise;
};
};
template <typename ResultT, typename... Args>
struct std::experimental::coroutine_traits<std::future<ResultT>, Args...>
{
class promise_type
{
public:
auto get_return_object() { return m_promise.get_future(); }
std::experimental::suspend_never initial_suspend() { return {}; }
std::experimental::suspend_never final_suspend() { return {}; }
// TODO: Replace this with set_exception once Clang updates to newer Coroutines TS.
void unhandled_exception() { arcana::internal::UnhandledException(); }
template <typename T>
void return_value(T&& result) { m_promise.set_value(std::forward<T>(result)); }
private:
std::promise<ResultT> m_promise;
};
};
#endif
namespace internal
{
// The task_awaiter_result class (plus void specialization) wrap an expected<ResultT, std::error_code> and ensure that any errors are observed.
// If the expected<ResultT, std::error_code> is in an error state and an attempt is made to access the value, an unobserved_error exception is thrown.
// This supports scenairos where a value is directly obtained:
// int result = co_await SomeTaskOfIntReturningFunction();
// If the expected<ResultT, std::error_code> is in an error state and is destroyed when the error has not been observed, an unobserved_error exception is thrown.
// This supports scenarios where the result of the co_await is ignored:
// co_await SomeTaskReturningFunctionThatResultsInAnError();
// This is propagated up to the coroutine_traits, and in the case of the arcana task coroutine_traits, the final task is set to an error
// state and contains the unobserved error (thereby propagating the error all the way to the caller).
template <typename ResultT>
class base_task_awaiter_result
{
public:
operator arcana::expected<ResultT, std::error_code>()
{
m_observed = true;
return m_expected;
}
protected:
base_task_awaiter_result(expected<ResultT, std::error_code>&& expected) :
m_expected(std::move(expected))
{
}
base_task_awaiter_result(base_task_awaiter_result&& other) :
m_expected(std::move(other.m_expected)),
m_observed(other.m_observed)
{
other.m_observed = true;
}
base_task_awaiter_result(const base_task_awaiter_result&) = delete;
base_task_awaiter_result& operator=(const base_task_awaiter_result&) = delete;
~base_task_awaiter_result() noexcept(false)
{
if (!m_observed && m_expected.has_error())
{
throw unobserved_error(m_expected.error());
}
}
expected<ResultT, std::error_code> m_expected;
bool m_observed{ false };
};
template <typename ResultT>
class task_awaiter_result : public base_task_awaiter_result<ResultT>
{
public:
template<typename T>
task_awaiter_result(T&& t)
: base_task_awaiter_result<ResultT>{ std::forward<T>(t) }
{}
operator ResultT()
{
m_observed = true;
if (m_expected.has_error())
{
throw unobserved_error(m_expected.error());
}
return m_expected.value();
}
};
template<>
class task_awaiter_result<void> : public base_task_awaiter_result<void>
{
public:
template<typename T>
task_awaiter_result(T&& t)
: base_task_awaiter_result<void>{ std::forward<T>(t) }
{}
};
template <typename SchedulerT, typename ResultT, typename ErrorT>
class base_task_awaiter
{
public:
base_task_awaiter(SchedulerT& scheduler, arcana::task<ResultT, ErrorT> task) : m_scheduler(scheduler), m_task(std::move(task)) {}
bool await_ready() { return false; }
void await_suspend(std::experimental::coroutine_handle<> coroutine)
{
auto continuation = m_task.then(m_scheduler, arcana::cancellation::none(),
[this, coroutine = std::move(coroutine)](const arcana::expected<ResultT, ErrorT>& result) noexcept(std::is_same<ErrorT, std::error_code>::value)
{
m_result = result;
coroutine.resume();
});
static_assert(std::is_same<decltype(continuation), arcana::task<void, ErrorT>>::value, "ErrorT of continuation should match ErrorT of task, otherwise we can introduce a try/catch (through task internals) in code that does not have exceptions enabled.");
}
protected:
using base = base_task_awaiter;
base_task_awaiter() = delete;
base_task_awaiter(const base_task_awaiter&) = default;
~base_task_awaiter() = default;
std::optional<arcana::expected<ResultT, ErrorT>> m_result;
private:
SchedulerT & m_scheduler;
arcana::task<ResultT, ErrorT> m_task;
};
}
// This enables awaiting a task<ResultT, std::error_code> within a coroutine. For example:
// std::future<int> DoAnotherThingAsync()
// {
// int result = co_await configure_await(arcana::inline_scheduler, DoSomethingAsync());
// return result;
// }
// - or -
// std::future<int> DoAnotherThingAsync()
// {
// expected<int, std::error_code> result = co_await configure_await(arcana::inline_scheduler, DoSomethingAsync());
// return result.value();
// }
template <typename SchedulerT, typename ResultT>
inline auto configure_await(SchedulerT& scheduler, task<ResultT, std::error_code> task)
{
class task_awaiter : private arcana::internal::base_task_awaiter<SchedulerT, ResultT, std::error_code>
{
public:
using base::base;
using base::await_ready;
using base::await_suspend;
auto await_resume()
{
return arcana::internal::task_awaiter_result<ResultT>(std::move(*m_result));
}
};
return task_awaiter{ scheduler, std::move(task) };
}
// This enables awaiting a task<ResultT, std::exception_ptr> within a coroutine. For example:
// std::future<int> DoAnotherThingAsync()
// {
// auto result = co_await configure_await(arcana::inline_scheduler, DoSomethingAsync());
// return result;
// }
template <typename SchedulerT, typename ResultT>
inline auto configure_await(SchedulerT& scheduler, task<ResultT, std::exception_ptr> task)
{
class task_awaiter : private arcana::internal::base_task_awaiter<SchedulerT, ResultT, std::exception_ptr>
{
public:
using base::base;
using base::await_ready;
using base::await_suspend;
ResultT await_resume()
{
if (m_result->has_error())
{
std::rethrow_exception(m_result->error());
}
return std::move(m_result->value());
}
};
return task_awaiter{ scheduler, std::move(task) };
}
// This enables awaiting a task<void, std::exception_ptr> within a coroutine. For example:
// std::future<void> DoAnotherThingAsync()
// {
// co_await configure_await(arcana::inline_scheduler, DoSomethingAsync());
// }
template <typename SchedulerT>
inline auto configure_await(SchedulerT& scheduler, task<void, std::exception_ptr> task)
{
class task_awaiter : private arcana::internal::base_task_awaiter<SchedulerT, void, std::exception_ptr>
{
public:
using base::base;
using base::await_ready;
using base::await_suspend;
void await_resume()
{
if (m_result->has_error())
{
std::rethrow_exception(m_result->error());
}
}
};
return task_awaiter{ scheduler, std::move(task) };
}
// This enables awaiting a scheduler (e.g. switching scheduler/dispatcher contexts). For example:
// std::future<void> DoSomethingAsync()
// {
// // do some stuff in the current scheduling context
// co_await switch_to(background_dispatcher);
// // do some stuff on a background thread
// co_await switch_to(render_dispatcher);
// // do some stuff on the render thread
// }
template <typename SchedulerT>
inline auto switch_to(SchedulerT& scheduler)
{
class scheduler_awaiter
{
public:
scheduler_awaiter(SchedulerT& scheduler) : m_scheduler(scheduler) {}
bool await_ready() { return false; }
void await_resume() {}
void await_suspend(std::experimental::coroutine_handle<> coroutine)
{
m_scheduler([coroutine = std::move(coroutine)]
{
coroutine.resume();
});
}
private:
SchedulerT& m_scheduler;
};
return scheduler_awaiter{ scheduler };
}
}
#endif
| 38.76962 | 269 | 0.610095 | [
"render"
] |
f34fe94878d596e5180480e9fa807e3cc581dc03 | 648 | h | C | include/OnePoint.PROM/GeofenceSurveyFactory.h | OnePointGlobal/MySurvey-2.0-App_New | 02368bee4a3b5b9e07f95d586c02c20880e35a4b | [
"MIT"
] | null | null | null | include/OnePoint.PROM/GeofenceSurveyFactory.h | OnePointGlobal/MySurvey-2.0-App_New | 02368bee4a3b5b9e07f95d586c02c20880e35a4b | [
"MIT"
] | 12 | 2019-10-14T10:29:55.000Z | 2020-04-23T10:52:13.000Z | include/OnePoint.PROM/GeofenceSurveyFactory.h | OnePointGlobal/OnePoint-Global-MySurvey-2.0-App-iOS-Latest | 02368bee4a3b5b9e07f95d586c02c20880e35a4b | [
"MIT"
] | 1 | 2022-03-17T08:46:39.000Z | 2022-03-17T08:46:39.000Z | //------------------------------------------------------------------------
// Generated on 23-01-2017 01:06:35 PM for ADMIN\User
//
// This file was autogenerated but you can (and are meant to) edit it as
// it will not be overwritten unless explicitly requested.
//------------------------------------------------------------------------
#import <Foundation/Foundation.h>
#import "GeofenceSurveyFactoryBase.h"
#import "GeofenceSurvey.h"
#import "IGeofenceSurveyData.h"
#import <OnePointFramework/IDisposable.h>
//package OnePoint.PROM.Model
@interface GeofenceSurveyFactory : GeofenceSurveyFactoryBase<IDisposable> {
}
@end
| 34.105263 | 76 | 0.57716 | [
"model"
] |
f36255917bcefd879d7fbebd59750c22628e9dd0 | 423 | h | C | OSE/src/OSE/Blueprints/Camera.h | CreoDen-dev/OSE | 0179271058260441354ce16e5935056e13fbb40a | [
"Apache-2.0"
] | null | null | null | OSE/src/OSE/Blueprints/Camera.h | CreoDen-dev/OSE | 0179271058260441354ce16e5935056e13fbb40a | [
"Apache-2.0"
] | null | null | null | OSE/src/OSE/Blueprints/Camera.h | CreoDen-dev/OSE | 0179271058260441354ce16e5935056e13fbb40a | [
"Apache-2.0"
] | null | null | null | #ifndef OSE_CAMERA_H
#define OSE_CAMERA_H
#include <OSE/Core.h>
#include <OSE/Math/Vecmath.h>
#include <OSE/Math/Transform.h>
namespace OSE {
class OSE_API Camera {
public:
Camera(int width, int height);
~Camera();
mat4 getProjection();
mat4 getView();
Transform& getTransform();
vec4 getForward();
vec4 getUp();
vec4 getRight();
protected:
Transform m_transform;
mat4 m_projection;
};
}
#endif | 15.666667 | 32 | 0.699764 | [
"transform"
] |
b3d7f29dcf6805eef3d9d1507a34845fadb8d168 | 6,513 | h | C | src/chrono_fsi/ChFsiInterface.h | lucasw/chrono | e79d8c761c718ecb4c796725cff37026f357da8c | [
"BSD-3-Clause"
] | 1,383 | 2015-02-04T14:17:40.000Z | 2022-03-30T04:58:16.000Z | src/chrono_fsi/ChFsiInterface.h | pchaoWT/chrono | fd68d37d1d4ee75230dc1eea78ceff91cca7ac32 | [
"BSD-3-Clause"
] | 245 | 2015-01-11T15:30:51.000Z | 2022-03-30T21:28:54.000Z | src/chrono_fsi/ChFsiInterface.h | pchaoWT/chrono | fd68d37d1d4ee75230dc1eea78ceff91cca7ac32 | [
"BSD-3-Clause"
] | 351 | 2015-02-04T14:17:47.000Z | 2022-03-30T04:42:52.000Z | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Author: Milad Rakhsha, Arman Pazouki, Wei Hu
// =============================================================================
//
// Base class for processing the interface between Chrono and FSI modules
// =============================================================================
#ifndef CH_FSI_INTERFACE_H
#define CH_FSI_INTERFACE_H
#include "chrono/ChConfig.h"
#include "chrono/physics/ChSystem.h"
#include "chrono_fsi/ChApiFsi.h"
#include "chrono_fsi/ChSystemFsi_impl.cuh"
#include "chrono_fsi/physics/ChFsiGeneral.h"
namespace chrono {
// Forward declarations
namespace fea {
class ChNodeFEAxyzD;
class ChMesh;
class ChElementCableANCF;
class ChElementShellANCF_3423;
}
namespace fsi {
/// @addtogroup fsi_physics
/// @{
/// Base class for processing the interface between Chrono and FSI modules.
class ChFsiInterface : public ChFsiGeneral {
public:
/// Constructor of the FSI interface class.
ChFsiInterface(ChSystem& other_mphysicalSystem,
std::shared_ptr<fea::ChMesh> other_fsiMesh,
std::shared_ptr<SimParams> other_paramsH,
std::shared_ptr<FsiBodiesDataH> other_fsiBodiesH,
std::shared_ptr<FsiMeshDataH> other_fsiMeshH,
std::vector<std::shared_ptr<ChBody>>& other_fsiBodies,
std::vector<std::shared_ptr<fea::ChNodeFEAxyzD>>& other_fsiNodes,
std::vector<std::shared_ptr<fea::ChElementCableANCF>>& other_fsiCables,
std::vector<std::shared_ptr<fea::ChElementShellANCF_3423>>& other_fsiShells,
thrust::host_vector<int2>& other_CableElementsNodesH,
thrust::device_vector<int2>& other_CableElementsNodes,
thrust::host_vector<int4>& other_ShellElementsNodesH,
thrust::device_vector<int4>& other_ShellElementsNodes,
thrust::device_vector<Real3>& other_rigid_FSI_ForcesD,
thrust::device_vector<Real3>& other_rigid_FSI_TorquesD,
thrust::device_vector<Real3>& other_Flex_FSI_ForcesD);
/// Destructor of the FSI interface class.
~ChFsiInterface();
/// Read the surface-integrated pressure and viscous forces form the fluid/granular dynamics system,
/// and add these forces and torques as external forces to the ChSystem rigid bodies.
void Add_Rigid_ForceTorques_To_ChSystem();
/// Use an external configuration to set the generalized coordinates of the ChSystem.
void Copy_External_To_ChSystem();
/// Use the generalized coordinates of the ChSystem to set the configuration state in the FSI system.
void Copy_ChSystem_to_External();
/// Copy the ChSystem rigid bodies from CPU to GPU.
void Copy_fsiBodies_ChSystem_to_FluidSystem(std::shared_ptr<FsiBodiesDataD> fsiBodiesD);
/// Resize the number of ChSystem rigid bodies.
void ResizeChronoBodiesData();
/// Set the FSI mesh for flexible elements.
void SetFsiMesh(std::shared_ptr<fea::ChMesh> other_fsi_mesh) { fsi_mesh = other_fsi_mesh; };
/// Add forces and torques as external forces to the ChSystem flexible bodies.
void Add_Flex_Forces_To_ChSystem();
/// Resize number of nodes used in the flexible elements
void ResizeChronoNodesData();
/// Resize number of cable elements used in the flexible elements
void ResizeChronoCablesData(std::vector<std::vector<int>> CableElementsNodesSTDVector,
thrust::host_vector<int2>& CableElementsNodesH);
/// Resize number of shell elements used in the flexible elements
void ResizeChronoShellsData(std::vector<std::vector<int>> ShellElementsNodesSTDVector,
thrust::host_vector<int4>& ShellElementsNodesH);
/// Resize number of nodes used in the flexible elements
void ResizeChronoFEANodesData();
/// Copy the nodes information in ChSystem from CPU to GPU.
void Copy_fsiNodes_ChSystem_to_FluidSystem(std::shared_ptr<FsiMeshDataD> FsiMeshD);
private:
ChSystem& mphysicalSystem; ///< Chrono system handled by the FSI system
std::shared_ptr<FsiBodiesDataH> fsiBodiesH; ///< states of the FSI rigid bodies
std::shared_ptr<ChronoBodiesDataH> chronoRigidBackup; ///< backup for the Chrono system state
std::shared_ptr<FsiMeshDataH> fsiMeshH; ///< information of the FEA mesh participating in FSI
std::shared_ptr<ChronoMeshDataH> chronoFlexMeshBackup; ///< backup for the Chrono system state
std::shared_ptr<SimParams> paramsH; ///< simulation parameters
thrust::device_vector<Real3>& rigid_FSI_ForcesD; ///< forces from the fluid dynamics system to rigid bodies
thrust::device_vector<Real3>& rigid_FSI_TorquesD; ///< torques from the fluid dynamics system to rigid bodies
thrust::device_vector<Real3>& Flex_FSI_ForcesD; ///< forces from the fluid dynamics system to flexible bodies
std::shared_ptr<fea::ChMesh> fsi_mesh;
std::vector<std::shared_ptr<ChBody>>& fsiBodies; ///< bodies handled by the FSI system
std::vector<std::shared_ptr<fea::ChNodeFEAxyzD>>& fsiNodes; ///< FEA nodes available in FSI system
std::vector<std::shared_ptr<fea::ChElementCableANCF>>& fsiCables; ///< FEA cable elements in FSI system
std::vector<std::shared_ptr<fea::ChElementShellANCF_3423>>& fsiShells; ///< FEA shell elements in FSI system
thrust::host_vector<int2>& CableElementsNodesH; ///< indices of nodes of each element
thrust::device_vector<int2>& CableElementsNodes; ///< indices of nodes of each element
thrust::host_vector<int4>& ShellElementsNodesH; ///< indices of nodes of each element
thrust::device_vector<int4>& ShellElementsNodes; ///< indices of nodes of each element
};
/// @} fsi_physics
} // end namespace fsi
} // end namespace chrono
#endif
| 48.969925 | 116 | 0.656533 | [
"mesh",
"vector"
] |
b3e0f26083671a6e85f4cf02da0982d8c91c1b09 | 1,762 | c | C | mingwrt/mingwex/math/round_generic.c | stahta01/mingw-org-wsl | 0c111acc00bc15f5270535a71ee1601a3ed4a168 | [
"MIT"
] | 1 | 2022-01-05T07:40:02.000Z | 2022-01-05T07:40:02.000Z | mingwrt/mingwex/math/round_generic.c | stahta01/mingw-org-wsl | 0c111acc00bc15f5270535a71ee1601a3ed4a168 | [
"MIT"
] | null | null | null | mingwrt/mingwex/math/round_generic.c | stahta01/mingw-org-wsl | 0c111acc00bc15f5270535a71ee1601a3ed4a168 | [
"MIT"
] | 1 | 2022-01-05T07:40:51.000Z | 2022-01-05T07:40:51.000Z | /*
* round_generic.c
*
* $Id$
*
* Provides a generic implementation for the `round()', `roundf()'
* and `roundl()' functions; compile with `-D FUNCTION=name', with
* `name' set to each of these three in turn, to create separate
* object files for each of the three functions.
*
* Written by Keith Marshall <keithmarshall@users.sourceforge.net>
*
* This is free software. You may redistribute and/or modify it as you
* see fit, without restriction of copyright.
*
* This software is provided "as is", in the hope that it may be useful,
* but WITHOUT WARRANTY OF ANY KIND, not even any implied warranty of
* MERCHANTABILITY, nor of FITNESS FOR ANY PARTICULAR PURPOSE. At no
* time will the author accept any form of liability for any damages,
* however caused, resulting from the use of this software.
*
*/
#ifndef FUNCTION
/*
* Normally specified with `-D FUNCTION=name', on the command line.
* Valid FUNCTION names are `round', `roundf' and `roundl'; specifying
* anything else will most likely cause a compilation error. If user
* did not specify any FUNCTION name, default to `round'.
*/
#define FUNCTION round
#endif
#include "round_internal.h"
/* Generic implementation.
* The user is required to specify the FUNCTION name;
* the RETURN_TYPE and INPUT_TYPE macros resolve to appropriate
* type declarations, to match the selected FUNCTION prototype.
*/
RETURN_TYPE FUNCTION( INPUT_TYPE x )
{
/* Round to nearest integer, away from zero for half-way.
*
* We split it with the `round_internal()' function in
* a private header file, so that it may be shared by this,
* `lround()' and `llround()' implementations.
*/
return isfinite( x ) ? round_internal( x ) : x;
}
/* $RCSfile$$Revision$: end of file */
| 33.884615 | 72 | 0.715664 | [
"object"
] |
b3e886d4c4b1d444a5a529e75ae84f6038596170 | 49,411 | h | C | ssm/src/captivate/BASE/CAPT_HAL.h | charitywater/india-mark-ii-sensor | 5485ef175ba6aab03897bb9d98c417bb8c702e16 | [
"Apache-2.0"
] | 2 | 2021-10-19T11:47:50.000Z | 2021-10-30T19:36:34.000Z | ssm/src/captivate/BASE/CAPT_HAL.h | charitywater/india-mark-ii-sensor | 5485ef175ba6aab03897bb9d98c417bb8c702e16 | [
"Apache-2.0"
] | null | null | null | ssm/src/captivate/BASE/CAPT_HAL.h | charitywater/india-mark-ii-sensor | 5485ef175ba6aab03897bb9d98c417bb8c702e16 | [
"Apache-2.0"
] | null | null | null | /* --COPYRIGHT--,BSD
* Copyright (c) 2017, Texas Instruments Incorporated
* 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 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.
* --/COPYRIGHT--*/
//*****************************************************************************
// CAPT_HAL.h
//
//! Low level CapTIvate configuration and peripheral hardware abstraction module.
//
//! This module contains low-level APIs for accessing the CapTIvate&tm; IP.
//! Some functions are a direct access of the CapTIvate&tm; registers while
//! others take the definitions (see CAPT_Type.h) and place the appropriate
//! values in the CapTIvate&tm; peripheral registers.
//
//! \version 1.82.00.02
//! Released on January 22, 2020
//
//*****************************************************************************
//*****************************************************************************
//! \addtogroup CAPT_HAL
//! @{
//*****************************************************************************
#ifndef CAPT_HAL_H_
#define CAPT_HAL_H_
#ifndef S_SPLINT_S
#include <stdint.h>
#include <stdbool.h>
#endif
#include <msp430.h>
#include "CAPT_Type.h"
//*****************************************************************************
//
// CapTIvate&tm; Timer Sources
//
//*****************************************************************************
#define CAPT_TIMER_SRC_ACLK (0x00)
#define CAPT_TIMER_SRC_VLOCLK (0x01)
//*****************************************************************************
//
// CapTIvate&tm; Timer Source Dividers
//
//*****************************************************************************
#define CAPT_TIMER_CLKDIV__1 (0x00)
#define CAPT_TIMER_CLKDIV__2 (0x01)
#define CAPT_TIMER_CLKDIV__4 (0x02)
#define CAPT_TIMER_CLKDIV__8 (0x03)
#define CAPT_TIMER_CLKDIV__16 (0x04)
#define CAPT_TIMER_CLKDIV__32 (0x05)
#define CAPT_TIMER_CLKDIV__64 (0x06)
#define CAPT_TIMER_CLKDIV__128 (0x07)
//*****************************************************************************
//
// CapTIvate&tm; Conversion Counter Interval Selections
//
//*****************************************************************************
#define CAPT_COUNTER__16 (0x00)
#define CAPT_COUNTER__32 (0x01)
#define CAPT_COUNTER__64 (0x02)
#define CAPT_COUNTER__128 (0x03)
#define CAPT_COUNTER__256 (0x04)
#define CAPT_COUNTER__512 (0x05)
#define CAPT_COUNTER__1024 (0x06)
#define CAPT_COUNTER__2048 (0x07)
#define CAPT_COUNTER__DISABLED (0x08)
//*****************************************************************************
//
// CapTIvate&tm; Conversion Clock Oscillator Frequencies
//
//*****************************************************************************
#define CAPT_OSC_FREQ_DEFAULT (0x00)
#define CAPT_OSC_FREQ_16MHZ (0x00)
#define CAPT_OSC_FREQ_14P7MHZ (0x01)
#define CAPT_OSC_FREQ_13P1MHZ (0x02)
#define CAPT_OSC_FREQ_11P2MHZ (0x03)
//*****************************************************************************
//
// CapTIvate&tm; Reference Capacitor Sizes
//
//*****************************************************************************
#define CAPT_REFERENCE_CAP__SELF_1P0PF (0x00)
#define CAPT_REFERENCE_CAP__SELF_1P1PF (0x04)
#define CAPT_REFERENCE_CAP__SELF_1P5PF (0x05)
#define CAPT_REFERENCE_CAP__SELF_5P0PF (0x02)
#define CAPT_REFERENCE_CAP__SELF_5P1PF (0x06)
#define CAPT_REFERENCE_CAP__SELF_5P5PF (0x07)
#define CAPT_REFERENCE_CAP__MUTUAL_0P1PFM_1P0PF (0x00)
#define CAPT_REFERENCE_CAP__MUTUAL_0P5PFM_1P0PF (0x01)
#define CAPT_REFERENCE_CAP__MUTUAL_0P1PFM_5P0PF (0x02)
#define CAPT_REFERENCE_CAP__MUTUAL_0P5PFM_5P0PF (0x03)
//*****************************************************************************
//
// CapTIvate&tm; Coarse Gain Ratios
//
//*****************************************************************************
#define CAPT_COARSEGAIN_0 (0x00)
#define CAPT_COARSEGAIN_1 (0x01)
#define CAPT_COARSEGAIN_2 (0x02)
#define CAPT_COARSEGAIN_3 (0x03)
#define CAPT_COARSEGAIN_4 (0x04)
#define CAPT_COARSEGAIN_5 (0x05)
#define CAPT_COARSEGAIN_6 (0x06)
#define CAPT_COARSEGAIN_7 (0x07)
#define CAPT_COARSEGAIN_MIN (CAPT_COARSEGAIN_0)
#define CAPT_COARSEGAIN_MAX (CAPT_COARSEGAIN_7)
//*****************************************************************************
//
// CapTIvate&tm; Fine Gain Ratios
//
//*****************************************************************************
#define CAPT_FINEGAIN_0 (0x00)
#define CAPT_FINEGAIN_1 (0x01)
#define CAPT_FINEGAIN_2 (0x02)
#define CAPT_FINEGAIN_3 (0x03)
#define CAPT_FINEGAIN_4 (0x04)
#define CAPT_FINEGAIN_5 (0x05)
#define CAPT_FINEGAIN_6 (0x06)
#define CAPT_FINEGAIN_7 (0x07)
#define CAPT_FINEGAIN_8 (0x08)
#define CAPT_FINEGAIN_9 (0x09)
#define CAPT_FINEGAIN_10 (0x0A)
#define CAPT_FINEGAIN_11 (0x0B)
#define CAPT_FINEGAIN_12 (0x0C)
#define CAPT_FINEGAIN_13 (0x0D)
#define CAPT_FINEGAIN_14 (0x0E)
#define CAPT_FINEGAIN_15 (0x0F)
#define CAPT_FINEGAIN_16 (0x10)
#define CAPT_FINEGAIN_17 (0x11)
#define CAPT_FINEGAIN_18 (0x12)
#define CAPT_FINEGAIN_19 (0x13)
#define CAPT_FINEGAIN_MIN (CAPT_FINEGAIN_0)
#define CAPT_FINEGAIN_MAX (CAPT_FINEGAIN_19)
//*****************************************************************************
//
// CapTIvate&tm; Offset Tap Values
//
//*****************************************************************************
#define CAPT_OFFSETTAP_MIN (0x00)
#define CAPT_OFFSETTAP_MAX (0xFF)
//*****************************************************************************
//
// CapTIvate&tm; Offset Scale Values
//
//*****************************************************************************
#define CAPT_OFFSETSCALE__VERYSMALL (0x0000)
#define CAPT_OFFSETSCALE__SMALL (0x0100)
#define CAPT_OFFSETSCALE__LARGE (0x0200)
#define CAPT_OFFSETSCALE__VERYLARGE (0x0300)
#define CAPT_OFFSETSCALE_MIN (CAPT_OFFSETSCALE__VERYSMALL)
#define CAPT_OFFSETSCALE_MAX (CAPT_OFFSETSCALE__VERYLARGE)
//*****************************************************************************
//
// CapTIvate&tm; Interrupt Definitions
//
//*****************************************************************************
#define CAPT_END_OF_CONVERSION_INTERRUPT (0x0001)
#define CAPT_DETECTION_INTERRUPT (0x0002)
#define CAPT_TIMER_INTERRUPT (0x0004)
#define CAPT_CONVERSION_COUNTER_INTERRUPT (0x0008)
#define CAPT_MAX_COUNT_ERROR_INTERRUPT (0x0100)
//*****************************************************************************
//
// CapTIvate&tm; Interrupt Vectors
//
//*****************************************************************************
#define CAPT_IV_NO_INTERRUPT (0x0000)
#define CAPT_IV_END_OF_CONVERSION (0x0002)
#define CAPT_IV_DETECTION (0x0004)
#define CAPT_IV_TIMER (0x0006)
#define CAPT_IV_CONVERSION_COUNTER (0x0008)
#define CAPT_IV_MAX_COUNT_ERROR (0x000A)
//*****************************************************************************
//
//! CAPT_init is not a ROM function. This function initializes global
//! parameters of the CapTIvate peripheral that are independent of mode and
//! application. This function should always be called once to initialize
//! the peripheral after a reset.
//!
//
//! Initialize global settings for an application.
//! \par Parameters
//! none
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_init(void);
//*****************************************************************************
//
//! Poll Reset Status Flag of the CapTIvate peripheral; 0, reset is not
//! complete. This function is intended to be used after the CAPT_reset()
//! function to determine that the peripheral is ready.
//!
//! \par Parameters
//! none
//! \return Reset State
//
//*****************************************************************************
extern bool CAPT_pollResetStatus(void);
//*****************************************************************************
//
//! Poll Conversion in progress flag (CIPF); 0, no conversion in progress. The
//! CIPF is not directly correlated to the conversion start: following a
//! conversion start there is a period during which the CIPF is 0 before
//! transitioning to a 1 when the actual convesion takes place.
//!
//! \par Parameters
//! none
//! \return CIPF state
//
//*****************************************************************************
extern bool CAPT_pollCIPF(void);
//*****************************************************************************
//
//! Reset the CapTIvate peripheral.
//!
//! \par Parameters
//! none
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_reset(void);
//*****************************************************************************
//
//! Set Stabilization control bit. This bit is used whenever a conversion is
//! predicated on a user controlled stabilization time. The stabilization
//! control must be set before the conversion is started.
//!
//! \par Parameters
//! none
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_setStabilization(void);
//*****************************************************************************
//
//! Clear Stabilization control bit. This bit is used whenever a conversion
//! is predicated on a user controlled stabilization time. Although the IO
//! will be active, clearing the stabilization control bit will start the
//! actual measurement.
//!
//! \par Parameters
//! none
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_releaseStabilization(void);
//*****************************************************************************
//
//! Enable a Reference cap for a specific block. The element definition,
//! tElement.ui8RxBlock, is used to determine which block the reference
//! capacitor is applied to. The reference capacitor size is defined in the
//! following table:
//! Size Self Value Mutual Value
//! 0 1.0pF 0.1pF
//! 1 1.0pF 0.5pF
//! 2 5.0pF 0.1pF
//! 3 5.0pF 0.5pF
//! 4 1.1pF 0.1pF
//! 5 1.5pF 0.1pF
//! 6 5.1pF 0.1pF
//! 7 5.5pF 0.1pF
//!
//! \param pElement = pointer to element
//! \param capSize = size of cap
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_enableRefCap(tElement* pElement, uint8_t capSize);
//*****************************************************************************
//
//! Disable and Remove the Reference Capacitor from the measurement circuit.
//!
//! \par Parameters
//! none
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_disableRefCap(void);
//*****************************************************************************
//
//! Enable all IO associated with a sensor. When a CapTIvate IO is enabled it
//! is in the analog mode and the digital function is disabled. Before
//! enabling the IO it is recommended to set the appropriate IO state as
//! defined in the tSensor.bIdleState, with the CAPT_initSensorIO function.
//!
//! \param pSensor = pointer to sensor
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_enableSensorIO(tSensor *pSensor);
//*****************************************************************************
//
//! Disable all IO associated with a sensor.
//!
//! \param pSensor = pointer to sensor
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_disableSensorIO(tSensor *pSensor);
//*****************************************************************************
//
//! This function configures the active (Rx or Tx) and inactive
//! (High-z or GND) states of the captivate channels, for a given sensor, as
//! well as initialize the IO to the inactive state.
//!
//! \param pSensor = pointer to sensor
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_initSensorIO(tSensor *pSensor);
//*****************************************************************************
//
//! Set all Sensor IO to Tx or Rx based upon parameter passed.
//! Also make these active.
//!
//! \param rxBarTx = Set to Rx if eSelf (0) or Tx if eProjected (1)
//! \param pSensor = pointer to sensor
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_forceSensorIO(tSenseTechnology rxBarTx, tSensor *pSensor);
//*****************************************************************************
//
//! Initialize Sensor specific settings that will remain constant for
//! all cycles within the Sensor.
//! Parameters Applied:
//! tSensor.SensingMethod
//! tSensor.DirectionOfInterest
//! tSensor.ui16NegativeTouchThreshold
//! tSensor.ui16ProxThreshold
//! tSensor.bModEnable
//! tSensor.ui8BiasControl
//! tSensor.bCsDischarge
//! tSensor.bLPMControl
//! tSensor.ui8InputSyncControl
//! tSensor.bTimerSyncControl
//! tSensor.ui8ChargeLength
//! tSensor.ui8TransferLength
//! tSensor.ui16ErrorThreshold
//! tSensor.ui8CntBeta
//! tSensor.ui8LTABeta
//! tSensor.bSensorHalt
//! tSensor.bPTSensorHalt
//! tSensor.bSensorTouch
//! tSensor.bSensorProx
//!
//! \param pSensor = pointer to sensor
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_applySensorParams(tSensor *pSensor);
//*****************************************************************************
//
//! Enable Sync event. When enabled the start of conversion is gated by the
//! edge of the SYNC pin.
//!
//! \par Parameters
//! none
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_enableSensorSyncEvent(void);
//*****************************************************************************
//
//! Disable Sync event.
//!
//! \par Parameters
//! none
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_disableSensorSyncEvent(void);
//*****************************************************************************
//
//! Bypass FSM. Bypassing the FSM only the maximum count and end of
//! conversion IFGs are updated.
//!
//! \par Parameters
//! none
//! \par Returns
//! none.
//
//*****************************************************************************
extern void CAPT_bypassFSM(void);
//*****************************************************************************
//
//! Engage FSM. The Finite State Machine (FSM), performs several post
//! measurement filters for the LTA, and measurement filter count as well as
//! well as detection logic.
//!
//! \par Parameters
//! none
//! \par Returns
//! none
//!
//
//*****************************************************************************
extern void CAPT_engageFSM(void);
//*****************************************************************************
//
//! Apply the Sensor frequency divider and for the requested frequency select.
//! This frequency is consistent for all elements within the cycle.
//! freqSelect Frequency
//! 0 16Mhz
//! 1 14.7Mhz
//! 2 13.1Mhz
//! 3 11.2Mhz
//!
//! \param freqSelect = frequency
//! \param pSensor = pointer to sensor
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_applySensorFreq(uint8_t freqSelect, tSensor *pSensor);
//*****************************************************************************
//
//! Initialize cycle IO parameters. Set to active the channels required for
//! the cycle measurement. The peripheral will manage the IO state
//! transitioning the active channels between the defined active state
//! (Rx or Tx) when actively measuring capacitance and the inactive state
//! (GND or High-Z) when the measurement is complete. All channels that are
//! not active but enabled will remain in their inactive state.
//!
//! \param pSensor = pointer to sensor
//! \param pCycle = pointer to cycle
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_setCycleIO(tSensor *pSensor,tCycle *pCycle);
//*****************************************************************************
//
//! Clear cycle IO parameters. Clear active channels.
//!
//! \param pSensor = pointer to sensor
//! \param pCycle = pointer to cycle
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_clearCycleIO(tSensor *pSensor, tCycle *pCycle);
//*****************************************************************************
//
//! Initialize cycle level parameters. These parameters are consistent for
//! all elements within the cycle.
//!
//! \param freqOffset = offset to indicate which frequency is being measured
//! \param pCycle = pointer to cycle
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_applyCycleComp(uint8_t freqOffset,tCycle * pCycle);
//*****************************************************************************
//
//! Only valid on certain devices, please consult device-specific datasheet.
//! Initialize cycle level parameters when using the hardware FSM to frequency
//! hop. Only available on devices that support hardware frequency hopping.
//! Loads all parameters necessary to perform a full frequency hop operation.
//!
//! \param pCycle = pointer to cycle
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_applyAutoMultiFreqCycleComp(tCycle *pCycle);
//*****************************************************************************
//
//! Apply cycle level parameters. These parameters are consistent for all
//! elements within the cycle.
//!
//! \param pCycle = pointer to cycle
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_applyCycleFSM(tCycle *pCycle);
//*****************************************************************************
//
//! Enable ISR. The interrupts are defined as follows:
//! BIT0 End of Conversion interrupt enable
//! BIT1 CapTIvate detection interrupt enable
//! BIT2 CapTIvate Timer interrupt enable
//! BIT3 CapTIvate Conversion Counter interrupt enable
//! BIT8 CapTIvate maximum count error interrupt enable
//!
//! \param interruptEnable = Interrupt(s) to enable
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_enableISR(uint16_t interruptEnable);
//*****************************************************************************
//
//! Disable ISR. The interrupts are defined as follows:
//! BIT0 End of Conversion interrupt disable
//! BIT1 CapTIvate detection interrupt disable
//! BIT2 CapTIvate Timer interrupt disable
//! BIT3 CapTIvate Conversion Counter interrupt disable
//! BIT8 CapTIvate maximum count error interrupt disable
//!
//! \param interruptDisable = Interrupt(s) to disable
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_disableISR(uint16_t interruptDisable);
//*****************************************************************************
//
//! Set the cycle conversion bit. If the CAPPWR bit is set
//! (call CAPT_powerOn), then setting the cycle conversion bit will start the
//! conversion process - the actual conversion (indicated by CAPT_pollCIPF
//! returning a '1') will take place after the stabilization time. If the
//! SYNC enable is set, either via the sensor configuration and
//! CAPT_applySensor API or the CAPT_enableSensorSyncEvent API, then the
//! conversion will be gate by the SYNC event (rising/falling edge) on the
//! SYNC pin.
//!
//! \par Parameters
//! none
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_setCAPSTART(void);
//*****************************************************************************
//
//! Clear the cycle conversion bit. When the conversion is in progress,
//! calling CAPT_clearCAPSTART will stop the conversion.
//!
//! \par Parameters
//! none
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_clearCAPSTART(void);
//*****************************************************************************
//
//! Save the current status of the peripheral into the data structures of
//! Raw measurement information is stored in:
//! pCycle->pElement[n]->pRawCount[indexFreq], where n is 0 to
//! pCycle.ui8NumberofElements
//! If there is a maximum count error, then the bit pSensor->bMaxCountError is
//! set and the value in pCycle->pElement[n]->pRawCount[indexFreq] is cleared.
//!
//! \param indexFreq = save results for selected frequency.
//! \param pSensor = pointer to sensor.
//! \param pCycle = pointer to cycle.
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_saveCycleRawResults(uint8_t indexFreq,tSensor *pSensor, tCycle *pCycle);
//*****************************************************************************
//
//! Save filter results, pElements[n]->LTA and pElements[n]->filterCount, and
//! status bits, pElements[n]->bDetect and pElements[n]->bNegativeTouch, in
//! addition to what is saved in CAPT_saveCycleRawResults from the peripheral.
//!
//! \param pSensor = pointer to sensor.
//! \param pCycle = pointer to cycle.
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_saveCycleResults(tSensor *pSensor ,tCycle *pCycle);
//*****************************************************************************
//
//! Only valid on certain devices, please consult device-specific datasheet.
//! To be used for Automatic (Hardware) Multiple Frequency use cases only:
//! transfer of Memory Mapped Registers to SRAM structs is slightly different.
//!
//! Save filter results, pElements[n]->LTA and pElements[n]->filterCount, and
//! status bits, pElements[n]->bDetect and pElements[n]->bNegativeTouch, in
//! addition to what is saved in CAPT_saveCycleRawResults from the peripheral.
//!
//! \param pSensor = pointer to sensor.
//! \param pCycle = pointer to cycle.
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_saveCycleResultsAutoMultiFreq(tSensor *pSensor, tCycle *pCycle);
//*****************************************************************************
//
//! Select the CapTIvate&tm; counter interval. The input represents the number
//! of conversions until a counter overflow event, CAPCNTRIFG.
//! counterSel Number of Conversions
//! 0 16
//! 1 32
//! 2 64
//! 3 128
//! 4 256
//! 5 512
//! 6 1024
//! 7 2048
//!
//! \param counterSel = counter selection
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_selectCCounterInterval(uint8_t counterSel);
//*****************************************************************************
//
//! Clear the CapTIvate&tm; counter interval.
//!
//! \par Parameters
//! none
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_clearCCounter(void);
//*****************************************************************************
//
//! Start (enable) the CapTIvate&tm; counter interval.
//!
//! \par Parameters
//! none
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_startCCounter(void);
//*****************************************************************************
//
//! Stop (disable) the CapTIvate&tm; counter interval.
//!
//! \par Parameters
//! none
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_stopCCounter(void);
//*****************************************************************************
//
//! Select the input divider to the CapTIvate&tm; timer.
//!
//! \param sourceDiv = time source divider
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_selectTimerSourceDivider(uint8_t sourceDiv);
//*****************************************************************************
//
//! Select the input source to the CapTIvate&tm; timer.
//!
//! \param source = timer source selection
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_selectTimerSource(uint8_t source);
//*****************************************************************************
//
//! Enable measurements to be triggered from CapTIvate&tm; timer.
//! Set CAPTCCTRL0:CAPTCONV
//!
//! \par Parameters
//! none
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_enableTimerTrigMeasurement(void);
//*****************************************************************************
//
//! Disable measurements to be triggered from CapTIvate&tm; timer.
//! Clear CAPTCCTRL0:CAPTCONV
//!
//! \par Parameters
//! none
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_disableTimerTrigMeasurement(void);
//*****************************************************************************
//
//! Clear the CapTIvate&tm; timer.
//!
//! \par Parameters
//! none
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_clearTimer(void);
//*****************************************************************************
//
//! Start (enable) the CapTIvate&tm; timer.
//!
//! \par Parameters
//! none
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_startTimer(void);
//*****************************************************************************
//
//! Stop (disable) the CapTIvate&tm; timer.
//!
//! \par Parameters
//! none
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_stopTimer(void);
//*****************************************************************************
//
//! Stop (disable) the CapTIvate&tm; timer.
//!
//! \par Parameters
//! none
//! \return timer contents
//
//*****************************************************************************
extern uint16_t CAPT_readTimerRegister(void);
//*****************************************************************************
//
//! Read value from timer compare register.
//!
//! \par Parameters
//! none
//! \return Compare Register Value
//
//*****************************************************************************
extern uint16_t CAPT_readTimerCompRegister(void);
//*****************************************************************************
//
//! Write value into timer compare register.
//!
//! \param compRegister = Compare Register Value
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_writeTimerCompRegister(uint16_t compRegister);
//*****************************************************************************
//
//! Turn off the CapTIvate&tm; IP.
//!
//! \par Parameters
//! none
//! \return Compare Register Value
//
//*****************************************************************************
extern void CAPT_powerOff(void);
//*****************************************************************************
//
//! Turn on the CapTIvate&tm; IP.
//!
//! \par Parameters
//! none
//! \return Compare Register Value
//
//*****************************************************************************
extern void CAPT_powerOn(void);
//*****************************************************************************
//
//! Activate specific IO channel, CAPx.y, ui8Block-> x, ui8Pin->y. When a
//! conversion is started then this IO will enter either a Tx or Rx mode of
//! operation.
//!
//! \param ui8Block = select block
//! \param ui8Pin = select pin
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_setChannelActive(uint8_t ui8Block, uint8_t ui8Pin);
//*****************************************************************************
//
//! Enable a specific IO channel, CAPx.y, ui8Block-> x, ui8Pin->y.
//!
//! \param ui8Block = select block
//! \param ui8Pin = select pin
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_setChannelEnable(uint8_t ui8Block, uint8_t ui8Pin);
//*****************************************************************************
//
//! Set off state for specific IO channel, CAPx.y, ui8Block-> x, ui8Pin->y.
//! This puts the IO into the Ground state when enabled and not active.
//!
//! \param ui8Block = select block
//! \param ui8Pin = select pin
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_setChannelOffState(uint8_t ui8Block, uint8_t ui8Pin);
//*****************************************************************************
//
//! Set on state for specific IO channel, CAPx.y, ui8Block-> x, ui8Pin->y.
//! This puts the IO into the Rx mode. The mode, mutual or self, is defined
//! by the sensor parameter tSensor.SensingMethod and applied by API
//! CAPT_apply_SensorParams. The default setting for the block is self mode.
//!
//! \param ui8Block = select block
//! \param ui8Pin = select pin
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_setChannelOnState(uint8_t ui8Block, uint8_t ui8Pin);
//*****************************************************************************
//
//! Activate a specific IO channel, CAPx.y, ui8Block-> x, ui8Pin->y.
//!
//! \param ui8Block = select block
//! \param ui8Pin = select pin
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_clearChannelActive(uint8_t ui8Block, uint8_t ui8Pin);
//*****************************************************************************
//
//! Enable a specific IO channel, CAPx.y, ui8Block-> x, ui8Pin->y.
//!
//! \param ui8Block = select block
//! \param ui8Pin = select pin
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_clearChannelEnable(uint8_t ui8Block, uint8_t ui8Pin);
//*****************************************************************************
//
//! Clear off state for specific IO channel, CAPx.y, ui8Block-> x, ui8Pin->y.
//!
//! \param ui8Block = select block
//! \param ui8Pin = select pin
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_clearChannelOffState(uint8_t ui8Block, uint8_t ui8Pin);
//*****************************************************************************
//
//! Set on state for specific IO channel, CAPx.y, ui8Block-> x, ui8Pin->y.
//!
//! \param ui8Block = select block
//! \param ui8Pin = select pin
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_clearChannelOnState(uint8_t ui8Block, uint8_t ui8Pin);
//*****************************************************************************
//
//! Write Coarse Gain value to Block Compensation.
//!
//! \param ui8Block = select block
//! \param ui8Value = value
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_writeCoarseGain(uint8_t ui8Block, uint8_t ui8Value);
//*****************************************************************************
//
//! Read Coarse Gain value from Block Compensation.
//!
//! \param ui8Block = select block
//! \return 8-bit coarse gain value
//
//*****************************************************************************
extern uint8_t CAPT_readCoarseGain(uint8_t ui8Block);
//*****************************************************************************
//
//! Write Fine Gain value to Block Compensation.
//!
//! \param ui8Block = select block
//! \param ui8Value = value
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_writeFineGain(uint8_t ui8Block, uint8_t ui8Value);
//*****************************************************************************
//
//! Read Fine Gain value from Block Compensation.
//!
//! \param ui8Block = select block
//! \return 8-bit fine gain value
//
//*****************************************************************************
extern uint8_t CAPT_readFineGain(uint8_t ui8Block);
//*****************************************************************************
//
//! Write Offset Tap value to Block Compensation.
//!
//! \param ui8Block = select block
//! \param ui16Value = offsetvalue
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_writeOffsetTap(uint8_t ui8Block, uint16_t ui16Value);
//*****************************************************************************
//
//! Read Offset Tap value from Block Compensation.
//!
//! \param ui8Block = select block
//! \return 16-bit offset tap value
//
//*****************************************************************************
extern uint16_t CAPT_readOffsetTap(uint8_t ui8Block);
//*****************************************************************************
//
//! Read Conversion value from Block.
//!
//! \param ui8Block = select block
//! \return 16-bit conversion value
//
//*****************************************************************************
extern uint16_t CAPT_readConversion(uint8_t ui8Block);
//*****************************************************************************
//
//! Set CAPLPMCFG.
//!
//! \par Parameters
//! none
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_setCAPLPMCFG(void);
//*****************************************************************************
//
//! Clear CAPLPMCFG.
//!
//! \par Parameters
//! none
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_clearCAPLPMCFG(void);
//*****************************************************************************
//
//! Poll a CapTIvate&tm; peripheral interrupt flag.
//!
//! \param ui16InterruptMask is a bit mask of the interrupts to test.
//!
//! \return interrupt flags that are set
//
//*****************************************************************************
extern uint16_t CAPT_pollIFG(uint16_t ui16InterruptMask);
//*****************************************************************************
//
//! Clear a Captivate peripheral interrupt flag. The bit mask is defined as:
//! BIT0 -> End Of Conversion IFG
//! BIT1 -> Detection IFG
//! BIT2 -> CapTIvate Timer IFG (number of clock cycles)
//! BIT3 -> CapTIvate Counter IFG (number of conversion cycles)
//!
//! BIT8 -> Maximum Count Error IFG
//!
//! \param ui16InterruptMask is a bit mask of the interrupt flags to clear.
//!
//! \return none.
//
//*****************************************************************************
extern void CAPT_clearIFG(uint16_t ui16InterruptMask);
//*****************************************************************************
//
//! Retrieve the CapTIvate&tm; peripheral interrupt vector register
//!
//! \param none.
//!
//! \return current value of the CapTIvate&tm; IV register.
//
//*****************************************************************************
extern uint16_t CAPT_getInterruptVector(void);
//*****************************************************************************
//
//! Enable a CapTIvate IO to be a shield.
//!
//! \param ui8Block is the CapTIvate block that the shield resides on.
//! \param ui8Pin is the pin on the block that the shield is connected to.
//!
//! \returns
//! None.
//
//*****************************************************************************
extern void CAPT_enableShieldIO(uint8_t ui8Block, uint8_t ui8Pin);
//*****************************************************************************
//
//! Disable a CapTIvate shield IO.
//!
//! \param ui8Block is the CapTIvate block that the shield resides on.
//! \param ui8Pin is the pin on the block that the shield is connected to.
//!
//! \returns
//! None.
//
//*****************************************************************************
extern void CAPT_disableShieldIO(uint8_t ui8Block, uint8_t ui8Pin);
//*****************************************************************************
//
//! Only valid on certain devices, please consult device-specific datasheet.
//! Select CapTIvate electrode charge voltage source supply, which is used
//! for sensing.
//! You should only change sources when there is no conversion in progress.
//!
//! \param electrodeChargeVoltageSourceSelectStyle is the voltage source used to supply electrode charging.
//! Valid values are:
//! - \b eVRegSupply
//! - \b eDVCCSupply
//!
//! \returns
//! None.
//
//*****************************************************************************
extern void CAPT_selectElectrodeChargeVoltageSource(tElectrodeChargeVoltageSourceSelectStyle electrodeChargeVoltageSourceSelectStyle);
//*****************************************************************************
//
//! Only valid on certain devices, please consult device-specific datasheet.
//! Select CapTIvate oversampling count.
//!
//! \param oversamplingCount is the number of data samples measured during
//! FSM oversampling operation
//! Valid values are:
//! - \b eNoOversampling
//! - \b e2xOversampling
//! - \b e4xOversampling
//! - \b e8xOversampling
//!
//! \returns
//! None.
//
//*****************************************************************************
extern void CAPT_selectOversamplingCount(tOversamplingStyle oversamplingStyle);
//*****************************************************************************
//
//! Only valid on certain devices, please consult device-specific datasheet.
//! Returns whether FSM-based autonomous frequency hopping is enabled or
//! disabled.
//!
//! \param none.
//!
//! \return true if FSM-based autonomous frequency hopping is enabled,
//! false if FSM-based autonomous frequency hopping is disabled.
//
//*****************************************************************************
extern bool CAPT_isFrequencyHopping(void);
//*****************************************************************************
//
//! Only valid on certain devices, please consult device-specific datasheet.
//! Enable FSM-based autonomous frequency hopping, which improves noise
//! immunity. Conversion frequency hops amongst the 4 preset values.
//! Set CAPFSMCTRL0:FHOPEN
//!
//! \par Parameters
//! none
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_enableFrequencyHopping(void);
//*****************************************************************************
//
//! Only valid on certain devices, please consult device-specific datasheet.
//! Disable FSM-based autonomous frequency hopping. Conversion frequency is
//! fixed.
//! Clear CAPFSMCTRL0:FHOPEN
//!
//! \par Parameters
//! none
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_disableFrequencyHopping(void);
//*****************************************************************************
//
//! Only valid on certain devices, please consult device-specific datasheet.
//! Returns level of input impedance bias current.
//! Get CAPCTRL1:LOWRIN
//!
//! \param none.
//!
//! \return enum tInputImpedanceBiasCurrent, level of bias current
//! Valid values are:
//! - \b eZeroIbias
//! - \b eIbiasSelf25Mutual10
//! - \b eIbiasSelf50Mutual10
//! - \b eIbiasSelf100Mutual10
//
//*****************************************************************************
extern tInputImpedanceBiasCurrent CAPT_getInputImpedanceBiasCurrent(void);
//*****************************************************************************
//
//! Only valid on certain devices, please consult device-specific datasheet.
//! Disables input impedance bias current to zero.
//! Clear CAPCTRL1:LOWRIN
//!
//! \par Parameters
//! none
//! \par Returns
//! none
//
//*****************************************************************************
extern void CAPT_clearInputImpedanceBiasCurrent(void);
//*****************************************************************************
//
//! Only valid on certain devices, please consult device-specific datasheet.
//! Select CapTIvate input impedance bias current.
//!
//! \param biasCurrent is the strength of the input impedance bias current
//! Valid values are:
//! - \b eZeroIbias
//! - \b eIbiasSelf25Mutual10
//! - \b eIbiasSelf50Mutual10
//! - \b eIbiasSelf100Mutual10
//!
//! \returns
//! None.
//
//*****************************************************************************
extern void CAPT_selectInputImpedanceBiasCurrent(
tInputImpedanceBiasCurrent biasCurrent);
//*****************************************************************************
//
//! Only valid on certain devices, please consult device-specific datasheet.
//! Select CapTIvate input impedance bias current trim. Helps to calibrate
//! how much current is removed based on input impedance bias current
//! Trim is applied per block, while the bias current is for whole system.
//!
//! \param trim is the strength of the input impedance bias current extraction
//! Valid values are 0-7.
//! \param pElement is the pointer to element about to utilize the trim.
//!
//! \returns
//! None.
//
//*****************************************************************************
extern void CAPT_selectInputImpedanceBiasCurrentTrim(uint8_t trim, tElement* pElement);
//*****************************************************************************
//
//! Read LTA value from Block.
//!
//! \param ui8Block = select block
//! \return IQ16_t of the LTA
//
//*****************************************************************************
extern IQ16_t CAPT_readLTA(uint8_t ui8Block);
#endif /* CAPT_HAL_H_ */
//*****************************************************************************
//! Close the doxygen group
//! @}
//*****************************************************************************
| 37.862835 | 134 | 0.440064 | [
"vector"
] |
b3f5b7bcb8d1b3de79416e3b17343cefe71a0eec | 503 | h | C | src/playground/scene.h | Cat-Lord/ppgso_project | fa2fc3fc16e3e20a656d87bfec865d629b197d00 | [
"MIT"
] | null | null | null | src/playground/scene.h | Cat-Lord/ppgso_project | fa2fc3fc16e3e20a656d87bfec865d629b197d00 | [
"MIT"
] | null | null | null | src/playground/scene.h | Cat-Lord/ppgso_project | fa2fc3fc16e3e20a656d87bfec865d629b197d00 | [
"MIT"
] | null | null | null | #pragma once
#include <map>
#include <list>
#include "camera.h"
#include "object.h"
class Object;
class Scene {
public:
bool addedCube = false;
bool finished = false; // finished informs about post-game animations status
bool end = false;
bool endSuccess = false;
float minX = -6, maxX = 6;
float minZ = -6, maxZ = 6;
std::unique_ptr<Camera> camera;
std::list< std::unique_ptr<Object> > objects;
std::map<int, int> keys;
Scene();
void update(float dt);
void render();
};
| 18.62963 | 80 | 0.66004 | [
"render",
"object"
] |
b3f6d4cdc543e93afe99039f6494756c1befc512 | 644 | h | C | CnprLibraSummary.h | mhoopmann/NeoProtXMLParser | f34b71cfb6bd2a366f405891bd68661d399d944d | [
"Apache-2.0"
] | null | null | null | CnprLibraSummary.h | mhoopmann/NeoProtXMLParser | f34b71cfb6bd2a366f405891bd68661d399d944d | [
"Apache-2.0"
] | null | null | null | CnprLibraSummary.h | mhoopmann/NeoProtXMLParser | f34b71cfb6bd2a366f405891bd68661d399d944d | [
"Apache-2.0"
] | null | null | null | #ifndef _CNPRLIBRASUMMARY_H
#define _CNPRLIBRASUMMARY_H
#include "NeoProtXMLStructs.h"
#include "CnprFragmentMasses.h"
#include "CnprIsotopicContributions.h"
#include <string>
#include <vector>
class CnprLibraSummary {
public:
CnprLibraSummary();
void write(FILE* f, int tabs = -1);
std::string version;
double mass_tolerance;
int centroiding_preference;
int normalization;
int output_type;
std::string channel_code;
double min_pep_prob;
double min_pep_wt;
double min_prot_prob;
std::vector<CnprFragmentMasses> fragment_masses;
std::vector<CnprIsotopicContributions> isotopic_contributions;
private:
};
#endif | 18.941176 | 64 | 0.776398 | [
"vector"
] |
b3ff7e5029ecd2ca50940f65ea41ca9173ed4373 | 347 | h | C | simulation/particula.h | anthonyfisicabsb/programas-ferrofluidos | d3cdd8efe6fd6048953378debd43c5872774e879 | [
"MIT"
] | null | null | null | simulation/particula.h | anthonyfisicabsb/programas-ferrofluidos | d3cdd8efe6fd6048953378debd43c5872774e879 | [
"MIT"
] | null | null | null | simulation/particula.h | anthonyfisicabsb/programas-ferrofluidos | d3cdd8efe6fd6048953378debd43c5872774e879 | [
"MIT"
] | 1 | 2019-07-11T17:36:03.000Z | 2019-07-11T17:36:03.000Z | /*
This file contains a struct that represents a
particle caracteristics during simulation.
The particle is describe by three vector in
R3 space: postion, magnetic momentum and
magnetization.
*/
struct particula {
double r[3]; // position
double m[3]; // magnetic momentum
double magz[3]; // magnetization
};
| 23.133333 | 49 | 0.682997 | [
"vector"
] |
b6021150a85d7f4f2549c0ee964352710f7adb7d | 276 | h | C | entity/module/modules.h | jeffreymanzione/jeff-vm-lang- | cb7bf7f6dc4260eb9346880b31d160632d10e608 | [
"MIT"
] | 1 | 2021-02-07T22:13:32.000Z | 2021-02-07T22:13:32.000Z | entity/module/modules.h | jeffreymanzione/jeff-vm | 7754eb4b72476ca6e8519b5832d460d07e8d220a | [
"MIT"
] | null | null | null | entity/module/modules.h | jeffreymanzione/jeff-vm | 7754eb4b72476ca6e8519b5832d460d07e8d220a | [
"MIT"
] | null | null | null | // modules.h
//
// Created on: Oct 3, 2020
// Author: Jeff Manzione
#ifndef ENTITY_MODULE_MODULES_H_
#define ENTITY_MODULE_MODULES_H_
#include "entity/object.h"
extern Module *Module_builtin;
extern Module *Module_io;
#endif /* ENTITY_MODULE_MODULES_H_ */ | 19.714286 | 37 | 0.721014 | [
"object"
] |
b603090a7bd73a439a7680818363c2100901e39f | 6,212 | h | C | processors/ARM/skyeye/arch/coldfire/common/coldfire.h | zecke/pharo-vm-1 | c06ab62eab741547dc4e0ed2e107928bd8885eb7 | [
"MIT"
] | 2 | 2018-07-09T14:14:48.000Z | 2018-11-01T20:54:57.000Z | processors/ARM/skyeye/arch/coldfire/common/coldfire.h | zecke/pharo-vm-1 | c06ab62eab741547dc4e0ed2e107928bd8885eb7 | [
"MIT"
] | 1 | 2016-09-30T10:16:44.000Z | 2016-09-30T10:16:44.000Z | processors/ARM/skyeye/arch/coldfire/common/coldfire.h | zecke/pharo-vm-1 | c06ab62eab741547dc4e0ed2e107928bd8885eb7 | [
"MIT"
] | 1 | 2018-10-25T23:31:42.000Z | 2018-10-25T23:31:42.000Z | /**********************************/
/* */
/* Copyright 2000, David Grant */
/* */
/* see LICENSE for more details */
/* */
/**********************************/
#ifndef __COLDFIRE_H__
#define __COLDFIRE_H__
#include <stdio.h>
#include <string.h>
#include "skyeye.h"
struct _Instruction {
void (*FunctionPtr)(void);
unsigned short Code;
unsigned short Mask;
int (*DIFunctionPtr)(char *Instruction, char *Arg1, char *Arg2);
};
/* This is ALWAYS cast into a longword, so we need to pad it to a longword */
struct _InstructionExtensionWord {
#ifndef WORDS_BIGENDIAN
signed Displacement:8;
unsigned EV:1;
unsigned Scale:2;
unsigned WL:1;
unsigned Register:3;
unsigned AD:1;
unsigned pad:16;
#else
unsigned pad:16;
unsigned AD:1;
unsigned Register:3;
unsigned WL:1;
unsigned Scale:2;
unsigned EV:1;
signed Displacement:8;
#endif
};
enum {
I_ADD, I_ADDA, I_ADDI, I_ADDQ, I_ADDX,
I_AND, I_ANDI, I_ASL, I_ASR, I_BCC, I_BCHG, I_BCLR, I_BRA,
I_BSET, I_BSR, I_BTST, I_CLR, I_CMP, I_CMPA, I_CMPI,
I_DIVS, I_DIVL, I_DIVU, I_DIVUL, I_EOR, I_EORI, I_EXT, I_JMP, I_JSR,
I_LEA, I_LINK, I_LSR, I_LSL, I_MOVE, I_MOVEC, I_MOVEA, I_MOVEM, I_MOVEQ,
I_MOVETOSR, I_MULS, I_MULU, I_NEG, I_NEGX, I_NOP, I_NOT, I_OR,
I_ORI, I_RTE, I_RTS, I_SCC, I_SUB, I_SUBA, I_SUBI, I_SUBQ, I_SUBX,
I_SWAP, I_TRAP, I_TRAPF, I_TST, I_UNLK,
I_LAST
};
enum _coldfire_cpu_id {
CF_NULL,
CF_5206,
CF_5206e,
CF_5276,
CF_5307,
CF_5407,
CF_LAST
};
#define INSTRUCTION_(I,A) \
typedef union _##I##_instr { \
struct _##I##_bits { \
A; \
} Bits; \
unsigned int Code; \
} I##_Instr
#ifndef WORDS_BIGENDIAN
#define INSTRUCTION_1ARG(I,A1,S1) \
INSTRUCTION_(I, A1:S1)
#define INSTRUCTION_2ARGS(I,A1,S1,A2,S2) \
INSTRUCTION_(I, A2:S2; A1:S1)
#define INSTRUCTION_3ARGS(I,A1,S1,A2,S2,A3,S3) \
INSTRUCTION_(I, A3:S3; A2:S2; A1:S1)
#define INSTRUCTION_4ARGS(I,A1,S1,A2,S2,A3,S3,A4,S4) \
INSTRUCTION_(I, A4:S4; A3:S3; A2:S2; A1:S1)
#define INSTRUCTION_5ARGS(I,A1,S1,A2,S2,A3,S3,A4,S4,A5,S5) \
INSTRUCTION_(I, A5:S5; A4:S4; A3:S3; A2:S2; A1:S1)
#define INSTRUCTION_6ARGS(I,A1,S1,A2,S2,A3,S3,A4,S4,A5,S5,A6,S6) \
INSTRUCTION_(I, A6:S6; A5:S5; A4:S4; A3:S3; A2:S2; A1:S1)
#define INSTRUCTION_7ARGS(I,A1,S1,A2,S2,A3,S3,A4,S4,A5,S5,A6,S6,A7,S7) \
INSTRUCTION_(I, A7:S7; A6:S6; A5:S5; A4:S4; A3:S3; A2:S2; A1:S1)
#else
#define INSTRUCTION_1ARG(I,A1,S1) \
INSTRUCTION_(I, unsigned pad:(32-S1); \
A1:S1)
#define INSTRUCTION_2ARGS(I,A1,S1,A2,S2) \
INSTRUCTION_(I, unsigned pad:(32-S1-S2); \
A1:S1; A2:S2)
#define INSTRUCTION_3ARGS(I,A1,S1,A2,S2,A3,S3) \
INSTRUCTION_(I, unsigned pad:(32-S1-S2-S3); \
A1:S1; A2:S2; A3:S3)
#define INSTRUCTION_4ARGS(I,A1,S1,A2,S2,A3,S3,A4,S4) \
INSTRUCTION_(I, unsigned pad:(32-S1-S2-S3-S4); \
A1:S1; A2:S2; A3:S3; A4:S4)
#define INSTRUCTION_5ARGS(I,A1,S1,A2,S2,A3,S3,A4,S4,A5,S5); \
INSTRUCTION_(I, unsigned pad:(32-S1-S2-S3-S4-S5); \
A1:S1; A2:S2; A3:S3; A4:S4; A5:S5)
#define INSTRUCTION_6ARGS(I,A1,S1,A2,S2,A3,S3,A4,S4,A5,S5,A6,S6)\
INSTRUCTION_(I, unsigned pad:(32-S1-S2-S3-S4-S5-S6); \
A1:S1; A2:S2; A3:S3; A4:S4; A5:S5; A6:S6)
#define INSTRUCTION_7ARGS(I,A1,S1,A2,S2,A3,S3,A4,S4,A5,S5,A6,S6,A7,S7) \
INSTRUCTION_(I, unsigned pad:(32-S1-S2-S3-S4-S5-S6-S7); \
A1:S1; A2:S2; A3:S3; A4:S4; A5:S5; A6:S6; A7:S7)
#endif
#include "memory.h"
#include "addressing.h"
//#include "monitor/monitor.h"
//#include "i_5206/i_5206.h"
//#include "i_5206e/i_5206e.h"
//#include "i_5307/i_5307.h"
//#include "peripherals/peripherals.h"
/* board.c -- definitions of various eval board layouts */
struct _board_data {
char *cpu_id;
unsigned int clock_speed;
unsigned int cycle_count;
unsigned int total_cycle_count;
char use_timer_hack;
char trace_run;
enum _coldfire_cpu_id cpu;
};
void board_init(void);
void board_reset(void);
void board_fini(void);
void board_setup(char *file);
struct _board_data *board_get_data(void);
/* cycle.c */
void cycle(unsigned int number);
int cycle_EA(short reg, short mode);
/* exception.c -- exception generators */
int exception_do_raw_exception(short vector);
int exception_do_exception(short vector);
void exception_restore_from_stack_frame(void);
void exception_push_stack_frame(short vector);
void exception_post(unsigned int interrupt_level,
unsigned int (*func)(unsigned int interrupt_level) );
void exception_withdraw(unsigned int interrupt_level);
void exception_check_and_handle(void);
/* handlers.c -- misc functions */
void SR_Set(short Instr, int Source, int Destination, int Result);
/* i.c -- instructions */
void Instruction_Init(void);
void instruction_register(unsigned short code, unsigned short mask,
void (*execute)(void),
int (*disassemble)(char *, char *, char *));
void Instruction_DeInit(void);
struct _Instruction *Instruction_FindInstruction(unsigned short Instr);
void instruction_register_instructions(void);
/* misc.c -- Misc functions */
int arg_split(char **argv, char *buffer, int max_args);
int arg_split_chars(char **argv, char *buffer, int max_args, char *split);
/* network.c -- Network functions */
int network_setup_on_port(int *fd, unsigned short port);
int network_check_accept(int *fd);
/* run.c -- Running the core */
extern char Run_Exit;
void Run(void);
/* sim.c -- System Integration Module */
struct _sim_register {
char *name;
int offset;
char width;
char read;
char write;
int resetvalue;
char *description;
};
struct _sim {
/* These are for peripherals to talk to the sim */
void (*interrupt_assert)(short number, short vector);
void (*interrupt_withdraw)(short number);
/* These are for the monitor to query SIM registers */
struct _sim_register *(*register_lookup_by_offset)(int offset);
struct _sim_register *(*register_lookup_by_name)(char *name);
};
void sim_register(struct _sim *sim_data);
extern struct _sim *sim;
/*
#define TRACE(x,y,z)
#define TRACE(x,y)
#define TRACE(x)
*/
/* INSTRUCTION TIMING is firewalled inside profile.h */
//#include "profile.h"
/* MEMORY_STATS is firewalled inside stats.h */
//#include "stats.h"
#endif
| 27.245614 | 77 | 0.684643 | [
"vector"
] |
b621ad74110cc1e2174d082c25e50cc988f73466 | 1,485 | h | C | src/ke/KnotSurface.h | Mathesis-Software/KnotEditor | 7aa7e3a5dfbc71bee5c9264e82ebc8267d45e5ff | [
"Apache-2.0"
] | 5 | 2021-07-27T15:26:54.000Z | 2021-09-11T16:38:53.000Z | src/ke/KnotSurface.h | Mathesis-Software/Knots | 7aa7e3a5dfbc71bee5c9264e82ebc8267d45e5ff | [
"Apache-2.0"
] | 7 | 2021-11-05T18:06:45.000Z | 2021-11-20T15:33:38.000Z | src/ke/KnotSurface.h | Mathesis-Software/KnotEditor | 7aa7e3a5dfbc71bee5c9264e82ebc8267d45e5ff | [
"Apache-2.0"
] | 1 | 2021-09-11T16:39:18.000Z | 2021-09-11T16:39:18.000Z | /*
* Copyright (c) 1995-2021, Nikolay Pultsin <geometer@geometer.name>
*
* 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 __KNOT_SURFACE_H__
#define __KNOT_SURFACE_H__
#include <vector>
#include "KnotWrapper.h"
#include "Surface.h"
namespace KE::GL {
class KnotSurface : public Surface {
private:
const ThreeD::KnotWrapper &knot;
std::vector<double> sines;
std::vector<double> cosines;
mutable std::shared_ptr<ThreeD::Knot::Snapshot> stored;
public:
KnotSurface(const ThreeD::KnotWrapper &knot, std::size_t numberOfPointsOnMeridian);
void setNumberOfPointsOnMeridian(std::size_t numberOfPointsOnMeridian);
const Color &frontColor() const override;
const Color &backColor() const override;
bool isObsolete() const override;
bool isVisible() const override;
private:
void calculate() const override;
private:
KnotSurface(const KnotSurface&) = delete;
KnotSurface& operator = (const KnotSurface&) = delete;
};
}
#endif /* __KNOT_SURFACE_H__ */
| 26.517857 | 84 | 0.753535 | [
"vector"
] |
b62ad395def27a1f18c130928d810d67fac46c44 | 625 | h | C | ouzel/audio/xaudio2/SoundDataXA2.h | keima97/ouzel | e6673e678b4739235371a15ae3863942b692c5fb | [
"BSD-2-Clause"
] | null | null | null | ouzel/audio/xaudio2/SoundDataXA2.h | keima97/ouzel | e6673e678b4739235371a15ae3863942b692c5fb | [
"BSD-2-Clause"
] | null | null | null | ouzel/audio/xaudio2/SoundDataXA2.h | keima97/ouzel | e6673e678b4739235371a15ae3863942b692c5fb | [
"BSD-2-Clause"
] | null | null | null | // Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.
#pragma once
#define NOMINMAX
#include <xaudio2.h>
#include "audio/SoundData.h"
namespace ouzel
{
namespace audio
{
class SoundDataXA2: public SoundData
{
public:
SoundDataXA2();
virtual ~SoundDataXA2();
virtual bool initFromBuffer(const std::vector<uint8_t>& newData) override;
const WAVEFORMATEX& getWaveFormat() const { return waveFormat; }
protected:
WAVEFORMATEX waveFormat;
};
} // namespace audio
} // namespace ouzel
| 20.833333 | 86 | 0.6208 | [
"vector"
] |
b62e1e347692159f9bd3f3b541b316ec6374c7c4 | 2,559 | h | C | src/sppm.h | leolvt/sppm | b90dcc13c7f8909d372940ca2055eba26b2ed63b | [
"MIT"
] | 1 | 2017-10-22T18:28:47.000Z | 2017-10-22T18:28:47.000Z | src/sppm.h | leolvt/sppm | b90dcc13c7f8909d372940ca2055eba26b2ed63b | [
"MIT"
] | null | null | null | src/sppm.h | leolvt/sppm | b90dcc13c7f8909d372940ca2055eba26b2ed63b | [
"MIT"
] | null | null | null | #ifndef SPPM_H_
#define SPPM_H_
#include <random>
#include <vector>
#include <fstream>
#include <unordered_map>
#include <unordered_set>
#include <lemon/adaptors.h>
#include <lemon/smart_graph.h>
#include "util.h"
// ========================== //
class SPPM {
public:
SPPM(lemon::SmartGraph& graph,
lemon::SmartGraph::NodeMap<long long>& node_id,
lemon::SmartGraph::NodeMap<Util::AttrMap>& node_attribute);
virtual ~SPPM();
void SetRhoParameters(double alpha, double beta);
void Run(int num_iter, int burn_in, int step_size);
protected:
typedef std::unordered_set<lemon::SmartGraph::Node> NodeSet;
lemon::SmartGraph& m_graph;
lemon::SmartGraph::NodeMap<long long>& m_node_id;
lemon::SmartGraph::NodeMap<Util::AttrMap>& m_node_attr;
std::default_random_engine m_rng;
int m_num_groups;
// Current state
double m_rho;
lemon::SmartGraph::NodeMap<long long> m_pi;
lemon::SmartGraph::EdgeMap<bool> m_tree;
private:
typedef lemon::FilterEdges<const lemon::SmartGraph> FilteredGraph;
// Helper stuff
lemon::SmartGraph::NodeMap<bool> m_u_group;
lemon::SmartGraph::NodeMap<bool> m_v_group;
// Output files
std::ofstream m_pi_file;
std::ofstream m_tree_file;
std::ofstream m_rho_file;
// Parameters
double m_rho_alpha;
double m_rho_beta;
void PrepareOutput();
void FinishOutput();
void GenerateInitialState();
void HoldSample();
void GetNewSample();
void PrepareOutputPartition();
void PrepareOutputRho();
void PrepareOutputTree();
void GenerateInitialPartition();
void GenerateInitialRho();
void GenerateInitialTree();
void FinishOutputPartition();
void FinishOutputRho();
void FinishOutputTree();
void SamplePartition();
void SampleRho();
void SampleTree();
void HoldPartition();
void HoldRho();
void HoldTree();
//int UpdatePi(const Graph::EdgeFilter& edges);
//double ComputeLogRatio(Graph::EdgeFilter& edges, int u, int v);
void FindNodes(FilteredGraph& fg, lemon::SmartGraph::Node& s,
lemon::SmartGraph::NodeMap<bool>& nodes);
int UpdatePi(FilteredGraph& graph);
double ComputeLogRatio(FilteredGraph& filtered_graph,
lemon::SmartGraph::Edge& e);
virtual void PrepareOutputTheta() = 0;
virtual void FinishOutputTheta() = 0;
virtual void GenerateInitialTheta() = 0;
virtual void HoldTheta() = 0;
virtual void SampleTheta() = 0;
virtual double ComputeLogRatioPredictive(
lemon::SmartGraph::NodeMap<bool>& set_u,
lemon::SmartGraph::NodeMap<bool>& set_v) = 0;
};
// ========================== //
#endif // SPPM_H_
| 24.84466 | 68 | 0.711606 | [
"vector"
] |
b6330c7fbce0425b7a045c37e0553487ad8e746e | 3,589 | h | C | TrafficManager/source/pipeline/Pipeline.h | owoschhodan/carla | 7da99d882afb4160f0901bbbac2ea2866683e314 | [
"MIT"
] | 8 | 2019-11-27T18:43:09.000Z | 2022-01-16T06:08:36.000Z | TrafficManager/source/pipeline/Pipeline.h | tcwangjiawei/carla | 714f8c4cbfbb46fa9ed163a27c94ede613948767 | [
"MIT"
] | null | null | null | TrafficManager/source/pipeline/Pipeline.h | tcwangjiawei/carla | 714f8c4cbfbb46fa9ed163a27c94ede613948767 | [
"MIT"
] | 5 | 2020-05-12T20:03:10.000Z | 2022-02-25T14:40:07.000Z | #pragma once
#include <algorithm>
#include <memory>
#include <random>
#include <vector>
#include "carla/client/Actor.h"
#include "carla/client/BlueprintLibrary.h"
#include "carla/client/Map.h"
#include "carla/client/World.h"
#include "carla/geom/Transform.h"
#include "carla/Logging.h"
#include "carla/Memory.h"
#include "carla/rpc/Command.h"
#include "BatchControlStage.h"
#include "CollisionStage.h"
#include "InMemoryMap.h"
#include "LocalizationStage.h"
#include "MotionPlannerStage.h"
#include "TrafficLightStage.h"
#define EXPECT_TRUE(pred) if (!(pred)) { throw std::runtime_error(# pred); }
namespace traffic_manager {
namespace cc = carla::client;
namespace cg = carla::geom;
namespace cr = carla::rpc;
using ActorPtr = carla::SharedPtr<cc::Actor>;
/// Function to read hardware concurrency.
uint read_core_count();
/// Function to spawn a specified number of vehicles.
std::vector<ActorPtr> spawn_traffic(
cc::Client &client,
cc::World &world,
uint core_count,
uint target_amount);
/// Destroy actors.
void destroy_traffic(
std::vector<ActorPtr> &actor_list,
cc::Client &client);
/// The function of this class is to integrate all the various stages of
/// the traffic manager appropriately using messengers.
class Pipeline {
private:
/// PID controller parameters.
std::vector<float> longitudinal_PID_parameters;
std::vector<float> longitudinal_highway_PID_parameters;
std::vector<float> lateral_PID_parameters;
/// The number of working threads per stage.
uint pipeline_width;
/// Target velocities.
float highway_target_velocity;
float urban_target_velocity;
/// Reference to list of all actors registered with traffic manager.
std::vector<ActorPtr> &actor_list;
/// Reference to local map cache.
InMemoryMap &local_map;
/// Reference to Carla's debug helper object.
cc::DebugHelper &debug_helper;
/// Reference to Carla's client connection object.
cc::Client &client_connection;
/// Reference to Carla's world object.
cc::World &world;
/// Pointers to messenger objects connecting stage pairs.
std::shared_ptr<CollisionToPlannerMessenger> collision_planner_messenger;
std::shared_ptr<LocalizationToCollisionMessenger> localization_collision_messenger;
std::shared_ptr<LocalizationToTrafficLightMessenger> localization_traffic_light_messenger;
std::shared_ptr<LocalizationToPlannerMessenger> localization_planner_messenger;
std::shared_ptr<PlannerToControlMessenger> planner_control_messenger;
std::shared_ptr<TrafficLightToPlannerMessenger> traffic_light_planner_messenger;
/// Pointers to the stage objects of traffic manager.
std::unique_ptr<CollisionStage> collision_stage;
std::unique_ptr<BatchControlStage> control_stage;
std::unique_ptr<LocalizationStage> localization_stage;
std::unique_ptr<MotionPlannerStage> planner_stage;
std::unique_ptr<TrafficLightStage> traffic_light_stage;
public:
Pipeline(
std::vector<float> longitudinal_PID_parameters,
std::vector<float> longitudinal_highway_PID_parameters,
std::vector<float> lateral_PID_parameters,
float urban_target_velocity,
float highway_target_velocity,
std::vector<ActorPtr> &actor_list,
InMemoryMap &local_map,
cc::Client &client_connection,
cc::World &world,
cc::DebugHelper &debug_helper,
uint pipeline_width);
/// To start the pipeline.
void Start();
/// To stop the pipeline.
void Stop();
};
}
| 32.333333 | 94 | 0.731959 | [
"object",
"vector",
"transform"
] |
b34e27c8ea76aaad7afdc2175b6f9cdfab79bd3c | 6,819 | h | C | include/GLFont.h | stonexjr/davinci | 40793f19de0919e5d74ecb0de10524c4bd10f084 | [
"MIT"
] | 1 | 2018-06-06T13:20:49.000Z | 2018-06-06T13:20:49.000Z | include/GLFont.h | stonexjr/davinci | 40793f19de0919e5d74ecb0de10524c4bd10f084 | [
"MIT"
] | null | null | null | include/GLFont.h | stonexjr/davinci | 40793f19de0919e5d74ecb0de10524c4bd10f084 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2013-2017 Jinrong Xie (jrxie at ucdavis dot edu)
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 _GLFONT_H_
#define _GLFONT_H_
#ifndef ENABLE_TEXT_RENDERING
#error "You need to enable text rendering in cmake to use GLFont"
#else
#include <vector>
#include <string>
#include <memory>
#include <stdexcept>
//FreeType Headers
#include <ft2build.h>
#include "vec2i.h"
#if defined(__APPLE__) || defined(MACOSX)
#include <freetype2/freetype/freetype.h>
#include <freetype2/freetype/ftglyph.h>
#include <freetype2/freetype/ftoutln.h>
#include <freetype2/freetype/fttrigon.h>
#else
#include <freetype.h>
#include <ftglyph.h>
#include <ftoutln.h>
#include <fttrigon.h>
#endif
namespace freetype_mod {
//Inside of this namespace, give ourselves the ability
//to write just "vector" instead of "std::vector"
using std::vector;
//Ditto for string.
using std::string;
///This is the data structure that I'm using to store everything I need
///to render a character glyph in opengl.
struct char_data {
int w,h;
int advance;
int left;
int move_up;
unsigned char * data;
char_data(char ch, FT_Face face) {
// Load The Glyph For Our Character.
if(FT_Load_Glyph( face, FT_Get_Char_Index( face, ch ), FT_LOAD_DEFAULT ))
throw std::runtime_error("FT_Load_Glyph failed");
// Move The Face's Glyph Into A Glyph Object.
FT_Glyph glyph;
if(FT_Get_Glyph( face->glyph, &glyph ))
throw std::runtime_error("FT_Get_Glyph failed");
// Convert The Glyph To A Bitmap.
FT_Glyph_To_Bitmap( &glyph, ft_render_mode_normal, 0, 1 );
FT_BitmapGlyph bitmap_glyph = (FT_BitmapGlyph)glyph;
// This Reference Will Make Accessing The Bitmap Easier.
FT_Bitmap& bitmap=bitmap_glyph->bitmap;
advance=face->glyph->advance.x >> 6;
left=bitmap_glyph->left;
w=bitmap.width;
h=bitmap.rows;
move_up=bitmap_glyph->top-bitmap.rows;
data = new unsigned char[2*w*h];
for(int x=0;x<w;x++) for(int y=0;y<h;y++) {
const int my=h-1-y;
data[2*(x+w*my)]=255;
data[2*(x+w*my)+1]=bitmap.buffer[x+w*y];
}
}
~char_data() { delete [] data; }
};
//This holds all of the information related to any
//freetype font that we want to create.
struct font_data {
char_data * chars[128];
float h;
//The init function will create a font of
//of the height h from the file fname.
void init(const char * fname, unsigned int h);
//Free all the resources associated with the font.
void clean();
};
//The flagship function of the library - this thing will print
//out text at the current raster position using the font ft_font.
//The current modelview matrix will also be applied to the text.
void print(const font_data &ft_font, const char *fmt, ...) ;
}
namespace davinci{
typedef freetype_mod::font_data TTFont;
typedef std::shared_ptr<freetype_mod::font_data> TTFontRef;
class GLFont
{
public:
GLFont(void);
~GLFont(void);
//////////////////////////////////////////////////////////////////////////
// write 2d text using GLUT
// The projection matrix must be set to orthogonal before call this function.
///////////////////////////////////////////////////////////////////////////////
static void drawString2D(const char *str, int x, int y, float color[4], void *font);
///////////////////////////////////////////////////////////////////////////////
// write 2d text using True Type Font(TTF)
// The projection matrix must be set to orthogonal before call this function.
///////////////////////////////////////////////////////////////////////////////
static void drawString2DTTF( const char *str, int x, int y, float color[4], freetype_mod::font_data& font);
static void drawString2DTTF( const std::string &str, int x, int y, float color[4], freetype_mod::font_data& font);
///////////////////////////////////////////////////////////////////////////////
// draw a string in 3D space
///////////////////////////////////////////////////////////////////////////////
static void drawString3D(const char *str, float pos[3], float color[4], void *font);
#ifdef ENABLE_QT
///////////////////////////////////////////////////////////////////////////////
// write 2d text using GLUT
// The projection matrix must be set to orthogonal before call this function.
///////////////////////////////////////////////////////////////////////////////
static void drawString2D(const QString &str, int x, int y, float color[4], void *font);
///////////////////////////////////////////////////////////////////////////////
// write 2d text using True Type Font(TTF)
// The projection matrix must be set to orthogonal before call this function.
///////////////////////////////////////////////////////////////////////////////
static void drawString2DTTF( const QString &str, int x, int y, float color[4], freetype_mod::font_data& font);
///////////////////////////////////////////////////////////////////////////////
// draw a string in 3D space
///////////////////////////////////////////////////////////////////////////////
static void drawString3D(const QString &str, float pos[3], float color[4], void *font);
#endif //ENABLE_QT
//compute the width and height in pixel units of a given string based on the specified TTF font.
static vec2i computeStringDimension(const string& str, const freetype_mod::font_data& ttf_font);
};
}//end of namespace lily
#endif
#endif | 38.308989 | 118 | 0.581757 | [
"render",
"object",
"vector",
"3d"
] |
b34f5963a73512b160ec130f79b02e694ac45a05 | 6,333 | h | C | rack/andre/JammingOp.h | fmidev/rack | 95c39ef610637e8068253efc36aab40177caff03 | [
"MIT"
] | 20 | 2018-03-21T10:58:00.000Z | 2022-02-11T14:43:03.000Z | rack/andre/JammingOp.h | fmidev/rack | 95c39ef610637e8068253efc36aab40177caff03 | [
"MIT"
] | null | null | null | rack/andre/JammingOp.h | fmidev/rack | 95c39ef610637e8068253efc36aab40177caff03 | [
"MIT"
] | 6 | 2018-07-04T04:55:56.000Z | 2021-04-15T19:25:13.000Z | /*
MIT License
Copyright (c) 2017 FMI Open Development / Markus Peura, first.last@fmi.fi
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.
*/
/*
Part of Rack development has been done in the BALTRAD projects part-financed
by the European Union (European Regional Development Fund and European
Neighbourhood Partnership Instrument, Baltic Sea Region Programme 2007-2013)
*/
#ifndef Jamming2_OP_H_
#define Jamming2_OP_H_
#include <limits>
//#include "drain/util/FunctorPack.h"
//#include "drain/util/Math.h"
/*
#include "drain/image/File.h"
#include "drain/imageops/RunLengthOp.h"
#include "drain/imageops/DistanceTransformOp.h"
*/
#include "DetectorOp.h"
//using namespace drain::image;
using namespace drain::image;
namespace rack {
/// A detector for widespread electromagnetic interference.
/** Detects smooth, widespread interference.
* Based on fitting a function that models how radar receives external emitters:
* \f[
* dbz = b_1 + b_1x + b_2*\log(x);
* \f]
*
*/
class JammingOp: public DetectorOp {
public:
/** Default constructor.
*
* \param smoothnessThreshold - maximum standard deviation in a 5x3 sliding window
* \param distanceMin - minimum sampling distance [km] for curve fitting
* \param weightLower - if not 1.0, refit the curve, weighting samples lower the initial curve with this.
* \param debugRow -
*
* \param sampleContent - minimum percentage of valid (detected) bins along the beam
* \param maxCurvature - b2 in fitting dbz = b0 + b1*x + b2*x*x;
*
* 5.0,0.25,2.0,0.001,40
*/
// \param derivativeDifferenceMax - maximum difference between modelled and detected dBZ(range) slopes.
// \param windowWidth - windowWidth [kilometres]
// JammingOp(int windowWidth=5000, float windowHeight=10.0, float sensitivity = 0.5, float eWidth = 1.0f, float eHeight = 0.0f) :
// JammingOp(double smoothnessThreshold = 5.0, double sampleContent=0.5, double weightLower = 0.1, double maxCurvature = 0.001, double distanceMin = 40.0, int debugRow=-1) :
JammingOp(double smoothnessThreshold = 5.0, double distanceMin = 80.0, double weightLower = 10.0, int debugRow=-1) : // , double derivativeDifferenceMax = 0.0001
DetectorOp(__FUNCTION__,"Detects broad lines caused by electromagnetic interference. Intensities should be smooth, increasing by distance.",
"signal.emitter.jamming")
{
parameters.link("smoothnessThreshold", this->smoothnessThreshold = smoothnessThreshold, "dBZ");
parameters.link("distanceMin", this->distanceMin = distanceMin, "km");
parameters.link("weightLower", this->weightLower = weightLower, "[0.0...1.0]");
parameters.link("debugRow", this->debugRow = debugRow, "index");
UNIVERSAL = true;
REQUIRE_STANDARD_DATA = true;
}
double smoothnessThreshold;
double distanceMin;
//double sampleContent;
double weightLower;
//double derivativeDifferenceMax;
/**
* Curvature is computed as a maximum difference between the fitted 2nd order polynomial curve
* \f[
* \hat{y_2}(x) = b_0 + b_1x + b_2x^2
* \f]
* and the direct line crossing its point values, \f$(0,b_0)\f$ and \f$(w,\hat{y_2}(w))\f$ where \f$w\f$ is the maximum of \f$x\f$.
* Denote \f$d_y=\hat{y_2}(w)-\hat{y_2}(0)\f$.
* Then, the line is
* \f[
* \hat{y_1}(x) = b_0 + \frac{x}{w}d_y
* \f]
* and the difference
* \f[
* d(x) = \hat{y_2}(x) - \hat{y_1}(x) = x(b_1 - \frac{d_y}{w}) + b_2x^2
* \f]
* and its derivative is
* \f[
* d'(x) = b_1 - \frac{d_y}{w} + 2b_2x .
* \f]
* Setting \f$d'(x)=0\f$ we get
* \f[
* x = (\frac{d_y}{w}-b_1)/2b_2
* \f]
*
* \f$(0,b_0)\f$ and \f$(x_w,b_0 + b_1x_w + b_2x_w^2)\f$ where \f$x_w\f$ is the maximum of x.
*/
//double maxCurvature;
int debugRow;
/// Model for radar amplification of an external emitter.
/**
* \param distance - distance in metres
*
*/
static inline
double modelledEmitter(double dBZ0, double distance){
return dBZ0 + distance*(0.016/1000.0) + 20.0*log10(distance);
};
protected:
virtual
void processData(const PlainData<PolarSrc> & srcData, PlainData<PolarDst> & dstProb) const;
//void filterImage(const PolarODIM &odimIn, const Image &src, Image &dst) const;
/*
static
void fitCurve(const std::vector<double> &src, const std::vector<double> &weight, std::vector<double> &coeff);
virtual
void filterImageOLD(const PolarODIM &odimIn, const Image &src, Image &dst) const;
*/
/// Returns the beam-oriented derivative of the dBZ field. In case of no-data, returns std::numeric_limits<double>::max().
inline
static
double derivativeDBZ(const PolarODIM &odimIn, const Image &src, int i, int j, int span = 10){
int iLower = std::max(i-span, 0);
double zLower = src.get<double>(iLower,j);
if (odimIn.isValue(zLower)){
int iUpper = std::min(i+span, static_cast<int>(src.getWidth())-1);
double zUpper = src.get<double>(iUpper,j);
if (odimIn.isValue(zUpper)){
return (zUpper - zLower)/(odimIn.rscale*static_cast<double>(iUpper-iLower));
}
}
return std::numeric_limits<double>::max();
}
/**
*/
inline
static
double derivativeDBZ_Modelled(double yModelBase, double range, double rangeDifference){
return (modelledEmitter(yModelBase, range+rangeDifference) - modelledEmitter(yModelBase, range-rangeDifference)) / (2.0*rangeDifference);
}
};
}
#endif // Jamming2_OP_H_
// Rack
| 33.157068 | 174 | 0.708827 | [
"vector",
"model"
] |
b36902e333166fdc79cb1e8e2f1614a348bc7268 | 3,079 | h | C | Addin/lib/Visio.h | nbelyh/ShapeSheetWatch | a519e6e430c5545105bfb096b6ba52e0d24684e7 | [
"MIT"
] | 6 | 2015-12-19T19:23:55.000Z | 2021-07-16T07:42:45.000Z | Addin/lib/Visio.h | nbelyh/ShapeSheetWatch | a519e6e430c5545105bfb096b6ba52e0d24684e7 | [
"MIT"
] | 1 | 2020-07-15T20:01:23.000Z | 2020-07-15T20:01:23.000Z | Addin/lib/Visio.h | nbelyh/ShapeSheetWatch | a519e6e430c5545105bfb096b6ba52e0d24684e7 | [
"MIT"
] | 3 | 2018-02-01T11:15:13.000Z | 2019-06-23T05:53:11.000Z |
/*******************************************************************************
ADDSINK.H - Definitions for client side of Visio Advise Sink.
Copyright (C) Microsoft Corporation. All rights reserved.
This header file contains the prototype for the event call back
function (VISEVENTPROC) along with the class definitions for VEventHandler
and CVisioAddonSink.
*******************************************************************************/
#pragma once
HWND GetVisioWindowHandle (IVWindowPtr visio_window);
HWND GetVisioAppWindowHandle (IVApplicationPtr app);
/**-----------------------------------------------------------------------------
VEventHandler - definition of interface for handling Visio events
This abstract base class contains a single method through which event
notification will take place. Inherit your C++ class from this Class if
you want a C++ object context (a this pointer) when you get called by
VisEventProc in response to a Visio event.
------------------------------------------------------------------------------*/
class VEventHandler
{
public:
/**-----------------------------------------------------------------------------
This signature for HandleVisioEvent matches the new IVisEventProc
signature verbatim except that the first param here is the
sink object that is calling the callback proc. (An additional param
over what's received in VisEventProc.)
------------------------------------------------------------------------------*/
virtual HRESULT HandleVisioEvent(
/* [in] */ IUnknown* ipSink, // ipSink [assert]
/* [in] */ short nEventCode, // code of event that's firing.
/* [in] */ IDispatch* pSourceObj, // object that is firing event.
/* [in] */ long nEventID, // id of event that is firing.
/* [in] */ long nEventSeqNum, // sequence number of event.
/* [in] */ IDispatch* pSubjectObj, // subject of this event.
/* [in] */ VARIANT vMoreInfo, // other info.
/* [retval][out] */ VARIANT* pvResult // return a value to Visio
// for query events.
) = 0;
};
/**-----------------------------------------------------------------------------
Helper class to help advising to visio events.
Provides the functionality to connect or disconnect a class
that implements VEventHander interface to given event.
------------------------------------------------------------------------------*/
struct CVisioEvent
{
public:
CVisioEvent ();
~CVisioEvent();
HRESULT Advise(IVEventListPtr evt_list, int evt_code, VEventHandler* target);
void Unadvise();
private:
IVEventPtr m_event;
};
/**---------------------------------------------------------------------------------
-----------------------------------------------------------------------------------*/
struct VisioScopeLock
{
VisioScopeLock(IVApplicationPtr app, LPCWSTR description);
~VisioScopeLock();
static bool IsInVisioScopeLock();
void Commit();
private:
IVApplicationPtr m_app;
long m_scope_id;
VARIANT_BOOL m_result;
static int g_level;
};
| 34.595506 | 85 | 0.530367 | [
"object"
] |
b369fa69107c17b6a836f819dd9d77d74d88f708 | 1,450 | c | C | nitan/d/gumu/mudao01.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | 1 | 2019-03-27T07:25:16.000Z | 2019-03-27T07:25:16.000Z | nitan/d/gumu/mudao01.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | nitan/d/gumu/mudao01.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | // mudao01.c 墓道
// Java Oct.10 1998
#include <ansi.h>
inherit ROOM;
void create()
{
set("short", HIG"墓道"NOR);
set("long", @LONG
這裏是古墓中的墓道,四周密不透風,藉着牆上昏暗的燈光,你能
勉強分辨出方向。牆是用整塊的青石砌合起來的,接合得甚是完美,難
以從中找出一絲縫隙。燈光照在青石壁上,閃爍着碧幽幽的光點。
LONG );
set("exits", ([
"north" : __DIR__"mumen",
"south" : __DIR__"qianting",
]));
set("no_clean_up", 0);
set("coor/x", -3220);
set("coor/y", 20);
set("coor/z", 90);
setup();
}
/*
void init()
{
add_action("do_move", "move");
add_action("do_move", "luo");
add_action("do_move", "tui");
}
int do_move(string arg)
{
object room, me = this_player();
if( !arg || arg != "shi" )
{
return notify_fail("你要移動什麼?\n");
}
if( !query("exits/north"))
{
return notify_fail("降龍石已經落下,你還能移動什麼?\n");
}
if((int)me->query_str()>33)
{
message_vision("$N站在降龍石前,雙掌發力推動降龍石,只聽得降龍石吱吱連聲,緩緩向下落去,封住了墓門。\n", me);
delete("exits/north");
if( !(room = find_object(__DIR__"mumen")) )
room = load_object(__DIR__"mumen");
delete("exits/south", room);
tell_room(room,"只聽得降龍石吱吱連聲,緩緩向下落去,封住了墓門。\n");
}
else
message_vision("$N試着推了推巨石,巨石紋絲不動,只得罷了。\n", this_player());
return 1;
}
*/ | 24.166667 | 84 | 0.491724 | [
"object"
] |
b37ba5be5117dd0cee1b139c7af9ac6f5e2027cc | 4,076 | h | C | skate/socket/common.h | owacoder/skate | 1839f8f9273672bd408f6087d148fa21cb156603 | [
"BSL-1.0"
] | null | null | null | skate/socket/common.h | owacoder/skate | 1839f8f9273672bd408f6087d148fa21cb156603 | [
"BSL-1.0"
] | null | null | null | skate/socket/common.h | owacoder/skate | 1839f8f9273672bd408f6087d148fa21cb156603 | [
"BSL-1.0"
] | null | null | null | /** @file
*
* @author Oliver Adams
* @copyright Copyright (C) 2021, Licensed under Apache 2.0
*/
#ifndef SKATE_SOCKET_COMMON_H
#define SKATE_SOCKET_COMMON_H
#include "socket.h"
#include <unordered_map>
namespace skate {
typedef uint8_t socket_watch_flags;
static constexpr socket_watch_flags WatchRead = 1 << 0;
static constexpr socket_watch_flags WatchWrite = 1 << 1;
static constexpr socket_watch_flags WatchExcept = 1 << 2;
static constexpr socket_watch_flags WatchError = 1 << 3;
static constexpr socket_watch_flags WatchHangup = 1 << 4;
static constexpr socket_watch_flags WatchInvalid = 1 << 5;
static constexpr socket_watch_flags WatchAll = 0xff;
class socket_timeout {
std::chrono::microseconds t;
bool infinite_;
public:
constexpr socket_timeout() : t{}, infinite_(true) {}
constexpr socket_timeout(std::chrono::microseconds timeout) : t(timeout), infinite_(false) {}
constexpr static socket_timeout infinite() noexcept { return {}; }
constexpr bool is_infinite() const noexcept { return infinite_; }
constexpr std::chrono::microseconds timeout() const noexcept { return t; }
};
enum class socket_blocking_adjustment {
unchanged,
nonblocking,
blocking
};
class socket_watcher {
socket_watcher(const socket_watcher &) = delete;
socket_watcher &operator=(const socket_watcher &) = delete;
protected:
socket_watcher() {}
template<typename socket_watcher>
friend class socket_server;
typedef std::function<void (system_socket_descriptor, socket_watch_flags)> native_watch_function;
// Returns which events are currently being watched on the socket
// Some watcher types (e.g. epoll(), kqueue()) may not have this information and will always return 0 (not watching)
virtual socket_watch_flags watching(system_socket_descriptor socket) const = 0;
// Watches a descriptor with the specified watch flags
virtual socket_blocking_adjustment watch(std::error_code &ec, system_socket_descriptor socket, socket_watch_flags watch_type) = 0;
// Modifies the watch type for a specified socket
// If the descriptor is not in the set, nothing happens
virtual socket_blocking_adjustment modify(std::error_code &ec, system_socket_descriptor socket, socket_watch_flags new_watch_type) {
const auto v = unwatch(ec, socket);
if (ec)
return v;
return watch(ec, socket, new_watch_type);
}
// Unwatches a descriptor that may still be open
// If the descriptor is not in the set, nothing happens
virtual socket_blocking_adjustment unwatch(std::error_code &ec, system_socket_descriptor socket) = 0;
// Unwatches a descriptor known to be closed already
// If the descriptor is not in the set, nothing happens
virtual void unwatch_dead_descriptor(std::error_code &ec, system_socket_descriptor socket) {
unwatch(ec, socket);
}
// Clears all descriptors from this watcher
virtual void clear(std::error_code &ec) = 0;
// Polls the watcher to obtain events that happened, returns system error on failure, 0 on success
virtual void poll(std::error_code &ec, native_watch_function fn, socket_timeout us) = 0;
public:
virtual ~socket_watcher() {}
};
}
#include "../io/adapters/json.h"
inline void display_socket_flags(skate::socket_watch_flags flags) {
std::vector<const char *> vec;
if (flags & skate::WatchRead) vec.push_back("Read");
if (flags & skate::WatchWrite) vec.push_back("Write");
if (flags & skate::WatchExcept) vec.push_back("Except");
if (flags & skate::WatchError) vec.push_back("Error");
if (flags & skate::WatchHangup) vec.push_back("Hangup");
if (flags & skate::WatchInvalid) vec.push_back("Invalid");
std::cout << skate::json(vec) << std::endl;
}
#endif // SKATE_SOCKET_COMMON_H
| 37.054545 | 140 | 0.683268 | [
"vector"
] |
b380a3d07f7e58159619c843bb78b2422b22b4fb | 919 | h | C | Engines/Internals/iTransform.h | ElianeBriand/SMolDock | de0cb746ef995ae0eef0f812ebd61727311c332f | [
"Apache-2.0"
] | 1 | 2019-05-30T02:33:13.000Z | 2019-05-30T02:33:13.000Z | Engines/Internals/iTransform.h | ElianeBriand/SMolDock | de0cb746ef995ae0eef0f812ebd61727311c332f | [
"Apache-2.0"
] | null | null | null | Engines/Internals/iTransform.h | ElianeBriand/SMolDock | de0cb746ef995ae0eef0f812ebd61727311c332f | [
"Apache-2.0"
] | 3 | 2020-12-30T19:11:51.000Z | 2021-06-25T02:45:49.000Z | //
// Created by eliane on 14/12/18.
//
#ifndef SMOLDOCK_ITRANSFORM_H
#define SMOLDOCK_ITRANSFORM_H
#include <vector>
#include <memory>
#include <array>
#include <cmath>
#include <boost/assert.hpp>
#include <Eigen/Core>
#include <Eigen/Dense>
namespace SmolDock {
//! Represents a rotation
/*!
*
*
* \sa iTransform
*/
//! Represents a rotation and translation transform to be applied on ligand/ligand part
/*!
* \sa iTranslation, Eigen::Quaternion<double>
*/
struct iTransform {
// Global component
Eigen::Vector3d transl;
Eigen::Quaternion<double> rota;
Eigen::Matrix<double, 3,3, Eigen::RowMajor> rotMatrix;
inline void doHousekeeping() {
rota.normalize();
rotMatrix = rota.toRotationMatrix();
}
std::vector<double> bondRotationsAngles;
};
}
#endif //SMOLDOCK_ITRANSFORM_H
| 19.145833 | 91 | 0.627856 | [
"vector",
"transform"
] |
b3845cc49f4815b9f5edb4337bc7aa07a4c8b715 | 18,572 | h | C | viennats/Math.h | Prindl/viennats-dev | 305eaf16709db950d10149daff87af1e07c58efa | [
"MIT"
] | null | null | null | viennats/Math.h | Prindl/viennats-dev | 305eaf16709db950d10149daff87af1e07c58efa | [
"MIT"
] | null | null | null | viennats/Math.h | Prindl/viennats-dev | 305eaf16709db950d10149daff87af1e07c58efa | [
"MIT"
] | null | null | null | #ifndef DEF_MYMATH_2D
#define DEF_MYMATH_2D
/* =========================================================================
Copyright (c) 2008-2015, Institute for Microelectronics, TU Wien.
-----------------
ViennaTS - The Vienna Topography Simulator
-----------------
Contact: viennats@iue.tuwien.ac.at
License: MIT (X11), see file LICENSE in the base directory
============================================================================= */
#include <cmath>
//#include <boost/static_assert.hpp>
///Namespace for all custom mathematical and statistical tools.
namespace my {
///Includes mathematical functions like equation solvers, root finders and vector arithmetic.
namespace math {
const double Pi1_2 =1*std::asin(1.);
const double Pi =2*std::asin(1.);
const double Pi2 =4*std::asin(1.);
const double PiH2_8 =std::asin(1.)*std::asin(1.)*0.5;
template<class T> int Sign(T);
template<class T> int SignPos(T);
template<class T> int SignNeg(T);
template<class T> int SignEps(T,T);
template<class T> T pow(T,int);
template<class T> T pow2(T);
int fac(int);
int SignPow(int);
int SolveCubic(double c[4], double s[3]);
int SolveQudratic(double c[3],double s[2]);
int SolveLinear(double c[2],double s[1]);
///factorial
template<int n> class factorial {
public:
enum {RET = n * factorial<n - 1>::RET};
};
template<> class factorial<0>{
public:
enum { RET = 1 };
};
//template<int D> class LinearRayInterpolation;
template<class CoefT, int Order> class Polynom;
double FindFirstRoot(double IntervalStart, double IntervalEnd, const Polynom<double, 2>& p);
double FindFirstRoot(double IntervalStart, double IntervalEnd, const Polynom<double, 3>& p);
template<int D> void TransformRho(double*);
//template <int D> int GetRho(double* rho, double* distances, unsigned int* pts );
template <int D> void DetermineCoefficientsForImplicitRayTracing(const double* Position, const double* Direction, const double* Rho, double* Coefficients );
template <int D> void CalculateNormal(double* n, const double* v, const double* A);
/*template <int D, template <class, int> class V > inline V<int,D> round(const V<double,D>& vd) {
V<int,D> vi;
for (int i=0;i<D;i++) vi[i]=static_cast<int>(nearbyint(vd[i]));
return vi;
}
template <int D, template <class, int> class V > inline V<int,D> floor(const V<double,D>& vd) {
V<int,D> vi;
for (int i=0;i<D;i++) vi[i]=static_cast<int>(std::floor(vd[i]));
return vi;
}
template <int D, template <class, int> class V > inline V<int,D> ceil(const V<double,D>& vd) {
V<int,D> vi;
for (int i=0;i<D;i++) vi[i]=static_cast<int>(std::ceil(vd[i]));
return vi;
}*/
template<class T>
inline T Interpolate(const T* X, const T* Y, int N, T v)
{
if (v<=X[0]) return Y[0];
if (v>=X[N-1]) return Y[N-1];
int a=0;
int b=N-1;
while (a+1!=b) {
int c=(a+b)/2;
if (X[c]>v) b=c; else a=c;
};
return Y[a]+(Y[b]-Y[a])*((v-X[a])/(X[b]-X[a]));
}
template <int D>
struct TransformRho2 {
static void exec(double Rho[]) {
enum {tmp=1<<(D-1)};
TransformRho2<D-1>::exec(Rho);
TransformRho2<D-1>::exec(Rho+tmp);
for (int i=0;i<tmp;++i) Rho[i+tmp]-=Rho[i];
}
};
template <>
struct TransformRho2<0> {
static void exec(double Rho[]) {}
};
}
}
template<class T> inline int my::math::Sign(T x) {
if (x>T(0)) return 1;
if (x<T(0)) return -1;
return 0;
}
template<class T> inline int my::math::SignPos(T x) {
if (x<T(0)) return -1;
return 1;
}
template<class T> inline int my::math::SignNeg(T x) {
if (x>T(0)) return 1;
return -1;
}
template<class T> inline int my::math::SignEps(T x, T eps) {
if (x>eps) {
return 1;
} else if (x<-eps) {
return -1;
} else {
return 0;
}
}
template<class T> inline T my::math::pow(T x, int k) {
T p(1);
for (int i=0;i<k;i++) p*=x;
return p;
}
template<class T> inline T my::math::pow2(T x) {
return x*x;
}
inline int my::math::fac(int k) {
int p=1;
for (int i=2;i<=k;i++) p*=i;
return p;
}
inline int my::math::SignPow(int k) {
if (k%2==0) return 1; else return -1;
}
inline int my::math::SolveCubic(double c[4], double s[3]) {
if (std::fabs(c[3])<=1e-10*std::fabs(c[0])) {
return SolveQudratic(c,s);
} else {
const double Pi2_3=(M_PI*2.)/3.;
double A = c[ 2 ] / (3.*c[ 3 ]);
double B = c[ 1 ] / c[ 3 ];
double C = c[ 0 ] / c[ 3 ];
double A2=A*A;
double R=A2*A+(C-A*B)*0.5;
double R2=R*R;
double Q=(A2-B/3.);
double Q3=Q*Q*Q;
if (R2<Q3) {
double Q1_2=sqrt(Q);
double theta=acos(R/(Q*Q1_2))/3.;
s[0]=-2.*Q1_2*cos(theta)-A;
s[1]=-2.*Q1_2*cos(theta+Pi2_3)-A;
s[2]=-2.*Q1_2*cos(theta-Pi2_3)-A;
return 3;
} else {
double AA=-cbrt(R+my::math::Sign(R)*sqrt(R2-Q3));
if (AA!=0.) {
s[0]=AA+Q/AA-A;
return 1;
} else {
s[0]=AA-A;
return 1;
}
}
}
}
int my::math::SolveQudratic(double c[3],double s[2]) {
if (std::fabs(c[2])<=1e-10*std::fabs(c[0])) {
return SolveLinear(c,s);
} else {
double D=c[1]*c[1]-4.*c[0]*c[2];
if (D<0.) {
return 0;
} else {
double Q=-0.5*(c[1]+my::math::Sign(c[1])*std::sqrt(D));
s[0]=Q/c[2];
s[1]=c[0]/Q;
return 2;
}
}
}
int my::math::SolveLinear(double c[2],double s[1]) {
if (std::fabs(c[1])<=1e-10*std::fabs(c[0])) {
return 0;
} else {
s[0]=-c[0]/c[1];
return 1;
}
}
namespace my {
namespace math {
/*template <int D> LinearRayInterpoaltion {
public:
LinearRayInterpolation()
}*/
template<class CoefT, int Order> class Polynom {
CoefT coefficients[Order+1];
public:
const CoefT* Coefficients() const {
return coefficients;
}
CoefT* Coefficients() {
return coefficients;
}
CoefT Coefficients(int order) const {
return coefficients[order];
}
Polynom() {}
template <class ArgT> CoefT operator()(ArgT x) const {
CoefT result=coefficients[Order];
for (int g=Order-1;g>=0;g--) {
result*=x;
result+=coefficients[g];
}
return result;
}
template <class ArgT> CoefT Derivate1(ArgT x) const {
CoefT result=Order*coefficients[Order];
for (int g=Order-1;g>0;g--) {
result*=x;
result+=g*coefficients[g];
}
return result;
}
};
template <class T> T FindFirstTransitionFromPosToNegOfPolynomBisect(T t0, T t1, const Polynom<T, 3>& p ,T eps) {
if (t0>t1) return std::numeric_limits<T>::max();
T f=p(t0);
if (f<-eps) {
return t0;
} else if (f<=eps) {
if (p.Derivate1(t0)<=0.) return t0;
}
f=p(t1);
bool Intersection=false;
if (f<-eps) {
Intersection=true;
} else if (f<=eps) {
if (p.Derivate1(t1)<=0.) {
Intersection=true;
}
}
T Discriminant=p.Coefficients()[2]*p.Coefficients()[2]-3.*p.Coefficients()[1]*p.Coefficients()[3];
if (Discriminant>=0) { //p' has real roots
//calculate roots of p'
T Q=-(p.Coefficients()[2]+my::math::SignPos(p.Coefficients()[2])*std::sqrt(Discriminant));
T e0=Q/(3.*p.Coefficients()[3]);
T e1=p.Coefficients()[1]/Q;
if (e0>e1) std::swap(e0,e1);
if ((e0<t1) && (e0>t0)) { //if e0 element of [t0,t1]
if (p(e0)>0.) {
t0=e0;
} else {
t1=e0;
Intersection=true;
}
}
if ((e1<t1) && (e1>t0)) { //if e1 element of [t0,t1]
if (p(e1)>0.) {
t0=e1;
} else {
t1=e1;
Intersection=true;
}
}
}
if (!Intersection) return std::numeric_limits<T>::max();
while(std::fabs(t1-t0)>eps) {
T t=0.5*(t1+t0);
f=p(t);
if (f==0.) {
return t;
} else if (f>0.) {
t0=t;
} else {
t1=t;
}
}
return t0;
}
template <class T> T FindFirstTransitionFromPosToNegOfPolynomNewton(T t0, T t1, const Polynom<T, 3>& p ,T eps) {
if (t0>t1) return std::numeric_limits<T>::max();
T f=p(t0);
if (f<-eps) {
return t0;
} else if (f<=eps) {
if (p.Derivate1(t0)<=0.) return t0;
}
f=p(t1);
bool Intersection=false;
if (f<-eps) {
Intersection=true;
} else if (f<=eps) {
if (p.Derivate1(t1)<=0.) {
Intersection=true;
}
}
T Discriminant=p.Coefficients(2)*p.Coefficients(2)-3.*p.Coefficients(1)*p.Coefficients(3);
if (Discriminant>=0) { //p' has real roots
//calculate roots of p'
T Q=-(p.Coefficients(2)+my::math::SignPos(p.Coefficients(2))*std::sqrt(Discriminant));
T e0=Q/(3.*p.Coefficients(3));
T e1=p.Coefficients()[1]/Q;
if (e0>e1) std::swap(e0,e1);
if ((e0<t1) && (e0>t0)) { //if e0 element of [t0,t1]
if (p(e0)>0.) {
t0=e0;
} else {
t1=e0;
Intersection=true;
}
}
if ((e1<t1) && (e1>t0)) { //if e1 element of [t0,t1]
if (p(e1)>0.) {
t0=e1;
} else {
t1=e1;
Intersection=true;
}
}
}
if (!Intersection) return std::numeric_limits<T>::max();
T t=(t1+t0)*0.5;
T dxold=t1-t0;
T dx=dxold;
T ft=p(t);
T dft=p.Derivate1(t);
while(true) {
if (( ((t-t0)*dft-ft)*((t-t1)*dft-ft)>0. ) || (std::fabs(ft+ft)>std::fabs(dxold*dft))) {
dxold=dx;
dx=0.5*(t1-t0);
t=t0+dx;
if ((t0==t) || (dx<eps)) return t0;
} else {
dxold=dx;
dx=ft/dft;
T temp=t;
t-=dx;
if ((temp==t) || (std::fabs(dx)<eps)) return std::max(t-eps,t0);
}
ft=p(t);
dft=p.Derivate1(t);
if (ft>0.0) {
t0=t;
} else {
t1=t;
}
}
}
template <class T> T FindFirstTransitionFromPosToNegOfPolynomNewton(T t0, T t1, const Polynom<T, 2>& p ,T eps) {
if (t0>t1) return std::numeric_limits<T>::max();
T f=p(t0);
if (f<-eps) {
return t0;
} else if (f<=eps) {
if (p.Derivate1(t0)<=0.) return t0;
}
f=p(t1);
bool Intersection=false;
if (f<-eps) {
Intersection=true;
} else if (f<=eps) {
if (p.Derivate1(t1)<=0.) {
Intersection=true;
}
}
T e=-0.5*(p.Coefficients(1)/p.Coefficients(2)); //determine inflection point
if ((e<t1) && (e>t0)) { //if e0 element of [t0,t1]
if (p(e)>0.) {
t0=e;
} else {
t1=e;
Intersection=true;
}
}
if (!Intersection) return std::numeric_limits<T>::max();
T t=(t1+t0)*0.5;
T dxold=t1-t0;
T dx=dxold;
T ft=p(t);
T dft=p.Derivate1(t);
while(true) {
if (( ((t-t0)*dft-ft)*((t-t1)*dft-ft)>0. ) || (std::fabs(ft+ft)>std::fabs(dxold*dft))) {
dxold=dx;
dx=0.5*(t1-t0);
t=t0+dx;
if ((t0==t) || (dx<eps)) return t0;
} else {
dxold=dx;
dx=ft/dft;
T temp=t;
t-=dx;
if ((temp==t) || (std::fabs(dx)<eps)) return std::max(t-eps,t0);
}
ft=p(t);
dft=p.Derivate1(t);
if (ft>0.0) {
t0=t;
} else {
t1=t;
}
}
}
double FindFirstRoot(double t0, double t1, const Polynom<double, 3>& p) {
//BOOST_STATIC_ASSERT(std::numeric_limits<double>::has_infinity);
const int N=5;
double f0=p(t0);
int sgn0=Sign(f0);
if (sgn0<0) return t0;
double f1=p(t1);
int sgn1=Sign(f1);
double Discriminant=p.Coefficients()[2]*p.Coefficients()[2]-3.*p.Coefficients()[1]*p.Coefficients()[3];
if (Discriminant>=0) { //p' has real roots
//calculate roots of p'
double Q=-(p.Coefficients()[2]+my::math::SignPos(p.Coefficients()[2])*std::sqrt(Discriminant));
double e0=Q/(3.*p.Coefficients()[3]);
double e1=p.Coefficients()[1]/Q;
if (e0>e1) std::swap(e0,e1);
if ((e0<=t1) && (e0>=t0)) { //if e0 element of [t0,t1]
double fe0=p(e0);
int sgn_fe0=Sign(fe0);
if (sgn_fe0==sgn0) {
t0=e0;
f0=fe0;
sgn0=sgn_fe0;
} else {
t1=e0;
f1=fe0;
sgn1=sgn_fe0;
}
}
if ((e1<=t1) && (e1>=t0)) { //if e1 element of [t0,t1]
double fe1=p(e1);
int sgn_fe1=Sign(fe1);
if (sgn_fe1==sgn0) {
t0=e1;
f0=fe1;
sgn0=sgn_fe1;
} else {
t1=e1;
f1=fe1;
sgn1=sgn_fe1;
}
}
}
if (sgn0==0) {
return t0;
} else if (sgn1==0) {
return t1;
} else if (sgn0==sgn1) {
return std::numeric_limits<double>::max();
}
for (int i=0;i<N;i++) {
//double t=t0-(t1-t0)*(f0/(f1-f0));
double t=(t1+t0)/2;
double ft=p(t);
int sgn_ft=Sign(ft);
if (sgn_ft==0) return t;
if (sgn_ft==sgn0) {
t0=t;
f0=ft;
} else {
t1=t;
f1=ft;
}
}
return t0-(t1-t0)*(f0/(f1-f0));
//return (t1+t0)/2;
}
double FindFirstRoot(double t0, double t1, const Polynom<double, 2>& p) {
//BOOST_STATIC_ASSERT(std::numeric_limits<double>::has_infinity);
double Discriminant=p.Coefficients()[1]*p.Coefficients()[1]-4.*p.Coefficients()[0]*p.Coefficients()[2];
if (Discriminant>=0) { //p has real roots
//calculate roots of p
double Q=-(p.Coefficients()[1]+my::math::SignPos(p.Coefficients()[1])*std::sqrt(Discriminant))*0.5;
double e0=Q/p.Coefficients()[2];
double e1=p.Coefficients()[0]/Q;
if (e0>e1) std::swap(e0,e1);
if ((e0<=t1) && (e0>=t0)) { //if e0 element of [t0,t1]
return e0;
}
if ((e1<=t1) && (e1>=t0)) { //if e1 element of [t0,t1]
return e1;
}
}
return std::numeric_limits<double>::max();
}
template <> void DetermineCoefficientsForImplicitRayTracing<2>(const double* Position, const double* Direction, const double* Rho, double* Coefficients ) {
Coefficients[2]=Direction[0]*Rho[3];
Coefficients[1]=Position[1]*Coefficients[2];
Coefficients[2]*=Direction[1];
Coefficients[0]=Position[0]*Rho[3]+Rho[2];
Coefficients[1]+=Direction[1]*Coefficients[0]+Direction[0]*Rho[1];
Coefficients[0]*=Position[1];
Coefficients[0]+=Position[0]*Rho[1]+Rho[0];
/*
//TEST
double t=43.3;
double x=Position[0]+t*Direction[0];
double y=Position[1]+t*Direction[1];
double val1=Coefficients[2]*t*t+Coefficients[1]*t+Coefficients[0];
double val2=x*y*Rho[3]+y*Rho[2]+x*Rho[1]+Rho[0];
assert(std::fabs(val1-val2)<1e-8);
*/
}
/*template <> void TransformRho<3>(double* Rho) {
double g=Rho[0];
g-=Rho[1];
g-=Rho[2];
g-=Rho[4];
Rho[7]-=g;
Rho[7]-=Rho[3];
Rho[7]-=Rho[5];
Rho[7]-=Rho[6];
Rho[3]+=g;
Rho[3]+=Rho[4];
Rho[5]+=g;
Rho[5]+=Rho[2];
Rho[6]+=g;
Rho[6]+=Rho[1];
Rho[1]-=Rho[0];
Rho[2]-=Rho[0];
Rho[4]-=Rho[0];
}
template <> void TransformRho<2>(double* Rho) {
Rho[1]-=Rho[0];
Rho[3]-=Rho[1];
Rho[3]-=Rho[2];
Rho[2]-=Rho[0];
}*/
template <> void DetermineCoefficientsForImplicitRayTracing<3>(const double* Position, const double* Direction, const double* Rho, double* Coefficients ) {
Coefficients[2]=Direction[1]*Direction[0];
Coefficients[3]=Coefficients[2]*Direction[2]*Rho[7];
Coefficients[2]*=(Position[2]*Rho[7]+Rho[3]);
double tmp=Position[1]*Rho[7]+Rho[5];
Coefficients[0]=tmp*Position[0]+Position[1]*Rho[6]+Rho[4];
Coefficients[1]=Coefficients[0]*Direction[2];
Coefficients[0]*=Position[2];
tmp*=Direction[0];
tmp+=(Direction[1]*(Position[0]*Rho[7]+Rho[6]));
Coefficients[2]+=Direction[2]*tmp;
Coefficients[1]+=Position[2]*tmp;
tmp=Position[0]*Rho[3]+Rho[2];
Coefficients[1]+=((Position[1]*Rho[3]+Rho[1])*Direction[0]+Direction[1]*tmp);
Coefficients[0]+=(Position[1]*tmp+Rho[1]*Position[0]+Rho[0]);
}
template <> void CalculateNormal<3>(double* n, const double* v, const double* Rho) {
n[0]=v[1]*Rho[7]+Rho[5];
n[2]=n[0];
n[0]*=v[2];
n[0]+=(v[1]*Rho[3]+Rho[1]);
n[1]=v[2]*(v[0]*Rho[7]+Rho[6])+v[0]*Rho[3]+Rho[2];
n[2]*=v[0];
n[2]+=(v[1]*Rho[6]+Rho[4]);
double no2=n[0]*n[0]+n[1]*n[1]+n[2]*n[2];
if (no2>0.) {
no2=std::sqrt(no2);
n[0]/=no2;
n[1]/=no2;
n[2]/=no2;
} else {
n[0]=0.;
n[1]=0.;
n[2]=0.;
}
}
template <> void CalculateNormal<2>(double* n, const double* v, const double* Rho) {
n[0]=Rho[1]+v[1]*Rho[3];
n[1]=Rho[2]+v[0]*Rho[3];
double no2=n[0]*n[0]+n[1]*n[1];
if (no2>0.) {
no2=std::sqrt(no2);
n[0]/=no2;
n[1]/=no2;
} else {
n[0]=0.;
n[1]=0.;
}
}
}
}
#endif //DEF_MYMATH_2D
| 23.658599 | 160 | 0.481154 | [
"vector"
] |
b3909953eab08a993efa5625409d05deb937ba3f | 21,483 | c | C | src/src/hostcall.c | Kochise/GLFrontier-win32 | 9ecb7c33a5ebf9c7916cb647483722dc66cad8f2 | [
"MIT"
] | null | null | null | src/src/hostcall.c | Kochise/GLFrontier-win32 | 9ecb7c33a5ebf9c7916cb647483722dc66cad8f2 | [
"MIT"
] | null | null | null | src/src/hostcall.c | Kochise/GLFrontier-win32 | 9ecb7c33a5ebf9c7916cb647483722dc66cad8f2 | [
"MIT"
] | null | null | null | /*
Hatari - gemdos.c
This file is distributed under the GNU Public License, version 2 or at
your option any later version. Read the file gpl.txt for details.
GEMDOS intercept routines.
These are used mainly for hard drive redirection of high level file routines.
Now case is handled by using glob. See the function
GemDOS_CreateHardDriveFileName for that. It also knows about symlinks.
A filename is recognized on its eight first characters, do don't try to
push this too far, or you'll get weirdness ! (But I can even run programs
directly from a mounted cd in lower cases, so I guess it's working well !).
*/
#include <time.h>
#include <ctype.h>
#include <SDL.h>
#include <SDL_endian.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include "main.h"
#include "../m68000.h"
#include "hostcall.h"
#include "screen.h"
#include "audio.h"
#include "input.h"
#include "keymap.h"
#include "shortcut.h"
/*
GEMDOS error codes, See 'The Atari Compendium' D.3
Call_Fread, Fwrite, etc should return these.
*/
#define GEMDOS_EOK 0 // OK
#define GEMDOS_ERROR -1 // Generic error
#define GEMDOS_EDRVNR -2 // Drive not ready
#define GEMDOS_EUNCMD -3 // Unknown command
#define GEMDOS_E_CRC -4 // CRC error
#define GEMDOS_EBADRQ -5 // Bad request
#define GEMDOS_E_SEEK -6 // Seek error
#define GEMDOS_EMEDIA -7 // Unknown media
#define GEMDOS_ESECNF -8 // Sector not found
#define GEMDOS_EPAPER -9 // Out of paper
#define GEMDOS_EWRITF -10 // Write fault
#define GEMDOS_EREADF -11 // Read fault
#define GEMDOS_EWRPRO -12 // Device is write protected
#define GEMDOS_E_CHNG -14 // Media change detected
#define GEMDOS_EUNDEV -15 // Unknown device
#define GEMDOS_EINVFN -32 // Invalid function
#define GEMDOS_EFILNF -33 // File not found
#define GEMDOS_EPTHNF -34 // Path not found
#define GEMDOS_ENHNDL -35 // No more handles
#define GEMDOS_EACCDN -36 // Access denied
#define GEMDOS_EIHNDL -37 // Invalid handle
#define GEMDOS_ENSMEM -39 // Insufficient memory
#define GEMDOS_EIMBA -40 // Invalid memory block address
#define GEMDOS_EDRIVE -46 // Invalid drive specification
#define GEMDOS_ENSAME -48 // Cross device rename
#define GEMDOS_ENMFIL -49 // No more files
#define GEMDOS_ELOCKED -58 // Record is already locked
#define GEMDOS_ENSLOCK -59 // Invalid lock removal request
#define GEMDOS_ERANGE -64 // Range error
#define GEMDOS_EINTRN -65 // Internal error
#define GEMDOS_EPLFMT -66 // Invalid program load format
#define GEMDOS_EGSBF -67 // Memory block growth failure
#define GEMDOS_ELOOP -80 // Too many symbolic links
#define GEMDOS_EMOUNT -200 // Mount point crossed (indicator)
void Call_Memset ()
{
int adr, count;
unsigned long Params;
Params = GetReg (REG_A7);
Params -= SIZE_WORD;
count = STMemory_ReadLong (Params+SIZE_WORD);
adr = STMemory_ReadLong (Params+SIZE_WORD+SIZE_LONG);
if (use_renderer == R_OLD) {
memset (STRam+adr, 0, count);
} else {
memset (STRam+adr, 255, count);
}
fe2_bgcol = 0;
}
void Call_MemsetBlue ()
{
int adr, count;
unsigned long Params;
Params = GetReg (REG_A7);
Params -= SIZE_WORD;
count = STMemory_ReadLong (Params+SIZE_WORD);
adr = STMemory_ReadLong (Params+SIZE_WORD+SIZE_LONG);
if (use_renderer == R_OLD) {
memset (STRam+adr, 0xe, count);
} else {
memset (STRam+adr, 255, count);
}
fe2_bgcol = 0xe;
}
void Call_Memcpy ()
{
int dest, src, count;
unsigned long Params;
Params = GetReg (REG_A7);
Params -= SIZE_WORD;
dest = STMemory_ReadLong (Params + SIZE_WORD);
src = STMemory_ReadLong (Params + SIZE_WORD + SIZE_LONG);
count = STMemory_ReadLong (Params + SIZE_WORD + 2*SIZE_LONG);
memcpy (STRam+dest, STRam+src, count);
}
static const char mouse_bmp[256] = {
0, 0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,15, 0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,15,15, 0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,15,15,15, 0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,15,15,15,15, 0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,15,15,15,15,15, 0,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,15,15,15,15, 0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,15,15,15,15, 0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0,15, 0,15,15,15, 0,-1,-1,-1,-1,-1,-1,-1,-1,-1,
0, 0,-1, 0,15,15, 0,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1, 0,15,15,15, 0,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1, 0,15,15, 0,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1, 0,15,15,15, 0,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1, 0,15, 0,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1, 0,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
};
Uint8 under_mouse[256];
void Call_BlitCursor ()
{
#if 0
int x, y, adr, org_x, org_y;
Uint8 *pixbase, *pix;
const char *bmp;
Uint8 *save;
unsigned long Params;
Params = GetReg (REG_A7);
Params -= SIZE_WORD;
org_x = STMemory_ReadLong (Params+SIZE_WORD);
org_y = STMemory_ReadLong (Params+SIZE_WORD+SIZE_LONG);
adr = STMemory_ReadLong (Params+SIZE_WORD+2*SIZE_LONG);
pixbase = STRam + adr + (org_y*SCREENBYTES_LINE) + org_x;
bmp = mouse_bmp;
save = under_mouse;
for (y=0; y<16; y++) {
if (y + org_y > SCREEN_HEIGHT_HBL) break;
pix = pixbase;
pixbase += SCREENBYTES_LINE;
for (x=0; x<16; x++, pix++, bmp++, save++) {
if (x+org_x >= SCREENBYTES_LINE) continue;
*save = *pix;
if (*bmp != -1) *pix = *bmp;
}
}
#endif /* 0 */
/* in screen.h */
mouse_shown = 1;
}
void Call_RestoreUnderCursor ()
{
#if 0
int x, y, adr, org_x, org_y;
Uint8 *pixbase, *pix;
char *bmp;
unsigned long Params;
Params = GetReg (REG_A7);
Params -= SIZE_WORD;
org_x = STMemory_ReadLong (Params+SIZE_WORD);
org_y = STMemory_ReadLong (Params+SIZE_WORD+SIZE_LONG);
adr = STMemory_ReadLong (Params+SIZE_WORD+2*SIZE_LONG);
pixbase = STRam + adr + (org_y*SCREENBYTES_LINE) + org_x;
bmp = under_mouse;
for (y=0; y<16; y++) {
if (y + org_y > SCREEN_HEIGHT_HBL) break;
pix = pixbase;
pixbase += SCREENBYTES_LINE;
for (x=0; x<16; x++, pix++, bmp++) {
if (x+org_x >= SCREENBYTES_LINE) continue;
if (*bmp != -1) *pix = *bmp;
}
}
#endif /* 0 */
}
void Call_PutPix ()
{
int col, org_x, scr;
char *pix;
unsigned long Params;
Params = GetReg (REG_A7);
Params -= SIZE_WORD;
col = STMemory_ReadWord (Params+SIZE_WORD)>>2;
org_x = (unsigned short) GetReg (REG_D4);
scr = GetReg (REG_A3);
/* hack to fix screen line. frontier's logic still thinks
* there are 160 bytes per line */
/* which screen buffer it is based on */
if (scr & 0x100000) {
scr -= 0x100000;
scr *= 2;
scr += 0x100000;
} else {
scr -= 0xf0000;
scr *= 2;
scr += 0xf0000;
}
pix = (char *)STRam + scr + org_x;
*pix = col;
return;
}
void Call_FillLine ()
{
int org_x,len,scr,col;
char *pix;
unsigned long Params;
Params = GetReg (REG_A7);
Params -= SIZE_WORD;
col = STMemory_ReadWord (Params+SIZE_WORD)>>2;
org_x = (unsigned short) GetReg (REG_D4);
len = (~GetReg (REG_D5)) & 0xffff;
scr = GetReg (REG_A3);
/* hack to fix screen line. frontier's logic still thinks
* there are 160 bytes per line */
/* which screen buffer it is based on */
if (scr & 0x100000) {
scr -= 0x100000;
scr *= 2;
scr += 0x100000;
} else {
scr -= 0xf0000;
scr *= 2;
scr += 0xf0000;
}
pix = (char *)STRam + scr;
org_x = SCREENBYTES_LINE;
while (org_x--) {
*pix = col;
pix++;
}
}
/*
* This is used by the scanner code to draw object stalks
* which are below the plane of the scanner.
* The mask d7 indicates which pixels in the plane to set,
* and they are set if their current colour is zero.
*
* This implementation isn't the way the function is really
* supposed to be implemented (colour and draw mask was
* combined in d6 but the colour mask is wrong now for
* non-planar screen).
*/
void Call_BackHLine ()
{
int i,scr,col,bitfield;
char *pix;
unsigned long Params;
Params = GetReg (REG_A7);
Params -= SIZE_WORD;
col = STMemory_ReadWord (Params+SIZE_WORD)>>2;
scr = GetReg (REG_A3);
bitfield = (unsigned short) GetReg (REG_D7);
/* hack to fix screen line. frontier's logic still thinks
* there are 160 bytes per line */
/* which screen buffer it is based on */
if (scr & 0x100000) {
scr -= 0x100000;
scr *= 2;
scr += 0x100000;
} else {
scr -= 0xf0000;
scr *= 2;
scr += 0xf0000;
}
pix = STRam + scr;
for (i=15; i>=0; i--) {
if ((bitfield & (1<<i)) && (*pix == 0)) *pix = col;
pix++;
}
}
void Call_OldHLine ()
{
int org_x,len,scr,col;
char *pix;
unsigned long Params;
Params = GetReg (REG_A7);
Params -= SIZE_WORD;
col = STMemory_ReadWord (Params+SIZE_WORD)>>2;
//printf ("col=%d, d4=%d, (idx) d5=%d, (scr_line) a3=%p\n", col, Regs[REG_D4]&0xffff, Regs[REG_D5]&0xffff, (void*)Regs[REG_A3]);
org_x = (unsigned short) GetReg (REG_D4);
len = (unsigned short) GetReg (REG_D5);
scr = GetReg (REG_A3);
/* hack to fix screen line. frontier's logic still thinks
* there are 160 bytes per line */
/* which screen buffer it is based on */
if (scr & 0x100000) {
scr -= 0x100000;
scr *= 2;
scr += 0x100000;
} else {
scr -= 0xf0000;
scr *= 2;
scr += 0xf0000;
}
len = len/2;
/* horizontal line */
pix = STRam + scr + org_x;
while (len--) {
*pix = col;
pix++;
}
}
void Call_HLine ()
{
int org_x,len,scr,col;
char *pix;
col = (GetReg(REG_D1) & 0xffff)>>2;
org_x = GetReg(REG_D4) & 0xffff;
len = GetReg(REG_D5) & 0xffff;
scr = GetReg(REG_A3);
/* horizontal line */
pix = STRam + scr + org_x;
while (len--) {
*pix = col;
pix++;
}
}
/*
* Blits frontier format 4-plane thingy
*/
void Call_BlitBmp ()
{
int width, height, org_x, org_y, bmp, scr;
char *bmp_pix, *scr_pix, *ybase;
int xpoo, i, ypoo, plane_incr;
short word0, word1, word2, word3;
unsigned long Params;
Params = GetReg (REG_A7);
Params -= SIZE_WORD;
width = STMemory_ReadWord (Params+SIZE_WORD);
height = STMemory_ReadWord (Params+SIZE_WORD*2);
org_x = STMemory_ReadWord (Params+SIZE_WORD*3);
org_y = STMemory_ReadWord (Params+SIZE_WORD*4);
bmp = STMemory_ReadLong (Params+SIZE_WORD*5);
scr = STMemory_ReadLong (Params+SIZE_WORD*5 + SIZE_LONG);
/* width is in words (width/16) */
//printf ("Blit %dx%d to %d,%d, bmp 0x%x, scr 0x%x.\n", width, height, org_x, org_y, bmp, scr);
bmp_pix = STRam + bmp + 4;
ybase = STRam + scr + (org_y*SCREENBYTES_LINE) + org_x;
/* These checks were in the original blit routine */
if (org_x < 0) return;
if (org_y < 0) return;
if (height > 200) return;
if (width > 320) return;
plane_incr = 2*height*width;
ypoo = height;
while (ypoo--) {
scr_pix = (char *)ybase;
ybase += SCREENBYTES_LINE;
for (xpoo = width; xpoo; xpoo--) {
word0 = SDL_SwapBE16 (*((short*)bmp_pix));
bmp_pix += plane_incr;
word1 = SDL_SwapBE16 (*((short*)bmp_pix));
bmp_pix += plane_incr;
word2 = SDL_SwapBE16 (*((short*)bmp_pix));
bmp_pix += plane_incr;
word3 = SDL_SwapBE16 (*((short*)bmp_pix));
for (i=0; i<16; i++) {
*scr_pix = (word0 >> (15-i))&0x1;
*scr_pix |= ((word1 >> (15-i))&0x1)<<1;
*scr_pix |= ((word2 >> (15-i))&0x1)<<2;
*scr_pix |= ((word3 >> (15-i))&0x1)<<3;
scr_pix++;
}
bmp_pix -= 3*plane_incr;
bmp_pix += 2;
}
}
#if 0
glDisable (GL_DEPTH_TEST);
glMatrixMode (GL_PROJECTION);
glPushMatrix ();
glLoadIdentity ();
glOrtho (0, 320, 0, 200, -1, 1);
glMatrixMode (GL_MODELVIEW);
glPushMatrix ();
glLoadIdentity ();
printf ("%d,%d %dx%d\n", org_x, org_y, width*16, height);
glTranslated (org_x, 0, 0);
glBegin (GL_TRIANGLE_STRIP);
glColor3f (0.0f, 0.0f, 1.0f);
glVertex2i (0, 0);
glVertex2i (width*16, 0);
glVertex2i (0, height);
glVertex2i (width*16, height);
glEnd ();
glMatrixMode (GL_PROJECTION);
glPopMatrix ();
glMatrixMode (GL_MODELVIEW);
glPopMatrix ();
glEnable (GL_DEPTH_TEST);
#endif
}
#define SCR_W 320
void Call_DrawStrShadowed ()
{
unsigned char *str;
str = GetReg (REG_A0) + STRam;
SetReg (REG_D1, DrawStr (
GetReg (REG_D1), GetReg (REG_D2),
GetReg (REG_D0), str, TRUE));
}
void Call_DrawStr ()
{
unsigned char *str;
str = GetReg (REG_A0) + STRam;
SetReg (REG_D1, DrawStr (
GetReg (REG_D1), GetReg (REG_D2),
GetReg (REG_D0), str, FALSE));
}
void Call_SetMainPalette ()
{
Uint32 pal_ptr;
int i;
unsigned long Params;
Params = GetReg (REG_A7);
Params -= SIZE_WORD;
pal_ptr = STMemory_ReadLong (Params+SIZE_WORD);
for (i=0; i<16; i++) {
MainPalette[i] = STMemory_ReadWord (pal_ptr);
//printf ("%hx ", MainPalette[i]);
pal_ptr+=2;
}
//printf ("\n");
}
void Call_SetCtrlPalette ()
{
Uint32 pal_ptr;
int i;
unsigned long Params;
Params = GetReg (REG_A7);
Params -= SIZE_WORD;
pal_ptr = STMemory_ReadLong (Params+SIZE_WORD);
for (i=0; i<16; i++) {
CtrlPalette[i] = STMemory_ReadWord (pal_ptr);
pal_ptr+=2;
}
}
int len_working_ext_pal;
unsigned short working_ext_pal[240];
void Call_InformScreens ()
{
unsigned long Params;
Params = GetReg (REG_A7);
Params -= SIZE_WORD;
physcreen2 = STMemory_ReadLong (Params+SIZE_WORD);
logscreen2 = STMemory_ReadLong (Params+SIZE_WORD+SIZE_LONG);
physcreen = STMemory_ReadLong (Params+SIZE_WORD+2*SIZE_LONG);
logscreen = STMemory_ReadLong (Params+SIZE_WORD+3*SIZE_LONG);
}
/* also copies the extended palette into main palette */
void Call_SetScreenBase ()
{
int i;
unsigned long Params;
Params = GetReg (REG_A7);
Params -= SIZE_WORD;
VideoBase = STMemory_ReadLong (Params+SIZE_WORD);
VideoRaster = STRam + VideoBase;
for (i=0; i<len_working_ext_pal; i++) {
MainPalette[16+i] = working_ext_pal[i];
}
len_main_palette = 16 + len_working_ext_pal;
}
void Call_MakeExtPalette ()
{
int col_list, len, col_idx, col_val, i;
unsigned long Params;
Params = GetReg (REG_A7);
Params -= SIZE_WORD;
col_list = STMemory_ReadLong (Params+SIZE_WORD);
len = STMemory_ReadWord (col_list) >> 2;
len_working_ext_pal = len;
col_list+=2;
//printf ("%d colours.\n", len+2);
for (i=0; i<len; i++) {
col_val = STMemory_ReadWord (col_list);
working_ext_pal[i] = col_val;
col_list += 2;
col_idx = STMemory_ReadWord (col_list);
/* offset dynamic colours into extended palette
* range (colours 16+) */
col_idx += 16<<2;
STMemory_WriteWord (col_list, col_idx);
col_list += 2;
}
}
void Call_DumpRegs ()
{
int i;
printf ("D: ");
for (i=0; i<8; i++) {
printf ("$%x ", GetReg (i));
} printf ("\n");
printf ("A: ");
for (i=0; i<8; i++) {
printf ("$%x ", GetReg (i+8));
} printf ("\n");
}
void Call_DumpDebug ()
{
int i, j;
printf ("Debug info. PC @ 68k line %d.\n", line_no);
Call_DumpRegs ();
printf ("Stack:");
j = GetReg (15);
for (i=0; i<8; i++) {
j+=4;
printf (" $%x", STMemory_ReadLong (j));
}
putchar ('\n');
}
/* mouse pos in d3,d4 */
void Call_NotifyMousePos ()
{
#if 0
int x, y;
x = GetReg (REG_D3) & 0xffff;
y = GetReg (REG_D4) & 0xffff;
x *= ScreenDraw.MouseScale;
y *= ScreenDraw.MouseScale;
SDL_EventState (SDL_MOUSEMOTION, SDL_DISABLE);
SDL_WarpMouse (x, y);
SDL_EventState (SDL_MOUSEMOTION, SDL_ENABLE);
SDL_ShowCursor (SDL_ENABLE);
#endif /* 0 */
}
static void Call_Idle ()
{
SDL_Delay (0);
}
void Call_HostUpdate ()
{
/* Clear any key presses which are due to be de-bounced (held for one ST frame) */
Keymap_DebounceAllKeys();
/* Check 'Function' keys, so if press F12 we update screen correctly to Window! */
ShortCut_CheckKeys();
/* And handle any messages, check for quit message */
Main_EventHandler(); /* Process messages, set 'bQuitProgram' if user tries to quit */
/* Pass NULL interrupt function to quit cleanly */
//if (bQuitProgram) Int_AddAbsoluteInterrupt(4, 0L);
}
/* d0.b = exception number, a0 = handler. */
static void SetExceptionHandler ()
{
/* only 32 handlers */
exception_handlers[GetReg(0) & 31] = GetReg (8);
}
int DumpMess (int pos, int line)
{
if (GetXFlag ()) putchar ('X');
if (GetZFlag ()) putchar ('Z');
if (GetNFlag ()) putchar ('N');
if (GetVFlag ()) putchar ('V');
if (GetCFlag ()) putchar ('C');
return 0;
printf (" $%x $%x $%x $%x $%x $%x $%x $%x*$%x $%x $%x $%x $%x $%x $%x $%x:%d\n",
GetReg (0),
GetReg (1),
GetReg (2),
GetReg (3),
GetReg (4),
GetReg (5),
GetReg (6),
GetReg (7),
GetReg (8),
GetReg (9),
GetReg (10),
GetReg (11),
GetReg (12),
GetReg (13),
GetReg (14),
GetReg (15),line_no);
}
static int _X, _Z, _N, _V, _C;
static int PrevRegs[16];
int changed ()
{
int i;
if (GetXFlag () != _X) return 1;
if (GetZFlag () != _Z) return 1;
if (GetNFlag () != _N) return 1;
if (GetVFlag () != _V) return 1;
if (GetCFlag () != _C) return 1;
for (i=0; i<16; i++) {
if (PrevRegs[i] != GetReg (i)) return 1;
}
return 0;
}
void DumpRegsChanged ()
{
int i;
//if (!changed ()) return;
_X = GetXFlag ();
_Z = GetZFlag ();
_V = GetVFlag ();
_N = GetNFlag ();
_C = GetCFlag ();
if (_X) putchar ('X');
if (_Z) putchar ('Z');
if (_N) putchar ('N');
if (_V) putchar ('V');
if (_C) putchar ('C');
for (i=0; i<16; i++) {
if (PrevRegs[i] != GetReg (i)) {
printf (" %c%d:%x->%x", (i<8?'d':'a'), (i<8?i:i-8), PrevRegs[i], GetReg (i));
PrevRegs[i] = GetReg (i);
}
}
printf (" @%d\n", line_no);
}
static void Call_Fdelete ()
{
int p, i;
char filename[64];
p = GetReg (REG_D1);
for (i=0; ; i++) {
filename[i] = STMemory_ReadByte (p++);
if (!filename[i]) break;
}
SetReg (REG_D0, remove (filename));
}
static void Call_Fwrite ()
{
int p, i;
int pBuf = GetReg (REG_A4);
int len = GetReg (REG_D7);
char filename[64];
FILE *f;
p = GetReg (REG_D1);
for (i=0; ; i++) {
filename[i] = STMemory_ReadByte (p++);
if (!filename[i]) break;
}
if (!(f = fopen (filename, "wb"))) {
SetReg (REG_D0, 0);
} else {
SetReg (REG_D0, fwrite (STRam+pBuf, 1, len, f));
fclose (f);
}
}
static void Call_Fread ()
{
int p, i;
int pBuf = GetReg (REG_A4);
int len = GetReg (REG_D7);
char filename[64];
FILE *f;
p = GetReg (REG_D1);
for (i=0; ; i++) {
filename[i] = STMemory_ReadByte (p++);
if (!filename[i]) break;
}
if (!(f = fopen (filename, "rb"))) {
SetReg (REG_D0, 0);
} else {
SetReg (REG_D0, fread (STRam+pBuf, 1, len, f));
fclose (f);
}
}
#include <dirent.h>
static DIR *poodir;
static char cur_dir[1024];
static void Call_Fopendir ()
{
int p, i;
char name[64];
p = GetReg (REG_A2);
for (i=0; ; i++) {
name[i] = STMemory_ReadByte (p++);
if (!name[i]) break;
}
strncpy (cur_dir, name, 1024);
poodir = opendir (name);
if (poodir) {
struct dirent *dent;
/* skip '.' and '..' */
dent = readdir (poodir);
dent = readdir (poodir);
SetReg (REG_D0, 0);
} else {
SetReg (REG_D0, -1);
}
}
static void Call_Fclosedir ()
{
closedir (poodir);
}
/* make sure fe2.s is allocating enough space at a0... */
#define MAX_FILENAME_LEN 14
static void Call_Freaddir ()
{
int p, i, attribs, len;
char name[MAX_FILENAME_LEN];
/* filename into buffer (a0), attributes d2, len d1 */
char full_path_shit[1024];
struct stat _stat;
struct dirent *dent = readdir (poodir);
if (dent == NULL) {
SetReg (REG_D0, -1);
return;
}
strncpy (name, dent->d_name, MAX_FILENAME_LEN);
name[MAX_FILENAME_LEN-1] = '\0';
strncpy (full_path_shit, cur_dir, 1024);
strncat (full_path_shit, "/", 1024);
strncat (full_path_shit, dent->d_name, 1024);
stat (full_path_shit, &_stat);
len = _stat.st_size;
attribs = (S_ISDIR (_stat.st_mode) ? 0x10 : 0);
p = GetReg (REG_A0);
for (i=0; i<MAX_FILENAME_LEN; i++) {
STMemory_WriteByte (p++, name[i]);
}
SetReg (REG_D2, attribs);
SetReg (REG_D1, len);
SetReg (REG_D0, 0);
}
HOSTCALL hcalls [] = {
&SetExceptionHandler,
&Call_Memset, /* 0x1 */
&Call_MemsetBlue, /* 0x2 */
&Call_BlitCursor, /* 0x3 */
&Call_RestoreUnderCursor, /* 0x4 */
&Call_BlitBmp, /* 0x5 */
&Call_OldHLine, /* 0x6 */
&Call_HostUpdate, /* 0x7 */
&Call_Memcpy, /* 0x8 */
&Call_PutPix, /* 0x9 */
&Call_BackHLine, /* 0xa */
&Call_FillLine, /* 0xb */
&Call_SetMainPalette, /* 0xc */
&Call_SetCtrlPalette, /* 0xd */
&Call_SetScreenBase, /* 0xe */
NULL, /* 0xf */
&Call_DumpRegs, /* 0x10 */
&Call_MakeExtPalette, /* 0x11 */
&Call_PlaySFX, /* 0x12 */
&Call_GetMouseInput, /* 0x13 */
&Call_GetKeyboardEvent, /* 0x14 */
NULL, /* 0x15 */
&Call_HLine, /* 0x16 */
NULL, /* 0x17 */
&Call_NotifyMousePos, /* 0x18 */
&Call_InformScreens, /* 0x19 */
NULL,
&Call_DrawStrShadowed, /* 0x1b */
&Call_DrawStr, /* 0x1c */
&Call_PlayMusic, /* 0x1d */
&Call_StopMusic, /* 0x1e */
&Call_Idle, /* 0x1f */
&Call_DumpDebug, /* 0x20 */
&Call_IsMusicPlaying,
&Call_Fread, /* 0x22 */
&Call_Fwrite,
&Call_Fdelete,
&Call_Fopendir, /* 0x25 */
&Call_Freaddir,
&Call_Fclosedir,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL, /* 0x30 */
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL, /* 0x40 */
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL, /* 0x50 */
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
Nu_PutTriangle, /* 0x60 */
Nu_PutQuad,
Nu_PutLine,
Nu_PutPoint,
Nu_PutTwinklyCircle,
Nu_PutColoredPoint,
Nu_PutBezierLine,
Nu_ComplexStart,
Nu_ComplexSNext,
Nu_ComplexSBegin,
Nu_ComplexEnd,
Nu_3DViewInit,
Nu_InsertZNode,
Nu_ComplexStartInner,
Nu_ComplexBezier,
Nu_DrawScreen,
Nu_PutTeardrop,
Nu_PutCircle,
Nu_PutOval,
Nu_IsGLRenderer,
Nu_GLClearArea,
Nu_QueueDrawStr,
Nu_PutCylinder,
Nu_PutBlob,
Nu_PutPlanet,
Nu_Put2DLine
};
| 21.765957 | 129 | 0.634269 | [
"object"
] |
b39382b17a6a5a6af7477116987b7e1b9b4a40f6 | 926 | h | C | include/libcryptosec/asn1/Asn1Type.h | LabSEC/libcryptosec | e53030ec32b52b6abeaa973a9f0bfba0eb2c2440 | [
"BSD-3-Clause"
] | 22 | 2015-08-26T16:40:59.000Z | 2022-02-22T19:52:55.000Z | include/libcryptosec/asn1/Asn1Type.h | LabSEC/Libcryptosec | e53030ec32b52b6abeaa973a9f0bfba0eb2c2440 | [
"BSD-3-Clause"
] | 14 | 2015-09-01T00:39:22.000Z | 2018-12-17T16:24:28.000Z | include/libcryptosec/asn1/Asn1Type.h | LabSEC/Libcryptosec | e53030ec32b52b6abeaa973a9f0bfba0eb2c2440 | [
"BSD-3-Clause"
] | 22 | 2015-08-31T19:17:37.000Z | 2021-01-04T13:38:35.000Z | #ifndef ASN1TYPE_H_
#define ASN1TYPE_H_
#include <libcryptosec/ByteArray.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/ossl_typ.h>
#include <openssl/objects.h>
class Asn1Type
{
public:
enum Type
{
BOOLEAN,
//STRING, //parece que ASN1_STRING é um tipo generico especializado por OCTET_STRING, UTF8STRING, etc
OBJECT,
INTEGER,
ENUMERATED,
BIT_STRING,
OCTET_STRING,
PRINTABLESTRING,
T61STRING,
IA5STRING,
GENERALSTRING,
BMPSTRING,
UNIVERSALSTRING,
UTCTIME,
GENERALIZEDTIME,
VISIBLESTRING,
UTF8STRING,
SEQUENCE,
SET,
};
virtual ~Asn1Type();
Type getType() const throw();
//nao faz copia
const ASN1_TYPE* getAsn1Type() const throw();
bool operator==(Asn1Type const& c) const throw();
bool operator!=(Asn1Type const& c) const throw();
protected:
Asn1Type();
Asn1Type(ASN1_TYPE* asn1Type);
ASN1_TYPE* asn1Type;
};
#endif /*ASN1TYPE_H_*/
| 16.836364 | 104 | 0.715983 | [
"object"
] |
b3a854179c4f1d395fb9ea1fba3a7faeb67be011 | 1,025 | h | C | IMSForm/Classes/Views/IMSFormImageCell.h | JinfeiChen/IMSForm | df07400a854fec8bd0d3bb592beb86d3802544f0 | [
"MIT"
] | null | null | null | IMSForm/Classes/Views/IMSFormImageCell.h | JinfeiChen/IMSForm | df07400a854fec8bd0d3bb592beb86d3802544f0 | [
"MIT"
] | null | null | null | IMSForm/Classes/Views/IMSFormImageCell.h | JinfeiChen/IMSForm | df07400a854fec8bd0d3bb592beb86d3802544f0 | [
"MIT"
] | null | null | null | //
// IMSFormImageCell.h
// IMSForm
//
// Created by cjf on 7/1/2021.
//
#import <IMSForm/IMSFormTableViewCell.h>
#import <AVFoundation/AVFoundation.h>
#import <IMSForm/IMSFormImageModel.h>
NS_ASSUME_NONNULL_BEGIN
@interface CJFFormImageItemCell : UICollectionViewCell
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UIImageView *videoImageView;
@property (nonatomic, strong) UIButton *deleteBtn;
@property (nonatomic, strong) UILabel *gifLable;
@property (nonatomic, assign) NSInteger row;
@property (nonatomic, strong) id asset;
- (UIView *)snapshotView;
@property (nonatomic, strong) NSURL * _Nullable videoURL;
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerLayer *playerLayer;
@end
@interface IMSFormImageCell : IMSFormTableViewCell
@property (strong, nonatomic) IMSFormImageModel *model; /**< <#property#> */
/**
数据模型的参数说明
@@param value 图片地址列表,e.g. ["http://www.baidu.com/pic/01/01/12313.png"]
*/
@end
NS_ASSUME_NONNULL_END
| 23.295455 | 76 | 0.756098 | [
"model"
] |
b3b87d9902a1d9715f5f39e679ca5ebdde1ef573 | 2,556 | h | C | Includes/Core/Geometry/Cylinder3.h | utilForever/CubbyFlow-v1 | d85c136d8eaa91ecce456c3356c7e578dda5d5bd | [
"MIT"
] | 3 | 2020-04-15T13:41:16.000Z | 2020-12-29T11:23:59.000Z | Includes/Core/Geometry/Cylinder3.h | utilForever/CubbyFlow-v1 | d85c136d8eaa91ecce456c3356c7e578dda5d5bd | [
"MIT"
] | null | null | null | Includes/Core/Geometry/Cylinder3.h | utilForever/CubbyFlow-v1 | d85c136d8eaa91ecce456c3356c7e578dda5d5bd | [
"MIT"
] | null | null | null | /*************************************************************************
> File Name: Cylinder3.h
> Project Name: CubbyFlow
> Author: Chan-Ho Chris Ohk
> Purpose: 3-D cylinder geometry.
> Created Time: 2017/06/24
> Copyright (c) 2018, Chan-Ho Chris Ohk
*************************************************************************/
#ifndef CUBBYFLOW_CYLINDER3_H
#define CUBBYFLOW_CYLINDER3_H
#include <Core/Surface/Surface3.h>
namespace CubbyFlow
{
//!
//! \brief 3-D cylinder geometry.
//!
//! This class represents 3-D cylinder geometry which extends Surface3 by
//! overriding surface-related queries. The cylinder is aligned with the y-axis.
//!
class Cylinder3 final : public Surface3
{
public:
class Builder;
//! Center of the cylinder.
Vector3D center;
//! Radius of the cylinder.
double radius = 1.0;
//! Height of the cylinder.
double height = 1.0;
//! Constructs a cylinder with
Cylinder3(const Transform3& transform = Transform3(), bool isNormalFlipped = false);
//! Constructs a cylinder with \p center, \p radius, and \p height.
Cylinder3(const Vector3D& center, double radius, double height,
const Transform3& transform = Transform3(), bool isNormalFlipped = false);
//! Copy constructor.
Cylinder3(const Cylinder3& other);
//! Returns builder fox Cylinder3.
static Builder GetBuilder();
protected:
// Surface3 implementations
Vector3D ClosestPointLocal(const Vector3D& otherPoint) const override;
double ClosestDistanceLocal(const Vector3D& otherPoint) const override;
bool IntersectsLocal(const Ray3D& ray) const override;
BoundingBox3D BoundingBoxLocal() const override;
Vector3D ClosestNormalLocal(const Vector3D& otherPoint) const override;
SurfaceRayIntersection3 ClosestIntersectionLocal(const Ray3D& ray) const override;
};
//! Shared pointer type for the Cylinder3.
using Cylinder3Ptr = std::shared_ptr<Cylinder3>;
//!
//! \brief Front-end to create Cylinder3 objects step by step.
//!
class Cylinder3::Builder final : public SurfaceBuilderBase3<Cylinder3::Builder>
{
public:
//! Returns builder with center.
Builder& WithCenter(const Vector3D& center);
//! Returns builder with radius.
Builder& WithRadius(double radius);
//! Returns builder with height.
Builder& WithHeight(double height);
//! Builds Cylinder3.
Cylinder3 Build() const;
//! Builds shared pointer of Cylinder3 instance.
Cylinder3Ptr MakeShared() const;
private:
Vector3D m_center{ 0, 0, 0 };
double m_radius = 1.0;
double m_height = 1.0;
};
}
#endif | 26.625 | 86 | 0.688185 | [
"geometry",
"transform"
] |
b3c9875282d1ae902658be699ede11bc06085a67 | 2,864 | h | C | WhirlyGlobeSrc/WhirlyGlobe-MaplyComponent/include/MaplyQuadPagingLayer.h | yuanshankongmeng/WhirlyGlobe | 22f44318b74ca3f8b1781dcb81ae28d1697f1bcc | [
"Apache-2.0"
] | 1 | 2015-03-17T01:48:43.000Z | 2015-03-17T01:48:43.000Z | WhirlyGlobeSrc/WhirlyGlobe-MaplyComponent/include/MaplyQuadPagingLayer.h | yuanshankongmeng/WhirlyGlobe | 22f44318b74ca3f8b1781dcb81ae28d1697f1bcc | [
"Apache-2.0"
] | null | null | null | WhirlyGlobeSrc/WhirlyGlobe-MaplyComponent/include/MaplyQuadPagingLayer.h | yuanshankongmeng/WhirlyGlobe | 22f44318b74ca3f8b1781dcb81ae28d1697f1bcc | [
"Apache-2.0"
] | null | null | null | /*
* MaplyQuadPagingLayer.h
* WhirlyGlobe-MaplyComponent
*
* Created by Steve Gifford on 5/20/13.
* Copyright 2011-2013 mousebird consulting
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#import "MaplyComponentObject.h"
#import "MaplyViewControllerLayer.h"
#import "MaplyCoordinateSystem.h"
#import "MaplyTileSource.h"
#import "MaplyBaseViewController.h"
@class MaplyQuadPagingLayer;
/** The protocol for the Maply Paging Delegate. Fill this in to
provide per tile data for features that you're loading.
*/
@protocol MaplyPagingDelegate
/// Minimum zoom level (e.g. 0)
- (int)minZoom;
/// Maximum zoom level (e.g. 17)
- (int)maxZoom;
/** Start fetching data for the given tile. This will not be called on the
main thread so be prepared for that. You should immediatley to an
async call to your own loading logic and then merge in your results.
If you do your loading calls in line you'll slow down the loading thread.
After you're done you MUST call tileDidLoad in the layer.
*/
- (void)startFetchForTile:(MaplyTileID)tileID forLayer:(MaplyQuadPagingLayer *)layer;
@end
/** This is a generic quad earth paging interface. Hand it your coordinate system,
bounds, and tile source object and it will page tiles for you.
*/
@interface MaplyQuadPagingLayer : MaplyViewControllerLayer
/// Change the number of fetches allowed at once
@property (nonatomic,assign) int numSimultaneousFetches;
/// The view controller this is part of
@property (nonatomic,readonly) MaplyBaseViewController *viewC;
/// Construct with the coordinate system (which contains bounds) and the tile source
- (id)initWithCoordSystem:(MaplyCoordinateSystem *)coordSys delegate:(NSObject<MaplyPagingDelegate> *)tileSource;
/// Add data for the given tileID. These should be one or more MaplyComponentObject.
/// Please create them disabled so we enable & disable them as needed.
- (void)addData:(NSArray *)dataObjects forTile:(MaplyTileID)tileID;
/// Let the pager know the tile completely failed to load
- (void)tileFailedToLoad:(MaplyTileID)tileID;
/// Let the paging know the tile is completely loaded
- (void)tileDidLoad:(MaplyTileID)tileID;
/// Utility routine to calculate a bounding box given a particular tile
- (void)geoBoundsforTile:(MaplyTileID)tileID ll:(MaplyCoordinate *)ll ur:(MaplyCoordinate *)ur ;
@end
| 36.717949 | 113 | 0.756285 | [
"object"
] |
278bd3b0d1662a8c028a93f2ce477d3fb3d0717b | 2,376 | h | C | handlers/cef_base.h | myvker/golanggui | 4eb412b27f3fecaab0f07aa906d2d70360cb1203 | [
"MIT"
] | 3 | 2018-07-17T16:57:42.000Z | 2020-08-11T14:06:02.000Z | handlers/cef_base.h | myvker/golanggui | 4eb412b27f3fecaab0f07aa906d2d70360cb1203 | [
"MIT"
] | null | null | null | handlers/cef_base.h | myvker/golanggui | 4eb412b27f3fecaab0f07aa906d2d70360cb1203 | [
"MIT"
] | 3 | 2018-04-20T17:45:39.000Z | 2021-10-20T19:48:00.000Z | // Copyright (c) 2014 The cefcapi authors. All rights reserved.
// License: BSD 3-clause.
// Website: https://github.com/CzarekTomczak/cefcapi
#pragma once
#include "include/capi/cef_base_capi.h"
#include <stdio.h>
// Set to 1 to check if add_ref() and release()
// are called and to track the total number of calls.
// add_ref will be printed as "+", release as "-".
#define DEBUG_REFERENCE_COUNTING 0
// Print only the first execution of the callback,
// ignore the subsequent.
#define DEBUG_CALLBACK(x) { static int first_call = 1; if (first_call == 1) { first_call = 0; printf(x); } }
// ----------------------------------------------------------------------------
// cef_base_t
// ----------------------------------------------------------------------------
///
// Structure defining the reference count implementation functions. All
// framework structures must include the cef_base_t structure first.
///
///
// Increment the reference count.
///
int CEF_CALLBACK add_ref(cef_base_t* self) {
DEBUG_CALLBACK("cef_base_t.add_ref\n");
if (DEBUG_REFERENCE_COUNTING)
printf("+");
return 1;
}
///
// Decrement the reference count. Delete this object when no references
// remain.
///
int CEF_CALLBACK release(cef_base_t* self) {
DEBUG_CALLBACK("cef_base_t.release\n");
if (DEBUG_REFERENCE_COUNTING)
printf("-");
return 1;
}
///
// Returns the current number of references.
///
int CEF_CALLBACK get_refct(cef_base_t* self) {
DEBUG_CALLBACK("cef_base_t.get_refct\n");
if (DEBUG_REFERENCE_COUNTING)
printf("=");
return 1;
}
int CEF_CALLBACK has_one_ref(cef_base_t* self) {
DEBUG_CALLBACK("cef_base_t.has_one_ref\n");
if (DEBUG_REFERENCE_COUNTING)
printf("=");
return 1;
}
void initialize_cef_base(cef_base_t* base) {
printf("initialize_cef_base\n");
// Check if "size" member was set.
size_t size = base->size;
// Let's print the size in case sizeof was used
// on a pointer instead of a structure. In such
// case the number will be very high.
printf("cef_base_t.size = %lu\n", (unsigned long)size);
if (size <= 0) {
printf("FATAL: initialize_cef_base failed, size member not set\n");
_exit(1);
}
//base->add_ref = add_ref;
//base->release = release;
//base->get_refct = get_refct;
//base->has_one_ref=has_one_ref;
}
| 28.626506 | 108 | 0.634259 | [
"object"
] |
27a12372ee38b6bddd672e0179344835f3833e78 | 2,573 | h | C | GPRO-Graphics1/include/gpro/sphere.h | doctorquackerzzz/GPR-200 | 448fbeb15953e609776d89d388e7a579fb43ee10 | [
"Apache-2.0"
] | null | null | null | GPRO-Graphics1/include/gpro/sphere.h | doctorquackerzzz/GPR-200 | 448fbeb15953e609776d89d388e7a579fb43ee10 | [
"Apache-2.0"
] | null | null | null | GPRO-Graphics1/include/gpro/sphere.h | doctorquackerzzz/GPR-200 | 448fbeb15953e609776d89d388e7a579fb43ee10 | [
"Apache-2.0"
] | null | null | null | #ifndef SPHERE_H
#define SPHERE_H
/*
include-sphere.h
sphere class and bool function initialization
Modified by: Nico Omenetto
Modified because: to manipulate and to functionalize the sphere.h file into the program
*/
/*
Contains Code from the following source:
Chapter 6.3
Ray Tracing in One Weekend. https://raytracing.github.io/books/RayTracingInOneWeekend.html#surfacenormalsandmultipleobjects/anabstractionforhittableobjects
Peter Shirley
Accessed 9 09. 2020.
*/
#include "hittable.h"
#include "gpro/gpro-math/gproVector.h"
//Intent: creation of the sphere class
//Reason: to create a sphere class to display in the ppm file
class sphere : public hittable {
public:
sphere() {}
sphere(point3 cen, float r) : center(cen), radius(r) {};
//boolean function of hit
virtual bool hit(
const ray& r, float tmin, float tmax, hit_record& rec) const override;
//public variables
point3 center;
float radius = 30.0f; // initialized radius
};
//intent: to determine whether or not the sphere has been hit
//reason: to provide a sense as to what the equations are to calculate whther the sphere was hit
bool sphere::hit(const ray& r, float t_min, float t_max, hit_record& rec) const {
point3 oc = r.origin() - center; //ray point of origin minus center = oc
float a = r.direction().length_squared(); //vector of direction length squared
float half_b = dot(oc, r.direction()); // dot product of oc and the direction of ray
float c = oc.length_squared() - radius * radius; // length squared of oc vector - radius times radius
float discriminant = half_b * half_b - a * c; // half of b * half of b - a times c
//if statement to determine whether the sphere was hit or not
if (discriminant > 0) {
float root = sqrt(discriminant);
float temp = (-half_b - root) / a;
if (temp < t_max && temp > t_min) { //if temporary value was less than max and greater than min for -halfb - root/a
rec.t = temp;
rec.p = r.at(rec.t);
vec3 outward_normal = (rec.p - center) / radius;
rec.set_face_normal(r, outward_normal);
return true;
}
temp = (-half_b + root) / a;
if (temp < t_max && temp > t_min) { //if temporary value is less than max or greater than min
rec.t = temp;
rec.p = r.at(rec.t);
vec3 outward_normal = (rec.p - center) / radius;
rec.set_face_normal(r, outward_normal);
return true;
}
}
return false;
}
#endif | 34.77027 | 155 | 0.655266 | [
"vector"
] |
27a2b4f0c31d50ecc0dcf54c016bae4983b5b4cc | 685 | h | C | ATK/Delay/HadamardMixture.h | AudioTK/AudioTK | dba42eea68534501efe74692b74edf4792cca231 | [
"BSD-3-Clause"
] | 23 | 2021-02-04T10:47:46.000Z | 2022-03-25T03:45:00.000Z | ATK/Delay/HadamardMixture.h | AudioTK/AudioTK | dba42eea68534501efe74692b74edf4792cca231 | [
"BSD-3-Clause"
] | 2 | 2021-02-01T15:45:06.000Z | 2021-09-13T19:39:05.000Z | ATK/Delay/HadamardMixture.h | AudioTK/AudioTK | dba42eea68534501efe74692b74edf4792cca231 | [
"BSD-3-Clause"
] | 2 | 2021-04-12T03:28:12.000Z | 2021-12-17T00:47:11.000Z | /**
* \file HadamardFeedbackDelayNetworkFilter.h
*/
#ifndef ATK_DELAY_HADAMARDFEEDBACKDELAYNETWORKFILTER_H
#define ATK_DELAY_HADAMARDFEEDBACKDELAYNETWORKFILTER_H
#include <ATK/Core/TypedBaseFilter.h>
#include <ATK/Delay/config.h>
#include <array>
#include <vector>
namespace ATK
{
/// Mixture matrix for Hadamard
template<typename DataType_, unsigned int order>
class HadamardMixture
{
public:
static constexpr gsl::index nb_channels = 1 << order;
using DataType = DataType_;
/// Gain factor to take into account in the feedback loop due to the instability of the mixture
static constexpr float gain_factor = 1.F;
class MixtureImpl;
};
}
#endif
| 22.096774 | 99 | 0.750365 | [
"vector"
] |
27b36796bf4bee4e5e026dcbcbbfcebe9ee456c4 | 765 | h | C | progress.h | bottle2515/snakec | d58400b19dd0d2d56a34c5eb6349c2b664bf9dc1 | [
"MIT"
] | null | null | null | progress.h | bottle2515/snakec | d58400b19dd0d2d56a34c5eb6349c2b664bf9dc1 | [
"MIT"
] | null | null | null | progress.h | bottle2515/snakec | d58400b19dd0d2d56a34c5eb6349c2b664bf9dc1 | [
"MIT"
] | null | null | null | /* Thinkings:
* 1. How to make the timer?
* (1) refresh the screen per 0.5s - DONE
* (2) use permanent fps timer and specifies the speed of snake -DOING
* 2. Data Structure of snake
* (1) Realize it by my own -DONE
* (2) Use Vector<> -TODO
* 3. Snake judgement for touching its body by itself.
*
* BUGS:
* (1) When the snake is near the border (1 blcok), sometimes if you turn left or right (on snake's viewpoint)
* the snake's head or its body will disappear one block. -DONE
* (2) If one press the other two arrow keys except snake's direction and the opposite arrow key (up <-> down)
* and switch to the opposite key to the snake's direction quickly, the snake will be able to move to worng way.
*/ | 51 | 121 | 0.654902 | [
"vector"
] |
27b36ddd0cd5228cb95b6252048ee0279a54ebac | 1,751 | h | C | processor/src/Z3ModelEvalAction.h | mballance-sf/open-ps | a5ed44ce30bfe59462801ca7de4361d16950bcd2 | [
"Apache-2.0"
] | null | null | null | processor/src/Z3ModelEvalAction.h | mballance-sf/open-ps | a5ed44ce30bfe59462801ca7de4361d16950bcd2 | [
"Apache-2.0"
] | null | null | null | processor/src/Z3ModelEvalAction.h | mballance-sf/open-ps | a5ed44ce30bfe59462801ca7de4361d16950bcd2 | [
"Apache-2.0"
] | null | null | null | /*
* Z3ModelEvalAction.h
*
* 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.
*
* Created on: May 20, 2018
* Author: ballance
*/
#pragma once
#include "IAction.h"
#include "ModelVisitor.h"
#include <string>
class Z3ModelEvaluator;
class Z3ModelVar;
class Z3ModelEvalAction : public virtual ModelVisitor {
public:
Z3ModelEvalAction(Z3ModelEvaluator *evaluator);
virtual ~Z3ModelEvalAction();
void eval_action(IAction *action);
protected:
virtual void visit_activity_if_else_stmt(IActivityIfElseStmt *stmt) override;
virtual void visit_activity_parallel_block_stmt(IActivityBlockStmt *block) override;
virtual void visit_activity_repeat_stmt(IActivityRepeatStmt *repeat) override;
virtual void visit_activity_schedule_block_stmt(IActivityBlockStmt *s) override;
virtual void visit_activity_select_stmt(IActivitySelectStmt *s) override;
virtual void visit_activity_traverse_stmt(IActivityTraverseStmt *t) override;
virtual void visit_activity_do_action_stmt(IActivityDoActionStmt *stmt) override;
private:
void init_variables(
IAction *action);
void collect_rand_variables(
std::vector<Z3ModelVar *> &vars,
IAction *action);
private:
Z3ModelEvaluator *m_evaluator;
};
| 25.014286 | 85 | 0.767561 | [
"vector"
] |
27c3d64f7274c13701cd6f2fd1664b9fbf942ff3 | 4,770 | h | C | tiems/include/tencentcloud/tiems/v20190416/model/ExposeServiceRequest.h | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | tiems/include/tencentcloud/tiems/v20190416/model/ExposeServiceRequest.h | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | tiems/include/tencentcloud/tiems/v20190416/model/ExposeServiceRequest.h | li5ch/tencentcloud-sdk-cpp | 12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4 | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 TENCENTCLOUD_TIEMS_V20190416_MODEL_EXPOSESERVICEREQUEST_H_
#define TENCENTCLOUD_TIEMS_V20190416_MODEL_EXPOSESERVICEREQUEST_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Tiems
{
namespace V20190416
{
namespace Model
{
/**
* ExposeService请求参数结构体
*/
class ExposeServiceRequest : public AbstractModel
{
public:
ExposeServiceRequest();
~ExposeServiceRequest() = default;
std::string ToJsonString() const;
/**
* 获取服务Id
* @return ServiceId 服务Id
*/
std::string GetServiceId() const;
/**
* 设置服务Id
* @param ServiceId 服务Id
*/
void SetServiceId(const std::string& _serviceId);
/**
* 判断参数 ServiceId 是否已赋值
* @return ServiceId 是否已赋值
*/
bool ServiceIdHasBeenSet() const;
/**
* 获取暴露方式,支持 EXTERNAL(外网暴露),VPC (VPC内网打通)
* @return ExposeType 暴露方式,支持 EXTERNAL(外网暴露),VPC (VPC内网打通)
*/
std::string GetExposeType() const;
/**
* 设置暴露方式,支持 EXTERNAL(外网暴露),VPC (VPC内网打通)
* @param ExposeType 暴露方式,支持 EXTERNAL(外网暴露),VPC (VPC内网打通)
*/
void SetExposeType(const std::string& _exposeType);
/**
* 判断参数 ExposeType 是否已赋值
* @return ExposeType 是否已赋值
*/
bool ExposeTypeHasBeenSet() const;
/**
* 获取暴露方式为 VPC 时,填写需要打通的私有网络Id
* @return VpcId 暴露方式为 VPC 时,填写需要打通的私有网络Id
*/
std::string GetVpcId() const;
/**
* 设置暴露方式为 VPC 时,填写需要打通的私有网络Id
* @param VpcId 暴露方式为 VPC 时,填写需要打通的私有网络Id
*/
void SetVpcId(const std::string& _vpcId);
/**
* 判断参数 VpcId 是否已赋值
* @return VpcId 是否已赋值
*/
bool VpcIdHasBeenSet() const;
/**
* 获取暴露方式为 VPC 时,填写需要打通的子网Id
* @return SubnetId 暴露方式为 VPC 时,填写需要打通的子网Id
*/
std::string GetSubnetId() const;
/**
* 设置暴露方式为 VPC 时,填写需要打通的子网Id
* @param SubnetId 暴露方式为 VPC 时,填写需要打通的子网Id
*/
void SetSubnetId(const std::string& _subnetId);
/**
* 判断参数 SubnetId 是否已赋值
* @return SubnetId 是否已赋值
*/
bool SubnetIdHasBeenSet() const;
private:
/**
* 服务Id
*/
std::string m_serviceId;
bool m_serviceIdHasBeenSet;
/**
* 暴露方式,支持 EXTERNAL(外网暴露),VPC (VPC内网打通)
*/
std::string m_exposeType;
bool m_exposeTypeHasBeenSet;
/**
* 暴露方式为 VPC 时,填写需要打通的私有网络Id
*/
std::string m_vpcId;
bool m_vpcIdHasBeenSet;
/**
* 暴露方式为 VPC 时,填写需要打通的子网Id
*/
std::string m_subnetId;
bool m_subnetIdHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_TIEMS_V20190416_MODEL_EXPOSESERVICEREQUEST_H_
| 31.8 | 83 | 0.446541 | [
"vector",
"model"
] |
27e4e1a1f2b3c3b4565df8ffccc2363deaf136a7 | 8,843 | h | C | src/gui/layertree/qgslayertreeview.h | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | null | null | null | src/gui/layertree/qgslayertreeview.h | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | null | null | null | src/gui/layertree/qgslayertreeview.h | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | 1 | 2021-12-25T08:40:30.000Z | 2021-12-25T08:40:30.000Z | /***************************************************************************
qgslayertreeview.h
--------------------------------------
Date : May 2014
Copyright : (C) 2014 by Martin Dobias
Email : wonder dot sk at gmail dot com
***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#ifndef QGSLAYERTREEVIEW_H
#define QGSLAYERTREEVIEW_H
#include <QTreeView>
#include "qgis.h"
#include "qgis_gui.h"
class QgsLayerTreeGroup;
class QgsLayerTreeLayer;
class QgsLayerTreeModel;
class QgsLayerTreeNode;
class QgsLayerTreeModelLegendNode;
class QgsLayerTreeViewDefaultActions;
class QgsLayerTreeViewIndicator;
class QgsLayerTreeViewMenuProvider;
class QgsMapLayer;
/**
* \ingroup gui
* The QgsLayerTreeView class extends QTreeView and provides some additional functionality
* when working with a layer tree.
*
* The view updates expanded state of layer tree nodes and also listens to changes
* to expanded states in the layer tree.
*
* The view keeps track of the current layer and emits a signal when the current layer has changed.
*
* Allows the client to specify a context menu provider with custom actions. Also it comes
* with a set of default actions that can be used when building context menu.
*
* \see QgsLayerTreeModel
* \since QGIS 2.4
*/
class GUI_EXPORT QgsLayerTreeView : public QTreeView
{
#ifdef SIP_RUN
SIP_CONVERT_TO_SUBCLASS_CODE
if ( sipCpp->inherits( "QgsLayerTreeView" ) )
sipType = sipType_QgsLayerTreeView;
else
sipType = 0;
SIP_END
#endif
Q_OBJECT
public:
//! Constructor for QgsLayerTreeView
explicit QgsLayerTreeView( QWidget *parent SIP_TRANSFERTHIS = nullptr );
~QgsLayerTreeView() override;
//! Overridden setModel() from base class. Only QgsLayerTreeModel is an acceptable model.
void setModel( QAbstractItemModel *model ) override;
//! Gets access to the model casted to QgsLayerTreeModel
QgsLayerTreeModel *layerTreeModel() const;
//! Gets access to the default actions that may be used with the tree view
QgsLayerTreeViewDefaultActions *defaultActions();
//! Sets provider for context menu. Takes ownership of the instance
void setMenuProvider( QgsLayerTreeViewMenuProvider *menuProvider SIP_TRANSFER );
//! Returns pointer to the context menu provider. May be NULLPTR
QgsLayerTreeViewMenuProvider *menuProvider() const { return mMenuProvider; }
/**
* Returns the currently selected layer, or NULLPTR if no layers is selected.
*
* \see setCurrentLayer()
*/
QgsMapLayer *currentLayer() const;
/**
* Sets the currently selected \a layer.
*
* If \a layer is NULLPTR then all layers will be deselected.
*
* \see currentLayer()
*/
void setCurrentLayer( QgsMapLayer *layer );
//! Gets current node. May be NULLPTR
QgsLayerTreeNode *currentNode() const;
//! Gets current group node. If a layer is current node, the function will return parent group. May be NULLPTR.
QgsLayerTreeGroup *currentGroupNode() const;
/**
* Gets current legend node. May be NULLPTR if current node is not a legend node.
* \since QGIS 2.14
*/
QgsLayerTreeModelLegendNode *currentLegendNode() const;
/**
* Returns list of selected nodes
* \param skipInternal If TRUE, will ignore nodes which have an ancestor in the selection
*/
QList<QgsLayerTreeNode *> selectedNodes( bool skipInternal = false ) const;
//! Returns list of selected nodes filtered to just layer nodes
QList<QgsLayerTreeLayer *> selectedLayerNodes() const;
//! Gets list of selected layers
QList<QgsMapLayer *> selectedLayers() const;
/**
* Gets list of selected layers, including those that are not directly selected, but their
* ancestor groups is selected. If we have a group with two layers L1, L2 and just the group
* node is selected, this method returns L1 and L2, while selectedLayers() returns an empty list.
* \since QGIS 3.4
*/
QList<QgsMapLayer *> selectedLayersRecursive() const;
/**
* Adds an indicator to the given layer tree node. Indicators are icons shown next to layer/group names
* in the layer tree view. They can be used to show extra information with tree nodes and they allow
* user interaction.
*
* Does not take ownership of the indicator. One indicator object may be used for multiple layer tree nodes.
* \see removeIndicator
* \see indicators
* \since QGIS 3.2
*/
void addIndicator( QgsLayerTreeNode *node, QgsLayerTreeViewIndicator *indicator );
/**
* Removes a previously added indicator to a layer tree node. Does not delete the indicator.
* \see addIndicator
* \see indicators
* \since QGIS 3.2
*/
void removeIndicator( QgsLayerTreeNode *node, QgsLayerTreeViewIndicator *indicator );
/**
* Returns list of indicators associated with a particular layer tree node.
* \see addIndicator
* \see removeIndicator
* \since QGIS 3.2
*/
QList<QgsLayerTreeViewIndicator *> indicators( QgsLayerTreeNode *node ) const;
///@cond PRIVATE
/**
* Returns a list of custom property keys which are considered as related to view operations
* only. E.g. node expanded state.
*
* Changes to these keys will not mark a project as "dirty" and trigger unsaved changes
* warnings.
*
* \since QGIS 3.2
*/
static QStringList viewOnlyCustomProperties() SIP_SKIP;
///@endcond
public slots:
//! Force refresh of layer symbology. Normally not needed as the changes of layer's renderer are monitored by the model
void refreshLayerSymbology( const QString &layerId );
/**
* Enhancement of QTreeView::expandAll() that also records expanded state in layer tree nodes
* \since QGIS 2.18
*/
void expandAllNodes();
/**
* Enhancement of QTreeView::collapseAll() that also records expanded state in layer tree nodes
* \since QGIS 2.18
*/
void collapseAllNodes();
signals:
//! Emitted when a current layer is changed
void currentLayerChanged( QgsMapLayer *layer );
protected:
void contextMenuEvent( QContextMenuEvent *event ) override;
void updateExpandedStateFromNode( QgsLayerTreeNode *node );
QgsMapLayer *layerForIndex( const QModelIndex &index ) const;
void mouseReleaseEvent( QMouseEvent *event ) override;
void keyPressEvent( QKeyEvent *event ) override;
void dropEvent( QDropEvent *event ) override;
protected slots:
void modelRowsInserted( const QModelIndex &index, int start, int end );
void modelRowsRemoved();
void updateExpandedStateToNode( const QModelIndex &index );
void onCurrentChanged();
void onExpandedChanged( QgsLayerTreeNode *node, bool expanded );
void onModelReset();
private slots:
void onCustomPropertyChanged( QgsLayerTreeNode *node, const QString &key );
protected:
//! helper class with default actions. Lazily initialized.
QgsLayerTreeViewDefaultActions *mDefaultActions = nullptr;
//! Context menu provider. Owned by the view.
QgsLayerTreeViewMenuProvider *mMenuProvider = nullptr;
//! Keeps track of current layer ID (to check when to emit signal about change of current layer)
QString mCurrentLayerID;
//! Storage of indicators used with the tree view
QHash< QgsLayerTreeNode *, QList<QgsLayerTreeViewIndicator *> > mIndicators;
//! Used by the item delegate for identification of which indicator has been clicked
QPoint mLastReleaseMousePos;
// friend so it can access viewOptions() method and mLastReleaseMousePos without making them public
friend class QgsLayerTreeViewItemDelegate;
};
/**
* \ingroup gui
* Implementation of this interface can be implemented to allow QgsLayerTreeView
* instance to provide custom context menus (opened upon right-click).
*
* \see QgsLayerTreeView
* \since QGIS 2.4
*/
class GUI_EXPORT QgsLayerTreeViewMenuProvider
{
public:
virtual ~QgsLayerTreeViewMenuProvider() = default;
//! Returns a newly created menu instance (or NULLPTR on error)
virtual QMenu *createContextMenu() = 0 SIP_FACTORY;
};
#endif // QGSLAYERTREEVIEW_H
| 34.952569 | 123 | 0.676128 | [
"object",
"model"
] |
27e5a520a8e39b36e354b942cf2843031dfbf4da | 7,449 | h | C | include/pxr_sfx.h | pixrex/pixiretro_engine | efe99f6ed5f812b1a54e77a07f86af2e3fdcef02 | [
"Unlicense"
] | null | null | null | include/pxr_sfx.h | pixrex/pixiretro_engine | efe99f6ed5f812b1a54e77a07f86af2e3fdcef02 | [
"Unlicense"
] | null | null | null | include/pxr_sfx.h | pixrex/pixiretro_engine | efe99f6ed5f812b1a54e77a07f86af2e3fdcef02 | [
"Unlicense"
] | null | null | null | #ifndef _PIXIRETRO_SFX_H_
#define _PIXIRETRO_SFX_H_
#include <SDL2/SDL_audio.h>
#include <limits>
namespace pxr
{
namespace sfx
{
//
// The relative paths to resource files on disk; save your sound assets to these directories.
//
constexpr const char* RESOURCE_PATH_SOUNDS = "assets/sounds/";
constexpr const char* RESOURCE_PATH_MUSIC = "assets/music/";
//
// The type of unique keys mapped to sound resources.
//
using ResourceKey_t = int32_t;
//
// The type of sound resource names.
//
using ResourceName_t = const char*;
//
// The type of unique keys which identify sound channels.
//
using SoundChannel_t = int;
//
// Returned upon failure to load a music file. This key is safe to pass to music functions
// and will simply cause those functions to be no-ops. It will not be returned upon failure
// to load sound effects, instead an error key is returned in that case.
//
static constexpr ResourceKey_t nullResourceKey {-1};
//
// The key returned upon failure to load sound resources. Will link to a generated sine tone
// which will play in place of any unloaded sounds.
//
extern ResourceKey_t errorSoundKey;
//////////////////////////////////////////////////////////////////////////////////////////////////
// GENERAL
//////////////////////////////////////////////////////////////////////////////////////////////////
enum OutputMode
{
MONO = 1,
STEREO = 2
};
//
// See SDL_audio.h for more details of audio sample formats.
//
// note: This module only supports little-endian integer output formats (designed for x86).
//
// note: U16 == U16LSB
// U32 == U32LSB
// S32 == S32LSB
// i.e. they are equivilent.
//
enum SampleFormat : uint16_t
{
SAMPLE_FORMAT_U8 = AUDIO_U8, // Unsigned 8-bit samples.
SAMPLE_FORMAT_S8 = AUDIO_S8, // Signed 8-bit samples.
SAMPLE_FORMAT_U16LSB = AUDIO_U16LSB, // Unsigned 16-bit samples little-endian.
SAMPLE_FORMAT_S16LSB = AUDIO_S16LSB, // Signed 16-bit samples little-endian.
SAMPLE_FORMAT_U16 = AUDIO_U16, // Unsigned 16-bit samples little endian.
SAMPLE_FORMAT_S16 = AUDIO_S16, // Signed 16-bit samples little endian.
SAMPLE_FORMAT_S32LSB = AUDIO_S32LSB, // Signed 32-bit samples little endian.
SAMPLE_FORMAT_S32 = AUDIO_S32, // Signed 32-bit samples little endian.
};
static constexpr int DEFAULT_SAMPLING_FREQ_HZ {22050 };
static constexpr int DEFAULT_SAMPLE_FORMAT {SAMPLE_FORMAT_S16LSB};
static constexpr int DEFAULT_CHUNK_SIZE {4096 };
static constexpr int DEFAULT_NUM_MIX_CHANNELS {16 };
struct SFXConfiguration
{
int _samplingFreq_hz {DEFAULT_SAMPLING_FREQ_HZ};
uint16_t _sampleFormat {DEFAULT_SAMPLE_FORMAT };
int _outputMode {OutputMode::MONO };
int _chunkSize {DEFAULT_CHUNK_SIZE };
int _numMixChannels {DEFAULT_NUM_MIX_CHANNELS};
};
//
// Must call before any other function in this module.
//
bool initialize(SFXConfiguration sfxconf = SFXConfiguration{});
//
// Call at program exit.
//
void shutdown();
//
// Called by the engine every tick to service the module, e.g. to unload any sounds in the
// unload queue.
//
void onUpdate(float dt);
//////////////////////////////////////////////////////////////////////////////////////////////////
// SOUND EFFECTS
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// Helper definition for use with play functions (both sounds and music).
//
static constexpr int INFINITE_LOOPS {-1};
static constexpr int NO_LOOPS {0};
//
// Helper definition for use with functions which pause/stop/resume sound channel playback.
//
static constexpr int ALL_CHANNELS {-1};
//
// Returned from play functions on errors. It is safe to pass this value to any function which
// modifies a channel, e.g. stopChannel, pauseChannel etc.
//
static constexpr int NULL_CHANNEL {-2};
//
// Helper definition for use with volume functions (both sounds and music).
//
static constexpr int MIN_VOLUME {0};
static constexpr int MAX_VOLUME {128};
//
// Can be used with play functions to play the error sound.
//
extern ResourceKey_t errorSoundKey;
//
// Load a WAV sound.
//
// Returns the resouce key the sound is mapped to which is needed to later play the sound.
//
// Internally sounds are reference counted and so can be loaded multiple times without
// duplication, each time returning the same key. To actually remove sounds from memory
// it is necessary to unload a sound an equal number of times to which it was loaded.
//
// If a sound cannot be loaded an error will be logged to the log and the resource key of
// the error sound will be returned.
//
// Returned resource keys are always positive.
//
ResourceKey_t loadSoundWAV(ResourceName_t soundName);
//
// Adds a sound to the queue of sounds waiting to be unloaded. Sounds in the queue are unloaded
// once all channels have stopped using it. A call to this function will only actually queue a
// sound if its reference count drops to 0. Thus it is necessary to unload a sound an equal
// number of times to which it was loaded.
//
void queueUnloadSound(ResourceKey_t soundKey);
//
// Play a sound. These functions return the channel the sound is playing on which can be used to
// manipulate the playback.
//
SoundChannel_t playSound(ResourceKey_t soundKey, int loops = NO_LOOPS);
SoundChannel_t playSoundTimed(ResourceKey_t soundKey, int loops, int playDuration_ms);
SoundChannel_t playSoundFadeIn(ResourceKey_t soundKey, int loops, int fadeDuration_ms);
SoundChannel_t playSoundFadeInTimed(ResourceKey_t soundKey, int loops, int fadeDuration_ms, int playDuration_ms);
//
// Pause/resume/stop sound channels.
//
void stopChannel(SoundChannel_t channel);
void stopChannelTimed(SoundChannel_t channel, int durationUntilStop_ms);
void stopChannelFadeOut(SoundChannel_t channel, int fadeDuration_ms);
void pauseChannel(SoundChannel_t channel);
void resumeChannel(SoundChannel_t channel);
//
// Passing in ALL_CHANNELS or NULL_CHANNEL will always return false.
//
bool isChannelPlaying(SoundChannel_t channel);
bool isChannelPaused(SoundChannel_t channel);
//
// Passing ALL_CHANNELS will set the volume for all channels as would be expected. Volumes
// outside the range of valid volumes will be clamped.
//
void setChannelVolume(SoundChannel_t channel, int volume);
//
// Passing in ALL_CHANNELS will return the average volume. Passing in NULL_CHANNEL will always
// return 0.
//
int getChannelVolume(SoundChannel_t channel);
int getMusicVolume();
//////////////////////////////////////////////////////////////////////////////////////////////////
// MUSIC FUNCTIONS
//////////////////////////////////////////////////////////////////////////////////////////////////
static constexpr float PLAY_MUSIC_FOREVER {std::numeric_limits<float>::max()};
struct MusicSequenceNode
{
ResourceKey_t _musicKey;
int _fadeInDuration_ms;
int _playDuration_ms;
int _fadeOutDuration_ms;
};
using MusicSequence_t = std::vector<MusicSequenceNode>;
ResourceKey_t loadMusicWAV(ResourceName_t musicName);
void queueUnloadMusic(ResourceKey_t musicKey);
void playMusic(MusicSequence_t sequence, bool loop = true);
void stopMusic();
void pauseMusic();
void resumeMusic();
bool isMusicPlaying();
bool isMusicPaused();
bool isMusicFadingIn();
bool isMusicFadingOut();
void setMusicVolume(int volume);
} // namespace sfx
} // namespace pxr
#endif
| 31.697872 | 113 | 0.688415 | [
"vector"
] |
27fc9e1f27970f8be6e9b6bd850f07ce82dc9060 | 869 | h | C | InfiniteHotel/Gene.h | NeuroWhAI/InfiniteHotel | a08715084f3acba053ed5bbfced6dbd66f207c97 | [
"MIT"
] | null | null | null | InfiniteHotel/Gene.h | NeuroWhAI/InfiniteHotel | a08715084f3acba053ed5bbfced6dbd66f207c97 | [
"MIT"
] | null | null | null | InfiniteHotel/Gene.h | NeuroWhAI/InfiniteHotel | a08715084f3acba053ed5bbfced6dbd66f207c97 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <random>
#include <ostream>
#include <istream>
class Gene
{
public:
class Hasher
{
public:
size_t operator() (const Gene& gene) const
{
return std::hash<int>()(gene.getSum());
}
};
public:
Gene();
Gene(const std::initializer_list<char>& list);
protected:
std::vector<char> m_code;
public:
void writeTo(std::ostream& osr) const;
void readFrom(std::istream& isr);
public:
void initializeRandomly(std::mt19937& engine, int cmdSetCount);
public:
size_t getLength() const;
const std::vector<char>& getCode() const;
double getEnergy() const;
public:
void combine(const Gene& other, std::mt19937& engine);
void mutate(std::mt19937& engine, int cmdSetCount);
public:
bool operator== (const Gene& right) const;
bool operator!= (const Gene& right) const;
protected:
int getSum() const;
};
| 13.793651 | 64 | 0.690449 | [
"vector"
] |
27fec4fba21080849e5ce94704de4649094131a4 | 4,221 | h | C | src/lib/GarthLib/Garth.h | Korovasoft/Concurrent-GARTH | 2f22c464ce30f743b45bbd6c18a8546bee69be93 | [
"MIT"
] | null | null | null | src/lib/GarthLib/Garth.h | Korovasoft/Concurrent-GARTH | 2f22c464ce30f743b45bbd6c18a8546bee69be93 | [
"MIT"
] | null | null | null | src/lib/GarthLib/Garth.h | Korovasoft/Concurrent-GARTH | 2f22c464ce30f743b45bbd6c18a8546bee69be93 | [
"MIT"
] | null | null | null | ////////////////////////////////////////
////////////////////////////////////////
//
// Copyright (C) 2014 Korovasoft, Inc.
//
// File:
// \file Garth.h
//
// Description:
// \brief Garth Library header.
//
// Author:
// \author J. Caleb Wherry
//
////////////////////////////////////////
////////////////////////////////////////
// Include guards:
#ifndef GARTH_H
#define GARTH_H
// Forward declarations:
//
// Local includes:
//
// Compiler includes:
#include <memory>
#include <string>
#include <ConcurrentObjects.h>
// Namespaces:
namespace CO = ConcurrentObjects;
/// Garth namespace
namespace Garth
{
/// Organism class
class Organism
{
protected:
std::string name;
std::vector<double> genome;
uint32_t numGenes;
double fitness;
public:
/// Default constructor
Organism();
/// Custom constructor
Organism (
const std::string& name_,
double fitness_ = 0.0
);
/// Destructor
virtual ~Organism();
/// Mutate method
virtual void mutate();
};
/// Population typedef (new syntax)
using Population = CO::ConcurrentVector<Organism>;
/// Habitat class
class Habitat
{
private:
std::string name;
uint32_t numberTrainers;
public:
/// Default constructor
Habitat();
/// Custom constructor
Habitat (
uint32_t numberTrainers
);
/// Get number of trainers:
uint32_t getNumberTrainers();
/// Set number of trainers:
void setNumberTrainers(uint32_t numberTrainers);
};
/// Habitat typedef
using Habitats = std::vector<Habitat>;
/// Zoo Statuses
enum ZooStatus
{
UNKNOWN, ///< Unknown status
OPEN, ///< Open status
SUSPENDED, ///< Suspended status
RESUMED, ///< Resumed status
CLOSED ///< Closed status
};
/// Zoo class
class Zoo
{
friend class ZooKeeper;
private:
std::string name; ///< Zoo name
ZooStatus status; ///< Status of Zoo
Population population; ///< Zoo Organism population
Habitats habitats; ///< Zoo habitats
uint32_t numberHabitats; ///< Number of habitats
uint32_t maxGenerations; ///< Max number of generations
uint32_t numberTrainers; ///< Number of trainers
public:
/// Default constructor
Zoo();
/// Custom constructor
Zoo (
const std::string& name_,
ZooStatus status_ = OPEN
);
// Zoo operations:
void open();
void suspend();
void resume();
void close();
// Get methods:
uint32_t getMaxGenerations();
uint32_t getNumberHabitats();
uint32_t getNumberTrainers();
// Set Max Generations
void setMaxGenerations (
uint32_t maxGenerations_
);
// Set Number of Habitats
void setNumberHabitats (
uint32_t numberHabitats_
);
// Set Number Trainers
void setNumberTrainers (
uint32_t numberHabitats
);
};
/// ZooKeeper class
class ZooKeeper
{
private:
std::string name;
std::shared_ptr<Zoo> zoo;
public:
/// Default constructor
ZooKeeper();
/// Custom constructor
ZooKeeper (
const std::string& name_,
std::shared_ptr<Zoo> zoo_
);
// Zoo operations:
void openZoo();
void suspendZoo();
void resumeZoo();
void closeZoo();
// Population operations:
void initializePopulation();
void shufflePopulation();
void rankPopulation();
void mutatePopulation();
bool populationConverged();
// Organism operations:
std::shared_ptr<Organism> getOptimalOrganism();
};
/// Trainer class
class Trainer
{
private:
std::string name;
public:
/// Default constructor
Trainer();
/// Custom constructor
Trainer (
const std::string& name_
);
/// Set name
void setName (
const std::string& name_
);
/// Get name
std::string getName();
};
} // Garth namespace
#endif // GARTH_H
| 16.884 | 62 | 0.55058 | [
"vector"
] |
7e004fa116ba5a879bb52743f1923002dc56ceb4 | 1,306 | h | C | src/solar_platforms/d3d9/d3d9_mesh_factory.h | jseward/solar | a0b76e3c945679a8fcb4cc94160298788b96e4a5 | [
"MIT"
] | 4 | 2017-04-02T07:56:14.000Z | 2021-10-01T18:23:33.000Z | src/solar_platforms/d3d9/d3d9_mesh_factory.h | jseward/solar | a0b76e3c945679a8fcb4cc94160298788b96e4a5 | [
"MIT"
] | null | null | null | src/solar_platforms/d3d9/d3d9_mesh_factory.h | jseward/solar | a0b76e3c945679a8fcb4cc94160298788b96e4a5 | [
"MIT"
] | 1 | 2021-10-01T18:23:38.000Z | 2021-10-01T18:23:38.000Z | #pragma once
#include <unordered_map>
#include <memory>
#include "solar/rendering/meshes/mesh_factory.h"
#include "d3d9_device_event_handler.h"
namespace solar {
class d3d9_context;
class d3d9_mesh;
class resource_system;
class resource_mapped_memory;
class d3d9_mesh_factory
: public mesh_factory
, public d3d9_device_event_handler {
private:
d3d9_context& _context;
resource_system& _resource_system;
bool _is_setup;
resource_factory_caching_context _caching_context;
std::unordered_map<std::string, std::unique_ptr<d3d9_mesh>> _meshs;
public:
d3d9_mesh_factory(d3d9_context& context, resource_system& resource_system);
virtual ~d3d9_mesh_factory();
void setup();
void teardown();
virtual mesh* get_mesh(const std::string& id, const std::string& id_source_description) override;
virtual const resource_factory_caching_context& get_caching_context() const override;
d3d9_context& get_d3d9_context();
resource_system& get_resource_system();
private:
void remove_all_meshs();
virtual void on_device_created(IDirect3DDevice9* device) override;
virtual void on_device_released(IDirect3DDevice9* device) override;
virtual void on_device_reset(IDirect3DDevice9* device) override;
virtual void on_device_lost(IDirect3DDevice9* device) override;
};
}
| 26.653061 | 99 | 0.795559 | [
"mesh"
] |
7e0add4cbc6876a62ff9f6df829907c461569adf | 4,042 | h | C | src/math/bvec3.h | chiguire/nttcitygenerator | 7c449e74d4363b54c1a59684b7aeb2e13686d695 | [
"MIT"
] | 3 | 2019-04-09T04:43:46.000Z | 2020-01-19T03:31:32.000Z | src/math/bvec3.h | chiguire/nttcitygenerator | 7c449e74d4363b54c1a59684b7aeb2e13686d695 | [
"MIT"
] | null | null | null | src/math/bvec3.h | chiguire/nttcitygenerator | 7c449e74d4363b54c1a59684b7aeb2e13686d695 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
//
// (C) Andy Thomason 2012, 2013
//
// Modular Framework for OpenGLES2 rendering on multiple platforms.
//
// Vector class
//
namespace octet {
class bvec3 {
#ifdef OCTET_SSE
union {
__m128 m;
int v[4];
};
#else
int v[3];
#endif
public:
bvec3() {}
bvec3(bool x, bool y, bool z) { v[0] = x ? -1 : 0; v[1] = y ? -1 : 0; v[2] = z ? -1 : 0; };
bvec3(int x, int y, int z) { v[0] = x; v[1] = y; v[2] = z; };
#ifdef OCTET_SSE
bvec3(__m128 m) {
this->m = m;
}
__m128 get_m() const {
return m;
}
#endif
int &operator[](int i) { return v[i]; }
const int &operator[](int i) const { return v[i]; }
bvec3 operator&(int r) const { return bvec3(v[0]&r, v[1]&r, v[2]&r); }
bvec3 operator|(int r) const { return bvec3(v[0]|r, v[1]|r, v[2]|r); }
bvec3 operator^(int r) const { return bvec3(v[0]^r, v[1]^r, v[2]^r); }
bvec3 operator&(const bvec3 &r) const { return bvec3(v[0]&r.v[0], v[1]&r.v[1], v[2]&r.v[2]); }
bvec3 operator|(const bvec3 &r) const { return bvec3(v[0]|r.v[0], v[1]|r.v[1], v[2]|r.v[2]); }
bvec3 operator^(const bvec3 &r) const { return bvec3(v[0]^r.v[0], v[1]^r.v[1], v[2]^r.v[2]); }
bvec3 &operator&=(const bvec3 &r) { v[0] &= r.v[0]; v[1] &= r.v[1]; v[2] &= r.v[2]; return *this; }
bvec3 &operator|=(const bvec3 &r) { v[0] |= r.v[0]; v[1] |= r.v[1]; v[2] |= r.v[2]; return *this; }
bvec3 &operator^=(const bvec3 &r) { v[0] ^= r.v[0]; v[1] ^= r.v[1]; v[2] ^= r.v[2]; return *this; }
bvec3 operator~() const { return bvec3(~v[0], ~v[1], ~v[2]); }
int &x() { return v[0]; }
int &y() { return v[1]; }
int &z() { return v[2]; }
int x() const { return v[0]; }
int y() const { return v[1]; }
int z() const { return v[2]; }
// convert to a string (up to 4 strings can be included at a time)
const char *toString() const
{
char *dest = get_sprintf_buffer();
sprintf(dest, "[%2d, %2d, %2d]", v[0]>>31, v[1]>>31, v[2]>>31);
return dest;
}
};
inline bvec3 operator>(const vec3 &lhs, const vec3 &rhs) {
#ifdef OCTET_SSE
return bvec3(_mm_cmpgt_ps(lhs.get_m(), rhs.get_m()) );
#else
return bvec3(fgt(lhs.x(), rhs.x()), fgt(lhs.y(), rhs.y()), fgt(lhs.z(), rhs.z()) );
#endif
}
inline bvec3 operator<(const vec3 &lhs, const vec3 &rhs) {
#ifdef OCTET_SSE
return bvec3(_mm_cmplt_ps(lhs.get_m(), rhs.get_m()) );
#else
return bvec3(flt(lhs.x(), rhs.x()), flt(lhs.y(), rhs.y()), flt(lhs.z(), rhs.z()) );
#endif
}
inline bvec3 operator>=(const vec3 &lhs, const vec3 &rhs) {
#ifdef OCTET_SSE
return bvec3(_mm_cmpge_ps(lhs.get_m(), rhs.get_m()) );
#else
return bvec3(fge(lhs.x(), rhs.x()), fge(lhs.y(), rhs.y()), fge(lhs.z(), rhs.z()) );
#endif
}
inline bvec3 operator<=(const vec3 &lhs, const vec3 &rhs) {
#ifdef OCTET_SSE
return bvec3(_mm_cmple_ps(lhs.get_m(), rhs.get_m()) );
#else
return bvec3(fle(lhs.x(), rhs.x()), fle(lhs.y(), rhs.y()), fle(lhs.z(), rhs.z()) );
#endif
}
inline bvec3 operator==(const vec3 &lhs, const vec3 &rhs) {
#ifdef OCTET_SSE
return bvec3(_mm_cmpeq_ps(lhs.get_m(), rhs.get_m()) );
#else
return bvec3(feq(lhs.x(), rhs.x()), feq(lhs.y(), rhs.y()), feq(lhs.z(), rhs.z()) );
#endif
}
inline bvec3 operator!=(const vec3 &lhs, const vec3 &rhs) {
#ifdef OCTET_SSE
return bvec3(_mm_cmpneq_ps(lhs.get_m(), rhs.get_m()) );
#else
return bvec3(fne(lhs.x(), rhs.x()), fne(lhs.y(), rhs.y()), fne(lhs.z(), rhs.z()) );
#endif
}
bool all(const bvec3 &b) {
#ifdef OCTET_SSE
return (_mm_movemask_ps(b.get_m()) & 7) == 7;
#else
return (b.x() & b.y() & b.z()) < 0;
#endif
}
bool any(const bvec3 &b) {
#ifdef OCTET_SSE
return (_mm_movemask_ps(b.get_m()) & 7) != 0;
#else
return (b.x() | b.y() | b.z()) < 0;
#endif
}
}
| 31.333333 | 103 | 0.519792 | [
"vector"
] |
7e117607b7a4df178dc9f84ed815a25df9599c09 | 1,892 | h | C | includes/Atlas/Shapes/Rectangle.h | Uedaki/Atlas | 32960472d369dffbf4fa44eae5ba7a2dec4ceae1 | [
"MIT"
] | null | null | null | includes/Atlas/Shapes/Rectangle.h | Uedaki/Atlas | 32960472d369dffbf4fa44eae5ba7a2dec4ceae1 | [
"MIT"
] | 12 | 2021-04-20T15:09:43.000Z | 2021-06-15T20:44:10.000Z | includes/Atlas/Shapes/Rectangle.h | Uedaki/Atlas | 32960472d369dffbf4fa44eae5ba7a2dec4ceae1 | [
"MIT"
] | null | null | null | #pragma once
#include "atlas/Atlas.h"
#include "atlas/AtlasLibHeader.h"
#include "atlas/core/Shape.h"
#include "atlas/core/Points.h"
namespace atlas
{
class Rectangle : public Shape
{
public:
struct Info : public Shape::Info
{
//Transform *Shape::objectToWorld = nullptr; --> inherited from Shape::Info
//Transform *Shape::worldToObject = nullptr;
//bool Shape::reverseOrientation = false;
Info()
: Shape::Info(ShapeType::RECTANGLE)
{}
};
ATLAS static std::shared_ptr<Rectangle> createShape(const Info &info);
Rectangle(const Info &info)
: Shape(info.objectToWorld, info.worldToObject, info.reverseOrientation)
, p0(objectToWorld(Point3f(-1, -1, 0)))
, p1(objectToWorld(Point3f(1, -1, 0)))
, p2(objectToWorld(Point3f(-1, 1, 0)))
{}
Rectangle(const Transform &objectToWorld, const Transform &worldToObject,
bool reverseOrientation)
: Shape(objectToWorld, worldToObject, reverseOrientation)
, p0(objectToWorld(Point3f(-1, -1, 0)))
, p1(objectToWorld(Point3f(1, -1, 0)))
, p2(objectToWorld(Point3f(-1, 1, 0)))
{}
ATLAS Bounds3f objectBound() const override;
ATLAS Bounds3f worldBound() const override;
ATLAS bool intersect(const Ray &ray, Float &tHit, SurfaceInteraction &intersection, bool testAlphaTexture) const override;
ATLAS bool intersectP(const Ray &ray, bool testAlphaTexture) const override;
ATLAS Float area() const override;
ATLAS Interaction sample(const Point2f &u, Float &pdf) const override;
ATLAS Interaction sample(const Interaction &ref, const Point2f &u, Float &pdf) const override;
ATLAS Float pdf(const Interaction &ref, const Vec3f &wi) const override;
ATLAS std::shared_ptr<Shape::Info> getInfo() const override;
private:
Point3f p0;
Point3f p1;
Point3f p2;
};
typedef Rectangle::Info RectangleInfo;
} | 30.516129 | 125 | 0.693975 | [
"shape",
"transform"
] |
5f50ffb08d4b1c41fa424fa2aefcd5bbde2ef00e | 1,093 | h | C | xfa/fxfa/cxfa_deffontmgr.h | KnIfER/pdfpdf | 2b918c8d05c922287efbc8858f029026cee31442 | [
"BSD-3-Clause"
] | 3 | 2019-01-12T07:06:18.000Z | 2019-10-13T08:07:26.000Z | xfa/fxfa/cxfa_deffontmgr.h | KnIfER/pdf | 2b918c8d05c922287efbc8858f029026cee31442 | [
"BSD-3-Clause"
] | null | null | null | xfa/fxfa/cxfa_deffontmgr.h | KnIfER/pdf | 2b918c8d05c922287efbc8858f029026cee31442 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#ifndef XFA_FXFA_CXFA_DEFFONTMGR_H_
#define XFA_FXFA_CXFA_DEFFONTMGR_H_
#include <vector>
#include "core/fxcrt/cfx_retain_ptr.h"
#include "core/fxcrt/fx_string.h"
#include "xfa/fgas/font/cfgas_gefont.h"
class CXFA_FFDoc;
class CXFA_DefFontMgr {
public:
CXFA_DefFontMgr();
~CXFA_DefFontMgr();
CFX_RetainPtr<CFGAS_GEFont> GetFont(CXFA_FFDoc* hDoc,
const CFX_WideStringC& wsFontFamily,
uint32_t dwFontStyles,
uint16_t wCodePage = 0xFFFF);
CFX_RetainPtr<CFGAS_GEFont> GetDefaultFont(
CXFA_FFDoc* hDoc,
const CFX_WideStringC& wsFontFamily,
uint32_t dwFontStyles,
uint16_t wCodePage = 0xFFFF);
private:
std::vector<CFX_RetainPtr<CFGAS_GEFont>> m_CacheFonts;
};
#endif // XFA_FXFA_CXFA_DEFFONTMGR_H_
| 28.763158 | 80 | 0.691674 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.