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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
192281343e27779367c3ecc2b26d0afb16920f4d | 4,667 | h | C | RM1_Ext/terrain.h | SRAM/RacerMateOne | b20b6a5bb4ea9168252dc15622bafb037a11b0d7 | [
"MIT"
] | 2 | 2020-10-08T21:30:38.000Z | 2020-11-13T23:50:50.000Z | RM1_Ext/terrain.h | SRAM/RacerMateOne | b20b6a5bb4ea9168252dc15622bafb037a11b0d7 | [
"MIT"
] | null | null | null | RM1_Ext/terrain.h | SRAM/RacerMateOne | b20b6a5bb4ea9168252dc15622bafb037a11b0d7 | [
"MIT"
] | null | null | null | // Terrain.h: interface for the Terrain class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_TERRAIN_H__25DDFA3B_33B1_439B_9EA9_3B2E55C4F4C0__INCLUDED_)
#define AFX_TERRAIN_H__25DDFA3B_33B1_439B_9EA9_3B2E55C4F4C0__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <TList.h>
#include <CCourse.h>
#include <gl\glu.h>
#pragma warning(disable:4786)
#include <vector>
using namespace std;
class Terrain : public TList<Terrain>::Node {
public:
static Terrain *ms_RenderList;
protected:
static TList<Terrain> ms_List;
static TList<Terrain> ms_ReadyList;
//static float ms_usize;
//static float ms_vsize;
static unsigned long ms_RID;
public:
float ms_usize;
float ms_vsize;
static HRESULT RenderAll();
struct EdgeNode{
struct EdgeNode *next; // Next Edge node in this list.
struct EdgeNode *pair; // The other pair of this edge node.
float start; // Starting location.
float dist; // distance - (neg or pos)
short idx;
short count; // negitive for an end node.
int dir;
int uid;
};
static bool DumpAll(const char *name);
static void ClearAll();
static bool FinishCutAll();
static int CountAll();
static void CloseAllModels();
static Terrain * GetFirstTerrain() {
return ms_List.GetFirst();
}
static void StartRender() {
ms_RID++;
}
static void EndRender();
void Show(bool bShow);
ISceneNode *GetNode() {return terrainNode;}
vector3df GetCenter() {return m_Center;}
float GetRadius() {return m_Radius;}
Terrain *m_pNextRender;
bool m_bRender;
protected:
CCourse &m_Course;
vector3df m_Min, m_Max;
vector3df m_Center;
float m_Radius;
vector<COURSEVERTEX> m_V;
vector<WORD> m_I;
int m_Errors;
unsigned long m_RID;
GLUtesselator *m_ptess;
COURSEVERTEX m_cv;
enum {
MODE_NONE,
MODE_ENCLOSED,
MODE_CUT
} m_Mode;
// The cutter.
EdgeNode *m_pEdgeArr[4];
EdgeNode *m_pStartEdge;
int m_Cuts;
vector3df m_LastV;
int pushV(const COURSEVERTEX &cv);
GLUtesselator *createTess();
EdgeNode *addEdgeNode(const COURSEVERTEX &cv, int dir, bool left);
void finishV();
// Render information
// ==================
//LPDIRECT3DVERTEXBUFFER7 m_pVBuf;
SMesh* m_pMesh;
ISceneNode *terrainNode;
bool bMeshCreated;
DWORD m_VertCount;
//LPWORD m_pIBuf;
DWORD m_IndexCount;
// tlm20050506. microsoft's opengl header files need stdcall!
static void __stdcall _beginCB(GLenum type, Terrain *caller);
static void __stdcall _edgeFlagCB(GLboolean flag, Terrain *caller);
static void __stdcall _vertexCB(unsigned int vertexIndex, Terrain *caller);
static void __stdcall _endCB(Terrain *caller);
static void __stdcall _combineCB(GLdouble coords[3], unsigned int vertexData[4], GLfloat weight[4], unsigned int *outData, Terrain *caller);
static void __stdcall _errorCB(GLenum errno, Terrain *caller);
/*
static void _beginCB(GLenum type, Terrain *caller);
static void _edgeFlagCB(GLboolean flag, Terrain *caller);
static void _vertexCB(unsigned int vertexIndex, Terrain *caller);
static void _endCB(Terrain *caller);
static void _combineCB(GLdouble coords[3], unsigned int vertexData[4], GLfloat weight[4], unsigned int *outData, Terrain *caller);
static void _errorCB(GLenum errno, Terrain *caller);
*/
public:
Terrain::Terrain(CCourse &course, const vector3df &min, const vector3df &max);
~Terrain();
void AddRender() {
//if (!m_bRender) {
m_pNextRender = ms_RenderList;
ms_RenderList = this;
m_bRender = true;
//}
}
static void ClearRenderList() {
ms_RenderList = NULL;
}
static void ClearRendered() {
Terrain *ptNext;
for(Terrain *pt = ms_RenderList;pt;pt = ptNext)
{
ptNext = pt->m_pNextRender;
pt->Show(false);
pt->m_pNextRender = NULL;
pt->m_bRender = false;
}
ms_RenderList = NULL;
}
bool InBox(const COURSEVERTEX &cv);
// Used for standalone
bool StartEnclosed();
bool EndEnclosed();
void BeginContour();
void EndContour();
void AddV(const COURSEVERTEX &cv);
void AddBox();
void InitCut();
bool FinishCut();
void StartCut(const COURSEVERTEX &cv, int dir, bool left);
void AddCutV(const COURSEVERTEX &cv);
void EndCut(const COURSEVERTEX &cv, int dir, bool left);
COURSEVERTEX * GetCornerPoints() {
return &(m_V[0]);
}
bool ReadyModel(ISceneNode *groupNode);
void CloseModel();
HRESULT Render();
bool InFrustum(ICameraSceneNode* cam);
bool Dump(const char *name);
};
#endif // !defined(AFX_TERRAIN_H__25DDFA3B_33B1_439B_9EA9_3B2E55C4F4C0__INCLUDED_)
| 22.990148 | 142 | 0.693808 | [
"render",
"vector"
] |
192613ab74e2c768bf76d7aa1ed5b51ea929ff33 | 6,056 | c | C | nRF5_SDK_15.0.0_a53641a/examples/peripheral/fatfs/main.c | ghsecuritylab/nrf52832sdk15.0.0 | 816cad7c0c2c1ebf271bc099554eaf17482bb8b9 | [
"Apache-2.0"
] | null | null | null | nRF5_SDK_15.0.0_a53641a/examples/peripheral/fatfs/main.c | ghsecuritylab/nrf52832sdk15.0.0 | 816cad7c0c2c1ebf271bc099554eaf17482bb8b9 | [
"Apache-2.0"
] | null | null | null | nRF5_SDK_15.0.0_a53641a/examples/peripheral/fatfs/main.c | ghsecuritylab/nrf52832sdk15.0.0 | 816cad7c0c2c1ebf271bc099554eaf17482bb8b9 | [
"Apache-2.0"
] | 1 | 2020-03-08T00:49:18.000Z | 2020-03-08T00:49:18.000Z | /**
* Copyright (c) 2016 - 2018, Nordic Semiconductor ASA
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA 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.
*
*/
/** @file
* @defgroup fatfs_example_main main.c
* @{
* @ingroup fatfs_example
* @brief FATFS Example Application main file.
*
* This file contains the source code for a sample application using FAT filesystem and SD card library.
*
*/
#include "nrf.h"
#include "bsp.h"
#include "ff.h"
#include "diskio_blkdev.h"
#include "nrf_block_dev_sdc.h"
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"
#define FILE_NAME "NORDIC.TXT"
#define TEST_STRING "SD card example."
#define SDC_SCK_PIN ARDUINO_13_PIN ///< SDC serial clock (SCK) pin.
#define SDC_MOSI_PIN ARDUINO_11_PIN ///< SDC serial data in (DI) pin.
#define SDC_MISO_PIN ARDUINO_12_PIN ///< SDC serial data out (DO) pin.
#define SDC_CS_PIN ARDUINO_10_PIN ///< SDC chip select (CS) pin.
/**
* @brief SDC block device definition
* */
NRF_BLOCK_DEV_SDC_DEFINE(
m_block_dev_sdc,
NRF_BLOCK_DEV_SDC_CONFIG(
SDC_SECTOR_SIZE,
APP_SDCARD_CONFIG(SDC_MOSI_PIN, SDC_MISO_PIN, SDC_SCK_PIN, SDC_CS_PIN)
),
NFR_BLOCK_DEV_INFO_CONFIG("Nordic", "SDC", "1.00")
);
/**
* @brief Function for demonstrating FAFTS usage.
*/
static void fatfs_example()
{
static FATFS fs;
static DIR dir;
static FILINFO fno;
static FIL file;
uint32_t bytes_written;
FRESULT ff_result;
DSTATUS disk_state = STA_NOINIT;
// Initialize FATFS disk I/O interface by providing the block device.
static diskio_blkdev_t drives[] =
{
DISKIO_BLOCKDEV_CONFIG(NRF_BLOCKDEV_BASE_ADDR(m_block_dev_sdc, block_dev), NULL)
};
diskio_blockdev_register(drives, ARRAY_SIZE(drives));
NRF_LOG_INFO("Initializing disk 0 (SDC)...");
for (uint32_t retries = 3; retries && disk_state; --retries)
{
disk_state = disk_initialize(0);
}
if (disk_state)
{
NRF_LOG_INFO("Disk initialization failed.");
return;
}
uint32_t blocks_per_mb = (1024uL * 1024uL) / m_block_dev_sdc.block_dev.p_ops->geometry(&m_block_dev_sdc.block_dev)->blk_size;
uint32_t capacity = m_block_dev_sdc.block_dev.p_ops->geometry(&m_block_dev_sdc.block_dev)->blk_count / blocks_per_mb;
NRF_LOG_INFO("Capacity: %d MB", capacity);
NRF_LOG_INFO("Mounting volume...");
ff_result = f_mount(&fs, "", 1);
if (ff_result)
{
NRF_LOG_INFO("Mount failed.");
return;
}
NRF_LOG_INFO("\r\n Listing directory: /");
ff_result = f_opendir(&dir, "/");
if (ff_result)
{
NRF_LOG_INFO("Directory listing failed!");
return;
}
do
{
ff_result = f_readdir(&dir, &fno);
if (ff_result != FR_OK)
{
NRF_LOG_INFO("Directory read failed.");
return;
}
if (fno.fname[0])
{
if (fno.fattrib & AM_DIR)
{
NRF_LOG_RAW_INFO(" <DIR> %s",(uint32_t)fno.fname);
}
else
{
NRF_LOG_RAW_INFO("%9lu %s", fno.fsize, (uint32_t)fno.fname);
}
}
}
while (fno.fname[0]);
NRF_LOG_RAW_INFO("");
NRF_LOG_INFO("Writing to file " FILE_NAME "...");
ff_result = f_open(&file, FILE_NAME, FA_READ | FA_WRITE | FA_OPEN_APPEND);
if (ff_result != FR_OK)
{
NRF_LOG_INFO("Unable to open or create file: " FILE_NAME ".");
return;
}
ff_result = f_write(&file, TEST_STRING, sizeof(TEST_STRING) - 1, (UINT *) &bytes_written);
if (ff_result != FR_OK)
{
NRF_LOG_INFO("Write failed\r\n.");
}
else
{
NRF_LOG_INFO("%d bytes written.", bytes_written);
}
(void) f_close(&file);
return;
}
/**
* @brief Function for main application entry.
*/
int main(void)
{
bsp_board_init(BSP_INIT_LEDS);
APP_ERROR_CHECK(NRF_LOG_INIT(NULL));
NRF_LOG_DEFAULT_BACKENDS_INIT();
NRF_LOG_INFO("FATFS example started.");
fatfs_example();
while (true)
{
__WFE();
}
}
/** @} */
| 29.980198 | 129 | 0.664465 | [
"geometry"
] |
192af15c30153f82288e1d3243b430315518c1a7 | 371 | h | C | LMImagePicker/Classes/LMAlbumPickerController.h | limeng99/LMImagePicker | 2daeec4b681ea912cf921afcd4b1d5285d453f80 | [
"MIT"
] | 2 | 2019-09-05T10:11:25.000Z | 2019-09-05T10:12:46.000Z | LMImagePicker/Classes/LMAlbumPickerController.h | limeng99/LMImagePicker | 2daeec4b681ea912cf921afcd4b1d5285d453f80 | [
"MIT"
] | null | null | null | LMImagePicker/Classes/LMAlbumPickerController.h | limeng99/LMImagePicker | 2daeec4b681ea912cf921afcd4b1d5285d453f80 | [
"MIT"
] | 1 | 2019-09-09T06:16:47.000Z | 2019-09-09T06:16:47.000Z | //
// LMAlbumPickerController.h
// LMImagePicker
//
// Created by LM on 2019/9/4.
// Copyright © 2019 LM. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@class LMAlbumModel;
@interface LMAlbumPickerController : UIViewController
@property (nonatomic, copy) void(^albumPickerSelectedBlock)(LMAlbumModel *model);
@end
NS_ASSUME_NONNULL_END
| 18.55 | 81 | 0.762803 | [
"model"
] |
192c77ef36084e1c53b36e07f7cde79d9cb01dc1 | 13,053 | c | C | drivers/iio/light/vl6180.c | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | 11 | 2022-02-05T12:12:43.000Z | 2022-03-08T08:09:08.000Z | drivers/iio/light/vl6180.c | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | 3 | 2021-09-06T09:14:42.000Z | 2022-03-27T08:09:54.000Z | drivers/iio/light/vl6180.c | fergy/aplit_linux-5 | a6ef4cb0e17e1eec9743c064e65f730c49765711 | [
"MIT"
] | 1 | 2020-11-06T07:32:55.000Z | 2020-11-06T07:32:55.000Z | /*
* vl6180.c - Support for STMicroelectronics VL6180 ALS, range and proximity
* sensor
*
* Copyright 2017 Peter Meerwald-Stadler <pmeerw@pmeerw.net>
* Copyright 2017 Manivannan Sadhasivam <manivannanece23@gmail.com>
*
* This file is subject to the terms and conditions of version 2 of
* the GNU General Public License. See the file COPYING in the main
* directory of this archive for more details.
*
* IIO driver for VL6180 (7-bit I2C slave address 0x29)
*
* Range: 0 to 100mm
* ALS: < 1 Lux up to 100 kLux
* IR: 850nm
*
* TODO: irq, threshold events, continuous mode, hardware buffer
*/
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/mutex.h>
#include <linux/err.h>
#include <linux/of.h>
#include <linux/delay.h>
#include <linux/util_macros.h>
#include <linux/iio/iio.h>
#include <linux/iio/sysfs.h>
#define VL6180_DRV_NAME "vl6180"
/* Device identification register and value */
#define VL6180_MODEL_ID 0x000
#define VL6180_MODEL_ID_VAL 0xb4
/* Configuration registers */
#define VL6180_INTR_CONFIG 0x014
#define VL6180_INTR_CLEAR 0x015
#define VL6180_OUT_OF_RESET 0x016
#define VL6180_HOLD 0x017
#define VL6180_RANGE_START 0x018
#define VL6180_ALS_START 0x038
#define VL6180_ALS_GAIN 0x03f
#define VL6180_ALS_IT 0x040
/* Status registers */
#define VL6180_RANGE_STATUS 0x04d
#define VL6180_ALS_STATUS 0x04e
#define VL6180_INTR_STATUS 0x04f
/* Result value registers */
#define VL6180_ALS_VALUE 0x050
#define VL6180_RANGE_VALUE 0x062
#define VL6180_RANGE_RATE 0x066
/* bits of the RANGE_START and ALS_START register */
#define VL6180_MODE_CONT BIT(1) /* continuous mode */
#define VL6180_STARTSTOP BIT(0) /* start measurement, auto-reset */
/* bits of the INTR_STATUS and INTR_CONFIG register */
#define VL6180_ALS_READY BIT(5)
#define VL6180_RANGE_READY BIT(2)
/* bits of the INTR_CLEAR register */
#define VL6180_CLEAR_ERROR BIT(2)
#define VL6180_CLEAR_ALS BIT(1)
#define VL6180_CLEAR_RANGE BIT(0)
/* bits of the HOLD register */
#define VL6180_HOLD_ON BIT(0)
/* default value for the ALS_IT register */
#define VL6180_ALS_IT_100 0x63 /* 100 ms */
/* values for the ALS_GAIN register */
#define VL6180_ALS_GAIN_1 0x46
#define VL6180_ALS_GAIN_1_25 0x45
#define VL6180_ALS_GAIN_1_67 0x44
#define VL6180_ALS_GAIN_2_5 0x43
#define VL6180_ALS_GAIN_5 0x42
#define VL6180_ALS_GAIN_10 0x41
#define VL6180_ALS_GAIN_20 0x40
#define VL6180_ALS_GAIN_40 0x47
struct vl6180_data {
struct i2c_client *client;
struct mutex lock;
unsigned int als_gain_milli;
unsigned int als_it_ms;
};
enum { VL6180_ALS, VL6180_RANGE, VL6180_PROX };
/**
* struct vl6180_chan_regs - Registers for accessing channels
* @drdy_mask: Data ready bit in status register
* @start_reg: Conversion start register
* @value_reg: Result value register
* @word: Register word length
*/
struct vl6180_chan_regs {
u8 drdy_mask;
u16 start_reg, value_reg;
bool word;
};
static const struct vl6180_chan_regs vl6180_chan_regs_table[] = {
[VL6180_ALS] = {
.drdy_mask = VL6180_ALS_READY,
.start_reg = VL6180_ALS_START,
.value_reg = VL6180_ALS_VALUE,
.word = true,
},
[VL6180_RANGE] = {
.drdy_mask = VL6180_RANGE_READY,
.start_reg = VL6180_RANGE_START,
.value_reg = VL6180_RANGE_VALUE,
.word = false,
},
[VL6180_PROX] = {
.drdy_mask = VL6180_RANGE_READY,
.start_reg = VL6180_RANGE_START,
.value_reg = VL6180_RANGE_RATE,
.word = true,
},
};
static int vl6180_read(struct i2c_client *client, u16 cmd, void *databuf,
u8 len)
{
__be16 cmdbuf = cpu_to_be16(cmd);
struct i2c_msg msgs[2] = {
{ .addr = client->addr, .len = sizeof(cmdbuf), .buf = (u8 *) &cmdbuf },
{ .addr = client->addr, .len = len, .buf = databuf,
.flags = I2C_M_RD } };
int ret;
ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
if (ret < 0)
dev_err(&client->dev, "failed reading register 0x%04x\n", cmd);
return ret;
}
static int vl6180_read_byte(struct i2c_client *client, u16 cmd)
{
u8 data;
int ret;
ret = vl6180_read(client, cmd, &data, sizeof(data));
if (ret < 0)
return ret;
return data;
}
static int vl6180_read_word(struct i2c_client *client, u16 cmd)
{
__be16 data;
int ret;
ret = vl6180_read(client, cmd, &data, sizeof(data));
if (ret < 0)
return ret;
return be16_to_cpu(data);
}
static int vl6180_write_byte(struct i2c_client *client, u16 cmd, u8 val)
{
u8 buf[3];
struct i2c_msg msgs[1] = {
{ .addr = client->addr, .len = sizeof(buf), .buf = (u8 *) &buf } };
int ret;
buf[0] = cmd >> 8;
buf[1] = cmd & 0xff;
buf[2] = val;
ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
if (ret < 0) {
dev_err(&client->dev, "failed writing register 0x%04x\n", cmd);
return ret;
}
return 0;
}
static int vl6180_write_word(struct i2c_client *client, u16 cmd, u16 val)
{
__be16 buf[2];
struct i2c_msg msgs[1] = {
{ .addr = client->addr, .len = sizeof(buf), .buf = (u8 *) &buf } };
int ret;
buf[0] = cpu_to_be16(cmd);
buf[1] = cpu_to_be16(val);
ret = i2c_transfer(client->adapter, msgs, ARRAY_SIZE(msgs));
if (ret < 0) {
dev_err(&client->dev, "failed writing register 0x%04x\n", cmd);
return ret;
}
return 0;
}
static int vl6180_measure(struct vl6180_data *data, int addr)
{
struct i2c_client *client = data->client;
int tries = 20, ret;
u16 value;
mutex_lock(&data->lock);
/* Start single shot measurement */
ret = vl6180_write_byte(client,
vl6180_chan_regs_table[addr].start_reg, VL6180_STARTSTOP);
if (ret < 0)
goto fail;
while (tries--) {
ret = vl6180_read_byte(client, VL6180_INTR_STATUS);
if (ret < 0)
goto fail;
if (ret & vl6180_chan_regs_table[addr].drdy_mask)
break;
msleep(20);
}
if (tries < 0) {
ret = -EIO;
goto fail;
}
/* Read result value from appropriate registers */
ret = vl6180_chan_regs_table[addr].word ?
vl6180_read_word(client, vl6180_chan_regs_table[addr].value_reg) :
vl6180_read_byte(client, vl6180_chan_regs_table[addr].value_reg);
if (ret < 0)
goto fail;
value = ret;
/* Clear the interrupt flag after data read */
ret = vl6180_write_byte(client, VL6180_INTR_CLEAR,
VL6180_CLEAR_ERROR | VL6180_CLEAR_ALS | VL6180_CLEAR_RANGE);
if (ret < 0)
goto fail;
ret = value;
fail:
mutex_unlock(&data->lock);
return ret;
}
static const struct iio_chan_spec vl6180_channels[] = {
{
.type = IIO_LIGHT,
.address = VL6180_ALS,
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
BIT(IIO_CHAN_INFO_INT_TIME) |
BIT(IIO_CHAN_INFO_SCALE) |
BIT(IIO_CHAN_INFO_HARDWAREGAIN),
}, {
.type = IIO_DISTANCE,
.address = VL6180_RANGE,
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW) |
BIT(IIO_CHAN_INFO_SCALE),
}, {
.type = IIO_PROXIMITY,
.address = VL6180_PROX,
.info_mask_separate = BIT(IIO_CHAN_INFO_RAW),
}
};
/*
* Available Ambient Light Sensor gain settings, 1/1000th, and
* corresponding setting for the VL6180_ALS_GAIN register
*/
static const int vl6180_als_gain_tab[8] = {
1000, 1250, 1670, 2500, 5000, 10000, 20000, 40000
};
static const u8 vl6180_als_gain_tab_bits[8] = {
VL6180_ALS_GAIN_1, VL6180_ALS_GAIN_1_25,
VL6180_ALS_GAIN_1_67, VL6180_ALS_GAIN_2_5,
VL6180_ALS_GAIN_5, VL6180_ALS_GAIN_10,
VL6180_ALS_GAIN_20, VL6180_ALS_GAIN_40
};
static int vl6180_read_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int *val, int *val2, long mask)
{
struct vl6180_data *data = iio_priv(indio_dev);
int ret;
switch (mask) {
case IIO_CHAN_INFO_RAW:
ret = vl6180_measure(data, chan->address);
if (ret < 0)
return ret;
*val = ret;
return IIO_VAL_INT;
case IIO_CHAN_INFO_INT_TIME:
*val = data->als_it_ms;
*val2 = 1000;
return IIO_VAL_FRACTIONAL;
case IIO_CHAN_INFO_SCALE:
switch (chan->type) {
case IIO_LIGHT:
/* one ALS count is 0.32 Lux @ gain 1, IT 100 ms */
*val = 32000; /* 0.32 * 1000 * 100 */
*val2 = data->als_gain_milli * data->als_it_ms;
return IIO_VAL_FRACTIONAL;
case IIO_DISTANCE:
*val = 0; /* sensor reports mm, scale to meter */
*val2 = 1000;
break;
default:
return -EINVAL;
}
return IIO_VAL_INT_PLUS_MICRO;
case IIO_CHAN_INFO_HARDWAREGAIN:
*val = data->als_gain_milli;
*val2 = 1000;
return IIO_VAL_FRACTIONAL;
default:
return -EINVAL;
}
}
static IIO_CONST_ATTR(als_gain_available, "1 1.25 1.67 2.5 5 10 20 40");
static struct attribute *vl6180_attributes[] = {
&iio_const_attr_als_gain_available.dev_attr.attr,
NULL
};
static const struct attribute_group vl6180_attribute_group = {
.attrs = vl6180_attributes,
};
/* HOLD is needed before updating any config registers */
static int vl6180_hold(struct vl6180_data *data, bool hold)
{
return vl6180_write_byte(data->client, VL6180_HOLD,
hold ? VL6180_HOLD_ON : 0);
}
static int vl6180_set_als_gain(struct vl6180_data *data, int val, int val2)
{
int i, ret, gain;
if (val < 1 || val > 40)
return -EINVAL;
gain = (val * 1000000 + val2) / 1000;
if (gain < 1 || gain > 40000)
return -EINVAL;
i = find_closest(gain, vl6180_als_gain_tab,
ARRAY_SIZE(vl6180_als_gain_tab));
mutex_lock(&data->lock);
ret = vl6180_hold(data, true);
if (ret < 0)
goto fail;
ret = vl6180_write_byte(data->client, VL6180_ALS_GAIN,
vl6180_als_gain_tab_bits[i]);
if (ret >= 0)
data->als_gain_milli = vl6180_als_gain_tab[i];
fail:
vl6180_hold(data, false);
mutex_unlock(&data->lock);
return ret;
}
static int vl6180_set_it(struct vl6180_data *data, int val, int val2)
{
int ret, it_ms;
it_ms = (val2 + 500) / 1000; /* round to ms */
if (val != 0 || it_ms < 1 || it_ms > 512)
return -EINVAL;
mutex_lock(&data->lock);
ret = vl6180_hold(data, true);
if (ret < 0)
goto fail;
ret = vl6180_write_word(data->client, VL6180_ALS_IT, it_ms - 1);
if (ret >= 0)
data->als_it_ms = it_ms;
fail:
vl6180_hold(data, false);
mutex_unlock(&data->lock);
return ret;
}
static int vl6180_write_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int val, int val2, long mask)
{
struct vl6180_data *data = iio_priv(indio_dev);
switch (mask) {
case IIO_CHAN_INFO_INT_TIME:
return vl6180_set_it(data, val, val2);
case IIO_CHAN_INFO_HARDWAREGAIN:
if (chan->type != IIO_LIGHT)
return -EINVAL;
return vl6180_set_als_gain(data, val, val2);
default:
return -EINVAL;
}
}
static const struct iio_info vl6180_info = {
.read_raw = vl6180_read_raw,
.write_raw = vl6180_write_raw,
.attrs = &vl6180_attribute_group,
};
static int vl6180_init(struct vl6180_data *data)
{
struct i2c_client *client = data->client;
int ret;
ret = vl6180_read_byte(client, VL6180_MODEL_ID);
if (ret < 0)
return ret;
if (ret != VL6180_MODEL_ID_VAL) {
dev_err(&client->dev, "invalid model ID %02x\n", ret);
return -ENODEV;
}
ret = vl6180_hold(data, true);
if (ret < 0)
return ret;
ret = vl6180_read_byte(client, VL6180_OUT_OF_RESET);
if (ret < 0)
return ret;
/*
* Detect false reset condition here. This bit is always set when the
* system comes out of reset.
*/
if (ret != 0x01)
dev_info(&client->dev, "device is not fresh out of reset\n");
/* Enable ALS and Range ready interrupts */
ret = vl6180_write_byte(client, VL6180_INTR_CONFIG,
VL6180_ALS_READY | VL6180_RANGE_READY);
if (ret < 0)
return ret;
/* ALS integration time: 100ms */
data->als_it_ms = 100;
ret = vl6180_write_word(client, VL6180_ALS_IT, VL6180_ALS_IT_100);
if (ret < 0)
return ret;
/* ALS gain: 1 */
data->als_gain_milli = 1000;
ret = vl6180_write_byte(client, VL6180_ALS_GAIN, VL6180_ALS_GAIN_1);
if (ret < 0)
return ret;
ret = vl6180_write_byte(client, VL6180_OUT_OF_RESET, 0x00);
if (ret < 0)
return ret;
return vl6180_hold(data, false);
}
static int vl6180_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct vl6180_data *data;
struct iio_dev *indio_dev;
int ret;
indio_dev = devm_iio_device_alloc(&client->dev, sizeof(*data));
if (!indio_dev)
return -ENOMEM;
data = iio_priv(indio_dev);
i2c_set_clientdata(client, indio_dev);
data->client = client;
mutex_init(&data->lock);
indio_dev->dev.parent = &client->dev;
indio_dev->info = &vl6180_info;
indio_dev->channels = vl6180_channels;
indio_dev->num_channels = ARRAY_SIZE(vl6180_channels);
indio_dev->name = VL6180_DRV_NAME;
indio_dev->modes = INDIO_DIRECT_MODE;
ret = vl6180_init(data);
if (ret < 0)
return ret;
return devm_iio_device_register(&client->dev, indio_dev);
}
static const struct of_device_id vl6180_of_match[] = {
{ .compatible = "st,vl6180", },
{ },
};
MODULE_DEVICE_TABLE(of, vl6180_of_match);
static const struct i2c_device_id vl6180_id[] = {
{ "vl6180", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, vl6180_id);
static struct i2c_driver vl6180_driver = {
.driver = {
.name = VL6180_DRV_NAME,
.of_match_table = of_match_ptr(vl6180_of_match),
},
.probe = vl6180_probe,
.id_table = vl6180_id,
};
module_i2c_driver(vl6180_driver);
MODULE_AUTHOR("Peter Meerwald-Stadler <pmeerw@pmeerw.net>");
MODULE_AUTHOR("Manivannan Sadhasivam <manivannanece23@gmail.com>");
MODULE_DESCRIPTION("STMicro VL6180 ALS, range and proximity sensor driver");
MODULE_LICENSE("GPL");
| 23.518919 | 76 | 0.714548 | [
"model"
] |
192c8af7497f649ace2aa3fe00b6eddbf4fe26d4 | 3,774 | h | C | include/luxrays/core/virtualdevice.h | aedancullen/LuxCore | 2b2289ce985ddc1ba1a44f932e1f76ee9a1c3e3a | [
"Apache-2.0"
] | null | null | null | include/luxrays/core/virtualdevice.h | aedancullen/LuxCore | 2b2289ce985ddc1ba1a44f932e1f76ee9a1c3e3a | [
"Apache-2.0"
] | null | null | null | include/luxrays/core/virtualdevice.h | aedancullen/LuxCore | 2b2289ce985ddc1ba1a44f932e1f76ee9a1c3e3a | [
"Apache-2.0"
] | null | null | null | /***************************************************************************
* Copyright 1998-2018 by authors (see AUTHORS.txt) *
* *
* This file is part of LuxCoreRender. *
* *
* 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 _LUXRAYS_VIRTUALDEVICE_H
#define _LUXRAYS_VIRTUALDEVICE_H
#include <deque>
#include <boost/thread/mutex.hpp>
#include "luxrays/luxrays.h"
#include "luxrays/core/intersectiondevice.h"
namespace luxrays {
// The old VirtualM2OHardwareIntersectionDevice (Virtual Many to One hardware device)
// has been replaced by the new IntersectionDevice interface.
// The old VirtualM2MHardwareIntersectionDevice has been replaced by the following
// generic virtual device.
//------------------------------------------------------------------------------
// Virtual device (used mainly to see multiple device as a single one)
//------------------------------------------------------------------------------
class VirtualIntersectionDevice : public IntersectionDevice {
public:
VirtualIntersectionDevice(const std::vector<IntersectionDevice *> &devices,
const size_t index);
~VirtualIntersectionDevice();
const std::vector<IntersectionDevice *> &GetRealDevices() const { return realDevices; }
virtual void SetMaxStackSize(const size_t s);
virtual void SetQueueCount(const u_int count);
virtual void SetBufferCount(const u_int count);
virtual RayBuffer *NewRayBuffer();
virtual RayBuffer *NewRayBuffer(const size_t size);
virtual void PushRayBuffer(RayBuffer *rayBuffer, const u_int queueIndex = 0);
virtual RayBuffer *PopRayBuffer(const u_int queueIndex = 0);
virtual size_t GetQueueSize() { return pendingRayBufferDeviceIndex.size(); }
virtual bool TraceRay(const Ray *ray, RayHit *rayHit) {
// Update this device statistics
statsTotalSerialRayCount += 1.0;
// Using the underlay real devices mostly to account for
// statsTotalSerialRayCount statistics
traceRayRealDeviceIndex = (traceRayRealDeviceIndex + 1) % realDevices.size();
return realDevices[traceRayRealDeviceIndex]->TraceRay(ray, rayHit);
}
//--------------------------------------------------------------------------
// Statistics
//--------------------------------------------------------------------------
virtual double GetLoad() const;
virtual void ResetPerformaceStats();
protected:
void SetDataSet(DataSet *newDataSet);
void Start();
void Interrupt();
void Stop();
private:
std::vector<IntersectionDevice *> realDevices;
std::vector<std::deque<u_int> > pendingRayBufferDeviceIndex;
// This is used to spread the TraceRay() calls uniformly over
// all real devices
u_int traceRayRealDeviceIndex;
};
}
#endif /* _LUXRAYS_VIRTUALDEVICE_H */
| 40.148936 | 88 | 0.572072 | [
"vector"
] |
aab78d51640a9af63a12c7c554741a7ac6a9c4d5 | 1,026 | h | C | src/prod/src/Federation/MulticastTargetsHeader.h | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/Federation/MulticastTargetsHeader.h | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/Federation/MulticastTargetsHeader.h | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#pragma once
namespace Federation
{
class MulticastTargetsHeader : public Transport::MessageHeader<Transport::MessageHeaderId::MulticastTargets>, public Serialization::FabricSerializable
{
public:
MulticastTargetsHeader()
{
}
MulticastTargetsHeader(std::vector<NodeInstance> const & targets)
: targets_(targets)
{
}
std::vector<NodeInstance> MoveTargets()
{
return std::move(targets_);
}
void WriteTo(Common::TextWriter & w, Common::FormatOptions const &) const
{
w << targets_;
}
FABRIC_FIELDS_01(targets_);
private:
std::vector<NodeInstance> targets_;
};
}
| 27 | 154 | 0.546784 | [
"vector"
] |
aab7982d3505ff7e4908a9e98801ac5685608233 | 3,708 | h | C | bindings/ios/MEGAPricing.h | shuryanc/sdk | b7ece50cfc546fa6c3620c28ee4d9aa05059678b | [
"BSD-2-Clause"
] | 3 | 2015-07-25T02:22:33.000Z | 2021-04-09T14:22:12.000Z | bindings/ios/MEGAPricing.h | shuryanc/sdk | b7ece50cfc546fa6c3620c28ee4d9aa05059678b | [
"BSD-2-Clause"
] | null | null | null | bindings/ios/MEGAPricing.h | shuryanc/sdk | b7ece50cfc546fa6c3620c28ee4d9aa05059678b | [
"BSD-2-Clause"
] | 1 | 2021-02-02T08:10:49.000Z | 2021-02-02T08:10:49.000Z | /**
* @file MEGAPricing.h
* @brief Details about pricing plans
*
* (c) 2013-2014 by Mega Limited, Auckland, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK 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.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#import <Foundation/Foundation.h>
#import "MEGAAccountDetails.h"
/**
* @brief Details about pricing plans
*
* Use [MEGASdk pricing] to get the pricing plans to upgrade MEGA accounts
*/
@interface MEGAPricing : NSObject
/**
* @brief Number of available products to upgrade the account.
*/
@property (readonly, nonatomic) NSInteger products;
/**
* @brief Creates a copy of this MEGAPricing object.
*
* The resulting object is fully independent of the source MEGAPricing,
* it contains a copy of all internal attributes, so it will be valid after
* the original object is deleted.
*
* You are the owner of the returned object.
*
* @return Copy of the MEGAPricing object.
*/
- (instancetype)clone;
/**
* @brief Get the handle of a product.
* @param index Product index (from 0 to [MEGAPricing products]).
* @return Handle of the product.
* @see [MEGASdk getPaymentIdForProductHandle:].
*/
- (uint64_t)handleAtProductIndex:(NSInteger)index;
/**
* @brief Get the PRO level associated with the product.
* @param index Product index (from 0 to [MEGAPricing products]).
* @return PRO level associated with the product:
* Valid values are:
* - MEGAAccountTypeFree = 0
* - MEGAAccountTypeProI = 1
* - MEGAAccountTypeProII = 2
* - MEGAAccountTypeProIII = 3
* - MEGAAccountTypeLite = 4
* - MEGAAccountTypeBusiness = 100
*/
- (MEGAAccountType)proLevelAtProductIndex:(NSInteger)index;
/**
* @brief Get the number of GB of storage associated with the product.
* @param index Product index (from 0 to [MEGAPricing products]).
* @return number of GB of storage.
*/
- (NSInteger)storageGBAtProductIndex:(NSInteger)index;
/**
* @brief Get the number of GB of bandwidth associated with the product.
* @param index Product index (from 0 to [MEGAPricing products]).
* @return number of GB of bandwidth.
*/
- (NSInteger)transferGBAtProductIndex:(NSInteger)index;
/**
* @brief Get the duration of the product (in months).
* @param index Product index (from 0 to [MEGAPricing products]).
* @return duration of the product (in months).
*/
- (NSInteger)monthsAtProductIndex:(NSInteger)index;
/**
* @brief Get the price of the product (in cents).
* @param index Product index (from 0 to [MEGAPricing products]).
* @return Price of the product (in cents).
*/
- (NSInteger)amountAtProductIndex:(NSInteger)index;
/**
* @brief Get the currency associated with [MEGAPricing amountAtProductIndex:].
*
* @param index Product index (from 0 to [MEGAPricing products]).
* @return Currency associated with [MEGAPricing amountAtProductIndex:].
*/
- (NSString *)currencyAtProductIndex:(NSInteger)index;
/**
* @brief Get a description of the product
*
* @param index Product index (from 0 to [MEGAPricing products])
* @return Description of the product
*/
- (NSString *)descriptionAtProductIndex:(NSInteger)index;
/**
* @brief Get the iOS ID of the product
*
* @param index Product index (from 0 to [MEGAPricing products])
* @return iOS ID of the product
*/
- (NSString *)iOSIDAtProductIndex:(NSInteger)index;
@end
| 29.903226 | 79 | 0.724919 | [
"object"
] |
aac238ffdb3d74478c8ae03d871f8d041261cad8 | 30,300 | h | C | eventstream_rpc/include/aws/eventstreamrpc/EventStreamClient.h | awslabs/aws-iot-device-sdk-cpp-v2 | b90ff7d9d324508f789bbce855e12787aec3ff6b | [
"Apache-2.0"
] | 11 | 2019-03-14T06:20:44.000Z | 2019-10-14T21:55:17.000Z | eventstream_rpc/include/aws/eventstreamrpc/EventStreamClient.h | awslabs/aws-iot-device-sdk-cpp-v2 | b90ff7d9d324508f789bbce855e12787aec3ff6b | [
"Apache-2.0"
] | 50 | 2019-02-22T08:34:49.000Z | 2019-11-21T03:44:11.000Z | eventstream_rpc/include/aws/eventstreamrpc/EventStreamClient.h | awslabs/aws-iot-device-sdk-cpp-v2 | b90ff7d9d324508f789bbce855e12787aec3ff6b | [
"Apache-2.0"
] | 7 | 2019-02-28T17:32:18.000Z | 2019-09-27T18:02:46.000Z | #pragma once
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/eventstreamrpc/Exports.h>
#include <aws/crt/DateTime.h>
#include <aws/crt/JsonObject.h>
#include <aws/crt/StlAllocator.h>
#include <aws/crt/Types.h>
#include <aws/crt/UUID.h>
#include <aws/crt/io/EventLoopGroup.h>
#include <aws/crt/io/SocketOptions.h>
#include <aws/crt/io/TlsOptions.h>
#include <aws/crt/io/HostResolver.h>
#include <aws/event-stream/event_stream_rpc_client.h>
#include <aws/io/host_resolver.h>
#include <atomic>
#include <functional>
#include <future>
#include <memory>
namespace Aws
{
namespace Crt
{
namespace Io
{
class ClientBootstrap;
}
} // namespace Crt
namespace Eventstreamrpc
{
class EventStreamHeader;
class MessageAmendment;
class ClientOperation;
class ClientConnection;
class ClientContinuation;
using HeaderValueType = aws_event_stream_header_value_type;
using MessageType = aws_event_stream_rpc_message_type;
/**
* A callback prototype that is called upon flushing a message over the wire.
* @param errorCode A non-zero value if an error occured while attempting to flush the message.
*/
using OnMessageFlushCallback = std::function<void(int errorCode)>;
/**
* Allows the application to add headers and change the payload of the CONNECT
* packet sent out by the client.
* @return The `MessageAmendment` for the client to use during an attempt to connect.
*/
using ConnectMessageAmender = std::function<const MessageAmendment &(void)>;
/**
* A wrapper around an `aws_event_stream_header_value_pair` object.
*/
class AWS_EVENTSTREAMRPC_API EventStreamHeader final
{
public:
EventStreamHeader(const EventStreamHeader &lhs) noexcept;
EventStreamHeader(EventStreamHeader &&rhs) noexcept;
EventStreamHeader &operator=(const EventStreamHeader &lhs) noexcept;
~EventStreamHeader() noexcept;
EventStreamHeader(
const struct aws_event_stream_header_value_pair &header,
Crt::Allocator *allocator = Crt::g_allocator);
EventStreamHeader(const Crt::String &name, bool value);
EventStreamHeader(const Crt::String &name, int8_t value);
EventStreamHeader(const Crt::String &name, int16_t value);
EventStreamHeader(const Crt::String &name, int32_t value);
EventStreamHeader(const Crt::String &name, int64_t value);
EventStreamHeader(const Crt::String &name, Crt::DateTime &value);
EventStreamHeader(
const Crt::String &name,
const Crt::String &value,
Crt::Allocator *allocator = Crt::g_allocator) noexcept;
EventStreamHeader(const Crt::String &name, Crt::ByteBuf &value);
EventStreamHeader(const Crt::String &name, Crt::UUID value);
HeaderValueType GetHeaderValueType();
Crt::String GetHeaderName() const noexcept;
void SetHeaderName(const Crt::String &);
bool GetValueAsBoolean(bool &);
bool GetValueAsByte(int8_t &);
bool GetValueAsShort(int16_t &);
bool GetValueAsInt(int32_t &);
bool GetValueAsLong(int64_t &);
bool GetValueAsTimestamp(Crt::DateTime &);
bool GetValueAsString(Crt::String &) const noexcept;
bool GetValueAsBytes(Crt::ByteBuf &);
bool GetValueAsUUID(Crt::UUID &);
const struct aws_event_stream_header_value_pair *GetUnderlyingHandle() const;
bool operator==(const EventStreamHeader &other) const noexcept;
private:
Crt::Allocator *m_allocator;
Crt::ByteBuf m_valueByteBuf;
struct aws_event_stream_header_value_pair m_underlyingHandle;
};
/**
* A means to append headers or modify the payload of a message to be sent by the client.
* @note The exception specifiers for move, copy constructors & assignment operators are required since
* this class is usually wrapped with `Crt::Optional`.
*/
class AWS_EVENTSTREAMRPC_API MessageAmendment final
{
public:
MessageAmendment(const MessageAmendment &lhs);
MessageAmendment(MessageAmendment &&rhs);
MessageAmendment &operator=(const MessageAmendment &lhs);
~MessageAmendment() noexcept;
explicit MessageAmendment(Crt::Allocator *allocator = Crt::g_allocator) noexcept;
MessageAmendment(
const Crt::List<EventStreamHeader> &headers,
Crt::Optional<Crt::ByteBuf> &payload,
Crt::Allocator *allocator) noexcept;
MessageAmendment(
const Crt::List<EventStreamHeader> &headers,
Crt::Allocator *allocator = Crt::g_allocator) noexcept;
MessageAmendment(
Crt::List<EventStreamHeader> &&headers,
Crt::Allocator *allocator = Crt::g_allocator) noexcept;
MessageAmendment(const Crt::ByteBuf &payload, Crt::Allocator *allocator = Crt::g_allocator) noexcept;
void AddHeader(EventStreamHeader &&header) noexcept;
void SetPayload(const Crt::Optional<Crt::ByteBuf> &payload) noexcept;
const Crt::List<EventStreamHeader> &GetHeaders() const noexcept;
const Crt::Optional<Crt::ByteBuf> &GetPayload() const noexcept;
private:
Crt::List<EventStreamHeader> m_headers;
Crt::Optional<Crt::ByteBuf> m_payload;
Crt::Allocator *m_allocator;
};
/**
* Configuration structure holding all configurations relating to eventstream RPC connection establishment
*/
class ConnectionConfig
{
public:
ConnectionConfig() noexcept : m_clientBootstrap(nullptr), m_connectRequestCallback(nullptr) {}
Crt::Optional<Crt::String> GetHostName() const noexcept { return m_hostName; }
Crt::Optional<uint16_t> GetPort() const noexcept { return m_port; }
Crt::Optional<Crt::Io::SocketOptions> GetSocketOptions() const noexcept { return m_socketOptions; }
Crt::Optional<MessageAmendment> GetConnectAmendment() const noexcept { return m_connectAmendment; }
Crt::Optional<Crt::Io::TlsConnectionOptions> GetTlsConnectionOptions() const noexcept
{
return m_tlsConnectionOptions;
}
Crt::Io::ClientBootstrap *GetClientBootstrap() const noexcept { return m_clientBootstrap; }
OnMessageFlushCallback GetConnectRequestCallback() const noexcept { return m_connectRequestCallback; }
ConnectMessageAmender GetConnectMessageAmender() const noexcept
{
return [&](void) -> const MessageAmendment & { return m_connectAmendment; };
}
void SetHostName(Crt::String hostName) noexcept { m_hostName = hostName; }
void SetPort(uint16_t port) noexcept { m_port = port; }
void SetSocketOptions(const Crt::Io::SocketOptions &socketOptions) noexcept
{
m_socketOptions = socketOptions;
}
void SetConnectAmendment(const MessageAmendment &connectAmendment) noexcept
{
m_connectAmendment = connectAmendment;
}
void SetTlsConnectionOptions(Crt::Io::TlsConnectionOptions tlsConnectionOptions) noexcept
{
m_tlsConnectionOptions = tlsConnectionOptions;
}
void SetClientBootstrap(Crt::Io::ClientBootstrap *clientBootstrap) noexcept
{
m_clientBootstrap = clientBootstrap;
}
void SetConnectRequestCallback(OnMessageFlushCallback connectRequestCallback) noexcept
{
m_connectRequestCallback = connectRequestCallback;
}
protected:
Crt::Optional<Crt::String> m_hostName;
Crt::Optional<uint16_t> m_port;
Crt::Optional<Crt::Io::SocketOptions> m_socketOptions;
Crt::Optional<Crt::Io::TlsConnectionOptions> m_tlsConnectionOptions;
Crt::Io::ClientBootstrap *m_clientBootstrap;
MessageAmendment m_connectAmendment;
OnMessageFlushCallback m_connectRequestCallback;
};
enum EventStreamRpcStatusCode
{
EVENT_STREAM_RPC_SUCCESS = 0,
EVENT_STREAM_RPC_NULL_PARAMETER,
EVENT_STREAM_RPC_UNINITIALIZED,
EVENT_STREAM_RPC_ALLOCATION_ERROR,
EVENT_STREAM_RPC_CONNECTION_SETUP_FAILED,
EVENT_STREAM_RPC_CONNECTION_ACCESS_DENIED,
EVENT_STREAM_RPC_CONNECTION_ALREADY_ESTABLISHED,
EVENT_STREAM_RPC_CONNECTION_CLOSED,
EVENT_STREAM_RPC_CONTINUATION_CLOSED,
EVENT_STREAM_RPC_UNKNOWN_PROTOCOL_MESSAGE,
EVENT_STREAM_RPC_UNMAPPED_DATA,
EVENT_STREAM_RPC_UNSUPPORTED_CONTENT_TYPE,
EVENT_STREAM_RPC_CRT_ERROR
};
struct RpcError
{
EventStreamRpcStatusCode baseStatus;
int crtError;
operator bool() const noexcept { return baseStatus == EVENT_STREAM_RPC_SUCCESS; }
Crt::String StatusToString();
};
class AWS_EVENTSTREAMRPC_API ConnectionLifecycleHandler
{
public:
/**
* This callback is only invoked upon receiving a CONNECT_ACK with the
* CONNECTION_ACCEPTED flag set by the server. Therefore, once this callback
* is invoked, the `ClientConnection` is ready to be used for sending messages.
*/
virtual void OnConnectCallback();
/**
* Invoked upon connection shutdown.
* @param status The status upon disconnection. It can be treated as a bool
* with true implying a successful disconnection.
*/
virtual void OnDisconnectCallback(RpcError status);
/**
* Invoked upon receiving an error. Use the return value to determine
* whether or not to force the connection to close. Keep in mind that once
* closed, the `ClientConnection` can no longer send messages.
* @param status The status upon disconnection. It can be treated as a bool
* with true implying a successful disconnection.
*/
virtual bool OnErrorCallback(RpcError status);
/**
* Invoked upon receiving a ping from the server. The `headers` and `payload`
* refer to what is contained in the ping message.
*/
virtual void OnPingCallback(
const Crt::List<EventStreamHeader> &headers,
const Crt::Optional<Crt::ByteBuf> &payload);
};
/* User data passed to callbacks for a new stream. */
class ContinuationCallbackData
{
public:
ContinuationCallbackData(
ClientContinuation *clientContinuation,
Crt::Allocator *allocator = Crt::g_allocator) noexcept
: clientContinuation(clientContinuation), allocator(allocator)
{
continuationDestroyed = false;
}
ContinuationCallbackData(const ContinuationCallbackData &lhs) noexcept = delete;
bool continuationDestroyed;
std::mutex callbackMutex;
ClientContinuation *clientContinuation;
Crt::Allocator *allocator;
};
class AWS_EVENTSTREAMRPC_API ClientContinuationHandler
{
public:
/**
* Invoked when a message is received on this continuation.
*/
virtual void OnContinuationMessage(
const Crt::List<EventStreamHeader> &headers,
const Crt::Optional<Crt::ByteBuf> &payload,
MessageType messageType,
uint32_t messageFlags) = 0;
/**
* Invoked when the continuation is closed.
*
* Once the continuation is closed, no more messages may be sent or received.
* The continuation is closed when a message is sent or received with
* the TERMINATE_STREAM flag, or when the connection shuts down.
*/
virtual void OnContinuationClosed() = 0;
virtual ~ClientContinuationHandler() noexcept;
private:
friend class ClientContinuation;
ContinuationCallbackData *m_callbackData;
};
class AWS_EVENTSTREAMRPC_API ClientContinuation final
{
public:
ClientContinuation(
ClientConnection *connection,
ClientContinuationHandler &continuationHandler,
Crt::Allocator *allocator) noexcept;
~ClientContinuation() noexcept;
std::future<RpcError> Activate(
const Crt::String &operation,
const Crt::List<EventStreamHeader> &headers,
const Crt::Optional<Crt::ByteBuf> &payload,
MessageType messageType,
uint32_t messageFlags,
OnMessageFlushCallback onMessageFlushCallback) noexcept;
bool IsClosed() noexcept;
void Release() noexcept;
std::future<RpcError> SendMessage(
const Crt::List<EventStreamHeader> &headers,
const Crt::Optional<Crt::ByteBuf> &payload,
MessageType messageType,
uint32_t messageFlags,
OnMessageFlushCallback onMessageFlushCallback) noexcept;
private:
friend class ClientOperation;
Crt::Allocator *m_allocator;
ClientContinuationHandler &m_continuationHandler;
struct aws_event_stream_rpc_client_continuation_token *m_continuationToken;
ContinuationCallbackData *m_callbackData;
static void s_onContinuationMessage(
struct aws_event_stream_rpc_client_continuation_token *continuationToken,
const struct aws_event_stream_rpc_message_args *messageArgs,
void *userData) noexcept;
static void s_onContinuationClosed(
struct aws_event_stream_rpc_client_continuation_token *continuationToken,
void *userData) noexcept;
};
class AWS_EVENTSTREAMRPC_API AbstractShapeBase
{
public:
AbstractShapeBase() noexcept;
virtual ~AbstractShapeBase() noexcept;
static void s_customDeleter(AbstractShapeBase *shape) noexcept;
virtual void SerializeToJsonObject(Crt::JsonObject &payloadObject) const = 0;
virtual Crt::String GetModelName() const noexcept = 0;
protected:
Crt::Allocator *m_allocator;
};
class AWS_EVENTSTREAMRPC_API OperationError : public AbstractShapeBase
{
public:
explicit OperationError() noexcept;
static void s_customDeleter(OperationError *shape) noexcept;
virtual void SerializeToJsonObject(Crt::JsonObject &payloadObject) const override;
virtual Crt::Optional<Crt::String> GetMessage() noexcept = 0;
};
/**
* Base class for all operation stream handlers.
* For operations with a streaming response (0+ messages that may arrive
* after the initial response).
*/
class AWS_EVENTSTREAMRPC_API StreamResponseHandler
{
public:
/**
* Invoked when stream is closed, so no more messages will be received.
*/
virtual void OnStreamClosed();
protected:
friend class ClientOperation;
/**
* Invoked when a message is received on this continuation.
*/
virtual void OnStreamEvent(Crt::ScopedResource<AbstractShapeBase> response);
/**
* Invoked when a message is received on this continuation but results in an error.
*
* This callback can return true so that the stream is closed afterwards.
*/
virtual bool OnStreamError(Crt::ScopedResource<OperationError> operationError, RpcError rpcError);
};
enum ResultType
{
OPERATION_RESPONSE,
OPERATION_ERROR,
RPC_ERROR
};
class AWS_EVENTSTREAMRPC_API TaggedResult
{
public:
TaggedResult() noexcept;
explicit TaggedResult(Crt::ScopedResource<AbstractShapeBase> response) noexcept;
explicit TaggedResult(Crt::ScopedResource<OperationError> error) noexcept;
explicit TaggedResult(RpcError rpcError) noexcept;
TaggedResult(TaggedResult &&rhs) noexcept;
TaggedResult &operator=(TaggedResult &&rhs) noexcept;
~TaggedResult() noexcept;
/**
* @return true if the response is associated with an expected response;
* false if the response is associated with an error.
*/
operator bool() const noexcept;
AbstractShapeBase *GetOperationResponse() const noexcept;
OperationError *GetOperationError() const noexcept;
RpcError GetRpcError() const noexcept;
ResultType GetResultType() const noexcept { return m_responseType; }
private:
union AWS_EVENTSTREAMRPC_API OperationResult {
OperationResult(Crt::ScopedResource<AbstractShapeBase> &&response) noexcept
: m_response(std::move(response))
{
}
OperationResult(Crt::ScopedResource<OperationError> &&error) noexcept : m_error(std::move(error)) {}
OperationResult() noexcept : m_response(nullptr) {}
~OperationResult() noexcept {};
Crt::ScopedResource<AbstractShapeBase> m_response;
Crt::ScopedResource<OperationError> m_error;
};
ResultType m_responseType;
OperationResult m_operationResult;
RpcError m_rpcError;
};
using ExpectedResponseFactory = std::function<
Crt::ScopedResource<AbstractShapeBase>(const Crt::StringView &payload, Crt::Allocator *allocator)>;
using ErrorResponseFactory = std::function<
Crt::ScopedResource<OperationError>(const Crt::StringView &payload, Crt::Allocator *allocator)>;
using LoneResponseRetriever = std::function<ExpectedResponseFactory(const Crt::String &modelName)>;
using StreamingResponseRetriever = std::function<ExpectedResponseFactory(const Crt::String &modelName)>;
using ErrorResponseRetriever = std::function<ErrorResponseFactory(const Crt::String &modelName)>;
class AWS_EVENTSTREAMRPC_API ResponseRetriever
{
/* An interface shared by all operations for retrieving the response object given the model name. */
public:
virtual ExpectedResponseFactory GetInitialResponseFromModelName(const Crt::String &modelName) const
noexcept = 0;
virtual ExpectedResponseFactory GetStreamingResponseFromModelName(const Crt::String &modelName) const
noexcept = 0;
virtual ErrorResponseFactory GetOperationErrorFromModelName(const Crt::String &modelName) const
noexcept = 0;
};
class AWS_EVENTSTREAMRPC_API ServiceModel
{
public:
virtual Crt::ScopedResource<OperationError> AllocateOperationErrorFromPayload(
const Crt::String &errorModelName,
Crt::StringView stringView,
Crt::Allocator *allocator) const noexcept = 0;
};
class AWS_EVENTSTREAMRPC_API OperationModelContext
{
public:
OperationModelContext(const ServiceModel &serviceModel) noexcept;
virtual Crt::ScopedResource<AbstractShapeBase> AllocateInitialResponseFromPayload(
Crt::StringView stringView,
Crt::Allocator *allocator) const noexcept = 0;
virtual Crt::ScopedResource<AbstractShapeBase> AllocateStreamingResponseFromPayload(
Crt::StringView stringView,
Crt::Allocator *allocator) const noexcept = 0;
virtual Crt::String GetInitialResponseModelName() const noexcept = 0;
virtual Crt::String GetRequestModelName() const noexcept = 0;
virtual Crt::Optional<Crt::String> GetStreamingResponseModelName() const noexcept = 0;
virtual Crt::String GetOperationName() const noexcept = 0;
Crt::ScopedResource<OperationError> AllocateOperationErrorFromPayload(
const Crt::String &errorModelName,
Crt::StringView stringView,
Crt::Allocator *allocator) const noexcept
{
return m_serviceModel.AllocateOperationErrorFromPayload(errorModelName, stringView, allocator);
}
private:
const ServiceModel &m_serviceModel;
};
class AWS_EVENTSTREAMRPC_API ClientOperation : public ClientContinuationHandler
{
public:
ClientOperation(
ClientConnection &connection,
std::shared_ptr<StreamResponseHandler> streamHandler,
const OperationModelContext &operationModelContext,
Crt::Allocator *allocator) noexcept;
~ClientOperation() noexcept;
ClientOperation(const ClientOperation &clientOperation) noexcept = delete;
ClientOperation(ClientOperation &&clientOperation) noexcept = delete;
bool operator=(const ClientOperation &clientOperation) noexcept = delete;
bool operator=(ClientOperation &&clientOperation) noexcept = delete;
std::future<RpcError> Close(OnMessageFlushCallback onMessageFlushCallback = nullptr) noexcept;
std::future<TaggedResult> GetOperationResult() noexcept;
protected:
std::future<RpcError> Activate(
const AbstractShapeBase *shape,
OnMessageFlushCallback onMessageFlushCallback) noexcept;
std::future<RpcError> SendStreamEvent(
AbstractShapeBase *shape,
OnMessageFlushCallback onMessageFlushCallback) noexcept;
virtual Crt::String GetModelName() const noexcept = 0;
const OperationModelContext &m_operationModelContext;
private:
EventStreamRpcStatusCode HandleData(const Crt::Optional<Crt::ByteBuf> &payload);
EventStreamRpcStatusCode HandleError(
const Crt::String &modelName,
const Crt::Optional<Crt::ByteBuf> &payload,
uint32_t messageFlags);
/**
* Invoked when a message is received on this continuation.
*/
void OnContinuationMessage(
const Crt::List<EventStreamHeader> &headers,
const Crt::Optional<Crt::ByteBuf> &payload,
MessageType messageType,
uint32_t messageFlags) override;
/**
* Invoked when the continuation is closed.
*
* Once the continuation is closed, no more messages may be sent or received.
* The continuation is closed when a message is sent or received with
* the TERMINATE_STREAM flag, or when the connection shuts down.
*/
void OnContinuationClosed() override;
const EventStreamHeader *GetHeaderByName(
const Crt::List<EventStreamHeader> &headers,
const Crt::String &name) noexcept;
enum CloseState
{
WONT_CLOSE = 0,
WILL_CLOSE,
ALREADY_CLOSED
};
uint32_t m_messageCount;
Crt::Allocator *m_allocator;
std::shared_ptr<StreamResponseHandler> m_streamHandler;
ClientContinuation m_clientContinuation;
/* This mutex protects m_resultReceived & m_closeState. */
std::mutex m_continuationMutex;
bool m_resultReceived;
std::promise<TaggedResult> m_initialResponsePromise;
std::atomic_int m_expectedCloses;
std::atomic_bool m_streamClosedCalled;
std::condition_variable m_closeReady;
};
class AWS_EVENTSTREAMRPC_API ClientConnection final
{
public:
ClientConnection(Crt::Allocator *allocator = Crt::g_allocator) noexcept;
~ClientConnection() noexcept;
ClientConnection(const ClientConnection &) noexcept = delete;
ClientConnection &operator=(const ClientConnection &) noexcept = delete;
ClientConnection(ClientConnection &&) noexcept;
ClientConnection &operator=(ClientConnection &&) noexcept;
std::future<RpcError> Connect(
const ConnectionConfig &connectionOptions,
ConnectionLifecycleHandler *connectionLifecycleHandler,
Crt::Io::ClientBootstrap &clientBootstrap) noexcept;
std::future<RpcError> SendPing(
const Crt::List<EventStreamHeader> &headers,
const Crt::Optional<Crt::ByteBuf> &payload,
OnMessageFlushCallback onMessageFlushCallback) noexcept;
std::future<RpcError> SendPingResponse(
const Crt::List<EventStreamHeader> &headers,
const Crt::Optional<Crt::ByteBuf> &payload,
OnMessageFlushCallback onMessageFlushCallback) noexcept;
ClientContinuation NewStream(ClientContinuationHandler &clientContinuationHandler) noexcept;
void Close() noexcept;
bool IsOpen() const noexcept
{
if (this->m_underlyingConnection == nullptr)
{
return false;
}
else
{
return aws_event_stream_rpc_client_connection_is_open(this->m_underlyingConnection);
}
}
/**
* @return true if the instance is in a valid state, false otherwise.
*/
operator bool() const noexcept { return IsOpen(); }
private:
friend class ClientContinuation;
friend std::future<RpcError> ClientOperation::Close(OnMessageFlushCallback onMessageFlushCallback) noexcept;
enum ClientState
{
DISCONNECTED = 1,
CONNECTING_SOCKET,
WAITING_FOR_CONNECT_ACK,
CONNECTED,
DISCONNECTING,
};
/* This recursive mutex protects m_clientState & m_connectionWillSetup */
std::recursive_mutex m_stateMutex;
Crt::Allocator *m_allocator;
struct aws_event_stream_rpc_client_connection *m_underlyingConnection;
ClientState m_clientState;
ConnectionLifecycleHandler *m_lifecycleHandler;
ConnectMessageAmender m_connectMessageAmender;
std::promise<void> m_connectionSetupPromise;
bool m_connectionWillSetup;
std::promise<RpcError> m_connectAckedPromise;
std::promise<RpcError> m_closedPromise;
bool m_onConnectCalled;
RpcError m_closeReason;
OnMessageFlushCallback m_onConnectRequestCallback;
Crt::Io::SocketOptions m_socketOptions;
ConnectionConfig m_connectionConfig;
std::future<RpcError> SendProtocolMessage(
const Crt::List<EventStreamHeader> &headers,
const Crt::Optional<Crt::ByteBuf> &payload,
MessageType messageType,
uint32_t messageFlags,
OnMessageFlushCallback onMessageFlushCallback) noexcept;
static void s_onConnectionShutdown(
struct aws_event_stream_rpc_client_connection *connection,
int errorCode,
void *userData) noexcept;
static void s_onConnectionSetup(
struct aws_event_stream_rpc_client_connection *connection,
int errorCode,
void *userData) noexcept;
static void s_onProtocolMessage(
struct aws_event_stream_rpc_client_connection *connection,
const struct aws_event_stream_rpc_message_args *messageArgs,
void *userData) noexcept;
static void s_protocolMessageCallback(int errorCode, void *userData) noexcept;
static std::future<RpcError> s_sendProtocolMessage(
ClientConnection *connection,
const Crt::List<EventStreamHeader> &headers,
const Crt::Optional<Crt::ByteBuf> &payload,
MessageType messageType,
uint32_t messageFlags,
OnMessageFlushCallback onMessageFlushCallback) noexcept;
static std::future<RpcError> s_sendPing(
ClientConnection *connection,
const Crt::List<EventStreamHeader> &headers,
const Crt::Optional<Crt::ByteBuf> &payload,
OnMessageFlushCallback onMessageFlushCallback) noexcept;
static std::future<RpcError> s_sendPingResponse(
ClientConnection *connection,
const Crt::List<EventStreamHeader> &headers,
const Crt::Optional<Crt::ByteBuf> &payload,
OnMessageFlushCallback onMessageFlushCallback) noexcept;
};
} // namespace Eventstreamrpc
} // namespace Aws
| 44.428152 | 120 | 0.62231 | [
"object",
"shape",
"model"
] |
aac6d7be6938d6c09067a7064ff7eb3c6400c412 | 8,618 | h | C | cc/animation/animation.h | tmpsantos/chromium | 802d4aeeb33af25c01ee5994037bbf14086d4ac0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | cc/animation/animation.h | tmpsantos/chromium | 802d4aeeb33af25c01ee5994037bbf14086d4ac0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | cc/animation/animation.h | tmpsantos/chromium | 802d4aeeb33af25c01ee5994037bbf14086d4ac0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T07:23:37.000Z | 2020-11-04T07:23:37.000Z | // Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CC_ANIMATION_ANIMATION_H_
#define CC_ANIMATION_ANIMATION_H_
#include "base/basictypes.h"
#include "base/memory/scoped_ptr.h"
#include "base/time/time.h"
#include "cc/base/cc_export.h"
namespace cc {
class AnimationCurve;
// An Animation contains all the state required to play an AnimationCurve.
// Specifically, the affected property, the run state (paused, finished, etc.),
// loop count, last pause time, and the total time spent paused.
class CC_EXPORT Animation {
public:
// Animations begin in the 'WaitingForTargetAvailability' state. An Animation
// waiting for target availibility will run as soon as its target property
// is free (and all the animations animating with it are also able to run).
// When this time arrives, the controller will move the animation into the
// Starting state, and then into the Running state. Running animations may
// toggle between Running and Paused, and may be stopped by moving into either
// the Aborted or Finished states. A Finished animation was allowed to run to
// completion, but an Aborted animation was not.
enum RunState {
WaitingForTargetAvailability = 0,
WaitingForDeletion,
Starting,
Running,
Paused,
Finished,
Aborted,
// This sentinel must be last.
RunStateEnumSize
};
enum TargetProperty {
Transform = 0,
Opacity,
Filter,
ScrollOffset,
BackgroundColor,
// This sentinel must be last.
TargetPropertyEnumSize
};
enum Direction { Normal, Reverse, Alternate, AlternateReverse };
static scoped_ptr<Animation> Create(scoped_ptr<AnimationCurve> curve,
int animation_id,
int group_id,
TargetProperty target_property);
virtual ~Animation();
int id() const { return id_; }
int group() const { return group_; }
TargetProperty target_property() const { return target_property_; }
RunState run_state() const { return run_state_; }
void SetRunState(RunState run_state, base::TimeTicks monotonic_time);
// This is the number of times that the animation will play. If this
// value is zero the animation will not play. If it is negative, then
// the animation will loop indefinitely.
double iterations() const { return iterations_; }
void set_iterations(double n) { iterations_ = n; }
base::TimeTicks start_time() const { return start_time_; }
void set_start_time(base::TimeTicks monotonic_time) {
start_time_ = monotonic_time;
}
bool has_set_start_time() const { return !start_time_.is_null(); }
base::TimeDelta time_offset() const { return time_offset_; }
void set_time_offset(base::TimeDelta monotonic_time) {
time_offset_ = monotonic_time;
}
void Suspend(base::TimeTicks monotonic_time);
void Resume(base::TimeTicks monotonic_time);
Direction direction() { return direction_; }
void set_direction(Direction direction) { direction_ = direction; }
double playback_rate() { return playback_rate_; }
void set_playback_rate(double playback_rate) {
playback_rate_ = playback_rate;
}
bool IsFinishedAt(base::TimeTicks monotonic_time) const;
bool is_finished() const {
return run_state_ == Finished ||
run_state_ == Aborted ||
run_state_ == WaitingForDeletion;
}
AnimationCurve* curve() { return curve_.get(); }
const AnimationCurve* curve() const { return curve_.get(); }
// If this is true, even if the animation is running, it will not be tickable
// until it is given a start time. This is true for animations running on the
// main thread.
bool needs_synchronized_start_time() const {
return needs_synchronized_start_time_;
}
void set_needs_synchronized_start_time(bool needs_synchronized_start_time) {
needs_synchronized_start_time_ = needs_synchronized_start_time;
}
// This is true for animations running on the main thread when the Finished
// event sent by the corresponding impl animation has been received.
bool received_finished_event() const {
return received_finished_event_;
}
void set_received_finished_event(bool received_finished_event) {
received_finished_event_ = received_finished_event;
}
// Takes the given absolute time, and using the start time and the number
// of iterations, returns the relative time in the current iteration.
double TrimTimeToCurrentIteration(base::TimeTicks monotonic_time) const;
scoped_ptr<Animation> CloneAndInitialize(RunState initial_run_state) const;
bool is_controlling_instance() const { return is_controlling_instance_; }
void PushPropertiesTo(Animation* other) const;
void set_is_impl_only(bool is_impl_only) { is_impl_only_ = is_impl_only; }
bool is_impl_only() const { return is_impl_only_; }
void set_affects_active_observers(bool affects_active_observers) {
affects_active_observers_ = affects_active_observers;
}
bool affects_active_observers() const { return affects_active_observers_; }
void set_affects_pending_observers(bool affects_pending_observers) {
affects_pending_observers_ = affects_pending_observers;
}
bool affects_pending_observers() const { return affects_pending_observers_; }
private:
Animation(scoped_ptr<AnimationCurve> curve,
int animation_id,
int group_id,
TargetProperty target_property);
scoped_ptr<AnimationCurve> curve_;
// IDs are not necessarily unique.
int id_;
// Animations that must be run together are called 'grouped' and have the same
// group id. Grouped animations are guaranteed to start at the same time and
// no other animations may animate any of the group's target properties until
// all animations in the group have finished animating. Note: an active
// animation's group id and target property uniquely identify that animation.
int group_;
TargetProperty target_property_;
RunState run_state_;
double iterations_;
base::TimeTicks start_time_;
Direction direction_;
double playback_rate_;
// The time offset effectively pushes the start of the animation back in time.
// This is used for resuming paused animations -- an animation is added with a
// non-zero time offset, causing the animation to skip ahead to the desired
// point in time.
base::TimeDelta time_offset_;
bool needs_synchronized_start_time_;
bool received_finished_event_;
// When an animation is suspended, it behaves as if it is paused and it also
// ignores all run state changes until it is resumed. This is used for testing
// purposes.
bool suspended_;
// These are used in TrimTimeToCurrentIteration to account for time
// spent while paused. This is not included in AnimationState since it
// there is absolutely no need for clients of this controller to know
// about these values.
base::TimeTicks pause_time_;
base::TimeDelta total_paused_time_;
// Animations lead dual lives. An active animation will be conceptually owned
// by two controllers, one on the impl thread and one on the main. In reality,
// there will be two separate Animation instances for the same animation. They
// will have the same group id and the same target property (these two values
// uniquely identify an animation). The instance on the impl thread is the
// instance that ultimately controls the values of the animating layer and so
// we will refer to it as the 'controlling instance'.
bool is_controlling_instance_;
bool is_impl_only_;
// When pushed from a main-thread controller to a compositor-thread
// controller, an animation will initially only affect pending observers
// (corresponding to layers in the pending tree). Animations that only
// affect pending observers are able to reach the Starting state and tick
// pending observers, but cannot proceed any further and do not tick active
// observers. After activation, such animations affect both kinds of observers
// and are able to proceed past the Starting state. When the removal of
// an animation is pushed from a main-thread controller to a
// compositor-thread controller, this initially only makes the animation
// stop affecting pending observers. After activation, such animations no
// longer affect any observers, and are deleted.
bool affects_active_observers_;
bool affects_pending_observers_;
DISALLOW_COPY_AND_ASSIGN(Animation);
};
} // namespace cc
#endif // CC_ANIMATION_ANIMATION_H_
| 38.132743 | 80 | 0.745997 | [
"transform"
] |
aac8b0aba0b938e0768f472cc325f6ff2248b0f3 | 29,727 | h | C | src/core/hw/gfxip/rpm/rsrcProcMgr.h | inequation/pal | 1f6c2382823451d232dfb86dd54e7c63673d73e8 | [
"MIT"
] | 1 | 2021-11-27T15:15:29.000Z | 2021-11-27T15:15:29.000Z | src/core/hw/gfxip/rpm/rsrcProcMgr.h | inequation/pal | 1f6c2382823451d232dfb86dd54e7c63673d73e8 | [
"MIT"
] | null | null | null | src/core/hw/gfxip/rpm/rsrcProcMgr.h | inequation/pal | 1f6c2382823451d232dfb86dd54e7c63673d73e8 | [
"MIT"
] | null | null | null | /*
***********************************************************************************************************************
*
* Copyright (c) 2015-2021 Advanced Micro Devices, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
**********************************************************************************************************************/
#pragma once
#include "core/hw/gfxip/rpm/g_rpmComputePipelineInit.h"
#include "core/hw/gfxip/rpm/g_rpmGfxPipelineInit.h"
#include "palCmdBuffer.h"
namespace Pal
{
class CmdStream;
class ColorBlendState;
enum CopyImageFlags : uint32;
class DepthStencilState;
class GfxCmdBuffer;
class GfxImage;
class GpuMemory;
class Image;
class IndirectCmdGenerator;
class Pipeline;
struct ImageCopyRegion;
struct ImageResolveRegion;
struct MemoryCopyRegion;
struct MemoryImageCopyRegion;
class MsaaState;
static constexpr uint32 MaxLog2AaSamples = 4; // Max AA sample rate is 16x.
static constexpr uint32 MaxLog2AaFragments = 3; // Max fragments is 8.
// Specifies image region for metadata fixup pre/post all RPM copies.
struct ImageFixupRegion
{
SubresId subres;
Offset3d offset;
Extent3d extent;
uint32 numSlices;
};
// Which engine should be used for RPM copies into images
enum class ImageCopyEngine : uint32
{
Graphics = 0x1,
Compute = 0x2,
ComputeVrsDirty = 0x3,
};
// Specifies gpu addresses that are used as input to CmdGenerateIndirectCmds
struct GenerateInfo
{
GfxCmdBuffer* pCmdBuffer;
const Pipeline* pPipeline;
const IndirectCmdGenerator& generator;
uint32 indexBufSize; // Maximum number of indices in the bound index buffer.
uint32 maximumCount; // Maximum number of draw or dispatch commands.
gpusize argsGpuAddr; // Argument buffer GPU address.
gpusize countGpuAddr; // GPU address of the memory containing the actual command
// count to generate.
};
// =====================================================================================================================
// Resource Processing Manager: Contains resource modification and preparation logic. RPM and its subclasses issue
// draws, dispatches, and other operations to manipulate resource contents and hardware state.
class RsrcProcMgr
{
public:
static constexpr bool UseMipLevelInSrd = true;
static constexpr bool OptimizeLinearDestGraphicsCopy = true;
explicit RsrcProcMgr(GfxDevice* pDevice);
virtual ~RsrcProcMgr();
Result EarlyInit();
Result LateInit();
void Cleanup();
void CmdCopyImage(
GfxCmdBuffer* pCmdBuffer,
const Image& srcImage,
ImageLayout srcImageLayout,
const Image& dstImage,
ImageLayout dstImageLayout,
uint32 regionCount,
const ImageCopyRegion* pRegions,
const Rect* pScissorRect,
uint32 flags) const;
virtual void CmdCopyMemoryToImage(
GfxCmdBuffer* pCmdBuffer,
const GpuMemory& srcGpuMemory,
const Image& dstImage,
ImageLayout dstImageLayout,
uint32 regionCount,
const MemoryImageCopyRegion* pRegions,
bool includePadding) const;
virtual void CmdCopyImageToMemory(
GfxCmdBuffer* pCmdBuffer,
const Image& srcImage,
ImageLayout srcImageLayout,
const GpuMemory& dstGpuMemory,
uint32 regionCount,
const MemoryImageCopyRegion* pRegions,
bool includePadding) const;
void CmdCopyTypedBuffer(
GfxCmdBuffer* pCmdBuffer,
const GpuMemory& srcGpuMemory,
const GpuMemory& dstGpuMemory,
uint32 regionCount,
const TypedBufferCopyRegion* pRegions) const;
void CmdScaledCopyImage(
GfxCmdBuffer* pCmdBuffer,
const ScaledCopyInfo& copyInfo) const;
void CmdGenerateMipmaps(
GfxCmdBuffer* pCmdBuffer,
const GenMipmapsInfo& genInfo) const;
void CmdColorSpaceConversionCopy(
GfxCmdBuffer* pCmdBuffer,
const Image& srcImage,
ImageLayout srcImageLayout,
const Image& dstImage,
ImageLayout dstImageLayout,
uint32 regionCount,
const ColorSpaceConversionRegion* pRegions,
TexFilter filter,
const ColorSpaceConversionTable& cscTable) const;
virtual void CmdFillMemory(
GfxCmdBuffer* pCmdBuffer,
bool saveRestoreComputeState,
const GpuMemory& dstGpuMemory,
gpusize dstOffset,
gpusize fillSize,
uint32 data) const;
void CmdClearBoundDepthStencilTargets(
GfxCmdBuffer* pCmdBuffer,
float depth,
uint8 stencil,
uint8 stencilWriteMask,
uint32 samples,
uint32 fragments,
DepthStencilSelectFlags flag,
uint32 regionCount,
const ClearBoundTargetRegion* pClearRegions) const;
void CmdClearDepthStencil(
GfxCmdBuffer* pCmdBuffer,
const Image& dstImage,
ImageLayout depthLayout,
ImageLayout stencilLayout,
float depth,
uint8 stencil,
uint8 stencilWriteMask,
uint32 rangeCount,
const SubresRange* pRanges,
uint32 rectCount,
const Rect* pRects,
uint32 flags) const;
void CmdClearColorBuffer(
GfxCmdBuffer* pCmdBuffer,
const IGpuMemory& dstGpuMemory,
const ClearColor& color,
SwizzledFormat bufferFormat,
uint32 bufferOffset,
uint32 bufferExtent,
uint32 rangeCount = 0,
const Range* pRanges = nullptr) const;
void CmdClearBoundColorTargets(
GfxCmdBuffer* pCmdBuffer,
uint32 colorTargetCount,
const BoundColorTarget* pBoundColorTargets,
uint32 regionCount,
const ClearBoundTargetRegion* pBoxes) const;
void CmdClearColorImage(
GfxCmdBuffer* pCmdBuffer,
const Image& dstImage,
ImageLayout dstImageLayout,
const ClearColor& color,
uint32 rangeCount,
const SubresRange* pRanges,
uint32 boxCount,
const Box* pBoxes,
uint32 flags) const;
virtual void CmdClearBufferView(
GfxCmdBuffer* pCmdBuffer,
const IGpuMemory& dstGpuMemory,
const ClearColor& color,
const void* pBufferViewSrd,
uint32 rangeCount = 0,
const Range* pRanges = nullptr) const;
virtual void CmdClearImageView(
GfxCmdBuffer* pCmdBuffer,
const Image& dstImage,
ImageLayout dstImageLayout,
const ClearColor& color,
const void* pImageViewSrd,
uint32 rectCount = 0,
const Rect* pRects = nullptr) const;
void CmdResolveImage(
GfxCmdBuffer* pCmdBuffer,
const Image& srcImage,
ImageLayout srcImageLayout,
const Image& dstImage,
ImageLayout dstImageLayout,
ResolveMode resolveMode,
uint32 regionCount,
const ImageResolveRegion* pRegions,
uint32 flags) const;
#if PAL_CLIENT_INTERFACE_MAJOR_VERSION >= 554
virtual void CmdResolvePrtPlusImage(
GfxCmdBuffer* pCmdBuffer,
const IImage& srcImage,
ImageLayout srcImageLayout,
const IImage& dstImage,
ImageLayout dstImageLayout,
PrtPlusResolveType resolveType,
uint32 regionCount,
const PrtPlusImageResolveRegion* pRegions) const
{ PAL_NEVER_CALLED(); }
#endif
void CmdGenerateIndirectCmds(
const GenerateInfo& genInfo,
CmdStreamChunk** ppChunkLists[],
uint32 NumChunkLists,
uint32* pNumGenChunks
) const;
virtual bool ExpandDepthStencil(
GfxCmdBuffer* pCmdBuffer,
const Image& image,
const IMsaaState* pMsaaState,
const MsaaQuadSamplePattern* pQuadSamplePattern,
const SubresRange& range
) const;
void ResummarizeDepthStencil(
GfxCmdBuffer* pCmdBuffer,
const Image& image,
ImageLayout imageLayout,
const IMsaaState* pMsaaState,
const MsaaQuadSamplePattern* pQuadSamplePattern,
const SubresRange& range
) const;
virtual void HwlResummarizeHtileCompute(
GfxCmdBuffer* pCmdBuffer,
const GfxImage& image,
const SubresRange& range) const = 0;
void CopyImageToPackedPixelImage(
GfxCmdBuffer* pCmdBuffer,
const Image& srcImage,
const Image& dstImage,
uint32 regionCount,
const ImageCopyRegion* pRegions,
Pal::PackedPixelType packPixelType) const;
virtual void CmdGfxDccToDisplayDcc(
GfxCmdBuffer* pCmdBuffer,
const IImage& image) const;
virtual void CmdDisplayDccFixUp(
GfxCmdBuffer* pCmdBuffer,
const IImage& image) const;
protected:
// When constructing SRD tables, all SRDs must be size and offset aligned to this many DWORDs.
uint32 SrdDwordAlignment() const { return m_srdAlignment; }
virtual bool CopyImageUseMipLevelInSrd(bool isCompressed) const { return UseMipLevelInSrd; }
// Assume optimized copies won't work
virtual bool HwlUseOptimizedImageCopy(
const Pal::Image& srcImage,
ImageLayout srcImageLayout,
const Pal::Image& dstImage,
ImageLayout dstImageLayout,
uint32 regionCount,
const ImageCopyRegion* pRegions) const
{ return false; }
virtual bool CopyDstBoundStencilNeedsWa(
const GfxCmdBuffer* pCmdBuffer,
const Pal::Image& dstImage) const
{ return false; }
// If need to access single zRange for each subres independantly.
virtual bool HwlNeedSinglezRangeAccess() const { return false; }
virtual ImageCopyEngine GetImageToImageCopyEngine(
const GfxCmdBuffer* pCmdBuffer,
const Image& srcImage,
const Image& dstImage,
uint32 regionCount,
const ImageCopyRegion* pRegions,
uint32 copyFlags) const;
virtual bool PreferComputeForNonLocalDestCopy(
const Pal::Image& dstImage) const
{ return false; }
const ComputePipeline* GetLinearHtileClearPipeline(
bool expClearEnable,
bool tileStencilDisabled,
uint32 hTileMask) const;
// Some blts need to use GFXIP-specific algorithms to pick the proper state. The baseState is the first
// graphics state in a series of states that vary only on target format and target index.
virtual const GraphicsPipeline* GetGfxPipelineByTargetIndexAndFormat(
RpmGfxPipeline basePipeline,
uint32 targetIndex,
SwizzledFormat format) const = 0;
// Generating indirect commands needs to choose different shaders based on the GFXIP version.
virtual const ComputePipeline* GetCmdGenerationPipeline(
const IndirectCmdGenerator& generator,
const CmdBuffer& cmdBuffer) const = 0;
const ComputePipeline* GetPipeline(RpmComputePipeline pipeline) const
{ return m_pComputePipelines[static_cast<size_t>(pipeline)]; }
const GraphicsPipeline* GetGfxPipeline(RpmGfxPipeline pipeline) const
{ return m_pGraphicsPipelines[pipeline]; }
const MsaaState* GetMsaaState(uint32 samples, uint32 fragments) const;
const GraphicsPipeline* GetCopyDepthStencilPipeline(bool isDepth,
bool isDepthStencil,
uint32 numSamples) const;
void GenericColorBlit(
GfxCmdBuffer* pCmdBuffer,
const Image& dstImage,
const SubresRange& range,
const IMsaaState& msaaState,
const MsaaQuadSamplePattern* pQuadSamplePattern,
RpmGfxPipeline pipeline,
const GpuMemory* pGpuMemory,
gpusize metaDataOffset
) const;
#if PAL_CLIENT_INTERFACE_MAJOR_VERSION < 642
static bool GetMetaDataTexFetchSupport(const Image* pImage, ImageAspect aspect, uint32 mipLevel);
#endif
static gpusize ComputeTypedBufferRange(
const Extent3d& extent,
uint32 elementSize,
gpusize rowPitch,
gpusize depthPitch);
void SlowClearGraphics(
GfxCmdBuffer* pCmdBuffer,
const Image& dstImage,
ImageLayout dstImageLayout,
const ClearColor* pColor,
const SubresRange& clearRange,
uint32 boxCount,
const Box* pBoxes) const;
void SlowClearCompute(
GfxCmdBuffer* pCmdBuffer,
const Image& dstImage,
ImageLayout dstImageLayout,
SwizzledFormat dstFormat,
const ClearColor* pColor,
const SubresRange& clearRange,
uint32 boxCount,
const Box* pBoxes) const;
void CopyMemoryCs(
GfxCmdBuffer* pCmdBuffer,
const GpuMemory& srcGpuMemory,
const GpuMemory& dstGpuMemory,
uint32 regionCount,
const MemoryCopyRegion* pRegions) const;
const ComputePipeline* GetComputeMaskRamExpandPipeline(
const Image& image) const;
void BindCommonGraphicsState(
GfxCmdBuffer* pCmdBuffer) const;
ColorBlendState* m_pBlendDisableState; // Blend state object with all blending disabled.
ColorBlendState* m_pColorBlendState; // Blend state object with rt0 blending enabled.
DepthStencilState* m_pDepthDisableState; // DS state object with all depth disabled.
DepthStencilState* m_pDepthClearState; // Ds state object for depth-only clears.
DepthStencilState* m_pStencilClearState; // Ds state object for stencil-only clears.
DepthStencilState* m_pDepthStencilClearState; // Ds state object for depth & stencil clears.
DepthStencilState* m_pDepthExpandState; // DS state object for expand.
DepthStencilState* m_pDepthResummarizeState; // DS state object for resummarization.
DepthStencilState* m_pDepthResolveState; // DS state object for depth resolves.
DepthStencilState* m_pStencilResolveState; // DS state object for stencil resolves.
MsaaState* m_pMsaaState[MaxLog2AaSamples + 1]
[MaxLog2AaFragments + 1]; // MSAA state objects for all AA sample rates.
DepthStencilState* m_pDepthStencilResolveState; // DS state object for depth/stencil resolves.
private:
virtual Result CreateCommonStateObjects();
virtual void HwlFastColorClear(
GfxCmdBuffer* pCmdBuffer,
const GfxImage& dstImage,
const uint32* pConvertedColor,
const SubresRange& clearRange) const = 0;
virtual void HwlFixupCopyDstImageMetaData(
GfxCmdBuffer* pCmdBuffer,
const Pal::Image* pSrcImage,
const Pal::Image& dstImage,
ImageLayout dstImageLayout,
const ImageFixupRegion* pRegions,
uint32 regionCount,
bool isFmaskCopyOptimized) const = 0;
virtual void HwlHtileCopyAndFixUp(
GfxCmdBuffer* pCmdBuffer,
const Pal::Image& srcImage,
const Pal::Image& dstImage,
ImageLayout dstImageLayout,
uint32 regionCount,
const ImageResolveRegion* pRegions,
bool computeResolve) const = 0;
virtual void HwlGfxDccToDisplayDcc(
GfxCmdBuffer* pCmdBuffer,
const Pal::Image& image) const
{ PAL_NEVER_CALLED(); }
virtual void InitDisplayDcc(
GfxCmdBuffer* pCmdBuffer,
const Pal::Image& image) const
{ PAL_NEVER_CALLED(); }
virtual void HwlDepthStencilClear(
GfxCmdBuffer* pCmdBuffer,
const GfxImage& dstImage,
ImageLayout depthLayout,
ImageLayout stencilLayout,
float depth,
uint8 stencil,
uint8 stencilWriteMask,
uint32 rangeCount,
const SubresRange* pRanges,
bool fastClear,
bool needComputeSync,
uint32 boxCnt,
const Box* pBox) const = 0;
// The next two functions should be called before and after a graphics copy. They give the gfxip layer a chance
// to optimize the hardware for the copy operation and restore to the previous state once the copy is done.
virtual uint32 HwlBeginGraphicsCopy(
GfxCmdBuffer* pCmdBuffer,
const GraphicsPipeline* pPipeline,
const Image& dstImage,
uint32 bpp) const = 0;
virtual void HwlEndGraphicsCopy(CmdStream* pCmdStream, uint32 restoreMask) const = 0;
virtual void HwlDecodeImageViewSrd(
const void* pImageViewSrd,
const Image& dstImage,
SwizzledFormat* pSwizzledFormat,
SubresRange* pSubresRange) const = 0;
virtual void HwlDecodeBufferViewSrd(
const void* pBufferViewSrd,
BufferViewInfo* pViewInfo) const = 0;
virtual bool HwlCanDoFixedFuncResolve(
const Pal::Image& srcImage,
const Pal::Image& dstImage,
ResolveMode resolveMode,
uint32 regionCount,
const ImageResolveRegion* pRegions) const = 0;
virtual bool HwlCanDoDepthStencilCopyResolve(
const Pal::Image& srcImage,
const Pal::Image& dstImage,
uint32 regionCount,
const ImageResolveRegion* pRegions) const = 0;
virtual void HwlFixupResolveDstImage(
GfxCmdBuffer* pCmdBuffer,
const GfxImage& dstImage,
ImageLayout dstImageLayout,
const ImageResolveRegion* pRegions,
uint32 regionCount,
bool computeResolve) const = 0;
virtual void HwlImageToImageMissingPixelCopy(
GfxCmdBuffer* pCmdBuffer,
const Pal::Image& srcImage,
const Pal::Image& dstImage,
const ImageCopyRegion& region) const = 0;
void CopyColorImageGraphics(
GfxCmdBuffer* pCmdBuffer,
const Image& srcImage,
ImageLayout srcImageLayout,
const Image& dstImage,
ImageLayout dstImageLayout,
uint32 regionCount,
const ImageCopyRegion* pRegions,
const Rect* pScissorRect,
uint32 flags) const;
void ScaledCopyImageGraphics(
GfxCmdBuffer* pCmdBuffer,
const ScaledCopyInfo& copyInfo) const;
void ScaledCopyImageCompute(
GfxCmdBuffer* pCmdBuffer,
const ScaledCopyInfo& copyInfo) const;
void CopyDepthStencilImageGraphics(
GfxCmdBuffer* pCmdBuffer,
const Image& srcImage,
ImageLayout srcImageLayout,
const Image& dstImage,
ImageLayout dstImageLayout,
uint32 regionCount,
const ImageCopyRegion* pRegions,
const Rect* pScissorRect,
uint32 flags) const;
void CopyImageCompute(
GfxCmdBuffer* pCmdBuffer,
const Image& srcImage,
ImageLayout srcImageLayout,
const Image& dstImage,
ImageLayout dstImageLayout,
uint32 regionCount,
const ImageCopyRegion* pRegions,
uint32 flags) const;
template <typename CopyRegion>
void GetCopyImageFormats(
const Image& srcImage,
ImageLayout srcImageLayout,
const Image& dstImage,
ImageLayout dstImageLayout,
const CopyRegion& copyRegion,
uint32 copyFlags,
SwizzledFormat* pSrcFormat,
SwizzledFormat* pDstFormat,
uint32* pTexelScale,
bool* pSingleSubres) const;
void CopyBetweenMemoryAndImage(
GfxCmdBuffer* pCmdBuffer,
const ComputePipeline* pPipeline,
const GpuMemory& gpuMemory,
const Image& image,
ImageLayout imageLayout,
bool isImageDst,
bool isFmaskCopy,
uint32 regionCount,
const MemoryImageCopyRegion* pRegions,
bool includePadding) const;
void ResolveImageGraphics(
GfxCmdBuffer* pCmdBuffer,
const Image& srcImage,
ImageLayout srcImageLayout,
const Image& dstImage,
ImageLayout dstImageLayout,
uint32 regionCount,
const ImageResolveRegion* pRegions,
uint32 flags) const;
void ResolveImageCompute(
GfxCmdBuffer* pCmdBuffer,
const Image& srcImage,
ImageLayout srcImageLayout,
const Image& dstImage,
ImageLayout dstImageLayout,
ResolveMode resolveMode,
uint32 regionCount,
const ImageResolveRegion* pRegions,
ResolveMethod method,
uint32 flags) const;
void ResolveImageFixedFunc(
GfxCmdBuffer* pCmdBuffer,
const Image& srcImage,
ImageLayout srcImageLayout,
const Image& dstImage,
ImageLayout dstImageLayout,
uint32 regionCount,
const ImageResolveRegion* pRegions,
uint32 flags) const;
void ResolveImageDepthStencilCopy(
GfxCmdBuffer* pCmdBuffer,
const Image& srcImage,
ImageLayout srcImageLayout,
const Image& dstImage,
ImageLayout dstImageLayout,
uint32 regionCount,
const ImageResolveRegion* pRegions,
uint32 flags) const;
void SlowClearGraphicsOneMip(
GfxCmdBuffer* pCmdBuffer,
const Image& dstImage,
const SubresId& mipSubres,
uint32 boxCount,
const Box* pBoxes,
ColorTargetViewCreateInfo* pColorViewInfo,
BindTargetParams* pBindTargetsInfo,
uint32 xRightShift) const;
void ClearImageOneBox(
GfxCmdBuffer* pCmdBuffer,
const SubResourceInfo& subResInfo,
const Box* pBox,
bool hasBoxes,
uint32 xRightShift,
uint32 numInstances) const;
void ConvertYuvToRgb(
GfxCmdBuffer* pCmdBuffer,
const Image& srcImage,
const Image& dstImage,
uint32 regionCount,
const ColorSpaceConversionRegion* pRegions,
const SamplerInfo& sampler,
const ColorSpaceConversionTable& cscTable) const;
void ConvertRgbToYuv(
GfxCmdBuffer* pCmdBuffer,
const Image& srcImage,
const Image& dstImage,
uint32 regionCount,
const ColorSpaceConversionRegion* pRegions,
const SamplerInfo& sampler,
const ColorSpaceConversionTable& cscTable) const;
const ComputePipeline* GetCsResolvePipeline(
const Image& srcImage,
#if PAL_CLIENT_INTERFACE_MAJOR_VERSION < 642
ImageAspect aspect,
#else
uint32 plane,
#endif
ResolveMode mode,
ResolveMethod method) const;
void LateExpandResolveSrc(
GfxCmdBuffer* pCmdBuffer,
const Image& srcImage,
ImageLayout srcImageLayout,
const ImageResolveRegion* pRegions,
uint32 regionCount,
ResolveMethod method) const;
void FixupLateExpandResolveSrc(
GfxCmdBuffer* pCmdBuffer,
const Image& srcImage,
ImageLayout srcImageLayout,
const ImageResolveRegion* pRegions,
uint32 regionCount,
ResolveMethod method) const;
void LateExpandResolveSrcHelper(
GfxCmdBuffer* pCmdBuffer,
const ImageResolveRegion* pRegions,
uint32 regionCount,
const BarrierTransition& transition,
HwPipePoint waitPoint) const;
void FixupMetadataForComputeDst(
GfxCmdBuffer* pCmdBuffer,
const Image& dstImage,
ImageLayout dstImageLayout,
uint32 regionCount,
const ImageFixupRegion* pRegions,
bool beforeCopy) const;
bool ScaledCopyImageUseGraphics(
GfxCmdBuffer* pCmdBuffer,
const ScaledCopyInfo& copyInfo) const;
void GenerateMipmapsFast(
GfxCmdBuffer* pCmdBuffer,
const GenMipmapsInfo& genInfo) const;
void GenerateMipmapsSlow(
GfxCmdBuffer* pCmdBuffer,
const GenMipmapsInfo& genInfo) const;
GfxDevice*const m_pDevice;
uint32 m_srdAlignment; // All SRDs must be offset and size aligned to this many DWORDs.
// All internal RPM pipelines are stored here.
ComputePipeline* m_pComputePipelines[static_cast<size_t>(RpmComputePipeline::Count)];
GraphicsPipeline* m_pGraphicsPipelines[RpmGfxPipelineCount];
PAL_DISALLOW_DEFAULT_CTOR(RsrcProcMgr);
PAL_DISALLOW_COPY_AND_ASSIGN(RsrcProcMgr);
};
extern void PreComputeDepthStencilClearSync(ICmdBuffer* pCmdBuffer,
const GfxImage& gfxImage,
const SubresRange& subres,
ImageLayout layout);
extern void PostComputeDepthStencilClearSync(ICmdBuffer* pCmdBuffer,
const GfxImage& gfxImage,
const SubresRange& subres,
ImageLayout layout);
} // Pal
| 39.636 | 120 | 0.570088 | [
"object"
] |
aac979dec5ec9472778d51fb58f754cde34f5233 | 19,153 | h | C | aws-cpp-sdk-codecommit/include/aws/codecommit/model/GetDifferencesRequest.h | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-codecommit/include/aws/codecommit/model/GetDifferencesRequest.h | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-codecommit/include/aws/codecommit/model/GetDifferencesRequest.h | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/codecommit/CodeCommit_EXPORTS.h>
#include <aws/codecommit/CodeCommitRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace CodeCommit
{
namespace Model
{
/**
*/
class AWS_CODECOMMIT_API GetDifferencesRequest : public CodeCommitRequest
{
public:
GetDifferencesRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "GetDifferences"; }
Aws::String SerializePayload() const override;
Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;
/**
* <p>The name of the repository where you want to get differences.</p>
*/
inline const Aws::String& GetRepositoryName() const{ return m_repositoryName; }
/**
* <p>The name of the repository where you want to get differences.</p>
*/
inline bool RepositoryNameHasBeenSet() const { return m_repositoryNameHasBeenSet; }
/**
* <p>The name of the repository where you want to get differences.</p>
*/
inline void SetRepositoryName(const Aws::String& value) { m_repositoryNameHasBeenSet = true; m_repositoryName = value; }
/**
* <p>The name of the repository where you want to get differences.</p>
*/
inline void SetRepositoryName(Aws::String&& value) { m_repositoryNameHasBeenSet = true; m_repositoryName = std::move(value); }
/**
* <p>The name of the repository where you want to get differences.</p>
*/
inline void SetRepositoryName(const char* value) { m_repositoryNameHasBeenSet = true; m_repositoryName.assign(value); }
/**
* <p>The name of the repository where you want to get differences.</p>
*/
inline GetDifferencesRequest& WithRepositoryName(const Aws::String& value) { SetRepositoryName(value); return *this;}
/**
* <p>The name of the repository where you want to get differences.</p>
*/
inline GetDifferencesRequest& WithRepositoryName(Aws::String&& value) { SetRepositoryName(std::move(value)); return *this;}
/**
* <p>The name of the repository where you want to get differences.</p>
*/
inline GetDifferencesRequest& WithRepositoryName(const char* value) { SetRepositoryName(value); return *this;}
/**
* <p>The branch, tag, HEAD, or other fully qualified reference used to identify a
* commit. For example, the full commit ID. Optional. If not specified, all changes
* prior to the <code>afterCommitSpecifier</code> value will be shown. If you do
* not use <code>beforeCommitSpecifier</code> in your request, consider limiting
* the results with <code>maxResults</code>.</p>
*/
inline const Aws::String& GetBeforeCommitSpecifier() const{ return m_beforeCommitSpecifier; }
/**
* <p>The branch, tag, HEAD, or other fully qualified reference used to identify a
* commit. For example, the full commit ID. Optional. If not specified, all changes
* prior to the <code>afterCommitSpecifier</code> value will be shown. If you do
* not use <code>beforeCommitSpecifier</code> in your request, consider limiting
* the results with <code>maxResults</code>.</p>
*/
inline bool BeforeCommitSpecifierHasBeenSet() const { return m_beforeCommitSpecifierHasBeenSet; }
/**
* <p>The branch, tag, HEAD, or other fully qualified reference used to identify a
* commit. For example, the full commit ID. Optional. If not specified, all changes
* prior to the <code>afterCommitSpecifier</code> value will be shown. If you do
* not use <code>beforeCommitSpecifier</code> in your request, consider limiting
* the results with <code>maxResults</code>.</p>
*/
inline void SetBeforeCommitSpecifier(const Aws::String& value) { m_beforeCommitSpecifierHasBeenSet = true; m_beforeCommitSpecifier = value; }
/**
* <p>The branch, tag, HEAD, or other fully qualified reference used to identify a
* commit. For example, the full commit ID. Optional. If not specified, all changes
* prior to the <code>afterCommitSpecifier</code> value will be shown. If you do
* not use <code>beforeCommitSpecifier</code> in your request, consider limiting
* the results with <code>maxResults</code>.</p>
*/
inline void SetBeforeCommitSpecifier(Aws::String&& value) { m_beforeCommitSpecifierHasBeenSet = true; m_beforeCommitSpecifier = std::move(value); }
/**
* <p>The branch, tag, HEAD, or other fully qualified reference used to identify a
* commit. For example, the full commit ID. Optional. If not specified, all changes
* prior to the <code>afterCommitSpecifier</code> value will be shown. If you do
* not use <code>beforeCommitSpecifier</code> in your request, consider limiting
* the results with <code>maxResults</code>.</p>
*/
inline void SetBeforeCommitSpecifier(const char* value) { m_beforeCommitSpecifierHasBeenSet = true; m_beforeCommitSpecifier.assign(value); }
/**
* <p>The branch, tag, HEAD, or other fully qualified reference used to identify a
* commit. For example, the full commit ID. Optional. If not specified, all changes
* prior to the <code>afterCommitSpecifier</code> value will be shown. If you do
* not use <code>beforeCommitSpecifier</code> in your request, consider limiting
* the results with <code>maxResults</code>.</p>
*/
inline GetDifferencesRequest& WithBeforeCommitSpecifier(const Aws::String& value) { SetBeforeCommitSpecifier(value); return *this;}
/**
* <p>The branch, tag, HEAD, or other fully qualified reference used to identify a
* commit. For example, the full commit ID. Optional. If not specified, all changes
* prior to the <code>afterCommitSpecifier</code> value will be shown. If you do
* not use <code>beforeCommitSpecifier</code> in your request, consider limiting
* the results with <code>maxResults</code>.</p>
*/
inline GetDifferencesRequest& WithBeforeCommitSpecifier(Aws::String&& value) { SetBeforeCommitSpecifier(std::move(value)); return *this;}
/**
* <p>The branch, tag, HEAD, or other fully qualified reference used to identify a
* commit. For example, the full commit ID. Optional. If not specified, all changes
* prior to the <code>afterCommitSpecifier</code> value will be shown. If you do
* not use <code>beforeCommitSpecifier</code> in your request, consider limiting
* the results with <code>maxResults</code>.</p>
*/
inline GetDifferencesRequest& WithBeforeCommitSpecifier(const char* value) { SetBeforeCommitSpecifier(value); return *this;}
/**
* <p>The branch, tag, HEAD, or other fully qualified reference used to identify a
* commit.</p>
*/
inline const Aws::String& GetAfterCommitSpecifier() const{ return m_afterCommitSpecifier; }
/**
* <p>The branch, tag, HEAD, or other fully qualified reference used to identify a
* commit.</p>
*/
inline bool AfterCommitSpecifierHasBeenSet() const { return m_afterCommitSpecifierHasBeenSet; }
/**
* <p>The branch, tag, HEAD, or other fully qualified reference used to identify a
* commit.</p>
*/
inline void SetAfterCommitSpecifier(const Aws::String& value) { m_afterCommitSpecifierHasBeenSet = true; m_afterCommitSpecifier = value; }
/**
* <p>The branch, tag, HEAD, or other fully qualified reference used to identify a
* commit.</p>
*/
inline void SetAfterCommitSpecifier(Aws::String&& value) { m_afterCommitSpecifierHasBeenSet = true; m_afterCommitSpecifier = std::move(value); }
/**
* <p>The branch, tag, HEAD, or other fully qualified reference used to identify a
* commit.</p>
*/
inline void SetAfterCommitSpecifier(const char* value) { m_afterCommitSpecifierHasBeenSet = true; m_afterCommitSpecifier.assign(value); }
/**
* <p>The branch, tag, HEAD, or other fully qualified reference used to identify a
* commit.</p>
*/
inline GetDifferencesRequest& WithAfterCommitSpecifier(const Aws::String& value) { SetAfterCommitSpecifier(value); return *this;}
/**
* <p>The branch, tag, HEAD, or other fully qualified reference used to identify a
* commit.</p>
*/
inline GetDifferencesRequest& WithAfterCommitSpecifier(Aws::String&& value) { SetAfterCommitSpecifier(std::move(value)); return *this;}
/**
* <p>The branch, tag, HEAD, or other fully qualified reference used to identify a
* commit.</p>
*/
inline GetDifferencesRequest& WithAfterCommitSpecifier(const char* value) { SetAfterCommitSpecifier(value); return *this;}
/**
* <p>The file path in which to check for differences. Limits the results to this
* path. Can also be used to specify the previous name of a directory or folder. If
* <code>beforePath</code> and <code>afterPath</code> are not specified,
* differences will be shown for all paths.</p>
*/
inline const Aws::String& GetBeforePath() const{ return m_beforePath; }
/**
* <p>The file path in which to check for differences. Limits the results to this
* path. Can also be used to specify the previous name of a directory or folder. If
* <code>beforePath</code> and <code>afterPath</code> are not specified,
* differences will be shown for all paths.</p>
*/
inline bool BeforePathHasBeenSet() const { return m_beforePathHasBeenSet; }
/**
* <p>The file path in which to check for differences. Limits the results to this
* path. Can also be used to specify the previous name of a directory or folder. If
* <code>beforePath</code> and <code>afterPath</code> are not specified,
* differences will be shown for all paths.</p>
*/
inline void SetBeforePath(const Aws::String& value) { m_beforePathHasBeenSet = true; m_beforePath = value; }
/**
* <p>The file path in which to check for differences. Limits the results to this
* path. Can also be used to specify the previous name of a directory or folder. If
* <code>beforePath</code> and <code>afterPath</code> are not specified,
* differences will be shown for all paths.</p>
*/
inline void SetBeforePath(Aws::String&& value) { m_beforePathHasBeenSet = true; m_beforePath = std::move(value); }
/**
* <p>The file path in which to check for differences. Limits the results to this
* path. Can also be used to specify the previous name of a directory or folder. If
* <code>beforePath</code> and <code>afterPath</code> are not specified,
* differences will be shown for all paths.</p>
*/
inline void SetBeforePath(const char* value) { m_beforePathHasBeenSet = true; m_beforePath.assign(value); }
/**
* <p>The file path in which to check for differences. Limits the results to this
* path. Can also be used to specify the previous name of a directory or folder. If
* <code>beforePath</code> and <code>afterPath</code> are not specified,
* differences will be shown for all paths.</p>
*/
inline GetDifferencesRequest& WithBeforePath(const Aws::String& value) { SetBeforePath(value); return *this;}
/**
* <p>The file path in which to check for differences. Limits the results to this
* path. Can also be used to specify the previous name of a directory or folder. If
* <code>beforePath</code> and <code>afterPath</code> are not specified,
* differences will be shown for all paths.</p>
*/
inline GetDifferencesRequest& WithBeforePath(Aws::String&& value) { SetBeforePath(std::move(value)); return *this;}
/**
* <p>The file path in which to check for differences. Limits the results to this
* path. Can also be used to specify the previous name of a directory or folder. If
* <code>beforePath</code> and <code>afterPath</code> are not specified,
* differences will be shown for all paths.</p>
*/
inline GetDifferencesRequest& WithBeforePath(const char* value) { SetBeforePath(value); return *this;}
/**
* <p>The file path in which to check differences. Limits the results to this path.
* Can also be used to specify the changed name of a directory or folder, if it has
* changed. If not specified, differences will be shown for all paths.</p>
*/
inline const Aws::String& GetAfterPath() const{ return m_afterPath; }
/**
* <p>The file path in which to check differences. Limits the results to this path.
* Can also be used to specify the changed name of a directory or folder, if it has
* changed. If not specified, differences will be shown for all paths.</p>
*/
inline bool AfterPathHasBeenSet() const { return m_afterPathHasBeenSet; }
/**
* <p>The file path in which to check differences. Limits the results to this path.
* Can also be used to specify the changed name of a directory or folder, if it has
* changed. If not specified, differences will be shown for all paths.</p>
*/
inline void SetAfterPath(const Aws::String& value) { m_afterPathHasBeenSet = true; m_afterPath = value; }
/**
* <p>The file path in which to check differences. Limits the results to this path.
* Can also be used to specify the changed name of a directory or folder, if it has
* changed. If not specified, differences will be shown for all paths.</p>
*/
inline void SetAfterPath(Aws::String&& value) { m_afterPathHasBeenSet = true; m_afterPath = std::move(value); }
/**
* <p>The file path in which to check differences. Limits the results to this path.
* Can also be used to specify the changed name of a directory or folder, if it has
* changed. If not specified, differences will be shown for all paths.</p>
*/
inline void SetAfterPath(const char* value) { m_afterPathHasBeenSet = true; m_afterPath.assign(value); }
/**
* <p>The file path in which to check differences. Limits the results to this path.
* Can also be used to specify the changed name of a directory or folder, if it has
* changed. If not specified, differences will be shown for all paths.</p>
*/
inline GetDifferencesRequest& WithAfterPath(const Aws::String& value) { SetAfterPath(value); return *this;}
/**
* <p>The file path in which to check differences. Limits the results to this path.
* Can also be used to specify the changed name of a directory or folder, if it has
* changed. If not specified, differences will be shown for all paths.</p>
*/
inline GetDifferencesRequest& WithAfterPath(Aws::String&& value) { SetAfterPath(std::move(value)); return *this;}
/**
* <p>The file path in which to check differences. Limits the results to this path.
* Can also be used to specify the changed name of a directory or folder, if it has
* changed. If not specified, differences will be shown for all paths.</p>
*/
inline GetDifferencesRequest& WithAfterPath(const char* value) { SetAfterPath(value); return *this;}
/**
* <p>A non-negative integer used to limit the number of returned results.</p>
*/
inline int GetMaxResults() const{ return m_maxResults; }
/**
* <p>A non-negative integer used to limit the number of returned results.</p>
*/
inline bool MaxResultsHasBeenSet() const { return m_maxResultsHasBeenSet; }
/**
* <p>A non-negative integer used to limit the number of returned results.</p>
*/
inline void SetMaxResults(int value) { m_maxResultsHasBeenSet = true; m_maxResults = value; }
/**
* <p>A non-negative integer used to limit the number of returned results.</p>
*/
inline GetDifferencesRequest& WithMaxResults(int value) { SetMaxResults(value); return *this;}
/**
* <p>An enumeration token that when provided in a request, returns the next batch
* of the results.</p>
*/
inline const Aws::String& GetNextToken() const{ return m_nextToken; }
/**
* <p>An enumeration token that when provided in a request, returns the next batch
* of the results.</p>
*/
inline bool NextTokenHasBeenSet() const { return m_nextTokenHasBeenSet; }
/**
* <p>An enumeration token that when provided in a request, returns the next batch
* of the results.</p>
*/
inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; }
/**
* <p>An enumeration token that when provided in a request, returns the next batch
* of the results.</p>
*/
inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); }
/**
* <p>An enumeration token that when provided in a request, returns the next batch
* of the results.</p>
*/
inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); }
/**
* <p>An enumeration token that when provided in a request, returns the next batch
* of the results.</p>
*/
inline GetDifferencesRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}
/**
* <p>An enumeration token that when provided in a request, returns the next batch
* of the results.</p>
*/
inline GetDifferencesRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}
/**
* <p>An enumeration token that when provided in a request, returns the next batch
* of the results.</p>
*/
inline GetDifferencesRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;}
private:
Aws::String m_repositoryName;
bool m_repositoryNameHasBeenSet;
Aws::String m_beforeCommitSpecifier;
bool m_beforeCommitSpecifierHasBeenSet;
Aws::String m_afterCommitSpecifier;
bool m_afterCommitSpecifierHasBeenSet;
Aws::String m_beforePath;
bool m_beforePathHasBeenSet;
Aws::String m_afterPath;
bool m_afterPathHasBeenSet;
int m_maxResults;
bool m_maxResultsHasBeenSet;
Aws::String m_nextToken;
bool m_nextTokenHasBeenSet;
};
} // namespace Model
} // namespace CodeCommit
} // namespace Aws
| 44.75 | 151 | 0.695035 | [
"model"
] |
aad2040821076c24f92017c2e74f2485ebdf5001 | 5,070 | h | C | servers/arvr/arvr_positional_tracker.h | LinuxUserGD/godot-opengl-4 | 6776f665672b86f0566681460a559f4ec25ccc8b | [
"MIT",
"Apache-2.0",
"CC-BY-4.0",
"Unlicense"
] | 15 | 2020-12-20T19:24:59.000Z | 2022-03-25T19:41:12.000Z | servers/arvr/arvr_positional_tracker.h | LinuxUserGD/godot-opengl-4 | 6776f665672b86f0566681460a559f4ec25ccc8b | [
"MIT",
"Apache-2.0",
"CC-BY-4.0",
"Unlicense"
] | 2 | 2021-12-10T04:07:19.000Z | 2021-12-27T20:00:03.000Z | servers/arvr/arvr_positional_tracker.h | LinuxUserGD/godot-opengl-4 | 6776f665672b86f0566681460a559f4ec25ccc8b | [
"MIT",
"Apache-2.0",
"CC-BY-4.0",
"Unlicense"
] | 1 | 2022-01-16T14:18:33.000Z | 2022-01-16T14:18:33.000Z | /*************************************************************************/
/* arvr_positional_tracker.h */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 ARVR_POSITIONAL_TRACKER_H
#define ARVR_POSITIONAL_TRACKER_H
#include "core/os/thread_safe.h"
#include "scene/resources/mesh.h"
#include "servers/arvr_server.h"
/**
@author Bastiaan Olij <mux213@gmail.com>
The positional tracker object as an object that represents the position and orientation of a tracked object like a controller or headset.
An AR/VR Interface will registered the trackers it manages with our AR/VR server and update its position and orientation.
This is where potentially additional AR/VR interfaces may be active as there are AR/VR SDKs that solely deal with positional tracking.
*/
class ARVRPositionalTracker : public Reference {
GDCLASS(ARVRPositionalTracker, Reference);
_THREAD_SAFE_CLASS_
public:
enum TrackerHand {
TRACKER_HAND_UNKNOWN, /* unknown or not applicable */
TRACKER_LEFT_HAND, /* controller is the left hand controller */
TRACKER_RIGHT_HAND /* controller is the right hand controller */
};
private:
ARVRServer::TrackerType type; // type of tracker
StringName name; // (unique) name of the tracker
int tracker_id; // tracker index id that is unique per type
int joy_id; // if we also have a related joystick entity, the id of the joystick
bool tracks_orientation; // do we track orientation?
Basis orientation; // our orientation
bool tracks_position; // do we track position?
Vector3 rw_position; // our position "in the real world, so without world_scale applied"
Ref<Mesh> mesh; // when available, a mesh that can be used to render this tracker
TrackerHand hand; // if known, the hand this tracker is held in
real_t rumble; // rumble strength, 0.0 is off, 1.0 is maximum, note that we only record here, arvr_interface is responsible for execution
protected:
static void _bind_methods();
public:
void set_type(ARVRServer::TrackerType p_type);
ARVRServer::TrackerType get_type() const;
void set_name(const String &p_name);
StringName get_name() const;
int get_tracker_id() const;
void set_joy_id(int p_joy_id);
int get_joy_id() const;
bool get_tracks_orientation() const;
void set_orientation(const Basis &p_orientation);
Basis get_orientation() const;
bool get_tracks_position() const;
void set_position(const Vector3 &p_position); // set position with world_scale applied
Vector3 get_position() const; // get position with world_scale applied
void set_rw_position(const Vector3 &p_rw_position);
Vector3 get_rw_position() const;
ARVRPositionalTracker::TrackerHand get_hand() const;
void set_hand(const ARVRPositionalTracker::TrackerHand p_hand);
real_t get_rumble() const;
void set_rumble(real_t p_rumble);
void set_mesh(const Ref<Mesh> &p_mesh);
Ref<Mesh> get_mesh() const;
Transform get_transform(bool p_adjust_by_reference_frame) const;
ARVRPositionalTracker();
~ARVRPositionalTracker();
};
VARIANT_ENUM_CAST(ARVRPositionalTracker::TrackerHand);
#endif
| 48.285714 | 138 | 0.638462 | [
"mesh",
"render",
"object",
"transform"
] |
aad3d4ba518a34b46c172ab3880a93d09c07acdb | 2,799 | h | C | Primer_sample/15/Basket.h | doruison/CppAssignMent | 30a59304367da49ec09403f45deae2b6a998fef9 | [
"MIT"
] | 3 | 2015-03-23T03:04:53.000Z | 2015-04-06T03:34:29.000Z | Primer_sample/15/Basket.h | doruison/CppAssignMent | 30a59304367da49ec09403f45deae2b6a998fef9 | [
"MIT"
] | null | null | null | Primer_sample/15/Basket.h | doruison/CppAssignMent | 30a59304367da49ec09403f45deae2b6a998fef9 | [
"MIT"
] | null | null | null | /*
* This file contains code from "C++ Primer, Fifth Edition", by Stanley B.
* Lippman, Josee Lajoie, and Barbara E. Moo, and is covered under the
* copyright and warranty notices given in that book:
*
* "Copyright (c) 2013 by Objectwrite, Inc., Josee Lajoie, and Barbara E. Moo."
*
*
* "The authors and publisher have taken care in the preparation of this book,
* but make no expressed or implied warranty of any kind and assume no
* responsibility for errors or omissions. No liability is assumed for
* incidental or consequential damages in connection with or arising out of the
* use of the information or programs contained herein."
*
* Permission is granted for this code to be used for educational purposes in
* association with the book, given proper citation if and when posted or
* reproduced.Any commercial use of this code requires the explicit written
* permission of the publisher, Addison-Wesley Professional, a division of
* Pearson Education, Inc. Send your request for permission, stating clearly
* what code you would like to use, and in what specific way, to the following
* address:
*
* Pearson Education, Inc.
* Rights and Permissions Department
* One Lake Street
* Upper Saddle River, NJ 07458
* Fax: (201) 236-3290
*/
#ifndef BASKET_H
#define BASKET_H
#include "Version_test.h"
#include <iostream>
#include <string>
#include <set>
#include <map>
#include <utility>
#include <cstddef>
#include <stdexcept>
#include <memory>
#include "Quote.h"
// holds items being purchased
class Basket {
public:
#ifdef IN_CLASS_INITS
// Basket uses synthesized default constructor and copy-control members
#else
Basket() : items(compare) { }
#endif
void add_item(const std::shared_ptr<Quote> &sale)
{ items.insert(sale); }
void add_item(const Quote& sale) // copy the given object
{ items.insert(std::shared_ptr<Quote>(sale.clone())); }
void add_item(Quote&& sale) // move the given object
{ items.insert(
std::shared_ptr<Quote>(std::move(sale).clone())); }
// prints the total price for each book
// and the overall total for all items in the basket
double total_receipt(std::ostream&) const;
// for debugging purposes, prints contents of the basket
void display (std::ostream&) const;
private:
// function to compare shared_ptrs needed by the multiset member
static bool compare(const std::shared_ptr<Quote> &lhs,
const std::shared_ptr<Quote> &rhs)
{ return lhs->isbn() < rhs->isbn(); }
// multiset to hold multiple quotes, ordered by the compare member
#ifdef IN_CLASS_INITS
std::multiset<std::shared_ptr<Quote>, decltype(compare)*>
items{compare};
#else
std::multiset<std::shared_ptr<Quote>, decltype(compare)*> items;
#endif
};
#endif
| 32.929412 | 79 | 0.714184 | [
"object"
] |
aadda3cfcb8d4b49404bdfe4073672db210dfd4c | 2,225 | h | C | Source/Game/GameState.h | Fiskmans/Old_Betsy | 6610586165250d21de9b9efb57b4e8e56e82ecdf | [
"MIT"
] | 3 | 2021-05-06T19:54:20.000Z | 2021-05-06T21:15:50.000Z | Source/Game/GameState.h | Fiskmans/Old_Betsy | 6610586165250d21de9b9efb57b4e8e56e82ecdf | [
"MIT"
] | null | null | null | Source/Game/GameState.h | Fiskmans/Old_Betsy | 6610586165250d21de9b9efb57b4e8e56e82ecdf | [
"MIT"
] | null | null | null | #pragma once
#include "GameWorld.h"
#include <Spline.h>
#include "BaseState.h"
#include "TimerController.h"
#include "SpotLightFactory.h"
#include "DecalFactory.h"
class NodePollingStation;
class Scene;
class AudioManager;
class GBPhysX;
class SpriteRenderer;
class GameState : public BaseState, public Observer
{
public:
GameState(bool aShouldDeleteOnPop = true);
~GameState();
virtual void Update(const float aDeltaTime) override;
bool Init(InputManager* aInputManager, SpriteFactory* aSpritefactory, LightLoader* aLightLoader, DirectX11Framework* aFramework, AudioManager* aAudioManager, SpriteRenderer* aSpriteRenderer);
virtual void Render(CGraphicsEngine* aGraphicsEngine) override;
void LoadLevel(const int& aLevel);
void PreSetup(const float aDeltaTime);
private:
void RunImGui(float aDeltatime);
void SetDefaultLevel(const std::string& aLevel);
void LoadDefaultLevel();
bool LoadLevel(const std::string& aFilePath);
void MergeNextLevel();
bool MergeLevel(const std::string& aFilePath);
bool MergeQueuedLevelPartially(float aTimeBudget);
void UnloadCurrentLevel();
void UnloadLevel(std::string aFilepath);
void CreateWorld(DirectX11Framework* aFramework, AudioManager* aAudioManager, SpriteRenderer* aSpriteRenderer);
virtual void Activate() override;
virtual void Deactivate() override;
virtual void Unload() override;
AssetHandle myLoadingLevel;
bool myHasRenderedAtleastOneFrame;
InputManager* myInputManager;
SpriteFactory* mySpriteFactory;
LightLoader* myLightLoader;
AudioManager* myAudioManager;
SpotLightFactory mySpotlightFactory;
DecalFactory myDecalFactory;
DirectX11Framework* myFramework;
ID3D11DeviceContext* myContext;
ID3D11Device* myDevice;
ModelInstance* mySkybox;
GameWorld* myGameWorld;
NodePollingStation* myNodePollingStation;
TimerController myTimerController;
GBPhysX* myGBPhysX;
#if USEFILEWATHCER
Tools::FileWatcher myWatcher;
Tools::FileWatcherUniqueID myMetricHandle;
#endif
std::string myCurrentLevel;
std::unordered_set<std::string> myCurrentLoadedLevels;
std::vector<std::string> myLevelSequence;
unsigned int myCurrentLevelindex;
// Inherited via Observer
virtual void RecieveMessage(const Message& aMessage) override;
};
| 26.807229 | 192 | 0.808539 | [
"render",
"vector"
] |
aae1d18ff7f51b66e4db8e24ed7c4b8ecf272b0b | 18,000 | h | C | extsrc/mesa/src/mesa/tnl/t_vb_lighttmp.h | MauroArgentino/RSXGL | bd206e11894f309680f48740346c17efe49755ba | [
"BSD-2-Clause"
] | 28 | 2015-07-11T17:11:12.000Z | 2022-03-26T04:14:16.000Z | extsrc/mesa/src/mesa/tnl/t_vb_lighttmp.h | MauroArgentino/RSXGL | bd206e11894f309680f48740346c17efe49755ba | [
"BSD-2-Clause"
] | 2 | 2019-05-26T19:02:24.000Z | 2021-05-27T14:15:04.000Z | extsrc/mesa/src/mesa/tnl/t_vb_lighttmp.h | MauroArgentino/RSXGL | bd206e11894f309680f48740346c17efe49755ba | [
"BSD-2-Clause"
] | 9 | 2019-07-04T12:54:29.000Z | 2022-02-09T13:04:38.000Z | /*
* Mesa 3-D graphics library
* Version: 5.1
*
* Copyright (C) 1999-2003 Brian Paul All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* BRIAN PAUL 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.
*
*
* Authors:
* Brian Paul
* Keith Whitwell <keith@tungstengraphics.com>
*/
#if IDX & LIGHT_TWOSIDE
# define NR_SIDES 2
#else
# define NR_SIDES 1
#endif
/* define TRACE to trace lighting code */
/* #define TRACE 1 */
/*
* ctx is the current context
* VB is the vertex buffer
* stage is the lighting stage-private data
* input is the vector of eye or object-space vertex coordinates
*/
static void TAG(light_rgba_spec)( struct gl_context *ctx,
struct vertex_buffer *VB,
struct tnl_pipeline_stage *stage,
GLvector4f *input )
{
struct light_stage_data *store = LIGHT_STAGE_DATA(stage);
GLfloat (*base)[3] = ctx->Light._BaseColor;
GLfloat sumA[2];
GLuint j;
const GLuint vstride = input->stride;
const GLfloat *vertex = (GLfloat *)input->data;
const GLuint nstride = VB->AttribPtr[_TNL_ATTRIB_NORMAL]->stride;
const GLfloat *normal = (GLfloat *)VB->AttribPtr[_TNL_ATTRIB_NORMAL]->data;
GLfloat (*Fcolor)[4] = (GLfloat (*)[4]) store->LitColor[0].data;
GLfloat (*Fspec)[4] = (GLfloat (*)[4]) store->LitSecondary[0].data;
#if IDX & LIGHT_TWOSIDE
GLfloat (*Bcolor)[4] = (GLfloat (*)[4]) store->LitColor[1].data;
GLfloat (*Bspec)[4] = (GLfloat (*)[4]) store->LitSecondary[1].data;
#endif
const GLuint nr = VB->Count;
#ifdef TRACE
fprintf(stderr, "%s\n", __FUNCTION__ );
#endif
VB->AttribPtr[_TNL_ATTRIB_COLOR0] = &store->LitColor[0];
VB->AttribPtr[_TNL_ATTRIB_COLOR1] = &store->LitSecondary[0];
sumA[0] = ctx->Light.Material.Attrib[MAT_ATTRIB_FRONT_DIFFUSE][3];
#if IDX & LIGHT_TWOSIDE
VB->BackfaceColorPtr = &store->LitColor[1];
VB->BackfaceSecondaryColorPtr = &store->LitSecondary[1];
sumA[1] = ctx->Light.Material.Attrib[MAT_ATTRIB_BACK_DIFFUSE][3];
#endif
store->LitColor[0].stride = 16;
store->LitColor[1].stride = 16;
for (j = 0; j < nr; j++,STRIDE_F(vertex,vstride),STRIDE_F(normal,nstride)) {
GLfloat sum[2][3], spec[2][3];
struct gl_light *light;
#if IDX & LIGHT_MATERIAL
update_materials( ctx, store );
sumA[0] = ctx->Light.Material.Attrib[MAT_ATTRIB_FRONT_DIFFUSE][3];
#if IDX & LIGHT_TWOSIDE
sumA[1] = ctx->Light.Material.Attrib[MAT_ATTRIB_BACK_DIFFUSE][3];
#endif
#endif
COPY_3V(sum[0], base[0]);
ZERO_3V(spec[0]);
#if IDX & LIGHT_TWOSIDE
COPY_3V(sum[1], base[1]);
ZERO_3V(spec[1]);
#endif
/* Add contribution from each enabled light source */
foreach (light, &ctx->Light.EnabledList) {
GLfloat n_dot_h;
GLfloat correction;
GLint side;
GLfloat contrib[3];
GLfloat attenuation;
GLfloat VP[3]; /* unit vector from vertex to light */
GLfloat n_dot_VP; /* n dot VP */
GLfloat *h;
/* compute VP and attenuation */
if (!(light->_Flags & LIGHT_POSITIONAL)) {
/* directional light */
COPY_3V(VP, light->_VP_inf_norm);
attenuation = light->_VP_inf_spot_attenuation;
}
else {
GLfloat d; /* distance from vertex to light */
SUB_3V(VP, light->_Position, vertex);
d = (GLfloat) LEN_3FV( VP );
if (d > 1e-6) {
GLfloat invd = 1.0F / d;
SELF_SCALE_SCALAR_3V(VP, invd);
}
attenuation = 1.0F / (light->ConstantAttenuation + d *
(light->LinearAttenuation + d *
light->QuadraticAttenuation));
/* spotlight attenuation */
if (light->_Flags & LIGHT_SPOT) {
GLfloat PV_dot_dir = - DOT3(VP, light->_NormSpotDirection);
if (PV_dot_dir<light->_CosCutoff) {
continue; /* this light makes no contribution */
}
else {
GLdouble x = PV_dot_dir * (EXP_TABLE_SIZE-1);
GLint k = (GLint) x;
GLfloat spot = (GLfloat) (light->_SpotExpTable[k][0]
+ (x-k)*light->_SpotExpTable[k][1]);
attenuation *= spot;
}
}
}
if (attenuation < 1e-3)
continue; /* this light makes no contribution */
/* Compute dot product or normal and vector from V to light pos */
n_dot_VP = DOT3( normal, VP );
/* Which side gets the diffuse & specular terms? */
if (n_dot_VP < 0.0F) {
ACC_SCALE_SCALAR_3V(sum[0], attenuation, light->_MatAmbient[0]);
#if IDX & LIGHT_TWOSIDE
side = 1;
correction = -1;
n_dot_VP = -n_dot_VP;
#else
continue;
#endif
}
else {
#if IDX & LIGHT_TWOSIDE
ACC_SCALE_SCALAR_3V( sum[1], attenuation, light->_MatAmbient[1]);
#endif
side = 0;
correction = 1;
}
/* diffuse term */
COPY_3V(contrib, light->_MatAmbient[side]);
ACC_SCALE_SCALAR_3V(contrib, n_dot_VP, light->_MatDiffuse[side]);
ACC_SCALE_SCALAR_3V(sum[side], attenuation, contrib );
/* specular term - cannibalize VP... */
if (ctx->Light.Model.LocalViewer) {
GLfloat v[3];
COPY_3V(v, vertex);
NORMALIZE_3FV(v);
SUB_3V(VP, VP, v); /* h = VP + VPe */
h = VP;
NORMALIZE_3FV(h);
}
else if (light->_Flags & LIGHT_POSITIONAL) {
h = VP;
ACC_3V(h, ctx->_EyeZDir);
NORMALIZE_3FV(h);
}
else {
h = light->_h_inf_norm;
}
n_dot_h = correction * DOT3(normal, h);
if (n_dot_h > 0.0F) {
GLfloat spec_coef;
struct gl_shine_tab *tab = ctx->_ShineTable[side];
GET_SHINE_TAB_ENTRY( tab, n_dot_h, spec_coef );
if (spec_coef > 1.0e-10) {
spec_coef *= attenuation;
ACC_SCALE_SCALAR_3V( spec[side], spec_coef,
light->_MatSpecular[side]);
}
}
} /*loop over lights*/
COPY_3V( Fcolor[j], sum[0] );
COPY_3V( Fspec[j], spec[0] );
Fcolor[j][3] = sumA[0];
#if IDX & LIGHT_TWOSIDE
COPY_3V( Bcolor[j], sum[1] );
COPY_3V( Bspec[j], spec[1] );
Bcolor[j][3] = sumA[1];
#endif
}
}
static void TAG(light_rgba)( struct gl_context *ctx,
struct vertex_buffer *VB,
struct tnl_pipeline_stage *stage,
GLvector4f *input )
{
struct light_stage_data *store = LIGHT_STAGE_DATA(stage);
GLuint j;
GLfloat (*base)[3] = ctx->Light._BaseColor;
GLfloat sumA[2];
const GLuint vstride = input->stride;
const GLfloat *vertex = (GLfloat *) input->data;
const GLuint nstride = VB->AttribPtr[_TNL_ATTRIB_NORMAL]->stride;
const GLfloat *normal = (GLfloat *)VB->AttribPtr[_TNL_ATTRIB_NORMAL]->data;
GLfloat (*Fcolor)[4] = (GLfloat (*)[4]) store->LitColor[0].data;
#if IDX & LIGHT_TWOSIDE
GLfloat (*Bcolor)[4] = (GLfloat (*)[4]) store->LitColor[1].data;
#endif
const GLuint nr = VB->Count;
#ifdef TRACE
fprintf(stderr, "%s\n", __FUNCTION__ );
#endif
VB->AttribPtr[_TNL_ATTRIB_COLOR0] = &store->LitColor[0];
sumA[0] = ctx->Light.Material.Attrib[MAT_ATTRIB_FRONT_DIFFUSE][3];
#if IDX & LIGHT_TWOSIDE
VB->BackfaceColorPtr = &store->LitColor[1];
sumA[1] = ctx->Light.Material.Attrib[MAT_ATTRIB_BACK_DIFFUSE][3];
#endif
store->LitColor[0].stride = 16;
store->LitColor[1].stride = 16;
for (j = 0; j < nr; j++,STRIDE_F(vertex,vstride),STRIDE_F(normal,nstride)) {
GLfloat sum[2][3];
struct gl_light *light;
#if IDX & LIGHT_MATERIAL
update_materials( ctx, store );
sumA[0] = ctx->Light.Material.Attrib[MAT_ATTRIB_FRONT_DIFFUSE][3];
#if IDX & LIGHT_TWOSIDE
sumA[1] = ctx->Light.Material.Attrib[MAT_ATTRIB_BACK_DIFFUSE][3];
#endif
#endif
COPY_3V(sum[0], base[0]);
#if IDX & LIGHT_TWOSIDE
COPY_3V(sum[1], base[1]);
#endif
/* Add contribution from each enabled light source */
foreach (light, &ctx->Light.EnabledList) {
GLfloat n_dot_h;
GLfloat correction;
GLint side;
GLfloat contrib[3];
GLfloat attenuation = 1.0;
GLfloat VP[3]; /* unit vector from vertex to light */
GLfloat n_dot_VP; /* n dot VP */
GLfloat *h;
/* compute VP and attenuation */
if (!(light->_Flags & LIGHT_POSITIONAL)) {
/* directional light */
COPY_3V(VP, light->_VP_inf_norm);
attenuation = light->_VP_inf_spot_attenuation;
}
else {
GLfloat d; /* distance from vertex to light */
SUB_3V(VP, light->_Position, vertex);
d = (GLfloat) LEN_3FV( VP );
if ( d > 1e-6) {
GLfloat invd = 1.0F / d;
SELF_SCALE_SCALAR_3V(VP, invd);
}
attenuation = 1.0F / (light->ConstantAttenuation + d *
(light->LinearAttenuation + d *
light->QuadraticAttenuation));
/* spotlight attenuation */
if (light->_Flags & LIGHT_SPOT) {
GLfloat PV_dot_dir = - DOT3(VP, light->_NormSpotDirection);
if (PV_dot_dir<light->_CosCutoff) {
continue; /* this light makes no contribution */
}
else {
GLdouble x = PV_dot_dir * (EXP_TABLE_SIZE-1);
GLint k = (GLint) x;
GLfloat spot = (GLfloat) (light->_SpotExpTable[k][0]
+ (x-k)*light->_SpotExpTable[k][1]);
attenuation *= spot;
}
}
}
if (attenuation < 1e-3)
continue; /* this light makes no contribution */
/* Compute dot product or normal and vector from V to light pos */
n_dot_VP = DOT3( normal, VP );
/* which side are we lighting? */
if (n_dot_VP < 0.0F) {
ACC_SCALE_SCALAR_3V(sum[0], attenuation, light->_MatAmbient[0]);
#if IDX & LIGHT_TWOSIDE
side = 1;
correction = -1;
n_dot_VP = -n_dot_VP;
#else
continue;
#endif
}
else {
#if IDX & LIGHT_TWOSIDE
ACC_SCALE_SCALAR_3V( sum[1], attenuation, light->_MatAmbient[1]);
#endif
side = 0;
correction = 1;
}
COPY_3V(contrib, light->_MatAmbient[side]);
/* diffuse term */
ACC_SCALE_SCALAR_3V(contrib, n_dot_VP, light->_MatDiffuse[side]);
/* specular term - cannibalize VP... */
{
if (ctx->Light.Model.LocalViewer) {
GLfloat v[3];
COPY_3V(v, vertex);
NORMALIZE_3FV(v);
SUB_3V(VP, VP, v); /* h = VP + VPe */
h = VP;
NORMALIZE_3FV(h);
}
else if (light->_Flags & LIGHT_POSITIONAL) {
h = VP;
ACC_3V(h, ctx->_EyeZDir);
NORMALIZE_3FV(h);
}
else {
h = light->_h_inf_norm;
}
n_dot_h = correction * DOT3(normal, h);
if (n_dot_h > 0.0F)
{
GLfloat spec_coef;
struct gl_shine_tab *tab = ctx->_ShineTable[side];
GET_SHINE_TAB_ENTRY( tab, n_dot_h, spec_coef );
ACC_SCALE_SCALAR_3V( contrib, spec_coef,
light->_MatSpecular[side]);
}
}
ACC_SCALE_SCALAR_3V( sum[side], attenuation, contrib );
}
COPY_3V( Fcolor[j], sum[0] );
Fcolor[j][3] = sumA[0];
#if IDX & LIGHT_TWOSIDE
COPY_3V( Bcolor[j], sum[1] );
Bcolor[j][3] = sumA[1];
#endif
}
}
/* As below, but with just a single light.
*/
static void TAG(light_fast_rgba_single)( struct gl_context *ctx,
struct vertex_buffer *VB,
struct tnl_pipeline_stage *stage,
GLvector4f *input )
{
struct light_stage_data *store = LIGHT_STAGE_DATA(stage);
const GLuint nstride = VB->AttribPtr[_TNL_ATTRIB_NORMAL]->stride;
const GLfloat *normal = (GLfloat *)VB->AttribPtr[_TNL_ATTRIB_NORMAL]->data;
GLfloat (*Fcolor)[4] = (GLfloat (*)[4]) store->LitColor[0].data;
#if IDX & LIGHT_TWOSIDE
GLfloat (*Bcolor)[4] = (GLfloat (*)[4]) store->LitColor[1].data;
#endif
const struct gl_light *light = ctx->Light.EnabledList.next;
GLuint j = 0;
GLfloat base[2][4];
#if IDX & LIGHT_MATERIAL
const GLuint nr = VB->Count;
#else
const GLuint nr = VB->AttribPtr[_TNL_ATTRIB_NORMAL]->count;
#endif
#ifdef TRACE
fprintf(stderr, "%s\n", __FUNCTION__ );
#endif
(void) input; /* doesn't refer to Eye or Obj */
VB->AttribPtr[_TNL_ATTRIB_COLOR0] = &store->LitColor[0];
#if IDX & LIGHT_TWOSIDE
VB->BackfaceColorPtr = &store->LitColor[1];
#endif
if (nr > 1) {
store->LitColor[0].stride = 16;
store->LitColor[1].stride = 16;
}
else {
store->LitColor[0].stride = 0;
store->LitColor[1].stride = 0;
}
for (j = 0; j < nr; j++, STRIDE_F(normal,nstride)) {
GLfloat n_dot_VP;
#if IDX & LIGHT_MATERIAL
update_materials( ctx, store );
#endif
/* No attenuation, so incoporate _MatAmbient into base color.
*/
#if !(IDX & LIGHT_MATERIAL)
if ( j == 0 )
#endif
{
COPY_3V(base[0], light->_MatAmbient[0]);
ACC_3V(base[0], ctx->Light._BaseColor[0] );
base[0][3] = ctx->Light.Material.Attrib[MAT_ATTRIB_FRONT_DIFFUSE][3];
#if IDX & LIGHT_TWOSIDE
COPY_3V(base[1], light->_MatAmbient[1]);
ACC_3V(base[1], ctx->Light._BaseColor[1]);
base[1][3] = ctx->Light.Material.Attrib[MAT_ATTRIB_BACK_DIFFUSE][3];
#endif
}
n_dot_VP = DOT3(normal, light->_VP_inf_norm);
if (n_dot_VP < 0.0F) {
#if IDX & LIGHT_TWOSIDE
GLfloat n_dot_h = -DOT3(normal, light->_h_inf_norm);
GLfloat sum[3];
COPY_3V(sum, base[1]);
ACC_SCALE_SCALAR_3V(sum, -n_dot_VP, light->_MatDiffuse[1]);
if (n_dot_h > 0.0F) {
GLfloat spec;
GET_SHINE_TAB_ENTRY( ctx->_ShineTable[1], n_dot_h, spec );
ACC_SCALE_SCALAR_3V(sum, spec, light->_MatSpecular[1]);
}
COPY_3V(Bcolor[j], sum );
Bcolor[j][3] = base[1][3];
#endif
COPY_4FV(Fcolor[j], base[0]);
}
else {
GLfloat n_dot_h = DOT3(normal, light->_h_inf_norm);
GLfloat sum[3];
COPY_3V(sum, base[0]);
ACC_SCALE_SCALAR_3V(sum, n_dot_VP, light->_MatDiffuse[0]);
if (n_dot_h > 0.0F) {
GLfloat spec;
GET_SHINE_TAB_ENTRY( ctx->_ShineTable[0], n_dot_h, spec );
ACC_SCALE_SCALAR_3V(sum, spec, light->_MatSpecular[0]);
}
COPY_3V(Fcolor[j], sum );
Fcolor[j][3] = base[0][3];
#if IDX & LIGHT_TWOSIDE
COPY_4FV(Bcolor[j], base[1]);
#endif
}
}
}
/* Light infinite lights
*/
static void TAG(light_fast_rgba)( struct gl_context *ctx,
struct vertex_buffer *VB,
struct tnl_pipeline_stage *stage,
GLvector4f *input )
{
struct light_stage_data *store = LIGHT_STAGE_DATA(stage);
GLfloat sumA[2];
const GLuint nstride = VB->AttribPtr[_TNL_ATTRIB_NORMAL]->stride;
const GLfloat *normal = (GLfloat *)VB->AttribPtr[_TNL_ATTRIB_NORMAL]->data;
GLfloat (*Fcolor)[4] = (GLfloat (*)[4]) store->LitColor[0].data;
#if IDX & LIGHT_TWOSIDE
GLfloat (*Bcolor)[4] = (GLfloat (*)[4]) store->LitColor[1].data;
#endif
GLuint j = 0;
#if IDX & LIGHT_MATERIAL
const GLuint nr = VB->Count;
#else
const GLuint nr = VB->AttribPtr[_TNL_ATTRIB_NORMAL]->count;
#endif
const struct gl_light *light;
#ifdef TRACE
fprintf(stderr, "%s %d\n", __FUNCTION__, nr );
#endif
(void) input;
sumA[0] = ctx->Light.Material.Attrib[MAT_ATTRIB_FRONT_DIFFUSE][3];
sumA[1] = ctx->Light.Material.Attrib[MAT_ATTRIB_BACK_DIFFUSE][3];
VB->AttribPtr[_TNL_ATTRIB_COLOR0] = &store->LitColor[0];
#if IDX & LIGHT_TWOSIDE
VB->BackfaceColorPtr = &store->LitColor[1];
#endif
if (nr > 1) {
store->LitColor[0].stride = 16;
store->LitColor[1].stride = 16;
}
else {
store->LitColor[0].stride = 0;
store->LitColor[1].stride = 0;
}
for (j = 0; j < nr; j++, STRIDE_F(normal,nstride)) {
GLfloat sum[2][3];
#if IDX & LIGHT_MATERIAL
update_materials( ctx, store );
sumA[0] = ctx->Light.Material.Attrib[MAT_ATTRIB_FRONT_DIFFUSE][3];
#if IDX & LIGHT_TWOSIDE
sumA[1] = ctx->Light.Material.Attrib[MAT_ATTRIB_BACK_DIFFUSE][3];
#endif
#endif
COPY_3V(sum[0], ctx->Light._BaseColor[0]);
#if IDX & LIGHT_TWOSIDE
COPY_3V(sum[1], ctx->Light._BaseColor[1]);
#endif
foreach (light, &ctx->Light.EnabledList) {
GLfloat n_dot_h, n_dot_VP, spec;
ACC_3V(sum[0], light->_MatAmbient[0]);
#if IDX & LIGHT_TWOSIDE
ACC_3V(sum[1], light->_MatAmbient[1]);
#endif
n_dot_VP = DOT3(normal, light->_VP_inf_norm);
if (n_dot_VP > 0.0F) {
ACC_SCALE_SCALAR_3V(sum[0], n_dot_VP, light->_MatDiffuse[0]);
n_dot_h = DOT3(normal, light->_h_inf_norm);
if (n_dot_h > 0.0F) {
struct gl_shine_tab *tab = ctx->_ShineTable[0];
GET_SHINE_TAB_ENTRY( tab, n_dot_h, spec );
ACC_SCALE_SCALAR_3V( sum[0], spec, light->_MatSpecular[0]);
}
}
#if IDX & LIGHT_TWOSIDE
else {
ACC_SCALE_SCALAR_3V(sum[1], -n_dot_VP, light->_MatDiffuse[1]);
n_dot_h = -DOT3(normal, light->_h_inf_norm);
if (n_dot_h > 0.0F) {
struct gl_shine_tab *tab = ctx->_ShineTable[1];
GET_SHINE_TAB_ENTRY( tab, n_dot_h, spec );
ACC_SCALE_SCALAR_3V( sum[1], spec, light->_MatSpecular[1]);
}
}
#endif
}
COPY_3V( Fcolor[j], sum[0] );
Fcolor[j][3] = sumA[0];
#if IDX & LIGHT_TWOSIDE
COPY_3V( Bcolor[j], sum[1] );
Bcolor[j][3] = sumA[1];
#endif
}
}
static void TAG(init_light_tab)( void )
{
_tnl_light_tab[IDX] = TAG(light_rgba);
_tnl_light_fast_tab[IDX] = TAG(light_fast_rgba);
_tnl_light_fast_single_tab[IDX] = TAG(light_fast_rgba_single);
_tnl_light_spec_tab[IDX] = TAG(light_rgba_spec);
}
#undef TAG
#undef IDX
#undef NR_SIDES
| 27.607362 | 79 | 0.631056 | [
"object",
"vector",
"model"
] |
aae31d100028e1e306fd38dbff46d8091867a74e | 3,408 | h | C | Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h | acekeysoft/o3de | 3f34fa56364fc05a922fbd1250bb76fa10966cbb | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h | acekeysoft/o3de | 3f34fa56364fc05a922fbd1250bb76fa10966cbb | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h | acekeysoft/o3de | 3f34fa56364fc05a922fbd1250bb76fa10966cbb | [
"Apache-2.0",
"MIT"
] | null | null | null | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#if !defined(Q_MOC_RUN)
#include <Atom/Document/ShaderManagementConsoleDocumentNotificationBus.h>
#include <Atom/RPI.Edit/Shader/ShaderVariantListSourceData.h>
#include <Atom/RPI.Public/Shader/Shader.h>
#include <AtomToolsFramework/Window/AtomToolsMainWindow.h>
#include <AzCore/Memory/SystemAllocator.h>
AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT
#include <Window/ShaderManagementConsoleBrowserWidget.h>
#include <Window/ToolBar/ShaderManagementConsoleToolBar.h>
#include <QStandardItemModel>
AZ_POP_DISABLE_WARNING
#endif
namespace ShaderManagementConsole
{
/**
* ShaderManagementConsoleWindow is the main class. Its responsibility is limited to initializing and connecting
* its panels, managing selection of assets, and performing high-level actions like saving. It contains...
*/
class ShaderManagementConsoleWindow
: public AtomToolsFramework::AtomToolsMainWindow
, private ShaderManagementConsoleDocumentNotificationBus::Handler
{
Q_OBJECT
public:
AZ_CLASS_ALLOCATOR(ShaderManagementConsoleWindow, AZ::SystemAllocator, 0);
using Base = AtomToolsFramework::AtomToolsMainWindow;
ShaderManagementConsoleWindow(QWidget* parent = 0);
~ShaderManagementConsoleWindow();
private:
// ShaderManagementConsoleDocumentNotificationBus::Handler overrides...
void OnDocumentOpened(const AZ::Uuid& documentId) override;
void OnDocumentClosed(const AZ::Uuid& documentId) override;
void OnDocumentModified(const AZ::Uuid& documentId) override;
void OnDocumentUndoStateChanged(const AZ::Uuid& documentId) override;
void OnDocumentSaved(const AZ::Uuid& documentId) override;
void CreateMenu() override;
void CreateTabBar() override;
void OpenTabContextMenu() override;
void SelectDocumentForTab(const int tabIndex);
void CloseDocumentForTab(const int tabIndex);
void CloseAllExceptDocumentForTab(const int tabIndex);
void closeEvent(QCloseEvent* closeEvent) override;
QStandardItemModel* CreateDocumentContent(const AZ::Uuid& documentId);
ShaderManagementConsoleToolBar* m_toolBar = nullptr;
QMenu* m_menuFile = {};
QMenu* m_menuNew = {};
QAction* m_actionOpen = {};
QAction* m_actionOpenRecent = {};
QAction* m_actionClose = {};
QAction* m_actionCloseAll = {};
QAction* m_actionCloseOthers = {};
QAction* m_actionSave = {};
QAction* m_actionSaveAsCopy = {};
QAction* m_actionSaveAll = {};
QAction* m_actionExit = {};
QMenu* m_menuEdit = {};
QAction* m_actionUndo = {};
QAction* m_actionRedo = {};
QAction* m_actionSettings = {};
QMenu* m_menuView = {};
QAction* m_actionAssetBrowser = {};
QAction* m_actionPythonTerminal = {};
QAction* m_actionNextTab = {};
QAction* m_actionPreviousTab = {};
QMenu* m_menuHelp = {};
QAction* m_actionHelp = {};
QAction* m_actionAbout = {};
};
} // namespace ShaderManagementConsole
| 35.873684 | 116 | 0.700411 | [
"3d"
] |
aae4b48e3d06383e4dcd87ab71e84347f21700a6 | 3,381 | h | C | lib/lmstruct.h | aosp-caf-upstream/platform_external_lmfit | ff75e29326d9fdff9395b544df6e8efda2e62429 | [
"BSD-2-Clause"
] | 1 | 2021-06-20T09:33:14.000Z | 2021-06-20T09:33:14.000Z | lib/lmstruct.h | aosp-caf-upstream/platform_external_lmfit | ff75e29326d9fdff9395b544df6e8efda2e62429 | [
"BSD-2-Clause"
] | null | null | null | lib/lmstruct.h | aosp-caf-upstream/platform_external_lmfit | ff75e29326d9fdff9395b544df6e8efda2e62429 | [
"BSD-2-Clause"
] | null | null | null | /*
* Library: lmfit (Levenberg-Marquardt least squares fitting)
*
* File: lmstruct.h
*
* Contents: Declarations of parameter records, used in lmmin.h and lmcurve.h
*
* Copyright: Joachim Wuttke, Forschungszentrum Juelich GmbH (2004-2013)
*
* License: see ../COPYING (FreeBSD)
*
* Homepage: apps.jcns.fz-juelich.de/lmfit
*/
#ifndef LMSTRUCT_H
#define LMSTRUCT_H
#undef __BEGIN_DECLS
#undef __END_DECLS
#ifdef __cplusplus
#define __BEGIN_DECLS extern "C" {
#define __END_DECLS }
#else
#define __BEGIN_DECLS /* empty */
#define __END_DECLS /* empty */
#endif
__BEGIN_DECLS
#include <stdio.h>
/* Collection of input parameters for fit control. */
typedef struct {
double ftol; /* Relative error desired in the sum of squares.
Termination occurs when both the actual and
predicted relative reductions in the sum of squares
are at most ftol. */
double xtol; /* Relative error between last two approximations.
Termination occurs when the relative error between
two consecutive iterates is at most xtol. */
double gtol; /* Orthogonality desired between fvec and its derivs.
Termination occurs when the cosine of the angle
between fvec and any column of the Jacobian is at
most gtol in absolute value. */
double epsilon; /* Step used to calculate the Jacobian, should be
slightly larger than the relative error in the
user-supplied functions. */
double stepbound; /* Used in determining the initial step bound. This
bound is set to the product of stepbound and the
Euclidean norm of diag*x if nonzero, or else to
stepbound itself. In most cases stepbound should lie
in the interval (0.1,100.0). Generally, the value
100.0 is recommended. */
int patience; /* Used to set the maximum number of function evaluations
to patience*(number_of_parameters+1). */
int scale_diag; /* If 1, the variables will be rescaled internally.
Recommended value is 1. */
FILE* msgfile; /* Progress messages will be written to this file. */
int verbosity; /* OR'ed: 1: print some messages; 2: print Jacobian. */
int n_maxpri; /* -1, or max number of parameters to print. */
int m_maxpri; /* -1, or max number of residuals to print. */
} lm_control_struct;
/* Collection of output parameters for status info. */
typedef struct {
double fnorm; /* norm of the residue vector fvec. */
int nfev; /* actual number of iterations. */
int outcome; /* Status indicator. Nonnegative values are used as index
for the message text lm_infmsg, set in lmmin.c. */
int userbreak; /* Set when function evaluation requests termination. */
} lm_status_struct;
/* Preset (and recommended) control parameter settings. */
extern const lm_control_struct lm_control_double;
extern const lm_control_struct lm_control_float;
/* Preset message texts. */
extern const char* lm_infmsg[];
extern const char* lm_shortmsg[];
__END_DECLS
#endif /* LMSTRUCT_H */
| 41.231707 | 79 | 0.630583 | [
"vector"
] |
aae72d22fb64c67f20e8bc402af719520fd12ae0 | 190 | h | C | src/SemiColon.h | sphan007/cs100 | 13cfbb0fbbd6f75bde512276f80dbaabdbbf0e05 | [
"BSD-3-Clause"
] | null | null | null | src/SemiColon.h | sphan007/cs100 | 13cfbb0fbbd6f75bde512276f80dbaabdbbf0e05 | [
"BSD-3-Clause"
] | null | null | null | src/SemiColon.h | sphan007/cs100 | 13cfbb0fbbd6f75bde512276f80dbaabdbbf0e05 | [
"BSD-3-Clause"
] | null | null | null | #ifndef SEMICOLON_H
#define SEMICOLON_H
#include "Connector.h"
class SemiColon : public Connector {
public:
SemiColon();
void run(vector<string> &commands);
};
#endif // SEMICOLON_H
| 14.615385 | 37 | 0.726316 | [
"vector"
] |
aaea2f248d53451de6ced2452c3d1536c63beb52 | 5,672 | h | C | shared/Irrlicht/source/Irrlicht/IBurningShader.h | iProgramMC/proton | 1c383134b44a22cebab8e8db1afb17afd59dd543 | [
"XFree86-1.1"
] | 47 | 2018-07-30T12:05:15.000Z | 2022-03-31T04:12:03.000Z | shared/Irrlicht/source/Irrlicht/IBurningShader.h | iProgramMC/proton | 1c383134b44a22cebab8e8db1afb17afd59dd543 | [
"XFree86-1.1"
] | 11 | 2019-03-31T13:05:10.000Z | 2021-11-03T11:37:18.000Z | shared/Irrlicht/source/Irrlicht/IBurningShader.h | iProgramMC/proton | 1c383134b44a22cebab8e8db1afb17afd59dd543 | [
"XFree86-1.1"
] | 16 | 2019-07-09T07:59:00.000Z | 2022-02-25T15:49:06.000Z | // Copyright (C) 2002-2009 Nikolaus Gebhardt / Thomas Alten
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#ifndef __I_BURNING_SHADER_H_INCLUDED__
#define __I_BURNING_SHADER_H_INCLUDED__
#include "SoftwareDriver2_compile_config.h"
#include "IReferenceCounted.h"
#include "irrMath.h"
#include "IImage.h"
#include "S2DVertex.h"
#include "rect.h"
#include "CDepthBuffer.h"
#include "S4DVertex.h"
#include "irrArray.h"
#include "SLight.h"
#include "SMaterial.h"
#include "os.h"
namespace irr
{
namespace video
{
struct SBurningShaderLight
{
//SLight org;
bool LightIsOn;
E_LIGHT_TYPE Type;
f32 radius;
f32 linearAttenuation;
f32 constantAttenuation;
f32 quadraticAttenuation;
sVec4 pos;
sVec3 AmbientColor;
sVec3 DiffuseColor;
sVec3 SpecularColor;
sVec4 pos_objectspace;
};
enum eLightFlags
{
ENABLED = 0x01,
POINTLIGHT = 0x02,
SPECULAR = 0x04,
FOG = 0x08,
NORMALIZE = 0x10,
VERTEXTRANSFORM = 0x20,
};
struct SBurningShaderLightSpace
{
void reset ()
{
Light.set_used ( 0 );
Global_AmbientLight.set ( 0.f, 0.f, 0.f );
Flags = 0;
}
core::array<SBurningShaderLight> Light;
sVec3 Global_AmbientLight;
sVec4 FogColor;
sVec4 campos;
sVec4 vertex;
sVec4 normal;
u32 Flags;
};
struct SBurningShaderMaterial
{
SMaterial org;
sVec3 AmbientColor;
sVec3 DiffuseColor;
sVec3 SpecularColor;
sVec3 EmissiveColor;
};
enum EBurningFFShader
{
ETR_FLAT = 0,
ETR_FLAT_WIRE,
ETR_GOURAUD,
ETR_GOURAUD_WIRE,
ETR_TEXTURE_FLAT,
ETR_TEXTURE_FLAT_WIRE,
ETR_TEXTURE_GOURAUD,
ETR_TEXTURE_GOURAUD_WIRE,
ETR_TEXTURE_GOURAUD_NOZ,
ETR_TEXTURE_GOURAUD_ADD,
ETR_TEXTURE_GOURAUD_ADD_NO_Z,
ETR_TEXTURE_GOURAUD_VERTEX_ALPHA,
ETR_TEXTURE_GOURAUD_LIGHTMAP_M1,
ETR_TEXTURE_GOURAUD_LIGHTMAP_M2,
ETR_TEXTURE_GOURAUD_LIGHTMAP_M4,
ETR_TEXTURE_LIGHTMAP_M4,
ETR_TEXTURE_GOURAUD_DETAIL_MAP,
ETR_TEXTURE_GOURAUD_LIGHTMAP_ADD,
ETR_GOURAUD_ALPHA,
ETR_GOURAUD_ALPHA_NOZ,
ETR_TEXTURE_GOURAUD_ALPHA,
ETR_TEXTURE_GOURAUD_ALPHA_NOZ,
ETR_NORMAL_MAP_SOLID,
ETR_STENCIL_SHADOW,
ETR_TEXTURE_BLEND,
ETR_REFERENCE,
ETR_INVALID,
ETR2_COUNT
};
class CBurningVideoDriver;
class IBurningShader : public virtual IReferenceCounted
{
public:
IBurningShader(CBurningVideoDriver* driver);
//! destructor
virtual ~IBurningShader();
//! sets a render target
virtual void setRenderTarget(video::IImage* surface, const core::rect<s32>& viewPort);
//! sets the Texture
virtual void setTextureParam( u32 stage, video::CSoftwareTexture2* texture, s32 lodLevel);
virtual void drawTriangle ( const s4DVertex *a,const s4DVertex *b,const s4DVertex *c ) = 0;
virtual void drawLine ( const s4DVertex *a,const s4DVertex *b) {};
virtual void setParam ( u32 index, f32 value) {};
virtual void setZCompareFunc ( u32 func) {};
virtual void setMaterial ( const SBurningShaderMaterial &material ) {};
protected:
CBurningVideoDriver *Driver;
video::CImage* RenderTarget;
CDepthBuffer* DepthBuffer;
CStencilBuffer * Stencil;
tVideoSample ColorMask;
sInternalTexture IT[ BURNING_MATERIAL_MAX_TEXTURES ];
static const tFixPointu dithermask[ 4 * 4];
};
IBurningShader* createTriangleRendererTextureGouraud2(CBurningVideoDriver* driver);
IBurningShader* createTriangleRendererTextureLightMap2_M1(CBurningVideoDriver* driver);
IBurningShader* createTriangleRendererTextureLightMap2_M2(CBurningVideoDriver* driver);
IBurningShader* createTriangleRendererTextureLightMap2_M4(CBurningVideoDriver* driver);
IBurningShader* createTriangleRendererGTextureLightMap2_M4(CBurningVideoDriver* driver);
IBurningShader* createTriangleRendererTextureLightMap2_Add(CBurningVideoDriver* driver);
IBurningShader* createTriangleRendererTextureDetailMap2(CBurningVideoDriver* driver);
IBurningShader* createTriangleRendererTextureVertexAlpha2(CBurningVideoDriver* driver);
IBurningShader* createTriangleRendererTextureGouraudWire2(CBurningVideoDriver* driver);
IBurningShader* createTriangleRendererGouraud2(CBurningVideoDriver* driver);
IBurningShader* createTriangleRendererGouraudAlpha2(CBurningVideoDriver* driver);
IBurningShader* createTRGouraudAlphaNoZ2(CBurningVideoDriver* driver);
IBurningShader* createTriangleRendererGouraudWire2(CBurningVideoDriver* driver);
IBurningShader* createTriangleRendererTextureFlat2(CBurningVideoDriver* driver);
IBurningShader* createTriangleRendererTextureFlatWire2(CBurningVideoDriver* driver);
IBurningShader* createTRFlat2(CBurningVideoDriver* driver);
IBurningShader* createTRFlatWire2(CBurningVideoDriver* driver);
IBurningShader* createTRTextureGouraudNoZ2(CBurningVideoDriver* driver);
IBurningShader* createTRTextureGouraudAdd2(CBurningVideoDriver* driver);
IBurningShader* createTRTextureGouraudAddNoZ2(CBurningVideoDriver* driver);
IBurningShader* createTRTextureGouraudAlpha(CBurningVideoDriver* driver);
IBurningShader* createTRTextureGouraudAlphaNoZ(CBurningVideoDriver* driver);
IBurningShader* createTRTextureBlend(CBurningVideoDriver* driver);
IBurningShader* createTRTextureInverseAlphaBlend(CBurningVideoDriver* driver);
IBurningShader* createTRNormalMap(CBurningVideoDriver* driver);
IBurningShader* createTRStencilShadow(CBurningVideoDriver* driver);
IBurningShader* createTriangleRendererReference(CBurningVideoDriver* driver);
} // end namespace video
} // end namespace irr
#endif
| 28.079208 | 94 | 0.774154 | [
"render"
] |
aaefb3a3bb4acad2efe06d6d5e16fc428e9a7d61 | 14,418 | h | C | src/dbPv/3.14/dbPv.h | slac-epics/pvaSrv | 83d2debe492789555a5c561654c83bd53bcdadfd | [
"MIT"
] | null | null | null | src/dbPv/3.14/dbPv.h | slac-epics/pvaSrv | 83d2debe492789555a5c561654c83bd53bcdadfd | [
"MIT"
] | null | null | null | src/dbPv/3.14/dbPv.h | slac-epics/pvaSrv | 83d2debe492789555a5c561654c83bd53bcdadfd | [
"MIT"
] | null | null | null | /**
* Copyright information and license terms for this software can be
* found in the file LICENSE that is included with the distribution.
*/
/**
* @author mrk
*/
#ifndef DBPV_H
#define DBPV_H
#include <dbAccess.h>
#include <dbNotify.h>
#include <pv/thread.h>
#include <pv/event.h>
#include <pv/pvAccess.h>
#include "caMonitor.h"
#include "dbPvDebug.h"
namespace epics { namespace pvaSrv {
class DbUtil;
typedef std::tr1::shared_ptr<DbUtil> DbUtilPtr;
class DbPvProvider;
typedef std::tr1::shared_ptr<DbPvProvider> DbPvProviderPtr;
class DbPv;
typedef std::tr1::shared_ptr<DbPv> DbPvPtr;
class DbPvProcess;
class DbPvGet;
class DbPvPut;
class DbPvMonitor;
class DbPvArray;
typedef struct dbAddr DbAddr;
typedef std::vector<DbAddr> DbAddrArray;
extern DbPvProviderPtr getDbPvProvider();
class DbPvProvider :
public epics::pvAccess::ChannelProvider,
public std::tr1::enable_shared_from_this<DbPvProvider>
{
public:
POINTER_DEFINITIONS(DbPvProvider);
virtual ~DbPvProvider();
virtual std::string getProviderName();
virtual void destroy() {}
virtual epics::pvAccess::ChannelFind::shared_pointer channelFind(
std::string const &channelName,
epics::pvAccess::ChannelFindRequester::shared_pointer const & channelFindRequester);
virtual epics::pvAccess::ChannelFind::shared_pointer channelList(
epics::pvAccess::ChannelListRequester::shared_pointer const & channelListRequester);
virtual epics::pvAccess::Channel::shared_pointer createChannel(
std::string const &channelName,
epics::pvAccess::ChannelRequester::shared_pointer const &channelRequester,
short priority)
{ return createChannel(channelName,channelRequester,priority,"");}
virtual epics::pvAccess::Channel::shared_pointer createChannel(
std::string const &channelName,
epics::pvAccess::ChannelRequester::shared_pointer const &channelRequester,
short priority,
std::string const &address);
private:
shared_pointer getPtrSelf()
{
return shared_from_this();
}
DbPvProvider();
epics::pvAccess::ChannelFind::shared_pointer channelFinder;
friend DbPvProviderPtr getDbPvProvider();
};
class DbPv :
public virtual epics::pvAccess::Channel,
public std::tr1::enable_shared_from_this<DbPv>
{
public:
POINTER_DEFINITIONS(DbPv);
DbPv(
DbPvProviderPtr const & provider,
epics::pvAccess::ChannelRequester::shared_pointer const & requester,
std::string const & name,
std::tr1::shared_ptr<DbAddr> addr
);
virtual ~DbPv();
void init();
virtual void destroy(){}
virtual std::string getRequesterName()
{return requester->getRequesterName();}
virtual void message(
std::string const & message,
epics::pvData::MessageType messageType)
{requester->message(message,messageType);}
virtual epics::pvAccess::ChannelProvider::shared_pointer getProvider()
{ return provider;}
virtual std::string getRemoteAddress()
{ return "local";}
virtual epics::pvAccess::Channel::ConnectionState getConnectionState()
{ return epics::pvAccess::Channel::CONNECTED;}
virtual std::string getChannelName()
{ return name; }
virtual epics::pvAccess::ChannelRequester::shared_pointer getChannelRequester()
{ return requester;}
virtual bool isConnected()
{ return true;}
virtual void getField(
epics::pvAccess::GetFieldRequester::shared_pointer const &requester,
std::string const &subField);
virtual epics::pvAccess::AccessRights getAccessRights(
epics::pvData::PVField::shared_pointer const &pvField)
{throw std::logic_error("Not Implemented");}
virtual epics::pvAccess::ChannelProcess::shared_pointer createChannelProcess(
epics::pvAccess::ChannelProcessRequester::shared_pointer const &channelProcessRequester,
epics::pvData::PVStructurePtr const &pvRequest);
virtual epics::pvAccess::ChannelGet::shared_pointer createChannelGet(
epics::pvAccess::ChannelGetRequester::shared_pointer const &channelGetRequester,
epics::pvData::PVStructurePtr const &pvRequest);
virtual epics::pvAccess::ChannelPut::shared_pointer createChannelPut(
epics::pvAccess::ChannelPutRequester::shared_pointer const &channelPutRequester,
epics::pvData::PVStructurePtr const &pvRequest);
virtual epics::pvAccess::ChannelPutGet::shared_pointer createChannelPutGet(
epics::pvAccess::ChannelPutGetRequester::shared_pointer const &requester,
epics::pvData::PVStructure::shared_pointer const &pvRequest)
{
epics::pvData::Status status(epics::pvData::Status::STATUSTYPE_ERROR,
"ChannelPutGet not supported");
epics::pvData::StructureConstPtr nullStructure;
requester->channelPutGetConnect(
status,
epics::pvAccess::ChannelPutGet::shared_pointer(),
nullStructure,
nullStructure);
return epics::pvAccess::ChannelPutGet::shared_pointer();
}
virtual epics::pvAccess::ChannelRPC::shared_pointer createChannelRPC(
epics::pvAccess::ChannelRPCRequester::shared_pointer const &requester,
epics::pvData::PVStructure::shared_pointer const &pvRequest)
{
epics::pvData::Status status(epics::pvData::Status::STATUSTYPE_ERROR,
"ChannelRPC not supported");
requester->channelRPCConnect(
status,
epics::pvAccess::ChannelRPC::shared_pointer());
return epics::pvAccess::ChannelRPC::shared_pointer();
}
virtual epics::pvData::Monitor::shared_pointer createMonitor(
epics::pvData::MonitorRequester::shared_pointer const &monitorRequester,
epics::pvData::PVStructurePtr const &pvRequest);
virtual epics::pvAccess::ChannelArray::shared_pointer createChannelArray(
epics::pvAccess::ChannelArrayRequester::shared_pointer const &channelArrayRequester,
epics::pvData::PVStructurePtr const &pvRequest);
virtual void printInfo();
virtual void printInfo(std::ostream& out);
private:
shared_pointer getPtrSelf()
{
return shared_from_this();
}
DbPvProviderPtr provider;
epics::pvAccess::ChannelRequester::shared_pointer requester;
std::string name;
std::tr1::shared_ptr<DbAddr> dbAddr;
epics::pvData::FieldConstPtr recordField;
epics::pvData::PVStructurePtr pvNullStructure;
epics::pvData::BitSetPtr emptyBitSet;
epics::pvData::StructureConstPtr nullStructure;
};
class DbPvProcess :
public virtual epics::pvAccess::ChannelProcess,
public std::tr1::enable_shared_from_this<DbPvProcess>
{
public:
POINTER_DEFINITIONS(DbPvProcess);
DbPvProcess(
DbPvPtr const & dbPv,
epics::pvAccess::ChannelProcessRequester::shared_pointer const & channelProcessRequester,
DbAddr &dbAddr);
virtual ~DbPvProcess();
bool init(epics::pvData::PVStructurePtr const & pvRequest);
virtual std::string getRequesterName();
virtual void message(
std::string const &message,
epics::pvData::MessageType messageType);
virtual void destroy();
virtual std::tr1::shared_ptr<epics::pvAccess::Channel> getChannel()
{return dbPv;}
virtual void cancel(){}
virtual void lastRequest() {}
virtual void process();
virtual void lock();
virtual void unlock();
private:
shared_pointer getPtrSelf()
{
return shared_from_this();
}
static void notifyCallback(struct putNotify *);
DbUtilPtr dbUtil;
DbPvPtr dbPv;
epics::pvAccess::ChannelProcessRequester::shared_pointer channelProcessRequester;
DbAddr &dbAddr;
int propertyMask;
bool block;
std::string recordString;
std::string processString;
std::string fieldString;
std::string fieldListString;
std::string valueString;
std::tr1::shared_ptr<struct putNotify> pNotify;
std::tr1::shared_ptr<DbAddr> notifyAddr;
epics::pvData::Mutex mutex;
bool beingDestroyed;
};
class DbPvGet :
public virtual epics::pvAccess::ChannelGet,
public std::tr1::enable_shared_from_this<DbPvGet>
{
public:
POINTER_DEFINITIONS(DbPvGet);
DbPvGet(
DbPvPtr const & dbPv,
epics::pvAccess::ChannelGetRequester::shared_pointer const &channelGetRequester,
DbAddr &dbAddr);
virtual ~DbPvGet();
bool init(epics::pvData::PVStructurePtr const & pvRequest);
virtual std::string getRequesterName();
virtual void message(
std::string const &message,
epics::pvData::MessageType messageType);
virtual void destroy();
virtual void get();
virtual std::tr1::shared_ptr<epics::pvAccess::Channel> getChannel()
{return dbPv;}
virtual void cancel(){}
virtual void lastRequest() {}
virtual void lock();
virtual void unlock();
private:
shared_pointer getPtrSelf()
{
return shared_from_this();
}
static void notifyCallback(struct putNotify *);
DbUtilPtr dbUtil;
DbPvPtr dbPv;
epics::pvAccess::ChannelGetRequester::shared_pointer channelGetRequester;
epics::pvData::PVStructurePtr pvStructure;
epics::pvData::BitSet::shared_pointer bitSet;
DbAddr &dbAddr;
bool process;
bool block;
bool firstTime;
int propertyMask;
std::tr1::shared_ptr<struct putNotify> pNotify;
std::tr1::shared_ptr<DbAddr> notifyAddr;
epics::pvData::Event event;
epics::pvData::Mutex dataMutex;
epics::pvData::Mutex mutex;
bool beingDestroyed;
};
class DbPvPut :
public virtual epics::pvAccess::ChannelPut,
public std::tr1::enable_shared_from_this<DbPvPut>
{
public:
POINTER_DEFINITIONS(DbPvPut);
DbPvPut(
DbPvPtr const & dbPv,
epics::pvAccess::ChannelPutRequester::shared_pointer const &channelPutRequester,
DbAddr &dbAddr);
virtual ~DbPvPut();
bool init(epics::pvData::PVStructurePtr const & pvRequest);
virtual std::string getRequesterName();
virtual void message(
std::string const &message,
epics::pvData::MessageType messageType);
virtual void destroy();
virtual void put(
epics::pvData::PVStructurePtr const & pvStructure,
epics::pvData::BitSetPtr const & bitSet);
virtual std::tr1::shared_ptr<epics::pvAccess::Channel> getChannel()
{return dbPv;}
virtual void cancel(){}
virtual void lastRequest() {}
virtual void get();
virtual void lock();
virtual void unlock();
private:
shared_pointer getPtrSelf()
{
return shared_from_this();
}
static void notifyCallback(struct putNotify *);
DbUtilPtr dbUtil;
DbPvPtr dbPv;
epics::pvAccess::ChannelPutRequester::shared_pointer channelPutRequester;
epics::pvData::PVStructurePtr pvStructure;
epics::pvData::BitSet::shared_pointer bitSet;
DbAddr &dbAddr;
int propertyMask;
bool process;
bool block;
bool firstTime;
std::tr1::shared_ptr<struct putNotify> pNotify;
std::tr1::shared_ptr<DbAddr> notifyAddr;
epics::pvData::Mutex dataMutex;
epics::pvData::Mutex mutex;
bool beingDestroyed;
};
class DbPvMonitor
: public virtual epics::pvData::Monitor,
public virtual CaMonitorRequester,
public std::tr1::enable_shared_from_this<DbPvMonitor>
{
public:
POINTER_DEFINITIONS(DbPvMonitor);
DbPvMonitor(
DbPvPtr const & dbPv,
epics::pvData::MonitorRequester::shared_pointer const & monitorRequester,
DbAddr &dbAddr
);
virtual ~DbPvMonitor();
bool init(epics::pvData::PVStructurePtr const & pvRequest);
virtual std::string getRequesterName();
virtual void message(
std::string const &message,
epics::pvData::MessageType messageType);
virtual void destroy();
virtual epics::pvData::Status start();
virtual epics::pvData::Status stop();
virtual epics::pvData::MonitorElementPtr poll();
virtual void release(
epics::pvData::MonitorElementPtr const & monitorElement);
virtual void exceptionCallback(long status,long op);
virtual void connectionCallback();
virtual void accessRightsCallback();
virtual void eventCallback(const char *);
virtual void lock();
virtual void unlock();
private:
shared_pointer getPtrSelf()
{
return shared_from_this();
}
DbUtilPtr dbUtil;
epics::pvData::MonitorElementPtr &getFree();
DbPvPtr dbPv;
epics::pvData::MonitorRequester::shared_pointer monitorRequester;
DbAddr &dbAddr;
epics::pvData::Event event;
int propertyMask;
bool firstTime;
bool gotEvent;
CaType caType;
int queueSize;
std::tr1::shared_ptr<CaMonitor> caMonitor;
int numberFree;
int numberUsed;
int nextGetFree;
int nextGetUsed;
int nextReleaseUsed;
epics::pvData::Mutex mutex;
bool beingDestroyed;
bool isStarted;
epics::pvData::MonitorElementPtrArray elements;
epics::pvData::MonitorElementPtr currentElement;
epics::pvData::MonitorElementPtr nullElement;
};
class DbPvArray :
public epics::pvAccess::ChannelArray,
public std::tr1::enable_shared_from_this<DbPvArray>
{
public:
POINTER_DEFINITIONS(DbPvArray);
DbPvArray(
DbPvPtr const & dbPv,
epics::pvAccess::ChannelArrayRequester::shared_pointer const &channelArrayRequester,
DbAddr &dbAddr);
virtual ~DbPvArray();
bool init(epics::pvData::PVStructurePtr const & pvRequest);
virtual void destroy();
virtual void putArray(
epics::pvData::PVArray::shared_pointer const &putArray,
size_t offset, size_t count, size_t stride);
virtual void getArray(size_t offset, size_t count, size_t stride);
virtual void getLength();
virtual void setLength(size_t length);
virtual std::tr1::shared_ptr<epics::pvAccess::Channel> getChannel()
{return dbPv;}
virtual void cancel(){}
virtual void lastRequest() {}
virtual void lock();
virtual void unlock();
private:
shared_pointer getPtrSelf()
{
return shared_from_this();
}
DbPvPtr dbPv;
epics::pvAccess::ChannelArrayRequester::shared_pointer channelArrayRequester;
epics::pvData::PVScalarArray::shared_pointer pvScalarArray;
DbAddr &dbAddr;
epics::pvData::Mutex dataMutex;
epics::pvData::Mutex mutex;
bool beingDestroyed;
};
}}
#endif /* DBPV_H */
| 34.328571 | 97 | 0.701415 | [
"vector"
] |
aaf0044ef0415c92cd20745187182f9b75f8e9c8 | 5,305 | h | C | src/Modules/Particle/include/Thinning.h | Indomerun/pyHiChi | fdceb238dfed6433ee350d5c593ca5e2cd4fbd2b | [
"MIT"
] | 11 | 2019-08-22T12:47:40.000Z | 2022-01-28T16:07:29.000Z | src/Modules/Particle/include/Thinning.h | Indomerun/pyHiChi | fdceb238dfed6433ee350d5c593ca5e2cd4fbd2b | [
"MIT"
] | 14 | 2019-09-02T08:24:55.000Z | 2022-02-14T11:40:43.000Z | src/Modules/Particle/include/Thinning.h | Indomerun/pyHiChi | fdceb238dfed6433ee350d5c593ca5e2cd4fbd2b | [
"MIT"
] | 9 | 2019-07-31T13:25:20.000Z | 2022-01-28T16:07:45.000Z | #pragma once
#include "Constants.h"
#include "FP.h"
#include "ParticleArray.h"
#include <algorithm>
#include <random>
#include <vector>
namespace pfc
{
template<class ParticleArray>
class Thinning
{
public:
static void simple(ParticleArray& particles, int m)
{
std::random_device rd;
std::mt19937 generator(rd());
int sizeArray = particles.size();
for (int i = 0; i < sizeArray - m; i++)
{
std::uniform_int_distribution<int> dist(0, sizeArray - i - 1);
int deleteIdx = dist(generator);
particles.deleteParticle(deleteIdx);
}
FP newCoeff = static_cast<FP>(sizeArray) / (static_cast<FP>(m));
for (int idx = 0; idx < particles.size(); idx++)
{
FP weight = particles[idx].getWeight();
particles[idx].setWeight(weight * newCoeff);
}
}
static void leveling(ParticleArray& particles)
{
std::random_device rd;
std::mt19937 generator(rd());
std::uniform_real_distribution<FP> dist(0, 1);
FP weightAvg = 0.0;
for (int idx = 0; idx < particles.size(); idx++)
{
weightAvg += particles[idx].getWeight() / particles.size();
}
FP threshold = 2 * weightAvg;
for (int idx = particles.size() - 1; idx >= 0; idx--)
{
if (particles[idx].getWeight() < threshold)
{
FP randNumber = dist(generator);
if (randNumber > particles[idx].getWeight() / threshold)
{
particles.deleteParticle(idx);
}
else
{
particles[idx].setWeight(threshold);
}
}
}
}
static void numberConservative(ParticleArray& particles, int m)
{
std::random_device rd;
std::mt19937 generator(rd());
FP weightSum = 0.0;
for (int idx = 0; idx < particles.size(); idx++)
{
weightSum += particles[idx].getWeight();
}
std::uniform_real_distribution<FP> dist(0, weightSum);
std::vector<FP> randomNumbers;
randomNumbers.resize(m + 1);
for (int idx = 0; idx < m; idx++)
{
randomNumbers[idx] = dist(generator);
}
randomNumbers[m] = weightSum * 2;
std::sort(randomNumbers.begin(), randomNumbers.end());
int idxNumber = 0;
FP currentWeightSum = 0.0;
for (int idx = particles.size() - 1; idx >= 0; idx--)
{
int ki = 0;
currentWeightSum += particles[idx].getWeight();
while (currentWeightSum > randomNumbers[idxNumber])
{
ki++;
idxNumber++;
}
if (ki == 0)
{
particles.deleteParticle(idx);
}
else
{
FP newCoeff = static_cast<FP>(ki) / static_cast<FP>(m);
particles[idx].setWeight(newCoeff * weightSum);
}
}
}
static void energyConservative(ParticleArray& particles, int m)
{
std::random_device rd;
std::mt19937 generator(rd());
FP energySum = 0.0;
std::vector<FP> energys;
for (int idx = 0; idx < particles.size(); idx++)
{
FP mass = particles[idx].getMass();
FP c = Constants<FP>::lightVelocity();
FP mc = mass * c;
FP energyParticle = sqrt(mc * mc + particles[idx].getMomentum().norm2());
energys.push_back(energyParticle);
energySum += particles[idx].getWeight() * energyParticle;
}
std::uniform_real_distribution<FP> dist(0, energySum);
std::vector<FP> randomNumbers;
randomNumbers.resize(m + 1);
for (int idx = 0; idx < m; idx++)
{
randomNumbers[idx] = dist(generator);
}
randomNumbers[m] = energySum * 2;
std::sort(randomNumbers.begin(), randomNumbers.end());
int idxNumber = 0;
FP currentEnergySum = 0.0;
for (int idx = particles.size() - 1; idx >= 0; idx--)
{
int ki = 0;
currentEnergySum += particles[idx].getWeight() * energys[idx];
while (currentEnergySum > randomNumbers[idxNumber])
{
ki++;
idxNumber++;
}
if (ki == 0)
{
particles.deleteParticle(idx);
}
else
{
FP newCoeff = static_cast<FP>(ki) / static_cast<FP>(m);
particles[idx].setWeight(newCoeff * energySum / energys[idx]);
}
}
}
};
} | 33.575949 | 89 | 0.453157 | [
"vector"
] |
aaf354f0f48bd24274ab6a70ab37f2da6eb32cb9 | 867 | h | C | code/tools/popart-current1/src/seqio/ParserTools.h | kibet-gilbert/co1_metaanalysis | 1089cc03bc4dbabab543a8dadf49130d8e399665 | [
"CC-BY-3.0"
] | 1 | 2021-01-01T05:57:08.000Z | 2021-01-01T05:57:08.000Z | code/tools/popart-current1/src/seqio/ParserTools.h | kibet-gilbert/co1_metaanalysis | 1089cc03bc4dbabab543a8dadf49130d8e399665 | [
"CC-BY-3.0"
] | null | null | null | code/tools/popart-current1/src/seqio/ParserTools.h | kibet-gilbert/co1_metaanalysis | 1089cc03bc4dbabab543a8dadf49130d8e399665 | [
"CC-BY-3.0"
] | 1 | 2021-01-01T06:15:56.000Z | 2021-01-01T06:15:56.000Z | /*
* ParserTools.h
*
* Created on: May 22, 2013
* Author: jleigh
*/
#ifndef PARSERTOOLS_H_
#define PARSERTOOLS_H_
#include <iostream>
#include <string>
#include <vector>
class ParserTools
{
public:
static std::string & strip(std::string &);
static std::string & rstrip(std::string &);
static std::string & lstrip(std::string &);
static void tokenise(std::vector<std::string> &, const std::string &, const std::string & = " \t\n\r", bool = true);
static bool caselessmatch(char, char);
static size_t caselessfind(const std::string &, const std::string &);
static std::string & replaceChars(std::string &, char, char);
static std::string & eraseChars(std::string &, char);
static std::string & lower(std::string &);
static std::string & upper(std::string &);
static char getEOLchar(std::istream &);
};
#endif /* PARSERTOOLS_H_ */
| 26.272727 | 119 | 0.670127 | [
"vector"
] |
aaf802ef6184ef7bf372a3448b9b74e8a82c6138 | 7,004 | h | C | examples/peripherals/uart/nmea0183_parser/main/nmea_parser.h | DCNick3/esp-idf | b0150615dff529662772a60dcb57d5b559f480e2 | [
"Apache-2.0"
] | 8,747 | 2016-08-18T14:58:24.000Z | 2022-03-31T20:58:55.000Z | examples/peripherals/uart/nmea0183_parser/main/nmea_parser.h | DCNick3/esp-idf | b0150615dff529662772a60dcb57d5b559f480e2 | [
"Apache-2.0"
] | 8,603 | 2016-08-20T08:55:56.000Z | 2022-03-31T23:04:01.000Z | examples/peripherals/uart/nmea0183_parser/main/nmea_parser.h | DCNick3/esp-idf | b0150615dff529662772a60dcb57d5b559f480e2 | [
"Apache-2.0"
] | 6,380 | 2016-08-18T18:17:00.000Z | 2022-03-31T22:25:57.000Z | // Copyright 2015-2018 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include "esp_types.h"
#include "esp_event.h"
#include "esp_err.h"
#include "driver/uart.h"
#define GPS_MAX_SATELLITES_IN_USE (12)
#define GPS_MAX_SATELLITES_IN_VIEW (16)
/**
* @brief Declare of NMEA Parser Event base
*
*/
ESP_EVENT_DECLARE_BASE(ESP_NMEA_EVENT);
/**
* @brief GPS fix type
*
*/
typedef enum {
GPS_FIX_INVALID, /*!< Not fixed */
GPS_FIX_GPS, /*!< GPS */
GPS_FIX_DGPS, /*!< Differential GPS */
} gps_fix_t;
/**
* @brief GPS fix mode
*
*/
typedef enum {
GPS_MODE_INVALID = 1, /*!< Not fixed */
GPS_MODE_2D, /*!< 2D GPS */
GPS_MODE_3D /*!< 3D GPS */
} gps_fix_mode_t;
/**
* @brief GPS satellite information
*
*/
typedef struct {
uint8_t num; /*!< Satellite number */
uint8_t elevation; /*!< Satellite elevation */
uint16_t azimuth; /*!< Satellite azimuth */
uint8_t snr; /*!< Satellite signal noise ratio */
} gps_satellite_t;
/**
* @brief GPS time
*
*/
typedef struct {
uint8_t hour; /*!< Hour */
uint8_t minute; /*!< Minute */
uint8_t second; /*!< Second */
uint16_t thousand; /*!< Thousand */
} gps_time_t;
/**
* @brief GPS date
*
*/
typedef struct {
uint8_t day; /*!< Day (start from 1) */
uint8_t month; /*!< Month (start from 1) */
uint16_t year; /*!< Year (start from 2000) */
} gps_date_t;
/**
* @brief NMEA Statement
*
*/
typedef enum {
STATEMENT_UNKNOWN = 0, /*!< Unknown statement */
STATEMENT_GGA, /*!< GGA */
STATEMENT_GSA, /*!< GSA */
STATEMENT_RMC, /*!< RMC */
STATEMENT_GSV, /*!< GSV */
STATEMENT_GLL, /*!< GLL */
STATEMENT_VTG /*!< VTG */
} nmea_statement_t;
/**
* @brief GPS object
*
*/
typedef struct {
float latitude; /*!< Latitude (degrees) */
float longitude; /*!< Longitude (degrees) */
float altitude; /*!< Altitude (meters) */
gps_fix_t fix; /*!< Fix status */
uint8_t sats_in_use; /*!< Number of satellites in use */
gps_time_t tim; /*!< time in UTC */
gps_fix_mode_t fix_mode; /*!< Fix mode */
uint8_t sats_id_in_use[GPS_MAX_SATELLITES_IN_USE]; /*!< ID list of satellite in use */
float dop_h; /*!< Horizontal dilution of precision */
float dop_p; /*!< Position dilution of precision */
float dop_v; /*!< Vertical dilution of precision */
uint8_t sats_in_view; /*!< Number of satellites in view */
gps_satellite_t sats_desc_in_view[GPS_MAX_SATELLITES_IN_VIEW]; /*!< Information of satellites in view */
gps_date_t date; /*!< Fix date */
bool valid; /*!< GPS validity */
float speed; /*!< Ground speed, unit: m/s */
float cog; /*!< Course over ground */
float variation; /*!< Magnetic variation */
} gps_t;
/**
* @brief Configuration of NMEA Parser
*
*/
typedef struct {
struct {
uart_port_t uart_port; /*!< UART port number */
uint32_t rx_pin; /*!< UART Rx Pin number */
uint32_t baud_rate; /*!< UART baud rate */
uart_word_length_t data_bits; /*!< UART data bits length */
uart_parity_t parity; /*!< UART parity */
uart_stop_bits_t stop_bits; /*!< UART stop bits length */
uint32_t event_queue_size; /*!< UART event queue size */
} uart; /*!< UART specific configuration */
} nmea_parser_config_t;
/**
* @brief NMEA Parser Handle
*
*/
typedef void *nmea_parser_handle_t;
/**
* @brief Default configuration for NMEA Parser
*
*/
#define NMEA_PARSER_CONFIG_DEFAULT() \
{ \
.uart = { \
.uart_port = UART_NUM_1, \
.rx_pin = 2, \
.baud_rate = 9600, \
.data_bits = UART_DATA_8_BITS, \
.parity = UART_PARITY_DISABLE, \
.stop_bits = UART_STOP_BITS_1, \
.event_queue_size = 16 \
} \
}
/**
* @brief NMEA Parser Event ID
*
*/
typedef enum {
GPS_UPDATE, /*!< GPS information has been updated */
GPS_UNKNOWN /*!< Unknown statements detected */
} nmea_event_id_t;
/**
* @brief Init NMEA Parser
*
* @param config Configuration of NMEA Parser
* @return nmea_parser_handle_t handle of NMEA parser
*/
nmea_parser_handle_t nmea_parser_init(const nmea_parser_config_t *config);
/**
* @brief Deinit NMEA Parser
*
* @param nmea_hdl handle of NMEA parser
* @return esp_err_t ESP_OK on success, ESP_FAIL on error
*/
esp_err_t nmea_parser_deinit(nmea_parser_handle_t nmea_hdl);
/**
* @brief Add user defined handler for NMEA parser
*
* @param nmea_hdl handle of NMEA parser
* @param event_handler user defined event handler
* @param handler_args handler specific arguments
* @return esp_err_t
* - ESP_OK: Success
* - ESP_ERR_NO_MEM: Cannot allocate memory for the handler
* - ESP_ERR_INVALIG_ARG: Invalid combination of event base and event id
* - Others: Fail
*/
esp_err_t nmea_parser_add_handler(nmea_parser_handle_t nmea_hdl, esp_event_handler_t event_handler, void *handler_args);
/**
* @brief Remove user defined handler for NMEA parser
*
* @param nmea_hdl handle of NMEA parser
* @param event_handler user defined event handler
* @return esp_err_t
* - ESP_OK: Success
* - ESP_ERR_INVALIG_ARG: Invalid combination of event base and event id
* - Others: Fail
*/
esp_err_t nmea_parser_remove_handler(nmea_parser_handle_t nmea_hdl, esp_event_handler_t event_handler);
#ifdef __cplusplus
}
#endif
| 31.981735 | 120 | 0.559966 | [
"object",
"3d"
] |
aafa8688c52831e9d667be60865749aa425c5418 | 3,527 | h | C | chrome/browser/sync/glue/new_non_frontend_data_type_controller.h | Scopetta197/chromium | b7bf8e39baadfd9089de2ebdc0c5d982de4a9820 | [
"BSD-3-Clause"
] | 212 | 2015-01-31T11:55:58.000Z | 2022-02-22T06:35:11.000Z | chrome/browser/sync/glue/new_non_frontend_data_type_controller.h | Scopetta197/chromium | b7bf8e39baadfd9089de2ebdc0c5d982de4a9820 | [
"BSD-3-Clause"
] | 5 | 2015-03-27T14:29:23.000Z | 2019-09-25T13:23:12.000Z | chrome/browser/sync/glue/new_non_frontend_data_type_controller.h | Scopetta197/chromium | b7bf8e39baadfd9089de2ebdc0c5d982de4a9820 | [
"BSD-3-Clause"
] | 221 | 2015-01-07T06:21:24.000Z | 2022-02-11T02:51:12.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_SYNC_GLUE_NEW_NON_FRONTEND_DATA_TYPE_CONTROLLER_H_
#define CHROME_BROWSER_SYNC_GLUE_NEW_NON_FRONTEND_DATA_TYPE_CONTROLLER_H_
#pragma once
#include "base/compiler_specific.h"
#include "base/memory/weak_ptr.h"
#include "chrome/browser/sync/glue/non_frontend_data_type_controller.h"
#include "chrome/browser/sync/glue/shared_change_processor.h"
class SyncableService;
namespace browser_sync {
class NewNonFrontendDataTypeController : public NonFrontendDataTypeController {
public:
NewNonFrontendDataTypeController(
ProfileSyncComponentsFactory* profile_sync_factory,
Profile* profile,
ProfileSyncService* sync_service);
virtual void Start(const StartCallback& start_callback) OVERRIDE;
virtual void Stop() OVERRIDE;
protected:
friend class NewNonFrontendDataTypeControllerMock;
NewNonFrontendDataTypeController();
virtual ~NewNonFrontendDataTypeController();
// Overrides of NonFrontendDataTypeController methods.
virtual void StartDone(DataTypeController::StartResult result,
DataTypeController::State new_state,
const SyncError& error) OVERRIDE;
virtual void StartDoneImpl(DataTypeController::StartResult result,
DataTypeController::State new_state,
const SyncError& error) OVERRIDE;
virtual bool StartAssociationAsync() OVERRIDE;
private:
// Posted on the backend thread by StartAssociationAsync().
void StartAssociationWithSharedChangeProcessor(
const scoped_refptr<SharedChangeProcessor>& shared_change_processor);
// Calls Disconnect() on |shared_change_processor_|, then sets it to
// NULL. Must be called only by StartDoneImpl() or Stop() (on the
// UI thread) and only after a call to Start() (i.e.,
// |shared_change_processor_| must be non-NULL).
void ClearSharedChangeProcessor();
// Posts StopLocalService() to the datatype's thread.
void StopLocalServiceAsync();
// Calls local_service_->StopSyncing() and releases our references to it.
void StopLocalService();
// Deprecated.
virtual void CreateSyncComponents() OVERRIDE;
// The shared change processor is the thread-safe interface to the
// datatype. We hold a reference to it from the UI thread so that
// we can call Disconnect() on it from Stop()/StartDoneImpl(). Most
// of the work is done on the backend thread, and in
// StartAssociationWithSharedChangeProcessor() for this class in
// particular.
//
// Lifetime: The SharedChangeProcessor object is created on the UI
// thread and passed on to the backend thread. This reference is
// released on the UI thread in Stop()/StartDoneImpl(), but the
// backend thread may still have references to it (which is okay,
// since we call Disconnect() before releasing the UI thread
// reference).
scoped_refptr<SharedChangeProcessor> shared_change_processor_;
// A weak pointer to the actual local syncable service, which performs all the
// real work. We do not own the object, and it is only safe to access on the
// DataType's thread.
// Lifetime: it gets set in StartAssociation() and released in
// StopLocalService().
base::WeakPtr<SyncableService> local_service_;
};
} // namespace browser_sync
#endif // CHROME_BROWSER_SYNC_GLUE_NEW_NON_FRONTEND_DATA_TYPE_CONTROLLER_H_
| 39.629213 | 80 | 0.755033 | [
"object"
] |
c900ba9ec13b4988612a3308d92ebc587ce1c7fd | 2,817 | h | C | cegui/include/CEGUI/RendererModules/OpenGL/GeometryBufferBase.h | bolry/cegui | 58b776a157409cb13092b77d68ab2618cf5c6e05 | [
"MIT"
] | 257 | 2020-01-03T10:13:29.000Z | 2022-03-26T14:55:12.000Z | cegui/include/CEGUI/RendererModules/OpenGL/GeometryBufferBase.h | bolry/cegui | 58b776a157409cb13092b77d68ab2618cf5c6e05 | [
"MIT"
] | 116 | 2020-01-09T18:13:13.000Z | 2022-03-15T18:32:02.000Z | cegui/include/CEGUI/RendererModules/OpenGL/GeometryBufferBase.h | bolry/cegui | 58b776a157409cb13092b77d68ab2618cf5c6e05 | [
"MIT"
] | 58 | 2020-01-09T03:07:02.000Z | 2022-03-22T17:21:36.000Z | /***********************************************************************
created: Tue Apr 30 2013
authors: Paul D Turner <paul@cegui.org.uk>
Lukas Meindl
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* 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 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 _CEGUIGeometryBufferBase_h_
#define _CEGUIGeometryBufferBase_h_
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/RendererModules/OpenGL/RendererBase.h"
#include "CEGUI/Rectf.h"
#include "CEGUI/RefCounted.h"
#include <utility>
#include <vector>
#if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable : 4251)
#endif
namespace CEGUI
{
class OpenGLTexture;
class RenderMaterial;
/*!
\brief
OpenGL based implementation of the GeometryBuffer interface.
*/
class OPENGL_GUIRENDERER_API OpenGLGeometryBufferBase : public GeometryBuffer
{
public:
//! Constructor
OpenGLGeometryBufferBase(OpenGLRendererBase& owner, CEGUI::RefCounted<RenderMaterial> renderMaterial);
virtual ~OpenGLGeometryBufferBase();
/*
\brief
The update function that is to be called when all the vertex attributes
are set.
*/
virtual void finaliseVertexAttributes() const {}
protected:
//! Update the cached matrices
void updateMatrix() const;
//! OpenGLRendererBase that owns the GeometryBuffer.
OpenGLRendererBase& d_owner;
//! Cache of the model view projection matrix
mutable glm::mat4 d_matrix;
};
}
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
#endif
| 32.755814 | 106 | 0.653532 | [
"vector",
"model"
] |
c9032d9437edc95a1e17dacea9b5c9e89498e98c | 3,424 | h | C | include/dataloader/modelloader/model_loader.h | b-it-bots/mas_kb_visualisation | 062f6229d2b435bcdd6f66484ac5d411ee742bbc | [
"MIT"
] | null | null | null | include/dataloader/modelloader/model_loader.h | b-it-bots/mas_kb_visualisation | 062f6229d2b435bcdd6f66484ac5d411ee742bbc | [
"MIT"
] | 4 | 2020-11-20T18:01:37.000Z | 2020-11-27T08:39:57.000Z | include/dataloader/modelloader/model_loader.h | b-it-bots/mas_kb_visualisation | 062f6229d2b435bcdd6f66484ac5d411ee742bbc | [
"MIT"
] | null | null | null | /*
* MIT License
*
* Copyright (c) 2020 Ahmed Faisal Abdelrahman, Sushant Vijay Chavan
*
* 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 DATALOADER_MODEL_LOADER
#define DATALOADER_MODEL_LOADER
#include<string>
#include<memory>
#include<vector>
#include <geometry_msgs/Point.h>
#include "dataloader/modelloader/yaml_loader.h"
#include "dataloader/modelloader/model_data.h"
namespace RVizDataLoader
{
class ModelLoader
{
public:
ModelLoader(const std::string& model_config_path);
virtual ~ModelLoader(){}
typedef std::pair<std::unique_ptr<visualization_msgs::Marker>, std::unique_ptr<visualization_msgs::Marker>> MarkerResultPair;
auto getMeshMarker(int id,
Mesh::Types type,
const std::string& name,
const std::string& frame_id,
const std::string& ns,
const Utils::Pose<double>& pose = Utils::Pose<double>())
-> MarkerResultPair;
auto getPlaneMarker(int id,
const std::string& name,
const std::string& frame_id,
const std::string& ns,
const Utils::Vec3<double>& center,
const Utils::Vec3Array<double>& convex_hull,
const Utils::Vec4<double>& color = Utils::Vec4<double>(1.0, 0.0, 0.0, 1.0),
const Utils::Vec3<double>& scale = Utils::Vec3<double>(1.0, 1.0, 1.0))
-> MarkerResultPair;
protected:
virtual auto loadModel(Mesh::Types model_type)
-> std::unique_ptr<visualization_msgs::Marker>;
virtual auto getTextLabelMarker(const std::string& name,
const Utils::Vec3<double>& pos)
-> std::unique_ptr<visualization_msgs::Marker>;
virtual auto generateTraingleVertices(const Utils::Vec3<double>& center,
const Utils::Vec3Array<double>& convex_hull)
-> std::vector<geometry_msgs::Point>;
geometry_msgs::Point asRVizPoint(const Utils::Vec3<double>& point);
YamlLoader yaml_loader_;
};
};
#endif // DATALOADER_MODEL_LOADER
| 40.761905 | 133 | 0.618575 | [
"mesh",
"vector"
] |
c9072ba872a8157e320c399c254133d21222ba36 | 28,546 | c | C | components/bt/esp_ble_mesh/mesh_core/proxy_client.c | bastianhjaeger/esp-idf | 52042e3e6bf86ee9e7f3b230d267a18ff1b02eeb | [
"Apache-2.0"
] | 6 | 2018-01-07T15:23:15.000Z | 2020-08-03T05:42:03.000Z | components/bt/esp_ble_mesh/mesh_core/proxy_client.c | bastianhjaeger/esp-idf | 52042e3e6bf86ee9e7f3b230d267a18ff1b02eeb | [
"Apache-2.0"
] | 1 | 2021-03-11T19:14:47.000Z | 2021-03-11T19:14:47.000Z | components/bt/esp_ble_mesh/mesh_core/proxy_client.c | bastianhjaeger/esp-idf | 52042e3e6bf86ee9e7f3b230d267a18ff1b02eeb | [
"Apache-2.0"
] | 6 | 2018-07-28T16:14:42.000Z | 2020-02-13T10:14:44.000Z | // Copyright 2017-2019 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <string.h>
#include <errno.h>
#include "mesh.h"
#include "access.h"
#include "beacon.h"
#include "transport.h"
#include "mesh_common.h"
#include "foundation.h"
#include "proxy_client.h"
#include "provisioner_prov.h"
#include "provisioner_main.h"
#include "mesh_bearer_adapt.h"
#define PDU_TYPE(data) (data[0] & BIT_MASK(6))
#define PDU_SAR(data) (data[0] >> 6)
#define PROXY_SAR_TIMEOUT K_SECONDS(20)
#define SAR_COMPLETE 0x00
#define SAR_FIRST 0x01
#define SAR_CONT 0x02
#define SAR_LAST 0x03
#define PDU_HDR(sar, type) (sar << 6 | (type & BIT_MASK(6)))
#define SERVER_BUF_SIZE 68
#if (CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH_PB_GATT) || \
CONFIG_BLE_MESH_GATT_PROXY_CLIENT
static struct bt_mesh_proxy_server {
struct bt_mesh_conn *conn;
enum __packed {
NONE,
PROV,
PROXY,
} conn_type;
#if CONFIG_BLE_MESH_GATT_PROXY_CLIENT
u16_t net_idx;
#endif
u8_t msg_type;
struct k_delayed_work sar_timer;
struct net_buf_simple buf;
} servers[BLE_MESH_MAX_CONN];
static u8_t server_buf_data[SERVER_BUF_SIZE * BLE_MESH_MAX_CONN];
static struct bt_mesh_proxy_server *find_server(struct bt_mesh_conn *conn)
{
int i;
for (i = 0; i < ARRAY_SIZE(servers); i++) {
if (servers[i].conn == conn) {
return &servers[i];
}
}
return NULL;
}
static void proxy_sar_timeout(struct k_work *work)
{
struct bt_mesh_proxy_server *server = NULL;
BT_WARN("%s", __func__);
server = CONTAINER_OF(work, struct bt_mesh_proxy_server, sar_timer.work);
if (!server || !server->conn) {
BT_ERR("Invalid proxy server parameter");
return;
}
net_buf_simple_reset(&server->buf);
bt_mesh_gattc_disconnect(server->conn);
}
#if CONFIG_BLE_MESH_GATT_PROXY_CLIENT
/**
* The following callbacks are used to notify proper information
* to the application layer.
*/
static proxy_client_recv_adv_cb_t proxy_client_adv_recv_cb;
static proxy_client_connect_cb_t proxy_client_connect_cb;
static proxy_client_disconnect_cb_t proxy_client_disconnect_cb;
static proxy_client_recv_filter_status_cb_t proxy_client_filter_status_recv_cb;
void bt_mesh_proxy_client_set_adv_recv_cb(proxy_client_recv_adv_cb_t cb)
{
proxy_client_adv_recv_cb = cb;
}
void bt_mesh_proxy_client_set_conn_cb(proxy_client_connect_cb_t cb)
{
proxy_client_connect_cb = cb;
}
void bt_mesh_proxy_client_set_disconn_cb(proxy_client_disconnect_cb_t cb)
{
proxy_client_disconnect_cb = cb;
}
void bt_mesh_proxy_client_set_filter_status_cb(proxy_client_recv_filter_status_cb_t cb)
{
proxy_client_filter_status_recv_cb = cb;
}
static void filter_status(struct bt_mesh_proxy_server *server,
struct bt_mesh_net_rx *rx,
struct net_buf_simple *buf)
{
u8_t filter_type = 0U;
u16_t list_size = 0U;
if (buf->len != 3) {
BT_ERR("Invalid Proxy Filter Status length %d", buf->len);
return;
}
filter_type = net_buf_simple_pull_u8(buf);
if (filter_type > 0x01) {
BT_ERR("Invalid proxy filter type 0x%02x", filter_type);
return;
}
list_size = net_buf_simple_pull_be16(buf);
BT_INFO("filter_type 0x%02x, list_size %d", filter_type, list_size);
if (proxy_client_filter_status_recv_cb) {
proxy_client_filter_status_recv_cb(server - servers, rx->ctx.addr, server->net_idx, filter_type, list_size);
}
return;
}
static void proxy_cfg(struct bt_mesh_proxy_server *server)
{
NET_BUF_SIMPLE_DEFINE(buf, 29);
struct bt_mesh_net_rx rx = {0};
u8_t opcode = 0U;
int err = 0;
if (server->buf.len > 29) {
BT_ERR("Too large proxy cfg pdu (len %d)", server->buf.len);
return;
}
err = bt_mesh_net_decode(&server->buf, BLE_MESH_NET_IF_PROXY_CFG,
&rx, &buf);
if (err) {
BT_ERR("Failed to decode Proxy Configuration (err %d)", err);
return;
}
if (!BLE_MESH_ADDR_IS_UNICAST(rx.ctx.addr)) {
BT_ERR("Proxy Configuration from non-unicast addr 0x%04x", rx.ctx.addr);
return;
}
rx.local_match = 1U;
if (bt_mesh_rpl_check(&rx, NULL)) {
BT_WARN("Replay: src 0x%04x dst 0x%04x seq 0x%06x",
rx.ctx.addr, rx.ctx.recv_dst, rx.seq);
return;
}
/* Remove network headers */
net_buf_simple_pull(&buf, BLE_MESH_NET_HDR_LEN);
BT_DBG("%u bytes: %s", buf.len, bt_hex(buf.data, buf.len));
if (buf.len < 3) {
BT_WARN("Too short proxy configuration PDU");
return;
}
opcode = net_buf_simple_pull_u8(&buf);
switch (opcode) {
case BLE_MESH_PROXY_CFG_FILTER_STATUS:
filter_status(server, &rx, &buf);
break;
default:
BT_WARN("Unknown Proxy Configuration OpCode 0x%02x", opcode);
break;
}
}
#endif /* CONFIG_BLE_MESH_GATT_PROXY_CLIENT */
static void proxy_complete_pdu(struct bt_mesh_proxy_server *server)
{
switch (server->msg_type) {
#if CONFIG_BLE_MESH_GATT_PROXY_CLIENT
case BLE_MESH_PROXY_NET_PDU:
BT_DBG("Mesh Network PDU");
bt_mesh_net_recv(&server->buf, 0, BLE_MESH_NET_IF_PROXY);
break;
case BLE_MESH_PROXY_BEACON:
BT_DBG("Mesh Beacon PDU");
bt_mesh_beacon_recv(&server->buf, 0);
break;
case BLE_MESH_PROXY_CONFIG:
BT_DBG("Mesh Configuration PDU");
proxy_cfg(server);
break;
#endif /* CONFIG_BLE_MESH_GATT_PROXY_CLIENT */
#if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH_PB_GATT
case BLE_MESH_PROXY_PROV:
BT_DBG("Mesh Provisioning PDU");
bt_mesh_provisioner_pb_gatt_recv(server->conn, &server->buf);
break;
#endif
default:
BT_WARN("Unhandled Message Type 0x%02x", server->msg_type);
break;
}
net_buf_simple_reset(&server->buf);
}
#define ATTR_IS_PROV(uuid) (uuid == BLE_MESH_UUID_MESH_PROV_VAL)
static ssize_t proxy_recv(struct bt_mesh_conn *conn,
const struct bt_mesh_gatt_attr *attr, const void *buf,
u16_t len, u16_t offset, u8_t flags)
{
struct bt_mesh_proxy_server *server = find_server(conn);
const u8_t *data = buf;
u16_t srvc_uuid = 0U;
if (!server) {
BT_ERR("No Proxy Server object found");
return -ENOTCONN;
}
if (len < 1) {
BT_WARN("Too small Proxy PDU");
return -EINVAL;
}
srvc_uuid = bt_mesh_gattc_get_service_uuid(conn);
if (!srvc_uuid) {
BT_ERR("No service uuid found");
return -ENOTCONN;
}
if (ATTR_IS_PROV(srvc_uuid) != (PDU_TYPE(data) == BLE_MESH_PROXY_PROV)) {
BT_WARN("Proxy PDU type doesn't match GATT service uuid");
return -EINVAL;
}
if (len - 1 > net_buf_simple_tailroom(&server->buf)) {
BT_WARN("Too big proxy PDU");
return -EINVAL;
}
switch (PDU_SAR(data)) {
case SAR_COMPLETE:
if (server->buf.len) {
BT_WARN("Complete PDU while a pending incomplete one");
return -EINVAL;
}
server->msg_type = PDU_TYPE(data);
net_buf_simple_add_mem(&server->buf, data + 1, len - 1);
proxy_complete_pdu(server);
break;
case SAR_FIRST:
if (server->buf.len) {
BT_WARN("First PDU while a pending incomplete one");
return -EINVAL;
}
k_delayed_work_submit(&server->sar_timer, PROXY_SAR_TIMEOUT);
server->msg_type = PDU_TYPE(data);
net_buf_simple_add_mem(&server->buf, data + 1, len - 1);
break;
case SAR_CONT:
if (!server->buf.len) {
BT_WARN("Continuation with no prior data");
return -EINVAL;
}
if (server->msg_type != PDU_TYPE(data)) {
BT_WARN("Unexpected message type in continuation");
return -EINVAL;
}
k_delayed_work_submit(&server->sar_timer, PROXY_SAR_TIMEOUT);
net_buf_simple_add_mem(&server->buf, data + 1, len - 1);
break;
case SAR_LAST:
if (!server->buf.len) {
BT_WARN("Last SAR PDU with no prior data");
return -EINVAL;
}
if (server->msg_type != PDU_TYPE(data)) {
BT_WARN("Unexpected message type in last SAR PDU");
return -EINVAL;
}
k_delayed_work_cancel(&server->sar_timer);
net_buf_simple_add_mem(&server->buf, data + 1, len - 1);
proxy_complete_pdu(server);
break;
}
return len;
}
static int proxy_send(struct bt_mesh_conn *conn, const void *data, u16_t len)
{
BT_DBG("%u bytes: %s", len, bt_hex(data, len));
return bt_mesh_gattc_write_no_rsp(conn, NULL, data, len);
}
static int proxy_segment_and_send(struct bt_mesh_conn *conn, u8_t type,
struct net_buf_simple *msg)
{
u16_t mtu = 0U;
int err = 0;
if (conn == NULL) {
BT_ERR("%s, Invalid parameter", __func__);
return -EINVAL;
}
BT_DBG("conn %p type 0x%02x len %u: %s", conn, type, msg->len,
bt_hex(msg->data, msg->len));
mtu = bt_mesh_gattc_get_mtu_info(conn);
if (!mtu) {
BT_ERR("Conn %p used to get mtu not exists", conn);
return -ENOTCONN;
}
/* ATT_MTU - OpCode (1 byte) - Handle (2 bytes) */
mtu -= 3;
if (mtu > msg->len) {
net_buf_simple_push_u8(msg, PDU_HDR(SAR_COMPLETE, type));
return proxy_send(conn, msg->data, msg->len);
}
net_buf_simple_push_u8(msg, PDU_HDR(SAR_FIRST, type));
err = proxy_send(conn, msg->data, mtu);
net_buf_simple_pull(msg, mtu);
while (msg->len) {
if (msg->len + 1 < mtu) {
net_buf_simple_push_u8(msg, PDU_HDR(SAR_LAST, type));
err = proxy_send(conn, msg->data, msg->len);
break;
}
net_buf_simple_push_u8(msg, PDU_HDR(SAR_CONT, type));
err = proxy_send(conn, msg->data, mtu);
net_buf_simple_pull(msg, mtu);
}
return err;
}
int bt_mesh_proxy_client_send(struct bt_mesh_conn *conn, u8_t type,
struct net_buf_simple *msg)
{
struct bt_mesh_proxy_server *server = find_server(conn);
if (!server) {
BT_ERR("No Proxy Server object found");
return -ENOTCONN;
}
if ((server->conn_type == PROV) != (type == BLE_MESH_PROXY_PROV)) {
BT_ERR("Invalid PDU type for Proxy Server");
return -EINVAL;
}
return proxy_segment_and_send(conn, type, msg);
}
static void proxy_connected(bt_mesh_addr_t *addr, struct bt_mesh_conn *conn, int id)
{
struct bt_mesh_proxy_server *server = NULL;
if (!servers[id].conn) {
server = &servers[id];
}
if (!server) {
BT_ERR("No free Proxy Server objects");
/** Disconnect current connection, clear part of prov_link
* information, like uuid, dev_addr, linking flag, etc.
*/
bt_mesh_gattc_disconnect(conn);
return;
}
server->conn = bt_mesh_conn_ref(conn);
server->conn_type = NONE;
net_buf_simple_reset(&server->buf);
bt_mesh_gattc_exchange_mtu(id);
return;
}
static void proxy_disconnected(bt_mesh_addr_t *addr, struct bt_mesh_conn *conn, u8_t reason)
{
struct bt_mesh_proxy_server *server = find_server(conn);
BT_DBG("conn %p, handle is %d, reason 0x%02x", conn, conn->handle, reason);
if (!server) {
BT_ERR("No Proxy Server object found");
return;
}
#if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH_PB_GATT
if (server->conn_type == PROV) {
bt_mesh_provisioner_pb_gatt_close(conn, reason);
}
#endif
#if CONFIG_BLE_MESH_GATT_PROXY_CLIENT
if (server->conn_type == PROXY) {
if (proxy_client_disconnect_cb) {
proxy_client_disconnect_cb(addr, server - servers, server->net_idx, reason);
}
}
#endif
k_delayed_work_cancel(&server->sar_timer);
server->conn = NULL;
server->conn_type = NONE;
#if CONFIG_BLE_MESH_GATT_PROXY_CLIENT
server->net_idx = BLE_MESH_KEY_UNUSED;
#endif
return;
}
#if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH_PB_GATT
static ssize_t prov_write_ccc(bt_mesh_addr_t *addr, struct bt_mesh_conn *conn)
{
struct bt_mesh_proxy_server *server = find_server(conn);
if (!server) {
BT_ERR("No Proxy Server object found");
return -ENOTCONN;
}
if (server->conn_type == NONE) {
server->conn_type = PROV;
if (bt_mesh_provisioner_set_prov_conn(addr->val, server->conn)) {
bt_mesh_gattc_disconnect(server->conn);
return -EIO;
}
return bt_mesh_provisioner_pb_gatt_open(conn, addr->val);
}
return -ENOMEM;
}
static ssize_t prov_recv_ntf(struct bt_mesh_conn *conn, u8_t *data, u16_t len)
{
struct bt_mesh_proxy_server *server = find_server(conn);
if (!server) {
BT_ERR("No Proxy Server object found");
return -ENOTCONN;
}
if (server->conn_type == PROV) {
return proxy_recv(conn, NULL, data, len, 0, 0);
}
return -EINVAL;
}
int bt_mesh_proxy_client_prov_enable(void)
{
int i;
BT_DBG("%s", __func__);
for (i = 0; i < ARRAY_SIZE(servers); i++) {
if (servers[i].conn) {
servers[i].conn_type = PROV;
}
}
return 0;
}
int bt_mesh_proxy_client_prov_disable(void)
{
int i;
BT_DBG("%s", __func__);
for (i = 0; i < ARRAY_SIZE(servers); i++) {
struct bt_mesh_proxy_server *server = &servers[i];
if (server->conn && server->conn_type == PROV) {
bt_mesh_gattc_disconnect(server->conn);
server->conn_type = NONE;
}
}
return 0;
}
#endif /* CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH_PB_GATT */
#if defined(CONFIG_BLE_MESH_GATT_PROXY_CLIENT)
static ssize_t proxy_write_ccc(bt_mesh_addr_t *addr, struct bt_mesh_conn *conn)
{
struct bt_mesh_proxy_server *server = find_server(conn);
if (!server) {
BT_ERR("No Proxy Server object found");
return -ENOTCONN;
}
if (server->conn_type == NONE) {
server->conn_type = PROXY;
if (proxy_client_connect_cb) {
proxy_client_connect_cb(addr, server - servers, server->net_idx);
}
return 0;
}
return -EINVAL;
}
static ssize_t proxy_recv_ntf(struct bt_mesh_conn *conn, u8_t *data, u16_t len)
{
struct bt_mesh_proxy_server *server = find_server(conn);
if (!server) {
BT_ERR("No Proxy Server object found");
return -ENOTCONN;
}
if (server->conn_type == PROXY) {
return proxy_recv(conn, NULL, data, len, 0, 0);
}
return -EINVAL;
}
/**
* Currently proxy client doesn't need bt_mesh_proxy_client_gatt_enable()
* and bt_mesh_proxy_client_gatt_disable() functions, and once they are
* used, proxy client can be enabled to parse node_id_adv and net_id_adv
* in order to support proxy client role.
* And if gatt proxy is disabled, proxy client can stop handling these
* two kinds of connectable advertising packets.
*/
int bt_mesh_proxy_client_gatt_enable(void)
{
int i;
BT_DBG("%s", __func__);
for (i = 0; i < ARRAY_SIZE(servers); i++) {
if (servers[i].conn) {
servers[i].conn_type = PROXY;
}
}
/**
* TODO:
* Once at least one device has been provisioned, proxy client can be
* set to allow receiving and parsing node_id & net_id adv packets,
* and we may use a global flag to indicate this.
*/
return 0;
}
int bt_mesh_proxy_client_gatt_disable(void)
{
int i;
BT_DBG("%s", __func__);
/**
* TODO:
* Once this function is invoked, proxy client shall stop handling
* node_id & net_id adv packets, and if proxy connection exists,
* it should be disconnected.
*/
for (i = 0; i < ARRAY_SIZE(servers); i++) {
struct bt_mesh_proxy_server *server = &servers[i];
if (server->conn && server->conn_type == PROXY) {
bt_mesh_gattc_disconnect(server->conn);
server->conn_type = NONE;
}
}
return 0;
}
#endif /* CONFIG_BLE_MESH_GATT_PROXY_CLIENT */
static struct bt_mesh_prov_conn_cb conn_callbacks = {
.connected = proxy_connected,
.disconnected = proxy_disconnected,
#if CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH_PB_GATT
.prov_write_descr = prov_write_ccc,
.prov_notify = prov_recv_ntf,
#endif /* CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH_PB_GATT */
#if defined(CONFIG_BLE_MESH_GATT_PROXY_CLIENT)
.proxy_write_descr = proxy_write_ccc,
.proxy_notify = proxy_recv_ntf,
#endif /* CONFIG_BLE_MESH_GATT_PROXY_CLIENT */
};
#if defined(CONFIG_BLE_MESH_GATT_PROXY_CLIENT)
static struct bt_mesh_subnet *bt_mesh_is_net_id_exist(const u8_t net_id[8])
{
struct bt_mesh_subnet *sub = NULL;
size_t size = 0U, i = 0U;
size = bt_mesh_rx_netkey_size();
for (i = 0U; i < size; i++) {
sub = bt_mesh_rx_netkey_get(i);
if (sub && !memcmp(sub->keys[sub->kr_flag].net_id, net_id, 8)) {
return sub;
}
}
return NULL;
}
void bt_mesh_proxy_client_gatt_adv_recv(struct net_buf_simple *buf,
const bt_mesh_addr_t *addr, s8_t rssi)
{
bt_mesh_proxy_adv_ctx_t ctx = {0};
u8_t type = 0U;
/* Check if connection reaches the maximum limitation */
if (bt_mesh_gattc_get_free_conn_count() == 0) {
BT_INFO("BLE connections for mesh reach max limit");
return;
}
type = net_buf_simple_pull_u8(buf);
switch (type) {
case BLE_MESH_PROXY_ADV_NET_ID: {
if (buf->len != sizeof(ctx.net_id.net_id)) {
BT_WARN("Malformed Network ID");
return;
}
struct bt_mesh_subnet *sub = NULL;
sub = bt_mesh_is_net_id_exist(buf->data);
if (!sub) {
return;
}
memcpy(ctx.net_id.net_id, buf->data, buf->len);
ctx.net_id.net_idx = sub->net_idx;
break;
}
case BLE_MESH_PROXY_ADV_NODE_ID:
/* Gets node identity information.
* hash = aes-ecb(identity key, 16 octets(padding + random + src)) mod 2^64,
* If Proxy Client wants to get src, it may encrypts multiple times and compare
* the hash value (8 octets) with the received one.
*/
return;
default:
BT_DBG("Unknown Mesh Proxy adv type 0x%02x", type);
return;
}
if (proxy_client_adv_recv_cb) {
proxy_client_adv_recv_cb(addr, type, &ctx, rssi);
}
}
int bt_mesh_proxy_client_connect(const u8_t addr[6], u8_t addr_type, u16_t net_idx)
{
bt_mesh_addr_t remote_addr = {0};
int result = 0;
if (!addr || addr_type > BLE_MESH_ADDR_RANDOM) {
BT_ERR("%s, Invalid parameter", __func__);
return -EINVAL;
}
memcpy(remote_addr.val, addr, BLE_MESH_ADDR_LEN);
remote_addr.type = addr_type;
result = bt_mesh_gattc_conn_create(&remote_addr, BLE_MESH_UUID_MESH_PROXY_VAL);
if (result < 0) {
return result;
}
/* Store corresponding net_idx which can be used for sending Proxy Configuration */
servers[result].net_idx = net_idx;
return 0;
}
int bt_mesh_proxy_client_disconnect(u8_t conn_handle)
{
struct bt_mesh_conn *conn = NULL;
if (conn_handle >= BLE_MESH_MAX_CONN) {
BT_ERR("%s, Invalid parameter", __func__);
return -EINVAL;
}
BT_DBG("conn_handle %d", conn_handle);
conn = servers[conn_handle].conn;
if (!conn) {
BT_ERR("Not connected, conn handle %d", conn_handle);
return -ENOTCONN;
}
bt_mesh_gattc_disconnect(conn);
return 0;
}
bool bt_mesh_proxy_client_relay(struct net_buf_simple *buf, u16_t dst)
{
bool send = false;
int err = 0;
int i;
for (i = 0; i < ARRAY_SIZE(servers); i++) {
struct bt_mesh_proxy_server *server = &servers[i];
NET_BUF_SIMPLE_DEFINE(msg, 32);
if (!server->conn || server->conn_type != PROXY) {
continue;
}
/* Proxy PDU sending modifies the original buffer,
* so we need to make a copy.
*/
net_buf_simple_init(&msg, 1);
net_buf_simple_add_mem(&msg, buf->data, buf->len);
err = bt_mesh_proxy_client_send(server->conn, BLE_MESH_PROXY_NET_PDU, &msg);
if (err) {
BT_ERR("Failed to send proxy network message (err %d)", err);
} else {
BT_INFO("%u bytes to dst 0x%04x", buf->len, dst);
send = true;
}
}
return send;
}
static int beacon_send(struct bt_mesh_conn *conn, struct bt_mesh_subnet *sub)
{
NET_BUF_SIMPLE_DEFINE(buf, 23);
net_buf_simple_init(&buf, 1);
bt_mesh_beacon_create(sub, &buf);
return bt_mesh_proxy_client_send(conn, BLE_MESH_PROXY_BEACON, &buf);
}
bool bt_mesh_proxy_client_beacon_send(struct bt_mesh_subnet *sub)
{
bool send = false;
int err = 0;
int i;
/* NULL means we send Secure Network Beacon on all subnets */
if (!sub) {
#if CONFIG_BLE_MESH_NODE
if (bt_mesh_is_provisioned()) {
for (i = 0; i < ARRAY_SIZE(bt_mesh.sub); i++) {
if (bt_mesh.sub[i].net_idx != BLE_MESH_KEY_UNUSED) {
send = bt_mesh_proxy_client_beacon_send(&bt_mesh.sub[i]);
}
}
return send;
}
#endif /* CONFIG_BLE_MESH_NODE */
#if CONFIG_BLE_MESH_PROVISIONER
if (bt_mesh_is_provisioner_en()) {
for (i = 0; i < ARRAY_SIZE(bt_mesh.p_sub); i++) {
if (bt_mesh.p_sub[i] && bt_mesh.p_sub[i]->net_idx != BLE_MESH_KEY_UNUSED) {
send = bt_mesh_proxy_client_beacon_send(bt_mesh.p_sub[i]);
}
}
return send;
}
#endif /* CONFIG_BLE_MESH_PROVISIONER */
return send;
}
for (i = 0; i < ARRAY_SIZE(servers); i++) {
if (servers[i].conn && servers[i].conn_type == PROXY) {
err = beacon_send(servers[i].conn, sub);
if (err) {
BT_ERR("Failed to send proxy beacon message (err %d)", err);
} else {
send = true;
}
}
}
return send;
}
static int send_proxy_cfg(struct bt_mesh_conn *conn, u16_t net_idx, struct bt_mesh_proxy_cfg_pdu *cfg)
{
struct bt_mesh_msg_ctx ctx = {
.net_idx = net_idx,
.app_idx = BLE_MESH_KEY_UNUSED, /* CTL shall be set to 1 */
.addr = BLE_MESH_ADDR_UNASSIGNED, /* DST shall be set to the unassigned address */
.send_ttl = 0U, /* TTL shall be set to 0 */
};
struct bt_mesh_net_tx tx = {
.ctx = &ctx,
.src = bt_mesh_primary_addr(),
};
struct net_buf_simple *buf = NULL;
u16_t alloc_len = 0U;
int err = 0;
if (IS_ENABLED(CONFIG_BLE_MESH_NODE) && bt_mesh_is_provisioned()) {
tx.sub = bt_mesh_subnet_get(net_idx);
} else if (IS_ENABLED(CONFIG_BLE_MESH_PROVISIONER) && bt_mesh_is_provisioner_en()) {
tx.sub = bt_mesh_provisioner_subnet_get(net_idx);
}
if (!tx.sub) {
BT_ERR("Invalid NetKeyIndex 0x%04x", net_idx);
return -EIO;
}
switch (cfg->opcode) {
case BLE_MESH_PROXY_CFG_FILTER_SET:
if (cfg->set.filter_type > 0x01) {
BT_ERR("Invalid proxy filter type 0x%02x", cfg->set.filter_type);
return -EINVAL;
}
alloc_len = sizeof(cfg->opcode) + sizeof(cfg->set.filter_type);
break;
case BLE_MESH_PROXY_CFG_FILTER_ADD:
if (cfg->add.addr == NULL || cfg->add.addr_num == 0) {
BT_ERR("Empty proxy addr list to add");
return -EINVAL;
}
alloc_len = sizeof(cfg->opcode) + (cfg->add.addr_num << 1);
break;
case BLE_MESH_PROXY_CFG_FILTER_REMOVE:
if (cfg->remove.addr == NULL || cfg->remove.addr_num == 0) {
BT_ERR("Empty proxy addr list to remove");
return -EINVAL;
}
alloc_len = sizeof(cfg->opcode) + (cfg->remove.addr_num << 1);
break;
default:
BT_ERR("Unknown Proxy Configuration opcode 0x%02x", cfg->opcode);
return -EINVAL;
}
/**
* For Proxy Configuration PDU:
* 1 octet Proxy PDU type + 9 octets network pdu header + Tranport PDU + 8 octets NetMIC
*/
buf = bt_mesh_alloc_buf(1 + BLE_MESH_NET_HDR_LEN + alloc_len + 8);
if (!buf) {
return -ENOMEM;
}
net_buf_simple_reset(buf);
net_buf_simple_reserve(buf, 10);
net_buf_simple_add_u8(buf, cfg->opcode);
switch (cfg->opcode) {
case BLE_MESH_PROXY_CFG_FILTER_SET:
net_buf_simple_add_u8(buf, cfg->set.filter_type);
break;
case BLE_MESH_PROXY_CFG_FILTER_ADD:
for (u16_t i = 0U; i < cfg->add.addr_num; i++) {
net_buf_simple_add_le16(buf, cfg->add.addr[i]);
}
break;
case BLE_MESH_PROXY_CFG_FILTER_REMOVE:
for (u16_t i = 0U; i < cfg->remove.addr_num; i++) {
net_buf_simple_add_le16(buf, cfg->remove.addr[i]);
}
break;
}
BT_DBG("len %u bytes: %s", buf->len, bt_hex(buf->data, buf->len));
err = bt_mesh_net_encode(&tx, buf, true);
if (err) {
BT_ERR("Encoding proxy message failed (err %d)", err);
bt_mesh_free_buf(buf);
return err;
}
err = bt_mesh_proxy_client_send(conn, BLE_MESH_PROXY_CONFIG, buf);
if (err) {
BT_ERR("Failed to send proxy cfg message (err %d)", err);
}
bt_mesh_free_buf(buf);
return err;
}
int bt_mesh_proxy_client_cfg_send(u8_t conn_handle, u16_t net_idx,
struct bt_mesh_proxy_cfg_pdu *pdu)
{
struct bt_mesh_conn *conn = NULL;
if (conn_handle >= BLE_MESH_MAX_CONN || !pdu || pdu->opcode > BLE_MESH_PROXY_CFG_FILTER_REMOVE) {
BT_ERR("%s, Invalid parameter", __func__);
return -EINVAL;
}
BT_DBG("conn_handle %d, net_idx 0x%04x", conn_handle, net_idx);
conn = servers[conn_handle].conn;
if (!conn) {
BT_ERR("Not connected, conn handle %d", conn_handle);
return -ENOTCONN;
}
/**
* Check if net_idx used to encrypt Proxy Configuration are the same
* with the one added when creating proxy connection.
*/
if (servers[conn_handle].net_idx != net_idx) {
BT_ERR("NetKeyIndex 0x%04x mismatch, expect 0x%04x",
net_idx, servers[conn_handle].net_idx);
return -EIO;
}
return send_proxy_cfg(conn, net_idx, pdu);
}
#endif /* CONFIG_BLE_MESH_GATT_PROXY_CLIENT */
int bt_mesh_proxy_client_init(void)
{
int i;
/* Initialize the server receive buffers */
for (i = 0; i < ARRAY_SIZE(servers); i++) {
struct bt_mesh_proxy_server *server = &servers[i];
k_delayed_work_init(&server->sar_timer, proxy_sar_timeout);
server->buf.size = SERVER_BUF_SIZE;
server->buf.__buf = server_buf_data + (i * SERVER_BUF_SIZE);
#if CONFIG_BLE_MESH_GATT_PROXY_CLIENT
server->net_idx = BLE_MESH_KEY_UNUSED;
#endif
}
bt_mesh_gattc_conn_cb_register(&conn_callbacks);
#if CONFIG_BLE_MESH_USE_DUPLICATE_SCAN && CONFIG_BLE_MESH_GATT_PROXY_CLIENT
bt_mesh_update_exceptional_list(BLE_MESH_EXCEP_LIST_ADD,
BLE_MESH_EXCEP_INFO_MESH_PROXY_ADV, NULL);
#endif
return 0;
}
int bt_mesh_proxy_client_deinit(void)
{
int i;
/* Initialize the server receive buffers */
for (i = 0; i < ARRAY_SIZE(servers); i++) {
struct bt_mesh_proxy_server *server = &servers[i];
k_delayed_work_free(&server->sar_timer);
memset(server, 0, sizeof(struct bt_mesh_proxy_server));
}
memset(server_buf_data, 0, sizeof(server_buf_data));
bt_mesh_gattc_conn_cb_deregister();
return 0;
}
#endif /* (CONFIG_BLE_MESH_PROVISIONER && CONFIG_BLE_MESH_PB_GATT) || CONFIG_BLE_MESH_GATT_PROXY_CLIENT */
| 27.986275 | 116 | 0.632278 | [
"mesh",
"object"
] |
c908f4529c42476dc3a951de5bce936f52780f42 | 4,579 | h | C | 2005/inc/AcTcUiCatalogViewItem.h | kevinzhwl/ObjectARXCore | ce09e150aa7d87675ca15c9416497c0487e3d4d4 | [
"MIT"
] | 12 | 2015-10-05T07:11:57.000Z | 2021-11-20T10:22:38.000Z | 2005/inc/AcTcUiCatalogViewItem.h | HelloWangQi/ObjectARXCore | ce09e150aa7d87675ca15c9416497c0487e3d4d4 | [
"MIT"
] | null | null | null | 2005/inc/AcTcUiCatalogViewItem.h | HelloWangQi/ObjectARXCore | ce09e150aa7d87675ca15c9416497c0487e3d4d4 | [
"MIT"
] | 14 | 2015-12-04T08:42:08.000Z | 2022-01-08T02:09:23.000Z | //////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright 1982-2003 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
//////////////////////////////////////////////////////////////////////////////
//
// Name: AcTcUiCatalogViewItem.h
//
// Description: Header for CAcTcUiCatalogViewItem class. This class
// implements the CatalogItem item in the Catalog view window.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef __ACTCUICATALOGVIEWITEM_H__
#define __ACTCUICATALOGVIEWITEM_H__
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "AcTc.h"
#include "AcTcUi.h"
class CAcTcUiCatalogView;
// View item styles
// Push button style
#define ACTCUI_CVISTYLE_PUSHBUTTON 0x0
// Show text for items.
// For some strange reason, this value cannot be 1. If it is 1 the images
// are not painted properly. Most of the images will be missing.
#define ACTCUI_CVISTYLE_SHOWTEXT (0x1 << 1)
#define ACTCUI_CVISTYLE_RIGHTTEXT (0x1 << 2)
#define ACTCUI_CVISTYLE_FLYOUT (0x1 << 3)
// View item states
// Item is highlighted (raised)
#define ACTCUI_CVISTATE_HIGHLIGHTED (0x1 << 0)
// Item is selected (selected)
#define ACTCUI_CVISTATE_SELECTED (0x1 << 1)
// Item is selected (halo)
#define ACTCUI_CVISTATE_HALO (0x1 << 2)
// Item is focused
#define ACTCUI_CVISTATE_FOCUSED (0x1 << 3)
// Flags for GetRect()
#define ACTCUI_CVIR_BOUNDS (0x1 << 0)
#define ACTCUI_CVIR_IMAGE (0x1 << 1)
#define ACTCUI_CVIR_LABEL (0x1 << 2)
#define ACTCUI_CVIR_USEFULLLABEL (0x1 << 3)
#define ACTCUI_CVIR_TRIGGER (0x1 << 4)
class ACTCUI_PORT CAcTcUiCatalogViewItem : public CObject
{
friend class CAcTcUiImpCatalogView;
public:
virtual ~CAcTcUiCatalogViewItem();
BOOL Render (BOOL bEraseBackground = FALSE);
BOOL Render (CDC* pDC, int x, int y);
BOOL GetRect (LPRECT lpRect,
int nCode) const;
AcTcCatalogItem * GetCatalogItem (void) const;
BOOL SetCatalogItem (AcTcCatalogItem* pCatalogItem);
DWORD GetStyle (void) const;
DWORD GetState (void) const;
BOOL SetState (DWORD dwState);
BOOL GetPosition (LPPOINT lpPoint) const;
DWORD GetData (void) const;
BOOL SetData (DWORD dwData);
BOOL Highlight (BOOL bHighlight = TRUE);
BOOL Select (BOOL bSelect = TRUE);
BOOL Halo (BOOL bHalo = TRUE);
protected:
// Constructors are protected so that this object can only be
// created by CAcTcUiCatalogView.
CAcTcUiCatalogViewItem(CAcTcUiCatalogView* pCatalogView);
CAcTcUiCatalogViewItem(CAcTcUiCatalogView* pCatalogView,
AcTcCatalogItem* pCatalogItem, const CSize& sizeImage,
DWORD dwStyle = ACTCUI_CVISTYLE_PUSHBUTTON);
protected:
void * mpImpObj; // Imp object CAcTcUiImpCatalogViewItem
};
// Array of CAcTcUiCatalogViewItem objects
typedef CTypedPtrArray<CPtrArray, CAcTcUiCatalogViewItem*> CAcTcUiCatalogViewItemArray;
#endif //__ACTCUICATALOGVIEWITEM_H__
| 39.817391 | 88 | 0.584407 | [
"render",
"object"
] |
c90caeaa8f6e4691198d0ae1db4449c5a65431ca | 3,101 | c | C | Source/GxB_Vector_Option_get.c | szarnyasg/GraphBLAS | eee9c97b2e58059d5272910a90df757473273c07 | [
"Apache-2.0"
] | null | null | null | Source/GxB_Vector_Option_get.c | szarnyasg/GraphBLAS | eee9c97b2e58059d5272910a90df757473273c07 | [
"Apache-2.0"
] | null | null | null | Source/GxB_Vector_Option_get.c | szarnyasg/GraphBLAS | eee9c97b2e58059d5272910a90df757473273c07 | [
"Apache-2.0"
] | null | null | null | //------------------------------------------------------------------------------
// GxB_Vector_Option_get: get an option in a vector
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
#include "GB.h"
GrB_Info GxB_Vector_Option_get // gets the current option of a vector
(
GrB_Vector v, // vector to query
GxB_Option_Field field, // option to query
... // return value of the vector option
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
GB_WHERE1 ("GxB_Vector_Option_get (v, field, &value)") ;
GB_RETURN_IF_NULL_OR_FAULTY (v) ;
ASSERT_VECTOR_OK (v, "v to get option", GB0) ;
//--------------------------------------------------------------------------
// get the option
//--------------------------------------------------------------------------
va_list ap ;
switch (field)
{
case GxB_BITMAP_SWITCH :
{
va_start (ap, field) ;
double *bitmap_switch = va_arg (ap, double *) ;
va_end (ap) ;
GB_RETURN_IF_NULL (bitmap_switch) ;
(*bitmap_switch) = (double) v->bitmap_switch ;
}
break ;
case GxB_SPARSITY_CONTROL :
{
va_start (ap, field) ;
int *sparsity_control = va_arg (ap, int *) ;
va_end (ap) ;
GB_RETURN_IF_NULL (sparsity_control) ;
(*sparsity_control) = v->sparsity_control ;
}
break ;
case GxB_SPARSITY_STATUS :
{
va_start (ap, field) ;
int *sparsity = va_arg (ap, int *) ;
va_end (ap) ;
GB_RETURN_IF_NULL (sparsity) ;
(*sparsity) = GB_sparsity ((GrB_Matrix) v) ;
}
break ;
case GxB_FORMAT :
{
// a GrB_Vector is always stored by-column
va_start (ap, field) ;
GxB_Format_Value *format = va_arg (ap, GxB_Format_Value *) ;
va_end (ap) ;
GB_RETURN_IF_NULL (format) ;
(*format) = GxB_BY_COL ;
}
break ;
case GxB_IS_HYPER : // historical; use GxB_SPARSITY_STATUS instead
{
// a GrB_Vector is never hypersparse
va_start (ap, field) ;
bool *v_is_hyper = va_arg (ap, bool *) ;
va_end (ap) ;
GB_RETURN_IF_NULL (v_is_hyper) ;
(*v_is_hyper) = false ;
}
break ;
default :
return (GrB_INVALID_VALUE) ;
}
return (GrB_SUCCESS) ;
}
| 30.401961 | 80 | 0.398259 | [
"vector"
] |
c90cf781fac13ad7a5536d28f45b734426e9991b | 4,646 | h | C | ubc/CmdLineArgs.h | Brillist/libutl | e55c2af091ba1101a1d0608db2830e279ec95d16 | [
"MIT"
] | 1 | 2021-09-14T06:12:58.000Z | 2021-09-14T06:12:58.000Z | ubc/CmdLineArgs.h | Brillist/libutl | e55c2af091ba1101a1d0608db2830e279ec95d16 | [
"MIT"
] | null | null | null | ubc/CmdLineArgs.h | Brillist/libutl | e55c2af091ba1101a1d0608db2830e279ec95d16 | [
"MIT"
] | 2 | 2019-05-13T23:04:31.000Z | 2021-09-14T06:12:59.000Z | #pragma once
////////////////////////////////////////////////////////////////////////////////////////////////////
#include <libutl/Array.h>
#include <libutl/RBtree.h>
#include <libutl/String.h>
////////////////////////////////////////////////////////////////////////////////////////////////////
UTL_NS_BEGIN;
////////////////////////////////////////////////////////////////////////////////////////////////////
class CmdLineArg;
////////////////////////////////////////////////////////////////////////////////////////////////////
/**
Parse command-line arguments.
CmdLineArgs simplifies the task of parsing command-line arguments. It can accept
one-character switches (e.g. \b -q) as well as long switches (e.g. \b --quiet).
It can also recognize and report any unknown switches that were given.
\author Adam McKee
\ingroup general
*/
////////////////////////////////////////////////////////////////////////////////////////////////////
class CmdLineArgs
: public Object
, protected FlagsMI
{
UTL_CLASS_DECL(CmdLineArgs, Object);
public:
/**
Constructor. Invokes parse() for the given arguments.
\param argc number of arguments (as in main())
\param argv array of arguments (as in main())
*/
CmdLineArgs(int argc, char** argv)
{
init(argc, argv);
}
/**
Constructor. Invokes parse() for the given arguments.
\param args Array of String's
*/
CmdLineArgs(const Array& args)
{
init(args);
}
/** See Object::clear. */
void clear();
/** Get the argument array. */
const TArray<String>&
getArray() const
{
return _array;
}
/** Return the index of the first non-switch argument. */
size_t
idx() const
{
return _idx;
}
/**
Determine whether a switch was given.
\return true if switch given, false otherwise
\param sw switch to test for
\param val (optional) value which was given for the switch
\param swIdx (optional) index of argument where switch was found
*/
bool isSet(const String& sw, String* val = nullptr, size_t* swIdx = nullptr);
/** Get the ownership flag. */
bool
isOwner() const
{
return getFlag(flg_owner);
}
/** Set the ownership flag. */
void
setOwner(bool owner)
{
setFlag(flg_owner, owner);
}
/** Return the number of arguments. */
size_t
items() const
{
return _array.items();
}
/**
Determine whether any unknown switches were given. This method \b must be called after
isSet() has been called for each known switch.
*/
bool
ok() const
{
return _args.empty();
}
/**
Parse the given arguments.
\param argc number of arguments (as in main())
\param argv array of arguments (as in main())
*/
void parse(int argc, char** argv);
/**
Parse the given arguments.
\param args Array of String's
*/
void parse(const Array& args);
/**
Print unknown switches to the given stream.
\return true if errors were found, false otherwise
\param os stream to print errors to
\param prefix prefix for each error report
*/
bool printErrors(Stream& os, const String* prefix = nullptr);
/**
Return the argument at the given index.
\see Array::operator[]
*/
const String* operator[](size_t idx) const
{
return _array.operator[](idx);
}
/** Same as above, but takes a signed argument. */
const String* operator[](int idx) const
{
return _array.operator[]((size_t)idx);
}
/**
Return the argument at the given index.
\see Array::operator()
*/
const String&
operator()(size_t idx) const
{
return _array.operator()(idx);
}
/** Same as above, but takes a signed argument. */
const String&
operator()(int idx) const
{
return _array.operator()((size_t)idx);
}
private:
enum flg_t
{
flg_owner
};
private:
void
init()
{
setOwner(true);
clear();
}
void
init(int argc, char** argv)
{
setOwner(true);
parse(argc, argv);
}
void
init(const Array& args)
{
setOwner(true);
parse(args);
}
void
deInit()
{
}
private:
size_t _idx;
TArray<String> _array;
TRBtree<CmdLineArg> _args;
};
////////////////////////////////////////////////////////////////////////////////////////////////////
UTL_NS_END;
| 22.12381 | 100 | 0.505166 | [
"object"
] |
c90dc16d3fa70aee11227813548027b0514e0982 | 2,572 | h | C | VTK/vtk_7.1.1_x64_Debug/include/vtk-7.1/vtkEarthSource.h | jiaguobing/FastCAE | 2348ab87e83fe5c704e4c998cf391229c25ac5d5 | [
"BSD-3-Clause"
] | 4 | 2019-05-30T01:52:12.000Z | 2021-09-29T21:12:13.000Z | VTK/vtk_7.1.1_x64_Release/include/vtk-7.1/vtkEarthSource.h | Sunqia/FastCAE | cbc023fe07b6e306ceefae8b8bd7c12bc1562acb | [
"BSD-3-Clause"
] | 1 | 2020-03-06T04:49:42.000Z | 2020-03-06T04:49:42.000Z | VTK/vtk_7.1.1_x64_Release/include/vtk-7.1/vtkEarthSource.h | Sunqia/FastCAE | cbc023fe07b6e306ceefae8b8bd7c12bc1562acb | [
"BSD-3-Clause"
] | 2 | 2019-08-30T23:36:13.000Z | 2019-11-08T16:52:01.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: vtkEarthSource.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/**
* @class vtkEarthSource
* @brief create the continents of the Earth as a sphere
*
* vtkEarthSource creates a spherical rendering of the geographical shapes
* of the major continents of the earth. The OnRatio determines
* how much of the data is actually used. The radius defines the radius
* of the sphere at which the continents are placed. Obtains data from
* an imbedded array of coordinates.
*/
#ifndef vtkEarthSource_h
#define vtkEarthSource_h
#include "vtkFiltersHybridModule.h" // For export macro
#include "vtkPolyDataAlgorithm.h"
class VTKFILTERSHYBRID_EXPORT vtkEarthSource : public vtkPolyDataAlgorithm
{
public:
static vtkEarthSource *New();
vtkTypeMacro(vtkEarthSource,vtkPolyDataAlgorithm);
void PrintSelf(ostream& os, vtkIndent indent);
//@{
/**
* Set radius of earth.
*/
vtkSetClampMacro(Radius,double,0.0,VTK_FLOAT_MAX);
vtkGetMacro(Radius,double);
//@}
//@{
/**
* Turn on every nth entity. This controls how much detail the model
* will have. The maximum ratio is sixteen. (The smaller OnRatio, the more
* detail there is.)
*/
vtkSetClampMacro(OnRatio,int,1,16);
vtkGetMacro(OnRatio,int);
//@}
//@{
/**
* Turn on/off drawing continents as filled polygons or as wireframe outlines.
* Warning: some graphics systems will have trouble with the very large, concave
* filled polygons. Recommend you use OutlienOn (i.e., disable filled polygons)
* for now.
*/
vtkSetMacro(Outline,int);
vtkGetMacro(Outline,int);
vtkBooleanMacro(Outline,int);
//@}
protected:
vtkEarthSource();
~vtkEarthSource() {}
int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *);
double Radius;
int OnRatio;
int Outline;
private:
vtkEarthSource(const vtkEarthSource&) VTK_DELETE_FUNCTION;
void operator=(const vtkEarthSource&) VTK_DELETE_FUNCTION;
};
#endif
| 27.361702 | 86 | 0.662131 | [
"model"
] |
c90e47342bb0698ae460efe7f8ca35bd313d6cce | 30,064 | c | C | net/batman-adv/hard-interface.c | xqdzn/linux-bpi-p2z-dev | fc302d86fb16fff3a25894efd3d5dd9e8e379a82 | [
"MIT"
] | null | null | null | net/batman-adv/hard-interface.c | xqdzn/linux-bpi-p2z-dev | fc302d86fb16fff3a25894efd3d5dd9e8e379a82 | [
"MIT"
] | null | null | null | net/batman-adv/hard-interface.c | xqdzn/linux-bpi-p2z-dev | fc302d86fb16fff3a25894efd3d5dd9e8e379a82 | [
"MIT"
] | null | null | null | // SPDX-License-Identifier: GPL-2.0
/* Copyright (C) 2007-2019 B.A.T.M.A.N. contributors:
*
* Marek Lindner, Simon Wunderlich
*/
#include "hard-interface.h"
#include "main.h"
#include <linux/atomic.h>
#include <linux/byteorder/generic.h>
#include <linux/errno.h>
#include <linux/gfp.h>
#include <linux/if.h>
#include <linux/if_arp.h>
#include <linux/if_ether.h>
#include <linux/kernel.h>
#include <linux/kref.h>
#include <linux/limits.h>
#include <linux/list.h>
#include <linux/netdevice.h>
#include <linux/printk.h>
#include <linux/rculist.h>
#include <linux/rtnetlink.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <net/net_namespace.h>
#include <net/rtnetlink.h>
#include <uapi/linux/batadv_packet.h>
#include "bat_v.h"
#include "bridge_loop_avoidance.h"
#include "debugfs.h"
#include "distributed-arp-table.h"
#include "gateway_client.h"
#include "log.h"
#include "originator.h"
#include "send.h"
#include "soft-interface.h"
#include "sysfs.h"
#include "translation-table.h"
/**
* batadv_hardif_release() - release hard interface from lists and queue for
* free after rcu grace period
* @ref: kref pointer of the hard interface
*/
void batadv_hardif_release(struct kref *ref)
{
struct batadv_hard_iface *hard_iface;
hard_iface = container_of(ref, struct batadv_hard_iface, refcount);
dev_put(hard_iface->net_dev);
kfree_rcu(hard_iface, rcu);
}
/**
* batadv_hardif_get_by_netdev() - Get hard interface object of a net_device
* @net_dev: net_device to search for
*
* Return: batadv_hard_iface of net_dev (with increased refcnt), NULL on errors
*/
struct batadv_hard_iface *
batadv_hardif_get_by_netdev(const struct net_device *net_dev)
{
struct batadv_hard_iface *hard_iface;
rcu_read_lock();
list_for_each_entry_rcu(hard_iface, &batadv_hardif_list, list) {
if (hard_iface->net_dev == net_dev &&
kref_get_unless_zero(&hard_iface->refcount))
goto out;
}
hard_iface = NULL;
out:
rcu_read_unlock();
return hard_iface;
}
/**
* batadv_getlink_net() - return link net namespace (of use fallback)
* @netdev: net_device to check
* @fallback_net: return in case get_link_net is not available for @netdev
*
* Return: result of rtnl_link_ops->get_link_net or @fallback_net
*/
static struct net *batadv_getlink_net(const struct net_device *netdev,
struct net *fallback_net)
{
if (!netdev->rtnl_link_ops)
return fallback_net;
if (!netdev->rtnl_link_ops->get_link_net)
return fallback_net;
return netdev->rtnl_link_ops->get_link_net(netdev);
}
/**
* batadv_mutual_parents() - check if two devices are each others parent
* @dev1: 1st net dev
* @net1: 1st devices netns
* @dev2: 2nd net dev
* @net2: 2nd devices netns
*
* veth devices come in pairs and each is the parent of the other!
*
* Return: true if the devices are each others parent, otherwise false
*/
static bool batadv_mutual_parents(const struct net_device *dev1,
struct net *net1,
const struct net_device *dev2,
struct net *net2)
{
int dev1_parent_iflink = dev_get_iflink(dev1);
int dev2_parent_iflink = dev_get_iflink(dev2);
const struct net *dev1_parent_net;
const struct net *dev2_parent_net;
dev1_parent_net = batadv_getlink_net(dev1, net1);
dev2_parent_net = batadv_getlink_net(dev2, net2);
if (!dev1_parent_iflink || !dev2_parent_iflink)
return false;
return (dev1_parent_iflink == dev2->ifindex) &&
(dev2_parent_iflink == dev1->ifindex) &&
net_eq(dev1_parent_net, net2) &&
net_eq(dev2_parent_net, net1);
}
/**
* batadv_is_on_batman_iface() - check if a device is a batman iface descendant
* @net_dev: the device to check
*
* If the user creates any virtual device on top of a batman-adv interface, it
* is important to prevent this new interface to be used to create a new mesh
* network (this behaviour would lead to a batman-over-batman configuration).
* This function recursively checks all the fathers of the device passed as
* argument looking for a batman-adv soft interface.
*
* Return: true if the device is descendant of a batman-adv mesh interface (or
* if it is a batman-adv interface itself), false otherwise
*/
static bool batadv_is_on_batman_iface(const struct net_device *net_dev)
{
struct net *net = dev_net(net_dev);
struct net_device *parent_dev;
struct net *parent_net;
bool ret;
/* check if this is a batman-adv mesh interface */
if (batadv_softif_is_valid(net_dev))
return true;
/* no more parents..stop recursion */
if (dev_get_iflink(net_dev) == 0 ||
dev_get_iflink(net_dev) == net_dev->ifindex)
return false;
parent_net = batadv_getlink_net(net_dev, net);
/* recurse over the parent device */
parent_dev = __dev_get_by_index((struct net *)parent_net,
dev_get_iflink(net_dev));
/* if we got a NULL parent_dev there is something broken.. */
if (!parent_dev) {
pr_err("Cannot find parent device\n");
return false;
}
if (batadv_mutual_parents(net_dev, net, parent_dev, parent_net))
return false;
ret = batadv_is_on_batman_iface(parent_dev);
return ret;
}
static bool batadv_is_valid_iface(const struct net_device *net_dev)
{
if (net_dev->flags & IFF_LOOPBACK)
return false;
if (net_dev->type != ARPHRD_ETHER)
return false;
if (net_dev->addr_len != ETH_ALEN)
return false;
/* no batman over batman */
if (batadv_is_on_batman_iface(net_dev))
return false;
return true;
}
/**
* batadv_get_real_netdevice() - check if the given netdev struct is a virtual
* interface on top of another 'real' interface
* @netdev: the device to check
*
* Callers must hold the rtnl semaphore. You may want batadv_get_real_netdev()
* instead of this.
*
* Return: the 'real' net device or the original net device and NULL in case
* of an error.
*/
static struct net_device *batadv_get_real_netdevice(struct net_device *netdev)
{
struct batadv_hard_iface *hard_iface = NULL;
struct net_device *real_netdev = NULL;
struct net *real_net;
struct net *net;
int ifindex;
ASSERT_RTNL();
if (!netdev)
return NULL;
if (netdev->ifindex == dev_get_iflink(netdev)) {
dev_hold(netdev);
return netdev;
}
hard_iface = batadv_hardif_get_by_netdev(netdev);
if (!hard_iface || !hard_iface->soft_iface)
goto out;
net = dev_net(hard_iface->soft_iface);
ifindex = dev_get_iflink(netdev);
real_net = batadv_getlink_net(netdev, net);
real_netdev = dev_get_by_index(real_net, ifindex);
out:
if (hard_iface)
batadv_hardif_put(hard_iface);
return real_netdev;
}
/**
* batadv_get_real_netdev() - check if the given net_device struct is a virtual
* interface on top of another 'real' interface
* @net_device: the device to check
*
* Return: the 'real' net device or the original net device and NULL in case
* of an error.
*/
struct net_device *batadv_get_real_netdev(struct net_device *net_device)
{
struct net_device *real_netdev;
rtnl_lock();
real_netdev = batadv_get_real_netdevice(net_device);
rtnl_unlock();
return real_netdev;
}
/**
* batadv_is_wext_netdev() - check if the given net_device struct is a
* wext wifi interface
* @net_device: the device to check
*
* Return: true if the net device is a wext wireless device, false
* otherwise.
*/
static bool batadv_is_wext_netdev(struct net_device *net_device)
{
if (!net_device)
return false;
#ifdef CONFIG_WIRELESS_EXT
/* pre-cfg80211 drivers have to implement WEXT, so it is possible to
* check for wireless_handlers != NULL
*/
if (net_device->wireless_handlers)
return true;
#endif
return false;
}
/**
* batadv_is_cfg80211_netdev() - check if the given net_device struct is a
* cfg80211 wifi interface
* @net_device: the device to check
*
* Return: true if the net device is a cfg80211 wireless device, false
* otherwise.
*/
static bool batadv_is_cfg80211_netdev(struct net_device *net_device)
{
if (!net_device)
return false;
/* cfg80211 drivers have to set ieee80211_ptr */
if (net_device->ieee80211_ptr)
return true;
return false;
}
/**
* batadv_wifi_flags_evaluate() - calculate wifi flags for net_device
* @net_device: the device to check
*
* Return: batadv_hard_iface_wifi_flags flags of the device
*/
static u32 batadv_wifi_flags_evaluate(struct net_device *net_device)
{
u32 wifi_flags = 0;
struct net_device *real_netdev;
if (batadv_is_wext_netdev(net_device))
wifi_flags |= BATADV_HARDIF_WIFI_WEXT_DIRECT;
if (batadv_is_cfg80211_netdev(net_device))
wifi_flags |= BATADV_HARDIF_WIFI_CFG80211_DIRECT;
real_netdev = batadv_get_real_netdevice(net_device);
if (!real_netdev)
return wifi_flags;
if (real_netdev == net_device)
goto out;
if (batadv_is_wext_netdev(real_netdev))
wifi_flags |= BATADV_HARDIF_WIFI_WEXT_INDIRECT;
if (batadv_is_cfg80211_netdev(real_netdev))
wifi_flags |= BATADV_HARDIF_WIFI_CFG80211_INDIRECT;
out:
dev_put(real_netdev);
return wifi_flags;
}
/**
* batadv_is_cfg80211_hardif() - check if the given hardif is a cfg80211 wifi
* interface
* @hard_iface: the device to check
*
* Return: true if the net device is a cfg80211 wireless device, false
* otherwise.
*/
bool batadv_is_cfg80211_hardif(struct batadv_hard_iface *hard_iface)
{
u32 allowed_flags = 0;
allowed_flags |= BATADV_HARDIF_WIFI_CFG80211_DIRECT;
allowed_flags |= BATADV_HARDIF_WIFI_CFG80211_INDIRECT;
return !!(hard_iface->wifi_flags & allowed_flags);
}
/**
* batadv_is_wifi_hardif() - check if the given hardif is a wifi interface
* @hard_iface: the device to check
*
* Return: true if the net device is a 802.11 wireless device, false otherwise.
*/
bool batadv_is_wifi_hardif(struct batadv_hard_iface *hard_iface)
{
if (!hard_iface)
return false;
return hard_iface->wifi_flags != 0;
}
/**
* batadv_hardif_no_broadcast() - check whether (re)broadcast is necessary
* @if_outgoing: the outgoing interface checked and considered for (re)broadcast
* @orig_addr: the originator of this packet
* @orig_neigh: originator address of the forwarder we just got the packet from
* (NULL if we originated)
*
* Checks whether a packet needs to be (re)broadcasted on the given interface.
*
* Return:
* BATADV_HARDIF_BCAST_NORECIPIENT: No neighbor on interface
* BATADV_HARDIF_BCAST_DUPFWD: Just one neighbor, but it is the forwarder
* BATADV_HARDIF_BCAST_DUPORIG: Just one neighbor, but it is the originator
* BATADV_HARDIF_BCAST_OK: Several neighbors, must broadcast
*/
int batadv_hardif_no_broadcast(struct batadv_hard_iface *if_outgoing,
u8 *orig_addr, u8 *orig_neigh)
{
struct batadv_hardif_neigh_node *hardif_neigh;
struct hlist_node *first;
int ret = BATADV_HARDIF_BCAST_OK;
rcu_read_lock();
/* 0 neighbors -> no (re)broadcast */
first = rcu_dereference(hlist_first_rcu(&if_outgoing->neigh_list));
if (!first) {
ret = BATADV_HARDIF_BCAST_NORECIPIENT;
goto out;
}
/* >1 neighbors -> (re)brodcast */
if (rcu_dereference(hlist_next_rcu(first)))
goto out;
hardif_neigh = hlist_entry(first, struct batadv_hardif_neigh_node,
list);
/* 1 neighbor, is the originator -> no rebroadcast */
if (orig_addr && batadv_compare_eth(hardif_neigh->orig, orig_addr)) {
ret = BATADV_HARDIF_BCAST_DUPORIG;
/* 1 neighbor, is the one we received from -> no rebroadcast */
} else if (orig_neigh &&
batadv_compare_eth(hardif_neigh->orig, orig_neigh)) {
ret = BATADV_HARDIF_BCAST_DUPFWD;
}
out:
rcu_read_unlock();
return ret;
}
static struct batadv_hard_iface *
batadv_hardif_get_active(const struct net_device *soft_iface)
{
struct batadv_hard_iface *hard_iface;
rcu_read_lock();
list_for_each_entry_rcu(hard_iface, &batadv_hardif_list, list) {
if (hard_iface->soft_iface != soft_iface)
continue;
if (hard_iface->if_status == BATADV_IF_ACTIVE &&
kref_get_unless_zero(&hard_iface->refcount))
goto out;
}
hard_iface = NULL;
out:
rcu_read_unlock();
return hard_iface;
}
static void batadv_primary_if_update_addr(struct batadv_priv *bat_priv,
struct batadv_hard_iface *oldif)
{
struct batadv_hard_iface *primary_if;
primary_if = batadv_primary_if_get_selected(bat_priv);
if (!primary_if)
goto out;
batadv_dat_init_own_addr(bat_priv, primary_if);
batadv_bla_update_orig_address(bat_priv, primary_if, oldif);
out:
if (primary_if)
batadv_hardif_put(primary_if);
}
static void batadv_primary_if_select(struct batadv_priv *bat_priv,
struct batadv_hard_iface *new_hard_iface)
{
struct batadv_hard_iface *curr_hard_iface;
ASSERT_RTNL();
if (new_hard_iface)
kref_get(&new_hard_iface->refcount);
curr_hard_iface = rcu_dereference_protected(bat_priv->primary_if, 1);
rcu_assign_pointer(bat_priv->primary_if, new_hard_iface);
if (!new_hard_iface)
goto out;
bat_priv->algo_ops->iface.primary_set(new_hard_iface);
batadv_primary_if_update_addr(bat_priv, curr_hard_iface);
out:
if (curr_hard_iface)
batadv_hardif_put(curr_hard_iface);
}
static bool
batadv_hardif_is_iface_up(const struct batadv_hard_iface *hard_iface)
{
if (hard_iface->net_dev->flags & IFF_UP)
return true;
return false;
}
static void batadv_check_known_mac_addr(const struct net_device *net_dev)
{
const struct batadv_hard_iface *hard_iface;
rcu_read_lock();
list_for_each_entry_rcu(hard_iface, &batadv_hardif_list, list) {
if (hard_iface->if_status != BATADV_IF_ACTIVE &&
hard_iface->if_status != BATADV_IF_TO_BE_ACTIVATED)
continue;
if (hard_iface->net_dev == net_dev)
continue;
if (!batadv_compare_eth(hard_iface->net_dev->dev_addr,
net_dev->dev_addr))
continue;
pr_warn("The newly added mac address (%pM) already exists on: %s\n",
net_dev->dev_addr, hard_iface->net_dev->name);
pr_warn("It is strongly recommended to keep mac addresses unique to avoid problems!\n");
}
rcu_read_unlock();
}
/**
* batadv_hardif_recalc_extra_skbroom() - Recalculate skbuff extra head/tailroom
* @soft_iface: netdev struct of the mesh interface
*/
static void batadv_hardif_recalc_extra_skbroom(struct net_device *soft_iface)
{
const struct batadv_hard_iface *hard_iface;
unsigned short lower_header_len = ETH_HLEN;
unsigned short lower_headroom = 0;
unsigned short lower_tailroom = 0;
unsigned short needed_headroom;
rcu_read_lock();
list_for_each_entry_rcu(hard_iface, &batadv_hardif_list, list) {
if (hard_iface->if_status == BATADV_IF_NOT_IN_USE)
continue;
if (hard_iface->soft_iface != soft_iface)
continue;
lower_header_len = max_t(unsigned short, lower_header_len,
hard_iface->net_dev->hard_header_len);
lower_headroom = max_t(unsigned short, lower_headroom,
hard_iface->net_dev->needed_headroom);
lower_tailroom = max_t(unsigned short, lower_tailroom,
hard_iface->net_dev->needed_tailroom);
}
rcu_read_unlock();
needed_headroom = lower_headroom + (lower_header_len - ETH_HLEN);
needed_headroom += batadv_max_header_len();
soft_iface->needed_headroom = needed_headroom;
soft_iface->needed_tailroom = lower_tailroom;
}
/**
* batadv_hardif_min_mtu() - Calculate maximum MTU for soft interface
* @soft_iface: netdev struct of the soft interface
*
* Return: MTU for the soft-interface (limited by the minimal MTU of all active
* slave interfaces)
*/
int batadv_hardif_min_mtu(struct net_device *soft_iface)
{
struct batadv_priv *bat_priv = netdev_priv(soft_iface);
const struct batadv_hard_iface *hard_iface;
int min_mtu = INT_MAX;
rcu_read_lock();
list_for_each_entry_rcu(hard_iface, &batadv_hardif_list, list) {
if (hard_iface->if_status != BATADV_IF_ACTIVE &&
hard_iface->if_status != BATADV_IF_TO_BE_ACTIVATED)
continue;
if (hard_iface->soft_iface != soft_iface)
continue;
min_mtu = min_t(int, hard_iface->net_dev->mtu, min_mtu);
}
rcu_read_unlock();
if (atomic_read(&bat_priv->fragmentation) == 0)
goto out;
/* with fragmentation enabled the maximum size of internally generated
* packets such as translation table exchanges or tvlv containers, etc
* has to be calculated
*/
min_mtu = min_t(int, min_mtu, BATADV_FRAG_MAX_FRAG_SIZE);
min_mtu -= sizeof(struct batadv_frag_packet);
min_mtu *= BATADV_FRAG_MAX_FRAGMENTS;
out:
/* report to the other components the maximum amount of bytes that
* batman-adv can send over the wire (without considering the payload
* overhead). For example, this value is used by TT to compute the
* maximum local table table size
*/
atomic_set(&bat_priv->packet_size_max, min_mtu);
/* the real soft-interface MTU is computed by removing the payload
* overhead from the maximum amount of bytes that was just computed.
*
* However batman-adv does not support MTUs bigger than ETH_DATA_LEN
*/
return min_t(int, min_mtu - batadv_max_header_len(), ETH_DATA_LEN);
}
/**
* batadv_update_min_mtu() - Adjusts the MTU if a new interface with a smaller
* MTU appeared
* @soft_iface: netdev struct of the soft interface
*/
void batadv_update_min_mtu(struct net_device *soft_iface)
{
soft_iface->mtu = batadv_hardif_min_mtu(soft_iface);
/* Check if the local translate table should be cleaned up to match a
* new (and smaller) MTU.
*/
batadv_tt_local_resize_to_mtu(soft_iface);
}
static void
batadv_hardif_activate_interface(struct batadv_hard_iface *hard_iface)
{
struct batadv_priv *bat_priv;
struct batadv_hard_iface *primary_if = NULL;
if (hard_iface->if_status != BATADV_IF_INACTIVE)
goto out;
bat_priv = netdev_priv(hard_iface->soft_iface);
bat_priv->algo_ops->iface.update_mac(hard_iface);
hard_iface->if_status = BATADV_IF_TO_BE_ACTIVATED;
/* the first active interface becomes our primary interface or
* the next active interface after the old primary interface was removed
*/
primary_if = batadv_primary_if_get_selected(bat_priv);
if (!primary_if)
batadv_primary_if_select(bat_priv, hard_iface);
batadv_info(hard_iface->soft_iface, "Interface activated: %s\n",
hard_iface->net_dev->name);
batadv_update_min_mtu(hard_iface->soft_iface);
if (bat_priv->algo_ops->iface.activate)
bat_priv->algo_ops->iface.activate(hard_iface);
out:
if (primary_if)
batadv_hardif_put(primary_if);
}
static void
batadv_hardif_deactivate_interface(struct batadv_hard_iface *hard_iface)
{
if (hard_iface->if_status != BATADV_IF_ACTIVE &&
hard_iface->if_status != BATADV_IF_TO_BE_ACTIVATED)
return;
hard_iface->if_status = BATADV_IF_INACTIVE;
batadv_info(hard_iface->soft_iface, "Interface deactivated: %s\n",
hard_iface->net_dev->name);
batadv_update_min_mtu(hard_iface->soft_iface);
}
/**
* batadv_master_del_slave() - remove hard_iface from the current master iface
* @slave: the interface enslaved in another master
* @master: the master from which slave has to be removed
*
* Invoke ndo_del_slave on master passing slave as argument. In this way slave
* is free'd and master can correctly change its internal state.
*
* Return: 0 on success, a negative value representing the error otherwise
*/
static int batadv_master_del_slave(struct batadv_hard_iface *slave,
struct net_device *master)
{
int ret;
if (!master)
return 0;
ret = -EBUSY;
if (master->netdev_ops->ndo_del_slave)
ret = master->netdev_ops->ndo_del_slave(master, slave->net_dev);
return ret;
}
/**
* batadv_hardif_enable_interface() - Enslave hard interface to soft interface
* @hard_iface: hard interface to add to soft interface
* @net: the applicable net namespace
* @iface_name: name of the soft interface
*
* Return: 0 on success or negative error number in case of failure
*/
int batadv_hardif_enable_interface(struct batadv_hard_iface *hard_iface,
struct net *net, const char *iface_name)
{
struct batadv_priv *bat_priv;
struct net_device *soft_iface, *master;
__be16 ethertype = htons(ETH_P_BATMAN);
int max_header_len = batadv_max_header_len();
int ret;
if (hard_iface->if_status != BATADV_IF_NOT_IN_USE)
goto out;
kref_get(&hard_iface->refcount);
soft_iface = dev_get_by_name(net, iface_name);
if (!soft_iface) {
soft_iface = batadv_softif_create(net, iface_name);
if (!soft_iface) {
ret = -ENOMEM;
goto err;
}
/* dev_get_by_name() increases the reference counter for us */
dev_hold(soft_iface);
}
if (!batadv_softif_is_valid(soft_iface)) {
pr_err("Can't create batman mesh interface %s: already exists as regular interface\n",
soft_iface->name);
ret = -EINVAL;
goto err_dev;
}
/* check if the interface is enslaved in another virtual one and
* in that case unlink it first
*/
master = netdev_master_upper_dev_get(hard_iface->net_dev);
ret = batadv_master_del_slave(hard_iface, master);
if (ret)
goto err_dev;
hard_iface->soft_iface = soft_iface;
bat_priv = netdev_priv(hard_iface->soft_iface);
ret = netdev_master_upper_dev_link(hard_iface->net_dev,
soft_iface, NULL, NULL, NULL);
if (ret)
goto err_dev;
ret = bat_priv->algo_ops->iface.enable(hard_iface);
if (ret < 0)
goto err_upper;
hard_iface->if_status = BATADV_IF_INACTIVE;
kref_get(&hard_iface->refcount);
hard_iface->batman_adv_ptype.type = ethertype;
hard_iface->batman_adv_ptype.func = batadv_batman_skb_recv;
hard_iface->batman_adv_ptype.dev = hard_iface->net_dev;
dev_add_pack(&hard_iface->batman_adv_ptype);
batadv_info(hard_iface->soft_iface, "Adding interface: %s\n",
hard_iface->net_dev->name);
if (atomic_read(&bat_priv->fragmentation) &&
hard_iface->net_dev->mtu < ETH_DATA_LEN + max_header_len)
batadv_info(hard_iface->soft_iface,
"The MTU of interface %s is too small (%i) to handle the transport of batman-adv packets. Packets going over this interface will be fragmented on layer2 which could impact the performance. Setting the MTU to %i would solve the problem.\n",
hard_iface->net_dev->name, hard_iface->net_dev->mtu,
ETH_DATA_LEN + max_header_len);
if (!atomic_read(&bat_priv->fragmentation) &&
hard_iface->net_dev->mtu < ETH_DATA_LEN + max_header_len)
batadv_info(hard_iface->soft_iface,
"The MTU of interface %s is too small (%i) to handle the transport of batman-adv packets. If you experience problems getting traffic through try increasing the MTU to %i.\n",
hard_iface->net_dev->name, hard_iface->net_dev->mtu,
ETH_DATA_LEN + max_header_len);
if (batadv_hardif_is_iface_up(hard_iface))
batadv_hardif_activate_interface(hard_iface);
else
batadv_err(hard_iface->soft_iface,
"Not using interface %s (retrying later): interface not active\n",
hard_iface->net_dev->name);
batadv_hardif_recalc_extra_skbroom(soft_iface);
if (bat_priv->algo_ops->iface.enabled)
bat_priv->algo_ops->iface.enabled(hard_iface);
out:
return 0;
err_upper:
netdev_upper_dev_unlink(hard_iface->net_dev, soft_iface);
err_dev:
hard_iface->soft_iface = NULL;
dev_put(soft_iface);
err:
batadv_hardif_put(hard_iface);
return ret;
}
/**
* batadv_hardif_cnt() - get number of interfaces enslaved to soft interface
* @soft_iface: soft interface to check
*
* This function is only using RCU for locking - the result can therefore be
* off when another functions is modifying the list at the same time. The
* caller can use the rtnl_lock to make sure that the count is accurate.
*
* Return: number of connected/enslaved hard interfaces
*/
static size_t batadv_hardif_cnt(const struct net_device *soft_iface)
{
struct batadv_hard_iface *hard_iface;
size_t count = 0;
rcu_read_lock();
list_for_each_entry_rcu(hard_iface, &batadv_hardif_list, list) {
if (hard_iface->soft_iface != soft_iface)
continue;
count++;
}
rcu_read_unlock();
return count;
}
/**
* batadv_hardif_disable_interface() - Remove hard interface from soft interface
* @hard_iface: hard interface to be removed
* @autodel: whether to delete soft interface when it doesn't contain any other
* slave interfaces
*/
void batadv_hardif_disable_interface(struct batadv_hard_iface *hard_iface,
enum batadv_hard_if_cleanup autodel)
{
struct batadv_priv *bat_priv = netdev_priv(hard_iface->soft_iface);
struct batadv_hard_iface *primary_if = NULL;
batadv_hardif_deactivate_interface(hard_iface);
if (hard_iface->if_status != BATADV_IF_INACTIVE)
goto out;
batadv_info(hard_iface->soft_iface, "Removing interface: %s\n",
hard_iface->net_dev->name);
dev_remove_pack(&hard_iface->batman_adv_ptype);
batadv_hardif_put(hard_iface);
primary_if = batadv_primary_if_get_selected(bat_priv);
if (hard_iface == primary_if) {
struct batadv_hard_iface *new_if;
new_if = batadv_hardif_get_active(hard_iface->soft_iface);
batadv_primary_if_select(bat_priv, new_if);
if (new_if)
batadv_hardif_put(new_if);
}
bat_priv->algo_ops->iface.disable(hard_iface);
hard_iface->if_status = BATADV_IF_NOT_IN_USE;
/* delete all references to this hard_iface */
batadv_purge_orig_ref(bat_priv);
batadv_purge_outstanding_packets(bat_priv, hard_iface);
dev_put(hard_iface->soft_iface);
netdev_upper_dev_unlink(hard_iface->net_dev, hard_iface->soft_iface);
batadv_hardif_recalc_extra_skbroom(hard_iface->soft_iface);
/* nobody uses this interface anymore */
if (batadv_hardif_cnt(hard_iface->soft_iface) <= 1) {
batadv_gw_check_client_stop(bat_priv);
if (autodel == BATADV_IF_CLEANUP_AUTO)
batadv_softif_destroy_sysfs(hard_iface->soft_iface);
}
hard_iface->soft_iface = NULL;
batadv_hardif_put(hard_iface);
out:
if (primary_if)
batadv_hardif_put(primary_if);
}
static struct batadv_hard_iface *
batadv_hardif_add_interface(struct net_device *net_dev)
{
struct batadv_hard_iface *hard_iface;
int ret;
ASSERT_RTNL();
if (!batadv_is_valid_iface(net_dev))
goto out;
dev_hold(net_dev);
hard_iface = kzalloc(sizeof(*hard_iface), GFP_ATOMIC);
if (!hard_iface)
goto release_dev;
ret = batadv_sysfs_add_hardif(&hard_iface->hardif_obj, net_dev);
if (ret)
goto free_if;
hard_iface->net_dev = net_dev;
hard_iface->soft_iface = NULL;
hard_iface->if_status = BATADV_IF_NOT_IN_USE;
batadv_debugfs_add_hardif(hard_iface);
INIT_LIST_HEAD(&hard_iface->list);
INIT_HLIST_HEAD(&hard_iface->neigh_list);
spin_lock_init(&hard_iface->neigh_list_lock);
kref_init(&hard_iface->refcount);
hard_iface->num_bcasts = BATADV_NUM_BCASTS_DEFAULT;
hard_iface->wifi_flags = batadv_wifi_flags_evaluate(net_dev);
if (batadv_is_wifi_hardif(hard_iface))
hard_iface->num_bcasts = BATADV_NUM_BCASTS_WIRELESS;
batadv_v_hardif_init(hard_iface);
batadv_check_known_mac_addr(hard_iface->net_dev);
kref_get(&hard_iface->refcount);
list_add_tail_rcu(&hard_iface->list, &batadv_hardif_list);
batadv_hardif_generation++;
return hard_iface;
free_if:
kfree(hard_iface);
release_dev:
dev_put(net_dev);
out:
return NULL;
}
static void batadv_hardif_remove_interface(struct batadv_hard_iface *hard_iface)
{
ASSERT_RTNL();
/* first deactivate interface */
if (hard_iface->if_status != BATADV_IF_NOT_IN_USE)
batadv_hardif_disable_interface(hard_iface,
BATADV_IF_CLEANUP_KEEP);
if (hard_iface->if_status != BATADV_IF_NOT_IN_USE)
return;
hard_iface->if_status = BATADV_IF_TO_BE_REMOVED;
batadv_debugfs_del_hardif(hard_iface);
batadv_sysfs_del_hardif(&hard_iface->hardif_obj);
batadv_hardif_put(hard_iface);
}
/**
* batadv_hardif_remove_interfaces() - Remove all hard interfaces
*/
void batadv_hardif_remove_interfaces(void)
{
struct batadv_hard_iface *hard_iface, *hard_iface_tmp;
rtnl_lock();
list_for_each_entry_safe(hard_iface, hard_iface_tmp,
&batadv_hardif_list, list) {
list_del_rcu(&hard_iface->list);
batadv_hardif_generation++;
batadv_hardif_remove_interface(hard_iface);
}
rtnl_unlock();
}
/**
* batadv_hard_if_event_softif() - Handle events for soft interfaces
* @event: NETDEV_* event to handle
* @net_dev: net_device which generated an event
*
* Return: NOTIFY_* result
*/
static int batadv_hard_if_event_softif(unsigned long event,
struct net_device *net_dev)
{
struct batadv_priv *bat_priv;
switch (event) {
case NETDEV_REGISTER:
batadv_sysfs_add_meshif(net_dev);
bat_priv = netdev_priv(net_dev);
batadv_softif_create_vlan(bat_priv, BATADV_NO_FLAGS);
break;
case NETDEV_CHANGENAME:
batadv_debugfs_rename_meshif(net_dev);
break;
}
return NOTIFY_DONE;
}
static int batadv_hard_if_event(struct notifier_block *this,
unsigned long event, void *ptr)
{
struct net_device *net_dev = netdev_notifier_info_to_dev(ptr);
struct batadv_hard_iface *hard_iface;
struct batadv_hard_iface *primary_if = NULL;
struct batadv_priv *bat_priv;
if (batadv_softif_is_valid(net_dev))
return batadv_hard_if_event_softif(event, net_dev);
hard_iface = batadv_hardif_get_by_netdev(net_dev);
if (!hard_iface && (event == NETDEV_REGISTER ||
event == NETDEV_POST_TYPE_CHANGE))
hard_iface = batadv_hardif_add_interface(net_dev);
if (!hard_iface)
goto out;
switch (event) {
case NETDEV_UP:
batadv_hardif_activate_interface(hard_iface);
break;
case NETDEV_GOING_DOWN:
case NETDEV_DOWN:
batadv_hardif_deactivate_interface(hard_iface);
break;
case NETDEV_UNREGISTER:
case NETDEV_PRE_TYPE_CHANGE:
list_del_rcu(&hard_iface->list);
batadv_hardif_generation++;
batadv_hardif_remove_interface(hard_iface);
break;
case NETDEV_CHANGEMTU:
if (hard_iface->soft_iface)
batadv_update_min_mtu(hard_iface->soft_iface);
break;
case NETDEV_CHANGEADDR:
if (hard_iface->if_status == BATADV_IF_NOT_IN_USE)
goto hardif_put;
batadv_check_known_mac_addr(hard_iface->net_dev);
bat_priv = netdev_priv(hard_iface->soft_iface);
bat_priv->algo_ops->iface.update_mac(hard_iface);
primary_if = batadv_primary_if_get_selected(bat_priv);
if (!primary_if)
goto hardif_put;
if (hard_iface == primary_if)
batadv_primary_if_update_addr(bat_priv, NULL);
break;
case NETDEV_CHANGEUPPER:
hard_iface->wifi_flags = batadv_wifi_flags_evaluate(net_dev);
if (batadv_is_wifi_hardif(hard_iface))
hard_iface->num_bcasts = BATADV_NUM_BCASTS_WIRELESS;
break;
case NETDEV_CHANGENAME:
batadv_debugfs_rename_hardif(hard_iface);
break;
default:
break;
}
hardif_put:
batadv_hardif_put(hard_iface);
out:
if (primary_if)
batadv_hardif_put(primary_if);
return NOTIFY_DONE;
}
struct notifier_block batadv_hard_if_notifier = {
.notifier_call = batadv_hard_if_event,
};
| 27.455708 | 246 | 0.758482 | [
"mesh",
"object"
] |
d27e0be2a5ab9a16cb1c7f394f286fae28bd6e40 | 2,688 | h | C | LYGTOnePass/Frameworks/GTOnePass.framework/Headers/GOPManager.h | ButtFly/LYGTOnePass | 662456617e11d23b9f457961b218f95c3231706f | [
"MIT"
] | null | null | null | LYGTOnePass/Frameworks/GTOnePass.framework/Headers/GOPManager.h | ButtFly/LYGTOnePass | 662456617e11d23b9f457961b218f95c3231706f | [
"MIT"
] | null | null | null | LYGTOnePass/Frameworks/GTOnePass.framework/Headers/GOPManager.h | ButtFly/LYGTOnePass | 662456617e11d23b9f457961b218f95c3231706f | [
"MIT"
] | null | null | null | //
// GOPManager.h
// GOPPhone
//
// Created by NikoXu on 07/09/2017.
// Copyright © 2017 geetest. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "GOPError.h"
@protocol GOPManagerDelegate;
typedef NS_ENUM(NSInteger, GOPPhoneNumEncryptOption) {
GOPPhoneNumEncryptOptionNone = 0, // none
GOPPhoneNumEncryptOptionSha256 // sha256
};
typedef void(^GOPCompletion)(NSDictionary *dict);
typedef void(^GOPFailure)(NSError *error);
@interface GOPManager : NSObject
@property (nonatomic, weak) id<GOPManagerDelegate> delegate;
/**
Diagnosis current network status.
If OnePass could work, `diagnosisStatus` return YES.
@discussion
In the extreme situation, `diagnosisStatus` isn't reliable.
*/
@property (nonatomic, readonly, assign) BOOL diagnosisStatus;
/**
Return current phone number.
If encrypted, return encrypted phone number.
@discussion
Before OnePass callback, `currentPhoneNum` return
original phone number.
*/
@property (nonatomic, readonly, copy) NSString *currentPhoneNum;
/**
Phone number Encryption Option.
If encrypted, it will be hard to debug. We recommend developers not to use this option.
If you want use this option, you should register this feature through us first.
*/
@property (nonatomic, assign) GOPPhoneNumEncryptOption phoneNumEncryptOption;
/**
Initializes and returns a newly allocated GOPManager object.
@discussion Register customID from `geetest.com`, and configure your verifyUrl
API base on Server SDK. Check Docs on `docs.geetest.com`. If OnePass
fail, GOPManager will request SMS URL that you set.
@param customID custom ID, nonull
@param timeout timeout interval
@return A initialized GOPManager object.
*/
- (instancetype)initWithCustomID:(NSString *)customID timeout:(NSTimeInterval)timeout;
/**
Verify phone number through OnePass.
See a sample result from `https://github.com/GeeTeam/gop-ios-sdk/blob/master/SDK/gop-ios-dev-doc.md#verifyphonenumcompletionfailure`
@discussion Country Code `+86` Only. Regex rule `^1([3-9])\\d{9}$`.
If you don't want to use validate, you should modify customID configuration
by contacting geetest stuff first.
QQ:2314321393 or E-mail: contact@geetest.com
@param phoneNum phone number, nonull
*/
- (void)verifyPhoneNumber:(NSString *)phoneNum;
@end
/**
Manager related to the operation of a verification that handle request
directly to the delegate.
*/
@protocol GOPManagerDelegate <NSObject>
@required
- (void)gtOnePass:(GOPManager *)manager errorHandler:(GOPError *)error;
- (void)gtOnePass:(GOPManager *)manager didReceiveDataToVerify:(NSDictionary *)data;
@end
| 29.217391 | 133 | 0.74442 | [
"object"
] |
d27e1c4a7945935fc175cde160db4170be1152c1 | 38,106 | c | C | Python-3.5.5/Modules/_functoolsmodule.c | it315/PSPNet-Keras-tensorflow | 876448d9c44a8ca475cf0f60f69eb3c72651be87 | [
"MIT"
] | 6 | 2018-02-23T08:52:04.000Z | 2021-08-19T12:01:50.000Z | Python-3.5.5/Modules/_functoolsmodule.c | it315/PSPNet-Keras-tensorflow | 876448d9c44a8ca475cf0f60f69eb3c72651be87 | [
"MIT"
] | 5 | 2021-12-14T20:56:36.000Z | 2021-12-20T14:45:34.000Z | Python-3.5.10/Modules/_functoolsmodule.c | AtriCZE23/POe-full | 89be2fda5747e44764a62ba5e358d8c9309fbf0a | [
"MIT",
"CNRI-Python-GPL-Compatible",
"BSD-3-Clause"
] | 1 | 2019-05-06T14:36:47.000Z | 2019-05-06T14:36:47.000Z |
#include "Python.h"
#include "structmember.h"
/* _functools module written and maintained
by Hye-Shik Chang <perky@FreeBSD.org>
with adaptations by Raymond Hettinger <python@rcn.com>
Copyright (c) 2004, 2005, 2006 Python Software Foundation.
All rights reserved.
*/
/* partial object **********************************************************/
typedef struct {
PyObject_HEAD
PyObject *fn;
PyObject *args;
PyObject *kw;
PyObject *dict;
PyObject *weakreflist; /* List of weak references */
} partialobject;
static PyTypeObject partial_type;
static PyObject *
partial_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
PyObject *func, *pargs, *nargs, *pkw;
partialobject *pto;
if (PyTuple_GET_SIZE(args) < 1) {
PyErr_SetString(PyExc_TypeError,
"type 'partial' takes at least one argument");
return NULL;
}
pargs = pkw = NULL;
func = PyTuple_GET_ITEM(args, 0);
if (Py_TYPE(func) == &partial_type && type == &partial_type) {
partialobject *part = (partialobject *)func;
if (part->dict == NULL) {
pargs = part->args;
pkw = part->kw;
func = part->fn;
assert(PyTuple_Check(pargs));
assert(PyDict_Check(pkw));
}
}
if (!PyCallable_Check(func)) {
PyErr_SetString(PyExc_TypeError,
"the first argument must be callable");
return NULL;
}
/* create partialobject structure */
pto = (partialobject *)type->tp_alloc(type, 0);
if (pto == NULL)
return NULL;
pto->fn = func;
Py_INCREF(func);
nargs = PyTuple_GetSlice(args, 1, PY_SSIZE_T_MAX);
if (nargs == NULL) {
Py_DECREF(pto);
return NULL;
}
if (pargs == NULL || PyTuple_GET_SIZE(pargs) == 0) {
pto->args = nargs;
Py_INCREF(nargs);
}
else if (PyTuple_GET_SIZE(nargs) == 0) {
pto->args = pargs;
Py_INCREF(pargs);
}
else {
pto->args = PySequence_Concat(pargs, nargs);
if (pto->args == NULL) {
Py_DECREF(nargs);
Py_DECREF(pto);
return NULL;
}
assert(PyTuple_Check(pto->args));
}
Py_DECREF(nargs);
if (pkw == NULL || PyDict_Size(pkw) == 0) {
if (kw == NULL) {
pto->kw = PyDict_New();
}
else if (Py_REFCNT(kw) == 1) {
Py_INCREF(kw);
pto->kw = kw;
}
else {
pto->kw = PyDict_Copy(kw);
}
}
else {
pto->kw = PyDict_Copy(pkw);
if (kw != NULL && pto->kw != NULL) {
if (PyDict_Merge(pto->kw, kw, 1) != 0) {
Py_DECREF(pto);
return NULL;
}
}
}
if (pto->kw == NULL) {
Py_DECREF(pto);
return NULL;
}
return (PyObject *)pto;
}
static void
partial_dealloc(partialobject *pto)
{
/* bpo-31095: UnTrack is needed before calling any callbacks */
PyObject_GC_UnTrack(pto);
if (pto->weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject *) pto);
Py_XDECREF(pto->fn);
Py_XDECREF(pto->args);
Py_XDECREF(pto->kw);
Py_XDECREF(pto->dict);
Py_TYPE(pto)->tp_free(pto);
}
static PyObject *
partial_call(partialobject *pto, PyObject *args, PyObject *kw)
{
PyObject *ret;
PyObject *argappl, *kwappl;
assert (PyCallable_Check(pto->fn));
assert (PyTuple_Check(pto->args));
assert (PyDict_Check(pto->kw));
if (PyTuple_GET_SIZE(pto->args) == 0) {
argappl = args;
Py_INCREF(args);
} else if (PyTuple_GET_SIZE(args) == 0) {
argappl = pto->args;
Py_INCREF(pto->args);
} else {
argappl = PySequence_Concat(pto->args, args);
if (argappl == NULL)
return NULL;
assert(PyTuple_Check(argappl));
}
if (PyDict_Size(pto->kw) == 0) {
kwappl = kw;
Py_XINCREF(kwappl);
} else {
kwappl = PyDict_Copy(pto->kw);
if (kwappl == NULL) {
Py_DECREF(argappl);
return NULL;
}
if (kw != NULL) {
if (PyDict_Merge(kwappl, kw, 1) != 0) {
Py_DECREF(argappl);
Py_DECREF(kwappl);
return NULL;
}
}
}
ret = PyObject_Call(pto->fn, argappl, kwappl);
Py_DECREF(argappl);
Py_XDECREF(kwappl);
return ret;
}
static int
partial_traverse(partialobject *pto, visitproc visit, void *arg)
{
Py_VISIT(pto->fn);
Py_VISIT(pto->args);
Py_VISIT(pto->kw);
Py_VISIT(pto->dict);
return 0;
}
PyDoc_STRVAR(partial_doc,
"partial(func, *args, **keywords) - new function with partial application\n\
of the given arguments and keywords.\n");
#define OFF(x) offsetof(partialobject, x)
static PyMemberDef partial_memberlist[] = {
{"func", T_OBJECT, OFF(fn), READONLY,
"function object to use in future partial calls"},
{"args", T_OBJECT, OFF(args), READONLY,
"tuple of arguments to future partial calls"},
{"keywords", T_OBJECT, OFF(kw), READONLY,
"dictionary of keyword arguments to future partial calls"},
{NULL} /* Sentinel */
};
static PyGetSetDef partial_getsetlist[] = {
{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
{NULL} /* Sentinel */
};
static PyObject *
partial_repr(partialobject *pto)
{
PyObject *result = NULL;
PyObject *arglist;
Py_ssize_t i, n;
PyObject *key, *value;
int status;
status = Py_ReprEnter((PyObject *)pto);
if (status != 0) {
if (status < 0)
return NULL;
return PyUnicode_FromFormat("%s(...)", Py_TYPE(pto)->tp_name);
}
arglist = PyUnicode_FromString("");
if (arglist == NULL)
goto done;
/* Pack positional arguments */
assert (PyTuple_Check(pto->args));
n = PyTuple_GET_SIZE(pto->args);
for (i = 0; i < n; i++) {
Py_SETREF(arglist, PyUnicode_FromFormat("%U, %R", arglist,
PyTuple_GET_ITEM(pto->args, i)));
if (arglist == NULL)
goto done;
}
/* Pack keyword arguments */
assert (PyDict_Check(pto->kw));
for (i = 0; PyDict_Next(pto->kw, &i, &key, &value);) {
/* Prevent key.__str__ from deleting the value. */
Py_INCREF(value);
Py_SETREF(arglist, PyUnicode_FromFormat("%U, %S=%R", arglist,
key, value));
Py_DECREF(value);
if (arglist == NULL)
goto done;
}
result = PyUnicode_FromFormat("%s(%R%U)", Py_TYPE(pto)->tp_name,
pto->fn, arglist);
Py_DECREF(arglist);
done:
Py_ReprLeave((PyObject *)pto);
return result;
}
/* Pickle strategy:
__reduce__ by itself doesn't support getting kwargs in the unpickle
operation so we define a __setstate__ that replaces all the information
about the partial. If we only replaced part of it someone would use
it as a hook to do strange things.
*/
static PyObject *
partial_reduce(partialobject *pto, PyObject *unused)
{
return Py_BuildValue("O(O)(OOOO)", Py_TYPE(pto), pto->fn, pto->fn,
pto->args, pto->kw,
pto->dict ? pto->dict : Py_None);
}
static PyObject *
partial_setstate(partialobject *pto, PyObject *state)
{
PyObject *fn, *fnargs, *kw, *dict;
if (!PyTuple_Check(state) ||
!PyArg_ParseTuple(state, "OOOO", &fn, &fnargs, &kw, &dict) ||
!PyCallable_Check(fn) ||
!PyTuple_Check(fnargs) ||
(kw != Py_None && !PyDict_Check(kw)))
{
PyErr_SetString(PyExc_TypeError, "invalid partial state");
return NULL;
}
if(!PyTuple_CheckExact(fnargs))
fnargs = PySequence_Tuple(fnargs);
else
Py_INCREF(fnargs);
if (fnargs == NULL)
return NULL;
if (kw == Py_None)
kw = PyDict_New();
else if(!PyDict_CheckExact(kw))
kw = PyDict_Copy(kw);
else
Py_INCREF(kw);
if (kw == NULL) {
Py_DECREF(fnargs);
return NULL;
}
Py_INCREF(fn);
if (dict == Py_None)
dict = NULL;
else
Py_INCREF(dict);
Py_SETREF(pto->fn, fn);
Py_SETREF(pto->args, fnargs);
Py_SETREF(pto->kw, kw);
Py_XSETREF(pto->dict, dict);
Py_RETURN_NONE;
}
static PyMethodDef partial_methods[] = {
{"__reduce__", (PyCFunction)partial_reduce, METH_NOARGS},
{"__setstate__", (PyCFunction)partial_setstate, METH_O},
{NULL, NULL} /* sentinel */
};
static PyTypeObject partial_type = {
PyVarObject_HEAD_INIT(NULL, 0)
"functools.partial", /* tp_name */
sizeof(partialobject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)partial_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
(reprfunc)partial_repr, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
(ternaryfunc)partial_call, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
PyObject_GenericSetAttr, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
Py_TPFLAGS_BASETYPE, /* tp_flags */
partial_doc, /* tp_doc */
(traverseproc)partial_traverse, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
offsetof(partialobject, weakreflist), /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
partial_methods, /* tp_methods */
partial_memberlist, /* tp_members */
partial_getsetlist, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
offsetof(partialobject, dict), /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
partial_new, /* tp_new */
PyObject_GC_Del, /* tp_free */
};
/* cmp_to_key ***************************************************************/
typedef struct {
PyObject_HEAD
PyObject *cmp;
PyObject *object;
} keyobject;
static void
keyobject_dealloc(keyobject *ko)
{
Py_DECREF(ko->cmp);
Py_XDECREF(ko->object);
PyObject_FREE(ko);
}
static int
keyobject_traverse(keyobject *ko, visitproc visit, void *arg)
{
Py_VISIT(ko->cmp);
if (ko->object)
Py_VISIT(ko->object);
return 0;
}
static int
keyobject_clear(keyobject *ko)
{
Py_CLEAR(ko->cmp);
if (ko->object)
Py_CLEAR(ko->object);
return 0;
}
static PyMemberDef keyobject_members[] = {
{"obj", T_OBJECT,
offsetof(keyobject, object), 0,
PyDoc_STR("Value wrapped by a key function.")},
{NULL}
};
static PyObject *
keyobject_call(keyobject *ko, PyObject *args, PyObject *kwds);
static PyObject *
keyobject_richcompare(PyObject *ko, PyObject *other, int op);
static PyTypeObject keyobject_type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"functools.KeyWrapper", /* tp_name */
sizeof(keyobject), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)keyobject_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
(ternaryfunc)keyobject_call, /* tp_call */
0, /* tp_str */
PyObject_GenericGetAttr, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
0, /* tp_doc */
(traverseproc)keyobject_traverse, /* tp_traverse */
(inquiry)keyobject_clear, /* tp_clear */
keyobject_richcompare, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
keyobject_members, /* tp_members */
0, /* tp_getset */
};
static PyObject *
keyobject_call(keyobject *ko, PyObject *args, PyObject *kwds)
{
PyObject *object;
keyobject *result;
static char *kwargs[] = {"obj", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:K", kwargs, &object))
return NULL;
result = PyObject_New(keyobject, &keyobject_type);
if (!result)
return NULL;
Py_INCREF(ko->cmp);
result->cmp = ko->cmp;
Py_INCREF(object);
result->object = object;
return (PyObject *)result;
}
static PyObject *
keyobject_richcompare(PyObject *ko, PyObject *other, int op)
{
PyObject *res;
PyObject *args;
PyObject *x;
PyObject *y;
PyObject *compare;
PyObject *answer;
static PyObject *zero;
if (zero == NULL) {
zero = PyLong_FromLong(0);
if (!zero)
return NULL;
}
if (Py_TYPE(other) != &keyobject_type){
PyErr_Format(PyExc_TypeError, "other argument must be K instance");
return NULL;
}
compare = ((keyobject *) ko)->cmp;
assert(compare != NULL);
x = ((keyobject *) ko)->object;
y = ((keyobject *) other)->object;
if (!x || !y){
PyErr_Format(PyExc_AttributeError, "object");
return NULL;
}
/* Call the user's comparison function and translate the 3-way
* result into true or false (or error).
*/
args = PyTuple_New(2);
if (args == NULL)
return NULL;
Py_INCREF(x);
Py_INCREF(y);
PyTuple_SET_ITEM(args, 0, x);
PyTuple_SET_ITEM(args, 1, y);
res = PyObject_Call(compare, args, NULL);
Py_DECREF(args);
if (res == NULL)
return NULL;
answer = PyObject_RichCompare(res, zero, op);
Py_DECREF(res);
return answer;
}
static PyObject *
functools_cmp_to_key(PyObject *self, PyObject *args, PyObject *kwds)
{
PyObject *cmp;
static char *kwargs[] = {"mycmp", NULL};
keyobject *object;
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:cmp_to_key", kwargs, &cmp))
return NULL;
object = PyObject_New(keyobject, &keyobject_type);
if (!object)
return NULL;
Py_INCREF(cmp);
object->cmp = cmp;
object->object = NULL;
return (PyObject *)object;
}
PyDoc_STRVAR(functools_cmp_to_key_doc,
"Convert a cmp= function into a key= function.");
/* reduce (used to be a builtin) ********************************************/
static PyObject *
functools_reduce(PyObject *self, PyObject *args)
{
PyObject *seq, *func, *result = NULL, *it;
if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result))
return NULL;
if (result != NULL)
Py_INCREF(result);
it = PyObject_GetIter(seq);
if (it == NULL) {
if (PyErr_ExceptionMatches(PyExc_TypeError))
PyErr_SetString(PyExc_TypeError,
"reduce() arg 2 must support iteration");
Py_XDECREF(result);
return NULL;
}
if ((args = PyTuple_New(2)) == NULL)
goto Fail;
for (;;) {
PyObject *op2;
if (args->ob_refcnt > 1) {
Py_DECREF(args);
if ((args = PyTuple_New(2)) == NULL)
goto Fail;
}
op2 = PyIter_Next(it);
if (op2 == NULL) {
if (PyErr_Occurred())
goto Fail;
break;
}
if (result == NULL)
result = op2;
else {
PyTuple_SetItem(args, 0, result);
PyTuple_SetItem(args, 1, op2);
if ((result = PyEval_CallObject(func, args)) == NULL)
goto Fail;
}
}
Py_DECREF(args);
if (result == NULL)
PyErr_SetString(PyExc_TypeError,
"reduce() of empty sequence with no initial value");
Py_DECREF(it);
return result;
Fail:
Py_XDECREF(args);
Py_XDECREF(result);
Py_DECREF(it);
return NULL;
}
PyDoc_STRVAR(functools_reduce_doc,
"reduce(function, sequence[, initial]) -> value\n\
\n\
Apply a function of two arguments cumulatively to the items of a sequence,\n\
from left to right, so as to reduce the sequence to a single value.\n\
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\
((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\
of the sequence in the calculation, and serves as a default when the\n\
sequence is empty.");
/* lru_cache object **********************************************************/
/* this object is used delimit args and keywords in the cache keys */
static PyObject *kwd_mark = NULL;
struct lru_list_elem;
struct lru_cache_object;
typedef struct lru_list_elem {
PyObject_HEAD
struct lru_list_elem *prev, *next; /* borrowed links */
Py_hash_t hash;
PyObject *key, *result;
} lru_list_elem;
static void
lru_list_elem_dealloc(lru_list_elem *link)
{
_PyObject_GC_UNTRACK(link);
Py_XDECREF(link->key);
Py_XDECREF(link->result);
PyObject_GC_Del(link);
}
static int
lru_list_elem_traverse(lru_list_elem *link, visitproc visit, void *arg)
{
Py_VISIT(link->key);
Py_VISIT(link->result);
return 0;
}
static int
lru_list_elem_clear(lru_list_elem *link)
{
Py_CLEAR(link->key);
Py_CLEAR(link->result);
return 0;
}
static PyTypeObject lru_list_elem_type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"functools._lru_list_elem", /* tp_name */
sizeof(lru_list_elem), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)lru_list_elem_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
0, /* tp_doc */
(traverseproc)lru_list_elem_traverse, /* tp_traverse */
(inquiry)lru_list_elem_clear, /* tp_clear */
};
typedef PyObject *(*lru_cache_ternaryfunc)(struct lru_cache_object *, PyObject *, PyObject *);
typedef struct lru_cache_object {
lru_list_elem root; /* includes PyObject_HEAD */
Py_ssize_t maxsize;
PyObject *maxsize_O;
PyObject *func;
lru_cache_ternaryfunc wrapper;
PyObject *cache;
PyObject *cache_info_type;
Py_ssize_t misses, hits;
int typed;
PyObject *dict;
int full;
} lru_cache_object;
static PyTypeObject lru_cache_type;
static PyObject *
lru_cache_make_key(PyObject *args, PyObject *kwds, int typed)
{
PyObject *key, *sorted_items;
Py_ssize_t key_size, pos, key_pos;
/* short path, key will match args anyway, which is a tuple */
if (!typed && !kwds) {
Py_INCREF(args);
return args;
}
if (kwds && PyDict_Size(kwds) > 0) {
sorted_items = PyDict_Items(kwds);
if (!sorted_items)
return NULL;
if (PyList_Sort(sorted_items) < 0) {
Py_DECREF(sorted_items);
return NULL;
}
} else
sorted_items = NULL;
key_size = PyTuple_GET_SIZE(args);
if (sorted_items)
key_size += PyList_GET_SIZE(sorted_items);
if (typed)
key_size *= 2;
if (sorted_items)
key_size++;
key = PyTuple_New(key_size);
if (key == NULL)
goto done;
key_pos = 0;
for (pos = 0; pos < PyTuple_GET_SIZE(args); ++pos) {
PyObject *item = PyTuple_GET_ITEM(args, pos);
Py_INCREF(item);
PyTuple_SET_ITEM(key, key_pos++, item);
}
if (sorted_items) {
Py_INCREF(kwd_mark);
PyTuple_SET_ITEM(key, key_pos++, kwd_mark);
for (pos = 0; pos < PyList_GET_SIZE(sorted_items); ++pos) {
PyObject *item = PyList_GET_ITEM(sorted_items, pos);
Py_INCREF(item);
PyTuple_SET_ITEM(key, key_pos++, item);
}
}
if (typed) {
for (pos = 0; pos < PyTuple_GET_SIZE(args); ++pos) {
PyObject *item = (PyObject *)Py_TYPE(PyTuple_GET_ITEM(args, pos));
Py_INCREF(item);
PyTuple_SET_ITEM(key, key_pos++, item);
}
if (sorted_items) {
for (pos = 0; pos < PyList_GET_SIZE(sorted_items); ++pos) {
PyObject *tp_items = PyList_GET_ITEM(sorted_items, pos);
PyObject *item = (PyObject *)Py_TYPE(PyTuple_GET_ITEM(tp_items, 1));
Py_INCREF(item);
PyTuple_SET_ITEM(key, key_pos++, item);
}
}
}
assert(key_pos == key_size);
done:
if (sorted_items)
Py_DECREF(sorted_items);
return key;
}
static PyObject *
uncached_lru_cache_wrapper(lru_cache_object *self, PyObject *args, PyObject *kwds)
{
PyObject *result = PyObject_Call(self->func, args, kwds);
if (!result)
return NULL;
self->misses++;
return result;
}
static PyObject *
infinite_lru_cache_wrapper(lru_cache_object *self, PyObject *args, PyObject *kwds)
{
PyObject *result;
Py_hash_t hash;
PyObject *key = lru_cache_make_key(args, kwds, self->typed);
if (!key)
return NULL;
hash = PyObject_Hash(key);
if (hash == -1) {
Py_DECREF(key);
return NULL;
}
result = _PyDict_GetItem_KnownHash(self->cache, key, hash);
if (result) {
Py_INCREF(result);
self->hits++;
Py_DECREF(key);
return result;
}
if (PyErr_Occurred()) {
Py_DECREF(key);
return NULL;
}
result = PyObject_Call(self->func, args, kwds);
if (!result) {
Py_DECREF(key);
return NULL;
}
if (_PyDict_SetItem_KnownHash(self->cache, key, result, hash) < 0) {
Py_DECREF(result);
Py_DECREF(key);
return NULL;
}
Py_DECREF(key);
self->misses++;
return result;
}
static void
lru_cache_extricate_link(lru_list_elem *link)
{
link->prev->next = link->next;
link->next->prev = link->prev;
}
static void
lru_cache_append_link(lru_cache_object *self, lru_list_elem *link)
{
lru_list_elem *root = &self->root;
lru_list_elem *last = root->prev;
last->next = root->prev = link;
link->prev = last;
link->next = root;
}
static PyObject *
bounded_lru_cache_wrapper(lru_cache_object *self, PyObject *args, PyObject *kwds)
{
lru_list_elem *link;
PyObject *key, *result;
Py_hash_t hash;
key = lru_cache_make_key(args, kwds, self->typed);
if (!key)
return NULL;
hash = PyObject_Hash(key);
if (hash == -1) {
Py_DECREF(key);
return NULL;
}
link = (lru_list_elem *)_PyDict_GetItem_KnownHash(self->cache, key, hash);
if (link) {
lru_cache_extricate_link(link);
lru_cache_append_link(self, link);
self->hits++;
result = link->result;
Py_INCREF(result);
Py_DECREF(key);
return result;
}
if (PyErr_Occurred()) {
Py_DECREF(key);
return NULL;
}
result = PyObject_Call(self->func, args, kwds);
if (!result) {
Py_DECREF(key);
return NULL;
}
if (self->full && self->root.next != &self->root) {
/* Use the oldest item to store the new key and result. */
PyObject *oldkey, *oldresult, *popresult;
/* Extricate the oldest item. */
link = self->root.next;
lru_cache_extricate_link(link);
/* Remove it from the cache.
The cache dict holds one reference to the link,
and the linked list holds yet one reference to it. */
popresult = _PyDict_Pop_KnownHash((PyDictObject *)self->cache,
link->key, link->hash,
Py_None);
if (popresult == Py_None) {
/* Getting here means that this same key was added to the
cache while the lock was released. Since the link
update is already done, we need only return the
computed result and update the count of misses. */
Py_DECREF(popresult);
Py_DECREF(link);
Py_DECREF(key);
}
else if (popresult == NULL) {
lru_cache_append_link(self, link);
Py_DECREF(key);
Py_DECREF(result);
return NULL;
}
else {
Py_DECREF(popresult);
/* Keep a reference to the old key and old result to
prevent their ref counts from going to zero during the
update. That will prevent potentially arbitrary object
clean-up code (i.e. __del__) from running while we're
still adjusting the links. */
oldkey = link->key;
oldresult = link->result;
link->hash = hash;
link->key = key;
link->result = result;
if (_PyDict_SetItem_KnownHash(self->cache, key, (PyObject *)link,
hash) < 0) {
Py_DECREF(link);
Py_DECREF(oldkey);
Py_DECREF(oldresult);
return NULL;
}
lru_cache_append_link(self, link);
Py_INCREF(result); /* for return */
Py_DECREF(oldkey);
Py_DECREF(oldresult);
}
} else {
/* Put result in a new link at the front of the queue. */
link = (lru_list_elem *)PyObject_GC_New(lru_list_elem,
&lru_list_elem_type);
if (link == NULL) {
Py_DECREF(key);
Py_DECREF(result);
return NULL;
}
link->hash = hash;
link->key = key;
link->result = result;
_PyObject_GC_TRACK(link);
if (_PyDict_SetItem_KnownHash(self->cache, key, (PyObject *)link,
hash) < 0) {
Py_DECREF(link);
return NULL;
}
lru_cache_append_link(self, link);
Py_INCREF(result); /* for return */
self->full = (PyDict_Size(self->cache) >= self->maxsize);
}
self->misses++;
return result;
}
static PyObject *
lru_cache_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
PyObject *func, *maxsize_O, *cache_info_type, *cachedict;
int typed;
lru_cache_object *obj;
Py_ssize_t maxsize;
PyObject *(*wrapper)(lru_cache_object *, PyObject *, PyObject *);
static char *keywords[] = {"user_function", "maxsize", "typed",
"cache_info_type", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kw, "OOpO:lru_cache", keywords,
&func, &maxsize_O, &typed,
&cache_info_type)) {
return NULL;
}
if (!PyCallable_Check(func)) {
PyErr_SetString(PyExc_TypeError,
"the first argument must be callable");
return NULL;
}
/* select the caching function, and make/inc maxsize_O */
if (maxsize_O == Py_None) {
wrapper = infinite_lru_cache_wrapper;
/* use this only to initialize lru_cache_object attribute maxsize */
maxsize = -1;
} else if (PyIndex_Check(maxsize_O)) {
maxsize = PyNumber_AsSsize_t(maxsize_O, PyExc_OverflowError);
if (maxsize == -1 && PyErr_Occurred())
return NULL;
if (maxsize == 0)
wrapper = uncached_lru_cache_wrapper;
else
wrapper = bounded_lru_cache_wrapper;
} else {
PyErr_SetString(PyExc_TypeError, "maxsize should be integer or None");
return NULL;
}
if (!(cachedict = PyDict_New()))
return NULL;
obj = (lru_cache_object *)type->tp_alloc(type, 0);
if (obj == NULL) {
Py_DECREF(cachedict);
return NULL;
}
obj->cache = cachedict;
obj->root.prev = &obj->root;
obj->root.next = &obj->root;
obj->maxsize = maxsize;
Py_INCREF(maxsize_O);
obj->maxsize_O = maxsize_O;
Py_INCREF(func);
obj->func = func;
obj->wrapper = wrapper;
obj->misses = obj->hits = 0;
obj->typed = typed;
Py_INCREF(cache_info_type);
obj->cache_info_type = cache_info_type;
return (PyObject *)obj;
}
static lru_list_elem *
lru_cache_unlink_list(lru_cache_object *self)
{
lru_list_elem *root = &self->root;
lru_list_elem *link = root->next;
if (link == root)
return NULL;
root->prev->next = NULL;
root->next = root->prev = root;
return link;
}
static void
lru_cache_clear_list(lru_list_elem *link)
{
while (link != NULL) {
lru_list_elem *next = link->next;
Py_DECREF(link);
link = next;
}
}
static void
lru_cache_dealloc(lru_cache_object *obj)
{
lru_list_elem *list;
/* bpo-31095: UnTrack is needed before calling any callbacks */
PyObject_GC_UnTrack(obj);
list = lru_cache_unlink_list(obj);
Py_XDECREF(obj->maxsize_O);
Py_XDECREF(obj->func);
Py_XDECREF(obj->cache);
Py_XDECREF(obj->dict);
Py_XDECREF(obj->cache_info_type);
lru_cache_clear_list(list);
Py_TYPE(obj)->tp_free(obj);
}
static PyObject *
lru_cache_call(lru_cache_object *self, PyObject *args, PyObject *kwds)
{
return self->wrapper(self, args, kwds);
}
static PyObject *
lru_cache_descr_get(PyObject *self, PyObject *obj, PyObject *type)
{
if (obj == Py_None || obj == NULL) {
Py_INCREF(self);
return self;
}
return PyMethod_New(self, obj);
}
static PyObject *
lru_cache_cache_info(lru_cache_object *self, PyObject *unused)
{
return PyObject_CallFunction(self->cache_info_type, "nnOn",
self->hits, self->misses, self->maxsize_O,
PyDict_Size(self->cache));
}
static PyObject *
lru_cache_cache_clear(lru_cache_object *self, PyObject *unused)
{
lru_list_elem *list = lru_cache_unlink_list(self);
self->hits = self->misses = 0;
self->full = 0;
PyDict_Clear(self->cache);
lru_cache_clear_list(list);
Py_RETURN_NONE;
}
static PyObject *
lru_cache_reduce(PyObject *self, PyObject *unused)
{
return PyObject_GetAttrString(self, "__qualname__");
}
static PyObject *
lru_cache_copy(PyObject *self, PyObject *unused)
{
Py_INCREF(self);
return self;
}
static PyObject *
lru_cache_deepcopy(PyObject *self, PyObject *unused)
{
Py_INCREF(self);
return self;
}
static int
lru_cache_tp_traverse(lru_cache_object *self, visitproc visit, void *arg)
{
lru_list_elem *link = self->root.next;
while (link != &self->root) {
lru_list_elem *next = link->next;
Py_VISIT(link);
link = next;
}
Py_VISIT(self->maxsize_O);
Py_VISIT(self->func);
Py_VISIT(self->cache);
Py_VISIT(self->cache_info_type);
Py_VISIT(self->dict);
return 0;
}
static int
lru_cache_tp_clear(lru_cache_object *self)
{
lru_list_elem *list = lru_cache_unlink_list(self);
Py_CLEAR(self->maxsize_O);
Py_CLEAR(self->func);
Py_CLEAR(self->cache);
Py_CLEAR(self->cache_info_type);
Py_CLEAR(self->dict);
lru_cache_clear_list(list);
return 0;
}
PyDoc_STRVAR(lru_cache_doc,
"Create a cached callable that wraps another function.\n\
\n\
user_function: the function being cached\n\
\n\
maxsize: 0 for no caching\n\
None for unlimited cache size\n\
n for a bounded cache\n\
\n\
typed: False cache f(3) and f(3.0) as identical calls\n\
True cache f(3) and f(3.0) as distinct calls\n\
\n\
cache_info_type: namedtuple class with the fields:\n\
hits misses currsize maxsize\n"
);
static PyMethodDef lru_cache_methods[] = {
{"cache_info", (PyCFunction)lru_cache_cache_info, METH_NOARGS},
{"cache_clear", (PyCFunction)lru_cache_cache_clear, METH_NOARGS},
{"__reduce__", (PyCFunction)lru_cache_reduce, METH_NOARGS},
{"__copy__", (PyCFunction)lru_cache_copy, METH_VARARGS},
{"__deepcopy__", (PyCFunction)lru_cache_deepcopy, METH_VARARGS},
{NULL}
};
static PyGetSetDef lru_cache_getsetlist[] = {
{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict},
{NULL}
};
static PyTypeObject lru_cache_type = {
PyVarObject_HEAD_INIT(NULL, 0)
"functools._lru_cache_wrapper", /* tp_name */
sizeof(lru_cache_object), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
(destructor)lru_cache_dealloc, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_reserved */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
(ternaryfunc)lru_cache_call, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC,
/* tp_flags */
lru_cache_doc, /* tp_doc */
(traverseproc)lru_cache_tp_traverse,/* tp_traverse */
(inquiry)lru_cache_tp_clear, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
lru_cache_methods, /* tp_methods */
0, /* tp_members */
lru_cache_getsetlist, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
lru_cache_descr_get, /* tp_descr_get */
0, /* tp_descr_set */
offsetof(lru_cache_object, dict), /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
lru_cache_new, /* tp_new */
};
/* module level code ********************************************************/
PyDoc_STRVAR(module_doc,
"Tools that operate on functions.");
static PyMethodDef module_methods[] = {
{"reduce", functools_reduce, METH_VARARGS, functools_reduce_doc},
{"cmp_to_key", (PyCFunction)functools_cmp_to_key,
METH_VARARGS | METH_KEYWORDS, functools_cmp_to_key_doc},
{NULL, NULL} /* sentinel */
};
static void
module_free(void *m)
{
Py_CLEAR(kwd_mark);
}
static struct PyModuleDef _functoolsmodule = {
PyModuleDef_HEAD_INIT,
"_functools",
module_doc,
-1,
module_methods,
NULL,
NULL,
NULL,
module_free,
};
PyMODINIT_FUNC
PyInit__functools(void)
{
int i;
PyObject *m;
char *name;
PyTypeObject *typelist[] = {
&partial_type,
&lru_cache_type,
NULL
};
m = PyModule_Create(&_functoolsmodule);
if (m == NULL)
return NULL;
kwd_mark = PyObject_CallObject((PyObject *)&PyBaseObject_Type, NULL);
if (!kwd_mark) {
Py_DECREF(m);
return NULL;
}
for (i=0 ; typelist[i] != NULL ; i++) {
if (PyType_Ready(typelist[i]) < 0) {
Py_DECREF(m);
return NULL;
}
name = strchr(typelist[i]->tp_name, '.');
assert (name != NULL);
Py_INCREF(typelist[i]);
PyModule_AddObject(m, name+1, (PyObject *)typelist[i]);
}
return m;
}
| 29.770313 | 94 | 0.537999 | [
"object"
] |
d27f1df5b641961c8defb2d7303d942fa43708ff | 1,341 | h | C | VCS PC/PostEffects.h | gta191977649/VCSPC | eafa91e0088fa784b777a8a3f8af0c220a95a396 | [
"MIT"
] | 66 | 2020-04-07T18:48:44.000Z | 2022-03-20T19:20:35.000Z | VCS PC/PostEffects.h | gta191977649/VCSPC | eafa91e0088fa784b777a8a3f8af0c220a95a396 | [
"MIT"
] | 1 | 2021-01-21T20:31:11.000Z | 2021-01-21T20:31:11.000Z | VCS PC/PostEffects.h | GTAmodding/VCSPC | eafa91e0088fa784b777a8a3f8af0c220a95a396 | [
"MIT"
] | 12 | 2020-04-25T07:40:35.000Z | 2021-12-05T09:21:55.000Z | #ifndef __POSTEFFECTS
#define __POSTEFFECTS
#include <d3d9.h>
class CPostEffects
{
private:
static void Radiosity(int limit, int intensity);
static void BlurOverlay(float intensity, float offset, RwRGBA color);
static void Blur_Init(void);
static void Blur_Close(void);
public:
static void DoScreenModeDependentInitializations();
static void Radiosity_Init(void);
static void Radiosity_Close(void);
static void Render();
static void Initialise();
static void Update();
static void Close();
static inline void SetTrailsState(bool bEnable)
{ m_bTrailsEnabled = bEnable; }
static inline void SwitchTrailsOnOff()
{ m_bTrailsEnabled = m_bTrailsEnabled == false; }
static inline bool TrailsEnabled()
{ return m_bTrailsEnabled; }
static bool m_bTrailsEnabled;
private:
static RwRaster* ms_pRadiosityRaster1;
static RwRaster* ms_pRadiosityRaster2;
static RwD3D9Vertex ms_radiosityVerts[44];
static RwImVertexIndex ms_radiosityIndices[7*6];
static RwRaster* ms_pCurrentFb;
static RwRaster* ms_pBlurBuffer;
static RwD3D9Vertex ms_blurVerts[24];
static RwImVertexIndex ms_blurIndices[3*6];
static bool ms_bJustInitialised;
static void ImmediateModeRenderStatesStore(void);
static void ImmediateModeRenderStatesSet(void);
static void ImmediateModeRenderStatesReStore(void);
};
#endif | 25.788462 | 72 | 0.781506 | [
"render"
] |
d27f7b1dc304b1986de80a5ad4f7e56b6bfe2507 | 1,385 | c | C | d/avatars/myrkul/soulbottle.c | gesslar/shadowgate | 97ce5d33a2275bb75c0cf6556602564b7870bc77 | [
"MIT"
] | 13 | 2019-07-19T05:24:44.000Z | 2021-11-18T04:08:19.000Z | d/avatars/myrkul/soulbottle.c | gesslar/shadowgate | 97ce5d33a2275bb75c0cf6556602564b7870bc77 | [
"MIT"
] | null | null | null | d/avatars/myrkul/soulbottle.c | gesslar/shadowgate | 97ce5d33a2275bb75c0cf6556602564b7870bc77 | [
"MIT"
] | 13 | 2019-09-12T06:22:38.000Z | 2022-01-31T01:15:12.000Z | #include <std.h>
inherit OBJECT;
void create(){
::create();
set_name("soulbottle");
set_id(({ "bottle", "soul bottle", "soulbottle" }));
set_short("%^BOLD%^%^CYAN%^s%^RED%^o%^CYAN%^ul%^BLUE%^b%^CYAN%^ott%^RESET%^%^MAGENTA%^l%^BOLD%^%^CYAN%^e%^RESET%^");
set_obvious_short("%^RESET%^%^MAGENTA%^sinister %^ORANGE%^bottle%^RESET%^");
set_long("%^RESET%^%^ORANGE%^This wine bottle has a slightly %^BOLD%^%^GREEN%^greenish tint%^RESET%^%^ORANGE%^ and looks fairly normal. It has no label on it, and has a kind of cork stopper. Nevertheless, you f"
"eel a sensation of %^MAGENTA%^sinister intent%^ORANGE%^ emanating from the bottle. You feel if you removed the stopper, something %^BOLD%^%^RED%^terrible would happen.%^RESET%^
"
);
set_value(0);
set_weight(0);
set_lore("%^BOLD%^%^CYAN%^These bottles are ancient tools of %^BLACK%^necromancers%^CYAN%^ used to trap %^WHITE%^souls%^CYAN%^. The %^RESET%^%^MAGENTA%^mystical design%^BOLD%^%^CYAN%^ of such bottles closely re"
"sembles the famous tools that summoners used to trap %^BLUE%^elementals and djinn%^CYAN%^. However, these bottles are not used for protection, but rather as ultimate %^BLACK%^weapons%^CYAN%^. It canno"
"t be used against a foe who can resist. But against the unconscious or bound enemies, they can be used to trap souls for %^RED%^evil purposes.%^RESET%^
"
);
set_property("lore difficulty",15);
}
| 60.217391 | 212 | 0.696029 | [
"object"
] |
d2801b21ba34b4d204bd4d42e978205034acb7e4 | 3,895 | h | C | google/cloud/testing_util/testing_types.h | tritone/google-cloud-cpp | fac45971f70205dfeebe88c472c2da1ed4eb8ce5 | [
"Apache-2.0"
] | 3 | 2020-05-27T23:21:23.000Z | 2020-05-31T22:31:53.000Z | google/cloud/testing_util/testing_types.h | cjrolo/google-cloud-cpp | bf7a432146952c5f3e8f29b84f5bf85eff69d327 | [
"Apache-2.0"
] | 2 | 2020-05-31T22:26:57.000Z | 2020-06-19T00:14:10.000Z | google/cloud/testing_util/testing_types.h | cjrolo/google-cloud-cpp | bf7a432146952c5f3e8f29b84f5bf85eff69d327 | [
"Apache-2.0"
] | null | null | null | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_TESTING_UTIL_TESTING_TYPES_H
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_TESTING_UTIL_TESTING_TYPES_H
/**
* @file
*
* Implement types useful to test the behavior of template classes.
*
* Just like a function should be tested with different inputs, template classes
* should be tested with types that have different characteristics. For example,
* it is often interesting to test a template with a type that lacks a default
* constructor. This file implements some types that we have found useful for
* testing template classes.
*/
#include "google/cloud/log.h"
#include <utility>
#include <vector>
namespace google {
namespace cloud {
inline namespace GOOGLE_CLOUD_CPP_NS {
namespace testing_util {
/// A class without a default constructor.
class NoDefaultConstructor {
public:
NoDefaultConstructor() = delete;
explicit NoDefaultConstructor(std::string x) : str_(std::move(x)) {}
std::string str() const { return str_; }
private:
friend bool operator==(NoDefaultConstructor const& lhs,
NoDefaultConstructor const& rhs);
std::string str_;
};
inline bool operator==(NoDefaultConstructor const& lhs,
NoDefaultConstructor const& rhs) {
return lhs.str_ == rhs.str_;
}
inline bool operator!=(NoDefaultConstructor const& lhs,
NoDefaultConstructor const& rhs) {
return std::rel_ops::operator!=(lhs, rhs);
}
/**
* A class that counts calls to its constructors.
*/
class Observable {
public:
static int default_constructor() { return default_constructor_; }
static int value_constructor() { return value_constructor_; }
static int copy_constructor() { return copy_constructor_; }
static int move_constructor() { return move_constructor_; }
static int copy_assignment() { return copy_assignment_; }
static int move_assignment() { return move_assignment_; }
static int destructor() { return destructor_; }
static void reset_counters() {
default_constructor_ = 0;
value_constructor_ = 0;
copy_constructor_ = 0;
move_constructor_ = 0;
copy_assignment_ = 0;
move_assignment_ = 0;
destructor_ = 0;
}
Observable() { ++default_constructor_; }
explicit Observable(std::string s) : str_(std::move(s)) {
++value_constructor_;
}
Observable(Observable const& rhs) : str_(rhs.str_) { ++copy_constructor_; }
Observable(Observable&& rhs) noexcept : str_(std::move(rhs.str_)) {
rhs.str_ = "moved-out";
++move_constructor_;
}
Observable& operator=(Observable const& rhs) {
str_ = rhs.str_;
++copy_assignment_;
return *this;
}
Observable& operator=(Observable&& rhs) noexcept {
str_ = std::move(rhs.str_);
rhs.str_ = "moved-out";
++move_assignment_;
return *this;
}
~Observable() { ++destructor_; }
std::string const& str() const { return str_; }
private:
static int default_constructor_;
static int value_constructor_;
static int copy_constructor_;
static int move_constructor_;
static int copy_assignment_;
static int move_assignment_;
static int destructor_;
std::string str_;
};
} // namespace testing_util
} // namespace GOOGLE_CLOUD_CPP_NS
} // namespace cloud
} // namespace google
#endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_TESTING_UTIL_TESTING_TYPES_H
| 30.193798 | 80 | 0.721694 | [
"vector"
] |
d282d7b0f82b311b3f149307fcb01be3037b35e8 | 1,395 | h | C | Classes/Photos/Media/GDataNormalPlayTime.h | brewpoo/WebAlbums | 468d609df7b1c199b789b6ee2db04154c39c33ee | [
"Apache-2.0"
] | 1 | 2021-08-30T10:33:21.000Z | 2021-08-30T10:33:21.000Z | Classes/Photos/Media/GDataNormalPlayTime.h | brewpoo/WebAlbums | 468d609df7b1c199b789b6ee2db04154c39c33ee | [
"Apache-2.0"
] | null | null | null | Classes/Photos/Media/GDataNormalPlayTime.h | brewpoo/WebAlbums | 468d609df7b1c199b789b6ee2db04154c39c33ee | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#import <Foundation/Foundation.h>
#import "GDataDefines.h"
// Time specification object which tries to conform to section 3.6
// of RFC 2326 (Normal Play Time). http://www.ietf.org/rfc/rfc2326.txt
//
// It does not support ranges.
//
// It only supports a millisecond precision. Any time more precise than
// that will be lost when parsing.
@interface GDataNormalPlayTime : NSObject {
long long ms_;
BOOL isNow_;
}
+ (GDataNormalPlayTime *)normalPlayTimeWithString:(NSString *)str;
- (long long)timeOffsetInMilliseconds; // -1 if "now"
- (void)setTimeOffsetInMilliseconds:(long long)ms;
- (BOOL)isNow;
- (void)setIsNow:(BOOL)isNow;
- (NSString *)HHMMSSString; // hh:mm:ss.fraction or "now"
- (NSString *)secondsString; // seconds.fraction or "now"
- (void)setFromString:(NSString *)str;
@end
| 30.326087 | 74 | 0.733333 | [
"object"
] |
d29706df077a2b43963e6bc30e16486f16d45ce0 | 512 | h | C | include/SchematLib/TrajectorySchematization/TrajectoryBundleTraits.h | tue-alga/CoordinatedSchematization | 9ffc292c946498d56f7938a86628adba534a9085 | [
"Apache-2.0"
] | null | null | null | include/SchematLib/TrajectorySchematization/TrajectoryBundleTraits.h | tue-alga/CoordinatedSchematization | 9ffc292c946498d56f7938a86628adba534a9085 | [
"Apache-2.0"
] | null | null | null | include/SchematLib/TrajectorySchematization/TrajectoryBundleTraits.h | tue-alga/CoordinatedSchematization | 9ffc292c946498d56f7938a86628adba534a9085 | [
"Apache-2.0"
] | null | null | null | #ifndef SCHEMATLIB_TRAJECTORYSCHEMATIZATION_TRAJECTORYBUNDLETRAITS_H
#define SCHEMATLIB_TRAJECTORYSCHEMATIZATION_TRAJECTORYBUNDLETRAITS_H
#include <vector>
namespace SchematLib::TrajectorySchematization
{
struct TrajectoryBundle
{
std::vector<std::size_t> edges;
std::size_t matchedTrajectoriesCount = 0;
std::size_t supportClass = 0;
long double bundleLength = 0;
};
struct TrajectoryBundleTraits
{
using Bundle = TrajectoryBundle;
};
}
#endif
| 23.272727 | 68 | 0.726563 | [
"vector"
] |
d299c05bfecc228f0b8f130dba3f992986694bfc | 12,966 | c | C | render.c | MinorLegato/OTU | b4b7709b69d9d2e282f3fb99404a7fb50e6cbf1f | [
"MIT"
] | null | null | null | render.c | MinorLegato/OTU | b4b7709b69d9d2e282f3fb99404a7fb50e6cbf1f | [
"MIT"
] | null | null | null | render.c | MinorLegato/OTU | b4b7709b69d9d2e282f3fb99404a7fb50e6cbf1f | [
"MIT"
] | null | null | null |
static model_t model_table[MODEL_COUNT];
static void model_add_vertex(model_t* model, vertex_t vertex, f32 scale_divisor) {
vertex.pos.x /= scale_divisor;
vertex.pos.y /= scale_divisor;
model->array[model->count++] = vertex;
}
static color_t color_mul(color_t a, color_t b) {
vec4_t va = { a.r / 255.0, a.g / 255.0, a.b / 255.0, a.a / 255.0f };
vec4_t vb = { b.r / 255.0, b.g / 255.0, b.b / 255.0, b.a / 255.0f };
vec4_t vc = v4_mul(va, vb);
return color(255 * vc.r, 255 * vc.g, 255 * vc.b, 255 * vc.a);
}
static void render_model(model_type_t type, vec2_t pos, f32 scale, f32 rot, color_t color) {
model_t* model = &model_table[type];
mat2_t rot_mat = m2_rotate(rot);
for (u32 i = 0; i < model->count; ++i) {
vertex_t vertex = model->array[i];
vec2_t v = m2_mulv(rot_mat, vertex.pos);
color_t c = color_mul(vertex.color, color);
glColor4ub(c.r, c.g, c.b, color.a);
glVertex3f(pos.x + scale * v.x, pos.y + scale * v.y, 0);
}
}
static void init_models(void) {
{
model_t* model = &model_table[MODEL_SQUARE];
model_add_vertex(model, vertex(v2(-1, -1), color(255, 255, 255, 255)), 1);
model_add_vertex(model, vertex(v2(+1, -1), color(255, 255, 255, 255)), 1);
model_add_vertex(model, vertex(v2(+1, +1), color(255, 255, 255, 255)), 1);
model_add_vertex(model, vertex(v2(+1, +1), color(255, 255, 255, 255)), 1);
model_add_vertex(model, vertex(v2(-1, +1), color(255, 255, 255, 255)), 1);
model_add_vertex(model, vertex(v2(-1, -1), color(255, 255, 255, 255)), 1);
}
{
model_t* model = &model_table[MODEL_SHIP];
model_add_vertex(model, vertex(v2(-2, -3), color(155, 185, 155, 255)), 4);
model_add_vertex(model, vertex(v2(+2, -3), color(155, 185, 155, 255)), 4);
model_add_vertex(model, vertex(v2(+2, +1), color(155, 185, 155, 255)), 4);
model_add_vertex(model, vertex(v2(+2, +1), color(155, 185, 155, 255)), 4);
model_add_vertex(model, vertex(v2(-2, +1), color(155, 185, 155, 255)), 4);
model_add_vertex(model, vertex(v2(-2, -3), color(155, 185, 155, 255)), 4);
model_add_vertex(model, vertex(v2(-2, +5), color(255, 255, 255, 255)), 4);
model_add_vertex(model, vertex(v2(-2, -4), color(255, 255, 255, 255)), 4);
model_add_vertex(model, vertex(v2(-5, -5), color(255, 255, 255, 255)), 4);
model_add_vertex(model, vertex(v2(+2, +5), color(255, 255, 255, 255)), 4);
model_add_vertex(model, vertex(v2(+2, -4), color(255, 255, 255, 255)), 4);
model_add_vertex(model, vertex(v2(+5, -5), color(255, 255, 255, 255)), 4);
}
{
model_t* model = &model_table[MODEL_CREEP];
model_add_vertex(model, vertex(v2(-0, +4), color(255, 255, 255, 255)), 4);
model_add_vertex(model, vertex(v2(-0, -4), color(255, 255, 255, 255)), 4);
model_add_vertex(model, vertex(v2(-4, +0), color(255, 255, 255, 255)), 4);
model_add_vertex(model, vertex(v2(+0, +4), color(255, 255, 255, 255)), 4);
model_add_vertex(model, vertex(v2(+0, -4), color(255, 255, 255, 255)), 4);
model_add_vertex(model, vertex(v2(+4, +0), color(255, 255, 255, 255)), 4);
model_add_vertex(model, vertex(v2(+4, +4), color(255, 255, 255, 255)), 4);
model_add_vertex(model, vertex(v2(+3, +1), color(255, 255, 255, 255)), 4);
model_add_vertex(model, vertex(v2(+1, +3), color(255, 255, 255, 255)), 4);
model_add_vertex(model, vertex(v2(-4, -4), color(255, 255, 255, 255)), 4);
model_add_vertex(model, vertex(v2(-3, -1), color(255, 255, 255, 255)), 4);
model_add_vertex(model, vertex(v2(-1, -3), color(255, 255, 255, 255)), 4);
model_add_vertex(model, vertex(v2(-4, +4), color(255, 255, 255, 255)), 4);
model_add_vertex(model, vertex(v2(-3, +1), color(255, 255, 255, 255)), 4);
model_add_vertex(model, vertex(v2(-1, +3), color(255, 255, 255, 255)), 4);
model_add_vertex(model, vertex(v2(+4, -4), color(255, 255, 255, 255)), 4);
model_add_vertex(model, vertex(v2(+3, -1), color(255, 255, 255, 255)), 4);
model_add_vertex(model, vertex(v2(+1, -3), color(255, 255, 255, 255)), 4);
}
{
model_t* model = &model_table[MODEL_PROJECTILE];
model_add_vertex(model, vertex(v2(+0, +3), color(255, 255, 255, 255)), 2);
model_add_vertex(model, vertex(v2(+2, +0), color(255, 255, 255, 255)), 2);
model_add_vertex(model, vertex(v2(-2, +0), color(255, 255, 255, 255)), 2);
model_add_vertex(model, vertex(v2(+0, -3), color(255, 255, 255, 255)), 2);
model_add_vertex(model, vertex(v2(-2, +0), color(255, 255, 255, 255)), 2);
model_add_vertex(model, vertex(v2(+2, +0), color(255, 255, 255, 255)), 2);
}
}
static void render_center_rect(vec3_t pos, vec2_t rad, color_t color) {
glColor4ub(color.r, color.g, color.b, color.a);
glVertex3f(pos.x - rad.x, pos.y - rad.y, pos.z);
glVertex3f(pos.x + rad.x, pos.y - rad.y, pos.z);
glVertex3f(pos.x + rad.x, pos.y + rad.y, pos.z);
glVertex3f(pos.x - rad.x, pos.y + rad.y, pos.z);
}
static void render_init(void) {
init_models();
}
static void render_entities(game_state_t* gs) {
entity_t* player = get_player(gs);
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glBegin(GL_TRIANGLES);
for (u32 i = 0; i < gs->entity_count; ++i) {
entity_t* e = &gs->entity_array[i];
entity_info_t* info = ent_info(e);
color_t color = color_lerp(color(10, 10, 10, 255), color(10, 255, 255, 255), e->shield);
render_model(info->model, e->pos, info->rad, e->rot, color);
}
if (gs->item && player) {
entity_info_t* item_info = &entity_info_table[gs->item];
render_model(item_info->model, player->pos, item_info->rad, player->rot, item_info->color);
}
glEnd();
}
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glBegin(GL_TRIANGLES);
for (u32 i = 0; i < gs->entity_count; ++i) {
entity_t* e = &gs->entity_array[i];
entity_info_t* info = ent_info(e);
color_t color = e->on_map? info->color : color(80, 80, 80, 255);
render_model(info->model, e->pos, info->rad, e->rot, color);
}
if (gs->item && player) {
entity_info_t* item_info = &entity_info_table[gs->item];
render_model(item_info->model, player->pos, item_info->rad, player->rot, item_info->color);
}
glEnd();
}
}
static void render_particles(game_state_t* gs) {
rect2_t map_rect = { .min = { 0, 0 }, .max = { MAP_SIZE_X, MAP_SIZE_Y } };
glBegin(GL_TRIANGLES);
for (u32 i = 0; i < gs->particle_count; ++i) {
particle_t* p = &gs->particle_array[i];
color_t color = color_lerp(p->end_color, p->start_color, p->life / p->life_max);
if (!rect2_contains(map_rect, p->pos)) {
color.r = 80;
color.g = 80;
color.b = 80;
}
render_model(p->model, p->pos, p->rad, p->rot, color);
}
glEnd();
}
static void render_texts(game_state_t* gs) {
rect2_t map_rect = { .min = { 0, 0 }, .max = { MAP_SIZE_X, MAP_SIZE_Y } };
for (u32 i = 0; i < gs->text_count; ++i) {
text_t* t = &gs->text_array[i];
color_t color = color_lerp(t->end_color, t->start_color, t->life / t->life_max);
if (!rect2_contains(map_rect, t->pos)) {
color.r = 80;
color.g = 80;
color.b = 80;
}
gl_render_string(t->str.buf, t->pos.x, t->pos.y, 0, 0.3, -0.3, pack_color_u8(color.r, color.g, color.b, color.a));
}
}
static void render_map(game_state_t* gs) {
{
glColor4f(0.2, 0.6, 0.4, 1);
glBegin(GL_LINES);
glVertex3f(0 * MAP_SIZE_X, 0 * MAP_SIZE_Y, 0);
glVertex3f(1 * MAP_SIZE_X, 0 * MAP_SIZE_Y, 0);
glVertex3f(0 * MAP_SIZE_X, 1 * MAP_SIZE_Y, 0);
glVertex3f(1 * MAP_SIZE_X, 1 * MAP_SIZE_Y, 0);
glVertex3f(0 * MAP_SIZE_X, 0 * MAP_SIZE_Y, 0);
glVertex3f(0 * MAP_SIZE_X, 1 * MAP_SIZE_Y, 0);
glVertex3f(1 * MAP_SIZE_X, 0 * MAP_SIZE_Y, 0);
glVertex3f(1 * MAP_SIZE_X, 1 * MAP_SIZE_Y, 0);
glEnd();
}
{
glColor4f(0.4, 0.4, 0.4, 0.1);
glBegin(GL_LINES);
for (u32 y = 0; y < MAP_SIZE_Y - 1; ++y) {
for (u32 x = 0; x < MAP_SIZE_X - 1; ++x) {
tile_t* ta = &gs->map.tiles[y][x];
tile_t* tb = &gs->map.tiles[y + 1][x];
tile_t* tc = &gs->map.tiles[y][x + 1];
vec2_t a = v2(x + ta->offset.x + 0.5, y + ta->offset.y + 0.5);
vec2_t b = v2(x + tb->offset.x + 0.5, y + tb->offset.y + 0.5 + 1);
vec2_t c = v2(x + tc->offset.x + 0.5 + 1, y + tc->offset.y + 0.5);
glVertex3f(a.x, a.y, 0);
glVertex3f(b.x, b.y, 0);
glVertex3f(a.x, a.y, 0);
glVertex3f(c.x, c.y, 0);
}
}
glEnd();
}
}
static void render_crosshair(vec2_t pos) {
f32 scale = 1;
glBegin(GL_QUADS);
render_center_rect(v3(pos.x - 0.8 * scale, pos.y, 0), v2(0.25 * scale, 0.08 * scale), color(200, 200, 200, 255));
render_center_rect(v3(pos.x + 0.8 * scale, pos.y, 0), v2(0.25 * scale, 0.08 * scale), color(200, 200, 200, 255));
render_center_rect(v3(pos.x, pos.y - 0.8 * scale, 0), v2(0.08 * scale, 0.25 * scale), color(200, 200, 200, 255));
render_center_rect(v3(pos.x, pos.y + 0.8 * scale, 0), v2(0.08 * scale, 0.25 * scale), color(200, 200, 200, 255));
glEnd();
}
static void render_curser(vec2_t pos) {
f32 scale = 1;
glBegin(GL_TRIANGLES);
glColor4ub(200, 200, 200, 255);
glVertex3f(pos.x, pos.y, 0);
glVertex3f(pos.x - 4, pos.y + 18, 0);
glVertex3f(pos.x + 8, pos.y + 16, 0);
glEnd();
}
static void use_camera(camera_t* cam) {
glMatrixMode(GL_PROJECTION);
glLoadMatrixf(m4_perspective(0.5 * PI, platform.aspect_ratio, 0.1, cam->pos.z + 4).e);
glMatrixMode(GL_MODELVIEW);
glLoadMatrixf(m4_look_at(cam->pos, v3(.xy = cam->pos.xy), v3(0, 1, 0)).e);
}
static void render_pause_screen(void) {
glBegin(GL_QUADS);
glColor4f(0, 0, 0, 0.4);
glVertex3f(0, 0, 0);
glVertex3f(platform.width, 0, 0);
glVertex3f(platform.width, platform.height, 0);
glVertex3f(0, platform.height, 0);
glEnd();
gl_render_string_format(platform.width / 2 - 158, 128, 0, 64, 64, 0xffffffff, "PAUSED");
{
const char* instructions[] = {
"move : W, A, S, D",
"aim : mouse | arrow keys | I, J, K, L",
"shoot : left mouse button",
"dodge : space",
"toggle fullscreen : F1"
};
for (u32 i = 0; i < ARRAY_COUNT(instructions); ++i) {
gl_render_string_format(32, 412 + i * 20, 0, 12, 16, 0xffffffff, instructions[i]);
}
}
gl_render_string_format(32, platform.height - 64, 0, 24, 24, 0xffffffff, "Q: quit");
}
static void render_game(game_state_t* gs, f32 dt) {
glClearColor(0.0, 0.1, 0.1, 1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
use_camera(&gs->cam);
mouse_position = gl_get_world_position(platform.mouse.pos.x, platform.mouse.pos.y);
glLineWidth(3);
render_particles(gs);
render_map(gs);
render_entities(gs);
render_texts(gs);
if (mouse_enabled) {
render_crosshair(mouse_position.xy);
}
// ui stuff
{
glMatrixMode(GL_PROJECTION);
glLoadMatrixf(m4_ortho(0, platform.width, platform.height, 0, -1, 1).e);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
{
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glBegin(GL_TRIANGLES);
for (i32 i = 0; i < gs->lives; ++i) {
render_model(MODEL_SHIP, v2(156 + 48 * i, 32), 16, PI, color(0, 0, 0, 255));
}
glEnd();
}
{
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
glBegin(GL_TRIANGLES);
for (i32 i = 0; i < gs->lives; ++i) {
render_model(MODEL_SHIP, v2(156 + 48 * i, 32), 16, PI, color(200, 250, 250, 255));
}
glEnd();
}
gl_render_string_format(300, 18, 0, 28, 28, 0xffffffff, "SCORE: %d", gs->score);
if (!get_player(gs)) {
gl_render_string_format(platform.width / 2 - 256 - 2, platform.height / 2 - 2, 0, 24, 24, 0xccccccc1, "press 'R' to restart!");
gl_render_string_format(platform.width / 2 - 256, platform.height / 2, 0, 24, 24, 0xff2222c1, "press 'R' to restart!");
}
if (gs->pause) {
render_pause_screen();
}
}
}
| 34.121053 | 139 | 0.558769 | [
"model"
] |
d2a50cdc573b5525b25d1d6f2889c199e36dce78 | 4,970 | h | C | codec/encoder/core/inc/wels_common_basis.h | BelledonneCommunications/openh264 | 70156cac67b1d4c829e6c479cb26df7e45a1bf12 | [
"BSD-2-Clause"
] | 1 | 2017-05-23T13:17:12.000Z | 2017-05-23T13:17:12.000Z | codec/encoder/core/inc/wels_common_basis.h | BelledonneCommunications/openh264 | 70156cac67b1d4c829e6c479cb26df7e45a1bf12 | [
"BSD-2-Clause"
] | null | null | null | codec/encoder/core/inc/wels_common_basis.h | BelledonneCommunications/openh264 | 70156cac67b1d4c829e6c479cb26df7e45a1bf12 | [
"BSD-2-Clause"
] | 8 | 2015-10-25T14:03:11.000Z | 2020-03-17T07:30:53.000Z | /*!
* \copy
* Copyright (c) 2013, Cisco Systems
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
//wels_common_basis.h
#ifndef WELS_COMMON_BASIS_H__
#define WELS_COMMON_BASIS_H__
#include "typedefs.h"
#include "macros.h"
#include "wels_const.h"
#include "wels_common_defs.h"
using namespace WelsCommon;
namespace WelsEnc {
struct SMVUnitXY { // each 4 Bytes
int16_t iMvX;
int16_t iMvY;
public:
SMVUnitXY& sDeltaMv (const SMVUnitXY& _v0, const SMVUnitXY& _v1) {
iMvX = _v0.iMvX - _v1.iMvX;
iMvY = _v0.iMvY - _v1.iMvY;
return (*this);
};
SMVUnitXY& sAssginMv (const SMVUnitXY& _v0) {
iMvX = _v0.iMvX;
iMvY = _v0.iMvY;
return (*this);
};
};
typedef struct TagMVComponentUnit { // each LIST_0/LIST_1
SMVUnitXY sMotionVectorCache[5 * 6 - 1]; // Luma only: 5 x 6 - 1 = 29 D-Words
int8_t iRefIndexCache[5 * 6]; // Luma only: 5 x 6 = 30 bytes
} SMVComponentUnit, *PMVComponentUnit;
typedef struct TagParaSetOffsetVariable {
int32_t iParaSetIdDelta[MAX_DQ_LAYER_NUM/*+1*/]; //mark delta between SPS_ID_in_bs and sps_id_in_encoder, can be minus, for each dq-layer
//need not extra +1 due no MGS and FMO case so far
bool bUsedParaSetIdInBs[MAX_PPS_COUNT]; //mark the used SPS_ID with 1
uint32_t uiNextParaSetIdToUseInBs; //mark the next SPS_ID_in_bs, for all layers
} SParaSetOffsetVariable;
typedef struct TagParaSetOffset {
//in PS0 design, "sParaSetOffsetVariable" record the previous paras before current IDR, AND NEED to be stacked and recover across IDR
SParaSetOffsetVariable
sParaSetOffsetVariable[PARA_SET_TYPE]; //PARA_SET_TYPE=3; paraset_type = 0: AVC_SPS; =1: Subset_SPS; =2: PPS
//in PSO design, "bPpsIdMappingIntoSubsetsps" uses the current para of current IDR period
bool
bPpsIdMappingIntoSubsetsps[MAX_DQ_LAYER_NUM/*+1*/]; // need not extra +1 due no MGS and FMO case so far
int32_t iPpsIdList[MAX_DQ_LAYER_NUM][MAX_PPS_COUNT]; //index0: max pps types; index1: for differnt IDRs, if only index0=1, index1 can reach MAX_PPS_COUNT
#if _DEBUG
int32_t eSpsPpsIdStrategy;
#endif
uint32_t uiNeededSpsNum;
uint32_t uiNeededSubsetSpsNum;
uint32_t uiNeededPpsNum;
uint32_t uiInUseSpsNum;
uint32_t uiInUseSubsetSpsNum;
uint32_t uiInUsePpsNum;
} SParaSetOffset;
/* Position Offset structure */
typedef struct TagCropOffset {
int16_t iCropLeft;
int16_t iCropRight;
int16_t iCropTop;
int16_t iCropBottom;
} SCropOffset;
/* Transform Type */
enum ETransType {
T_4x4 = 0,
T_8x8 = 1,
T_16x16 = 2,
T_PCM = 3
};
enum EMbPosition {
LEFT_MB_POS = 0x01, // A
TOP_MB_POS = 0x02, // B
TOPRIGHT_MB_POS = 0x04, // C
TOPLEFT_MB_POS = 0x08, // D,
RIGHT_MB_POS = 0x10, // add followed four case to reuse when intra up-sample
BOTTOM_MB_POS = 0x20, //
BOTTOMRIGHT_MB_POS = 0x40, //
BOTTOMLEFT_MB_POS = 0x80, //
MB_POS_A = 0x100
};
/* MB Type & Sub-MB Type */
typedef uint32_t Mb_Type;
#define MB_LEFT_BIT 0// add to use in intra up-sample
#define MB_TOP_BIT 1
#define MB_TOPRIGHT_BIT 2
#define MB_TOPLEFT_BIT 3
#define MB_RIGHT_BIT 4
#define MB_BOTTOM_BIT 5
#define MB_BTMRIGHT_BIT 6
#define MB_BTMLEFT_BIT 7
#define MB_TYPE_BACKGROUND 0x00010000 // conditional BG skip_mb
enum {
Intra4x4 = 0,
Intra16x16 = 1,
Inter16x16 = 2,
Inter16x8 = 3,
Inter8x16 = 4,
Inter8x8 = 5,
PSkip = 6
};
}
#endif//WELS_COMMON_BASIS_H__
| 31.0625 | 156 | 0.691751 | [
"transform"
] |
d2aaf6c0948e3ac3338a0059de5b0bd6efac8973 | 2,063 | c | C | framework/protocol/linkkit/iotkit/hal-impl/refs/linux_ota.c | ghsecuritylab/AliOS-FM | ae9f234c073404d8c97100927cbc53f49ae59a25 | [
"Apache-2.0"
] | 4 | 2018-09-05T05:29:39.000Z | 2022-03-30T01:37:02.000Z | framework/protocol/linkkit/iotkit/hal-impl/refs/linux_ota.c | ghsecuritylab/AliOS-FM | ae9f234c073404d8c97100927cbc53f49ae59a25 | [
"Apache-2.0"
] | null | null | null | framework/protocol/linkkit/iotkit/hal-impl/refs/linux_ota.c | ghsecuritylab/AliOS-FM | ae9f234c073404d8c97100927cbc53f49ae59a25 | [
"Apache-2.0"
] | 4 | 2018-09-28T09:27:11.000Z | 2022-03-30T01:37:06.000Z | /*
* Copyright (c) 2014-2016 Alibaba Group. All rights reserved.
*
* Alibaba Group retains all right, title and interest (including all
* intellectual property rights) in and to this computer program, which is
* protected by applicable intellectual property laws. Unless you have
* obtained a separate written license from Alibaba Group., you are not
* authorized to utilize all or a part of this computer program for any
* purpose (including reproduction, distribution, modification, and
* compilation into object code), and you must immediately destroy or
* return to Alibaba Group all copies of this computer program. If you
* are licensed by Alibaba Group, your rights to utilize this computer
* program are limited by the terms of that license. To obtain a license,
* please contact Alibaba Group.
*
* This computer program contains trade secrets owned by Alibaba Group.
* and, unless unauthorized by Alibaba Group in writing, you agree to
* maintain the confidentiality of this computer program and related
* information and to not disclose this computer program and related
* information to any other person or entity.
*
* THIS COMPUTER PROGRAM IS PROVIDED AS IS WITHOUT ANY WARRANTIES, AND
* Alibaba Group EXPRESSLY DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED,
* INCLUDING THE WARRANTIES OF MERCHANTIBILITY, FITNESS FOR A PARTICULAR
* PURPOSE, TITLE, AND NONINFRINGEMENT.
*/
#include <stdio.h>
#include <assert.h>
#include "platform.h"
static FILE *fp;
#define otafilename "/tmp/alinkota.bin"
void platform_flash_program_start(void)
{
fp = fopen(otafilename, "w");
assert(fp);
return;
}
int platform_flash_program_write_block(_IN_ char *buffer, _IN_ uint32_t length)
{
unsigned int written_len = 0;
written_len = fwrite(buffer, 1, length, fp);
if (written_len != length) {
return -1;
}
return 0;
}
int platform_flash_program_stop(void)
{
if (fp != NULL) {
fclose(fp);
}
/* check file md5, and burning it to flash ... finally reboot system */
return 0;
}
| 32.746032 | 79 | 0.735337 | [
"object"
] |
d2ad526f9627287c4bcfe47efddbbdf5c1b35435 | 5,478 | h | C | libs/mpf/include/mpf_engine.h | bjqiwei/unimrcp | c081282cc5b9572d7ee6c9d01aa42bd5ce0628ba | [
"Apache-2.0"
] | null | null | null | libs/mpf/include/mpf_engine.h | bjqiwei/unimrcp | c081282cc5b9572d7ee6c9d01aa42bd5ce0628ba | [
"Apache-2.0"
] | null | null | null | libs/mpf/include/mpf_engine.h | bjqiwei/unimrcp | c081282cc5b9572d7ee6c9d01aa42bd5ce0628ba | [
"Apache-2.0"
] | 1 | 2020-08-02T12:23:25.000Z | 2020-08-02T12:23:25.000Z | /*
* Copyright 2008-2015 Arsen Chaloyan
*
* 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 MPF_ENGINE_H
#define MPF_ENGINE_H
/**
* @file mpf_engine.h
* @brief Media Processing Framework Engine
*/
#include "apt_task.h"
#include "mpf_message.h"
APT_BEGIN_EXTERN_C
/** MPF task message definition */
typedef apt_task_msg_t mpf_task_msg_t;
/**
* Create MPF engine.
* @param id the identifier of the engine
* @param pool the pool to allocate memory from
*/
MPF_DECLARE(mpf_engine_t*) mpf_engine_create(const char *id, apr_pool_t *pool);
/**
* Create MPF codec manager.
* @param pool the pool to allocate memory from
*/
MPF_DECLARE(mpf_codec_manager_t*) mpf_engine_codec_manager_create(apr_pool_t *pool);
/**
* Register MPF codec manager.
* @param engine the engine to register codec manager for
* @param codec_manager the codec manager to register
*/
MPF_DECLARE(apt_bool_t) mpf_engine_codec_manager_register(mpf_engine_t *engine, const mpf_codec_manager_t *codec_manager);
/**
* Create MPF context.
* @param engine the engine to create context for
* @param name the informative name of the context
* @param obj the external object associated with context
* @param max_termination_count the max number of terminations in context
* @param pool the pool to allocate memory from
*/
MPF_DECLARE(mpf_context_t*) mpf_engine_context_create(
mpf_engine_t *engine,
const char *name,
void *obj,
apr_size_t max_termination_count,
apr_pool_t *pool);
/**
* Destroy MPF context.
* @param context the context to destroy
*/
MPF_DECLARE(apt_bool_t) mpf_engine_context_destroy(mpf_context_t *context);
/**
* Get external object associated with MPF context.
* @param context the context to get object from
*/
MPF_DECLARE(void*) mpf_engine_context_object_get(const mpf_context_t *context);
/**
* Get task.
* @param engine the engine to get task from
*/
MPF_DECLARE(apt_task_t*) mpf_task_get(const mpf_engine_t *engine);
/**
* Set task msg type to send responses and events with.
* @param engine the engine to set task msg type for
* @param type the type to set
*/
MPF_DECLARE(void) mpf_engine_task_msg_type_set(mpf_engine_t *engine, apt_task_msg_type_e type);
/**
* Create task message(if not created) and add MPF termination message to it.
* @param engine the engine task message belongs to
* @param command_id the MPF command identifier
* @param context the context to add termination to
* @param termination the termination to add
* @param descriptor the termination dependent descriptor
* @param task_msg the task message to create and add constructed MPF message to
*/
MPF_DECLARE(apt_bool_t) mpf_engine_termination_message_add(
mpf_engine_t *engine,
mpf_command_type_e command_id,
mpf_context_t *context,
mpf_termination_t *termination,
void *descriptor,
mpf_task_msg_t **task_msg);
/**
* Create task message(if not created) and add MPF association message to it.
* @param engine the engine task message belongs to
* @param command_id the MPF command identifier
* @param context the context to add association of terminations for
* @param termination the termination to associate
* @param assoc_termination the termination to associate
* @param task_msg the task message to create and add constructed MPF message to
*/
MPF_DECLARE(apt_bool_t) mpf_engine_assoc_message_add(
mpf_engine_t *engine,
mpf_command_type_e command_id,
mpf_context_t *context,
mpf_termination_t *termination,
mpf_termination_t *assoc_termination,
mpf_task_msg_t **task_msg);
/**
* Create task message(if not created) and add MPF topology message to it.
* @param engine the engine task message belongs to
* @param command_id the MPF command identifier
* @param context the context to modify topology for
* @param task_msg the task message to create and add constructed MPF message to
*/
MPF_DECLARE(apt_bool_t) mpf_engine_topology_message_add(
mpf_engine_t *engine,
mpf_command_type_e command_id,
mpf_context_t *context,
mpf_task_msg_t **task_msg);
/**
* Send MPF task message.
* @param engine the engine to send task message to
* @param task_msg the task message to send
*/
MPF_DECLARE(apt_bool_t) mpf_engine_message_send(mpf_engine_t *engine, mpf_task_msg_t **task_msg);
/**
* Set scheduler rate.
* @param engine the engine to set rate for
* @param rate the rate (n times faster than real-time)
*/
MPF_DECLARE(apt_bool_t) mpf_engine_scheduler_rate_set(mpf_engine_t *engine, unsigned long rate);
/**
* Get the identifier of the engine .
* @param engine the engine to get name of
*/
MPF_DECLARE(const char*) mpf_engine_id_get(const mpf_engine_t *engine);
APT_END_EXTERN_C
#endif /* MPF_ENGINE_H */
| 33.402439 | 123 | 0.727638 | [
"object"
] |
d2b0388a44bc1ced555920ab3a5e97903780a2d7 | 22,160 | h | C | app/src/main/cpp/gstreamer-1.0/armv7/include/gstreamer-1.0/gst/gstquery.h | pierotofy/rosettadrone | 336fa43d3ebcb5f544f83884656db18cbbbf2b72 | [
"BSD-3-Clause"
] | 88 | 2018-05-17T20:37:10.000Z | 2022-03-09T04:34:28.000Z | app/src/main/cpp/gstreamer-1.0/armv7/include/gstreamer-1.0/gst/gstquery.h | pierotofy/rosettadrone | 336fa43d3ebcb5f544f83884656db18cbbbf2b72 | [
"BSD-3-Clause"
] | 23 | 2018-05-17T21:56:30.000Z | 2021-02-24T12:58:43.000Z | app/src/main/cpp/gstreamer-1.0/armv7/include/gstreamer-1.0/gst/gstquery.h | pierotofy/rosettadrone | 336fa43d3ebcb5f544f83884656db18cbbbf2b72 | [
"BSD-3-Clause"
] | 55 | 2018-06-05T20:33:43.000Z | 2022-03-17T05:47:35.000Z | /* GStreamer
* Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
* 2000 Wim Taymans <wim.taymans@chello.be>
* 2005 Wim Taymans <wim@fluendo.com>
* 2011 Wim Taymans <wim.taymans@gmail.com>
*
* gstquery.h: GstQuery API declaration
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef __GST_QUERY_H__
#define __GST_QUERY_H__
#include <glib.h>
#include <glib-object.h>
#include <gst/gstconfig.h>
G_BEGIN_DECLS
typedef struct _GstQuery GstQuery;
#include <gst/gstminiobject.h>
/**
* GstQueryTypeFlags:
* @GST_QUERY_TYPE_UPSTREAM: Set if the query can travel upstream.
* @GST_QUERY_TYPE_DOWNSTREAM: Set if the query can travel downstream.
* @GST_QUERY_TYPE_SERIALIZED: Set if the query should be serialized with data
* flow.
*
* #GstQueryTypeFlags indicate the aspects of the different #GstQueryType
* values. You can get the type flags of a #GstQueryType with the
* gst_query_type_get_flags() function.
*/
typedef enum {
GST_QUERY_TYPE_UPSTREAM = 1 << 0,
GST_QUERY_TYPE_DOWNSTREAM = 1 << 1,
GST_QUERY_TYPE_SERIALIZED = 1 << 2
} GstQueryTypeFlags;
/**
* GST_QUERY_TYPE_BOTH: (value 3) (type GstQueryTypeFlags)
*
* The same thing as #GST_QUERY_TYPE_UPSTREAM | #GST_QUERY_TYPE_DOWNSTREAM.
*/
#define GST_QUERY_TYPE_BOTH \
((GstQueryTypeFlags)(GST_QUERY_TYPE_UPSTREAM | GST_QUERY_TYPE_DOWNSTREAM))
#define GST_QUERY_NUM_SHIFT (8)
/**
* GST_QUERY_MAKE_TYPE:
* @num: the query number to create
* @flags: the query flags
*
* when making custom query types, use this macro with the num and
* the given flags
*/
#define GST_QUERY_MAKE_TYPE(num,flags) \
(((num) << GST_QUERY_NUM_SHIFT) | (flags))
#define FLAG(name) GST_QUERY_TYPE_##name
/**
* GstQueryType:
* @GST_QUERY_UNKNOWN: unknown query type
* @GST_QUERY_POSITION: current position in stream
* @GST_QUERY_DURATION: total duration of the stream
* @GST_QUERY_LATENCY: latency of stream
* @GST_QUERY_JITTER: current jitter of stream
* @GST_QUERY_RATE: current rate of the stream
* @GST_QUERY_SEEKING: seeking capabilities
* @GST_QUERY_SEGMENT: segment start/stop positions
* @GST_QUERY_CONVERT: convert values between formats
* @GST_QUERY_FORMATS: query supported formats for convert
* @GST_QUERY_BUFFERING: query available media for efficient seeking.
* @GST_QUERY_CUSTOM: a custom application or element defined query.
* @GST_QUERY_URI: query the URI of the source or sink.
* @GST_QUERY_ALLOCATION: the buffer allocation properties
* @GST_QUERY_SCHEDULING: the scheduling properties
* @GST_QUERY_ACCEPT_CAPS: the accept caps query
* @GST_QUERY_CAPS: the caps query
* @GST_QUERY_DRAIN: wait till all serialized data is consumed downstream
* @GST_QUERY_CONTEXT: query the pipeline-local context from
* downstream or upstream (since 1.2)
*
* Standard predefined Query types
*/
/* NOTE: don't forget to update the table in gstquery.c when changing
* this enum */
typedef enum {
GST_QUERY_UNKNOWN = GST_QUERY_MAKE_TYPE (0, 0),
GST_QUERY_POSITION = GST_QUERY_MAKE_TYPE (10, FLAG(BOTH)),
GST_QUERY_DURATION = GST_QUERY_MAKE_TYPE (20, FLAG(BOTH)),
GST_QUERY_LATENCY = GST_QUERY_MAKE_TYPE (30, FLAG(BOTH)),
GST_QUERY_JITTER = GST_QUERY_MAKE_TYPE (40, FLAG(BOTH)),
GST_QUERY_RATE = GST_QUERY_MAKE_TYPE (50, FLAG(BOTH)),
GST_QUERY_SEEKING = GST_QUERY_MAKE_TYPE (60, FLAG(BOTH)),
GST_QUERY_SEGMENT = GST_QUERY_MAKE_TYPE (70, FLAG(BOTH)),
GST_QUERY_CONVERT = GST_QUERY_MAKE_TYPE (80, FLAG(BOTH)),
GST_QUERY_FORMATS = GST_QUERY_MAKE_TYPE (90, FLAG(BOTH)),
GST_QUERY_BUFFERING = GST_QUERY_MAKE_TYPE (110, FLAG(BOTH)),
GST_QUERY_CUSTOM = GST_QUERY_MAKE_TYPE (120, FLAG(BOTH)),
GST_QUERY_URI = GST_QUERY_MAKE_TYPE (130, FLAG(BOTH)),
GST_QUERY_ALLOCATION = GST_QUERY_MAKE_TYPE (140, FLAG(DOWNSTREAM) | FLAG(SERIALIZED)),
GST_QUERY_SCHEDULING = GST_QUERY_MAKE_TYPE (150, FLAG(UPSTREAM)),
GST_QUERY_ACCEPT_CAPS = GST_QUERY_MAKE_TYPE (160, FLAG(BOTH)),
GST_QUERY_CAPS = GST_QUERY_MAKE_TYPE (170, FLAG(BOTH)),
GST_QUERY_DRAIN = GST_QUERY_MAKE_TYPE (180, FLAG(DOWNSTREAM) | FLAG(SERIALIZED)),
GST_QUERY_CONTEXT = GST_QUERY_MAKE_TYPE (190, FLAG(BOTH))
} GstQueryType;
#undef FLAG
GST_API GType _gst_query_type;
#define GST_TYPE_QUERY (_gst_query_type)
#define GST_IS_QUERY(obj) (GST_IS_MINI_OBJECT_TYPE (obj, GST_TYPE_QUERY))
#define GST_QUERY_CAST(obj) ((GstQuery*)(obj))
#define GST_QUERY(obj) (GST_QUERY_CAST(obj))
/**
* GST_QUERY_TYPE:
* @query: the query to query
*
* Get the #GstQueryType of the query.
*/
#define GST_QUERY_TYPE(query) (((GstQuery*)(query))->type)
/**
* GST_QUERY_TYPE_NAME:
* @query: the query to query
*
* Get a constant string representation of the #GstQueryType of the query.
*/
#define GST_QUERY_TYPE_NAME(query) (gst_query_type_get_name(GST_QUERY_TYPE(query)))
/**
* GST_QUERY_IS_UPSTREAM:
* @ev: the query to query
*
* Check if an query can travel upstream.
*/
#define GST_QUERY_IS_UPSTREAM(ev) !!(GST_QUERY_TYPE (ev) & GST_QUERY_TYPE_UPSTREAM)
/**
* GST_QUERY_IS_DOWNSTREAM:
* @ev: the query to query
*
* Check if an query can travel downstream.
*/
#define GST_QUERY_IS_DOWNSTREAM(ev) !!(GST_QUERY_TYPE (ev) & GST_QUERY_TYPE_DOWNSTREAM)
/**
* GST_QUERY_IS_SERIALIZED:
* @ev: the query to query
*
* Check if an query is serialized with the data stream.
*/
#define GST_QUERY_IS_SERIALIZED(ev) !!(GST_QUERY_TYPE (ev) & GST_QUERY_TYPE_SERIALIZED)
/**
* GstQuery:
* @mini_object: The parent #GstMiniObject type
* @type: the #GstQueryType
*
* The #GstQuery structure.
*/
struct _GstQuery
{
GstMiniObject mini_object;
/*< public > *//* with COW */
GstQueryType type;
};
/**
* GstBufferingMode:
* @GST_BUFFERING_STREAM: a small amount of data is buffered
* @GST_BUFFERING_DOWNLOAD: the stream is being downloaded
* @GST_BUFFERING_TIMESHIFT: the stream is being downloaded in a ringbuffer
* @GST_BUFFERING_LIVE: the stream is a live stream
*
* The different types of buffering methods.
*/
typedef enum {
GST_BUFFERING_STREAM,
GST_BUFFERING_DOWNLOAD,
GST_BUFFERING_TIMESHIFT,
GST_BUFFERING_LIVE
} GstBufferingMode;
#include <gst/gstiterator.h>
#include <gst/gststructure.h>
#include <gst/gstformat.h>
#include <gst/gstpad.h>
#include <gst/gstallocator.h>
#include <gst/gsttoc.h>
#include <gst/gstcontext.h>
GST_API
const gchar* gst_query_type_get_name (GstQueryType type);
GST_API
GQuark gst_query_type_to_quark (GstQueryType type);
GST_API
GstQueryTypeFlags
gst_query_type_get_flags (GstQueryType type);
GST_API
GType gst_query_get_type (void);
/* refcounting */
/**
* gst_query_ref:
* @q: a #GstQuery to increase the refcount of.
*
* Increases the refcount of the given query by one.
*
* Returns: @q
*/
static inline GstQuery *
gst_query_ref (GstQuery * q)
{
return GST_QUERY_CAST (gst_mini_object_ref (GST_MINI_OBJECT_CAST (q)));
}
/**
* gst_query_unref:
* @q: a #GstQuery to decrease the refcount of.
*
* Decreases the refcount of the query. If the refcount reaches 0, the query
* will be freed.
*/
static inline void
gst_query_unref (GstQuery * q)
{
gst_mini_object_unref (GST_MINI_OBJECT_CAST (q));
}
/* copy query */
/**
* gst_query_copy:
* @q: a #GstQuery to copy.
*
* Copies the given query using the copy function of the parent #GstStructure.
*
* Free-function: gst_query_unref
*
* Returns: (transfer full): a new copy of @q.
*/
static inline GstQuery *
gst_query_copy (const GstQuery * q)
{
return GST_QUERY_CAST (gst_mini_object_copy (GST_MINI_OBJECT_CONST_CAST (q)));
}
/**
* gst_query_is_writable:
* @q: a #GstQuery
*
* Tests if you can safely write data into a query's structure.
*/
#define gst_query_is_writable(q) gst_mini_object_is_writable (GST_MINI_OBJECT_CAST (q))
/**
* gst_query_make_writable:
* @q: (transfer full): a #GstQuery to make writable
*
* Makes a writable query from the given query.
*
* Returns: (transfer full): a new writable query (possibly same as @q)
*/
#define gst_query_make_writable(q) GST_QUERY_CAST (gst_mini_object_make_writable (GST_MINI_OBJECT_CAST (q)))
/**
* gst_query_replace:
* @old_query: (inout) (transfer full) (nullable): pointer to a pointer to a
* #GstQuery to be replaced.
* @new_query: (allow-none) (transfer none): pointer to a #GstQuery that will
* replace the query pointed to by @old_query.
*
* Modifies a pointer to a #GstQuery to point to a different #GstQuery. The
* modification is done atomically (so this is useful for ensuring thread safety
* in some cases), and the reference counts are updated appropriately (the old
* query is unreffed, the new one is reffed).
*
* Either @new_query or the #GstQuery pointed to by @old_query may be %NULL.
*
* Returns: %TRUE if @new_query was different from @old_query
*/
static inline gboolean
gst_query_replace (GstQuery **old_query, GstQuery *new_query)
{
return gst_mini_object_replace ((GstMiniObject **) old_query, (GstMiniObject *) new_query);
}
/* application specific query */
GST_API
GstQuery * gst_query_new_custom (GstQueryType type, GstStructure *structure) G_GNUC_MALLOC;
GST_API
const GstStructure *
gst_query_get_structure (GstQuery *query);
GST_API
GstStructure * gst_query_writable_structure (GstQuery *query);
/* position query */
GST_API
GstQuery* gst_query_new_position (GstFormat format) G_GNUC_MALLOC;
GST_API
void gst_query_set_position (GstQuery *query, GstFormat format, gint64 cur);
GST_API
void gst_query_parse_position (GstQuery *query, GstFormat *format, gint64 *cur);
/* duration query */
GST_API
GstQuery* gst_query_new_duration (GstFormat format) G_GNUC_MALLOC;
GST_API
void gst_query_set_duration (GstQuery *query, GstFormat format, gint64 duration);
GST_API
void gst_query_parse_duration (GstQuery *query, GstFormat *format, gint64 *duration);
/* latency query */
GST_API
GstQuery* gst_query_new_latency (void) G_GNUC_MALLOC;
GST_API
void gst_query_set_latency (GstQuery *query, gboolean live, GstClockTime min_latency,
GstClockTime max_latency);
GST_API
void gst_query_parse_latency (GstQuery *query, gboolean *live, GstClockTime *min_latency,
GstClockTime *max_latency);
/* convert query */
GST_API
GstQuery* gst_query_new_convert (GstFormat src_format, gint64 value, GstFormat dest_format) G_GNUC_MALLOC;
GST_API
void gst_query_set_convert (GstQuery *query, GstFormat src_format, gint64 src_value,
GstFormat dest_format, gint64 dest_value);
GST_API
void gst_query_parse_convert (GstQuery *query, GstFormat *src_format, gint64 *src_value,
GstFormat *dest_format, gint64 *dest_value);
/* segment query */
GST_API
GstQuery* gst_query_new_segment (GstFormat format) G_GNUC_MALLOC;
GST_API
void gst_query_set_segment (GstQuery *query, gdouble rate, GstFormat format,
gint64 start_value, gint64 stop_value);
GST_API
void gst_query_parse_segment (GstQuery *query, gdouble *rate, GstFormat *format,
gint64 *start_value, gint64 *stop_value);
/* seeking query */
GST_API
GstQuery* gst_query_new_seeking (GstFormat format) G_GNUC_MALLOC;
GST_API
void gst_query_set_seeking (GstQuery *query, GstFormat format,
gboolean seekable,
gint64 segment_start,
gint64 segment_end);
GST_API
void gst_query_parse_seeking (GstQuery *query, GstFormat *format,
gboolean *seekable,
gint64 *segment_start,
gint64 *segment_end);
/* formats query */
GST_API
GstQuery* gst_query_new_formats (void) G_GNUC_MALLOC;
GST_API
void gst_query_set_formats (GstQuery *query, gint n_formats, ...);
GST_API
void gst_query_set_formatsv (GstQuery *query, gint n_formats, const GstFormat *formats);
GST_API
void gst_query_parse_n_formats (GstQuery *query, guint *n_formats);
GST_API
void gst_query_parse_nth_format (GstQuery *query, guint nth, GstFormat *format);
/* buffering query */
GST_API
GstQuery* gst_query_new_buffering (GstFormat format) G_GNUC_MALLOC;
GST_API
void gst_query_set_buffering_percent (GstQuery *query, gboolean busy, gint percent);
GST_API
void gst_query_parse_buffering_percent (GstQuery *query, gboolean *busy, gint *percent);
GST_API
void gst_query_set_buffering_stats (GstQuery *query, GstBufferingMode mode,
gint avg_in, gint avg_out,
gint64 buffering_left);
GST_API
void gst_query_parse_buffering_stats (GstQuery *query, GstBufferingMode *mode,
gint *avg_in, gint *avg_out,
gint64 *buffering_left);
GST_API
void gst_query_set_buffering_range (GstQuery *query, GstFormat format,
gint64 start, gint64 stop,
gint64 estimated_total);
GST_API
void gst_query_parse_buffering_range (GstQuery *query, GstFormat *format,
gint64 *start, gint64 *stop,
gint64 *estimated_total);
GST_API
gboolean gst_query_add_buffering_range (GstQuery *query,
gint64 start, gint64 stop);
GST_API
guint gst_query_get_n_buffering_ranges (GstQuery *query);
GST_API
gboolean gst_query_parse_nth_buffering_range (GstQuery *query,
guint index, gint64 *start,
gint64 *stop);
/* URI query */
GST_API
GstQuery * gst_query_new_uri (void) G_GNUC_MALLOC;
GST_API
void gst_query_parse_uri (GstQuery *query, gchar **uri);
GST_API
void gst_query_set_uri (GstQuery *query, const gchar *uri);
GST_API
void gst_query_parse_uri_redirection (GstQuery *query, gchar **uri);
GST_API
void gst_query_set_uri_redirection (GstQuery *query, const gchar *uri);
GST_API
void gst_query_parse_uri_redirection_permanent (GstQuery *query, gboolean * permanent);
GST_API
void gst_query_set_uri_redirection_permanent (GstQuery *query, gboolean permanent);
/* allocation query */
GST_API
GstQuery * gst_query_new_allocation (GstCaps *caps, gboolean need_pool) G_GNUC_MALLOC;
GST_API
void gst_query_parse_allocation (GstQuery *query, GstCaps **caps, gboolean *need_pool);
/* pools */
GST_API
void gst_query_add_allocation_pool (GstQuery *query, GstBufferPool *pool,
guint size, guint min_buffers,
guint max_buffers);
GST_API
guint gst_query_get_n_allocation_pools (GstQuery *query);
GST_API
void gst_query_parse_nth_allocation_pool (GstQuery *query, guint index,
GstBufferPool **pool,
guint *size, guint *min_buffers,
guint *max_buffers);
GST_API
void gst_query_set_nth_allocation_pool (GstQuery *query, guint index,
GstBufferPool *pool,
guint size, guint min_buffers,
guint max_buffers);
GST_API
void gst_query_remove_nth_allocation_pool (GstQuery *query, guint index);
/* allocators */
GST_API
void gst_query_add_allocation_param (GstQuery *query, GstAllocator *allocator,
const GstAllocationParams *params);
GST_API
guint gst_query_get_n_allocation_params (GstQuery *query);
GST_API
void gst_query_parse_nth_allocation_param (GstQuery *query, guint index,
GstAllocator **allocator,
GstAllocationParams *params);
GST_API
void gst_query_set_nth_allocation_param (GstQuery *query, guint index,
GstAllocator *allocator,
const GstAllocationParams *params);
GST_API
void gst_query_remove_nth_allocation_param (GstQuery *query, guint index);
/* metadata */
GST_API
void gst_query_add_allocation_meta (GstQuery *query, GType api, const GstStructure *params);
GST_API
guint gst_query_get_n_allocation_metas (GstQuery *query);
GST_API
GType gst_query_parse_nth_allocation_meta (GstQuery *query, guint index,
const GstStructure **params);
GST_API
void gst_query_remove_nth_allocation_meta (GstQuery *query, guint index);
GST_API
gboolean gst_query_find_allocation_meta (GstQuery *query, GType api, guint *index);
/* scheduling query */
/**
* GstSchedulingFlags:
* @GST_SCHEDULING_FLAG_SEEKABLE: if seeking is possible
* @GST_SCHEDULING_FLAG_SEQUENTIAL: if sequential access is recommended
* @GST_SCHEDULING_FLAG_BANDWIDTH_LIMITED: if bandwidth is limited and buffering possible (since 1.2)
*
* The different scheduling flags.
*/
typedef enum {
GST_SCHEDULING_FLAG_SEEKABLE = (1 << 0),
GST_SCHEDULING_FLAG_SEQUENTIAL = (1 << 1),
GST_SCHEDULING_FLAG_BANDWIDTH_LIMITED = (1 << 2)
} GstSchedulingFlags;
GST_API
GstQuery * gst_query_new_scheduling (void) G_GNUC_MALLOC;
GST_API
void gst_query_set_scheduling (GstQuery *query, GstSchedulingFlags flags,
gint minsize, gint maxsize, gint align);
GST_API
void gst_query_parse_scheduling (GstQuery *query, GstSchedulingFlags *flags,
gint *minsize, gint *maxsize, gint *align);
GST_API
void gst_query_add_scheduling_mode (GstQuery *query, GstPadMode mode);
GST_API
guint gst_query_get_n_scheduling_modes (GstQuery *query);
GST_API
GstPadMode gst_query_parse_nth_scheduling_mode (GstQuery *query, guint index);
GST_API
gboolean gst_query_has_scheduling_mode (GstQuery *query, GstPadMode mode);
GST_API
gboolean gst_query_has_scheduling_mode_with_flags (GstQuery * query, GstPadMode mode,
GstSchedulingFlags flags);
/* accept-caps query */
GST_API
GstQuery * gst_query_new_accept_caps (GstCaps *caps) G_GNUC_MALLOC;
GST_API
void gst_query_parse_accept_caps (GstQuery *query, GstCaps **caps);
GST_API
void gst_query_set_accept_caps_result (GstQuery *query, gboolean result);
GST_API
void gst_query_parse_accept_caps_result (GstQuery *query, gboolean *result);
/* caps query */
GST_API
GstQuery * gst_query_new_caps (GstCaps *filter) G_GNUC_MALLOC;
GST_API
void gst_query_parse_caps (GstQuery *query, GstCaps **filter);
GST_API
void gst_query_set_caps_result (GstQuery *query, GstCaps *caps);
GST_API
void gst_query_parse_caps_result (GstQuery *query, GstCaps **caps);
/* drain query */
GST_API
GstQuery * gst_query_new_drain (void) G_GNUC_MALLOC;
/* context query */
GST_API
GstQuery * gst_query_new_context (const gchar * context_type) G_GNUC_MALLOC;
GST_API
gboolean gst_query_parse_context_type (GstQuery * query, const gchar ** context_type);
GST_API
void gst_query_set_context (GstQuery *query, GstContext *context);
GST_API
void gst_query_parse_context (GstQuery *query, GstContext **context);
#ifdef G_DEFINE_AUTOPTR_CLEANUP_FUNC
G_DEFINE_AUTOPTR_CLEANUP_FUNC(GstQuery, gst_query_unref)
#endif
G_END_DECLS
#endif /* __GST_QUERY_H__ */
| 33.883792 | 122 | 0.645442 | [
"object"
] |
d2bf0cb6ecae5b7fb91335d565eb648e7e2a20ce | 3,834 | h | C | src/planner/Algo.h | whitewum/nebula-graph | 4163e51f949298a33a337192028d76de6d4325fd | [
"Apache-2.0"
] | null | null | null | src/planner/Algo.h | whitewum/nebula-graph | 4163e51f949298a33a337192028d76de6d4325fd | [
"Apache-2.0"
] | null | null | null | src/planner/Algo.h | whitewum/nebula-graph | 4163e51f949298a33a337192028d76de6d4325fd | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2020 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#ifndef PLANNER_ALGO_H_
#define PLANNER_ALGO_H_
#include "common/base/Base.h"
#include "context/QueryContext.h"
#include "planner/PlanNode.h"
namespace nebula {
namespace graph {
class ProduceSemiShortestPath : public SingleInputNode {
public:
static ProduceSemiShortestPath* make(QueryContext* qctx, PlanNode* input) {
return qctx->objPool()->add(new ProduceSemiShortestPath(qctx, input));
}
private:
ProduceSemiShortestPath(QueryContext* qctx, PlanNode* input)
: SingleInputNode(qctx, Kind::kProduceSemiShortestPath, input) {}
};
class BFSShortestPath : public SingleInputNode {
public:
static BFSShortestPath* make(QueryContext* qctx, PlanNode* input) {
return qctx->objPool()->add(new BFSShortestPath(qctx, input));
}
private:
BFSShortestPath(QueryContext* qctx, PlanNode* input)
: SingleInputNode(qctx, Kind::kBFSShortest, input) {}
};
class ConjunctPath : public BiInputNode {
public:
enum class PathKind : uint8_t {
kBiBFS,
kBiDijkstra,
kFloyd,
kAllPaths,
};
static ConjunctPath* make(QueryContext* qctx,
PlanNode* left,
PlanNode* right,
PathKind pathKind,
size_t steps) {
return qctx->objPool()->add(new ConjunctPath(qctx, left, right, pathKind, steps));
}
PathKind pathKind() const {
return pathKind_;
}
size_t steps() const {
return steps_;
}
void setConditionalVar(std::string varName) {
conditionalVar_ = std::move(varName);
}
std::string conditionalVar() const {
return conditionalVar_;
}
bool noLoop() const {
return noLoop_;
}
void setNoLoop(bool noLoop) {
noLoop_ = noLoop;
}
std::unique_ptr<PlanNodeDescription> explain() const override;
private:
ConjunctPath(QueryContext* qctx,
PlanNode* left,
PlanNode* right,
PathKind pathKind,
size_t steps)
: BiInputNode(qctx, Kind::kConjunctPath, left, right) {
pathKind_ = pathKind;
steps_ = steps;
}
PathKind pathKind_;
size_t steps_{0};
std::string conditionalVar_;
bool noLoop_;
};
class ProduceAllPaths final : public SingleInputNode {
public:
static ProduceAllPaths* make(QueryContext* qctx, PlanNode* input) {
return qctx->objPool()->add(new ProduceAllPaths(qctx, input));
}
bool noLoop() const {
return noLoop_;
}
void setNoLoop(bool noLoop) {
noLoop_ = noLoop;
}
std::unique_ptr<PlanNodeDescription> explain() const override;
private:
ProduceAllPaths(QueryContext* qctx, PlanNode* input)
: SingleInputNode(qctx, Kind::kProduceAllPaths, input) {}
private:
bool noLoop_{false};
};
class CartesianProduct final : public SingleDependencyNode {
public:
static CartesianProduct* make(QueryContext* qctx, PlanNode* input) {
return qctx->objPool()->add(new CartesianProduct(qctx, input));
}
Status addVar(std::string varName);
std::vector<std::string> inputVars() const;
std::vector<std::vector<std::string>> allColNames() const {
return allColNames_;
}
std::unique_ptr<PlanNodeDescription> explain() const override;
private:
CartesianProduct(QueryContext* qctx, PlanNode* input)
: SingleDependencyNode(qctx, Kind::kCartesianProduct, input) {}
std::vector<std::vector<std::string>> allColNames_;
};
} // namespace graph
} // namespace nebula
#endif // PLANNER_ALGO_H_
| 26.441379 | 90 | 0.648148 | [
"vector"
] |
d2c0b442bce5fb010fc43414a266c34ee245ca54 | 31,503 | c | C | linux-3.16/drivers/s390/kvm/virtio_ccw.c | jj1232727/system_call | 145315cdf532c45b6aa753d98260d2b1c0b63abc | [
"Unlicense"
] | null | null | null | linux-3.16/drivers/s390/kvm/virtio_ccw.c | jj1232727/system_call | 145315cdf532c45b6aa753d98260d2b1c0b63abc | [
"Unlicense"
] | null | null | null | linux-3.16/drivers/s390/kvm/virtio_ccw.c | jj1232727/system_call | 145315cdf532c45b6aa753d98260d2b1c0b63abc | [
"Unlicense"
] | null | null | null | /*
* ccw based virtio transport
*
* Copyright IBM Corp. 2012, 2014
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License (version 2 only)
* as published by the Free Software Foundation.
*
* Author(s): Cornelia Huck <cornelia.huck@de.ibm.com>
*/
#include <linux/kernel_stat.h>
#include <linux/init.h>
#include <linux/bootmem.h>
#include <linux/err.h>
#include <linux/virtio.h>
#include <linux/virtio_config.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/virtio_ring.h>
#include <linux/pfn.h>
#include <linux/async.h>
#include <linux/wait.h>
#include <linux/list.h>
#include <linux/bitops.h>
#include <linux/module.h>
#include <linux/io.h>
#include <linux/kvm_para.h>
#include <linux/notifier.h>
#include <asm/setup.h>
#include <asm/irq.h>
#include <asm/cio.h>
#include <asm/ccwdev.h>
#include <asm/virtio-ccw.h>
#include <asm/isc.h>
#include <asm/airq.h>
/*
* virtio related functions
*/
struct vq_config_block {
__u16 index;
__u16 num;
} __packed;
#define VIRTIO_CCW_CONFIG_SIZE 0x100
/* same as PCI config space size, should be enough for all drivers */
struct virtio_ccw_device {
struct virtio_device vdev;
__u8 *status;
__u8 config[VIRTIO_CCW_CONFIG_SIZE];
struct ccw_device *cdev;
__u32 curr_io;
int err;
wait_queue_head_t wait_q;
spinlock_t lock;
struct list_head virtqueues;
unsigned long indicators;
unsigned long indicators2;
struct vq_config_block *config_block;
bool is_thinint;
bool going_away;
bool device_lost;
void *airq_info;
};
struct vq_info_block {
__u64 queue;
__u32 align;
__u16 index;
__u16 num;
} __packed;
struct virtio_feature_desc {
__u32 features;
__u8 index;
} __packed;
struct virtio_thinint_area {
unsigned long summary_indicator;
unsigned long indicator;
u64 bit_nr;
u8 isc;
} __packed;
struct virtio_ccw_vq_info {
struct virtqueue *vq;
int num;
void *queue;
struct vq_info_block *info_block;
int bit_nr;
struct list_head node;
long cookie;
};
#define VIRTIO_AIRQ_ISC IO_SCH_ISC /* inherit from subchannel */
#define VIRTIO_IV_BITS (L1_CACHE_BYTES * 8)
#define MAX_AIRQ_AREAS 20
static int virtio_ccw_use_airq = 1;
struct airq_info {
rwlock_t lock;
u8 summary_indicator;
struct airq_struct airq;
struct airq_iv *aiv;
};
static struct airq_info *airq_areas[MAX_AIRQ_AREAS];
#define CCW_CMD_SET_VQ 0x13
#define CCW_CMD_VDEV_RESET 0x33
#define CCW_CMD_SET_IND 0x43
#define CCW_CMD_SET_CONF_IND 0x53
#define CCW_CMD_READ_FEAT 0x12
#define CCW_CMD_WRITE_FEAT 0x11
#define CCW_CMD_READ_CONF 0x22
#define CCW_CMD_WRITE_CONF 0x21
#define CCW_CMD_WRITE_STATUS 0x31
#define CCW_CMD_READ_VQ_CONF 0x32
#define CCW_CMD_SET_IND_ADAPTER 0x73
#define VIRTIO_CCW_DOING_SET_VQ 0x00010000
#define VIRTIO_CCW_DOING_RESET 0x00040000
#define VIRTIO_CCW_DOING_READ_FEAT 0x00080000
#define VIRTIO_CCW_DOING_WRITE_FEAT 0x00100000
#define VIRTIO_CCW_DOING_READ_CONFIG 0x00200000
#define VIRTIO_CCW_DOING_WRITE_CONFIG 0x00400000
#define VIRTIO_CCW_DOING_WRITE_STATUS 0x00800000
#define VIRTIO_CCW_DOING_SET_IND 0x01000000
#define VIRTIO_CCW_DOING_READ_VQ_CONF 0x02000000
#define VIRTIO_CCW_DOING_SET_CONF_IND 0x04000000
#define VIRTIO_CCW_DOING_SET_IND_ADAPTER 0x08000000
#define VIRTIO_CCW_INTPARM_MASK 0xffff0000
static struct virtio_ccw_device *to_vc_device(struct virtio_device *vdev)
{
return container_of(vdev, struct virtio_ccw_device, vdev);
}
static void drop_airq_indicator(struct virtqueue *vq, struct airq_info *info)
{
unsigned long i, flags;
write_lock_irqsave(&info->lock, flags);
for (i = 0; i < airq_iv_end(info->aiv); i++) {
if (vq == (void *)airq_iv_get_ptr(info->aiv, i)) {
airq_iv_free_bit(info->aiv, i);
airq_iv_set_ptr(info->aiv, i, 0);
break;
}
}
write_unlock_irqrestore(&info->lock, flags);
}
static void virtio_airq_handler(struct airq_struct *airq)
{
struct airq_info *info = container_of(airq, struct airq_info, airq);
unsigned long ai;
inc_irq_stat(IRQIO_VAI);
read_lock(&info->lock);
/* Walk through indicators field, summary indicator active. */
for (ai = 0;;) {
ai = airq_iv_scan(info->aiv, ai, airq_iv_end(info->aiv));
if (ai == -1UL)
break;
vring_interrupt(0, (void *)airq_iv_get_ptr(info->aiv, ai));
}
info->summary_indicator = 0;
smp_wmb();
/* Walk through indicators field, summary indicator not active. */
for (ai = 0;;) {
ai = airq_iv_scan(info->aiv, ai, airq_iv_end(info->aiv));
if (ai == -1UL)
break;
vring_interrupt(0, (void *)airq_iv_get_ptr(info->aiv, ai));
}
read_unlock(&info->lock);
}
static struct airq_info *new_airq_info(void)
{
struct airq_info *info;
int rc;
info = kzalloc(sizeof(*info), GFP_KERNEL);
if (!info)
return NULL;
rwlock_init(&info->lock);
info->aiv = airq_iv_create(VIRTIO_IV_BITS, AIRQ_IV_ALLOC | AIRQ_IV_PTR);
if (!info->aiv) {
kfree(info);
return NULL;
}
info->airq.handler = virtio_airq_handler;
info->airq.lsi_ptr = &info->summary_indicator;
info->airq.lsi_mask = 0xff;
info->airq.isc = VIRTIO_AIRQ_ISC;
rc = register_adapter_interrupt(&info->airq);
if (rc) {
airq_iv_release(info->aiv);
kfree(info);
return NULL;
}
return info;
}
static void destroy_airq_info(struct airq_info *info)
{
if (!info)
return;
unregister_adapter_interrupt(&info->airq);
airq_iv_release(info->aiv);
kfree(info);
}
static unsigned long get_airq_indicator(struct virtqueue *vqs[], int nvqs,
u64 *first, void **airq_info)
{
int i, j;
struct airq_info *info;
unsigned long indicator_addr = 0;
unsigned long bit, flags;
for (i = 0; i < MAX_AIRQ_AREAS && !indicator_addr; i++) {
if (!airq_areas[i])
airq_areas[i] = new_airq_info();
info = airq_areas[i];
if (!info)
return 0;
write_lock_irqsave(&info->lock, flags);
bit = airq_iv_alloc(info->aiv, nvqs);
if (bit == -1UL) {
/* Not enough vacancies. */
write_unlock_irqrestore(&info->lock, flags);
continue;
}
*first = bit;
*airq_info = info;
indicator_addr = (unsigned long)info->aiv->vector;
for (j = 0; j < nvqs; j++) {
airq_iv_set_ptr(info->aiv, bit + j,
(unsigned long)vqs[j]);
}
write_unlock_irqrestore(&info->lock, flags);
}
return indicator_addr;
}
static void virtio_ccw_drop_indicators(struct virtio_ccw_device *vcdev)
{
struct virtio_ccw_vq_info *info;
list_for_each_entry(info, &vcdev->virtqueues, node)
drop_airq_indicator(info->vq, vcdev->airq_info);
}
static int doing_io(struct virtio_ccw_device *vcdev, __u32 flag)
{
unsigned long flags;
__u32 ret;
spin_lock_irqsave(get_ccwdev_lock(vcdev->cdev), flags);
if (vcdev->err)
ret = 0;
else
ret = vcdev->curr_io & flag;
spin_unlock_irqrestore(get_ccwdev_lock(vcdev->cdev), flags);
return ret;
}
static int ccw_io_helper(struct virtio_ccw_device *vcdev,
struct ccw1 *ccw, __u32 intparm)
{
int ret;
unsigned long flags;
int flag = intparm & VIRTIO_CCW_INTPARM_MASK;
do {
spin_lock_irqsave(get_ccwdev_lock(vcdev->cdev), flags);
ret = ccw_device_start(vcdev->cdev, ccw, intparm, 0, 0);
if (!ret) {
if (!vcdev->curr_io)
vcdev->err = 0;
vcdev->curr_io |= flag;
}
spin_unlock_irqrestore(get_ccwdev_lock(vcdev->cdev), flags);
cpu_relax();
} while (ret == -EBUSY);
wait_event(vcdev->wait_q, doing_io(vcdev, flag) == 0);
return ret ? ret : vcdev->err;
}
static void virtio_ccw_drop_indicator(struct virtio_ccw_device *vcdev,
struct ccw1 *ccw)
{
int ret;
unsigned long *indicatorp = NULL;
struct virtio_thinint_area *thinint_area = NULL;
struct airq_info *airq_info = vcdev->airq_info;
if (vcdev->is_thinint) {
thinint_area = kzalloc(sizeof(*thinint_area),
GFP_DMA | GFP_KERNEL);
if (!thinint_area)
return;
thinint_area->summary_indicator =
(unsigned long) &airq_info->summary_indicator;
thinint_area->isc = VIRTIO_AIRQ_ISC;
ccw->cmd_code = CCW_CMD_SET_IND_ADAPTER;
ccw->count = sizeof(*thinint_area);
ccw->cda = (__u32)(unsigned long) thinint_area;
} else {
indicatorp = kmalloc(sizeof(&vcdev->indicators),
GFP_DMA | GFP_KERNEL);
if (!indicatorp)
return;
*indicatorp = 0;
ccw->cmd_code = CCW_CMD_SET_IND;
ccw->count = sizeof(vcdev->indicators);
ccw->cda = (__u32)(unsigned long) indicatorp;
}
/* Deregister indicators from host. */
vcdev->indicators = 0;
ccw->flags = 0;
ret = ccw_io_helper(vcdev, ccw,
vcdev->is_thinint ?
VIRTIO_CCW_DOING_SET_IND_ADAPTER :
VIRTIO_CCW_DOING_SET_IND);
if (ret && (ret != -ENODEV))
dev_info(&vcdev->cdev->dev,
"Failed to deregister indicators (%d)\n", ret);
else if (vcdev->is_thinint)
virtio_ccw_drop_indicators(vcdev);
kfree(indicatorp);
kfree(thinint_area);
}
static inline long do_kvm_notify(struct subchannel_id schid,
unsigned long queue_index,
long cookie)
{
register unsigned long __nr asm("1") = KVM_S390_VIRTIO_CCW_NOTIFY;
register struct subchannel_id __schid asm("2") = schid;
register unsigned long __index asm("3") = queue_index;
register long __rc asm("2");
register long __cookie asm("4") = cookie;
asm volatile ("diag 2,4,0x500\n"
: "=d" (__rc) : "d" (__nr), "d" (__schid), "d" (__index),
"d"(__cookie)
: "memory", "cc");
return __rc;
}
static bool virtio_ccw_kvm_notify(struct virtqueue *vq)
{
struct virtio_ccw_vq_info *info = vq->priv;
struct virtio_ccw_device *vcdev;
struct subchannel_id schid;
vcdev = to_vc_device(info->vq->vdev);
ccw_device_get_schid(vcdev->cdev, &schid);
info->cookie = do_kvm_notify(schid, vq->index, info->cookie);
if (info->cookie < 0)
return false;
return true;
}
static int virtio_ccw_read_vq_conf(struct virtio_ccw_device *vcdev,
struct ccw1 *ccw, int index)
{
vcdev->config_block->index = index;
ccw->cmd_code = CCW_CMD_READ_VQ_CONF;
ccw->flags = 0;
ccw->count = sizeof(struct vq_config_block);
ccw->cda = (__u32)(unsigned long)(vcdev->config_block);
ccw_io_helper(vcdev, ccw, VIRTIO_CCW_DOING_READ_VQ_CONF);
return vcdev->config_block->num;
}
static void virtio_ccw_del_vq(struct virtqueue *vq, struct ccw1 *ccw)
{
struct virtio_ccw_device *vcdev = to_vc_device(vq->vdev);
struct virtio_ccw_vq_info *info = vq->priv;
unsigned long flags;
unsigned long size;
int ret;
unsigned int index = vq->index;
/* Remove from our list. */
spin_lock_irqsave(&vcdev->lock, flags);
list_del(&info->node);
spin_unlock_irqrestore(&vcdev->lock, flags);
/* Release from host. */
info->info_block->queue = 0;
info->info_block->align = 0;
info->info_block->index = index;
info->info_block->num = 0;
ccw->cmd_code = CCW_CMD_SET_VQ;
ccw->flags = 0;
ccw->count = sizeof(*info->info_block);
ccw->cda = (__u32)(unsigned long)(info->info_block);
ret = ccw_io_helper(vcdev, ccw,
VIRTIO_CCW_DOING_SET_VQ | index);
/*
* -ENODEV isn't considered an error: The device is gone anyway.
* This may happen on device detach.
*/
if (ret && (ret != -ENODEV))
dev_warn(&vq->vdev->dev, "Error %d while deleting queue %d",
ret, index);
vring_del_virtqueue(vq);
size = PAGE_ALIGN(vring_size(info->num, KVM_VIRTIO_CCW_RING_ALIGN));
free_pages_exact(info->queue, size);
kfree(info->info_block);
kfree(info);
}
static void virtio_ccw_del_vqs(struct virtio_device *vdev)
{
struct virtqueue *vq, *n;
struct ccw1 *ccw;
struct virtio_ccw_device *vcdev = to_vc_device(vdev);
ccw = kzalloc(sizeof(*ccw), GFP_DMA | GFP_KERNEL);
if (!ccw)
return;
virtio_ccw_drop_indicator(vcdev, ccw);
list_for_each_entry_safe(vq, n, &vdev->vqs, list)
virtio_ccw_del_vq(vq, ccw);
kfree(ccw);
}
static struct virtqueue *virtio_ccw_setup_vq(struct virtio_device *vdev,
int i, vq_callback_t *callback,
const char *name,
struct ccw1 *ccw)
{
struct virtio_ccw_device *vcdev = to_vc_device(vdev);
int err;
struct virtqueue *vq = NULL;
struct virtio_ccw_vq_info *info;
unsigned long size = 0; /* silence the compiler */
unsigned long flags;
/* Allocate queue. */
info = kzalloc(sizeof(struct virtio_ccw_vq_info), GFP_KERNEL);
if (!info) {
dev_warn(&vcdev->cdev->dev, "no info\n");
err = -ENOMEM;
goto out_err;
}
info->info_block = kzalloc(sizeof(*info->info_block),
GFP_DMA | GFP_KERNEL);
if (!info->info_block) {
dev_warn(&vcdev->cdev->dev, "no info block\n");
err = -ENOMEM;
goto out_err;
}
info->num = virtio_ccw_read_vq_conf(vcdev, ccw, i);
size = PAGE_ALIGN(vring_size(info->num, KVM_VIRTIO_CCW_RING_ALIGN));
info->queue = alloc_pages_exact(size, GFP_KERNEL | __GFP_ZERO);
if (info->queue == NULL) {
dev_warn(&vcdev->cdev->dev, "no queue\n");
err = -ENOMEM;
goto out_err;
}
vq = vring_new_virtqueue(i, info->num, KVM_VIRTIO_CCW_RING_ALIGN, vdev,
true, info->queue, virtio_ccw_kvm_notify,
callback, name);
if (!vq) {
/* For now, we fail if we can't get the requested size. */
dev_warn(&vcdev->cdev->dev, "no vq\n");
err = -ENOMEM;
goto out_err;
}
/* Register it with the host. */
info->info_block->queue = (__u64)info->queue;
info->info_block->align = KVM_VIRTIO_CCW_RING_ALIGN;
info->info_block->index = i;
info->info_block->num = info->num;
ccw->cmd_code = CCW_CMD_SET_VQ;
ccw->flags = 0;
ccw->count = sizeof(*info->info_block);
ccw->cda = (__u32)(unsigned long)(info->info_block);
err = ccw_io_helper(vcdev, ccw, VIRTIO_CCW_DOING_SET_VQ | i);
if (err) {
dev_warn(&vcdev->cdev->dev, "SET_VQ failed\n");
goto out_err;
}
info->vq = vq;
vq->priv = info;
/* Save it to our list. */
spin_lock_irqsave(&vcdev->lock, flags);
list_add(&info->node, &vcdev->virtqueues);
spin_unlock_irqrestore(&vcdev->lock, flags);
return vq;
out_err:
if (vq)
vring_del_virtqueue(vq);
if (info) {
if (info->queue)
free_pages_exact(info->queue, size);
kfree(info->info_block);
}
kfree(info);
return ERR_PTR(err);
}
static int virtio_ccw_register_adapter_ind(struct virtio_ccw_device *vcdev,
struct virtqueue *vqs[], int nvqs,
struct ccw1 *ccw)
{
int ret;
struct virtio_thinint_area *thinint_area = NULL;
struct airq_info *info;
thinint_area = kzalloc(sizeof(*thinint_area), GFP_DMA | GFP_KERNEL);
if (!thinint_area) {
ret = -ENOMEM;
goto out;
}
/* Try to get an indicator. */
thinint_area->indicator = get_airq_indicator(vqs, nvqs,
&thinint_area->bit_nr,
&vcdev->airq_info);
if (!thinint_area->indicator) {
ret = -ENOSPC;
goto out;
}
info = vcdev->airq_info;
thinint_area->summary_indicator =
(unsigned long) &info->summary_indicator;
thinint_area->isc = VIRTIO_AIRQ_ISC;
ccw->cmd_code = CCW_CMD_SET_IND_ADAPTER;
ccw->flags = CCW_FLAG_SLI;
ccw->count = sizeof(*thinint_area);
ccw->cda = (__u32)(unsigned long)thinint_area;
ret = ccw_io_helper(vcdev, ccw, VIRTIO_CCW_DOING_SET_IND_ADAPTER);
if (ret) {
if (ret == -EOPNOTSUPP) {
/*
* The host does not support adapter interrupts
* for virtio-ccw, stop trying.
*/
virtio_ccw_use_airq = 0;
pr_info("Adapter interrupts unsupported on host\n");
} else
dev_warn(&vcdev->cdev->dev,
"enabling adapter interrupts = %d\n", ret);
virtio_ccw_drop_indicators(vcdev);
}
out:
kfree(thinint_area);
return ret;
}
static int virtio_ccw_find_vqs(struct virtio_device *vdev, unsigned nvqs,
struct virtqueue *vqs[],
vq_callback_t *callbacks[],
const char *names[])
{
struct virtio_ccw_device *vcdev = to_vc_device(vdev);
unsigned long *indicatorp = NULL;
int ret, i;
struct ccw1 *ccw;
ccw = kzalloc(sizeof(*ccw), GFP_DMA | GFP_KERNEL);
if (!ccw)
return -ENOMEM;
for (i = 0; i < nvqs; ++i) {
vqs[i] = virtio_ccw_setup_vq(vdev, i, callbacks[i], names[i],
ccw);
if (IS_ERR(vqs[i])) {
ret = PTR_ERR(vqs[i]);
vqs[i] = NULL;
goto out;
}
}
ret = -ENOMEM;
/* We need a data area under 2G to communicate. */
indicatorp = kmalloc(sizeof(&vcdev->indicators), GFP_DMA | GFP_KERNEL);
if (!indicatorp)
goto out;
*indicatorp = (unsigned long) &vcdev->indicators;
if (vcdev->is_thinint) {
ret = virtio_ccw_register_adapter_ind(vcdev, vqs, nvqs, ccw);
if (ret)
/* no error, just fall back to legacy interrupts */
vcdev->is_thinint = 0;
}
if (!vcdev->is_thinint) {
/* Register queue indicators with host. */
vcdev->indicators = 0;
ccw->cmd_code = CCW_CMD_SET_IND;
ccw->flags = 0;
ccw->count = sizeof(vcdev->indicators);
ccw->cda = (__u32)(unsigned long) indicatorp;
ret = ccw_io_helper(vcdev, ccw, VIRTIO_CCW_DOING_SET_IND);
if (ret)
goto out;
}
/* Register indicators2 with host for config changes */
*indicatorp = (unsigned long) &vcdev->indicators2;
vcdev->indicators2 = 0;
ccw->cmd_code = CCW_CMD_SET_CONF_IND;
ccw->flags = 0;
ccw->count = sizeof(vcdev->indicators2);
ccw->cda = (__u32)(unsigned long) indicatorp;
ret = ccw_io_helper(vcdev, ccw, VIRTIO_CCW_DOING_SET_CONF_IND);
if (ret)
goto out;
kfree(indicatorp);
kfree(ccw);
return 0;
out:
kfree(indicatorp);
kfree(ccw);
virtio_ccw_del_vqs(vdev);
return ret;
}
static void virtio_ccw_reset(struct virtio_device *vdev)
{
struct virtio_ccw_device *vcdev = to_vc_device(vdev);
struct ccw1 *ccw;
ccw = kzalloc(sizeof(*ccw), GFP_DMA | GFP_KERNEL);
if (!ccw)
return;
/* Zero status bits. */
*vcdev->status = 0;
/* Send a reset ccw on device. */
ccw->cmd_code = CCW_CMD_VDEV_RESET;
ccw->flags = 0;
ccw->count = 0;
ccw->cda = 0;
ccw_io_helper(vcdev, ccw, VIRTIO_CCW_DOING_RESET);
kfree(ccw);
}
static u32 virtio_ccw_get_features(struct virtio_device *vdev)
{
struct virtio_ccw_device *vcdev = to_vc_device(vdev);
struct virtio_feature_desc *features;
int ret, rc;
struct ccw1 *ccw;
ccw = kzalloc(sizeof(*ccw), GFP_DMA | GFP_KERNEL);
if (!ccw)
return 0;
features = kzalloc(sizeof(*features), GFP_DMA | GFP_KERNEL);
if (!features) {
rc = 0;
goto out_free;
}
/* Read the feature bits from the host. */
/* TODO: Features > 32 bits */
features->index = 0;
ccw->cmd_code = CCW_CMD_READ_FEAT;
ccw->flags = 0;
ccw->count = sizeof(*features);
ccw->cda = (__u32)(unsigned long)features;
ret = ccw_io_helper(vcdev, ccw, VIRTIO_CCW_DOING_READ_FEAT);
if (ret) {
rc = 0;
goto out_free;
}
rc = le32_to_cpu(features->features);
out_free:
kfree(features);
kfree(ccw);
return rc;
}
static void virtio_ccw_finalize_features(struct virtio_device *vdev)
{
struct virtio_ccw_device *vcdev = to_vc_device(vdev);
struct virtio_feature_desc *features;
int i;
struct ccw1 *ccw;
ccw = kzalloc(sizeof(*ccw), GFP_DMA | GFP_KERNEL);
if (!ccw)
return;
features = kzalloc(sizeof(*features), GFP_DMA | GFP_KERNEL);
if (!features)
goto out_free;
/* Give virtio_ring a chance to accept features. */
vring_transport_features(vdev);
for (i = 0; i < sizeof(*vdev->features) / sizeof(features->features);
i++) {
int highbits = i % 2 ? 32 : 0;
features->index = i;
features->features = cpu_to_le32(vdev->features[i / 2]
>> highbits);
/* Write the feature bits to the host. */
ccw->cmd_code = CCW_CMD_WRITE_FEAT;
ccw->flags = 0;
ccw->count = sizeof(*features);
ccw->cda = (__u32)(unsigned long)features;
ccw_io_helper(vcdev, ccw, VIRTIO_CCW_DOING_WRITE_FEAT);
}
out_free:
kfree(features);
kfree(ccw);
}
static void virtio_ccw_get_config(struct virtio_device *vdev,
unsigned int offset, void *buf, unsigned len)
{
struct virtio_ccw_device *vcdev = to_vc_device(vdev);
int ret;
struct ccw1 *ccw;
void *config_area;
ccw = kzalloc(sizeof(*ccw), GFP_DMA | GFP_KERNEL);
if (!ccw)
return;
config_area = kzalloc(VIRTIO_CCW_CONFIG_SIZE, GFP_DMA | GFP_KERNEL);
if (!config_area)
goto out_free;
/* Read the config area from the host. */
ccw->cmd_code = CCW_CMD_READ_CONF;
ccw->flags = 0;
ccw->count = offset + len;
ccw->cda = (__u32)(unsigned long)config_area;
ret = ccw_io_helper(vcdev, ccw, VIRTIO_CCW_DOING_READ_CONFIG);
if (ret)
goto out_free;
memcpy(vcdev->config, config_area, sizeof(vcdev->config));
memcpy(buf, &vcdev->config[offset], len);
out_free:
kfree(config_area);
kfree(ccw);
}
static void virtio_ccw_set_config(struct virtio_device *vdev,
unsigned int offset, const void *buf,
unsigned len)
{
struct virtio_ccw_device *vcdev = to_vc_device(vdev);
struct ccw1 *ccw;
void *config_area;
ccw = kzalloc(sizeof(*ccw), GFP_DMA | GFP_KERNEL);
if (!ccw)
return;
config_area = kzalloc(VIRTIO_CCW_CONFIG_SIZE, GFP_DMA | GFP_KERNEL);
if (!config_area)
goto out_free;
memcpy(&vcdev->config[offset], buf, len);
/* Write the config area to the host. */
memcpy(config_area, vcdev->config, sizeof(vcdev->config));
ccw->cmd_code = CCW_CMD_WRITE_CONF;
ccw->flags = 0;
ccw->count = offset + len;
ccw->cda = (__u32)(unsigned long)config_area;
ccw_io_helper(vcdev, ccw, VIRTIO_CCW_DOING_WRITE_CONFIG);
out_free:
kfree(config_area);
kfree(ccw);
}
static u8 virtio_ccw_get_status(struct virtio_device *vdev)
{
struct virtio_ccw_device *vcdev = to_vc_device(vdev);
return *vcdev->status;
}
static void virtio_ccw_set_status(struct virtio_device *vdev, u8 status)
{
struct virtio_ccw_device *vcdev = to_vc_device(vdev);
struct ccw1 *ccw;
ccw = kzalloc(sizeof(*ccw), GFP_DMA | GFP_KERNEL);
if (!ccw)
return;
/* Write the status to the host. */
*vcdev->status = status;
ccw->cmd_code = CCW_CMD_WRITE_STATUS;
ccw->flags = 0;
ccw->count = sizeof(status);
ccw->cda = (__u32)(unsigned long)vcdev->status;
ccw_io_helper(vcdev, ccw, VIRTIO_CCW_DOING_WRITE_STATUS);
kfree(ccw);
}
static struct virtio_config_ops virtio_ccw_config_ops = {
.get_features = virtio_ccw_get_features,
.finalize_features = virtio_ccw_finalize_features,
.get = virtio_ccw_get_config,
.set = virtio_ccw_set_config,
.get_status = virtio_ccw_get_status,
.set_status = virtio_ccw_set_status,
.reset = virtio_ccw_reset,
.find_vqs = virtio_ccw_find_vqs,
.del_vqs = virtio_ccw_del_vqs,
};
/*
* ccw bus driver related functions
*/
static void virtio_ccw_release_dev(struct device *_d)
{
struct virtio_device *dev = container_of(_d, struct virtio_device,
dev);
struct virtio_ccw_device *vcdev = to_vc_device(dev);
kfree(vcdev->status);
kfree(vcdev->config_block);
kfree(vcdev);
}
static int irb_is_error(struct irb *irb)
{
if (scsw_cstat(&irb->scsw) != 0)
return 1;
if (scsw_dstat(&irb->scsw) & ~(DEV_STAT_CHN_END | DEV_STAT_DEV_END))
return 1;
if (scsw_cc(&irb->scsw) != 0)
return 1;
return 0;
}
static struct virtqueue *virtio_ccw_vq_by_ind(struct virtio_ccw_device *vcdev,
int index)
{
struct virtio_ccw_vq_info *info;
unsigned long flags;
struct virtqueue *vq;
vq = NULL;
spin_lock_irqsave(&vcdev->lock, flags);
list_for_each_entry(info, &vcdev->virtqueues, node) {
if (info->vq->index == index) {
vq = info->vq;
break;
}
}
spin_unlock_irqrestore(&vcdev->lock, flags);
return vq;
}
static void virtio_ccw_int_handler(struct ccw_device *cdev,
unsigned long intparm,
struct irb *irb)
{
__u32 activity = intparm & VIRTIO_CCW_INTPARM_MASK;
struct virtio_ccw_device *vcdev = dev_get_drvdata(&cdev->dev);
int i;
struct virtqueue *vq;
struct virtio_driver *drv;
if (!vcdev)
return;
/* Check if it's a notification from the host. */
if ((intparm == 0) &&
(scsw_stctl(&irb->scsw) ==
(SCSW_STCTL_ALERT_STATUS | SCSW_STCTL_STATUS_PEND))) {
/* OK */
}
if (irb_is_error(irb)) {
/* Command reject? */
if ((scsw_dstat(&irb->scsw) & DEV_STAT_UNIT_CHECK) &&
(irb->ecw[0] & SNS0_CMD_REJECT))
vcdev->err = -EOPNOTSUPP;
else
/* Map everything else to -EIO. */
vcdev->err = -EIO;
}
if (vcdev->curr_io & activity) {
switch (activity) {
case VIRTIO_CCW_DOING_READ_FEAT:
case VIRTIO_CCW_DOING_WRITE_FEAT:
case VIRTIO_CCW_DOING_READ_CONFIG:
case VIRTIO_CCW_DOING_WRITE_CONFIG:
case VIRTIO_CCW_DOING_WRITE_STATUS:
case VIRTIO_CCW_DOING_SET_VQ:
case VIRTIO_CCW_DOING_SET_IND:
case VIRTIO_CCW_DOING_SET_CONF_IND:
case VIRTIO_CCW_DOING_RESET:
case VIRTIO_CCW_DOING_READ_VQ_CONF:
case VIRTIO_CCW_DOING_SET_IND_ADAPTER:
vcdev->curr_io &= ~activity;
wake_up(&vcdev->wait_q);
break;
default:
/* don't know what to do... */
dev_warn(&cdev->dev, "Suspicious activity '%08x'\n",
activity);
WARN_ON(1);
break;
}
}
for_each_set_bit(i, &vcdev->indicators,
sizeof(vcdev->indicators) * BITS_PER_BYTE) {
/* The bit clear must happen before the vring kick. */
clear_bit(i, &vcdev->indicators);
barrier();
vq = virtio_ccw_vq_by_ind(vcdev, i);
vring_interrupt(0, vq);
}
if (test_bit(0, &vcdev->indicators2)) {
drv = container_of(vcdev->vdev.dev.driver,
struct virtio_driver, driver);
if (drv && drv->config_changed)
drv->config_changed(&vcdev->vdev);
clear_bit(0, &vcdev->indicators2);
}
}
/*
* We usually want to autoonline all devices, but give the admin
* a way to exempt devices from this.
*/
#define __DEV_WORDS ((__MAX_SUBCHANNEL + (8*sizeof(long) - 1)) / \
(8*sizeof(long)))
static unsigned long devs_no_auto[__MAX_SSID + 1][__DEV_WORDS];
static char *no_auto = "";
module_param(no_auto, charp, 0444);
MODULE_PARM_DESC(no_auto, "list of ccw bus id ranges not to be auto-onlined");
static int virtio_ccw_check_autoonline(struct ccw_device *cdev)
{
struct ccw_dev_id id;
ccw_device_get_id(cdev, &id);
if (test_bit(id.devno, devs_no_auto[id.ssid]))
return 0;
return 1;
}
static void virtio_ccw_auto_online(void *data, async_cookie_t cookie)
{
struct ccw_device *cdev = data;
int ret;
ret = ccw_device_set_online(cdev);
if (ret)
dev_warn(&cdev->dev, "Failed to set online: %d\n", ret);
}
static int virtio_ccw_probe(struct ccw_device *cdev)
{
cdev->handler = virtio_ccw_int_handler;
if (virtio_ccw_check_autoonline(cdev))
async_schedule(virtio_ccw_auto_online, cdev);
return 0;
}
static struct virtio_ccw_device *virtio_grab_drvdata(struct ccw_device *cdev)
{
unsigned long flags;
struct virtio_ccw_device *vcdev;
spin_lock_irqsave(get_ccwdev_lock(cdev), flags);
vcdev = dev_get_drvdata(&cdev->dev);
if (!vcdev || vcdev->going_away) {
spin_unlock_irqrestore(get_ccwdev_lock(cdev), flags);
return NULL;
}
vcdev->going_away = true;
spin_unlock_irqrestore(get_ccwdev_lock(cdev), flags);
return vcdev;
}
static void virtio_ccw_remove(struct ccw_device *cdev)
{
unsigned long flags;
struct virtio_ccw_device *vcdev = virtio_grab_drvdata(cdev);
if (vcdev && cdev->online) {
if (vcdev->device_lost)
virtio_break_device(&vcdev->vdev);
unregister_virtio_device(&vcdev->vdev);
spin_lock_irqsave(get_ccwdev_lock(cdev), flags);
dev_set_drvdata(&cdev->dev, NULL);
spin_unlock_irqrestore(get_ccwdev_lock(cdev), flags);
}
cdev->handler = NULL;
}
static int virtio_ccw_offline(struct ccw_device *cdev)
{
unsigned long flags;
struct virtio_ccw_device *vcdev = virtio_grab_drvdata(cdev);
if (!vcdev)
return 0;
if (vcdev->device_lost)
virtio_break_device(&vcdev->vdev);
unregister_virtio_device(&vcdev->vdev);
spin_lock_irqsave(get_ccwdev_lock(cdev), flags);
dev_set_drvdata(&cdev->dev, NULL);
spin_unlock_irqrestore(get_ccwdev_lock(cdev), flags);
return 0;
}
static int virtio_ccw_online(struct ccw_device *cdev)
{
int ret;
struct virtio_ccw_device *vcdev;
unsigned long flags;
vcdev = kzalloc(sizeof(*vcdev), GFP_KERNEL);
if (!vcdev) {
dev_warn(&cdev->dev, "Could not get memory for virtio\n");
ret = -ENOMEM;
goto out_free;
}
vcdev->config_block = kzalloc(sizeof(*vcdev->config_block),
GFP_DMA | GFP_KERNEL);
if (!vcdev->config_block) {
ret = -ENOMEM;
goto out_free;
}
vcdev->status = kzalloc(sizeof(*vcdev->status), GFP_DMA | GFP_KERNEL);
if (!vcdev->status) {
ret = -ENOMEM;
goto out_free;
}
vcdev->is_thinint = virtio_ccw_use_airq; /* at least try */
vcdev->vdev.dev.parent = &cdev->dev;
vcdev->vdev.dev.release = virtio_ccw_release_dev;
vcdev->vdev.config = &virtio_ccw_config_ops;
vcdev->cdev = cdev;
init_waitqueue_head(&vcdev->wait_q);
INIT_LIST_HEAD(&vcdev->virtqueues);
spin_lock_init(&vcdev->lock);
spin_lock_irqsave(get_ccwdev_lock(cdev), flags);
dev_set_drvdata(&cdev->dev, vcdev);
spin_unlock_irqrestore(get_ccwdev_lock(cdev), flags);
vcdev->vdev.id.vendor = cdev->id.cu_type;
vcdev->vdev.id.device = cdev->id.cu_model;
ret = register_virtio_device(&vcdev->vdev);
if (ret) {
dev_warn(&cdev->dev, "Failed to register virtio device: %d\n",
ret);
goto out_put;
}
return 0;
out_put:
spin_lock_irqsave(get_ccwdev_lock(cdev), flags);
dev_set_drvdata(&cdev->dev, NULL);
spin_unlock_irqrestore(get_ccwdev_lock(cdev), flags);
put_device(&vcdev->vdev.dev);
return ret;
out_free:
if (vcdev) {
kfree(vcdev->status);
kfree(vcdev->config_block);
}
kfree(vcdev);
return ret;
}
static int virtio_ccw_cio_notify(struct ccw_device *cdev, int event)
{
int rc;
struct virtio_ccw_device *vcdev = dev_get_drvdata(&cdev->dev);
/*
* Make sure vcdev is set
* i.e. set_offline/remove callback not already running
*/
if (!vcdev)
return NOTIFY_DONE;
switch (event) {
case CIO_GONE:
vcdev->device_lost = true;
rc = NOTIFY_DONE;
break;
default:
rc = NOTIFY_DONE;
break;
}
return rc;
}
static struct ccw_device_id virtio_ids[] = {
{ CCW_DEVICE(0x3832, 0) },
{},
};
MODULE_DEVICE_TABLE(ccw, virtio_ids);
static struct ccw_driver virtio_ccw_driver = {
.driver = {
.owner = THIS_MODULE,
.name = "virtio_ccw",
},
.ids = virtio_ids,
.probe = virtio_ccw_probe,
.remove = virtio_ccw_remove,
.set_offline = virtio_ccw_offline,
.set_online = virtio_ccw_online,
.notify = virtio_ccw_cio_notify,
.int_class = IRQIO_VIR,
};
static int __init pure_hex(char **cp, unsigned int *val, int min_digit,
int max_digit, int max_val)
{
int diff;
diff = 0;
*val = 0;
while (diff <= max_digit) {
int value = hex_to_bin(**cp);
if (value < 0)
break;
*val = *val * 16 + value;
(*cp)++;
diff++;
}
if ((diff < min_digit) || (diff > max_digit) || (*val > max_val))
return 1;
return 0;
}
static int __init parse_busid(char *str, unsigned int *cssid,
unsigned int *ssid, unsigned int *devno)
{
char *str_work;
int rc, ret;
rc = 1;
if (*str == '\0')
goto out;
str_work = str;
ret = pure_hex(&str_work, cssid, 1, 2, __MAX_CSSID);
if (ret || (str_work[0] != '.'))
goto out;
str_work++;
ret = pure_hex(&str_work, ssid, 1, 1, __MAX_SSID);
if (ret || (str_work[0] != '.'))
goto out;
str_work++;
ret = pure_hex(&str_work, devno, 4, 4, __MAX_SUBCHANNEL);
if (ret || (str_work[0] != '\0'))
goto out;
rc = 0;
out:
return rc;
}
static void __init no_auto_parse(void)
{
unsigned int from_cssid, to_cssid, from_ssid, to_ssid, from, to;
char *parm, *str;
int rc;
str = no_auto;
while ((parm = strsep(&str, ","))) {
rc = parse_busid(strsep(&parm, "-"), &from_cssid,
&from_ssid, &from);
if (rc)
continue;
if (parm != NULL) {
rc = parse_busid(parm, &to_cssid,
&to_ssid, &to);
if ((from_ssid > to_ssid) ||
((from_ssid == to_ssid) && (from > to)))
rc = -EINVAL;
} else {
to_cssid = from_cssid;
to_ssid = from_ssid;
to = from;
}
if (rc)
continue;
while ((from_ssid < to_ssid) ||
((from_ssid == to_ssid) && (from <= to))) {
set_bit(from, devs_no_auto[from_ssid]);
from++;
if (from > __MAX_SUBCHANNEL) {
from_ssid++;
from = 0;
}
}
}
}
static int __init virtio_ccw_init(void)
{
/* parse no_auto string before we do anything further */
no_auto_parse();
return ccw_driver_register(&virtio_ccw_driver);
}
module_init(virtio_ccw_init);
static void __exit virtio_ccw_exit(void)
{
int i;
ccw_driver_unregister(&virtio_ccw_driver);
for (i = 0; i < MAX_AIRQ_AREAS; i++)
destroy_airq_info(airq_areas[i]);
}
module_exit(virtio_ccw_exit);
| 25.101992 | 78 | 0.706091 | [
"vector"
] |
d2c2555fe08241fd7284fb636276cf457a4ce9c5 | 45,427 | c | C | src/z80asm.stable/z80asm.c | meesokim/z88dk | 5763c7778f19a71d936b3200374059d267066bb2 | [
"ClArtistic"
] | 1 | 2020-09-15T08:35:49.000Z | 2020-09-15T08:35:49.000Z | src/z80asm.stable/z80asm.c | meesokim/z88dk | 5763c7778f19a71d936b3200374059d267066bb2 | [
"ClArtistic"
] | null | null | null | src/z80asm.stable/z80asm.c | meesokim/z88dk | 5763c7778f19a71d936b3200374059d267066bb2 | [
"ClArtistic"
] | null | null | null |
/*
ZZZZZZZZZZZZZZZZZZZZ 8888888888888 00000000000
ZZZZZZZZZZZZZZZZZZZZ 88888888888888888 0000000000000
ZZZZZ 888 888 0000 0000
ZZZZZ 88888888888888888 0000 0000
ZZZZZ 8888888888888 0000 0000 AAAAAA SSSSSSSSSSS MMMM MMMM
ZZZZZ 88888888888888888 0000 0000 AAAAAAAA SSSS MMMMMM MMMMMM
ZZZZZ 8888 8888 0000 0000 AAAA AAAA SSSSSSSSSSS MMMMMMMMMMMMMMM
ZZZZZ 8888 8888 0000 0000 AAAAAAAAAAAA SSSSSSSSSSS MMMM MMMMM MMMM
ZZZZZZZZZZZZZZZZZZZZZ 88888888888888888 0000000000000 AAAA AAAA SSSSS MMMM MMMM
ZZZZZZZZZZZZZZZZZZZZZ 8888888888888 00000000000 AAAA AAAA SSSSSSSSSSS MMMM MMMM
Copyright (C) Gunther Strube, InterLogic 1993-99
*/
/* $Header: /cvsroot/z88dk/z88dk/src/z80asm.stable/z80asm.c,v 1.1 2011/09/27 19:16:55 dom Exp $ */
/* $History: Z80ASM.C $ */
/* */
/* ***************** Version 22 ***************** */
/* User: Gbs Date: 30-01-00 Time: 12:49 */
/* Updated in $/Z80asm */
/* New option -M implemented, which defines arbitrary object file name */
/* extension. */
/* */
/* ***************** Version 21 ***************** */
/* User: Gbs Date: 26-01-00 Time: 22:12 */
/* Updated in $/Z80asm */
/* "V1.0.14" version text changes. */
/* */
/* ***************** Version 20 ***************** */
/* User: Gbs Date: 30-09-99 Time: 22:39 */
/* Updated in $/Z80asm */
/* CALL_PKG hard coded macro implemented for Garry Lancaster's Package */
/* System. */
/* */
/* ***************** Version 18 ***************** */
/* User: Gbs Date: 6-06-99 Time: 20:07 */
/* Updated in $/Z80asm */
/* "PC" program counter changed to long (from unsigned short). */
/* */
/* ***************** Version 16 ***************** */
/* User: Gbs Date: 6-06-99 Time: 12:13 */
/* Updated in $/Z80asm */
/* Added Ascii Art "Z80asm" at top of source file. */
/* '#' changed to '@' in default help page. */
/* ReportError() changed to display the platform specific MAXCODESIZE */
/* value when the maximum code generation size has been reached. */
/* */
/* ***************** Version 11 ***************** */
/* User: Gbs Date: 30-05-99 Time: 1:04 */
/* Updated in $/Z80asm */
/* Redundant system include files removed. */
/* Explicitly specified file source file extension automaticlly removed. */
/* Slight changes to default help page. */
/* */
/* ***************** Version 10 ***************** */
/* User: Gbs Date: 2-05-99 Time: 18:12 */
/* Updated in $/Z80asm */
/* New function, ReportIOError(). */
/* ReportError() improved to display to <stderr> when no error filename is */
/* available and to display the name of the module in which the error */
/* occurred (this is especially useful during linking errors). */
/* */
/* ***************** Version 8 ***************** */
/* User: Gbs Date: 17-04-99 Time: 0:30 */
/* Updated in $/Z80asm */
/* New GNU programming style C format. Improved ANSI C coding style */
/* eliminating previous compiler warnings. New -o option. Asm sources file */
/* now parsed even though any line feed standards (CR,LF or CRLF) are */
/* used. */
/* */
/* ***************** Version 7 ***************** */
/* User: Gbs Date: 7-03-99 Time: 13:14 */
/* Updated in $/Z80asm */
/* Program terminates with 1 if error occurs, otherwise 0 if all went OK. */
/* (Dominic Morris - djm@jb.man.ac.uk) */
/* */
/* ***************** Version 5 ***************** */
/* User: Gbs Date: 6-09-98 Time: 12:53 */
/* Updated in $/Z80asm */
/* -o logic replaced with -e<ext> option. This makes Z80asm completely */
/* configurable on which filename extension to use for source files. */
/* */
/* ***************** Version 3 ***************** */
/* User: Gbs Date: 4-09-98 Time: 0:11 */
/* Updated in $/Z80asm */
/* ".opt" source files now parsed in stead of ".asm" files using new -o */
/* option. */
/* */
/* ***************** Version 2 ***************** */
/* User: Gbs Date: 20-06-98 Time: 15:00 */
/* Updated in $/Z80asm */
/* SourceSafe Version History comment block added. */
/* program version strings updated, "V1.0.3". */
/* All exit(-1) changed to exit(0) - djm 26/6/98 */
/* Cleaned up info so doesn't linewrap on Amiga */
/* Oops, screw up! exit(0) (was exit(-1)) should be exit(1) - djm 29/2/99 */
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <ctype.h>
#include "config.h"
#include "symbol.h"
#include "z80asm.h"
#ifdef WIN32
#define snprintf _snprintf
#endif
/* external functions */
char *AllocIdentifier (size_t len);
void RemovePfixlist (struct expr *pfixexpr);
void Z80pass1 (void);
void Z80pass2 (void);
void CreateLib (void);
void LinkModules (void);
void DeclModuleName (void);
void DeclSymGlobal (void);
void FreeSym (symbol * node);
void CreateDeffile (void);
void WriteGlobal (symbol * node);
void WriteMapFile (void);
void CreateBinFile (void);
struct sourcefile *Newfile (struct sourcefile *curfile, char *fname);
enum symbols GetSym (void);
long GetConstant (char *evalerr);
long ReadLong (FILE * fileid);
int cmpidstr (symbol * kptr, symbol * p);
int DefineSymbol (char *identifier, long value, unsigned char symboltype);
int DefineDefSym (char *ident, long value, unsigned char symtype, avltree ** root);
symbol *CreateSymbol (char *identifier, long value, unsigned char symboltype, struct module *symowner);
/* local functions */
void prompt (void);
void usage (void);
void ReportError (char *filename, int linenr, int errnum);
void ReportIOError (char *filename);
void SetAsmFlag (char *flagid);
void WriteHeader (void);
void ReleaseFile (struct sourcefile *srcfile);
void ReleaseLibraries (void);
void ReleaseOwnedFile (struct usedfile *ownedfile);
void ReleaseModules (void);
void ReleaseFilenames (void);
void ReleaseExprns (struct expression *express);
void CloseFiles (void);
void CreateLibfile (char *libfilename);
int AssembleSourceFile (void);
int TestAsmFile (void);
int GetModuleSize (void);
symbol *createsym (symbol * symptr);
struct modules *AllocModuleHdr (void);
struct module *AllocModule (void);
struct liblist *AllocLibHdr (void);
struct libfile *AllocLib (void);
struct module *NewModule (void);
struct libfile *NewLibrary (void);
struct expression *AllocExprHdr (void);
struct JRPC_Hdr *AllocJRaddrHdr (void);
#ifdef QDOS
#include <qdos.h>
char _prog_name[] = "Z80asm";
char _version[] = "1.0.31";
char _copyright[] = "\x7f InterLogic 1993-2009";
void consetup_title ();
void (*_consetup) () = consetup_title;
int (*_readkbd) (chanid_t, timeout_t, char *) = readkbd_move;
struct WINDOWDEF _condetails =
{2, 1, 0, 7, 484, 256, 0, 0};
#endif
#ifdef AMIGA
char amiver[] = "$VER: z80asm v1.0.31, (c) InterLogic 1993-2000";
#endif
char copyrightmsg[] = "Z80 Module Assembler V1.0.31 (13.6.2009), (c) InterLogic 1993-2009";
FILE *z80asmfile, *listfile, *errfile, *objfile, *mapfile, *modsrcfile, *deffile, *libfile;
long clineno;
static int include_dir_num = 0;
static char **include_dir = NULL;
static int lib_dir_num = 0;
static char **lib_dir = NULL;
char *errmsg[] =
{"File open/read error", /* 0 */
"Syntax error", /* 1 */
"Symbol not defined", /* 2 */
"Not enough memory", /* 3 */
"Integer out of range", /* 4 */
"Syntax error in expression", /* 5 */
"Right bracket missing", /* 6 */
"Out of range", /* 7 */
"Source filename missing", /* 8 */
"Illegal option", /* 9 */
"Unknown identifier", /* 10 */
"Illegal identifier", /* 11 */
"Max. code size of %ld bytes reached", /* 12 */
"errors occurred during assembly", /* 13 */
"Symbol already defined", /* 14 */
"Module name already defined", /* 15 */
"Module name not defined", /* 16 */
"Symbol already declared local", /* 17 */
"Symbol already declared global", /* 18 */
"Symbol already declared external", /* 19 */
"No command line arguments", /* 20 */
"Illegal source filename", /* 21 */
"Symbol declared global in another module", /* 22 */
"Re-declaration not allowed", /* 23 */
"ORG already defined", /* 24 */
"Relative jump address must be local", /* 25 */
"Not an object file", /* 26 */
"Reserved name", /* 27 */
"Couldn't open library file", /* 28 */
"Not a library file", /* 29 */
"Environment variable not defined", /* 30 */
"Cannot include file recursively", /* 31 */
};
enum symbols sym, ssym[] =
{space, strconq, dquote, squote, semicolon, comma, fullstop,
lparen, lcurly, lsquare, rsquare, rcurly, rparen, plus, minus, multiply, divi, mod, power,
assign, bin_and, bin_or, bin_xor, less, greater, log_not, constexpr};
enum flag pass1, listing, listing_CPY, symtable, z80bin, writeline, mapref, globaldef, datestamp, ti83plus, sdcc_hacks;
enum flag deforigin, verbose, ASMERROR, EOL, symfile, library, createlibrary, autorelocate;
enum flag smallc_source, codesegment, expl_binflnm, clinemode, swapIXIY, force_xlib;
int cpu_type = CPU_Z80;
int ASSEMBLE_ERROR, ERRORS, TOTALERRORS, PAGENR, LINENR;
long TOTALLINES;
int sourcefile_open;
char PAGELEN;
int TAB_DIST = 8, COLUMN_WIDTH;
char separators[] = " &\"\';,.({[]})+-*/%^=~|:<>!#:";
char line[255], stringconst[255], ident[FILENAME_MAX+1];
char *srcfilename, *lstfilename, *objfilename, *errfilename, *libfilename;
#ifdef QDOS
char asmext[] = "_asm", lstext[] = "_lst", objext_templ[] = "_obj", defext[] = "_def", errext[] = "_err";
char binext[] = "_bin", libext[] = "_lib", symext[] = "_sym", mapext[] = "_map";
char segmbinext[] = "_bn0";
#else
char asmext[] = ".asm", lstext[] = ".lst", objext_templ[] = ".obj", defext[] = ".def", binext[] = ".bin";
char mapext[] = ".map", errext[] = ".err", symext[] = ".sym", libext[] = ".lib";
char segmbinext[] = ".bn0";
#endif
char srcext[5]; /* contains default source file extension */
char objext[5]; /* contains default object file extension */
char binfilename[64]; /* -o explicit filename buffer */
char Z80objhdr[] = "Z80RMF01";
char objhdrprefix[] = "oomodnexprnamelibnmodc";
char Z80libhdr[] = "Z80LMF01";
unsigned char reloc_routine[] =
"\x08\xD9\xFD\xE5\xE1\x01\x49\x00\x09\x5E\x23\x56\xD5\x23\x4E\x23"
"\x46\x23\xE5\x09\x44\x4D\xE3\x7E\x23\xB7\x20\x06\x5E\x23\x56\x23"
"\x18\x03\x16\x00\x5F\xE3\x19\x5E\x23\x56\xEB\x09\xEB\x72\x2B\x73"
"\xD1\xE3\x2B\x7C\xB5\xE3\xD5\x20\xDD\xF1\xF1\xFD\x36\x00\xC3\xFD"
"\x71\x01\xFD\x70\x02\xD9\x08\xFD\xE9";
size_t sizeof_relocroutine = 73;
char *reloctable = NULL, *relocptr = NULL;
long listfileptr;
unsigned char *codearea, *codeptr;
size_t CODESIZE;
long PC, oldPC; /* Program Counter */
unsigned short DEFVPC; /* DEFVARS address counter */
size_t EXPLICIT_ORIGIN; /* origin defined from command line */
time_t asmtime; /* time of assembly in seconds */
char *date; /* pointer to datestring calculated from asmtime */
struct modules *modulehdr;
struct module *CURRENTMODULE;
struct liblist *libraryhdr;
avltree *globalroot, *staticroot;
int
AssembleSourceFile (void)
{
char *dotptr;
if ((errfile = fopen (errfilename, "w")) == NULL)
{ /* Create error file */
ReportIOError (errfilename);
return 0;
}
if (listing_CPY || symfile)
{
if ((listfile = fopen (lstfilename, "w+")) != NULL)
{ /* Create LIST or SYMBOL file */
PAGENR = 0;
LINENR = 6;
WriteHeader (); /* Begin list file with a header */
listfileptr = ftell (listfile); /* Get file pos. of next line in list file */
}
else
{
ReportIOError (lstfilename);
return 0;
}
}
if ((objfile = fopen (objfilename, "w+b")) != NULL)
{ /* Create relocatable object file */
fwrite (Z80objhdr, sizeof (char), strlen (Z80objhdr), objfile);
fwrite (objhdrprefix, sizeof (char), strlen (objhdrprefix), objfile);
}
else
{
ReportIOError (objfilename);
return 0;
}
PC = oldPC = 0;
copy (staticroot, &CURRENTMODULE->localroot, (int (*)()) cmpidstr, (void *(*)()) createsym);
if (DefineDefSym (ASSEMBLERPC, PC, 0, &globalroot) == 0)
{ /* Create standard 'ASMPC' identifier */
ReportError (NULL, 0, 3);
return 0;
}
if (verbose)
printf ("Assembling '%s'...\nPass1...\n", srcfilename);
pass1 = ON;
Z80pass1 ();
pass1 = OFF; /* GetSymPtr will only generate page references in Pass1 (if listing is ON) */
/*
* Source file no longer needed (file could already have been closed, if fatal error occurred during INCLUDE
* processing).
*/
if (sourcefile_open)
{
fclose (z80asmfile);
z80asmfile = NULL;
}
if (CURRENTMODULE->mname == NULL) { /* Module name must be defined */
dotptr = strrchr(srcfilename,'/');
if ( dotptr == NULL )
dotptr = strrchr(srcfilename,'\\');
if ( dotptr == NULL )
dotptr = srcfilename-1;
strcpy(ident,dotptr+1);
dotptr = strchr(ident,asmext[0]);
if ( dotptr )
*dotptr = 0;
sym = name;
dotptr = ident;
while ( *dotptr )
{
*dotptr = toupper(*dotptr);
dotptr++;
}
DeclModuleName();
/* ReportError (CURRENTFILE->fname, 0, 16); */
}
if (ERRORS == 0)
{
if (verbose)
puts ("Pass2...");
Z80pass2 ();
}
if (listing_CPY || symfile)
{
fseek (listfile, 0, SEEK_END);
fputc (12, listfile); /* end listing with a FF */
fclose (listfile);
listfile = NULL;
if (ERRORS)
remove (lstfilename); /* remove incomplete list file */
}
fclose (objfile);
objfile = NULL;
if (ERRORS)
remove (objfilename); /* remove incomplete object file */
if (errfile != NULL)
{
fclose (errfile);
errfile = NULL;
if (ERRORS == 0 && errfilename != NULL)
remove (errfilename); /* remove empty error file */
}
if (globaldef)
{
fputc ('\n', deffile); /* separate DEFC lines for each module */
inorder (globalroot, (void (*)()) WriteGlobal);
}
deleteall (&CURRENTMODULE->localroot, (void (*)()) FreeSym);
deleteall (&CURRENTMODULE->notdeclroot, (void (*)()) FreeSym);
deleteall (&globalroot, (void (*)()) FreeSym);
return 1;
}
void
ReleaseFilenames (void)
{
if (srcfilename != NULL) free (srcfilename);
if (lstfilename != NULL) free (lstfilename);
if (objfilename != NULL) free (objfilename);
if (errfilename != NULL) free (errfilename);
srcfilename = lstfilename = objfilename = errfilename = NULL;
}
void
CloseFiles (void)
{
if (z80asmfile != NULL) fclose (z80asmfile);
if (listfile != NULL) fclose (listfile);
if (objfile != NULL) fclose (objfile);
if (errfile != NULL) fclose (errfile);
z80asmfile = listfile = objfile = errfile = NULL;
}
int
TestAsmFile (void)
{
struct stat afile, ofile;
if (datestamp)
{ /* assemble only updated files */
if (stat (srcfilename, &afile) == -1)
return GetModuleSize (); /* source file not available... */
else if (stat (objfilename, &ofile) != -1)
if (afile.st_mtime <= ofile.st_mtime)
return GetModuleSize (); /* source is older than object module */
}
if ((z80asmfile = fopen (srcfilename, "rb")) == NULL)
{ /* Open source file */
ReportIOError (srcfilename); /* Object module is not found or */
return -1; /* source is has recently been updated */
}
sourcefile_open = 1;
return 1; /* assemble if no datestamp check */
}
int
GetModuleSize (void)
{
char fheader[9];
long fptr_modcode, fptr_modname;
long highbyte, lowbyte;
size_t size;
if ((objfile = fopen (objfilename, "rb")) != NULL)
{ /* open relocatable object file */
fread (fheader, 1U, 8U, objfile); /* read first 8 chars from file into array */
fheader[8] = '\0';
if (strcmp (fheader, Z80objhdr) != 0)
{ /* compare header of file */
ReportError (objfilename, 0, 26); /* not an object file */
fclose (objfile);
objfile = NULL;
return -1;
}
fseek (objfile, 8 + 2, SEEK_SET); /* set file pointer to point at module name */
fptr_modname = ReadLong (objfile); /* get file pointer to module name */
fseek (objfile, fptr_modname, SEEK_SET); /* set file pointer to module name */
size = fgetc (objfile);
fread (line, sizeof (char), size, objfile); /* read module name */
line[size] = '\0';
if ((CURRENTMODULE->mname = AllocIdentifier (size + 1)) == NULL)
{
ReportError (NULL, 0, 3);
return -1;
}
else
strcpy (CURRENTMODULE->mname, line);
fseek (objfile, 26, SEEK_SET); /* set file pointer to point at module code pointer */
fptr_modcode = ReadLong (objfile); /* get file pointer to module code */
if (fptr_modcode != -1)
{
fseek (objfile, fptr_modcode, SEEK_SET); /* set file pointer to module code */
lowbyte = fgetc (objfile);
highbyte = fgetc (objfile);
size = lowbyte + highbyte * 256;
if (CURRENTMODULE->startoffset + size > MAXCODESIZE)
ReportError (objfilename, 0, 12);
else
CODESIZE += size;
}
fclose (objfile);
return 0;
}
else
{
ReportIOError (objfilename);
return -1;
}
}
void
CreateLibfile (char *filename)
{
size_t l;
l = strlen (filename);
if (l)
{
if (strcmp (filename + (l - 4), libext) != 0)
{ /* 'lib' extension not specified */
if ((libfilename = AllocIdentifier (l + 4 + 1)) != NULL)
{
strcpy (libfilename, filename);
strcat (libfilename, libext); /* add '_lib' extension */
}
else
{
ReportError (NULL, 0, 3);
return;
}
}
else
{
if ((libfilename = AllocIdentifier (l + 1)) != NULL) /* 'lib' extension specified */
strcpy (libfilename, filename);
else
{
ReportError (NULL, 0, 3);
return;
}
}
}
else
{
if ((filename = getenv ("Z80_STDLIB")) != NULL)
{
if ((libfilename = AllocIdentifier (strlen (filename))) != NULL)
strcpy (libfilename, filename);
else
{
ReportError (NULL, 0, 3);
return;
}
}
else
{
ReportError (NULL, 0, 30);
return;
}
}
if ((libfile = fopen (libfilename, "w+b")) == NULL)
{ /* create library as BINARY file */
free (libfilename);
libfilename = NULL;
ReportError (libfilename, 0, 28);
}
else
{
createlibrary = ON;
fwrite (Z80libhdr, sizeof (char), 8U, libfile); /* write library header */
}
}
void
GetLibfile (char *filename)
{
char tempbuf[FILENAME_MAX+1];
struct libfile *newlib;
char *ptr;
char *ext = "";
char *f, fheader[9];
int l;
if ((newlib = NewLibrary ()) == NULL)
{
ReportError (NULL, 0, 3);
return;
}
l = strlen (filename);
if (l)
{
if (strcmp (filename + (l - 4), libext) != 0)
{
ext = libext;
}
snprintf(tempbuf, sizeof(tempbuf),"%s%s",filename, ext);
ptr = SearchFile(tempbuf, 0);
l = strlen(ptr);
if ((f = AllocIdentifier (l + 1)) != NULL)
{
strcpy (f, ptr);
}
else
{
ReportError (NULL, 0, 3);
return;
}
}
else
{
filename = getenv ("Z80_STDLIB");
if (filename != NULL)
{
if ((f = AllocIdentifier (strlen (filename))) != NULL)
strcpy (f, filename);
else
{
ReportError (NULL, 0, 3);
return;
}
}
else
{
ReportError (NULL, 0, 30);
return;
}
}
newlib->libfilename = f;
if ((z80asmfile = fopen (f, "rb")) == NULL)
{ /* Does file exist? */
ReportError (f, 0, 28);
return;
}
else
{
fread (fheader, 1U, 8U, z80asmfile); /* read first 8 chars from file into array */
fheader[8] = '\0';
}
if (strcmp (fheader, Z80libhdr) != 0) /* compare header of file */
ReportError (f, 0, 29); /* not a library file */
else
library = ON;
fclose (z80asmfile);
z80asmfile = NULL;
}
void
SetAsmFlag (char *flagid)
{
int i;
if (*flagid == 'e')
{
smallc_source = ON; /* use ".xxx" as source file in stead of ".asm" */
srcext[0] = '.';
strncpy ((srcext + 1), (flagid + 1), 3); /* copy argument string */
srcext[4] = '\0'; /* max. 3 letters extension */
return;
}
/* djm: mod to get .o files produced instead of .obj */
/* gbs: extended to use argument as definition, e.g. -Mo, which defines .o extension */
if (*flagid == 'M')
{
strncpy ((objext + 1), (flagid + 1), 3); /* copy argument string (append after '.') */
objext[4] = '\0'; /* max. 3 letters extension */
}
/** Check whether this is for the RCM2000/RCM3000 series of Z80-like CPU's */
if (strcmp (flagid, "RCMX000") == 0)
{
cpu_type = CPU_RCM2000;
return;
}
/* check weather to use an RST or CALL when Invoke is used */
if (strcmp(flagid, "plus") == 0 )
{
ti83plus = ON;
return;
}
/* (stefano) IX and IY swap option */
if (strcmp (flagid, "IXIY") == 0)
{
swapIXIY = ON;
return;
}
/* djm turn on c line mode to report line number of C source */
if (strcmp(flagid, "C") == 0 )
{
clinemode = ON;
return;
}
if (strcmp(flagid, "c") == 0)
{
codesegment = ON;
return;
}
if (strcmp (flagid, "a") == 0)
{
z80bin = ON;
datestamp = ON;
return;
}
if ( strcmp(flagid, "sdcc") == 0 )
{
sdcc_hacks = ON;
return;
}
if ( strcmp(flagid, "forcexlib") == 0 )
{
force_xlib = ON;
return;
}
if (strcmp (flagid, "l") == 0)
{
listing_CPY = listing = ON;
if (symtable)
symfile = OFF;
return;
}
if (strcmp (flagid, "nl") == 0)
{
listing_CPY = listing = OFF;
if (symtable)
symfile = ON;
return;
}
if (strcmp (flagid, "s") == 0)
{
symtable = ON;
if (listing_CPY)
symfile = OFF;
else
symfile = ON;
return;
}
if (strcmp (flagid, "ns") == 0)
{
symtable = symfile = OFF;
return;
}
if (strcmp (flagid, "nb") == 0)
{
z80bin = OFF;
mapref = OFF;
return;
}
if (strcmp (flagid, "b") == 0)
{
z80bin = ON; /* perform address relocation & linking */
return;
}
if (strcmp (flagid, "v") == 0)
{
verbose = ON; /* perform address relocation & linking */
return;
}
if (strcmp (flagid, "nv") == 0)
{
verbose = OFF; /* perform address relocation & linking */
return;
}
if (strcmp (flagid, "d") == 0)
{
datestamp = ON; /* assemble only if source > object file */
return;
}
if (strcmp (flagid, "nd") == 0)
{
datestamp = OFF;
return;
}
if (strcmp (flagid, "m") == 0)
{
mapref = ON;
return;
}
if (strcmp (flagid, "g") == 0)
{
globaldef = ON;
return;
}
if (strcmp (flagid, "ng") == 0)
{
globaldef = OFF;
return;
}
if (strcmp (flagid, "nm") == 0)
{
mapref = OFF;
return;
}
if (strcmp (flagid, "nR") == 0)
{
autorelocate = OFF;
return;
}
if (*flagid == 'h')
{
usage();
exit(1);
}
if (*flagid == 'i')
{
GetLibfile ((flagid + 1));
return;
}
if (*flagid == 'x')
{
CreateLibfile ((flagid + 1));
return;
}
if (*flagid == 'r')
{
sscanf (flagid + 1, "%x", &EXPLICIT_ORIGIN);
deforigin = ON; /* explicit origin has been defined */
return;
}
if (*flagid == 'o')
{
sscanf (flagid + 1, "%s", binfilename); /* store explicit filename for .BIN file */
expl_binflnm = ON;
return;
}
if (*flagid == 'R')
{
autorelocate = ON;
return;
}
if (*flagid == 't')
{
sscanf (flagid + 1, "%d", &TAB_DIST);
return;
}
if (*flagid == 'I')
{
i = include_dir_num++;
include_dir = realloc(include_dir, include_dir_num * sizeof(include_dir[0]));
include_dir[i] = strdup(flagid+1);
}
if (*flagid == 'L')
{
i = lib_dir_num++;
lib_dir = realloc(lib_dir, lib_dir_num * sizeof(lib_dir[0]));
lib_dir[i] = strdup(flagid+1);
}
if (*flagid == 'D')
{
strcpy (ident, (flagid + 1)); /* copy argument string */
if (!isalpha (ident[0]))
{
ReportError (NULL, 0, 11); /* symbol must begin with alpha */
return;
}
i = 0;
while (ident[i] != '\0')
{
if (strchr (separators, ident[i]) == NULL)
{
if (!isalnum (ident[i]))
{
if (ident[i] != '_')
{
ReportError (NULL, 0, 11); /* illegal char in identifier */
return;
}
else
ident[i] = '_'; /* underscore in identifier */
}
else
ident[i] = toupper (ident[i]);
}
else
{
ReportError (NULL, 0, 11); /* illegal char in identifier */
return;
}
++i;
}
DefineDefSym (ident, 1, 0, &staticroot);
}
}
struct module *
NewModule (void)
{
struct module *newm;
if (modulehdr == NULL)
{
if ((modulehdr = AllocModuleHdr ()) == NULL)
return NULL;
else
{
modulehdr->first = NULL;
modulehdr->last = NULL; /* Module header initialised */
}
}
if ((newm = AllocModule ()) == NULL)
return NULL;
else
{
newm->nextmodule = NULL;
newm->mname = NULL;
newm->startoffset = CODESIZE;
newm->origin = 65535;
newm->cfile = NULL;
newm->localroot = NULL;
newm->notdeclroot = NULL;
if ((newm->mexpr = AllocExprHdr ()) != NULL)
{ /* Allocate room for expression header */
newm->mexpr->firstexpr = NULL;
newm->mexpr->currexpr = NULL; /* Module expression header initialised */
}
else
{
free (newm); /* remove partial module definition */
return NULL; /* No room for header */
}
if ((newm->JRaddr = AllocJRaddrHdr ()) != NULL)
{
newm->JRaddr->firstref = NULL;
newm->JRaddr->lastref = NULL; /* Module JRaddr list header initialised */
}
else
{
free (newm->mexpr); /* remove expression header */
free (newm); /* remove partial module definition */
return NULL; /* No room for header */
}
}
if (modulehdr->first == NULL)
{
modulehdr->first = newm;
modulehdr->last = newm; /* First module in list */
}
else
{
modulehdr->last->nextmodule = newm; /* current/last module points now at new current */
modulehdr->last = newm; /* pointer to current module updated */
}
return newm;
}
struct libfile *
NewLibrary (void)
{
struct libfile *newl;
if (libraryhdr == NULL)
{
if ((libraryhdr = AllocLibHdr ()) == NULL)
return NULL;
else
{
libraryhdr->firstlib = NULL;
libraryhdr->currlib = NULL; /* Library header initialised */
}
}
if ((newl = AllocLib ()) == NULL)
return NULL;
else
{
newl->nextlib = NULL;
newl->libfilename = NULL;
newl->nextobjfile = -1;
}
if (libraryhdr->firstlib == NULL)
{
libraryhdr->firstlib = newl;
libraryhdr->currlib = newl; /* First library in list */
}
else
{
libraryhdr->currlib->nextlib = newl; /* current/last library points now at new current */
libraryhdr->currlib = newl; /* pointer to current module updated */
}
return newl;
}
void
ReleaseModules (void)
{
struct module *tmpptr, *curptr;
if (modulehdr == NULL)
return;
curptr = modulehdr->first;
do
{
if (curptr->cfile != NULL)
ReleaseFile (curptr->cfile);
deleteall (&curptr->localroot, (void (*)()) FreeSym);
deleteall (&curptr->notdeclroot, (void (*)()) FreeSym);
if (curptr->mexpr != NULL)
ReleaseExprns (curptr->mexpr);
if (curptr->mname != NULL)
free (curptr->mname);
tmpptr = curptr;
curptr = curptr->nextmodule;
free (tmpptr); /* Release module */
}
while (curptr != NULL); /* until all modules are released */
free (modulehdr);
modulehdr = NULL;
CURRENTMODULE = NULL;
}
void
ReleaseLibraries (void)
{
struct libfile *curptr, *tmpptr;
curptr = libraryhdr->firstlib;
do
{
if (curptr->libfilename != NULL)
free (curptr->libfilename);
tmpptr = curptr;
curptr = curptr->nextlib;
free (tmpptr); /* release library */
}
while (curptr != NULL); /* until all libraries are released */
free (libraryhdr); /* Release library header */
libraryhdr = NULL;
}
void
ReleaseExprns (struct expression *express)
{
struct expr *tmpexpr, *curexpr;
curexpr = express->firstexpr;
while (curexpr != NULL)
{
tmpexpr = curexpr->nextexpr;
RemovePfixlist (curexpr);
curexpr = tmpexpr;
}
free (express);
}
void
ReleaseFile (struct sourcefile *srcfile)
{
if (srcfile->usedsourcefile != NULL)
ReleaseOwnedFile (srcfile->usedsourcefile);
free (srcfile->fname); /* Release allocated area for filename */
free (srcfile); /* Release file information record for this file */
}
void
ReleaseOwnedFile (struct usedfile *ownedfile)
{
/* Release first other files called by this file */
if (ownedfile->nextusedfile != NULL)
ReleaseOwnedFile (ownedfile->nextusedfile);
/* Release first file owned by this file */
if (ownedfile->ownedsourcefile != NULL)
ReleaseFile (ownedfile->ownedsourcefile);
free (ownedfile); /* Then release this owned file */
}
void
ReportError (char *filename, int lineno, int errnum)
{
char errstr[256], errflnmstr[128], errmodstr[128], errlinestr[64];
ASSEMBLE_ERROR = errnum; /* set the global error variable for general error trapping */
ASMERROR = ON;
errflnmstr[0] = '\0';
errmodstr[0] = '\0';
errlinestr[0] = '\0';
errstr[0] = '\0';
if (clinemode && clineno ) lineno=clineno;
if (filename != NULL)
sprintf (errflnmstr,"File '%s', ", filename);
if (CURRENTMODULE != NULL)
if ( CURRENTMODULE->mname != NULL )
sprintf(errmodstr,"Module '%s', ", CURRENTMODULE->mname);
if (lineno != 0)
sprintf (errlinestr, "at line %d, ", lineno);
strcpy(errstr, errflnmstr);
strcat(errstr, errmodstr);
strcat(errstr, errlinestr);
strcat(errstr, errmsg[errnum]);
switch(errnum)
{
case 12:
if (errfile == NULL) {
fprintf (stderr, errstr, MAXCODESIZE);
fputc ('\n',stderr);
}
else {
fprintf (errfile, errstr, MAXCODESIZE);
fputc ('\n',errfile);
}
break;
case 13:
fprintf (stderr, "%d %s\n", TOTALERRORS, errmsg[errnum]);
break;
default:
if (errfile == NULL)
fprintf (stderr, "%s\n", errstr);
else
fprintf (errfile, "%s\n", errstr);
}
++ERRORS;
++TOTALERRORS;
}
void
ReportIOError (char *filename)
{
ASSEMBLE_ERROR = 0;
ASMERROR = ON;
if (CURRENTMODULE != NULL)
if ( CURRENTMODULE->mname != NULL )
fprintf(stderr,"Module '%s', ", CURRENTMODULE->mname);
fprintf (stderr,"file '%s' couldn't be opened or created\n", filename);
++ERRORS;
++TOTALERRORS;
}
void
display_options (void)
{
if (datestamp == ON)
puts ("Assemble only updated files.");
else
puts ("Assemble all files");
if (symfile == ON)
puts ("Create symbol table file.");
if (listing == ON)
puts ("Create listing file.");
if (globaldef == ON)
puts ("Create global definition file.");
if (createlibrary == ON)
puts ("Create library from specified modules.");
if (z80bin == ON)
puts ("Link/relocate assembled modules.");
if (library == ON)
puts ("Link library modules with code.");
if (z80bin == ON && mapref == ON)
puts ("Create address map file.");
if (codesegment == ON && autorelocate == OFF)
puts ("Split code into 16K banks.");
if (autorelocate == ON)
puts ("Create relocatable code.");
putchar ('\n');
}
/***************************************************************************************************
* Main entry of Z80asm
***************************************************************************************************/
int
main (int argc, char *argv[])
{
int asmflag;
int i;
char *ptr;
int include_level = 0;
FILE *includes[10]; /* 10 levels of inclusion should be enough */
symtable = symfile = writeline = mapref = ON;
verbose = smallc_source = listing = listing_CPY = z80bin = datestamp = ASMERROR = codesegment = clinemode = OFF;
deforigin = globaldef = library = createlibrary = autorelocate = clineno = OFF;
cpu_type = CPU_Z80;
libfilename = NULL;
modsrcfile = NULL;
CURRENTMODULE = NULL;
modulehdr = NULL; /* initialise to no modules */
libraryhdr = NULL; /* initialise to no library files */
globalroot = NULL; /* global identifier tree initialized */
staticroot = NULL; /* static identifier tree initialized */
asmflag = DefineDefSym (OS_ID, 1, 0, &staticroot);
if (!asmflag)
exit (1);
strcpy (objext, objext_templ); /* use ".obj" as default object file extension */
/* Get command line arguments, if any... */
if (argc == 1)
{
prompt ();
exit (1);
}
time (&asmtime);
date = asctime (localtime (&asmtime)); /* get current system time for date in list file */
codearea = (unsigned char *) calloc (MAXCODESIZE, sizeof (char)); /* Allocate Memory for Z80 machine code */
if (codearea == NULL)
{
ReportError (NULL, 0, 3);
exit (1);
}
CODESIZE = 0;
PAGELEN = 66;
TOTALERRORS = 0;
TOTALLINES = 0;
if ((CURRENTMODULE = NewModule ()) == NULL)
{ /* then create a dummy module */
ReportError (NULL, 0, 3); /* this is needed during command line parsing */
exit (1);
}
/* Setup some default search paths */
i = include_dir_num++;
include_dir = realloc(include_dir, include_dir_num * sizeof(include_dir[0]));
include_dir[i] = strdup(".");
if ( ( ptr = getenv("Z80_OZFILES") ) != NULL ) {
i = include_dir_num++;
include_dir = realloc(include_dir, include_dir_num * sizeof(include_dir[0]));
include_dir[i] = strdup(ptr);
}
i = lib_dir_num++;
lib_dir = realloc(lib_dir, lib_dir_num * sizeof(lib_dir[0]));
lib_dir[i] = strdup(".");
while (--argc > 0)
{ /* Get options first */
++argv;
if ((*argv)[0] == '-')
SetAsmFlag (((*argv) + 1));
else
{
if ((*argv)[0] == '@')
if ((modsrcfile = fopen ((*argv + 1), "rb")) == NULL)
ReportIOError ((*argv + 1));
break;
}
}
ReleaseModules (); /* Now remove dummy module again, not needed */
if (!argc && modsrcfile == NULL)
{
ReportError (NULL, 0, 8);
exit (1);
}
COLUMN_WIDTH = 4 * TAB_DIST; /* define column width for output files */
if (verbose == ON)
display_options (); /* display status messages of select assembler options */
if (smallc_source == OFF)
{
strcpy (srcext, asmext); /* use ".asm" as default source file extension */
}
for (;;)
{ /* Module loop */
z80asmfile = listfile = objfile = errfile = NULL;
codeptr = codearea; /* Pointer (PC) to store z80 instruction */
ERRORS = 0;
ASSEMBLE_ERROR = -1; /* General error flag */
if (modsrcfile == NULL)
{
if (argc > 0)
{
if ((*argv)[0] != '-')
{
strncpy(ident, *argv, 254);
--argc;
++argv; /* get ready for next filename */
}
else
{
ReportError (NULL, 0, 21); /* Illegal source file name */
break;
}
}
else
break;
}
else
{
again:
ptr = Fetchfilename(modsrcfile);
strcpy(ident, ptr);
if (strlen (ident) == 0)
{
fclose (modsrcfile);
if ( include_level )
{
include_level--;
modsrcfile = includes[include_level];
goto again;
}
break;
}
else if ( ident[0] == '@' && include_level < sizeof(includes) - 1 )
{
includes[include_level++] = modsrcfile;
if ( ( modsrcfile = fopen(ident + 1, "rb") ) == NULL )
{
ReportIOError(ident+1);
}
else
{
goto again;
}
}
}
#ifdef QDOS
/* explicit extension are automatically discarded */
if (strrchr(ident,'_') != NULL) *(strrchr(ident, '_')) ='\0';
#else
if (strrchr(ident,'.') != NULL) *(strrchr(ident, '.')) ='\0';
#endif
if ((srcfilename = AllocIdentifier (strlen (ident) + 5)) != NULL)
{
strcpy (srcfilename, ident);
strcat (srcfilename, srcext); /* add '_asm' or '_opt' extension */
}
else
{
ReportError (NULL, 0, 3);
break;
}
if ((objfilename = AllocIdentifier (strlen (srcfilename) + 1)) != NULL)
{
strcpy (objfilename, srcfilename);
strcpy (objfilename + strlen (srcfilename) - 4, objext); /* overwrite '_asm' extension with
* '_obj' */
}
else
{
ReportError (NULL, 0, 3);
break; /* No more room */
}
if ((lstfilename = AllocIdentifier (strlen (srcfilename) + 1)) != NULL)
{
strcpy (lstfilename, srcfilename);
if (listing)
strcpy (lstfilename + strlen (srcfilename) - 4, lstext); /* overwrite '_asm' extension
* with '_lst' */
else
strcpy (lstfilename + strlen (srcfilename) - 4, symext); /* overwrite '_asm' extension
* with '_sym' */
}
else
{
ReportError (NULL, 0, 3);
break; /* No more room */
}
if ((errfilename = AllocIdentifier (strlen (srcfilename) + 1)) != NULL)
{
strcpy (errfilename, srcfilename);
strcpy (errfilename + strlen (srcfilename) - 4, errext); /* overwrite '_asm' extension with
* '_err' */
}
else
{
ReportError (NULL, 0, 3);
break; /* No more room */
}
if ((CURRENTMODULE = NewModule ()) == NULL)
{ /* Create module data structures for new file */
ReportError (NULL, 0, 3);
break;
}
if ((CURRENTFILE = Newfile (NULL, srcfilename)) == NULL)
break; /* Create first file record, if possible */
if (globaldef && CURRENTMODULE == modulehdr->first)
CreateDeffile ();
if ((asmflag = TestAsmFile ()) == 1)
{
AssembleSourceFile (); /* begin assembly... */
if (verbose)
putchar ('\n'); /* separate module texts */
}
else if (asmflag == -1)
break; /* file open error - stop assembler */
ReleaseFilenames ();
} /* for */
ReleaseFilenames ();
CloseFiles ();
if (globaldef)
fclose (deffile);
if (createlibrary && ASMERROR == OFF)
CreateLib ();
if (createlibrary)
{
fclose (libfile);
if (ASMERROR)
remove (libfilename);
free (libfilename);
libfilename = NULL;
}
if ((ASMERROR == OFF) && verbose)
printf ("Total of %ld lines assembled.\n", TOTALLINES);
if ((ASMERROR == OFF) && z80bin)
LinkModules ();
if ((TOTALERRORS == 0) && z80bin)
{
if (mapref)
WriteMapFile ();
CreateBinFile ();
}
ReleaseFilenames ();
CloseFiles ();
#ifndef QDOS
deleteall (&globalroot, (void (*)()) FreeSym);
deleteall (&staticroot, (void (*)()) FreeSym);
if (modulehdr != NULL)
ReleaseModules (); /* Release module information (symbols, etc.) */
if (libraryhdr != NULL)
ReleaseLibraries (); /* Release library information */
free (codearea); /* Release area for machine code */
if (autorelocate)
if (reloctable != NULL)
free (reloctable);
#endif
if (ASMERROR)
ReportError (NULL, 0, 13);
/* <djm>, if errors, then we really want to return an error number
* surely?
*/
if (ASMERROR)
return 1;
else
return 0; /* assembler successfully ended */
}
void
prompt (void)
{
printf("%s\n",copyrightmsg);
}
void
usage (void)
{
printf ("%s\n", copyrightmsg);
puts ("z80asm [options] [ @<modulefile> | {<filename>} ]");
puts ("[] = may be ignored. {} = may be repeated. | = OR clause.");
printf ("To assemble 'fred%s' use 'fred' or 'fred%s'\n", asmext, asmext);
puts ("<modulefile> contains file names of all modules to be linked:");
puts ("File names are put on separate lines ended with \\n. File types recognized or");
puts ("created by z80asm (defined by the following extension):");
printf ("%s = source file (default), or alternative -e<ext>\n", asmext);
printf ("%s = object file (default), or alternative -M<ext>\n", objext);
printf ("%s = list file, %s = Z80 code file\n", lstext, binext);
printf ("%s = symbols file, %s = map file, %s = XDEF file, %s = error file\n", symext, mapext, defext, errext);
puts ("Options: -n defines option to be turned OFF (except -r -R -i -x -D -t -o)");
printf ("-v verbose, -l listing file, -s symbol table, -m map listing file\n");
puts ("-r<ORG> Explicit relocation <ORG> defined in hex (ignore ORG in first module)");
puts ("-plus Interpret 'Invoke' as RST 28h");
puts ("-R Generate relocatable code (Automatical relocation before execution)");
puts ("-D<symbol> define symbol as logically TRUE (used for conditional assembly)");
puts ("-b assemble files & link to ORG address. -c split code in 16K banks");
puts ("-d date stamp control, assemble only if source file > object file");
puts ("-a: -b & -d (assemble only updated source files, then link & relocate)");
puts ("-o<bin filename> expl. output filename, -g XDEF reloc. addr. from all modules");
printf ("-i<library> include <library> LIB modules with %s modules during linking\n", objext);
puts ("-x<library> create library from specified modules ( e.g. with @<modules> )");
printf ("-t<n> tabulator width for %s, %s, %s files. Column width is 4 times -t\n", mapext, defext, symext);
printf ("-I<path> additional path to search for includes\n");
printf ("-L<path> path to search for libraries\n");
puts ("Default options: -nv -nd -nb -nl -s -m -ng -nc -nR -t8");
}
symbol *
createsym (symbol * symptr)
{
return CreateSymbol (symptr->symname, symptr->symvalue, symptr->type, symptr->owner);
}
struct expression *
AllocExprHdr (void)
{
return (struct expression *) malloc (sizeof (struct expression));
}
struct JRPC_Hdr *
AllocJRaddrHdr (void)
{
return (struct JRPC_Hdr *) malloc (sizeof (struct JRPC_Hdr));
}
struct modules *
AllocModuleHdr (void)
{
return (struct modules *) malloc (sizeof (struct modules));
}
struct module *
AllocModule (void)
{
return (struct module *) malloc (sizeof (struct module));
}
struct liblist *
AllocLibHdr (void)
{
return (struct liblist *) malloc (sizeof (struct liblist));
}
struct libfile *
AllocLib (void)
{
return (struct libfile *) malloc (sizeof (struct libfile));
}
/** \brief Search for a filename in the include path
*
* \param base - The filename to search for
*
* \return Filename (static buffer)
*/
char *SearchFile(char *base, int is_include)
{
static char filename[FILENAME_MAX+1];
char **paths = lib_dir;
int paths_num = lib_dir_num;
struct stat sb;
int i;
if ( is_include )
{
paths = include_dir;
paths_num = include_dir_num;
}
if ( stat(base,&sb) == 0 )
{
snprintf(filename, sizeof(filename),"%s",base);
return filename;
}
for ( i = 0; i < paths_num; i++ )
{
snprintf(filename, sizeof(filename),"%s/%s",paths[i], base);
if ( stat(filename,&sb) == 0 )
{
return filename;
}
}
snprintf(filename, sizeof(filename),"%s",base);
return filename;
}
/*
* Local Variables:
* indent-tabs-mode:nil
* require-final-newline:t
* c-basic-offset: 2
* eval: (c-set-offset 'case-label 0)
* eval: (c-set-offset 'substatement-open 2)
* eval: (c-set-offset 'access-label 0)
* eval: (c-set-offset 'class-open 2)
* eval: (c-set-offset 'class-close 2)
* End:
*/
| 27.201796 | 119 | 0.56396 | [
"object"
] |
d2c36ceaf99fadee986c8c0f5c87a60a2917436f | 2,050 | h | C | Source/Server/Server/Streams/Frpg2Message.h | HanasakiHonoka/ds3os | 6924fa44400fc79dac0132cc7f7cf8470effb311 | [
"MIT"
] | 280 | 2021-08-08T08:14:16.000Z | 2022-03-31T14:42:21.000Z | Source/Server/Server/Streams/Frpg2Message.h | Adephx/ds3os | e5b8881c43b61a81a08d0d8c6ab83407c60cb450 | [
"MIT"
] | 90 | 2021-08-28T21:16:47.000Z | 2022-03-31T14:09:55.000Z | Source/Server/Server/Streams/Frpg2Message.h | Adephx/ds3os | e5b8881c43b61a81a08d0d8c6ab83407c60cb450 | [
"MIT"
] | 85 | 2021-09-14T18:38:23.000Z | 2022-03-31T10:56:39.000Z | /*
* Dark Souls 3 - Open Server
* Copyright (C) 2021 Tim Leonard
*
* This program is free software; licensed under the MIT license.
* You should have received a copy of the license along with this program.
* If not, see <https://opensource.org/licenses/MIT>.
*/
#pragma once
#include "Core/Utils/Endian.h"
#include <vector>
// All the id's of message type we can recieve.
enum class Frpg2MessageType
{
Reply = 0x0,
// Authentication flow messages.
KeyMaterial = 1,
SteamTicket = 3,
GetServiceStatus = 2,
RequestQueryLoginServerInfo = 5,
RequestHandshake = 6,
};
// See ds3server_packet.bt for commentry on what each of these
// fields appears to represent.
#pragma pack(push,1)
struct Frpg2MessageHeader
{
public:
uint32_t header_size = 12; // As far as I can tell this is always 12.
Frpg2MessageType msg_type = Frpg2MessageType::Reply;
uint32_t msg_index = 0x00; // Request/response messages have the same value for this.
void SwapEndian()
{
header_size = HostOrderToBigEndian(header_size);
msg_type = HostOrderToBigEndian(msg_type);
msg_index = HostOrderToLittleEndian(msg_index);
}
};
struct Frpg2MessageResponseHeader
{
public:
uint32_t unknown_1 = 0x0;
uint32_t unknown_2 = 0x1;
uint32_t unknown_3 = 0x0;
uint32_t unknown_4 = 0x0;
void SwapEndian()
{
unknown_1 = HostOrderToBigEndian(unknown_1);
unknown_2 = HostOrderToBigEndian(unknown_2);
unknown_3 = HostOrderToBigEndian(unknown_3);
unknown_4 = HostOrderToBigEndian(unknown_4);
}
};
#pragma pack(pop)
static_assert(sizeof(Frpg2MessageHeader) == 12, "Message header is not expected size.");
struct Frpg2Message
{
public:
Frpg2MessageHeader Header;
Frpg2MessageResponseHeader ResponseHeader; // Only exists if its a response :thinking:
// Length of this payload should be the same
// as the value stored in Header.payload_length
std::vector<uint8_t> Payload;
std::string Disassembly;
}; | 25 | 98 | 0.697561 | [
"vector"
] |
d2c3cb189545ffdfec07b2a00be5356cf9d19ffd | 40,919 | h | C | blis/_src/frame/include/bli_type_defs.h | sebpop/cython-blis | 0010334752ef184dfd1c9a1aed311097fedb8ac3 | [
"BSD-3-Clause"
] | null | null | null | blis/_src/frame/include/bli_type_defs.h | sebpop/cython-blis | 0010334752ef184dfd1c9a1aed311097fedb8ac3 | [
"BSD-3-Clause"
] | null | null | null | blis/_src/frame/include/bli_type_defs.h | sebpop/cython-blis | 0010334752ef184dfd1c9a1aed311097fedb8ac3 | [
"BSD-3-Clause"
] | null | null | null | /*
BLIS
An object-based framework for developing high-performance BLAS-like
libraries.
Copyright (C) 2014, The University of Texas at Austin
Copyright (C) 2016, Hewlett Packard Enterprise Development LP
Copyright (C) 2018, Advanced Micro Devices, Inc.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name(s) of the copyright holder(s) nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef BLIS_TYPE_DEFS_H
#define BLIS_TYPE_DEFS_H
//
// -- BLIS basic types ---------------------------------------------------------
//
#ifdef __cplusplus
// For C++, include stdint.h.
#include <stdint.h>
#elif __STDC_VERSION__ >= 199901L
// For C99 (or later), include stdint.h.
#include <stdint.h>
#else
// When stdint.h is not available, manually typedef the types we will use.
#ifdef _WIN32
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#else
#error "Attempting to compile on pre-C99 system without stdint.h."
#endif
#endif
// -- General-purpose integers --
// If BLAS integers are 64 bits, mandate that BLIS integers also be 64 bits.
// NOTE: This cpp guard will only meaningfully change BLIS's behavior on
// systems where the BLIS integer size would have been automatically selected
// to be 32 bits, since explicit selection of 32 bits is prohibited at
// configure-time (and explicit or automatic selection of 64 bits is fine
// and would have had the same result).
#if BLIS_BLAS_INT_SIZE == 64
#undef BLIS_INT_TYPE_SIZE
#define BLIS_INT_TYPE_SIZE 64
#endif
// Define integer types depending on what size integer was requested.
#if BLIS_INT_TYPE_SIZE == 32
typedef int32_t gint_t;
typedef uint32_t guint_t;
#elif BLIS_INT_TYPE_SIZE == 64
typedef int64_t gint_t;
typedef uint64_t guint_t;
#else
typedef signed long int gint_t;
typedef unsigned long int guint_t;
#endif
// -- Boolean type --
typedef gint_t bool_t;
// -- Boolean values --
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
// -- Special-purpose integers --
// This cpp guard provides a temporary hack to allow libflame
// interoperability with BLIS.
#ifndef _DEFINED_DIM_T
#define _DEFINED_DIM_T
typedef gint_t dim_t; // dimension type
#endif
typedef gint_t inc_t; // increment/stride type
typedef gint_t doff_t; // diagonal offset type
typedef guint_t siz_t; // byte size type
typedef uint32_t objbits_t; // object information bit field
// -- Real types --
// Define the number of floating-point types supported, and the size of the
// largest type.
#define BLIS_NUM_FP_TYPES 4
#define BLIS_MAX_TYPE_SIZE sizeof(dcomplex)
// There are some places where we need to use sizeof() inside of a C
// preprocessor #if conditional, and so here we define the various sizes
// for those purposes.
#define BLIS_SIZEOF_S 4 // sizeof(float)
#define BLIS_SIZEOF_D 8 // sizeof(double)
#define BLIS_SIZEOF_C 8 // sizeof(scomplex)
#define BLIS_SIZEOF_Z 16 // sizeof(dcomplex)
// -- Complex types --
#ifdef BLIS_ENABLE_C99_COMPLEX
#if __STDC_VERSION__ >= 199901L
#include <complex.h>
// Typedef official complex types to BLIS complex type names.
typedef float complex scomplex;
typedef double complex dcomplex;
#else
#error "Configuration requested C99 complex types, but C99 does not appear to be supported."
#endif
#else // ifndef BLIS_ENABLE_C99_COMPLEX
// This cpp guard provides a temporary hack to allow libflame
// interoperability with BLIS.
#ifndef _DEFINED_SCOMPLEX
#define _DEFINED_SCOMPLEX
typedef struct
{
float real;
float imag;
} scomplex;
#endif
// This cpp guard provides a temporary hack to allow libflame
// interoperability with BLIS.
#ifndef _DEFINED_DCOMPLEX
#define _DEFINED_DCOMPLEX
typedef struct
{
double real;
double imag;
} dcomplex;
#endif
#endif // BLIS_ENABLE_C99_COMPLEX
// -- Atom type --
// Note: atom types are used to hold "bufferless" scalar object values. Note
// that it needs to be as large as the largest possible scalar value we might
// want to hold. Thus, for now, it is a dcomplex.
typedef dcomplex atom_t;
// -- Fortran-77 types --
// Note: These types are typically only used by BLAS compatibility layer, but
// we must define them even when the compatibility layer isn't being built
// because they also occur in bli_slamch() and bli_dlamch().
// Define f77_int depending on what size of integer was requested.
#if BLIS_BLAS_INT_TYPE_SIZE == 32
typedef int32_t f77_int;
#elif BLIS_BLAS_INT_TYPE_SIZE == 64
typedef int64_t f77_int;
#else
typedef long int f77_int;
#endif
typedef char f77_char;
typedef float f77_float;
typedef double f77_double;
typedef scomplex f77_scomplex;
typedef dcomplex f77_dcomplex;
//
// -- BLIS info bit field offsets ----------------------------------------------
//
/*
info field description
bit(s) purpose
------- -------
2 ~ 0 Stored numerical datatype
- 0: domain (0 == real, 1 == complex)
- 1: precision (0 == single, 1 == double)
- 2: special (100 = int; 101 = const)
3 Transposition required [during pack]?
4 Conjugation required [during pack]?
7 ~ 5 Part of matrix stored:
- 5: strictly upper triangular
- 6: diagonal
- 7: strictly lower triangular
8 Implicit unit diagonal?
9 Invert diagonal required [during pack]?
12 ~ 10 Target numerical datatype
- 10: domain (0 == real, 1 == complex)
- 11: precision (0 == single, 1 == double)
- 12: used to encode integer, constant types
15 ~ 13 Execution numerical datatype
- 13: domain (0 == real, 1 == complex)
- 14: precision (0 == single, 1 == double)
- 15: used to encode integer, constant types
22 ~ 16 Packed type/status
- 0 0000 00: not packed
- 1 0000 00: packed (unspecified; by rows, columns, or vector)
- 1 0000 00: packed by rows
- 1 0000 01: packed by columns
- 1 0000 10: packed by row panels
- 1 0000 11: packed by column panels
- 1 0001 10: packed by 4m interleaved row panels
- 1 0001 11: packed by 4m interleaved column panels
- 1 0010 10: packed by 3m interleaved row panels
- 1 0010 11: packed by 3m interleaved column panels
- 1 0011 10: packed by 4m separated row panels (not used)
- 1 0011 11: packed by 4m separated column panels (not used)
- 1 0100 10: packed by 3m separated row panels
- 1 0100 11: packed by 3m separated column panels
- 1 0101 10: packed real-only row panels
- 1 0101 11: packed real-only column panels
- 1 0110 10: packed imag-only row panels
- 1 0110 11: packed imag-only column panels
- 1 0111 10: packed real+imag row panels
- 1 0111 11: packed real+imag column panels
- 1 1000 10: packed by 1m expanded row panels
- 1 1000 11: packed by 1m expanded column panels
- 1 1001 10: packed by 1m reordered row panels
- 1 1001 11: packed by 1m reordered column panels
23 Packed panel order if upper-stored
- 0 == forward order if upper
- 1 == reverse order if upper
24 Packed panel order if lower-stored
- 0 == forward order if lower
- 1 == reverse order if lower
26 ~ 25 Packed buffer type
- 0 == block of A
- 1 == panel of B
- 2 == panel of C
- 3 == general use
28 ~ 27 Structure type
- 0 == general
- 1 == Hermitian
- 2 == symmetric
- 3 == triangular
31 ~ 29 Computation numerical datatype
- 29: domain (0 == real, 1 == complex)
- 30: precision (0 == single, 1 == double)
- 31: used to encode integer, constant types
info2 field description
bit(s) purpose
------- -------
2 ~ 0 Scalar storage numerical datatype
- 0: domain (0 == real, 1 == complex)
- 1: precision (0 == single, 1 == double)
- 2: used to encode integer, constant types
*/
// info
#define BLIS_DATATYPE_SHIFT 0
#define BLIS_DOMAIN_SHIFT 0
#define BLIS_PRECISION_SHIFT 1
#define BLIS_CONJTRANS_SHIFT 3
#define BLIS_TRANS_SHIFT 3
#define BLIS_CONJ_SHIFT 4
#define BLIS_UPLO_SHIFT 5
#define BLIS_UPPER_SHIFT 5
#define BLIS_DIAG_SHIFT 6
#define BLIS_LOWER_SHIFT 7
#define BLIS_UNIT_DIAG_SHIFT 8
#define BLIS_INVERT_DIAG_SHIFT 9
#define BLIS_TARGET_DT_SHIFT 10
#define BLIS_TARGET_DOMAIN_SHIFT 10
#define BLIS_TARGET_PREC_SHIFT 11
#define BLIS_EXEC_DT_SHIFT 13
#define BLIS_EXEC_DOMAIN_SHIFT 13
#define BLIS_EXEC_PREC_SHIFT 14
#define BLIS_PACK_SCHEMA_SHIFT 16
#define BLIS_PACK_RC_SHIFT 16
#define BLIS_PACK_PANEL_SHIFT 17
#define BLIS_PACK_FORMAT_SHIFT 18
#define BLIS_PACK_SHIFT 22
#define BLIS_PACK_REV_IF_UPPER_SHIFT 23
#define BLIS_PACK_REV_IF_LOWER_SHIFT 24
#define BLIS_PACK_BUFFER_SHIFT 25
#define BLIS_STRUC_SHIFT 27
#define BLIS_COMP_DT_SHIFT 29
#define BLIS_COMP_DOMAIN_SHIFT 29
#define BLIS_COMP_PREC_SHIFT 30
// info2
#define BLIS_SCALAR_DT_SHIFT 0
#define BLIS_SCALAR_DOMAIN_SHIFT 0
#define BLIS_SCALAR_PREC_SHIFT 1
//
// -- BLIS info bit field masks ------------------------------------------------
//
// info
#define BLIS_DATATYPE_BITS ( 0x7 << BLIS_DATATYPE_SHIFT )
#define BLIS_DOMAIN_BIT ( 0x1 << BLIS_DOMAIN_SHIFT )
#define BLIS_PRECISION_BIT ( 0x1 << BLIS_PRECISION_SHIFT )
#define BLIS_CONJTRANS_BITS ( 0x3 << BLIS_CONJTRANS_SHIFT )
#define BLIS_TRANS_BIT ( 0x1 << BLIS_TRANS_SHIFT )
#define BLIS_CONJ_BIT ( 0x1 << BLIS_CONJ_SHIFT )
#define BLIS_UPLO_BITS ( 0x7 << BLIS_UPLO_SHIFT )
#define BLIS_UPPER_BIT ( 0x1 << BLIS_UPPER_SHIFT )
#define BLIS_DIAG_BIT ( 0x1 << BLIS_DIAG_SHIFT )
#define BLIS_LOWER_BIT ( 0x1 << BLIS_LOWER_SHIFT )
#define BLIS_UNIT_DIAG_BIT ( 0x1 << BLIS_UNIT_DIAG_SHIFT )
#define BLIS_INVERT_DIAG_BIT ( 0x1 << BLIS_INVERT_DIAG_SHIFT )
#define BLIS_TARGET_DT_BITS ( 0x7 << BLIS_TARGET_DT_SHIFT )
#define BLIS_TARGET_DOMAIN_BIT ( 0x1 << BLIS_TARGET_DOMAIN_SHIFT )
#define BLIS_TARGET_PREC_BIT ( 0x1 << BLIS_TARGET_PREC_SHIFT )
#define BLIS_EXEC_DT_BITS ( 0x7 << BLIS_EXEC_DT_SHIFT )
#define BLIS_EXEC_DOMAIN_BIT ( 0x1 << BLIS_EXEC_DOMAIN_SHIFT )
#define BLIS_EXEC_PREC_BIT ( 0x1 << BLIS_EXEC_PREC_SHIFT )
#define BLIS_PACK_SCHEMA_BITS ( 0x7F << BLIS_PACK_SCHEMA_SHIFT )
#define BLIS_PACK_RC_BIT ( 0x1 << BLIS_PACK_RC_SHIFT )
#define BLIS_PACK_PANEL_BIT ( 0x1 << BLIS_PACK_PANEL_SHIFT )
#define BLIS_PACK_FORMAT_BITS ( 0xF << BLIS_PACK_FORMAT_SHIFT )
#define BLIS_PACK_BIT ( 0x1 << BLIS_PACK_SHIFT )
#define BLIS_PACK_REV_IF_UPPER_BIT ( 0x1 << BLIS_PACK_REV_IF_UPPER_SHIFT )
#define BLIS_PACK_REV_IF_LOWER_BIT ( 0x1 << BLIS_PACK_REV_IF_LOWER_SHIFT )
#define BLIS_PACK_BUFFER_BITS ( 0x3 << BLIS_PACK_BUFFER_SHIFT )
#define BLIS_STRUC_BITS ( 0x3 << BLIS_STRUC_SHIFT )
#define BLIS_COMP_DT_BITS ( 0x7 << BLIS_COMP_DT_SHIFT )
#define BLIS_COMP_DOMAIN_BIT ( 0x1 << BLIS_COMP_DOMAIN_SHIFT )
#define BLIS_COMP_PREC_BIT ( 0x1 << BLIS_COMP_PREC_SHIFT )
// info2
#define BLIS_SCALAR_DT_BITS ( 0x7 << BLIS_SCALAR_DT_SHIFT )
#define BLIS_SCALAR_DOMAIN_BIT ( 0x1 << BLIS_SCALAR_DOMAIN_SHIFT )
#define BLIS_SCALAR_PREC_BIT ( 0x1 << BLIS_SCALAR_PREC_SHIFT )
//
// -- BLIS enumerated type value definitions -----------------------------------
//
#define BLIS_BITVAL_REAL 0x0
#define BLIS_BITVAL_COMPLEX BLIS_DOMAIN_BIT
#define BLIS_BITVAL_SINGLE_PREC 0x0
#define BLIS_BITVAL_DOUBLE_PREC BLIS_PRECISION_BIT
#define BLIS_BITVAL_FLOAT_TYPE 0x0
#define BLIS_BITVAL_SCOMPLEX_TYPE BLIS_DOMAIN_BIT
#define BLIS_BITVAL_DOUBLE_TYPE BLIS_PRECISION_BIT
#define BLIS_BITVAL_DCOMPLEX_TYPE ( BLIS_DOMAIN_BIT | BLIS_PRECISION_BIT )
#define BLIS_BITVAL_INT_TYPE 0x04
#define BLIS_BITVAL_CONST_TYPE 0x05
#define BLIS_BITVAL_NO_TRANS 0x0
#define BLIS_BITVAL_TRANS BLIS_TRANS_BIT
#define BLIS_BITVAL_NO_CONJ 0x0
#define BLIS_BITVAL_CONJ BLIS_CONJ_BIT
#define BLIS_BITVAL_CONJ_TRANS ( BLIS_CONJ_BIT | BLIS_TRANS_BIT )
#define BLIS_BITVAL_ZEROS 0x0
#define BLIS_BITVAL_UPPER ( BLIS_UPPER_BIT | BLIS_DIAG_BIT )
#define BLIS_BITVAL_LOWER ( BLIS_LOWER_BIT | BLIS_DIAG_BIT )
#define BLIS_BITVAL_DENSE BLIS_UPLO_BITS
#define BLIS_BITVAL_NONUNIT_DIAG 0x0
#define BLIS_BITVAL_UNIT_DIAG BLIS_UNIT_DIAG_BIT
#define BLIS_BITVAL_INVERT_DIAG BLIS_INVERT_DIAG_BIT
#define BLIS_BITVAL_NOT_PACKED 0x0
#define BLIS_BITVAL_4MI ( 0x1 << BLIS_PACK_FORMAT_SHIFT )
#define BLIS_BITVAL_3MI ( 0x2 << BLIS_PACK_FORMAT_SHIFT )
#define BLIS_BITVAL_4MS ( 0x3 << BLIS_PACK_FORMAT_SHIFT )
#define BLIS_BITVAL_3MS ( 0x4 << BLIS_PACK_FORMAT_SHIFT )
#define BLIS_BITVAL_RO ( 0x5 << BLIS_PACK_FORMAT_SHIFT )
#define BLIS_BITVAL_IO ( 0x6 << BLIS_PACK_FORMAT_SHIFT )
#define BLIS_BITVAL_RPI ( 0x7 << BLIS_PACK_FORMAT_SHIFT )
#define BLIS_BITVAL_1E ( 0x8 << BLIS_PACK_FORMAT_SHIFT )
#define BLIS_BITVAL_1R ( 0x9 << BLIS_PACK_FORMAT_SHIFT )
#define BLIS_BITVAL_PACKED_UNSPEC ( BLIS_PACK_BIT )
#define BLIS_BITVAL_PACKED_ROWS ( BLIS_PACK_BIT )
#define BLIS_BITVAL_PACKED_COLUMNS ( BLIS_PACK_BIT | BLIS_PACK_RC_BIT )
#define BLIS_BITVAL_PACKED_ROW_PANELS ( BLIS_PACK_BIT | BLIS_PACK_PANEL_BIT )
#define BLIS_BITVAL_PACKED_COL_PANELS ( BLIS_PACK_BIT | BLIS_PACK_PANEL_BIT | BLIS_PACK_RC_BIT )
#define BLIS_BITVAL_PACKED_ROW_PANELS_4MI ( BLIS_PACK_BIT | BLIS_BITVAL_4MI | BLIS_PACK_PANEL_BIT )
#define BLIS_BITVAL_PACKED_COL_PANELS_4MI ( BLIS_PACK_BIT | BLIS_BITVAL_4MI | BLIS_PACK_PANEL_BIT | BLIS_PACK_RC_BIT )
#define BLIS_BITVAL_PACKED_ROW_PANELS_3MI ( BLIS_PACK_BIT | BLIS_BITVAL_3MI | BLIS_PACK_PANEL_BIT )
#define BLIS_BITVAL_PACKED_COL_PANELS_3MI ( BLIS_PACK_BIT | BLIS_BITVAL_3MI | BLIS_PACK_PANEL_BIT | BLIS_PACK_RC_BIT )
#define BLIS_BITVAL_PACKED_ROW_PANELS_4MS ( BLIS_PACK_BIT | BLIS_BITVAL_4MS | BLIS_PACK_PANEL_BIT )
#define BLIS_BITVAL_PACKED_COL_PANELS_4MS ( BLIS_PACK_BIT | BLIS_BITVAL_4MS | BLIS_PACK_PANEL_BIT | BLIS_PACK_RC_BIT )
#define BLIS_BITVAL_PACKED_ROW_PANELS_3MS ( BLIS_PACK_BIT | BLIS_BITVAL_3MS | BLIS_PACK_PANEL_BIT )
#define BLIS_BITVAL_PACKED_COL_PANELS_3MS ( BLIS_PACK_BIT | BLIS_BITVAL_3MS | BLIS_PACK_PANEL_BIT | BLIS_PACK_RC_BIT )
#define BLIS_BITVAL_PACKED_ROW_PANELS_RO ( BLIS_PACK_BIT | BLIS_BITVAL_RO | BLIS_PACK_PANEL_BIT )
#define BLIS_BITVAL_PACKED_COL_PANELS_RO ( BLIS_PACK_BIT | BLIS_BITVAL_RO | BLIS_PACK_PANEL_BIT | BLIS_PACK_RC_BIT )
#define BLIS_BITVAL_PACKED_ROW_PANELS_IO ( BLIS_PACK_BIT | BLIS_BITVAL_IO | BLIS_PACK_PANEL_BIT )
#define BLIS_BITVAL_PACKED_COL_PANELS_IO ( BLIS_PACK_BIT | BLIS_BITVAL_IO | BLIS_PACK_PANEL_BIT | BLIS_PACK_RC_BIT )
#define BLIS_BITVAL_PACKED_ROW_PANELS_RPI ( BLIS_PACK_BIT | BLIS_BITVAL_RPI | BLIS_PACK_PANEL_BIT )
#define BLIS_BITVAL_PACKED_COL_PANELS_RPI ( BLIS_PACK_BIT | BLIS_BITVAL_RPI | BLIS_PACK_PANEL_BIT | BLIS_PACK_RC_BIT )
#define BLIS_BITVAL_PACKED_ROW_PANELS_1E ( BLIS_PACK_BIT | BLIS_BITVAL_1E | BLIS_PACK_PANEL_BIT )
#define BLIS_BITVAL_PACKED_COL_PANELS_1E ( BLIS_PACK_BIT | BLIS_BITVAL_1E | BLIS_PACK_PANEL_BIT | BLIS_PACK_RC_BIT )
#define BLIS_BITVAL_PACKED_ROW_PANELS_1R ( BLIS_PACK_BIT | BLIS_BITVAL_1R | BLIS_PACK_PANEL_BIT )
#define BLIS_BITVAL_PACKED_COL_PANELS_1R ( BLIS_PACK_BIT | BLIS_BITVAL_1R | BLIS_PACK_PANEL_BIT | BLIS_PACK_RC_BIT )
#define BLIS_BITVAL_PACK_FWD_IF_UPPER 0x0
#define BLIS_BITVAL_PACK_REV_IF_UPPER BLIS_PACK_REV_IF_UPPER_BIT
#define BLIS_BITVAL_PACK_FWD_IF_LOWER 0x0
#define BLIS_BITVAL_PACK_REV_IF_LOWER BLIS_PACK_REV_IF_LOWER_BIT
#define BLIS_BITVAL_BUFFER_FOR_A_BLOCK 0x0
#define BLIS_BITVAL_BUFFER_FOR_B_PANEL ( 0x1 << BLIS_PACK_BUFFER_SHIFT )
#define BLIS_BITVAL_BUFFER_FOR_C_PANEL ( 0x2 << BLIS_PACK_BUFFER_SHIFT )
#define BLIS_BITVAL_BUFFER_FOR_GEN_USE ( 0x3 << BLIS_PACK_BUFFER_SHIFT )
#define BLIS_BITVAL_GENERAL 0x0
#define BLIS_BITVAL_HERMITIAN ( 0x1 << BLIS_STRUC_SHIFT )
#define BLIS_BITVAL_SYMMETRIC ( 0x2 << BLIS_STRUC_SHIFT )
#define BLIS_BITVAL_TRIANGULAR ( 0x3 << BLIS_STRUC_SHIFT )
//
// -- BLIS enumerated type definitions -----------------------------------------
//
// -- Operational parameter types --
typedef enum
{
BLIS_NO_TRANSPOSE = 0x0,
BLIS_TRANSPOSE = BLIS_BITVAL_TRANS,
BLIS_CONJ_NO_TRANSPOSE = BLIS_BITVAL_CONJ,
BLIS_CONJ_TRANSPOSE = BLIS_BITVAL_CONJ_TRANS
} trans_t;
typedef enum
{
BLIS_NO_CONJUGATE = 0x0,
BLIS_CONJUGATE = BLIS_BITVAL_CONJ
} conj_t;
typedef enum
{
BLIS_ZEROS = BLIS_BITVAL_ZEROS,
BLIS_LOWER = BLIS_BITVAL_LOWER,
BLIS_UPPER = BLIS_BITVAL_UPPER,
BLIS_DENSE = BLIS_BITVAL_DENSE
} uplo_t;
typedef enum
{
BLIS_LEFT = 0x0,
BLIS_RIGHT
} side_t;
typedef enum
{
BLIS_NONUNIT_DIAG = 0x0,
BLIS_UNIT_DIAG = BLIS_BITVAL_UNIT_DIAG
} diag_t;
typedef enum
{
BLIS_NO_INVERT_DIAG = 0x0,
BLIS_INVERT_DIAG = BLIS_BITVAL_INVERT_DIAG
} invdiag_t;
typedef enum
{
BLIS_GENERAL = BLIS_BITVAL_GENERAL,
BLIS_HERMITIAN = BLIS_BITVAL_HERMITIAN,
BLIS_SYMMETRIC = BLIS_BITVAL_SYMMETRIC,
BLIS_TRIANGULAR = BLIS_BITVAL_TRIANGULAR
} struc_t;
// -- Data type --
typedef enum
{
BLIS_FLOAT = BLIS_BITVAL_FLOAT_TYPE,
BLIS_DOUBLE = BLIS_BITVAL_DOUBLE_TYPE,
BLIS_SCOMPLEX = BLIS_BITVAL_SCOMPLEX_TYPE,
BLIS_DCOMPLEX = BLIS_BITVAL_DCOMPLEX_TYPE,
BLIS_INT = BLIS_BITVAL_INT_TYPE,
BLIS_CONSTANT = BLIS_BITVAL_CONST_TYPE,
BLIS_DT_LO = BLIS_FLOAT,
BLIS_DT_HI = BLIS_DCOMPLEX
} num_t;
typedef enum
{
BLIS_REAL = BLIS_BITVAL_REAL,
BLIS_COMPLEX = BLIS_BITVAL_COMPLEX
} dom_t;
typedef enum
{
BLIS_SINGLE_PREC = BLIS_BITVAL_SINGLE_PREC,
BLIS_DOUBLE_PREC = BLIS_BITVAL_DOUBLE_PREC
} prec_t;
// -- Pack schema type --
typedef enum
{
BLIS_NOT_PACKED = BLIS_BITVAL_NOT_PACKED,
BLIS_PACKED_UNSPEC = BLIS_BITVAL_PACKED_UNSPEC,
BLIS_PACKED_VECTOR = BLIS_BITVAL_PACKED_UNSPEC,
BLIS_PACKED_ROWS = BLIS_BITVAL_PACKED_ROWS,
BLIS_PACKED_COLUMNS = BLIS_BITVAL_PACKED_COLUMNS,
BLIS_PACKED_ROW_PANELS = BLIS_BITVAL_PACKED_ROW_PANELS,
BLIS_PACKED_COL_PANELS = BLIS_BITVAL_PACKED_COL_PANELS,
BLIS_PACKED_ROW_PANELS_4MI = BLIS_BITVAL_PACKED_ROW_PANELS_4MI,
BLIS_PACKED_COL_PANELS_4MI = BLIS_BITVAL_PACKED_COL_PANELS_4MI,
BLIS_PACKED_ROW_PANELS_3MI = BLIS_BITVAL_PACKED_ROW_PANELS_3MI,
BLIS_PACKED_COL_PANELS_3MI = BLIS_BITVAL_PACKED_COL_PANELS_3MI,
BLIS_PACKED_ROW_PANELS_4MS = BLIS_BITVAL_PACKED_ROW_PANELS_4MS,
BLIS_PACKED_COL_PANELS_4MS = BLIS_BITVAL_PACKED_COL_PANELS_4MS,
BLIS_PACKED_ROW_PANELS_3MS = BLIS_BITVAL_PACKED_ROW_PANELS_3MS,
BLIS_PACKED_COL_PANELS_3MS = BLIS_BITVAL_PACKED_COL_PANELS_3MS,
BLIS_PACKED_ROW_PANELS_RO = BLIS_BITVAL_PACKED_ROW_PANELS_RO,
BLIS_PACKED_COL_PANELS_RO = BLIS_BITVAL_PACKED_COL_PANELS_RO,
BLIS_PACKED_ROW_PANELS_IO = BLIS_BITVAL_PACKED_ROW_PANELS_IO,
BLIS_PACKED_COL_PANELS_IO = BLIS_BITVAL_PACKED_COL_PANELS_IO,
BLIS_PACKED_ROW_PANELS_RPI = BLIS_BITVAL_PACKED_ROW_PANELS_RPI,
BLIS_PACKED_COL_PANELS_RPI = BLIS_BITVAL_PACKED_COL_PANELS_RPI,
BLIS_PACKED_ROW_PANELS_1E = BLIS_BITVAL_PACKED_ROW_PANELS_1E,
BLIS_PACKED_COL_PANELS_1E = BLIS_BITVAL_PACKED_COL_PANELS_1E,
BLIS_PACKED_ROW_PANELS_1R = BLIS_BITVAL_PACKED_ROW_PANELS_1R,
BLIS_PACKED_COL_PANELS_1R = BLIS_BITVAL_PACKED_COL_PANELS_1R
} pack_t;
// We combine row and column packing into one "type", and we start
// with BLIS_PACKED_ROW_PANELS, _COLUMN_PANELS. We also count the
// schema pair for "4ms" (4m separated), because its bit value has
// been reserved, even though we don't use it.
#define BLIS_NUM_PACK_SCHEMA_TYPES 10
// -- Pack order type --
typedef enum
{
BLIS_PACK_FWD_IF_UPPER = BLIS_BITVAL_PACK_FWD_IF_UPPER,
BLIS_PACK_REV_IF_UPPER = BLIS_BITVAL_PACK_REV_IF_UPPER,
BLIS_PACK_FWD_IF_LOWER = BLIS_BITVAL_PACK_FWD_IF_LOWER,
BLIS_PACK_REV_IF_LOWER = BLIS_BITVAL_PACK_REV_IF_LOWER
} packord_t;
// -- Pack buffer type --
typedef enum
{
BLIS_BUFFER_FOR_A_BLOCK = BLIS_BITVAL_BUFFER_FOR_A_BLOCK,
BLIS_BUFFER_FOR_B_PANEL = BLIS_BITVAL_BUFFER_FOR_B_PANEL,
BLIS_BUFFER_FOR_C_PANEL = BLIS_BITVAL_BUFFER_FOR_C_PANEL,
BLIS_BUFFER_FOR_GEN_USE = BLIS_BITVAL_BUFFER_FOR_GEN_USE
} packbuf_t;
// -- Partitioning direction --
typedef enum
{
BLIS_FWD,
BLIS_BWD
} dir_t;
// -- Subpartition type --
typedef enum
{
BLIS_SUBPART0,
BLIS_SUBPART1,
BLIS_SUBPART2,
BLIS_SUBPART1AND0,
BLIS_SUBPART1AND2,
BLIS_SUBPART1A,
BLIS_SUBPART1B,
BLIS_SUBPART00,
BLIS_SUBPART10,
BLIS_SUBPART20,
BLIS_SUBPART01,
BLIS_SUBPART11,
BLIS_SUBPART21,
BLIS_SUBPART02,
BLIS_SUBPART12,
BLIS_SUBPART22
} subpart_t;
// -- Matrix dimension type --
typedef enum
{
BLIS_M = 0,
BLIS_N = 1
} mdim_t;
// -- Machine parameter types --
typedef enum
{
BLIS_MACH_EPS = 0,
BLIS_MACH_SFMIN,
BLIS_MACH_BASE,
BLIS_MACH_PREC,
BLIS_MACH_NDIGMANT,
BLIS_MACH_RND,
BLIS_MACH_EMIN,
BLIS_MACH_RMIN,
BLIS_MACH_EMAX,
BLIS_MACH_RMAX,
BLIS_MACH_EPS2
} machval_t;
#define BLIS_NUM_MACH_PARAMS 11
#define BLIS_MACH_PARAM_FIRST BLIS_MACH_EPS
#define BLIS_MACH_PARAM_LAST BLIS_MACH_EPS2
// -- Induced method types --
typedef enum
{
BLIS_3MH = 0,
BLIS_3M1,
BLIS_4MH,
BLIS_4M1B,
BLIS_4M1A,
BLIS_1M,
BLIS_NAT,
BLIS_IND_FIRST = 0,
BLIS_IND_LAST = BLIS_NAT
} ind_t;
#define BLIS_NUM_IND_METHODS (BLIS_NAT+1)
// These are used in bli_*_oapi.c to construct the ind_t values from
// the induced method substrings that go into function names.
#define bli_3mh BLIS_3MH
#define bli_3m1 BLIS_3M1
#define bli_4mh BLIS_4MH
#define bli_4mb BLIS_4M1B
#define bli_4m1 BLIS_4M1A
#define bli_1m BLIS_1M
#define bli_nat BLIS_NAT
// -- Kernel ID types --
typedef enum
{
BLIS_ADDV_KER = 0,
BLIS_AMAXV_KER,
BLIS_AXPBYV_KER,
BLIS_AXPYV_KER,
BLIS_COPYV_KER,
BLIS_DOTV_KER,
BLIS_DOTXV_KER,
BLIS_INVERTV_KER,
BLIS_SCALV_KER,
BLIS_SCAL2V_KER,
BLIS_SETV_KER,
BLIS_SUBV_KER,
BLIS_SWAPV_KER,
BLIS_XPBYV_KER
} l1vkr_t;
#define BLIS_NUM_LEVEL1V_KERS 14
typedef enum
{
BLIS_AXPY2V_KER = 0,
BLIS_DOTAXPYV_KER,
BLIS_AXPYF_KER,
BLIS_DOTXF_KER,
BLIS_DOTXAXPYF_KER
} l1fkr_t;
#define BLIS_NUM_LEVEL1F_KERS 5
typedef enum
{
BLIS_PACKM_0XK_KER = 0,
BLIS_PACKM_1XK_KER = 1,
BLIS_PACKM_2XK_KER = 2,
BLIS_PACKM_3XK_KER = 3,
BLIS_PACKM_4XK_KER = 4,
BLIS_PACKM_5XK_KER = 5,
BLIS_PACKM_6XK_KER = 6,
BLIS_PACKM_7XK_KER = 7,
BLIS_PACKM_8XK_KER = 8,
BLIS_PACKM_9XK_KER = 9,
BLIS_PACKM_10XK_KER = 10,
BLIS_PACKM_11XK_KER = 11,
BLIS_PACKM_12XK_KER = 12,
BLIS_PACKM_13XK_KER = 13,
BLIS_PACKM_14XK_KER = 14,
BLIS_PACKM_15XK_KER = 15,
BLIS_PACKM_16XK_KER = 16,
BLIS_PACKM_17XK_KER = 17,
BLIS_PACKM_18XK_KER = 18,
BLIS_PACKM_19XK_KER = 19,
BLIS_PACKM_20XK_KER = 20,
BLIS_PACKM_21XK_KER = 21,
BLIS_PACKM_22XK_KER = 22,
BLIS_PACKM_23XK_KER = 23,
BLIS_PACKM_24XK_KER = 24,
BLIS_PACKM_25XK_KER = 25,
BLIS_PACKM_26XK_KER = 26,
BLIS_PACKM_27XK_KER = 27,
BLIS_PACKM_28XK_KER = 28,
BLIS_PACKM_29XK_KER = 29,
BLIS_PACKM_30XK_KER = 30,
BLIS_PACKM_31XK_KER = 31,
BLIS_UNPACKM_0XK_KER = 0,
BLIS_UNPACKM_1XK_KER = 1,
BLIS_UNPACKM_2XK_KER = 2,
BLIS_UNPACKM_3XK_KER = 3,
BLIS_UNPACKM_4XK_KER = 4,
BLIS_UNPACKM_5XK_KER = 5,
BLIS_UNPACKM_6XK_KER = 6,
BLIS_UNPACKM_7XK_KER = 7,
BLIS_UNPACKM_8XK_KER = 8,
BLIS_UNPACKM_9XK_KER = 9,
BLIS_UNPACKM_10XK_KER = 10,
BLIS_UNPACKM_11XK_KER = 11,
BLIS_UNPACKM_12XK_KER = 12,
BLIS_UNPACKM_13XK_KER = 13,
BLIS_UNPACKM_14XK_KER = 14,
BLIS_UNPACKM_15XK_KER = 15,
BLIS_UNPACKM_16XK_KER = 16,
BLIS_UNPACKM_17XK_KER = 17,
BLIS_UNPACKM_18XK_KER = 18,
BLIS_UNPACKM_19XK_KER = 19,
BLIS_UNPACKM_20XK_KER = 20,
BLIS_UNPACKM_21XK_KER = 21,
BLIS_UNPACKM_22XK_KER = 22,
BLIS_UNPACKM_23XK_KER = 23,
BLIS_UNPACKM_24XK_KER = 24,
BLIS_UNPACKM_25XK_KER = 25,
BLIS_UNPACKM_26XK_KER = 26,
BLIS_UNPACKM_27XK_KER = 27,
BLIS_UNPACKM_28XK_KER = 28,
BLIS_UNPACKM_29XK_KER = 29,
BLIS_UNPACKM_30XK_KER = 30,
BLIS_UNPACKM_31XK_KER = 31
} l1mkr_t;
#define BLIS_NUM_PACKM_KERS 32
#define BLIS_NUM_UNPACKM_KERS 32
typedef enum
{
BLIS_GEMM_UKR = 0,
BLIS_GEMMTRSM_L_UKR,
BLIS_GEMMTRSM_U_UKR,
BLIS_TRSM_L_UKR,
BLIS_TRSM_U_UKR
} l3ukr_t;
#define BLIS_NUM_LEVEL3_UKRS 5
typedef enum
{
BLIS_REFERENCE_UKERNEL = 0,
BLIS_VIRTUAL_UKERNEL,
BLIS_OPTIMIZED_UKERNEL,
BLIS_NOTAPPLIC_UKERNEL
} kimpl_t;
#define BLIS_NUM_UKR_IMPL_TYPES 4
#if 0
typedef enum
{
BLIS_JC_IDX = 0,
BLIS_PC_IDX,
BLIS_IC_IDX,
BLIS_JR_IDX,
BLIS_IR_IDX,
BLIS_PR_IDX
} thridx_t;
#endif
#define BLIS_NUM_LOOPS 6
// -- Operation ID type --
typedef enum
{
//
// NOTE: If/when additional type values are added to this enum,
// you must either:
// - keep the level-3 values (starting with _GEMM) beginning at
// index 0; or
// - if the value range is moved such that it does not begin at
// index 0, implement something like a BLIS_OPID_LEVEL3_RANGE_START
// value that can be subtracted from the opid_t value to map it
// to a zero-based range.
// This is needed because these level-3 opid_t values are used in
// bli_l3_ind.c to index into arrays.
//
BLIS_GEMM = 0,
BLIS_HEMM,
BLIS_HERK,
BLIS_HER2K,
BLIS_SYMM,
BLIS_SYRK,
BLIS_SYR2K,
BLIS_TRMM3,
BLIS_TRMM,
BLIS_TRSM,
BLIS_NOID
} opid_t;
#define BLIS_NUM_LEVEL3_OPS 10
// -- Blocksize ID type --
typedef enum
{
// NOTE: the level-3 blocksizes MUST be indexed starting at zero.
// At one point, we made this assumption in bli_cntx_set_blkszs()
// and friends.
BLIS_KR = 0,
BLIS_MR,
BLIS_NR,
BLIS_MC,
BLIS_KC,
BLIS_NC,
BLIS_M2, // level-2 blocksize in m dimension
BLIS_N2, // level-2 blocksize in n dimension
BLIS_AF, // level-1f axpyf fusing factor
BLIS_DF, // level-1f dotxf fusing factor
BLIS_XF, // level-1f dotxaxpyf fusing factor
BLIS_NO_PART // used as a placeholder when blocksizes are not applicable.
} bszid_t;
#define BLIS_NUM_BLKSZS 11
// -- Architecture ID type --
// NOTE: This typedef enum must be kept up-to-date with the arch_t
// string array in bli_arch.c. Whenever values are added/inserted
// OR if values are rearranged, be sure to update the string array
// in bli_arch.c.
typedef enum
{
// Intel
BLIS_ARCH_SKX = 0,
BLIS_ARCH_KNL,
BLIS_ARCH_KNC,
BLIS_ARCH_HASWELL,
BLIS_ARCH_SANDYBRIDGE,
BLIS_ARCH_PENRYN,
// AMD
BLIS_ARCH_ZEN,
BLIS_ARCH_EXCAVATOR,
BLIS_ARCH_STEAMROLLER,
BLIS_ARCH_PILEDRIVER,
BLIS_ARCH_BULLDOZER,
// ARM
BLIS_ARCH_THUNDERX2,
BLIS_ARCH_CORTEXA57,
BLIS_ARCH_CORTEXA53,
BLIS_ARCH_CORTEXA15,
BLIS_ARCH_CORTEXA9,
// IBM/Power
BLIS_ARCH_POWER9,
BLIS_ARCH_POWER7,
BLIS_ARCH_BGQ,
// Generic architecture/configuration
BLIS_ARCH_GENERIC
} arch_t;
#define BLIS_NUM_ARCHS 20
//
// -- BLIS misc. structure types -----------------------------------------------
//
// These headers must be included here (or earlier) because definitions they
// provide are needed in the pool_t and related structs.
#include "bli_pthread.h"
#include "bli_malloc.h"
// -- Pool block type --
typedef struct
{
void* buf;
siz_t block_size;
} pblk_t;
// -- Pool type --
typedef struct
{
void* block_ptrs;
dim_t block_ptrs_len;
dim_t top_index;
dim_t num_blocks;
siz_t block_size;
siz_t align_size;
malloc_ft malloc_fp;
free_ft free_fp;
} pool_t;
// -- Array type --
typedef struct
{
void* buf;
siz_t num_elem;
siz_t elem_size;
} array_t;
// -- Locked pool-of-arrays-of-pools type --
typedef struct
{
bli_pthread_mutex_t mutex;
pool_t pool;
siz_t def_array_len;
} apool_t;
// -- packing block allocator: Locked set of pools type --
typedef struct membrk_s
{
pool_t pools[3];
bli_pthread_mutex_t mutex;
// These fields are used for general-purpose allocation.
siz_t align_size;
malloc_ft malloc_fp;
free_ft free_fp;
} membrk_t;
// -- Memory object type --
typedef struct mem_s
{
pblk_t pblk;
packbuf_t buf_type;
pool_t* pool;
siz_t size;
} mem_t;
// -- Control tree node type --
struct cntl_s
{
// Basic fields (usually required).
opid_t family;
bszid_t bszid;
void* var_func;
struct cntl_s* sub_prenode;
struct cntl_s* sub_node;
// Optional fields (needed only by some operations such as packm).
// NOTE: first field of params must be a uint64_t containing the size
// of the struct.
void* params;
// Internal fields that track "cached" data.
mem_t pack_mem;
};
typedef struct cntl_s cntl_t;
// -- Blocksize object type --
typedef struct blksz_s
{
// Primary blocksize values.
dim_t v[BLIS_NUM_FP_TYPES];
// Blocksize extensions.
dim_t e[BLIS_NUM_FP_TYPES];
} blksz_t;
// -- Function pointer object type --
typedef struct func_s
{
// Kernel function address.
void* ptr[BLIS_NUM_FP_TYPES];
} func_t;
// -- Multi-boolean object type --
typedef struct mbool_s
{
bool_t v[BLIS_NUM_FP_TYPES];
} mbool_t;
// -- Auxiliary kernel info type --
// Note: This struct is used by macro-kernels to package together extra
// parameter values that may be of use to the micro-kernel without
// cluttering up the micro-kernel interface itself.
typedef struct
{
// The pack schemas of A and B.
pack_t schema_a;
pack_t schema_b;
// Pointers to the micro-panels of A and B which will be used by the
// next call to the micro-kernel.
void* a_next;
void* b_next;
// The imaginary strides of A and B.
inc_t is_a;
inc_t is_b;
// The type to convert to on output.
//num_t dt_on_output;
} auxinfo_t;
// -- Global scalar constant data struct --
// Note: This struct is used only when statically initializing the
// global scalar constants in bli_const.c.
typedef struct constdata_s
{
float s;
double d;
scomplex c;
dcomplex z;
gint_t i;
} constdata_t;
//
// -- BLIS object type definitions ---------------------------------------------
//
typedef struct obj_s
{
// Basic fields
struct obj_s* root;
dim_t off[2];
dim_t dim[2];
doff_t diag_off;
objbits_t info;
objbits_t info2;
siz_t elem_size;
void* buffer;
inc_t rs;
inc_t cs;
inc_t is;
// Bufferless scalar storage
atom_t scalar;
// Pack-related fields
dim_t m_padded; // m dimension of matrix, including any padding
dim_t n_padded; // n dimension of matrix, including any padding
inc_t ps; // panel stride (distance to next panel)
inc_t pd; // panel dimension (the "width" of a panel:
// usually MR or NR)
dim_t m_panel; // m dimension of a "full" panel
dim_t n_panel; // n dimension of a "full" panel
} obj_t;
// Define these macros here since they must be updated if contents of
// obj_t changes.
static void bli_obj_init_full_shallow_copy_of( obj_t* a, obj_t* b )
{
b->root = a->root;
b->off[0] = a->off[0];
b->off[1] = a->off[1];
b->dim[0] = a->dim[0];
b->dim[1] = a->dim[1];
b->diag_off = a->diag_off;
b->info = a->info;
b->info2 = a->info2;
b->elem_size = a->elem_size;
b->buffer = a->buffer;
b->rs = a->rs;
b->cs = a->cs;
b->is = a->is;
b->scalar = a->scalar;
//b->pack_mem = a->pack_mem;
b->m_padded = a->m_padded;
b->n_padded = a->n_padded;
b->ps = a->ps;
b->pd = a->pd;
b->m_panel = a->m_panel;
b->n_panel = a->n_panel;
}
static void bli_obj_init_subpart_from( obj_t* a, obj_t* b )
{
b->root = a->root;
b->off[0] = a->off[0];
b->off[1] = a->off[1];
// Avoid copying m and n since they will be overwritten.
//b->dim[0] = a->dim[0];
//b->dim[1] = a->dim[1];
b->diag_off = a->diag_off;
b->info = a->info;
b->info2 = a->info2;
b->elem_size = a->elem_size;
b->buffer = a->buffer;
b->rs = a->rs;
b->cs = a->cs;
b->is = a->is;
b->scalar = a->scalar;
// Avoid copying pack_mem entry.
// FGVZ: You should probably make sure this is right.
//b->pack_mem = a->pack_mem;
b->m_padded = a->m_padded;
b->n_padded = a->n_padded;
b->ps = a->ps;
b->pd = a->pd;
b->m_panel = a->m_panel;
b->n_panel = a->n_panel;
}
// -- Context type --
typedef struct cntx_s
{
blksz_t blkszs[ BLIS_NUM_BLKSZS ];
bszid_t bmults[ BLIS_NUM_BLKSZS ];
func_t l3_vir_ukrs[ BLIS_NUM_LEVEL3_UKRS ];
func_t l3_nat_ukrs[ BLIS_NUM_LEVEL3_UKRS ];
mbool_t l3_nat_ukrs_prefs[ BLIS_NUM_LEVEL3_UKRS ];
func_t l1f_kers[ BLIS_NUM_LEVEL1F_KERS ];
func_t l1v_kers[ BLIS_NUM_LEVEL1V_KERS ];
func_t packm_kers[ BLIS_NUM_PACKM_KERS ];
func_t unpackm_kers[ BLIS_NUM_UNPACKM_KERS ];
ind_t method;
pack_t schema_a_block;
pack_t schema_b_panel;
pack_t schema_c_panel;
} cntx_t;
// -- Runtime type --
typedef struct rntm_s
{
// "External" fields: these may be queried by the end-user.
dim_t num_threads;
dim_t thrloop[ BLIS_NUM_LOOPS ];
// "Internal" fields: these should not be exposed to the end-user.
// The small block pool, which is attached in the l3 thread decorator.
pool_t* sba_pool;
// The packing block allocator, which is attached in the l3 thread decorator.
membrk_t* membrk;
} rntm_t;
// -- Error types --
typedef enum
{
BLIS_NO_ERROR_CHECKING = 0,
BLIS_FULL_ERROR_CHECKING
} errlev_t;
typedef enum
{
// Generic error codes
BLIS_SUCCESS = ( -1),
BLIS_FAILURE = ( -2),
BLIS_ERROR_CODE_MIN = ( -9),
// General errors
BLIS_INVALID_ERROR_CHECKING_LEVEL = ( -10),
BLIS_UNDEFINED_ERROR_CODE = ( -11),
BLIS_NULL_POINTER = ( -12),
BLIS_NOT_YET_IMPLEMENTED = ( -13),
// Parameter-specific errors
BLIS_INVALID_SIDE = ( -20),
BLIS_INVALID_UPLO = ( -21),
BLIS_INVALID_TRANS = ( -22),
BLIS_INVALID_CONJ = ( -23),
BLIS_INVALID_DIAG = ( -24),
BLIS_INVALID_MACHVAL = ( -25),
BLIS_EXPECTED_NONUNIT_DIAG = ( -26),
// Datatype-specific errors
BLIS_INVALID_DATATYPE = ( -30),
BLIS_EXPECTED_FLOATING_POINT_DATATYPE = ( -31),
BLIS_EXPECTED_NONINTEGER_DATATYPE = ( -32),
BLIS_EXPECTED_NONCONSTANT_DATATYPE = ( -33),
BLIS_EXPECTED_REAL_DATATYPE = ( -34),
BLIS_EXPECTED_INTEGER_DATATYPE = ( -35),
BLIS_INCONSISTENT_DATATYPES = ( -36),
BLIS_EXPECTED_REAL_PROJ_OF = ( -37),
BLIS_EXPECTED_REAL_VALUED_OBJECT = ( -38),
BLIS_INCONSISTENT_PRECISIONS = ( -39),
// Dimension-specific errors
BLIS_NONCONFORMAL_DIMENSIONS = ( -40),
BLIS_EXPECTED_SCALAR_OBJECT = ( -41),
BLIS_EXPECTED_VECTOR_OBJECT = ( -42),
BLIS_UNEQUAL_VECTOR_LENGTHS = ( -43),
BLIS_EXPECTED_SQUARE_OBJECT = ( -44),
BLIS_UNEXPECTED_OBJECT_LENGTH = ( -45),
BLIS_UNEXPECTED_OBJECT_WIDTH = ( -46),
BLIS_UNEXPECTED_VECTOR_DIM = ( -47),
BLIS_UNEXPECTED_DIAG_OFFSET = ( -48),
BLIS_NEGATIVE_DIMENSION = ( -49),
// Stride-specific errors
BLIS_INVALID_ROW_STRIDE = ( -50),
BLIS_INVALID_COL_STRIDE = ( -51),
BLIS_INVALID_DIM_STRIDE_COMBINATION = ( -52),
// Structure-specific errors
BLIS_EXPECTED_GENERAL_OBJECT = ( -60),
BLIS_EXPECTED_HERMITIAN_OBJECT = ( -61),
BLIS_EXPECTED_SYMMETRIC_OBJECT = ( -62),
BLIS_EXPECTED_TRIANGULAR_OBJECT = ( -63),
// Storage-specific errors
BLIS_EXPECTED_UPPER_OR_LOWER_OBJECT = ( -70),
// Partitioning-specific errors
BLIS_INVALID_3x1_SUBPART = ( -80),
BLIS_INVALID_1x3_SUBPART = ( -81),
BLIS_INVALID_3x3_SUBPART = ( -82),
// Control tree-specific errors
BLIS_UNEXPECTED_NULL_CONTROL_TREE = ( -90),
// Packing-specific errors
BLIS_PACK_SCHEMA_NOT_SUPPORTED_FOR_UNPACK = (-100),
// Buffer-specific errors
BLIS_EXPECTED_NONNULL_OBJECT_BUFFER = (-110),
// Memory errors
BLIS_MALLOC_RETURNED_NULL = (-120),
// Internal memory pool errors
BLIS_INVALID_PACKBUF = (-130),
BLIS_EXHAUSTED_CONTIG_MEMORY_POOL = (-131),
BLIS_INSUFFICIENT_STACK_BUF_SIZE = (-132),
BLIS_ALIGNMENT_NOT_POWER_OF_TWO = (-133),
BLIS_ALIGNMENT_NOT_MULT_OF_PTR_SIZE = (-134),
// Object-related errors
BLIS_EXPECTED_OBJECT_ALIAS = (-140),
// Architecture-related errors
BLIS_INVALID_ARCH_ID = (-150),
// Blocksize-related errors
BLIS_MC_DEF_NONMULTIPLE_OF_MR = (-160),
BLIS_MC_MAX_NONMULTIPLE_OF_MR = (-161),
BLIS_NC_DEF_NONMULTIPLE_OF_NR = (-162),
BLIS_NC_MAX_NONMULTIPLE_OF_NR = (-163),
BLIS_KC_DEF_NONMULTIPLE_OF_KR = (-164),
BLIS_KC_MAX_NONMULTIPLE_OF_KR = (-165),
BLIS_ERROR_CODE_MAX = (-170)
} err_t;
#endif
| 30.021277 | 120 | 0.667856 | [
"object",
"vector"
] |
d2c757f020ef42da89f053fa0c24e99e1f6312b6 | 235,154 | c | C | modules/es/ut-coverage/es_UT.c | zachar1a/cFE | 9d4fcaed503f243683d144b30a003583d8f4f217 | [
"Apache-2.0"
] | null | null | null | modules/es/ut-coverage/es_UT.c | zachar1a/cFE | 9d4fcaed503f243683d144b30a003583d8f4f217 | [
"Apache-2.0"
] | null | null | null | modules/es/ut-coverage/es_UT.c | zachar1a/cFE | 9d4fcaed503f243683d144b30a003583d8f4f217 | [
"Apache-2.0"
] | null | null | null | /*
** GSC-18128-1, "Core Flight Executive Version 6.7"
**
** Copyright (c) 2006-2019 United States Government as represented by
** the Administrator of the National Aeronautics and Space Administration.
** All Rights Reserved.
**
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
/*
** File:
** es_UT.c
**
** Purpose:
** Executive Services unit test
**
** References:
** 1. cFE Application Developers Guide
** 2. unit test standard 092503
** 3. C Coding Standard 102904
**
** Notes:
** 1. This is unit test code only, not for use in flight
**
*/
/*
** Includes
*/
#include "es_UT.h"
#define ES_UT_CDS_BLOCK_SIZE 16
/*
* A size which meets the minimum CDS size
* requirements for the implementation, but
* not much larger.
*/
#define ES_UT_CDS_SMALL_TEST_SIZE (56 * 1024)
/*
* A size which has room for actual allocations
*/
#define ES_UT_CDS_LARGE_TEST_SIZE (128 * 1024)
extern CFE_ES_Global_t CFE_ES_Global;
extern int32 dummy_function(void);
/*
** Global variables
*/
/*
* Pointer to reset data that will be re-configured/preserved across calls to ES_ResetUnitTest()
*/
static CFE_ES_ResetData_t *ES_UT_PersistentResetData = NULL;
/* Buffers to support memory pool testing */
typedef union
{
CFE_ES_PoolAlign_t Align; /* make aligned */
uint8 Data[300];
} CFE_ES_GMP_DirectBuffer_t;
typedef struct
{
CFE_ES_GenPoolBD_t BD;
CFE_ES_PoolAlign_t Align; /* make aligned */
uint8 Spare; /* make unaligned */
uint8 Data[(sizeof(CFE_ES_GenPoolBD_t) * 4) + 157]; /* oddball size */
} CFE_ES_GMP_IndirectBuffer_t;
CFE_ES_GMP_DirectBuffer_t UT_MemPoolDirectBuffer;
CFE_ES_GMP_IndirectBuffer_t UT_MemPoolIndirectBuffer;
/* Create a startup script buffer for a maximum of 5 lines * 80 chars/line */
char StartupScript[MAX_STARTUP_SCRIPT];
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_NOOP_CC = {.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID),
.CommandCode = CFE_ES_NOOP_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_RESET_COUNTERS_CC = {
.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID), .CommandCode = CFE_ES_RESET_COUNTERS_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_RESTART_CC = {.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID),
.CommandCode = CFE_ES_RESTART_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_START_APP_CC = {
.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID), .CommandCode = CFE_ES_START_APP_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_STOP_APP_CC = {.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID),
.CommandCode = CFE_ES_STOP_APP_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_RESTART_APP_CC = {
.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID), .CommandCode = CFE_ES_RESTART_APP_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_RELOAD_APP_CC = {
.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID), .CommandCode = CFE_ES_RELOAD_APP_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_QUERY_ONE_CC = {
.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID), .CommandCode = CFE_ES_QUERY_ONE_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_QUERY_ALL_CC = {
.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID), .CommandCode = CFE_ES_QUERY_ALL_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_QUERY_ALL_TASKS_CC = {
.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID), .CommandCode = CFE_ES_QUERY_ALL_TASKS_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_CLEAR_SYSLOG_CC = {
.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID), .CommandCode = CFE_ES_CLEAR_SYSLOG_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_WRITE_SYSLOG_CC = {
.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID), .CommandCode = CFE_ES_WRITE_SYSLOG_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_OVER_WRITE_SYSLOG_CC = {
.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID), .CommandCode = CFE_ES_OVER_WRITE_SYSLOG_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_CLEAR_ER_LOG_CC = {
.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID), .CommandCode = CFE_ES_CLEAR_ER_LOG_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_WRITE_ER_LOG_CC = {
.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID), .CommandCode = CFE_ES_WRITE_ER_LOG_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_START_PERF_DATA_CC = {
.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID), .CommandCode = CFE_ES_START_PERF_DATA_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_STOP_PERF_DATA_CC = {
.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID), .CommandCode = CFE_ES_STOP_PERF_DATA_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_SET_PERF_FILTER_MASK_CC = {
.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID), .CommandCode = CFE_ES_SET_PERF_FILTER_MASK_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_SET_PERF_TRIGGER_MASK_CC = {
.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID), .CommandCode = CFE_ES_SET_PERF_TRIGGER_MASK_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_RESET_PR_COUNT_CC = {
.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID), .CommandCode = CFE_ES_RESET_PR_COUNT_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_SET_MAX_PR_COUNT_CC = {
.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID), .CommandCode = CFE_ES_SET_MAX_PR_COUNT_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_DELETE_CDS_CC = {
.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID), .CommandCode = CFE_ES_DELETE_CDS_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_SEND_MEM_POOL_STATS_CC = {
.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID), .CommandCode = CFE_ES_SEND_MEM_POOL_STATS_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_DUMP_CDS_REGISTRY_CC = {
.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID), .CommandCode = CFE_ES_DUMP_CDS_REGISTRY_CC};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_CMD_INVALID_CC = {.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_CMD_MID),
.CommandCode = CFE_ES_DUMP_CDS_REGISTRY_CC + 2};
static const UT_TaskPipeDispatchId_t UT_TPID_CFE_ES_SEND_HK = {.MsgId = CFE_SB_MSGID_WRAP_VALUE(CFE_ES_SEND_HK_MID)};
/*
** Functions
*/
CFE_ResourceId_t ES_UT_MakeAppIdForIndex(uint32 ArrayIdx)
{
/* UT hack - make up AppID values in a manner similar to FSW.
* Real apps should never do this. */
return CFE_ResourceId_FromInteger(ArrayIdx + CFE_ES_APPID_BASE);
}
CFE_ResourceId_t ES_UT_MakeTaskIdForIndex(uint32 ArrayIdx)
{
/* UT hack - make up TaskID values in a manner similar to FSW.
* Real apps should never do this. */
uint32 Base;
/* The base to use depends on whether STRICT mode is enabled or not */
#ifndef CFE_RESOURCEID_STRICT //_MODE
Base = CFE_ES_TASKID_BASE;
#else
Base = 0x40010000; /* note this is NOT the same as the normal OSAL task ID base */
#endif
return CFE_ResourceId_FromInteger(ArrayIdx + Base);
}
CFE_ResourceId_t ES_UT_MakeLibIdForIndex(uint32 ArrayIdx)
{
/* UT hack - make up LibID values in a manner similar to FSW.
* Real apps should never do this. */
return CFE_ResourceId_FromInteger(ArrayIdx + CFE_ES_LIBID_BASE);
}
CFE_ResourceId_t ES_UT_MakeCounterIdForIndex(uint32 ArrayIdx)
{
/* UT hack - make up CounterID values in a manner similar to FSW.
* Real apps should never do this. */
return CFE_ResourceId_FromInteger(ArrayIdx + CFE_ES_COUNTID_BASE);
}
CFE_ResourceId_t ES_UT_MakePoolIdForIndex(uint32 ArrayIdx)
{
/* UT hack - make up PoolID values in a manner similar to FSW.
* Real apps should never do this. */
return CFE_ResourceId_FromInteger(ArrayIdx + CFE_ES_POOLID_BASE);
}
CFE_ResourceId_t ES_UT_MakeCDSIdForIndex(uint32 ArrayIdx)
{
/* UT hack - make up CDSID values in a manner similar to FSW.
* Real apps should never do this. */
return CFE_ResourceId_FromInteger(ArrayIdx + CFE_ES_CDSBLOCKID_BASE);
}
/*
* A local stub that can serve as the user function for testing ES tasks
*/
void ES_UT_TaskFunction(void)
{
UT_DEFAULT_IMPL(ES_UT_TaskFunction);
}
/*
* Helper function to assemble basic bits of info into the "CFE_ES_ModuleLoadParams_t" struct
*/
void ES_UT_SetupModuleLoadParams(CFE_ES_ModuleLoadParams_t *Params, const char *FileName, const char *EntryName)
{
char Empty = 0;
if (FileName == NULL)
{
FileName = &Empty;
}
if (EntryName == NULL)
{
EntryName = &Empty;
}
strncpy(Params->FileName, FileName, sizeof(Params->FileName));
strncpy(Params->InitSymbolName, EntryName, sizeof(Params->InitSymbolName));
}
/*
* Helper function to assemble basic bits of info into the "CFE_ES_AppStartParams_t" struct
*/
void ES_UT_SetupAppStartParams(CFE_ES_AppStartParams_t *Params, const char *FileName, const char *EntryName,
size_t StackSize, CFE_ES_TaskPriority_Atom_t Priority,
CFE_ES_ExceptionAction_Enum_t ExceptionAction)
{
ES_UT_SetupModuleLoadParams(&Params->BasicInfo, FileName, EntryName);
Params->MainTaskInfo.StackSize = StackSize;
Params->MainTaskInfo.Priority = Priority;
Params->ExceptionAction = ExceptionAction;
}
/*
* Helper function to setup a single app ID in the given state, along with
* a main task ID. A pointer to the App and Task record is output so the
* record can be modified
*/
void ES_UT_SetupSingleAppId(CFE_ES_AppType_Enum_t AppType, CFE_ES_AppState_Enum_t AppState, const char *AppName,
CFE_ES_AppRecord_t **OutAppRec, CFE_ES_TaskRecord_t **OutTaskRec)
{
osal_id_t UtOsalId;
CFE_ResourceId_t UtTaskId;
CFE_ResourceId_t UtAppId;
CFE_ES_AppRecord_t * LocalAppPtr;
CFE_ES_TaskRecord_t *LocalTaskPtr;
OS_TaskCreate(&UtOsalId, "UT", NULL, OSAL_TASK_STACK_ALLOCATE, 0, 0, 0);
UtTaskId = CFE_RESOURCEID_UNWRAP(CFE_ES_TaskId_FromOSAL(UtOsalId));
UtAppId = CFE_ES_Global.LastAppId;
CFE_ES_Global.LastAppId = CFE_ResourceId_FromInteger(CFE_ResourceId_ToInteger(UtAppId) + 1);
LocalTaskPtr = CFE_ES_LocateTaskRecordByID(CFE_ES_TASKID_C(UtTaskId));
LocalAppPtr = CFE_ES_LocateAppRecordByID(CFE_ES_APPID_C(UtAppId));
CFE_ES_TaskRecordSetUsed(LocalTaskPtr, UtTaskId);
CFE_ES_AppRecordSetUsed(LocalAppPtr, UtAppId);
LocalTaskPtr->AppId = CFE_ES_AppRecordGetID(LocalAppPtr);
LocalAppPtr->MainTaskId = CFE_ES_TaskRecordGetID(LocalTaskPtr);
LocalAppPtr->AppState = AppState;
LocalAppPtr->Type = AppType;
if (AppName)
{
strncpy(LocalAppPtr->AppName, AppName, sizeof(LocalAppPtr->AppName) - 1);
LocalAppPtr->AppName[sizeof(LocalAppPtr->AppName) - 1] = 0;
strncpy(LocalTaskPtr->TaskName, AppName, sizeof(LocalTaskPtr->TaskName) - 1);
LocalTaskPtr->TaskName[sizeof(LocalTaskPtr->TaskName) - 1] = 0;
}
if (OutAppRec)
{
*OutAppRec = LocalAppPtr;
}
if (OutTaskRec)
{
*OutTaskRec = LocalTaskPtr;
}
if (AppType == CFE_ES_AppType_CORE)
{
++CFE_ES_Global.RegisteredCoreApps;
}
if (AppType == CFE_ES_AppType_EXTERNAL)
{
++CFE_ES_Global.RegisteredExternalApps;
OS_ModuleLoad(&UtOsalId, NULL, NULL, 0);
LocalAppPtr->LoadStatus.ModuleId = UtOsalId;
}
++CFE_ES_Global.RegisteredTasks;
}
/*
* Helper function to setup a child task ID associated with the given
* app record. A pointer to the Task record is output so the record
* can be modified
*/
void ES_UT_SetupChildTaskId(const CFE_ES_AppRecord_t *ParentApp, const char *TaskName, CFE_ES_TaskRecord_t **OutTaskRec)
{
osal_id_t UtOsalId;
CFE_ES_TaskId_t UtTaskId;
CFE_ES_AppId_t UtAppId;
CFE_ES_TaskRecord_t *LocalTaskPtr;
UtAppId = CFE_ES_AppRecordGetID(ParentApp);
OS_TaskCreate(&UtOsalId, "C", NULL, OSAL_TASK_STACK_ALLOCATE, 0, 0, 0);
UtTaskId = CFE_ES_TaskId_FromOSAL(UtOsalId);
LocalTaskPtr = CFE_ES_LocateTaskRecordByID(UtTaskId);
CFE_ES_TaskRecordSetUsed(LocalTaskPtr, CFE_RESOURCEID_UNWRAP(UtTaskId));
LocalTaskPtr->AppId = UtAppId;
if (TaskName)
{
strncpy(LocalTaskPtr->TaskName, TaskName, sizeof(LocalTaskPtr->TaskName) - 1);
LocalTaskPtr->TaskName[sizeof(LocalTaskPtr->TaskName) - 1] = 0;
}
if (OutTaskRec)
{
*OutTaskRec = LocalTaskPtr;
}
++CFE_ES_Global.RegisteredTasks;
}
/*
* Helper function to setup a single Lib ID. A pointer to the Lib
* record is output so the record can be modified
*/
void ES_UT_SetupSingleLibId(const char *LibName, CFE_ES_LibRecord_t **OutLibRec)
{
CFE_ResourceId_t UtLibId;
CFE_ES_LibRecord_t *LocalLibPtr;
UtLibId = CFE_ES_Global.LastLibId;
CFE_ES_Global.LastLibId = CFE_ResourceId_FromInteger(CFE_ResourceId_ToInteger(UtLibId) + 1);
LocalLibPtr = CFE_ES_LocateLibRecordByID(CFE_ES_LIBID_C(UtLibId));
CFE_ES_LibRecordSetUsed(LocalLibPtr, UtLibId);
if (LibName)
{
strncpy(LocalLibPtr->LibName, LibName, sizeof(LocalLibPtr->LibName) - 1);
LocalLibPtr->LibName[sizeof(LocalLibPtr->LibName) - 1] = 0;
}
if (OutLibRec)
{
*OutLibRec = LocalLibPtr;
}
++CFE_ES_Global.RegisteredLibs;
}
int32 ES_UT_PoolDirectRetrieve(CFE_ES_GenPoolRecord_t *PoolRecPtr, size_t Offset, CFE_ES_GenPoolBD_t **BdPtr)
{
*BdPtr = (CFE_ES_GenPoolBD_t *)((void *)&UT_MemPoolDirectBuffer.Data[Offset]);
return CFE_SUCCESS;
}
int32 ES_UT_PoolDirectCommit(CFE_ES_GenPoolRecord_t *PoolRecPtr, size_t Offset, const CFE_ES_GenPoolBD_t *BdPtr)
{
return CFE_SUCCESS;
}
int32 ES_UT_PoolIndirectRetrieve(CFE_ES_GenPoolRecord_t *PoolRecPtr, size_t Offset, CFE_ES_GenPoolBD_t **BdPtr)
{
memcpy(&UT_MemPoolIndirectBuffer.BD, &UT_MemPoolIndirectBuffer.Data[Offset], sizeof(CFE_ES_GenPoolBD_t));
*BdPtr = &UT_MemPoolIndirectBuffer.BD;
return CFE_SUCCESS;
}
int32 ES_UT_PoolIndirectCommit(CFE_ES_GenPoolRecord_t *PoolRecPtr, size_t Offset, const CFE_ES_GenPoolBD_t *BdPtr)
{
memcpy(&UT_MemPoolIndirectBuffer.Data[Offset], BdPtr, sizeof(CFE_ES_GenPoolBD_t));
return CFE_SUCCESS;
}
int32 ES_UT_CDSPoolRetrieve(CFE_ES_GenPoolRecord_t *PoolRecPtr, size_t Offset, CFE_ES_GenPoolBD_t **BdPtr)
{
static CFE_ES_GenPoolBD_t BdBuf;
*BdPtr = &BdBuf;
return CFE_PSP_ReadFromCDS(&BdBuf, Offset, sizeof(BdBuf));
}
int32 ES_UT_CDSPoolCommit(CFE_ES_GenPoolRecord_t *PoolRecPtr, size_t Offset, const CFE_ES_GenPoolBD_t *BdPtr)
{
return CFE_PSP_WriteToCDS(BdPtr, Offset, sizeof(*BdPtr));
}
void ES_UT_SetupMemPoolId(CFE_ES_MemPoolRecord_t **OutPoolRecPtr)
{
CFE_ResourceId_t UtPoolID;
CFE_ES_MemPoolRecord_t *LocalPoolRecPtr;
UtPoolID = CFE_ES_Global.LastMemPoolId;
CFE_ES_Global.LastMemPoolId = CFE_ResourceId_FromInteger(CFE_ResourceId_ToInteger(UtPoolID) + 1);
LocalPoolRecPtr = CFE_ES_LocateMemPoolRecordByID(CFE_ES_MEMHANDLE_C(UtPoolID));
/* in order to validate the size must be nonzero */
LocalPoolRecPtr->Pool.PoolTotalSize = sizeof(UT_MemPoolDirectBuffer.Data);
LocalPoolRecPtr->Pool.PoolMaxOffset = sizeof(UT_MemPoolDirectBuffer.Data);
LocalPoolRecPtr->Pool.Buckets[0].BlockSize = 16;
LocalPoolRecPtr->Pool.NumBuckets = 1;
LocalPoolRecPtr->Pool.Retrieve = ES_UT_PoolDirectRetrieve;
LocalPoolRecPtr->Pool.Commit = ES_UT_PoolDirectCommit;
LocalPoolRecPtr->BaseAddr = (cpuaddr)UT_MemPoolDirectBuffer.Data;
OS_MutSemCreate(&LocalPoolRecPtr->MutexId, NULL, 0);
CFE_ES_MemPoolRecordSetUsed(LocalPoolRecPtr, UtPoolID);
if (OutPoolRecPtr)
{
*OutPoolRecPtr = LocalPoolRecPtr;
}
}
void ES_UT_SetupCDSGlobal(uint32 CDS_Size)
{
CFE_ES_CDS_Instance_t *CDS = &CFE_ES_Global.CDSVars;
UT_SetCDSSize(CDS_Size);
if (CDS_Size > CDS_RESERVED_MIN_SIZE)
{
OS_MutSemCreate(&CDS->GenMutex, "UT", 0);
CDS->TotalSize = CDS_Size;
CDS->DataSize = CDS->TotalSize;
CDS->DataSize -= CDS_RESERVED_MIN_SIZE;
CFE_ES_InitCDSSignatures();
CFE_ES_CreateCDSPool(CDS->DataSize, CDS_POOL_OFFSET);
CFE_ES_InitCDSRegistry();
CFE_ES_Global.CDSIsAvailable = true;
}
}
void ES_UT_SetupSingleCDSRegistry(const char *CDSName, size_t BlockSize, bool IsTable, CFE_ES_CDS_RegRec_t **OutRegRec)
{
CFE_ES_CDS_RegRec_t *LocalRegRecPtr;
CFE_ResourceId_t UtCDSID;
CFE_ES_GenPoolBD_t LocalBD;
size_t UT_CDS_BufferSize;
/* first time this is done, set up the global */
if (!CFE_ES_Global.CDSIsAvailable)
{
UT_GetDataBuffer(UT_KEY(CFE_PSP_GetCDSSize), NULL, &UT_CDS_BufferSize, NULL);
if (UT_CDS_BufferSize > (2 * CFE_ES_CDS_SIGNATURE_LEN))
{
/* Use the CDS buffer from ut_support.c if it was configured */
CFE_ES_Global.CDSVars.Pool.PoolMaxOffset = UT_CDS_BufferSize - CFE_ES_CDS_SIGNATURE_LEN;
CFE_ES_Global.CDSVars.Pool.Retrieve = ES_UT_CDSPoolRetrieve;
CFE_ES_Global.CDSVars.Pool.Commit = ES_UT_CDSPoolCommit;
}
else
{
CFE_ES_Global.CDSVars.Pool.PoolMaxOffset = sizeof(UT_MemPoolIndirectBuffer.Data);
CFE_ES_Global.CDSVars.Pool.Retrieve = ES_UT_PoolIndirectRetrieve;
CFE_ES_Global.CDSVars.Pool.Commit = ES_UT_PoolIndirectCommit;
}
CFE_ES_Global.CDSVars.Pool.Buckets[0].BlockSize = ES_UT_CDS_BLOCK_SIZE;
CFE_ES_Global.CDSVars.Pool.NumBuckets = 1;
CFE_ES_Global.CDSVars.Pool.TailPosition = CFE_ES_CDS_SIGNATURE_LEN;
CFE_ES_Global.CDSVars.Pool.PoolTotalSize =
CFE_ES_Global.CDSVars.Pool.PoolMaxOffset - CFE_ES_Global.CDSVars.Pool.TailPosition;
CFE_ES_Global.CDSIsAvailable = true;
}
UtCDSID = CFE_ES_Global.CDSVars.LastCDSBlockId;
CFE_ES_Global.CDSVars.LastCDSBlockId = CFE_ResourceId_FromInteger(CFE_ResourceId_ToInteger(UtCDSID) + 1);
LocalRegRecPtr = CFE_ES_LocateCDSBlockRecordByID(CFE_ES_CDSHANDLE_C(UtCDSID));
if (CDSName != NULL)
{
strncpy(LocalRegRecPtr->Name, CDSName, sizeof(LocalRegRecPtr->Name) - 1);
LocalRegRecPtr->Name[sizeof(LocalRegRecPtr->Name) - 1] = 0;
}
else
{
LocalRegRecPtr->Name[0] = 0;
}
LocalRegRecPtr->Table = IsTable;
LocalRegRecPtr->BlockOffset = CFE_ES_Global.CDSVars.Pool.TailPosition + sizeof(LocalBD);
LocalRegRecPtr->BlockSize = BlockSize;
LocalBD.CheckBits = CFE_ES_CHECK_PATTERN;
LocalBD.Allocated = CFE_ES_MEMORY_ALLOCATED + 1;
LocalBD.ActualSize = BlockSize;
LocalBD.NextOffset = 0;
CFE_ES_Global.CDSVars.Pool.Commit(&CFE_ES_Global.CDSVars.Pool, CFE_ES_Global.CDSVars.Pool.TailPosition, &LocalBD);
CFE_ES_Global.CDSVars.Pool.TailPosition = LocalRegRecPtr->BlockOffset + LocalRegRecPtr->BlockSize;
CFE_ES_CDSBlockRecordSetUsed(LocalRegRecPtr, UtCDSID);
if (OutRegRec)
{
*OutRegRec = LocalRegRecPtr;
}
}
int32 ES_UT_SetupOSCleanupHook(void *UserObj, int32 StubRetcode, uint32 CallCount, const UT_StubContext_t *Context)
{
osal_id_t ObjList[7];
/* On the first call, Use the stub functions to generate one object of
* each type
*/
if (CallCount == 0)
{
OS_TaskCreate(&ObjList[0], NULL, NULL, OSAL_TASK_STACK_ALLOCATE, 0, 0, 0);
OS_QueueCreate(&ObjList[1], NULL, 0, 0, 0);
OS_MutSemCreate(&ObjList[2], NULL, 0);
OS_BinSemCreate(&ObjList[3], NULL, 0, 0);
OS_CountSemCreate(&ObjList[4], NULL, 0, 0);
OS_TimerCreate(&ObjList[5], NULL, NULL, NULL);
OS_OpenCreate(&ObjList[6], NULL, 0, 0);
UT_SetDataBuffer((UT_EntryKey_t)&OS_ForEachObject, ObjList, sizeof(ObjList), true);
}
return StubRetcode;
}
static void ES_UT_SetupForOSCleanup(void)
{
UT_SetHookFunction(UT_KEY(OS_ForEachObject), ES_UT_SetupOSCleanupHook, NULL);
}
typedef struct
{
uint32 AppType;
uint32 AppState;
} ES_UT_SetAppStateHook_t;
static int32 ES_UT_SetAppStateHook(void *UserObj, int32 StubRetcode, uint32 CallCount, const UT_StubContext_t *Context)
{
ES_UT_SetAppStateHook_t *StateHook = UserObj;
uint32 i;
CFE_ES_AppRecord_t * AppRecPtr;
AppRecPtr = CFE_ES_Global.AppTable;
for (i = 0; i < CFE_PLATFORM_ES_MAX_APPLICATIONS; ++i)
{
if (CFE_ES_AppRecordIsUsed(AppRecPtr))
{
/* If no filter object supplied, set all apps to RUNNING */
if (StateHook == NULL)
{
AppRecPtr->AppState = CFE_ES_AppState_RUNNING;
}
else if (StateHook->AppType == 0 || AppRecPtr->Type == StateHook->AppType)
{
AppRecPtr->AppState = StateHook->AppState;
}
}
++AppRecPtr;
}
return StubRetcode;
}
void UtTest_Setup(void)
{
UT_Init("es");
UtPrintf("cFE ES Unit Test Output File\n\n");
UT_ADD_TEST(TestInit);
UT_ADD_TEST(TestStartupErrorPaths);
UT_ADD_TEST(TestResourceID);
UT_ADD_TEST(TestApps);
UT_ADD_TEST(TestLibs);
UT_ADD_TEST(TestERLog);
UT_ADD_TEST(TestTask);
UT_ADD_TEST(TestPerf);
UT_ADD_TEST(TestAPI);
UT_ADD_TEST(TestGenericCounterAPI);
UT_ADD_TEST(TestCDS);
UT_ADD_TEST(TestGenericPool);
UT_ADD_TEST(TestCDSMempool);
UT_ADD_TEST(TestESMempool);
UT_ADD_TEST(TestSysLog);
UT_ADD_TEST(TestBackground);
}
/*
** Reset variable values prior to a test
*/
void ES_ResetUnitTest(void)
{
UT_InitData();
memset(&CFE_ES_Global, 0, sizeof(CFE_ES_Global));
/*
** Initialize the Last Id
*/
CFE_ES_Global.LastAppId = CFE_ResourceId_FromInteger(CFE_ES_APPID_BASE);
CFE_ES_Global.LastLibId = CFE_ResourceId_FromInteger(CFE_ES_LIBID_BASE);
CFE_ES_Global.LastCounterId = CFE_ResourceId_FromInteger(CFE_ES_COUNTID_BASE);
CFE_ES_Global.LastMemPoolId = CFE_ResourceId_FromInteger(CFE_ES_POOLID_BASE);
CFE_ES_Global.CDSVars.LastCDSBlockId = CFE_ResourceId_FromInteger(CFE_ES_CDSBLOCKID_BASE);
/*
* (Re-)Initialize the reset data pointer
* This was formerly a separate global, but now part of CFE_ES_Global.
*
* Some unit tests assume/rely on it preserving its value across tests,
* so is must be re-initialized here every time CFE_ES_Global is reset.
*/
CFE_ES_Global.ResetDataPtr = ES_UT_PersistentResetData;
} /* end ES_ResetUnitTest() */
void TestInit(void)
{
UtPrintf("Begin Test Init");
UT_SetCDSSize(128 * 1024);
UT_SetSizeofESResetArea(sizeof(CFE_ES_ResetData_t));
/* Set up the reset area */
UT_SetStatusBSPResetArea(OS_SUCCESS, CFE_TIME_RESET_SIGNATURE, CFE_TIME_ToneSignalSelect_PRIMARY);
/* Set up the startup script for reading */
strncpy(StartupScript,
"CFE_LIB, /cf/apps/tst_lib.bundle, TST_LIB_Init, TST_LIB, 0, 0, 0x0, 1; "
"CFE_APP, /cf/apps/ci.bundle, CI_task_main, CI_APP, 70, 4096, 0x0, 1; "
"CFE_APP, /cf/apps/sch.bundle, SCH_TaskMain, SCH_APP, 120, 4096, 0x0, 1; "
"CFE_APP, /cf/apps/to.bundle, TO_task_main, TO_APP, 74, 4096, 0x0, 1; !",
sizeof(StartupScript) - 1);
StartupScript[sizeof(StartupScript) - 1] = '\0';
UT_SetReadBuffer(StartupScript, strlen(StartupScript));
/* Go through ES_Main and cover normal paths */
UT_SetDummyFuncRtn(OS_SUCCESS);
UT_SetHookFunction(UT_KEY(OS_TaskCreate), ES_UT_SetAppStateHook, NULL);
CFE_ES_Main(CFE_PSP_RST_TYPE_POWERON, CFE_PSP_RST_SUBTYPE_POWER_CYCLE, 1, "ut_startup");
UtAssert_STUB_COUNT(CFE_PSP_Panic, 0);
}
void TestStartupErrorPaths(void)
{
int j;
ES_UT_SetAppStateHook_t StateHook;
uint32 PanicStatus;
uint32 ResetType;
OS_statvfs_t StatBuf;
CFE_ES_TaskRecord_t * TaskRecPtr;
CFE_ES_AppRecord_t * AppRecPtr;
UtPrintf("Begin Test Startup Error Paths");
/*
* Get the reference to the reset area and save it so it will be preserved
* across calls to ES_ResetUnitTest(). This is required since now the pointer
* is part of CFE_ES_Global which is zeroed out as part of test reset. Formerly
* this was a separate global which was not cleared with the other globals.
*/
UT_GetDataBuffer(UT_KEY(CFE_PSP_GetResetArea), (void **)&ES_UT_PersistentResetData, NULL, NULL);
/* Set up the startup script for reading */
strncpy(StartupScript,
"CFE_LIB, /cf/apps/tst_lib.bundle, TST_LIB_Init, TST_LIB, 0, 0, 0x0, 1; "
"CFE_APP, /cf/apps/ci.bundle, CI_task_main, CI_APP, 70, 4096, 0x0, 1; "
"CFE_APP, /cf/apps/sch.bundle, SCH_TaskMain, SCH_APP, 120, 4096, 0x0, 1; "
"CFE_APP, /cf/apps/to.bundle, TO_task_main, TO_APP, 74, 4096, 0x0, 1; !",
sizeof(StartupScript) - 1);
StartupScript[sizeof(StartupScript) - 1] = '\0';
/* Perform ES main startup with a mutex creation failure */
ES_ResetUnitTest();
UT_SetDefaultReturnValue(UT_KEY(OS_MutSemCreate), OS_ERROR);
UT_SetReadBuffer(StartupScript, strlen(StartupScript));
UT_SetDataBuffer(UT_KEY(CFE_PSP_Panic), &PanicStatus, sizeof(PanicStatus), false);
CFE_ES_Main(CFE_PSP_RST_TYPE_POWERON, 1, 1, "ut_startup");
UtAssert_STUB_COUNT(CFE_PSP_Panic, 1);
UtAssert_UINT32_EQ(PanicStatus, CFE_PSP_PANIC_STARTUP_SEM);
/* Perform ES main startup with a file open failure */
ES_ResetUnitTest();
UT_SetDummyFuncRtn(OS_SUCCESS);
UT_SetDefaultReturnValue(UT_KEY(OS_OpenCreate), OS_ERROR);
UT_SetHookFunction(UT_KEY(OS_TaskCreate), ES_UT_SetAppStateHook, NULL);
CFE_ES_Main(CFE_PSP_RST_TYPE_POWERON, 1, 1, "ut_startup");
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_CANNOT_OPEN_ES_APP_STARTUP]);
/* Perform ES main startup with a startup sync failure */
ES_ResetUnitTest();
StateHook.AppState = CFE_ES_AppState_RUNNING;
StateHook.AppType =
CFE_ES_AppType_CORE; /* by only setting core apps, it will appear as if external apps did not start */
UT_SetHookFunction(UT_KEY(OS_TaskCreate), ES_UT_SetAppStateHook, &StateHook);
UT_SetReadBuffer(StartupScript, strlen(StartupScript));
CFE_ES_Main(CFE_PSP_RST_TYPE_POWERON, 1, 1, "ut_startup");
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_STARTUP_SYNC_FAIL_1]);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_STARTUP_SYNC_FAIL_2]);
/* Perform a power on reset with a hardware special sub-type */
ES_ResetUnitTest();
CFE_ES_SetupResetVariables(CFE_PSP_RST_TYPE_POWERON, CFE_PSP_RST_SUBTYPE_HW_SPECIAL_COMMAND, 1);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_POR_HW_SPECIAL]);
/* Perform a processor reset with a hardware special sub-type */
ES_ResetUnitTest();
CFE_ES_SetupResetVariables(CFE_PSP_RST_TYPE_PROCESSOR, CFE_PSP_RST_SUBTYPE_HW_SPECIAL_COMMAND, 1);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_PROC_RESET_MAX_HW_SPECIAL]);
/* Perform a power on reset with an "other cause" sub-type */
ES_ResetUnitTest();
CFE_ES_SetupResetVariables(CFE_PSP_RST_TYPE_POWERON, -1, 1);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_POR_OTHER]);
/* Perform the maximum number of processor resets */
ES_ResetUnitTest();
CFE_ES_Global.ResetDataPtr->ResetVars.ProcessorResetCount = 0;
CFE_ES_Global.ResetDataPtr->ResetVars.ES_CausedReset = false;
for (j = 0; j < CFE_PLATFORM_ES_MAX_PROCESSOR_RESETS; j++)
{
CFE_ES_SetupResetVariables(CFE_PSP_RST_TYPE_PROCESSOR, CFE_PSP_RST_SUBTYPE_POWER_CYCLE, 1);
}
UtAssert_UINT32_EQ(CFE_ES_Global.ResetDataPtr->ResetVars.ProcessorResetCount, CFE_PLATFORM_ES_MAX_PROCESSOR_RESETS);
/* Attempt another processor reset after the maximum have occurred */
ES_ResetUnitTest();
UT_SetDataBuffer(UT_KEY(CFE_PSP_Restart), &ResetType, sizeof(ResetType), false);
CFE_ES_SetupResetVariables(CFE_PSP_RST_TYPE_PROCESSOR, CFE_PSP_RST_SUBTYPE_POWER_CYCLE, 1);
UtAssert_UINT32_EQ(CFE_ES_Global.ResetDataPtr->ResetVars.ProcessorResetCount,
CFE_PLATFORM_ES_MAX_PROCESSOR_RESETS + 1);
UtAssert_UINT32_EQ(ResetType, CFE_PSP_RST_TYPE_POWERON);
UtAssert_STUB_COUNT(CFE_PSP_Restart, 1);
/* Perform a power on reset with a hardware special sub-type */
ES_ResetUnitTest();
CFE_ES_SetupResetVariables(CFE_PSP_RST_TYPE_PROCESSOR, CFE_PSP_RST_SUBTYPE_HW_SPECIAL_COMMAND, 1);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_POR_MAX_HW_SPECIAL]);
/* Perform a processor reset with an reset area failure */
ES_ResetUnitTest();
UT_SetStatusBSPResetArea(OS_ERROR, 0, CFE_TIME_ToneSignalSelect_PRIMARY);
UT_SetDataBuffer(UT_KEY(CFE_PSP_Panic), &PanicStatus, sizeof(PanicStatus), false);
CFE_ES_Global.ResetDataPtr->ResetVars.ES_CausedReset = true;
CFE_ES_SetupResetVariables(CFE_PSP_RST_TYPE_PROCESSOR, CFE_PSP_RST_SUBTYPE_POWER_CYCLE, 1);
UtAssert_UINT32_EQ(PanicStatus, CFE_PSP_PANIC_MEMORY_ALLOC);
UtAssert_STUB_COUNT(CFE_PSP_Panic, 1);
/* Perform a processor reset triggered by ES */
/* Added for coverage, as the "panic" case will should not cover this one */
ES_ResetUnitTest();
CFE_ES_Global.ResetDataPtr->ResetVars.ES_CausedReset = true;
CFE_ES_SetupResetVariables(CFE_PSP_RST_TYPE_PROCESSOR, CFE_PSP_RST_SUBTYPE_POWER_CYCLE, 1);
UtAssert_STUB_COUNT(CFE_PSP_Panic, 0);
/* Perform a processor reset with the size of the reset area too small */
ES_ResetUnitTest();
UT_SetSizeofESResetArea(0);
UT_SetDataBuffer(UT_KEY(CFE_PSP_Panic), &PanicStatus, sizeof(PanicStatus), false);
UT_SetStatusBSPResetArea(OS_SUCCESS, 0, CFE_TIME_ToneSignalSelect_PRIMARY);
CFE_ES_SetupResetVariables(CFE_PSP_RST_TYPE_PROCESSOR, CFE_PSP_RST_SUBTYPE_POWER_CYCLE, 1);
UtAssert_UINT32_EQ(PanicStatus, CFE_PSP_PANIC_MEMORY_ALLOC);
UtAssert_STUB_COUNT(CFE_PSP_Panic, 1);
/* Test initialization of the file systems specifying a power on reset
* following a failure to create the RAM volume
*/
ES_ResetUnitTest();
UT_SetDefaultReturnValue(UT_KEY(OS_initfs), OS_ERROR);
UT_SetDefaultReturnValue(UT_KEY(OS_mount), OS_ERROR);
UT_SetDefaultReturnValue(UT_KEY(OS_mkfs), OS_ERROR);
CFE_ES_InitializeFileSystems(CFE_PSP_RST_TYPE_POWERON);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_CREATE_VOLATILE]);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_MOUNT_VOLATILE]);
/* prepare the StatBuf to reflect a RAM disk that is 99% full */
StatBuf.block_size = 1024;
StatBuf.total_blocks = CFE_PLATFORM_ES_RAM_DISK_NUM_SECTORS;
StatBuf.blocks_free = CFE_PLATFORM_ES_RAM_DISK_NUM_SECTORS / 100;
/* Test initialization of the file systems specifying a processor reset
* following a failure to reformat the RAM volume
*/
ES_ResetUnitTest();
UT_SetDefaultReturnValue(UT_KEY(OS_initfs), OS_ERROR);
UT_SetDefaultReturnValue(UT_KEY(OS_mount), OS_ERROR);
UT_SetDefaultReturnValue(UT_KEY(OS_mkfs), OS_ERROR);
UT_SetDataBuffer(UT_KEY(OS_FileSysStatVolume), &StatBuf, sizeof(StatBuf), false);
CFE_ES_InitializeFileSystems(CFE_PSP_RST_TYPE_PROCESSOR);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_INSUFF_FREE_SPACE]);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_CREATE_VOLATILE]);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_INIT_VOLATILE]);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_MOUNT_VOLATILE]);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_REFORMAT_VOLATILE]);
/* Test initialization of the file systems specifying a processor reset
* following failure to get the volatile disk memory
*/
ES_ResetUnitTest();
UT_SetDefaultReturnValue(UT_KEY(CFE_PSP_GetVolatileDiskMem), CFE_PSP_ERROR);
UT_SetDataBuffer(UT_KEY(OS_FileSysStatVolume), &StatBuf, sizeof(StatBuf), false);
CFE_ES_InitializeFileSystems(CFE_PSP_RST_TYPE_PROCESSOR);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_INSUFF_FREE_SPACE]);
/* Test initialization of the file systems specifying a processor reset
* following a failure to remove the RAM volume
*/
ES_ResetUnitTest();
UT_SetDefaultReturnValue(UT_KEY(OS_rmfs), OS_ERROR);
UT_SetDataBuffer(UT_KEY(OS_FileSysStatVolume), &StatBuf, sizeof(StatBuf), false);
CFE_ES_InitializeFileSystems(CFE_PSP_RST_TYPE_PROCESSOR);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_INSUFF_FREE_SPACE]);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_REMOVE_VOLATILE]);
/* Test initialization of the file systems specifying a processor reset
* following a failure to unmount the RAM volume
*/
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(OS_unmount), 1, -1);
UT_SetDataBuffer(UT_KEY(OS_FileSysStatVolume), &StatBuf, sizeof(StatBuf), false);
CFE_ES_InitializeFileSystems(CFE_PSP_RST_TYPE_PROCESSOR);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_INSUFF_FREE_SPACE]);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_UNMOUNT_VOLATILE]);
/* Test successful initialization of the file systems */
ES_ResetUnitTest();
CFE_ES_InitializeFileSystems(4564564);
UtAssert_STUB_COUNT(CFE_PSP_Panic, 0);
/* Test initialization of the file systems specifying a processor reset
* following a failure to remount the RAM volume
*/
ES_ResetUnitTest();
UT_SetDefaultReturnValue(UT_KEY(OS_mount), OS_ERROR);
UT_SetDataBuffer(UT_KEY(OS_FileSysStatVolume), &StatBuf, sizeof(StatBuf), false);
CFE_ES_InitializeFileSystems(CFE_PSP_RST_TYPE_PROCESSOR);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_INSUFF_FREE_SPACE]);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_MOUNT_VOLATILE]);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_REMOUNT_VOLATILE]);
/* Test initialization of the file systems with an error determining the
* number of blocks that are free on the volume
*/
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(OS_FileSysStatVolume), 1, -1);
CFE_ES_InitializeFileSystems(CFE_PSP_RST_TYPE_PROCESSOR);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_DETERMINE_BLOCKS]);
/* Test reading the object table where a record used error occurs */
ES_ResetUnitTest();
TaskRecPtr = CFE_ES_Global.TaskTable;
for (j = 0; j < OS_MAX_TASKS; j++)
{
/* Mark all entries as "used" to ensure that the log message gets
* output
*/
CFE_ES_TaskRecordSetUsed(TaskRecPtr, ES_UT_MakeTaskIdForIndex(j));
++TaskRecPtr;
}
UT_SetHookFunction(UT_KEY(OS_TaskCreate), ES_UT_SetAppStateHook, NULL);
CFE_ES_CreateObjects();
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_RECORD_USED]);
/* Test reading the object table where an error occurs when
* calling a function
*/
ES_ResetUnitTest();
TaskRecPtr = CFE_ES_Global.TaskTable;
for (j = 0; j < OS_MAX_TASKS; j++)
{
/* Mark all entries as "used" to ensure that the log message gets
* output
*/
CFE_ES_TaskRecordSetUsed(TaskRecPtr, ES_UT_MakeAppIdForIndex(j));
++TaskRecPtr;
}
UT_SetDeferredRetcode(UT_KEY(CFE_TBL_EarlyInit), 1, -1);
UT_SetHookFunction(UT_KEY(OS_TaskCreate), ES_UT_SetAppStateHook, NULL);
CFE_ES_CreateObjects();
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_RECORD_USED]);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_EARLYINIT]);
/* Test reading the object table where an error occurs when
* creating a core app
*/
ES_ResetUnitTest();
UT_SetDefaultReturnValue(UT_KEY(OS_TaskCreate), OS_ERROR);
UT_SetDefaultReturnValue(UT_KEY(OS_BinSemCreate), OS_ERROR);
UT_SetHookFunction(UT_KEY(OS_TaskCreate), ES_UT_SetAppStateHook, NULL);
CFE_ES_CreateObjects();
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_CORE_APP_CREATE]);
/* Test reading the object table where all app slots are taken */
ES_ResetUnitTest();
UT_SetDefaultReturnValue(UT_KEY(CFE_ResourceId_FindNext), OS_ERROR);
CFE_ES_CreateObjects();
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_NO_FREE_CORE_APP_SLOTS]);
/* Test reading the object table with a NULL function pointer */
ES_ResetUnitTest();
UT_SetDefaultReturnValue(UT_KEY(CFE_ResourceId_FindNext), OS_ERROR);
CFE_ES_ObjectTable[1].ObjectType = CFE_ES_FUNCTION_CALL;
CFE_ES_CreateObjects();
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_NO_FREE_CORE_APP_SLOTS]);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_FUNCTION_POINTER]);
/* Test response to an invalid startup type */
ES_ResetUnitTest();
CFE_ES_Global.DebugVars.DebugFlag = 1;
CFE_ES_SetupResetVariables(-1, CFE_PSP_RST_SUBTYPE_HW_SPECIAL_COMMAND, 1);
UtAssert_UINT32_EQ(CFE_ES_Global.DebugVars.DebugFlag, 1);
CFE_ES_Global.DebugVars.DebugFlag = 0;
/* Test initialization of the file systems specifying a processor reset
* following a failure to initialize and mount the RAM volume
*/
ES_ResetUnitTest();
UT_SetDefaultReturnValue(UT_KEY(OS_initfs), OS_ERROR);
UT_SetDefaultReturnValue(UT_KEY(OS_mount), OS_ERROR);
UT_SetDataBuffer(UT_KEY(OS_FileSysStatVolume), &StatBuf, sizeof(StatBuf), false);
CFE_ES_InitializeFileSystems(CFE_PSP_RST_TYPE_PROCESSOR);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_INSUFF_FREE_SPACE]);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_INIT_VOLATILE]);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_MOUNT_VOLATILE]);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_REMOUNT_VOLATILE]);
/* Test application sync delay where the operation times out */
ES_ResetUnitTest();
/* This prep is necessary so GetAppId works */
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppType_CORE, NULL, &AppRecPtr, NULL);
CFE_ES_Global.SystemState = CFE_ES_SystemState_CORE_READY;
UtAssert_INT32_EQ(
CFE_ES_WaitForSystemState(CFE_ES_SystemState_OPERATIONAL, CFE_PLATFORM_ES_STARTUP_SCRIPT_TIMEOUT_MSEC),
CFE_ES_OPERATION_TIMED_OUT);
/* Test startup sync with alternate minimum system state
* of CFE_ES_SystemState_SHUTDOWN
*/
ES_ResetUnitTest();
/* This prep is necessary so GetAppId works */
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppType_CORE, NULL, &AppRecPtr, NULL);
CFE_ES_Global.SystemState = CFE_ES_SystemState_CORE_READY;
UtAssert_INT32_EQ(
CFE_ES_WaitForSystemState(CFE_ES_SystemState_SHUTDOWN, CFE_PLATFORM_ES_STARTUP_SCRIPT_TIMEOUT_MSEC),
CFE_ES_OPERATION_TIMED_OUT);
UtAssert_UINT32_EQ(AppRecPtr->AppState, CFE_ES_AppState_STOPPED);
/* Test startup sync with alternate minimum system state
* of CFE_ES_SystemState_APPS_INIT
*/
ES_ResetUnitTest();
/* This prep is necessary so GetAppId works */
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppType_CORE, NULL, &AppRecPtr, NULL);
CFE_ES_Global.SystemState = CFE_ES_SystemState_CORE_READY;
UtAssert_INT32_EQ(
CFE_ES_WaitForSystemState(CFE_ES_SystemState_APPS_INIT, CFE_PLATFORM_ES_STARTUP_SCRIPT_TIMEOUT_MSEC),
CFE_ES_OPERATION_TIMED_OUT);
UtAssert_UINT32_EQ(AppRecPtr->AppState, CFE_ES_AppState_LATE_INIT);
/* Test success */
ES_ResetUnitTest();
/* This prep is necessary so GetAppId works */
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppType_CORE, NULL, &AppRecPtr, NULL);
CFE_ES_Global.SystemState = CFE_ES_SystemState_CORE_READY;
CFE_UtAssert_SUCCESS(CFE_ES_WaitForSystemState(CFE_ES_SystemState_CORE_READY, 0));
}
void TestApps(void)
{
int NumBytes;
CFE_ES_AppInfo_t AppInfo;
CFE_ES_AppId_t AppId;
CFE_ES_TaskId_t TaskId;
CFE_ES_TaskRecord_t * UtTaskRecPtr;
CFE_ES_AppRecord_t * UtAppRecPtr;
CFE_ES_MemPoolRecord_t *UtPoolRecPtr;
char NameBuffer[OS_MAX_API_NAME + 5];
CFE_ES_AppStartParams_t StartParams;
UtPrintf("Begin Test Apps");
/* Test starting an application where the startup script is too long */
ES_ResetUnitTest();
strncpy(StartupScript,
"CFE_LIB, /cf/apps/tst_lib.bundle, TST_LIB_Init, TST_fghfghfghfghfg"
"hfghfghfghfghfghfghfghfghfghfghfghfghfghfghfghfghfghfghfghfghLIB, "
"0, 0, 0x0, 1; CFE_APP, /cf/apps/ci.bundle, CI_task_main, CI_APP, "
"70, 4096, 0x0, 1; CFE_APP, /cf/apps/sch.bundle, SCH_TaskMain, "
"SCH_APP, 120, 4096, 0x0, 1; CFE_APP, /cf/apps/to.bundle, "
"TO_task_main, TO_APP, 74, 4096, 0x0, 1; !",
sizeof(StartupScript) - 1);
StartupScript[sizeof(StartupScript) - 1] = '\0';
NumBytes = strlen(StartupScript);
UT_SetReadBuffer(StartupScript, NumBytes);
CFE_ES_StartApplications(CFE_PSP_RST_TYPE_PROCESSOR, "ut_startup");
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_FILE_LINE_TOO_LONG]);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_ES_APP_STARTUP_OPEN]);
/* Test starting an application where the startup script has extra tokens */
ES_ResetUnitTest();
strncpy(StartupScript, "A,B,C,D,E,F,G,H,I,J,K; !", sizeof(StartupScript) - 1);
StartupScript[sizeof(StartupScript) - 1] = '\0';
NumBytes = strlen(StartupScript);
UT_SetReadBuffer(StartupScript, NumBytes);
CFE_ES_StartApplications(CFE_PSP_RST_TYPE_PROCESSOR, "ut_startup");
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_FILE_LINE_TOO_LONG]);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_ES_APP_STARTUP_OPEN]);
/* Create a valid startup script for subsequent tests */
strncpy(StartupScript,
"CFE_LIB, /cf/apps/tst_lib.bundle, TST_LIB_Init, TST_LIB, 0, 0, 0x0, 1; "
"CFE_APP, /cf/apps/ci.bundle, CI_task_main, CI_APP, 70, 4096, 0x0, 1; "
"CFE_APP, /cf/apps/sch.bundle, SCH_TaskMain, SCH_APP, 120, 4096, 0x0, 1; "
"CFE_APP, /cf/apps/to.bundle, TO_task_main, TO_APP, 74, 4096, 0x0, 1; !",
sizeof(StartupScript) - 1);
StartupScript[sizeof(StartupScript) - 1] = '\0';
NumBytes = strlen(StartupScript);
UT_SetReadBuffer(StartupScript, NumBytes);
/* Test starting an application with an error reading the startup file */
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(OS_read), 1, -1);
CFE_ES_StartApplications(CFE_PSP_RST_TYPE_PROCESSOR, "ut_startup");
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_STARTUP_READ]);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_ES_APP_STARTUP_OPEN]);
/* Test starting an application with an end-of-file returned by the
* OS read
*/
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(OS_read), 1, 0);
CFE_ES_StartApplications(CFE_PSP_RST_TYPE_PROCESSOR, "ut_startup");
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_ES_APP_STARTUP_OPEN]);
/* Test starting an application with an open failure */
ES_ResetUnitTest();
UT_SetDefaultReturnValue(UT_KEY(OS_OpenCreate), OS_ERROR);
CFE_ES_StartApplications(CFE_PSP_RST_TYPE_PROCESSOR, "ut_startup");
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_CANNOT_OPEN_ES_APP_STARTUP]);
/* Test successfully starting an application */
ES_ResetUnitTest();
UT_SetReadBuffer(StartupScript, NumBytes);
UT_SetHookFunction(UT_KEY(OS_TaskCreate), ES_UT_SetAppStateHook, NULL);
CFE_ES_StartApplications(CFE_PSP_RST_TYPE_PROCESSOR, "ut_startup");
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_ES_APP_STARTUP_OPEN]);
/* Test parsing the startup script with an unknown entry type */
ES_ResetUnitTest();
{
const char *TokenList[] = {"UNKNOWN", "/cf/apps/tst_lib.bundle", "TST_LIB_Init", "TST_LIB", "0", "0", "0x0",
"1"};
UtAssert_INT32_EQ(CFE_ES_ParseFileEntry(TokenList, 8), CFE_ES_ERR_APP_CREATE);
/* Test parsing the startup script with an invalid file name */
UT_SetDefaultReturnValue(UT_KEY(CFE_FS_ParseInputFileName), CFE_FS_INVALID_PATH);
UtAssert_INT32_EQ(CFE_ES_ParseFileEntry(TokenList, 8), CFE_FS_INVALID_PATH);
}
/* Test parsing the startup script with an invalid argument passed in */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_ParseFileEntry(NULL, 0), CFE_ES_BAD_ARGUMENT);
/* Test application loading and creation with a task creation failure */
ES_ResetUnitTest();
UT_SetDefaultReturnValue(UT_KEY(OS_TaskCreate), OS_ERROR);
ES_UT_SetupAppStartParams(&StartParams, "ut/filename", "EntryPoint", 170, 4096, 1);
UtAssert_INT32_EQ(CFE_ES_AppCreate(&AppId, "AppName", &StartParams), CFE_STATUS_EXTERNAL_RESOURCE_FAIL);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_APP_CREATE]);
/* Test application creation with NULL parameters */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_AppCreate(&AppId, "AppName", NULL), CFE_ES_BAD_ARGUMENT);
/* Test application creation with name too long */
memset(NameBuffer, 'x', sizeof(NameBuffer) - 1);
NameBuffer[sizeof(NameBuffer) - 1] = 0;
ES_UT_SetupAppStartParams(&StartParams, "ut/filename.x", "EntryPoint", 170, 4096, 1);
UtAssert_INT32_EQ(CFE_ES_AppCreate(&AppId, NameBuffer, &StartParams), CFE_ES_BAD_ARGUMENT);
/* Test successful application loading and creation */
ES_ResetUnitTest();
ES_UT_SetupAppStartParams(&StartParams, "ut/filename.x", "EntryPoint", 170, 8192, 1);
CFE_UtAssert_SUCCESS(CFE_ES_AppCreate(&AppId, "AppName", &StartParams));
/* Test application loading of the same name again */
ES_UT_SetupAppStartParams(&StartParams, "ut/filename.x", "EntryPoint", 170, 8192, 1);
UtAssert_INT32_EQ(CFE_ES_AppCreate(&AppId, "AppName", &StartParams), CFE_ES_ERR_DUPLICATE_NAME);
/* Test application loading and creation where the file cannot be loaded */
UT_InitData();
UT_SetDeferredRetcode(UT_KEY(OS_ModuleLoad), 1, -1);
ES_UT_SetupAppStartParams(&StartParams, "ut/filename.x", "EntryPoint", 170, 8192, 1);
UtAssert_INT32_EQ(CFE_ES_AppCreate(&AppId, "AppName2", &StartParams), CFE_STATUS_EXTERNAL_RESOURCE_FAIL);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_EXTRACT_FILENAME_UT55]);
/* Test application loading and creation where all app slots are taken */
ES_ResetUnitTest();
UT_SetDefaultReturnValue(UT_KEY(CFE_ResourceId_FindNext), OS_ERROR);
ES_UT_SetupAppStartParams(&StartParams, "ut/filename.x", "EntryPoint", 170, 8192, 1);
UtAssert_INT32_EQ(CFE_ES_AppCreate(&AppId, "AppName", &StartParams), CFE_ES_NO_RESOURCE_IDS_AVAILABLE);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_NO_FREE_APP_SLOTS]);
/* Check operation of the CFE_ES_CheckAppIdSlotUsed() helper function */
CFE_ES_Global.AppTable[1].AppId = CFE_ES_APPID_C(ES_UT_MakeAppIdForIndex(1));
CFE_ES_Global.AppTable[2].AppId = CFE_ES_APPID_UNDEFINED;
CFE_UtAssert_TRUE(CFE_ES_CheckAppIdSlotUsed(ES_UT_MakeAppIdForIndex(1)));
CFE_UtAssert_FALSE(CFE_ES_CheckAppIdSlotUsed(ES_UT_MakeAppIdForIndex(2)));
/* Test application loading and creation where the entry point symbol
* cannot be found
*/
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(OS_ModuleSymbolLookup), 1, -1);
ES_UT_SetupAppStartParams(&StartParams, "ut/filename.x", "EntryPoint", 170, 8192, 1);
UtAssert_INT32_EQ(CFE_ES_AppCreate(&AppId, "AppName", &StartParams), CFE_STATUS_EXTERNAL_RESOURCE_FAIL);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_CANNOT_FIND_SYMBOL]);
/* Test application loading and creation where the entry point symbol
* cannot be found and module unload fails
*/
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(OS_ModuleSymbolLookup), 1, -1);
UT_SetDeferredRetcode(UT_KEY(OS_ModuleUnload), 1, -1);
ES_UT_SetupAppStartParams(&StartParams, "ut/filename.x", "EntryPoint", 170, 8192, 1);
UtAssert_INT32_EQ(CFE_ES_AppCreate(&AppId, "AppName", &StartParams), CFE_STATUS_EXTERNAL_RESOURCE_FAIL);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_CANNOT_FIND_SYMBOL]);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_MODULE_UNLOAD_FAILED]);
/*
* Set up a situation where attempting to get appID by context,
* but the task record does not match the app record.
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, &UtTaskRecPtr);
UtTaskRecPtr->AppId = CFE_ES_APPID_UNDEFINED;
UtAssert_NULL(CFE_ES_GetAppRecordByContext());
/* Test scanning and acting on the application table where the timer
* expires for a waiting application
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_WAITING, NULL, &UtAppRecPtr, NULL);
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_APP_RUN;
UtAppRecPtr->ControlReq.AppTimerMsec = 0;
memset(&CFE_ES_Global.BackgroundAppScanState, 0, sizeof(CFE_ES_Global.BackgroundAppScanState));
CFE_ES_RunAppTableScan(0, &CFE_ES_Global.BackgroundAppScanState);
UtAssert_INT32_EQ(UtAppRecPtr->ControlReq.AppTimerMsec, 0);
CFE_UtAssert_EVENTSENT(CFE_ES_PCR_ERR2_EID);
/* Test scanning and acting on the application table where the timer
* has not expired for a waiting application
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_WAITING, NULL, &UtAppRecPtr, NULL);
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_APP_EXIT;
UtAppRecPtr->ControlReq.AppTimerMsec = 5000;
CFE_ES_RunAppTableScan(1000, &CFE_ES_Global.BackgroundAppScanState);
UtAssert_INT32_EQ(UtAppRecPtr->ControlReq.AppTimerMsec, 4000);
UtAssert_UINT32_EQ(UtAppRecPtr->ControlReq.AppControlRequest, CFE_ES_RunStatus_APP_EXIT);
/* Test scanning and acting on the application table where the application
* has stopped and is ready to be acted on
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_STOPPED, NULL, &UtAppRecPtr, NULL);
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_APP_RUN;
UtAppRecPtr->ControlReq.AppTimerMsec = 0;
CFE_ES_RunAppTableScan(0, &CFE_ES_Global.BackgroundAppScanState);
UtAssert_INT32_EQ(UtAppRecPtr->ControlReq.AppTimerMsec, 0);
CFE_UtAssert_EVENTSENT(CFE_ES_PCR_ERR2_EID);
/* Test scanning and acting on the application table where the application
* has stopped and is ready to be acted on
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_EARLY_INIT, NULL, &UtAppRecPtr, NULL);
UtAppRecPtr->ControlReq.AppTimerMsec = 5000;
CFE_ES_RunAppTableScan(0, &CFE_ES_Global.BackgroundAppScanState);
UtAssert_INT32_EQ(UtAppRecPtr->ControlReq.AppTimerMsec, 5000);
CFE_UtAssert_EVENTCOUNT(0);
/* Test a control action request on an application with an
* undefined control request state
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
UtAppRecPtr->ControlReq.AppControlRequest = 0x12345;
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
CFE_UtAssert_VOIDCALL(CFE_ES_ProcessControlRequest(AppId));
CFE_UtAssert_EVENTSENT(CFE_ES_PCR_ERR2_EID);
/* Test a successful control action request to exit an application */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
ES_UT_SetupAppStartParams(&UtAppRecPtr->StartParams, "/ram/Filename", "NotNULL", 8192, 255, 0);
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_APP_EXIT;
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
CFE_UtAssert_VOIDCALL(CFE_ES_ProcessControlRequest(AppId));
CFE_UtAssert_EVENTSENT(CFE_ES_EXIT_APP_INF_EID);
/* Test a control action request to exit an application where the
* request fails
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_APP_EXIT;
UT_SetDeferredRetcode(UT_KEY(CFE_EVS_CleanUpApp), 1, -1);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
CFE_UtAssert_VOIDCALL(CFE_ES_ProcessControlRequest(AppId));
CFE_UtAssert_EVENTSENT(CFE_ES_EXIT_APP_ERR_EID);
/* Test a control action request to stop an application where the
* request fails
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_SYS_DELETE;
UT_SetDeferredRetcode(UT_KEY(CFE_EVS_CleanUpApp), 1, -1);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
CFE_UtAssert_VOIDCALL(CFE_ES_ProcessControlRequest(AppId));
CFE_UtAssert_EVENTSENT(CFE_ES_STOP_ERR3_EID);
/* Test a control action request to restart an application where the
* request fails due to a CleanUpApp error
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_SYS_RESTART;
UT_SetDeferredRetcode(UT_KEY(CFE_EVS_CleanUpApp), 1, -1);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
CFE_UtAssert_VOIDCALL(CFE_ES_ProcessControlRequest(AppId));
CFE_UtAssert_EVENTSENT(CFE_ES_RESTART_APP_ERR4_EID);
/* Test a control action request to restart an application where the
* request fails due to an AppCreate error
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_SYS_RESTART;
OS_ModuleLoad(&UtAppRecPtr->LoadStatus.ModuleId, NULL, NULL, 0);
UT_SetDefaultReturnValue(UT_KEY(OS_TaskCreate), OS_ERROR);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
CFE_UtAssert_VOIDCALL(CFE_ES_ProcessControlRequest(AppId));
CFE_UtAssert_EVENTSENT(CFE_ES_RESTART_APP_ERR3_EID);
/* Test a control action request to reload an application where the
* request fails due to a CleanUpApp error
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_SYS_RELOAD;
UT_SetDeferredRetcode(UT_KEY(CFE_EVS_CleanUpApp), 1, -1);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
CFE_UtAssert_VOIDCALL(CFE_ES_ProcessControlRequest(AppId));
CFE_UtAssert_EVENTSENT(CFE_ES_RELOAD_APP_ERR4_EID);
/* Test a control action request to reload an application where the
* request fails due to an AppCreate error
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_SYS_RELOAD;
OS_ModuleLoad(&UtAppRecPtr->LoadStatus.ModuleId, NULL, NULL, 0);
UT_SetDefaultReturnValue(UT_KEY(OS_TaskCreate), OS_ERROR);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
CFE_UtAssert_VOIDCALL(CFE_ES_ProcessControlRequest(AppId));
CFE_UtAssert_EVENTSENT(CFE_ES_RELOAD_APP_ERR3_EID);
/* Test a successful control action request to exit an application that
* has an error
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
ES_UT_SetupAppStartParams(&UtAppRecPtr->StartParams, "/ram/FileName", "NULL", 8192, 255, 0);
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_APP_ERROR;
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
CFE_UtAssert_VOIDCALL(CFE_ES_ProcessControlRequest(AppId));
CFE_UtAssert_EVENTSENT(CFE_ES_ERREXIT_APP_INF_EID);
/* Test a control action request to exit an application that
* has an error where the request fails
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
UT_SetDeferredRetcode(UT_KEY(CFE_EVS_CleanUpApp), 1, -1);
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_APP_ERROR;
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
CFE_UtAssert_VOIDCALL(CFE_ES_ProcessControlRequest(AppId));
CFE_UtAssert_EVENTSENT(CFE_ES_ERREXIT_APP_ERR_EID);
/* Test a successful control action request to stop an application */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
ES_UT_SetupAppStartParams(&UtAppRecPtr->StartParams, "/ram/FileName", "NULL", 8192, 255, 0);
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_SYS_DELETE;
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
CFE_UtAssert_VOIDCALL(CFE_ES_ProcessControlRequest(AppId));
CFE_UtAssert_EVENTSENT(CFE_ES_STOP_INF_EID);
/* Test a successful control action request to restart an application */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
ES_UT_SetupAppStartParams(&UtAppRecPtr->StartParams, "/ram/FileName", "NULL", 8192, 255, 0);
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_SYS_RESTART;
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
CFE_UtAssert_VOIDCALL(CFE_ES_ProcessControlRequest(AppId));
CFE_UtAssert_EVENTSENT(CFE_ES_RESTART_APP_INF_EID);
/* Test a successful control action request to reload an application */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
ES_UT_SetupAppStartParams(&UtAppRecPtr->StartParams, "/ram/FileName", "NULL", 8192, 255, 0);
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_SYS_RELOAD;
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
CFE_UtAssert_VOIDCALL(CFE_ES_ProcessControlRequest(AppId));
CFE_UtAssert_EVENTSENT(CFE_ES_RELOAD_APP_INF_EID);
/* Test a control action request for an application that has an invalid
* state (exception)
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
ES_UT_SetupAppStartParams(&UtAppRecPtr->StartParams, "/ram/FileName", "NULL", 8192, 255, 0);
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_SYS_EXCEPTION;
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
CFE_UtAssert_VOIDCALL(CFE_ES_ProcessControlRequest(AppId));
CFE_UtAssert_EVENTSENT(CFE_ES_PCR_ERR1_EID);
/* Test populating the application information structure with data */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
CFE_UtAssert_SUCCESS(CFE_ES_GetAppInfo(&AppInfo, AppId));
/* Test populating the application information structure with data using
* a null application information pointer
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
UtAssert_INT32_EQ(CFE_ES_GetAppInfo(NULL, AppId), CFE_ES_BAD_ARGUMENT);
/* Test populating the application information structure using an
* inactive application ID
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
CFE_ES_AppRecordSetFree(UtAppRecPtr);
UtAssert_INT32_EQ(CFE_ES_GetAppInfo(&AppInfo, AppId), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test populating the application information structure using an
* application ID value greater than the maximum allowed
*/
ES_ResetUnitTest();
AppId = CFE_ES_APPID_C(ES_UT_MakeAppIdForIndex(99999));
UtAssert_INT32_EQ(CFE_ES_GetAppInfo(&AppInfo, AppId), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test populating the application information structure using a valid
* application ID, but with a failure to retrieve the module information
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
UT_SetDeferredRetcode(UT_KEY(OS_ModuleInfo), 1, OS_ERROR);
CFE_UtAssert_SUCCESS(CFE_ES_GetAppInfo(&AppInfo, AppId));
/* Test deleting an application and cleaning up its resources with OS
* delete and close failures
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
ES_UT_SetupForOSCleanup();
OS_ModuleLoad(&UtAppRecPtr->LoadStatus.ModuleId, NULL, NULL, 0);
UT_SetDefaultReturnValue(UT_KEY(OS_TaskDelete), OS_ERROR);
UT_SetDefaultReturnValue(UT_KEY(OS_close), OS_ERROR);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
UtAssert_INT32_EQ(CFE_ES_CleanUpApp(AppId), CFE_ES_APP_CLEANUP_ERR);
/* Test deleting an application and cleaning up its resources with a
* mutex delete failure
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, NULL, NULL);
ES_UT_SetupForOSCleanup();
UT_SetDeferredRetcode(UT_KEY(OS_MutSemDelete), 1, OS_ERROR);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
UtAssert_INT32_EQ(CFE_ES_CleanUpApp(AppId), CFE_ES_APP_CLEANUP_ERR);
/* Test deleting an application and cleaning up its resources with a
* failure to unload the module
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
UT_SetDeferredRetcode(UT_KEY(OS_ModuleUnload), 1, OS_ERROR);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
UtAssert_INT32_EQ(CFE_ES_CleanUpApp(AppId), CFE_ES_APP_CLEANUP_ERR);
/* Test deleting an application and cleaning up its resources where the
* EVS application cleanup fails
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
UT_SetDeferredRetcode(UT_KEY(CFE_EVS_CleanUpApp), 1, -1);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
UtAssert_INT32_EQ(CFE_ES_CleanUpApp(AppId), CFE_ES_APP_CLEANUP_ERR);
/* Test cleaning up the OS resources for a task with a failure
* deleting mutexes
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, NULL, &UtTaskRecPtr);
ES_UT_SetupForOSCleanup();
TaskId = CFE_ES_TaskRecordGetID(UtTaskRecPtr);
UT_SetDeferredRetcode(UT_KEY(OS_MutSemDelete), 1, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_CleanupTaskResources(TaskId), CFE_ES_MUT_SEM_DELETE_ERR);
/* Test cleaning up the OS resources for a task with a failure deleting
* binary semaphores
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, NULL, &UtTaskRecPtr);
ES_UT_SetupForOSCleanup();
TaskId = CFE_ES_TaskRecordGetID(UtTaskRecPtr);
UT_SetDeferredRetcode(UT_KEY(OS_BinSemDelete), 1, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_CleanupTaskResources(TaskId), CFE_ES_BIN_SEM_DELETE_ERR);
/* Test cleaning up the OS resources for a task with a failure deleting
* counting semaphores
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, NULL, &UtTaskRecPtr);
ES_UT_SetupForOSCleanup();
UT_SetDeferredRetcode(UT_KEY(OS_CountSemDelete), 1, OS_ERROR);
TaskId = CFE_ES_TaskRecordGetID(UtTaskRecPtr);
UtAssert_INT32_EQ(CFE_ES_CleanupTaskResources(TaskId), CFE_ES_COUNT_SEM_DELETE_ERR);
/* Test cleaning up the OS resources for a task with a failure
* deleting queues
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, NULL, &UtTaskRecPtr);
ES_UT_SetupForOSCleanup();
UT_SetDeferredRetcode(UT_KEY(OS_QueueDelete), 1, OS_ERROR);
TaskId = CFE_ES_TaskRecordGetID(UtTaskRecPtr);
UtAssert_INT32_EQ(CFE_ES_CleanupTaskResources(TaskId), CFE_ES_QUEUE_DELETE_ERR);
/* Test cleaning up the OS resources for a task with a failure
* deleting timers
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, NULL, &UtTaskRecPtr);
TaskId = CFE_ES_TaskRecordGetID(UtTaskRecPtr);
ES_UT_SetupForOSCleanup();
/* Just set OS_TimerDelete to fail. There is no requirement
* that the code call OS_TimerGetInfo first.
*/
UT_SetDeferredRetcode(UT_KEY(OS_TimerDelete), 1, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_CleanupTaskResources(TaskId), CFE_ES_TIMER_DELETE_ERR);
/* Test cleaning up the OS resources for a task with a failure
* closing files
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, NULL, &UtTaskRecPtr);
TaskId = CFE_ES_TaskRecordGetID(UtTaskRecPtr);
ES_UT_SetupForOSCleanup();
UT_SetDeferredRetcode(UT_KEY(OS_TimerGetInfo), 1, OS_ERROR);
UT_SetDefaultReturnValue(UT_KEY(OS_close), OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_CleanupTaskResources(TaskId), CFE_ES_APP_CLEANUP_ERR);
/* Test cleaning up the OS resources for a task with a failure
* to delete the task
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, NULL, &UtTaskRecPtr);
TaskId = CFE_ES_TaskRecordGetID(UtTaskRecPtr);
UT_SetDeferredRetcode(UT_KEY(OS_TimerGetInfo), 1, OS_ERROR);
UT_SetDefaultReturnValue(UT_KEY(OS_TaskDelete), OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_CleanupTaskResources(TaskId), CFE_ES_TASK_DELETE_ERR);
/* Test successfully cleaning up the OS resources for a task */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, NULL, &UtTaskRecPtr);
TaskId = CFE_ES_TaskRecordGetID(UtTaskRecPtr);
UT_SetDeferredRetcode(UT_KEY(OS_TimerGetInfo), 1, OS_ERROR);
CFE_UtAssert_SUCCESS(CFE_ES_CleanupTaskResources(TaskId));
/* Test parsing the startup script for a cFE application and a restart
* application exception action
*/
ES_ResetUnitTest();
{
const char *TokenList[] = {"CFE_APP", "/cf/apps/tst_lib.bundle", "TST_LIB_Init", "TST_LIB", "0", "0", "0x0",
"0"};
CFE_UtAssert_SUCCESS(CFE_ES_ParseFileEntry(TokenList, 8));
}
/* Test scanning and acting on the application table where the timer
* expires for a waiting application
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_WAITING, NULL, &UtAppRecPtr, NULL);
UtAppRecPtr->ControlReq.AppTimerMsec = 0;
CFE_ES_RunAppTableScan(0, &CFE_ES_Global.BackgroundAppScanState);
UtAssert_INT32_EQ(UtAppRecPtr->ControlReq.AppTimerMsec, 0);
CFE_UtAssert_EVENTCOUNT(0);
/* Test scanning and acting on the application table where the application
* is already running
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
UtAppRecPtr->ControlReq.AppTimerMsec = 0;
CFE_ES_RunAppTableScan(0, &CFE_ES_Global.BackgroundAppScanState);
UtAssert_INT32_EQ(UtAppRecPtr->ControlReq.AppTimerMsec, 0);
CFE_UtAssert_EVENTCOUNT(0);
/* Test deleting an application and cleaning up its resources where the
* application ID matches the main task ID
*/
ES_ResetUnitTest();
/* Setup an entry which will be deleted */
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
/* Setup a second entry which will NOT be deleted */
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, NULL, &UtTaskRecPtr);
ES_UT_SetupMemPoolId(&UtPoolRecPtr);
UtPoolRecPtr->OwnerAppID = CFE_ES_AppRecordGetID(UtAppRecPtr);
/* Associate a child task with the app to be deleted */
ES_UT_SetupChildTaskId(UtAppRecPtr, NULL, NULL);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
CFE_UtAssert_SUCCESS(CFE_ES_CleanUpApp(AppId));
CFE_UtAssert_TRUE(CFE_ES_TaskRecordIsUsed(UtTaskRecPtr));
CFE_UtAssert_FALSE(CFE_ES_MemPoolRecordIsUsed(UtPoolRecPtr));
/* Test deleting an application and cleaning up its resources where the
* memory pool deletion fails
*/
ES_ResetUnitTest();
/* Setup an entry which will be deleted */
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
ES_UT_SetupMemPoolId(&UtPoolRecPtr);
UtPoolRecPtr->OwnerAppID = CFE_ES_AppRecordGetID(UtAppRecPtr);
UtPoolRecPtr->PoolID = CFE_ES_MEMHANDLE_C(CFE_ResourceId_FromInteger(99999)); /* Mismatch */
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
UtAssert_INT32_EQ(CFE_ES_CleanUpApp(AppId), CFE_ES_APP_CLEANUP_ERR);
CFE_UtAssert_TRUE(CFE_ES_MemPoolRecordIsUsed(UtPoolRecPtr));
/* Test deleting an application and cleaning up its resources where the
* application ID doesn't match the main task ID
*/
ES_ResetUnitTest();
/* Setup an entry which will be deleted */
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
/* Setup a second entry which will NOT be deleted */
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, NULL, &UtTaskRecPtr);
/* Associate a child task with the app to be deleted */
ES_UT_SetupChildTaskId(UtAppRecPtr, NULL, NULL);
/* switch the main task association (makes it wrong) */
UtAppRecPtr->MainTaskId = CFE_ES_TaskRecordGetID(UtTaskRecPtr);
UT_SetDefaultReturnValue(UT_KEY(OS_TaskDelete), OS_ERROR);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
UtAssert_INT32_EQ(CFE_ES_CleanUpApp(AppId), CFE_ES_APP_CLEANUP_ERR);
CFE_UtAssert_TRUE(CFE_ES_TaskRecordIsUsed(UtTaskRecPtr));
/* Test deleting an application and cleaning up its resources where the
* application ID doesn't match and the application is a core application
*/
ES_ResetUnitTest();
/* Setup an entry which will be deleted */
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
/* Setup a second entry which will NOT be deleted */
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, NULL, &UtTaskRecPtr);
/* Associate a child task with the app to be deleted */
ES_UT_SetupChildTaskId(UtAppRecPtr, NULL, NULL);
/* switch the main task association (makes it wrong) */
UtAppRecPtr->MainTaskId = CFE_ES_TaskRecordGetID(UtTaskRecPtr);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
CFE_UtAssert_SUCCESS(CFE_ES_CleanUpApp(AppId));
CFE_UtAssert_TRUE(CFE_ES_TaskRecordIsUsed(UtTaskRecPtr));
UtAssert_UINT32_EQ(CFE_ES_Global.RegisteredExternalApps, 1);
/* Test successfully deleting an application and cleaning up its resources
* and the application is an external application
*/
ES_ResetUnitTest();
/* Setup an entry which will be deleted */
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, &UtTaskRecPtr);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
CFE_UtAssert_SUCCESS(CFE_ES_CleanUpApp(AppId));
CFE_UtAssert_FALSE(CFE_ES_TaskRecordIsUsed(UtTaskRecPtr));
UtAssert_UINT32_EQ(CFE_ES_Global.RegisteredExternalApps, 0);
/* Test cleaning up the OS resources for a task with failure to
* obtain information on mutex, binary, and counter semaphores, and
* queues, timers, and file descriptors
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, &UtTaskRecPtr);
TaskId = CFE_ES_TaskRecordGetID(UtTaskRecPtr);
UT_SetDeferredRetcode(UT_KEY(OS_MutSemGetInfo), 1, OS_ERROR);
UT_SetDeferredRetcode(UT_KEY(OS_BinSemGetInfo), 1, OS_ERROR);
UT_SetDeferredRetcode(UT_KEY(OS_CountSemGetInfo), 1, OS_ERROR);
UT_SetDeferredRetcode(UT_KEY(OS_QueueGetInfo), 1, OS_ERROR);
UT_SetDeferredRetcode(UT_KEY(OS_TimerGetInfo), 1, OS_ERROR);
UT_SetDeferredRetcode(UT_KEY(OS_FDGetInfo), 1, OS_ERROR);
CFE_UtAssert_SUCCESS(CFE_ES_CleanupTaskResources(TaskId));
}
void TestResourceID(void)
{
/*
* Test cases for generic resource ID functions which are
* not sufficiently covered by other app/lib tests.
*
* Most of the Resource ID functions have been moved to a separate module and that module
* has its own unit test which tests these APIs.
*
* This is mainly to exercise the conversion of CFE ES task IDs to OSAL task IDs and vice versa.
* The conversion is only implemented for tasks, because this is the only resource type where
* there is overlap between OSAL and CFE (they both have task records).
*/
CFE_ES_TaskId_t cfe_id1, cfe_id2;
osal_id_t osal_id;
/*
* In this function the actual values may or may not change,
* depending on whether strict/simple mode is in use. However
* converting to and from should result in the original value
* either way.
*/
UT_SetDefaultReturnValue(UT_KEY(OS_IdentifyObject), OS_OBJECT_TYPE_OS_TASK);
cfe_id1 = CFE_ES_TASKID_C(ES_UT_MakeTaskIdForIndex(0));
osal_id = CFE_ES_TaskId_ToOSAL(cfe_id1);
cfe_id2 = CFE_ES_TaskId_FromOSAL(osal_id);
CFE_UtAssert_RESOURCEID_EQ(cfe_id1, cfe_id2);
}
void TestLibs(void)
{
CFE_ES_LibRecord_t * UtLibRecPtr;
char LongLibraryName[sizeof(UtLibRecPtr->LibName) + 1];
CFE_ES_LibId_t Id;
CFE_ES_ModuleLoadParams_t LoadParams;
/* Test shared library loading and initialization where the initialization
* routine returns an error
*/
ES_ResetUnitTest();
UT_SetDummyFuncRtn(-444);
ES_UT_SetupModuleLoadParams(&LoadParams, "filename", "entrypt");
UtAssert_INT32_EQ(CFE_ES_LoadLibrary(&Id, "LibName", &LoadParams), -444);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_SHARED_LIBRARY_INIT]);
/* Test Load library returning an error on a null pointer argument */
UtAssert_INT32_EQ(CFE_ES_LoadLibrary(&Id, "LibName", NULL), CFE_ES_BAD_ARGUMENT);
UtAssert_INT32_EQ(CFE_ES_LoadLibrary(&Id, NULL, &LoadParams), CFE_ES_BAD_ARGUMENT);
/* Test Load library returning an error on a too long library name */
memset(LongLibraryName, 'a', sizeof(LongLibraryName) - 1);
LongLibraryName[sizeof(LongLibraryName) - 1] = '\0';
UtAssert_INT32_EQ(CFE_ES_LoadLibrary(&Id, LongLibraryName, &LoadParams), CFE_ES_BAD_ARGUMENT);
/* Test successful shared library loading and initialization */
UT_InitData();
UT_SetDummyFuncRtn(OS_SUCCESS);
CFE_UtAssert_SUCCESS(CFE_ES_LoadLibrary(&Id, "TST_LIB", &LoadParams));
UtLibRecPtr = CFE_ES_LocateLibRecordByID(Id);
UtAssert_NOT_NULL(UtLibRecPtr);
CFE_UtAssert_TRUE(CFE_ES_LibRecordIsUsed(UtLibRecPtr));
/* Try loading same library again, should return the DUPLICATE code */
UtAssert_INT32_EQ(CFE_ES_LoadLibrary(&Id, "TST_LIB", &LoadParams), CFE_ES_ERR_DUPLICATE_NAME);
CFE_UtAssert_RESOURCEID_EQ(Id, CFE_ES_LibRecordGetID(UtLibRecPtr));
/* Test shared library loading and initialization where the library
* fails to load
*/
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(OS_ModuleLoad), 1, -1);
UtAssert_INT32_EQ(CFE_ES_LoadLibrary(&Id, "TST_LIB", &LoadParams), CFE_STATUS_EXTERNAL_RESOURCE_FAIL);
/* Test shared library loading and initialization where the library
* entry point symbol cannot be found
*/
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(OS_ModuleSymbolLookup), 1, -1);
UtAssert_INT32_EQ(CFE_ES_LoadLibrary(&Id, "TST_LIB", &LoadParams), CFE_STATUS_EXTERNAL_RESOURCE_FAIL);
/*
* Test shared library loading and initialization where the library
* entry point symbol is the special string "NULL". This should skip
* symbol lookup.
*/
ES_ResetUnitTest();
ES_UT_SetupModuleLoadParams(&LoadParams, "nullep", "NULL");
CFE_UtAssert_SUCCESS(CFE_ES_LoadLibrary(&Id, "TST_LIB1", &LoadParams));
UtAssert_STUB_COUNT(OS_ModuleSymbolLookup, 0); /* should NOT have been called */
/* Likewise for a entry point where the string is empty */
LoadParams.InitSymbolName[0] = 0;
CFE_UtAssert_SUCCESS(CFE_ES_LoadLibrary(&Id, "TST_LIB2", &LoadParams));
UtAssert_STUB_COUNT(OS_ModuleSymbolLookup, 0); /* should NOT have been called */
/* Test shared library loading and initialization where the library
* initialization function fails and then must be cleaned up
*/
ES_ResetUnitTest();
UT_SetDefaultReturnValue(UT_KEY(OS_remove), OS_ERROR); /* for coverage of error path */
UT_SetDefaultReturnValue(UT_KEY(dummy_function), -555);
ES_UT_SetupModuleLoadParams(&LoadParams, "filename", "dummy_function");
UtAssert_INT32_EQ(CFE_ES_LoadLibrary(&Id, "TST_LIB", &LoadParams), -555);
/* Test shared library loading and initialization where there are no
* library slots available
*/
ES_ResetUnitTest();
UT_SetDefaultReturnValue(UT_KEY(CFE_ResourceId_FindNext), OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_LoadLibrary(&Id, "LibName", &LoadParams), CFE_ES_NO_RESOURCE_IDS_AVAILABLE);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_LIBRARY_SLOTS]);
/* check operation of the CFE_ES_CheckLibIdSlotUsed() function */
CFE_ES_Global.LibTable[1].LibId = CFE_ES_LIBID_C(ES_UT_MakeLibIdForIndex(1));
CFE_ES_Global.LibTable[2].LibId = CFE_ES_LIBID_UNDEFINED;
CFE_UtAssert_TRUE(CFE_ES_CheckLibIdSlotUsed(ES_UT_MakeLibIdForIndex(1)));
CFE_UtAssert_FALSE(CFE_ES_CheckLibIdSlotUsed(ES_UT_MakeLibIdForIndex(2)));
/*
* Test public Name+ID query/lookup API
*/
ES_ResetUnitTest();
ES_UT_SetupSingleLibId("UT", &UtLibRecPtr);
Id = CFE_ES_LibRecordGetID(UtLibRecPtr);
CFE_UtAssert_SUCCESS(CFE_ES_GetLibName(LongLibraryName, Id, sizeof(LongLibraryName)));
UtAssert_INT32_EQ(CFE_ES_GetLibIDByName(&Id, "Nonexistent"), CFE_ES_ERR_NAME_NOT_FOUND);
CFE_UtAssert_SUCCESS(CFE_ES_GetLibIDByName(&Id, LongLibraryName));
CFE_UtAssert_RESOURCEID_EQ(Id, CFE_ES_LibRecordGetID(UtLibRecPtr));
UtAssert_INT32_EQ(CFE_ES_GetLibName(LongLibraryName, CFE_ES_LIBID_UNDEFINED, sizeof(LongLibraryName)),
CFE_ES_ERR_RESOURCEID_NOT_VALID);
UtAssert_INT32_EQ(CFE_ES_GetLibName(NULL, Id, sizeof(LongLibraryName)), CFE_ES_BAD_ARGUMENT);
UtAssert_INT32_EQ(CFE_ES_GetLibIDByName(&Id, NULL), CFE_ES_BAD_ARGUMENT);
}
void TestERLog(void)
{
void * LocalBuffer;
size_t LocalBufSize;
CFE_ES_BackgroundLogDumpGlobal_t State;
UtPrintf("Begin Test Exception and Reset Log");
/* Test initial rolling over log entry,
* null description,
* and non-null context with small size
*/
ES_ResetUnitTest();
CFE_ES_Global.ResetDataPtr->ERLogIndex = CFE_PLATFORM_ES_ER_LOG_ENTRIES + 1;
CFE_UtAssert_SUCCESS(CFE_ES_WriteToERLog(CFE_ES_LogEntryType_CORE, CFE_PSP_RST_TYPE_POWERON, 1, NULL));
UtAssert_UINT32_EQ(CFE_ES_Global.ResetDataPtr->ERLogIndex, 1);
CFE_UtAssert_STRINGBUF_EQ(CFE_ES_Global.ResetDataPtr->ERLog[0].BaseInfo.Description,
sizeof(CFE_ES_Global.ResetDataPtr->ERLog[0].BaseInfo.Description),
"No Description String Given.", SIZE_MAX);
/* Test non-rolling over log entry,
* null description,
* and null context
*/
ES_ResetUnitTest();
CFE_ES_Global.ResetDataPtr->ERLogIndex = 0;
CFE_UtAssert_SUCCESS(CFE_ES_WriteToERLog(CFE_ES_LogEntryType_CORE, CFE_PSP_RST_TYPE_POWERON, 1, NULL));
UtAssert_UINT32_EQ(CFE_ES_Global.ResetDataPtr->ERLogIndex, 1);
/* Test ER log background write functions */
memset(&State, 0, sizeof(State));
LocalBuffer = NULL;
LocalBufSize = 0;
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_Exception_CopyContext), 1, 128);
CFE_UtAssert_FALSE(CFE_ES_BackgroundERLogFileDataGetter(&State, 0, &LocalBuffer, &LocalBufSize));
CFE_UtAssert_MEMOFFSET_EQ(State.EntryBuffer.ContextSize, 128);
UtAssert_NOT_NULL(LocalBuffer);
UtAssert_NONZERO(LocalBufSize);
memset(&State.EntryBuffer, 0xEE, sizeof(State.EntryBuffer));
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_Exception_CopyContext), 1, -1);
CFE_UtAssert_TRUE(
CFE_ES_BackgroundERLogFileDataGetter(&State, CFE_PLATFORM_ES_ER_LOG_ENTRIES - 1, &LocalBuffer, &LocalBufSize));
UtAssert_ZERO(State.EntryBuffer.ContextSize);
CFE_UtAssert_TRUE(
CFE_ES_BackgroundERLogFileDataGetter(&State, CFE_PLATFORM_ES_ER_LOG_ENTRIES, &LocalBuffer, &LocalBufSize));
UtAssert_NULL(LocalBuffer);
UtAssert_ZERO(LocalBufSize);
/* Test ER log background write event handling */
UT_ClearEventHistory();
CFE_ES_BackgroundERLogFileEventHandler(&State, CFE_FS_FileWriteEvent_COMPLETE, CFE_SUCCESS, 10, 0, 100);
CFE_UtAssert_EVENTSENT(CFE_ES_ERLOG2_EID);
UT_ClearEventHistory();
CFE_ES_BackgroundERLogFileEventHandler(&State, CFE_FS_FileWriteEvent_HEADER_WRITE_ERROR, -1, 10, 10, 100);
CFE_UtAssert_EVENTSENT(CFE_ES_FILEWRITE_ERR_EID);
UT_ClearEventHistory();
CFE_ES_BackgroundERLogFileEventHandler(&State, CFE_FS_FileWriteEvent_RECORD_WRITE_ERROR, -1, 10, 10, 100);
CFE_UtAssert_EVENTSENT(CFE_ES_FILEWRITE_ERR_EID);
UT_ClearEventHistory();
CFE_ES_BackgroundERLogFileEventHandler(&State, CFE_FS_FileWriteEvent_CREATE_ERROR, -1, 10, 10, 100);
CFE_UtAssert_EVENTSENT(CFE_ES_ERLOG2_ERR_EID);
UT_ClearEventHistory();
CFE_ES_BackgroundERLogFileEventHandler(&State, CFE_FS_FileWriteEvent_UNDEFINED, CFE_SUCCESS, 10, 0, 100);
CFE_UtAssert_EVENTCOUNT(0);
}
void TestGenericPool(void)
{
CFE_ES_GenPoolRecord_t Pool1;
CFE_ES_GenPoolRecord_t Pool2;
size_t Offset1;
size_t Offset2;
size_t Offset3;
size_t Offset4;
size_t OffsetEnd;
size_t BlockSize;
CFE_ES_MemOffset_t FreeSize;
CFE_ES_MemOffset_t TotalSize;
uint16 NumBlocks;
uint32 CountBuf;
uint32 ErrBuf;
CFE_ES_BlockStats_t BlockStats;
static const size_t UT_POOL_BLOCK_SIZES[CFE_PLATFORM_ES_POOL_MAX_BUCKETS] = {
/*
* These are intentionally in a mixed order
* so that the implementation will sort them.
*/
16, 56, 60, 40, 44, 48, 64, 128, 20, 24, 28, 12, 52, 32, 4, 8, 36};
uint16 i;
uint32 ExpectedCount;
ES_ResetUnitTest();
/* Test Attempt to create pool with bad alignment / non power of 2 - should reject. */
memset(&UT_MemPoolDirectBuffer, 0xee, sizeof(UT_MemPoolDirectBuffer));
OffsetEnd = sizeof(UT_MemPoolDirectBuffer.Data);
UtAssert_INT32_EQ(CFE_ES_GenPoolInitialize(&Pool1, 0, OffsetEnd, 42, CFE_PLATFORM_ES_POOL_MAX_BUCKETS,
UT_POOL_BLOCK_SIZES, ES_UT_PoolDirectRetrieve, ES_UT_PoolDirectCommit),
CFE_ES_BAD_ARGUMENT);
/* Test successfully creating direct access pool, with alignment, no mutex */
memset(&UT_MemPoolDirectBuffer, 0xee, sizeof(UT_MemPoolDirectBuffer));
OffsetEnd = sizeof(UT_MemPoolDirectBuffer.Data);
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolInitialize(&Pool1, 0, OffsetEnd, 32, CFE_PLATFORM_ES_POOL_MAX_BUCKETS,
UT_POOL_BLOCK_SIZES, ES_UT_PoolDirectRetrieve,
ES_UT_PoolDirectCommit));
/* Allocate buffers until no space left */
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolGetBlock(&Pool1, &Offset1, 44));
UtAssert_NONZERO(Offset1);
CFE_UtAssert_ATMOST(Offset1, OffsetEnd - 44);
UtAssert_True((Offset1 & 0x1F) == 0, "Offset1(%lu) 32 byte alignment", (unsigned long)Offset1);
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolGetBlock(&Pool1, &Offset2, 72));
CFE_UtAssert_ATLEAST(Offset2, Offset1 + 44);
CFE_UtAssert_ATMOST(Offset2, OffsetEnd - 72);
UtAssert_True((Offset2 & 0x1F) == 0, "Offset2(%lu) 32 byte alignment", (unsigned long)Offset2);
UtAssert_INT32_EQ(CFE_ES_GenPoolGetBlock(&Pool1, &Offset3, 72), CFE_ES_ERR_MEM_BLOCK_SIZE);
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolGetBlock(&Pool1, &Offset3, 6));
CFE_UtAssert_ATLEAST(Offset3, Offset2 + 72);
CFE_UtAssert_ATMOST(Offset3, OffsetEnd - 6);
UtAssert_True((Offset3 & 0x1F) == 0, "Offset3(%lu) 32 byte alignment", (unsigned long)Offset3);
/* Free a buffer and attempt to reallocate */
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolPutBlock(&Pool1, &BlockSize, Offset2));
CFE_UtAssert_MEMOFFSET_EQ(BlockSize, 72);
/* Should not be able to free more than once */
/* This should increment the validation error count */
UtAssert_ZERO(Pool1.ValidationErrorCount);
UtAssert_INT32_EQ(CFE_ES_GenPoolPutBlock(&Pool1, &BlockSize, Offset2), CFE_ES_POOL_BLOCK_INVALID);
UtAssert_NONZERO(Pool1.ValidationErrorCount);
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolGetBlock(&Pool1, &Offset4, 100));
CFE_UtAssert_MEMOFFSET_EQ(Offset4, Offset2);
/* Attempt Bigger than the largest bucket */
UtAssert_INT32_EQ(CFE_ES_GenPoolGetBlock(&Pool1, &Offset1, 1000), CFE_ES_ERR_MEM_BLOCK_SIZE);
/* Call stats functions for coverage (no return code) */
CFE_ES_GenPoolGetUsage(&Pool1, &FreeSize, &TotalSize);
CFE_ES_GenPoolGetCounts(&Pool1, &NumBlocks, &CountBuf, &ErrBuf);
CFE_ES_GenPoolGetBucketUsage(&Pool1, 1, &BlockStats);
/* Check various outputs to ensure correctness */
CFE_UtAssert_MEMOFFSET_EQ(TotalSize, OffsetEnd);
UtAssert_UINT32_EQ(CountBuf, 3);
UtAssert_NONZERO(FreeSize);
/* put blocks so the pool has a mixture of allocated an deallocated blocks */
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolPutBlock(&Pool1, &BlockSize, Offset1));
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolPutBlock(&Pool1, &BlockSize, Offset2));
/* Now wipe the pool management structure, and attempt to rebuild it. */
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolInitialize(&Pool2, 0, OffsetEnd, 32, CFE_PLATFORM_ES_POOL_MAX_BUCKETS,
UT_POOL_BLOCK_SIZES, ES_UT_PoolDirectRetrieve,
ES_UT_PoolDirectCommit));
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolRebuild(&Pool2));
/* After rebuilding, Pool2 should have similar state data to Pool1. */
CFE_UtAssert_MEMOFFSET_EQ(Pool1.TailPosition, Pool2.TailPosition);
UtAssert_UINT32_EQ(Pool1.AllocationCount, Pool2.AllocationCount);
for (i = 0; i < Pool1.NumBuckets; ++i)
{
/* Allocation counts should match exactly */
UtAssert_UINT32_EQ(Pool1.Buckets[i].AllocationCount, Pool2.Buckets[i].AllocationCount);
/*
* The recovery is not aware of how many times the block was
* recycled, so this needs to be adjusted.
*/
ExpectedCount = Pool1.Buckets[i].ReleaseCount - Pool1.Buckets[i].RecycleCount;
UtAssert_UINT32_EQ(ExpectedCount, Pool2.Buckets[i].ReleaseCount);
}
/* Get blocks again, from the recovered pool, to demonstrate that
* the pool is functional after recovery. */
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolGetBlock(&Pool2, &Offset3, 44));
CFE_UtAssert_MEMOFFSET_EQ(Offset3, Offset1);
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolGetBlock(&Pool2, &Offset4, 72));
CFE_UtAssert_MEMOFFSET_EQ(Offset4, Offset2);
/* Test successfully creating indirect memory pool, no alignment, with mutex */
memset(&UT_MemPoolIndirectBuffer, 0xee, sizeof(UT_MemPoolIndirectBuffer));
OffsetEnd = sizeof(UT_MemPoolIndirectBuffer.Data);
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolInitialize(&Pool2, 2, OffsetEnd - 2, 0, CFE_PLATFORM_ES_POOL_MAX_BUCKETS,
UT_POOL_BLOCK_SIZES, ES_UT_PoolIndirectRetrieve,
ES_UT_PoolIndirectCommit));
/* Do Series of allocations - confirm that the implementation is
* properly adhering to the block sizes specified. */
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolGetBlock(&Pool2, &Offset1, 1));
/* With no alignment adjustments, the result offset should be exactly matching */
CFE_UtAssert_MEMOFFSET_EQ(Offset1, 2 + sizeof(CFE_ES_GenPoolBD_t));
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolGetBlock(&Pool2, &Offset2, 55));
/* the previous block should be 4 in size (smallest block) */
CFE_UtAssert_MEMOFFSET_EQ(Offset2, Offset1 + 4 + sizeof(CFE_ES_GenPoolBD_t));
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolGetBlock(&Pool2, &Offset3, 15));
/* the previous block should be 56 in size */
CFE_UtAssert_MEMOFFSET_EQ(Offset3, Offset2 + 56 + sizeof(CFE_ES_GenPoolBD_t));
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolGetBlock(&Pool2, &Offset4, 54));
/* the previous block should be 16 in size */
CFE_UtAssert_MEMOFFSET_EQ(Offset4, Offset3 + 16 + sizeof(CFE_ES_GenPoolBD_t));
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolPutBlock(&Pool2, &BlockSize, Offset1));
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolPutBlock(&Pool2, &BlockSize, Offset2));
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolPutBlock(&Pool2, &BlockSize, Offset3));
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolPutBlock(&Pool2, &BlockSize, Offset4));
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolGetBlock(&Pool2, &Offset1, 56));
/* should re-issue previous block */
CFE_UtAssert_MEMOFFSET_EQ(Offset4, Offset1);
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolGetBlock(&Pool2, &Offset3, 56));
/* should re-issue previous block */
CFE_UtAssert_MEMOFFSET_EQ(Offset3, Offset2);
/* Getting another will fail, despite being enough space,
* because its now fragmented. */
UtAssert_INT32_EQ(CFE_ES_GenPoolGetBlock(&Pool2, &Offset2, 12), CFE_ES_ERR_MEM_BLOCK_SIZE);
/* Put the buffer, then corrupt the memory and try to recycle */
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolPutBlock(&Pool2, &BlockSize, Offset3));
memset(UT_MemPoolIndirectBuffer.Data, 0xee, sizeof(UT_MemPoolIndirectBuffer.Data));
UtAssert_INT32_EQ(CFE_ES_GenPoolGetBlock(&Pool2, &Offset3, 56), CFE_ES_ERR_MEM_BLOCK_SIZE);
/* Test with just a single block size */
ES_ResetUnitTest();
memset(&UT_MemPoolDirectBuffer, 0xee, sizeof(UT_MemPoolDirectBuffer));
/* Calculate exact (predicted) pool consumption per block */
OffsetEnd = (sizeof(CFE_ES_GenPoolBD_t) + 31) & 0xFFF0;
OffsetEnd *= 2; /* make enough for 2 */
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolInitialize(&Pool1, 0, OffsetEnd, 16, 1, UT_POOL_BLOCK_SIZES,
ES_UT_PoolDirectRetrieve, ES_UT_PoolDirectCommit));
/*
* This should be exactly enough for 2 allocations.
* Allocation larger than 16 should fail.
*/
UtAssert_INT32_EQ(CFE_ES_GenPoolGetBlock(&Pool1, &Offset1, 32), CFE_ES_ERR_MEM_BLOCK_SIZE);
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolGetBlock(&Pool1, &Offset2, 1));
CFE_UtAssert_SUCCESS(CFE_ES_GenPoolGetBlock(&Pool1, &Offset3, 16));
/* Call stats functions for coverage (no return code) */
CFE_ES_GenPoolGetUsage(&Pool1, &FreeSize, &TotalSize);
CFE_ES_GenPoolGetCounts(&Pool1, &NumBlocks, &CountBuf, &ErrBuf);
/* Check various outputs to ensure correctness */
CFE_UtAssert_MEMOFFSET_EQ(TotalSize, OffsetEnd);
CFE_UtAssert_MEMOFFSET_EQ(FreeSize, 0);
UtAssert_UINT32_EQ(CountBuf, 2);
/*
* Check other validation
*/
UtAssert_INT32_EQ(CFE_ES_GenPoolPutBlock(&Pool1, &BlockSize, 0), CFE_ES_BUFFER_NOT_IN_POOL);
CFE_UtAssert_TRUE(CFE_ES_GenPoolValidateState(&Pool1));
Pool1.TailPosition = 0xFFFFFF;
CFE_UtAssert_FALSE(CFE_ES_GenPoolValidateState(&Pool1));
}
void TestTask(void)
{
uint32 ResetType;
osal_id_t UT_ContextTask;
union
{
CFE_MSG_Message_t Msg;
CFE_ES_NoArgsCmd_t NoArgsCmd;
CFE_ES_ClearSysLogCmd_t ClearSysLogCmd;
CFE_ES_ClearERLogCmd_t ClearERLogCmd;
CFE_ES_ResetPRCountCmd_t ResetPRCountCmd;
CFE_ES_RestartCmd_t RestartCmd;
CFE_ES_StartAppCmd_t StartAppCmd;
CFE_ES_StopAppCmd_t StopAppCmd;
CFE_ES_RestartAppCmd_t RestartAppCmd;
CFE_ES_ReloadAppCmd_t ReloadAppCmd;
CFE_ES_QueryOneCmd_t QueryOneCmd;
CFE_ES_QueryAllCmd_t QueryAllCmd;
CFE_ES_OverWriteSysLogCmd_t OverwriteSysLogCmd;
CFE_ES_WriteSysLogCmd_t WriteSysLogCmd;
CFE_ES_WriteERLogCmd_t WriteERLogCmd;
CFE_ES_SetMaxPRCountCmd_t SetMaxPRCountCmd;
CFE_ES_DeleteCDSCmd_t DeleteCDSCmd;
CFE_ES_SendMemPoolStatsCmd_t SendMemPoolStatsCmd;
CFE_ES_DumpCDSRegistryCmd_t DumpCDSRegistryCmd;
CFE_ES_QueryAllTasksCmd_t QueryAllTasksCmd;
} CmdBuf;
CFE_ES_AppRecord_t * UtAppRecPtr;
CFE_ES_TaskRecord_t * UtTaskRecPtr;
CFE_ES_CDS_RegRec_t * UtCDSRegRecPtr;
CFE_ES_MemPoolRecord_t *UtPoolRecPtr;
CFE_SB_MsgId_t MsgId = CFE_SB_INVALID_MSG_ID;
UtPrintf("Begin Test Task");
/* Reset the log index; CFE_ES_TaskMain() calls CFE_ES_TaskInit() which
* sets SystemLogMode to DISCARD, which can result in a log overflow
* depending on the value that the index has reached from previous tests
*/
memset(&CmdBuf, 0, sizeof(CmdBuf));
CFE_ES_Global.ResetDataPtr->SystemLogWriteIdx = 0;
CFE_ES_Global.ResetDataPtr->SystemLogEndIdx = CFE_ES_Global.ResetDataPtr->SystemLogWriteIdx;
/* Test task main process loop with a command pipe error */
ES_ResetUnitTest();
/* this is needed so CFE_ES_GetAppId works */
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, NULL, NULL, NULL);
/* Set up buffer for first cycle, pipe failure is on 2nd */
UT_SetDataBuffer(UT_KEY(CFE_MSG_GetMsgId), &MsgId, sizeof(MsgId), false);
CFE_ES_TaskMain();
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_COMMAND_PIPE]);
/* Test task main process loop with bad checksum information */
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_GetCFETextSegmentInfo), 1, -1);
/* this is needed so CFE_ES_GetAppId works */
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, NULL, NULL, NULL);
CFE_UtAssert_SUCCESS(CFE_ES_TaskInit());
UtAssert_UINT32_EQ(CFE_ES_Global.TaskData.HkPacket.Payload.CFECoreChecksum, 0xFFFF);
/* Test successful task main process loop - Power On Reset Path */
ES_ResetUnitTest();
/* this is needed so CFE_ES_GetAppId works */
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, NULL, NULL, NULL);
CFE_ES_Global.ResetDataPtr->ResetVars.ResetType = 2;
CFE_UtAssert_SUCCESS(CFE_ES_TaskInit());
/* Test successful task main process loop - Processor Reset Path */
ES_ResetUnitTest();
/* this is needed so CFE_ES_GetAppId works */
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, NULL, NULL, NULL);
CFE_ES_Global.ResetDataPtr->ResetVars.ResetType = 1;
CFE_UtAssert_SUCCESS(CFE_ES_TaskInit());
/* Test task main process loop with a with an EVS register failure */
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(CFE_EVS_Register), 1, -1);
UtAssert_INT32_EQ(CFE_ES_TaskInit(), -1);
/* Test task main process loop with a SB pipe create failure */
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(CFE_SB_CreatePipe), 1, -2);
UtAssert_INT32_EQ(CFE_ES_TaskInit(), -2);
/* Test task main process loop with a HK packet subscribe failure */
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(CFE_SB_Subscribe), 1, -3);
UtAssert_INT32_EQ(CFE_ES_TaskInit(), -3);
/* Test task main process loop with a ground command subscribe failure */
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(CFE_SB_Subscribe), 2, -4);
UtAssert_INT32_EQ(CFE_ES_TaskInit(), -4);
/* Test task main process loop with an init event send failure */
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(CFE_EVS_SendEvent), 1, -5);
UtAssert_INT32_EQ(CFE_ES_TaskInit(), -5);
/* Test task main process loop with version event send failure */
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(CFE_EVS_SendEvent), 2, -6);
UtAssert_INT32_EQ(CFE_ES_TaskInit(), -6);
/* Test task init with background init fail */
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(OS_BinSemCreate), 1, -7);
UtAssert_INT32_EQ(CFE_ES_TaskInit(), -7);
/* Set the log mode to OVERWRITE; CFE_ES_TaskInit() sets SystemLogMode to
* DISCARD, which can result in a log overflow depending on the value that
* the index reaches during subsequent tests
*/
CFE_ES_Global.ResetDataPtr->SystemLogMode = CFE_ES_LogMode_OVERWRITE;
/* Test a successful HK request */
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.NoArgsCmd), UT_TPID_CFE_ES_SEND_HK);
UtAssert_NONZERO(CFE_ES_Global.TaskData.HkPacket.Payload.HeapBytesFree);
/* Test the HK request with a get heap failure */
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(OS_HeapGetInfo), 1, -1);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.NoArgsCmd), UT_TPID_CFE_ES_SEND_HK);
UtAssert_ZERO(CFE_ES_Global.TaskData.HkPacket.Payload.HeapBytesFree);
/* Test successful no-op command */
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.NoArgsCmd), UT_TPID_CFE_ES_CMD_NOOP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_NOOP_INF_EID);
/* Test successful reset counters command */
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.NoArgsCmd), UT_TPID_CFE_ES_CMD_RESET_COUNTERS_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_RESET_INF_EID);
/* Test successful cFE restart */
ES_ResetUnitTest();
CFE_ES_Global.ResetDataPtr->ResetVars.ProcessorResetCount = 0;
CmdBuf.RestartCmd.Payload.RestartType = CFE_PSP_RST_TYPE_PROCESSOR;
UT_SetDataBuffer(UT_KEY(CFE_PSP_Restart), &ResetType, sizeof(ResetType), false);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.RestartCmd), UT_TPID_CFE_ES_CMD_RESTART_CC);
UtAssert_UINT32_EQ(ResetType, CFE_PSP_RST_TYPE_PROCESSOR);
UtAssert_STUB_COUNT(CFE_PSP_Restart, 1);
/* Test cFE restart with bad restart type */
ES_ResetUnitTest();
CmdBuf.RestartCmd.Payload.RestartType = 4524;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.RestartCmd), UT_TPID_CFE_ES_CMD_RESTART_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_BOOT_ERR_EID);
/* Test successful app create */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
strncpy(CmdBuf.StartAppCmd.Payload.AppFileName, "filename", sizeof(CmdBuf.StartAppCmd.Payload.AppFileName) - 1);
CmdBuf.StartAppCmd.Payload.AppFileName[sizeof(CmdBuf.StartAppCmd.Payload.AppFileName) - 1] = '\0';
strncpy(CmdBuf.StartAppCmd.Payload.AppEntryPoint, "entrypoint",
sizeof(CmdBuf.StartAppCmd.Payload.AppEntryPoint) - 1);
CmdBuf.StartAppCmd.Payload.AppEntryPoint[sizeof(CmdBuf.StartAppCmd.Payload.AppEntryPoint) - 1] = '\0';
memset(CmdBuf.StartAppCmd.Payload.Application, 'x', sizeof(CmdBuf.StartAppCmd.Payload.Application) - 1);
CmdBuf.StartAppCmd.Payload.Application[sizeof(CmdBuf.StartAppCmd.Payload.Application) - 1] = '\0';
CmdBuf.StartAppCmd.Payload.Priority = 160;
CmdBuf.StartAppCmd.Payload.StackSize = CFE_ES_MEMOFFSET_C(8192);
CmdBuf.StartAppCmd.Payload.ExceptionAction = CFE_ES_ExceptionAction_RESTART_APP;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.StartAppCmd), UT_TPID_CFE_ES_CMD_START_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_START_INF_EID);
/* Test app create with an OS task create failure */
ES_ResetUnitTest();
UT_SetDefaultReturnValue(UT_KEY(OS_TaskCreate), OS_ERROR);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.StartAppCmd), UT_TPID_CFE_ES_CMD_START_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_START_ERR_EID);
/* Test app create with an invalid file name */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
strncpy(CmdBuf.StartAppCmd.Payload.AppFileName, "123", sizeof(CmdBuf.StartAppCmd.Payload.AppFileName) - 1);
CmdBuf.StartAppCmd.Payload.AppFileName[sizeof(CmdBuf.StartAppCmd.Payload.AppFileName) - 1] = '\0';
strncpy(CmdBuf.StartAppCmd.Payload.AppEntryPoint, "entrypoint",
sizeof(CmdBuf.StartAppCmd.Payload.AppEntryPoint) - 1);
CmdBuf.StartAppCmd.Payload.AppEntryPoint[sizeof(CmdBuf.StartAppCmd.Payload.AppEntryPoint) - 1] = '\0';
strncpy(CmdBuf.StartAppCmd.Payload.Application, "appName", sizeof(CmdBuf.StartAppCmd.Payload.Application) - 1);
CmdBuf.StartAppCmd.Payload.Application[sizeof(CmdBuf.StartAppCmd.Payload.Application) - 1] = '\0';
CmdBuf.StartAppCmd.Payload.Priority = 160;
CmdBuf.StartAppCmd.Payload.StackSize = CFE_ES_MEMOFFSET_C(12096);
CmdBuf.StartAppCmd.Payload.ExceptionAction = CFE_ES_ExceptionAction_RESTART_APP;
UT_SetDeferredRetcode(UT_KEY(CFE_FS_ParseInputFileNameEx), 1, CFE_FS_INVALID_PATH);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.StartAppCmd), UT_TPID_CFE_ES_CMD_START_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_START_INVALID_FILENAME_ERR_EID);
/* Test app create with a null application entry point */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
strncpy(CmdBuf.StartAppCmd.Payload.AppFileName, "filename", sizeof(CmdBuf.StartAppCmd.Payload.AppFileName) - 1);
CmdBuf.StartAppCmd.Payload.AppFileName[sizeof(CmdBuf.StartAppCmd.Payload.AppFileName) - 1] = '\0';
CmdBuf.StartAppCmd.Payload.AppEntryPoint[0] = '\0';
strncpy(CmdBuf.StartAppCmd.Payload.Application, "appName", sizeof(CmdBuf.StartAppCmd.Payload.Application) - 1);
CmdBuf.StartAppCmd.Payload.Application[sizeof(CmdBuf.StartAppCmd.Payload.Application) - 1] = '\0';
CmdBuf.StartAppCmd.Payload.Priority = 160;
CmdBuf.StartAppCmd.Payload.StackSize = CFE_ES_MEMOFFSET_C(12096);
CmdBuf.StartAppCmd.Payload.ExceptionAction = CFE_ES_ExceptionAction_RESTART_APP;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.StartAppCmd), UT_TPID_CFE_ES_CMD_START_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_START_INVALID_ENTRY_POINT_ERR_EID);
/* Test app create with a null application name */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
strncpy(CmdBuf.StartAppCmd.Payload.AppFileName, "filename", sizeof(CmdBuf.StartAppCmd.Payload.AppFileName) - 1);
CmdBuf.StartAppCmd.Payload.AppFileName[sizeof(CmdBuf.StartAppCmd.Payload.AppFileName) - 1] = '\0';
strncpy(CmdBuf.StartAppCmd.Payload.AppEntryPoint, "entrypoint",
sizeof(CmdBuf.StartAppCmd.Payload.AppEntryPoint) - 1);
CmdBuf.StartAppCmd.Payload.AppEntryPoint[sizeof(CmdBuf.StartAppCmd.Payload.AppEntryPoint) - 1] = '\0';
CmdBuf.StartAppCmd.Payload.Application[0] = '\0';
CmdBuf.StartAppCmd.Payload.Priority = 160;
CmdBuf.StartAppCmd.Payload.StackSize = CFE_ES_MEMOFFSET_C(12096);
CmdBuf.StartAppCmd.Payload.ExceptionAction = CFE_ES_ExceptionAction_RESTART_APP;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.StartAppCmd), UT_TPID_CFE_ES_CMD_START_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_START_NULL_APP_NAME_ERR_EID);
/* Test app create with with an invalid exception action */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
strncpy(CmdBuf.StartAppCmd.Payload.AppFileName, "filename", sizeof(CmdBuf.StartAppCmd.Payload.AppFileName) - 1);
CmdBuf.StartAppCmd.Payload.AppFileName[sizeof(CmdBuf.StartAppCmd.Payload.AppFileName) - 1] = '\0';
strncpy(CmdBuf.StartAppCmd.Payload.AppEntryPoint, "entrypoint",
sizeof(CmdBuf.StartAppCmd.Payload.AppEntryPoint) - 1);
CmdBuf.StartAppCmd.Payload.AppEntryPoint[sizeof(CmdBuf.StartAppCmd.Payload.AppEntryPoint) - 1] = '\0';
strncpy(CmdBuf.StartAppCmd.Payload.Application, "appName", sizeof(CmdBuf.StartAppCmd.Payload.Application) - 1);
CmdBuf.StartAppCmd.Payload.Application[sizeof(CmdBuf.StartAppCmd.Payload.Application) - 1] = '\0';
CmdBuf.StartAppCmd.Payload.Priority = 160;
CmdBuf.StartAppCmd.Payload.StackSize = CFE_ES_MEMOFFSET_C(12096);
CmdBuf.StartAppCmd.Payload.ExceptionAction = 255;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.StartAppCmd), UT_TPID_CFE_ES_CMD_START_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_START_EXC_ACTION_ERR_EID);
/* Test app create with a default stack size */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
strncpy(CmdBuf.StartAppCmd.Payload.AppFileName, "filename", sizeof(CmdBuf.StartAppCmd.Payload.AppFileName) - 1);
CmdBuf.StartAppCmd.Payload.AppFileName[sizeof(CmdBuf.StartAppCmd.Payload.AppFileName) - 1] = '\0';
strncpy(CmdBuf.StartAppCmd.Payload.AppEntryPoint, "entrypoint",
sizeof(CmdBuf.StartAppCmd.Payload.AppEntryPoint) - 1);
CmdBuf.StartAppCmd.Payload.AppEntryPoint[sizeof(CmdBuf.StartAppCmd.Payload.AppEntryPoint) - 1] = '\0';
strncpy(CmdBuf.StartAppCmd.Payload.Application, "appName", sizeof(CmdBuf.StartAppCmd.Payload.Application) - 1);
CmdBuf.StartAppCmd.Payload.Application[sizeof(CmdBuf.StartAppCmd.Payload.Application) - 1] = '\0';
CmdBuf.StartAppCmd.Payload.Priority = 160;
CmdBuf.StartAppCmd.Payload.StackSize = CFE_ES_MEMOFFSET_C(0);
CmdBuf.StartAppCmd.Payload.ExceptionAction = CFE_ES_ExceptionAction_RESTART_APP;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.StartAppCmd), UT_TPID_CFE_ES_CMD_START_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_START_INF_EID);
/* Test app create with a bad priority */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
strncpy(CmdBuf.StartAppCmd.Payload.AppFileName, "filename", sizeof(CmdBuf.StartAppCmd.Payload.AppFileName) - 1);
CmdBuf.StartAppCmd.Payload.AppFileName[sizeof(CmdBuf.StartAppCmd.Payload.AppFileName) - 1] = '\0';
strncpy(CmdBuf.StartAppCmd.Payload.AppEntryPoint, "entrypoint",
sizeof(CmdBuf.StartAppCmd.Payload.AppEntryPoint) - 1);
CmdBuf.StartAppCmd.Payload.AppEntryPoint[sizeof(CmdBuf.StartAppCmd.Payload.AppEntryPoint) - 1] = '\0';
strncpy(CmdBuf.StartAppCmd.Payload.Application, "appName", sizeof(CmdBuf.StartAppCmd.Payload.Application) - 1);
CmdBuf.StartAppCmd.Payload.Application[sizeof(CmdBuf.StartAppCmd.Payload.Application) - 1] = '\0';
CmdBuf.StartAppCmd.Payload.Priority = 1000;
CmdBuf.StartAppCmd.Payload.StackSize = CFE_ES_MEMOFFSET_C(12096);
CmdBuf.StartAppCmd.Payload.ExceptionAction = CFE_ES_ExceptionAction_RESTART_APP;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.StartAppCmd), UT_TPID_CFE_ES_CMD_START_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_START_PRIORITY_ERR_EID);
/* Test successful app stop */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, "CFE_ES", NULL, NULL);
strncpy(CmdBuf.StopAppCmd.Payload.Application, "CFE_ES", sizeof(CmdBuf.StopAppCmd.Payload.Application) - 1);
CmdBuf.StopAppCmd.Payload.Application[sizeof(CmdBuf.StopAppCmd.Payload.Application) - 1] = '\0';
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.StopAppCmd), UT_TPID_CFE_ES_CMD_STOP_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_STOP_DBG_EID);
/* Test app stop failure */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_WAITING, "CFE_ES", NULL, NULL);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.StopAppCmd), UT_TPID_CFE_ES_CMD_STOP_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_STOP_ERR1_EID);
/* Test app stop with a bad app name */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
strncpy(CmdBuf.StopAppCmd.Payload.Application, "BAD_APP_NAME", sizeof(CmdBuf.StopAppCmd.Payload.Application) - 1);
CmdBuf.StopAppCmd.Payload.Application[sizeof(CmdBuf.StopAppCmd.Payload.Application) - 1] = '\0';
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.StopAppCmd), UT_TPID_CFE_ES_CMD_STOP_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_STOP_ERR2_EID);
/* Test successful app restart */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, "CFE_ES", NULL, NULL);
strncpy(CmdBuf.RestartAppCmd.Payload.Application, "CFE_ES", sizeof(CmdBuf.RestartAppCmd.Payload.Application) - 1);
CmdBuf.RestartAppCmd.Payload.Application[sizeof(CmdBuf.RestartAppCmd.Payload.Application) - 1] = '\0';
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.RestartAppCmd), UT_TPID_CFE_ES_CMD_RESTART_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_RESTART_APP_DBG_EID);
/* Test app restart with failed file check */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
UT_SetDefaultReturnValue(UT_KEY(OS_stat), OS_ERROR);
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, "CFE_ES", NULL, NULL);
strncpy(CmdBuf.RestartAppCmd.Payload.Application, "CFE_ES", sizeof(CmdBuf.RestartAppCmd.Payload.Application));
CmdBuf.RestartAppCmd.Payload.Application[sizeof(CmdBuf.RestartAppCmd.Payload.Application) - 1] = '\0';
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.RestartAppCmd), UT_TPID_CFE_ES_CMD_RESTART_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_RESTART_APP_ERR1_EID);
/* Test app restart with a bad app name */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
strncpy(CmdBuf.RestartAppCmd.Payload.Application, "BAD_APP_NAME",
sizeof(CmdBuf.RestartAppCmd.Payload.Application) - 1);
CmdBuf.RestartAppCmd.Payload.Application[sizeof(CmdBuf.RestartAppCmd.Payload.Application) - 1] = '\0';
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.RestartAppCmd), UT_TPID_CFE_ES_CMD_RESTART_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_RESTART_APP_ERR2_EID);
/* Test failed app restart, core app */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, "CFE_ES", NULL, NULL);
strncpy(CmdBuf.RestartAppCmd.Payload.Application, "CFE_ES", sizeof(CmdBuf.RestartAppCmd.Payload.Application) - 1);
CmdBuf.RestartAppCmd.Payload.Application[sizeof(CmdBuf.RestartAppCmd.Payload.Application) - 1] = '\0';
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.RestartAppCmd), UT_TPID_CFE_ES_CMD_RESTART_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_RESTART_APP_ERR1_EID);
/* Test failed app restart, not running */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_WAITING, "CFE_ES", NULL, NULL);
strncpy(CmdBuf.RestartAppCmd.Payload.Application, "CFE_ES", sizeof(CmdBuf.RestartAppCmd.Payload.Application));
CmdBuf.RestartAppCmd.Payload.Application[sizeof(CmdBuf.RestartAppCmd.Payload.Application) - 1] = '\0';
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.RestartAppCmd), UT_TPID_CFE_ES_CMD_RESTART_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_RESTART_APP_ERR1_EID);
/* Test successful app reload */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, "CFE_ES", NULL, NULL);
strncpy(CmdBuf.ReloadAppCmd.Payload.AppFileName, "New_Name", sizeof(CmdBuf.ReloadAppCmd.Payload.AppFileName) - 1);
CmdBuf.ReloadAppCmd.Payload.AppFileName[sizeof(CmdBuf.ReloadAppCmd.Payload.AppFileName) - 1] = '\0';
strncpy(CmdBuf.ReloadAppCmd.Payload.Application, "CFE_ES", sizeof(CmdBuf.ReloadAppCmd.Payload.Application) - 1);
CmdBuf.ReloadAppCmd.Payload.Application[sizeof(CmdBuf.ReloadAppCmd.Payload.Application) - 1] = '\0';
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.ReloadAppCmd), UT_TPID_CFE_ES_CMD_RELOAD_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_RELOAD_APP_DBG_EID);
/* Test app reload with missing file */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
UT_SetDefaultReturnValue(UT_KEY(OS_stat), OS_ERROR);
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, "CFE_ES", NULL, NULL);
strncpy(CmdBuf.ReloadAppCmd.Payload.AppFileName, "New_Name", sizeof(CmdBuf.ReloadAppCmd.Payload.AppFileName));
CmdBuf.ReloadAppCmd.Payload.AppFileName[sizeof(CmdBuf.ReloadAppCmd.Payload.AppFileName) - 1] = '\0';
strncpy(CmdBuf.ReloadAppCmd.Payload.Application, "CFE_ES", sizeof(CmdBuf.ReloadAppCmd.Payload.Application));
CmdBuf.ReloadAppCmd.Payload.Application[sizeof(CmdBuf.ReloadAppCmd.Payload.Application) - 1] = '\0';
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.ReloadAppCmd), UT_TPID_CFE_ES_CMD_RELOAD_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_RELOAD_APP_ERR1_EID);
/* Test app reload with a bad app name */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
strncpy(CmdBuf.ReloadAppCmd.Payload.Application, "BAD_APP_NAME",
sizeof(CmdBuf.ReloadAppCmd.Payload.Application) - 1);
CmdBuf.ReloadAppCmd.Payload.Application[sizeof(CmdBuf.ReloadAppCmd.Payload.Application) - 1] = '\0';
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.ReloadAppCmd), UT_TPID_CFE_ES_CMD_RELOAD_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_RELOAD_APP_ERR2_EID);
/* Test failed app reload, core app */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, "CFE_ES", NULL, NULL);
strncpy(CmdBuf.ReloadAppCmd.Payload.Application, "CFE_ES", sizeof(CmdBuf.ReloadAppCmd.Payload.Application));
CmdBuf.ReloadAppCmd.Payload.Application[sizeof(CmdBuf.ReloadAppCmd.Payload.Application) - 1] = '\0';
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.ReloadAppCmd), UT_TPID_CFE_ES_CMD_RELOAD_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_RELOAD_APP_ERR1_EID);
/* Test failed app reload, not RUNNING */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_WAITING, "CFE_ES", NULL, NULL);
strncpy(CmdBuf.ReloadAppCmd.Payload.Application, "CFE_ES", sizeof(CmdBuf.ReloadAppCmd.Payload.Application));
CmdBuf.ReloadAppCmd.Payload.Application[sizeof(CmdBuf.ReloadAppCmd.Payload.Application) - 1] = '\0';
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.ReloadAppCmd), UT_TPID_CFE_ES_CMD_RELOAD_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_RELOAD_APP_ERR1_EID);
/* Test successful telemetry packet request for single app data */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_WAITING, "CFE_ES", NULL, NULL);
strncpy(CmdBuf.QueryOneCmd.Payload.Application, "CFE_ES", sizeof(CmdBuf.QueryOneCmd.Payload.Application) - 1);
CmdBuf.QueryOneCmd.Payload.Application[sizeof(CmdBuf.QueryOneCmd.Payload.Application) - 1] = '\0';
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.QueryOneCmd), UT_TPID_CFE_ES_CMD_QUERY_ONE_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_ONE_APP_EID);
/* Test telemetry packet request for single app data with send message failure */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, "CFE_ES", NULL, NULL);
strncpy(CmdBuf.QueryOneCmd.Payload.Application, "CFE_ES", sizeof(CmdBuf.QueryOneCmd.Payload.Application) - 1);
CmdBuf.QueryOneCmd.Payload.Application[sizeof(CmdBuf.QueryOneCmd.Payload.Application) - 1] = '\0';
UT_SetDeferredRetcode(UT_KEY(CFE_SB_TransmitMsg), 1, -1);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.QueryOneCmd), UT_TPID_CFE_ES_CMD_QUERY_ONE_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_ONE_ERR_EID);
/* Test telemetry packet request for single app data with a bad app name */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, "CFE_ES", NULL, NULL);
strncpy(CmdBuf.QueryOneCmd.Payload.Application, "BAD_APP_NAME", sizeof(CmdBuf.QueryOneCmd.Payload.Application) - 1);
CmdBuf.QueryOneCmd.Payload.Application[sizeof(CmdBuf.QueryOneCmd.Payload.Application) - 1] = '\0';
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.QueryOneCmd), UT_TPID_CFE_ES_CMD_QUERY_ONE_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_ONE_APPID_ERR_EID);
/* Test successful write of all app data to file */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, "CFE_ES", NULL, NULL);
strncpy(CmdBuf.QueryAllCmd.Payload.FileName, "AllFilename", sizeof(CmdBuf.QueryAllCmd.Payload.FileName) - 1);
CmdBuf.QueryAllCmd.Payload.FileName[sizeof(CmdBuf.QueryAllCmd.Payload.FileName) - 1] = '\0';
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.QueryAllCmd), UT_TPID_CFE_ES_CMD_QUERY_ALL_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_ALL_APPS_EID);
/* Test write of all app data to file with a null file name */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.QueryAllCmd), UT_TPID_CFE_ES_CMD_QUERY_ALL_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_ALL_APPS_EID);
/* Test write of all app data to file with a bad file name */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
UT_SetDeferredRetcode(UT_KEY(CFE_FS_ParseInputFileNameEx), 1, CFE_FS_INVALID_PATH);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.QueryAllCmd), UT_TPID_CFE_ES_CMD_QUERY_ALL_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_OSCREATE_ERR_EID);
/* Test write of all app data to file with a write header failure */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
UT_SetDeferredRetcode(UT_KEY(CFE_FS_WriteHeader), 1, OS_ERROR);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.QueryAllCmd), UT_TPID_CFE_ES_CMD_QUERY_ALL_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_WRHDR_ERR_EID);
/* Test write of all app data to file with a file write failure */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, "CFE_ES", NULL, NULL);
UT_SetDefaultReturnValue(UT_KEY(OS_write), OS_ERROR);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.QueryAllCmd), UT_TPID_CFE_ES_CMD_QUERY_ALL_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_TASKWR_ERR_EID);
/* Test write of all app data to file with a file create failure */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, "CFE_ES", NULL, NULL);
UT_SetDefaultReturnValue(UT_KEY(OS_OpenCreate), OS_ERROR);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.QueryAllCmd), UT_TPID_CFE_ES_CMD_QUERY_ALL_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_OSCREATE_ERR_EID);
/* Test successful write of all task data to a file */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, "CFE_ES", NULL, NULL);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.QueryAllTasksCmd),
UT_TPID_CFE_ES_CMD_QUERY_ALL_TASKS_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_TASKINFO_EID);
/* Test write of all task data to a file with file name validation failure */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
UT_SetDeferredRetcode(UT_KEY(CFE_FS_ParseInputFileNameEx), 1, CFE_FS_INVALID_PATH);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.QueryAllTasksCmd),
UT_TPID_CFE_ES_CMD_QUERY_ALL_TASKS_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_TASKINFO_OSCREATE_ERR_EID);
/* Test write of all task data to a file with write header failure */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
strncpy(CmdBuf.QueryAllTasksCmd.Payload.FileName, "filename", sizeof(CmdBuf.QueryAllTasksCmd.Payload.FileName) - 1);
CmdBuf.QueryAllTasksCmd.Payload.FileName[sizeof(CmdBuf.QueryAllTasksCmd.Payload.FileName) - 1] = '\0';
UT_SetDeferredRetcode(UT_KEY(CFE_FS_WriteHeader), 1, -1);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.QueryAllTasksCmd),
UT_TPID_CFE_ES_CMD_QUERY_ALL_TASKS_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_TASKINFO_WRHDR_ERR_EID);
/* Test write of all task data to a file with a task write failure */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, "UT", NULL, NULL);
memset(&CmdBuf, 0, sizeof(CmdBuf));
UT_SetDefaultReturnValue(UT_KEY(OS_write), OS_ERROR);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.QueryAllTasksCmd),
UT_TPID_CFE_ES_CMD_QUERY_ALL_TASKS_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_TASKINFO_WR_ERR_EID);
/* Test write of all task data to a file with an OS create failure */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
UT_SetDefaultReturnValue(UT_KEY(OS_OpenCreate), OS_ERROR);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.QueryAllTasksCmd),
UT_TPID_CFE_ES_CMD_QUERY_ALL_TASKS_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_TASKINFO_OSCREATE_ERR_EID);
/* Test successful clearing of the system log */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.ClearSysLogCmd), UT_TPID_CFE_ES_CMD_CLEAR_SYSLOG_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_SYSLOG1_INF_EID);
/* Test successful overwriting of the system log using discard mode */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
CmdBuf.OverwriteSysLogCmd.Payload.Mode = CFE_ES_LogMode_OVERWRITE;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.OverwriteSysLogCmd),
UT_TPID_CFE_ES_CMD_OVER_WRITE_SYSLOG_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_SYSLOGMODE_EID);
/* Test overwriting the system log using an invalid mode */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
CmdBuf.OverwriteSysLogCmd.Payload.Mode = 255;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.OverwriteSysLogCmd),
UT_TPID_CFE_ES_CMD_OVER_WRITE_SYSLOG_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_ERR_SYSLOGMODE_EID);
/* Test successful writing of the system log */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
strncpy(CmdBuf.WriteSysLogCmd.Payload.FileName, "filename", sizeof(CmdBuf.WriteSysLogCmd.Payload.FileName) - 1);
CmdBuf.WriteSysLogCmd.Payload.FileName[sizeof(CmdBuf.WriteSysLogCmd.Payload.FileName) - 1] = '\0';
CFE_ES_Global.TaskData.HkPacket.Payload.SysLogEntries = 123;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.WriteSysLogCmd), UT_TPID_CFE_ES_CMD_WRITE_SYSLOG_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_SYSLOG2_EID);
/* Test writing the system log using a bad file name */
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(CFE_FS_ParseInputFileNameEx), 1, CFE_FS_INVALID_PATH);
memset(&CmdBuf, 0, sizeof(CmdBuf));
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.WriteSysLogCmd), UT_TPID_CFE_ES_CMD_WRITE_SYSLOG_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_SYSLOG2_ERR_EID);
/* Test writing the system log using a null file name */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
CmdBuf.WriteSysLogCmd.Payload.FileName[0] = '\0';
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.WriteSysLogCmd), UT_TPID_CFE_ES_CMD_WRITE_SYSLOG_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_SYSLOG2_EID);
/* Test writing the system log with an OS create failure */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
UT_SetDefaultReturnValue(UT_KEY(OS_OpenCreate), OS_ERROR);
CmdBuf.WriteSysLogCmd.Payload.FileName[0] = '\0';
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.WriteSysLogCmd), UT_TPID_CFE_ES_CMD_WRITE_SYSLOG_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_SYSLOG2_ERR_EID);
/* Test writing the system log with an OS write failure */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
UT_SetDefaultReturnValue(UT_KEY(OS_write), OS_ERROR);
CFE_ES_Global.ResetDataPtr->SystemLogWriteIdx =
snprintf(CFE_ES_Global.ResetDataPtr->SystemLog, sizeof(CFE_ES_Global.ResetDataPtr->SystemLog),
"0000-000-00:00:00.00000 Test Message\n");
CFE_ES_Global.ResetDataPtr->SystemLogEndIdx = CFE_ES_Global.ResetDataPtr->SystemLogWriteIdx;
CmdBuf.WriteSysLogCmd.Payload.FileName[0] = '\0';
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.WriteSysLogCmd), UT_TPID_CFE_ES_CMD_WRITE_SYSLOG_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_FILEWRITE_ERR_EID);
/* Test writing the system log with a write header failure */
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(CFE_FS_WriteHeader), 1, OS_ERROR);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.WriteSysLogCmd), UT_TPID_CFE_ES_CMD_WRITE_SYSLOG_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_FILEWRITE_ERR_EID);
/* Test successful clearing of the E&R log */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.ClearERLogCmd), UT_TPID_CFE_ES_CMD_CLEAR_ER_LOG_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_ERLOG1_INF_EID);
/* Test successful writing of the E&R log */
/* In the current implementation, it does not directly write the file,
* this just sets a flag for the background task */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
strncpy(CmdBuf.WriteERLogCmd.Payload.FileName, "filename", sizeof(CmdBuf.WriteERLogCmd.Payload.FileName) - 1);
CmdBuf.WriteERLogCmd.Payload.FileName[sizeof(CmdBuf.WriteERLogCmd.Payload.FileName) - 1] = '\0';
UT_SetDefaultReturnValue(UT_KEY(CFE_FS_BackgroundFileDumpIsPending), false);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.WriteERLogCmd), UT_TPID_CFE_ES_CMD_WRITE_ER_LOG_CC);
UtAssert_STUB_COUNT(CFE_FS_BackgroundFileDumpRequest, 1);
CFE_UtAssert_EVENTCOUNT(0);
/* Failure of parsing the file name */
UT_ClearEventHistory();
UT_SetDeferredRetcode(UT_KEY(CFE_FS_ParseInputFileNameEx), 1, CFE_FS_INVALID_PATH);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.WriteERLogCmd), UT_TPID_CFE_ES_CMD_WRITE_ER_LOG_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_ERLOG2_ERR_EID);
/* Failure from CFE_FS_BackgroundFileDumpRequest() should send the pending error event ID */
UT_ClearEventHistory();
UT_SetDeferredRetcode(UT_KEY(CFE_FS_BackgroundFileDumpRequest), 1, CFE_STATUS_REQUEST_ALREADY_PENDING);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.WriteERLogCmd), UT_TPID_CFE_ES_CMD_WRITE_ER_LOG_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_ERLOG_PENDING_ERR_EID);
/* Same event but pending locally */
UT_ClearEventHistory();
UT_SetDefaultReturnValue(UT_KEY(CFE_FS_BackgroundFileDumpIsPending), true);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.WriteERLogCmd), UT_TPID_CFE_ES_CMD_WRITE_ER_LOG_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_ERLOG_PENDING_ERR_EID);
/* Test scan for exceptions in the PSP, should invoke a Processor Reset */
ES_ResetUnitTest();
UT_SetDefaultReturnValue(UT_KEY(CFE_PSP_Exception_GetCount), 1);
CFE_ES_RunExceptionScan(0, NULL);
UtAssert_STUB_COUNT(CFE_PSP_Restart, 1);
ES_ResetUnitTest();
CFE_ES_Global.ResetDataPtr->ResetVars.ProcessorResetCount = 0;
CFE_ES_Global.ResetDataPtr->ResetVars.MaxProcessorResetCount = 1;
UT_SetDefaultReturnValue(UT_KEY(CFE_PSP_Exception_GetCount), 1);
CFE_ES_RunExceptionScan(0, NULL);
/* first time should do a processor restart (limit reached) */
UtAssert_STUB_COUNT(CFE_PSP_Restart, 1);
/* next time should do a poweron restart (limit reached) */
CFE_ES_RunExceptionScan(0, NULL);
UtAssert_STUB_COUNT(CFE_PSP_Restart, 2);
/* nominal for app restart - associate exception with a task ID */
ES_ResetUnitTest();
UT_SetDefaultReturnValue(UT_KEY(CFE_PSP_Exception_GetCount), 1);
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, &UtTaskRecPtr);
UT_ContextTask = CFE_ES_TaskId_ToOSAL(CFE_ES_TaskRecordGetID(UtTaskRecPtr));
UT_SetDataBuffer(UT_KEY(CFE_PSP_Exception_GetSummary), &UT_ContextTask, sizeof(UT_ContextTask), false);
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_APP_RUN;
UtAppRecPtr->StartParams.ExceptionAction = CFE_ES_ExceptionAction_RESTART_APP;
CFE_ES_RunExceptionScan(0, NULL);
/* should have changed AppControlRequest from RUN to SYS_RESTART,
* and the call to CFE_PSP_Restart should NOT increment */
UtAssert_INT32_EQ(UtAppRecPtr->ControlReq.AppControlRequest, CFE_ES_RunStatus_SYS_RESTART);
UtAssert_STUB_COUNT(CFE_PSP_Restart, 0);
/* repeat, but for a CORE app, which cannot be restarted */
ES_ResetUnitTest();
UT_SetDefaultReturnValue(UT_KEY(CFE_PSP_Exception_GetCount), 1);
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, &UtTaskRecPtr);
UT_ContextTask = CFE_ES_TaskId_ToOSAL(CFE_ES_TaskRecordGetID(UtTaskRecPtr));
UT_SetDataBuffer(UT_KEY(CFE_PSP_Exception_GetSummary), &UT_ContextTask, sizeof(UT_ContextTask), false);
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_APP_RUN;
UtAppRecPtr->StartParams.ExceptionAction = CFE_ES_ExceptionAction_RESTART_APP;
CFE_ES_RunExceptionScan(0, NULL);
UtAssert_STUB_COUNT(CFE_PSP_Restart, 1);
/* check failure of getting summary data */
UT_SetDefaultReturnValue(UT_KEY(CFE_PSP_Exception_GetSummary), CFE_PSP_NO_EXCEPTION_DATA);
CFE_ES_RunExceptionScan(0, NULL);
UtAssert_STUB_COUNT(CFE_PSP_Restart, 2);
/* Test clearing the log with a bad size in the verify command
* length call
*/
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, 0, UT_TPID_CFE_ES_CMD_CLEAR_ER_LOG_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_LEN_ERR_EID);
/* Test resetting and setting the max for the processor reset count */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.ResetPRCountCmd), UT_TPID_CFE_ES_CMD_RESET_PR_COUNT_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_RESET_PR_COUNT_EID);
/* Test setting the maximum processor reset count */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
CmdBuf.SetMaxPRCountCmd.Payload.MaxPRCount = 3;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.SetMaxPRCountCmd),
UT_TPID_CFE_ES_CMD_SET_MAX_PR_COUNT_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_SET_MAX_PR_COUNT_EID);
/* Test failed deletion of specified CDS */
ES_ResetUnitTest();
ES_UT_SetupSingleCDSRegistry("CFE_ES.CDS_NAME", ES_UT_CDS_BLOCK_SIZE, false, &UtCDSRegRecPtr);
UtCDSRegRecPtr->BlockOffset = 0xFFFFFFFF; /* Fails validation in PutBuf */
memset(&CmdBuf, 0, sizeof(CmdBuf));
strncpy(CmdBuf.DeleteCDSCmd.Payload.CdsName, "CFE_ES.CDS_NAME", sizeof(CmdBuf.DeleteCDSCmd.Payload.CdsName) - 1);
CmdBuf.DeleteCDSCmd.Payload.CdsName[sizeof(CmdBuf.DeleteCDSCmd.Payload.CdsName) - 1] = '\0';
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.DeleteCDSCmd), UT_TPID_CFE_ES_CMD_DELETE_CDS_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_CDS_DELETE_ERR_EID);
/* Test failed deletion of specified critical table CDS */
/* NOTE - reuse command from previous test */
ES_ResetUnitTest();
ES_UT_SetupSingleCDSRegistry("CFE_ES.CDS_NAME", ES_UT_CDS_BLOCK_SIZE, true, NULL);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.DeleteCDSCmd), UT_TPID_CFE_ES_CMD_DELETE_CDS_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_CDS_DELETE_TBL_ERR_EID);
/* Test successful deletion of a specified CDS */
ES_ResetUnitTest();
UT_SetCDSSize(0); /* defeats the "ReadFromCDS" and causes it to use the value here */
ES_UT_SetupSingleCDSRegistry("CFE_ES.CDS_NAME", ES_UT_CDS_BLOCK_SIZE, false, NULL);
/* Set up the block to read what we need to from the CDS */
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.DeleteCDSCmd), UT_TPID_CFE_ES_CMD_DELETE_CDS_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_CDS_DELETED_INFO_EID);
/* Test deletion of a specified CDS with the owning app being active */
ES_ResetUnitTest();
ES_UT_SetupSingleCDSRegistry("CFE_ES.CDS_NAME", ES_UT_CDS_BLOCK_SIZE, false, NULL);
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, "CFE_ES", NULL, NULL);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.DeleteCDSCmd), UT_TPID_CFE_ES_CMD_DELETE_CDS_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_CDS_OWNER_ACTIVE_EID);
/* Test deletion of a specified CDS with the name not found */
ES_ResetUnitTest();
ES_UT_SetupSingleCDSRegistry("CFE_ES.CDS_NAME", ES_UT_CDS_BLOCK_SIZE, false, &UtCDSRegRecPtr);
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, "CFE_BAD", NULL, NULL);
CFE_ES_CDSBlockRecordSetFree(UtCDSRegRecPtr);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.DeleteCDSCmd), UT_TPID_CFE_ES_CMD_DELETE_CDS_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_CDS_NAME_ERR_EID);
/* Test successful dump of CDS to file using the default dump file name */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.DumpCDSRegistryCmd),
UT_TPID_CFE_ES_CMD_DUMP_CDS_REGISTRY_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_CDS_REG_DUMP_INF_EID);
/* Test dumping of the CDS to a file with a bad file name */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
UT_SetDeferredRetcode(UT_KEY(CFE_FS_ParseInputFileNameEx), 1, CFE_FS_INVALID_PATH);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.DumpCDSRegistryCmd),
UT_TPID_CFE_ES_CMD_DUMP_CDS_REGISTRY_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_CREATING_CDS_DUMP_ERR_EID);
/* Test dumping of the CDS to a file with a bad FS write header */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
UT_SetDeferredRetcode(UT_KEY(CFE_FS_WriteHeader), 1, -1);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.DumpCDSRegistryCmd),
UT_TPID_CFE_ES_CMD_DUMP_CDS_REGISTRY_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_WRITE_CFE_HDR_ERR_EID);
/* Test dumping of the CDS to a file with an OS create failure */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
UT_SetDefaultReturnValue(UT_KEY(OS_OpenCreate), OS_ERROR);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.DumpCDSRegistryCmd),
UT_TPID_CFE_ES_CMD_DUMP_CDS_REGISTRY_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_CREATING_CDS_DUMP_ERR_EID);
/* Test dumping of the CDS to a file with an OS write failure */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
UT_SetDefaultReturnValue(UT_KEY(OS_write), OS_ERROR);
ES_UT_SetupSingleCDSRegistry("CFE_ES.CDS_NAME", ES_UT_CDS_BLOCK_SIZE, false, NULL);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.DumpCDSRegistryCmd),
UT_TPID_CFE_ES_CMD_DUMP_CDS_REGISTRY_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_CDS_DUMP_ERR_EID);
/* Test telemetry pool statistics retrieval with an invalid handle */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.SendMemPoolStatsCmd),
UT_TPID_CFE_ES_CMD_SEND_MEM_POOL_STATS_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_INVALID_POOL_HANDLE_ERR_EID);
/* Test successful telemetry pool statistics retrieval */
ES_ResetUnitTest();
ES_UT_SetupMemPoolId(&UtPoolRecPtr);
CmdBuf.SendMemPoolStatsCmd.Payload.PoolHandle = CFE_ES_MemPoolRecordGetID(UtPoolRecPtr);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.SendMemPoolStatsCmd),
UT_TPID_CFE_ES_CMD_SEND_MEM_POOL_STATS_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_TLM_POOL_STATS_INFO_EID);
/* Test the command pipe message process with an invalid command */
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.NoArgsCmd), UT_TPID_CFE_ES_CMD_INVALID_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_CC1_ERR_EID);
/* Test sending a no-op command with an invalid command length */
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, 0, UT_TPID_CFE_ES_CMD_NOOP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_LEN_ERR_EID);
/* Test sending a reset counters command with an invalid command length */
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, 0, UT_TPID_CFE_ES_CMD_RESET_COUNTERS_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_LEN_ERR_EID);
/* Test sending a cFE restart command with an invalid command length */
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, 0, UT_TPID_CFE_ES_CMD_RESTART_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_LEN_ERR_EID);
/* Test cFE restart with a power on reset */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
CmdBuf.RestartCmd.Payload.RestartType = CFE_PSP_RST_TYPE_POWERON;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.RestartCmd), UT_TPID_CFE_ES_CMD_RESTART_CC);
CFE_UtAssert_EVENTNOTSENT(CFE_ES_BOOT_ERR_EID);
/* Test sending a start application command with an invalid command
* length
*/
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, 0, UT_TPID_CFE_ES_CMD_START_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_LEN_ERR_EID);
/* Test start application command with a processor restart on application
* exception
*/
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
strncpy(CmdBuf.StartAppCmd.Payload.AppFileName, "filename", sizeof(CmdBuf.StartAppCmd.Payload.AppFileName) - 1);
CmdBuf.StartAppCmd.Payload.AppFileName[sizeof(CmdBuf.StartAppCmd.Payload.AppFileName) - 1] = '\0';
strncpy(CmdBuf.StartAppCmd.Payload.AppEntryPoint, "entrypoint",
sizeof(CmdBuf.StartAppCmd.Payload.AppEntryPoint) - 1);
CmdBuf.StartAppCmd.Payload.AppEntryPoint[sizeof(CmdBuf.StartAppCmd.Payload.AppEntryPoint) - 1] = '\0';
strncpy(CmdBuf.StartAppCmd.Payload.Application, "appName", sizeof(CmdBuf.StartAppCmd.Payload.Application) - 1);
CmdBuf.StartAppCmd.Payload.Application[sizeof(CmdBuf.StartAppCmd.Payload.Application) - 1] = '\0';
CmdBuf.StartAppCmd.Payload.ExceptionAction = CFE_ES_ExceptionAction_PROC_RESTART;
CmdBuf.StartAppCmd.Payload.Priority = 160;
CmdBuf.StartAppCmd.Payload.StackSize = CFE_ES_MEMOFFSET_C(CFE_PLATFORM_ES_DEFAULT_STACK_SIZE);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.StartAppCmd), UT_TPID_CFE_ES_CMD_START_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_START_INF_EID);
/* Test sending a stop application command with an invalid command
* length
*/
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, 0, UT_TPID_CFE_ES_CMD_STOP_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_LEN_ERR_EID);
/* Test sending a restart application command with an invalid command
* length
*/
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, 0, UT_TPID_CFE_ES_CMD_RESTART_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_LEN_ERR_EID);
/* Test sending a reload application command with an invalid command
* length
*/
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, 0, UT_TPID_CFE_ES_CMD_RELOAD_APP_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_LEN_ERR_EID);
/* Test sending a write request for a single application with an
* invalid command length
*/
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, 0, UT_TPID_CFE_ES_CMD_QUERY_ONE_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_LEN_ERR_EID);
/* Test sending a write request for all applications with an
* invalid command length
*/
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, 0, UT_TPID_CFE_ES_CMD_QUERY_ALL_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_LEN_ERR_EID);
/* Test sending a write request for all tasks with an
* invalid command length
*/
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, 0, UT_TPID_CFE_ES_CMD_QUERY_ALL_TASKS_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_LEN_ERR_EID);
/* Test sending a request to clear the system log with an
* invalid command length
*/
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, 0, UT_TPID_CFE_ES_CMD_CLEAR_SYSLOG_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_LEN_ERR_EID);
/* Test sending a request to overwrite the system log with an
* invalid command length
*/
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, 0, UT_TPID_CFE_ES_CMD_OVER_WRITE_SYSLOG_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_LEN_ERR_EID);
/* Test sending a request to write the system log with an
* invalid command length
*/
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, 0, UT_TPID_CFE_ES_CMD_WRITE_SYSLOG_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_LEN_ERR_EID);
/* Test successful overwriting of the system log using overwrite mode */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
CmdBuf.OverwriteSysLogCmd.Payload.Mode = CFE_ES_LogMode_OVERWRITE;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.OverwriteSysLogCmd),
UT_TPID_CFE_ES_CMD_OVER_WRITE_SYSLOG_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_SYSLOGMODE_EID);
/* Test sending a request to write the error log with an
* invalid command length
*/
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, 0, UT_TPID_CFE_ES_CMD_WRITE_ER_LOG_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_LEN_ERR_EID);
/* Test sending a request to reset the processor reset count with an
* invalid command length
*/
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, 0, UT_TPID_CFE_ES_CMD_RESET_PR_COUNT_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_LEN_ERR_EID);
/* Test sending a request to set the maximum processor reset count with
* an invalid command length
*/
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, 0, UT_TPID_CFE_ES_CMD_SET_MAX_PR_COUNT_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_LEN_ERR_EID);
/* Test sending a request to delete the CDS with an invalid command
* length
*/
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, 0, UT_TPID_CFE_ES_CMD_DELETE_CDS_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_LEN_ERR_EID);
/* Test sending a telemetry pool statistics retrieval command with an
* invalid command length
*/
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, 0, UT_TPID_CFE_ES_CMD_SEND_MEM_POOL_STATS_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_LEN_ERR_EID);
/* Test successful dump of CDS to file using a specified dump file name */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, "CFE_ES", NULL, NULL);
ES_UT_SetupSingleCDSRegistry("CFE_ES.CDS_NAME", ES_UT_CDS_BLOCK_SIZE, false, NULL);
strncpy(CmdBuf.DumpCDSRegistryCmd.Payload.DumpFilename, "DumpFile",
sizeof(CmdBuf.DumpCDSRegistryCmd.Payload.DumpFilename) - 1);
CmdBuf.DumpCDSRegistryCmd.Payload.DumpFilename[sizeof(CmdBuf.DumpCDSRegistryCmd.Payload.DumpFilename) - 1] = '\0';
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.DumpCDSRegistryCmd),
UT_TPID_CFE_ES_CMD_DUMP_CDS_REGISTRY_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_CDS_REG_DUMP_INF_EID);
} /* end TestTask */
void TestPerf(void)
{
union
{
CFE_MSG_Message_t Msg;
CFE_ES_StartPerfDataCmd_t PerfStartCmd;
CFE_ES_StopPerfDataCmd_t PerfStopCmd;
CFE_ES_SetPerfFilterMaskCmd_t PerfSetFilterMaskCmd;
CFE_ES_SetPerfTriggerMaskCmd_t PerfSetTrigMaskCmd;
} CmdBuf;
UtPrintf("Begin Test Performance Log");
CFE_ES_PerfData_t *Perf;
/*
** Set the pointer to the data area
*/
UT_GetDataBuffer(UT_KEY(CFE_PSP_GetResetArea), (void **)&ES_UT_PersistentResetData, NULL, NULL);
Perf = &ES_UT_PersistentResetData->Perf;
/* Test successful performance mask and value initialization */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, "CFE_ES", NULL, NULL);
Perf->MetaData.State = CFE_ES_PERF_MAX_STATES;
CFE_ES_SetupPerfVariables(CFE_PSP_RST_TYPE_PROCESSOR);
UtAssert_UINT32_EQ(Perf->MetaData.State, CFE_ES_PERF_IDLE);
/* Test successful performance data collection start in START
* trigger mode
*/
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
CmdBuf.PerfStartCmd.Payload.TriggerMode = CFE_ES_PERF_TRIGGER_START;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.PerfStartCmd), UT_TPID_CFE_ES_CMD_START_PERF_DATA_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_PERF_STARTCMD_EID);
/* Test successful performance data collection start in CENTER
* trigger mode
*/
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
CmdBuf.PerfStartCmd.Payload.TriggerMode = CFE_ES_PERF_TRIGGER_CENTER;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.PerfStartCmd), UT_TPID_CFE_ES_CMD_START_PERF_DATA_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_PERF_STARTCMD_EID);
/* Test successful performance data collection start in END
* trigger mode
*/
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
CmdBuf.PerfStartCmd.Payload.TriggerMode = CFE_ES_PERF_TRIGGER_END;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.PerfStartCmd), UT_TPID_CFE_ES_CMD_START_PERF_DATA_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_PERF_STARTCMD_EID);
/* Test performance data collection start with an invalid trigger mode
* (too high)
*/
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
CmdBuf.PerfStartCmd.Payload.TriggerMode = (CFE_ES_PERF_TRIGGER_END + 1);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.PerfStartCmd), UT_TPID_CFE_ES_CMD_START_PERF_DATA_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_PERF_STARTCMD_TRIG_ERR_EID);
/* Test performance data collection start with an invalid trigger mode
* (too low)
*/
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
CmdBuf.PerfStartCmd.Payload.TriggerMode = 0xffffffff;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.PerfStartCmd), UT_TPID_CFE_ES_CMD_START_PERF_DATA_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_PERF_STARTCMD_TRIG_ERR_EID);
/* Test performance data collection start with a file write in progress */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
/* clearing the BackgroundPerfDumpState will fully reset to initial state */
memset(&CFE_ES_Global.BackgroundPerfDumpState, 0, sizeof(CFE_ES_Global.BackgroundPerfDumpState));
CFE_ES_Global.BackgroundPerfDumpState.CurrentState = CFE_ES_PerfDumpState_INIT;
CmdBuf.PerfStartCmd.Payload.TriggerMode = CFE_ES_PERF_TRIGGER_START;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.PerfStartCmd), UT_TPID_CFE_ES_CMD_START_PERF_DATA_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_PERF_STARTCMD_ERR_EID);
/* Test performance data collection by sending another valid
* start command
*/
ES_ResetUnitTest();
memset(&CFE_ES_Global.BackgroundPerfDumpState, 0, sizeof(CFE_ES_Global.BackgroundPerfDumpState));
memset(&CmdBuf, 0, sizeof(CmdBuf));
CmdBuf.PerfStartCmd.Payload.TriggerMode = CFE_ES_PERF_TRIGGER_START;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.PerfStartCmd), UT_TPID_CFE_ES_CMD_START_PERF_DATA_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_PERF_STARTCMD_EID);
/* Test successful performance data collection stop */
ES_ResetUnitTest();
memset(&CFE_ES_Global.BackgroundPerfDumpState, 0, sizeof(CFE_ES_Global.BackgroundPerfDumpState));
memset(&CmdBuf, 0, sizeof(CmdBuf));
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.PerfStopCmd), UT_TPID_CFE_ES_CMD_STOP_PERF_DATA_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_PERF_STOPCMD_EID);
/* Test performance data collection stop with a file name validation issue */
ES_ResetUnitTest();
memset(&CFE_ES_Global.BackgroundPerfDumpState, 0, sizeof(CFE_ES_Global.BackgroundPerfDumpState));
memset(&CmdBuf, 0, sizeof(CmdBuf));
UT_SetDefaultReturnValue(UT_KEY(CFE_FS_ParseInputFileNameEx), CFE_FS_INVALID_PATH);
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.PerfStopCmd), UT_TPID_CFE_ES_CMD_STOP_PERF_DATA_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_PERF_LOG_ERR_EID);
/* Test successful performance data collection stop with a non-default
file name */
ES_ResetUnitTest();
/* clearing the BackgroundPerfDumpState will fully reset to initial state */
memset(&CFE_ES_Global.BackgroundPerfDumpState, 0, sizeof(CFE_ES_Global.BackgroundPerfDumpState));
strncpy(CmdBuf.PerfStopCmd.Payload.DataFileName, "filename", sizeof(CmdBuf.PerfStopCmd.Payload.DataFileName) - 1);
CmdBuf.PerfStopCmd.Payload.DataFileName[sizeof(CmdBuf.PerfStopCmd.Payload.DataFileName) - 1] = '\0';
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.PerfStopCmd), UT_TPID_CFE_ES_CMD_STOP_PERF_DATA_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_PERF_STOPCMD_EID);
/* Test performance data collection stop with a file write in progress */
ES_ResetUnitTest();
CFE_ES_Global.BackgroundPerfDumpState.CurrentState = CFE_ES_PerfDumpState_INIT;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.PerfStopCmd), UT_TPID_CFE_ES_CMD_STOP_PERF_DATA_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_PERF_STOPCMD_ERR2_EID);
/* Test performance filter mask command with out of range filter
mask value */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
CmdBuf.PerfSetFilterMaskCmd.Payload.FilterMaskNum = CFE_ES_PERF_32BIT_WORDS_IN_MASK;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.PerfSetFilterMaskCmd),
UT_TPID_CFE_ES_CMD_SET_PERF_FILTER_MASK_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_PERF_FILTMSKERR_EID);
/* Test successful performance filter mask command */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
CmdBuf.PerfSetFilterMaskCmd.Payload.FilterMaskNum = CFE_ES_PERF_32BIT_WORDS_IN_MASK / 2;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.PerfSetFilterMaskCmd),
UT_TPID_CFE_ES_CMD_SET_PERF_FILTER_MASK_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_PERF_FILTMSKCMD_EID);
/* Test successful performance filter mask command with minimum filter
mask value */
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
CmdBuf.PerfSetTrigMaskCmd.Payload.TriggerMaskNum = 0;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.PerfSetTrigMaskCmd),
UT_TPID_CFE_ES_CMD_SET_PERF_TRIGGER_MASK_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_PERF_TRIGMSKCMD_EID);
/* Test successful performance filter mask command with maximum filter
* mask value
*/
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
CmdBuf.PerfSetTrigMaskCmd.Payload.TriggerMaskNum = CFE_ES_PERF_32BIT_WORDS_IN_MASK - 1;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.PerfSetTrigMaskCmd),
UT_TPID_CFE_ES_CMD_SET_PERF_TRIGGER_MASK_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_PERF_TRIGMSKCMD_EID);
/* Test successful performance filter mask command with a greater than the
* maximum filter mask value
*/
ES_ResetUnitTest();
memset(&CmdBuf, 0, sizeof(CmdBuf));
CmdBuf.PerfSetTrigMaskCmd.Payload.TriggerMaskNum = CFE_ES_PERF_32BIT_WORDS_IN_MASK + 1;
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, sizeof(CmdBuf.PerfSetTrigMaskCmd),
UT_TPID_CFE_ES_CMD_SET_PERF_TRIGGER_MASK_CC);
CFE_UtAssert_EVENTSENT(CFE_ES_PERF_TRIGMSKERR_EID);
/* Test successful addition of a new entry to the performance log */
ES_ResetUnitTest();
Perf->MetaData.State = CFE_ES_PERF_WAITING_FOR_TRIGGER;
Perf->MetaData.TriggerCount = CFE_PLATFORM_ES_PERF_DATA_BUFFER_SIZE + 1;
Perf->MetaData.InvalidMarkerReported = false;
Perf->MetaData.DataEnd = CFE_PLATFORM_ES_PERF_DATA_BUFFER_SIZE + 1;
CFE_ES_PerfLogAdd(CFE_MISSION_ES_PERF_MAX_IDS, 0);
UtAssert_UINT32_EQ(Perf->MetaData.InvalidMarkerReported, true);
/* Test addition of a new entry to the performance log with START
* trigger mode
*/
ES_ResetUnitTest();
Perf->MetaData.InvalidMarkerReported = true;
Perf->MetaData.Mode = CFE_ES_PERF_TRIGGER_START;
Perf->MetaData.DataCount = CFE_PLATFORM_ES_PERF_DATA_BUFFER_SIZE + 1;
Perf->MetaData.TriggerMask[0] = 0xFFFF;
CFE_ES_PerfLogAdd(1, 0);
UtAssert_UINT32_EQ(Perf->MetaData.Mode, CFE_ES_PERF_TRIGGER_START);
UtAssert_UINT32_EQ(Perf->MetaData.State, CFE_ES_PERF_IDLE);
/* Test addition of a new entry to the performance log with CENTER
* trigger mode
*/
ES_ResetUnitTest();
Perf->MetaData.State = CFE_ES_PERF_TRIGGERED;
Perf->MetaData.Mode = CFE_ES_PERF_TRIGGER_CENTER;
Perf->MetaData.TriggerCount = CFE_PLATFORM_ES_PERF_DATA_BUFFER_SIZE / 2 + 1;
CFE_ES_PerfLogAdd(1, 0);
UtAssert_UINT32_EQ(Perf->MetaData.Mode, CFE_ES_PERF_TRIGGER_CENTER);
UtAssert_UINT32_EQ(Perf->MetaData.State, CFE_ES_PERF_IDLE);
/* Test addition of a new entry to the performance log with END
* trigger mode
*/
ES_ResetUnitTest();
Perf->MetaData.State = CFE_ES_PERF_TRIGGERED;
Perf->MetaData.Mode = CFE_ES_PERF_TRIGGER_END;
CFE_ES_PerfLogAdd(1, 0);
UtAssert_UINT32_EQ(Perf->MetaData.Mode, CFE_ES_PERF_TRIGGER_END);
UtAssert_UINT32_EQ(Perf->MetaData.State, CFE_ES_PERF_IDLE);
/* Test addition of a new entry to the performance log with an invalid
* marker after an invalid marker has already been reported
*/
ES_ResetUnitTest();
Perf->MetaData.State = CFE_ES_PERF_TRIGGERED;
Perf->MetaData.InvalidMarkerReported = 2;
CFE_ES_PerfLogAdd(CFE_MISSION_ES_PERF_MAX_IDS + 1, 0);
UtAssert_UINT32_EQ(Perf->MetaData.InvalidMarkerReported, 2);
/* Test addition of a new entry to the performance log with a marker that
* is not in the filter mask
*/
ES_ResetUnitTest();
Perf->MetaData.State = CFE_ES_PERF_TRIGGERED;
Perf->MetaData.FilterMask[0] = 0x0;
Perf->MetaData.DataEnd = 0;
CFE_ES_PerfLogAdd(0x1, 0);
UtAssert_UINT32_EQ(Perf->MetaData.DataEnd, 0);
/* Test addition of a new entry to the performance log with the data count
* below the maximum allowed
*/
ES_ResetUnitTest();
Perf->MetaData.State = CFE_ES_PERF_WAITING_FOR_TRIGGER;
Perf->MetaData.DataCount = 0;
Perf->MetaData.FilterMask[0] = 0xffff;
CFE_ES_PerfLogAdd(0x1, 0);
UtAssert_UINT32_EQ(Perf->MetaData.DataCount, 1);
/* Test addition of a new entry to the performance log with a marker that
* is not in the trigger mask
*/
ES_ResetUnitTest();
Perf->MetaData.State = CFE_ES_PERF_WAITING_FOR_TRIGGER;
Perf->MetaData.TriggerMask[0] = 0x0;
CFE_ES_PerfLogAdd(0x1, 0);
UtAssert_UINT32_EQ(Perf->MetaData.State, CFE_ES_PERF_WAITING_FOR_TRIGGER);
/* Test addition of a new entry to the performance log with a start
* trigger mode and the trigger count is less the buffer size
*/
ES_ResetUnitTest();
Perf->MetaData.TriggerCount = 0;
Perf->MetaData.State = CFE_ES_PERF_TRIGGERED;
Perf->MetaData.Mode = CFE_ES_PERF_TRIGGER_START;
Perf->MetaData.TriggerMask[0] = 0xffff;
CFE_ES_PerfLogAdd(0x1, 0);
UtAssert_UINT32_EQ(Perf->MetaData.TriggerCount, 1);
/* Test addition of a new entry to the performance log with a center
* trigger mode and the trigger count is less than half the buffer size
*/
ES_ResetUnitTest();
Perf->MetaData.TriggerCount = CFE_PLATFORM_ES_PERF_DATA_BUFFER_SIZE / 2 - 2;
Perf->MetaData.State = CFE_ES_PERF_TRIGGERED;
Perf->MetaData.Mode = CFE_ES_PERF_TRIGGER_CENTER;
CFE_ES_PerfLogAdd(0x1, 0);
UtAssert_UINT32_EQ(Perf->MetaData.State, CFE_ES_PERF_TRIGGERED);
/* Test addition of a new entry to the performance log with an invalid
* trigger mode
*/
ES_ResetUnitTest();
Perf->MetaData.TriggerCount = 0;
Perf->MetaData.State = CFE_ES_PERF_TRIGGERED;
Perf->MetaData.Mode = -1;
CFE_ES_PerfLogAdd(0x1, 0);
UtAssert_UINT32_EQ(Perf->MetaData.State, CFE_ES_PERF_TRIGGERED);
/* Test performance data collection start with an invalid message length */
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, 0, UT_TPID_CFE_ES_CMD_START_PERF_DATA_CC);
CFE_UtAssert_EVENTNOTSENT(CFE_ES_PERF_STARTCMD_EID);
/* Test performance data collection stop with an invalid message length */
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, 0, UT_TPID_CFE_ES_CMD_STOP_PERF_DATA_CC);
CFE_UtAssert_EVENTNOTSENT(CFE_ES_PERF_STOPCMD_EID);
/* Test performance data filer mask with an invalid message length */
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, 0, UT_TPID_CFE_ES_CMD_SET_PERF_FILTER_MASK_CC);
CFE_UtAssert_EVENTNOTSENT(CFE_ES_PERF_FILTMSKCMD_EID);
/* Test performance data trigger mask with an invalid message length */
ES_ResetUnitTest();
UT_CallTaskPipe(CFE_ES_TaskPipe, &CmdBuf.Msg, 0, UT_TPID_CFE_ES_CMD_SET_PERF_TRIGGER_MASK_CC);
CFE_UtAssert_EVENTNOTSENT(CFE_ES_PERF_TRIGMSKCMD_EID);
/* Test perf log dump state machine */
/* Nominal call 1 - should go through up to the DELAY state */
ES_ResetUnitTest();
memset(&CFE_ES_Global.BackgroundPerfDumpState, 0, sizeof(CFE_ES_Global.BackgroundPerfDumpState));
CFE_ES_Global.BackgroundPerfDumpState.PendingState = CFE_ES_PerfDumpState_INIT;
CFE_ES_RunPerfLogDump(1000, &CFE_ES_Global.BackgroundPerfDumpState);
UtAssert_UINT32_EQ(CFE_ES_Global.BackgroundPerfDumpState.CurrentState, CFE_ES_PerfDumpState_DELAY);
/* Nominal call 2 - should go through up to the remainder of states, back to IDLE */
CFE_ES_RunPerfLogDump(1000, &CFE_ES_Global.BackgroundPerfDumpState);
UtAssert_UINT32_EQ(CFE_ES_Global.BackgroundPerfDumpState.CurrentState, CFE_ES_PerfDumpState_IDLE);
/* Test a failure to open the output file */
/* This should go immediately back to idle, and generate CFE_ES_PERF_LOG_ERR_EID */
ES_ResetUnitTest();
memset(&CFE_ES_Global.BackgroundPerfDumpState, 0, sizeof(CFE_ES_Global.BackgroundPerfDumpState));
CFE_ES_Global.BackgroundPerfDumpState.PendingState = CFE_ES_PerfDumpState_INIT;
UT_SetDefaultReturnValue(UT_KEY(OS_OpenCreate), -10);
CFE_ES_RunPerfLogDump(1000, &CFE_ES_Global.BackgroundPerfDumpState);
UtAssert_UINT32_EQ(CFE_ES_Global.BackgroundPerfDumpState.CurrentState, CFE_ES_PerfDumpState_IDLE);
CFE_UtAssert_EVENTSENT(CFE_ES_PERF_LOG_ERR_EID);
/* Test a failure to write to the output file */
ES_ResetUnitTest();
memset(&CFE_ES_Global.BackgroundPerfDumpState, 0, sizeof(CFE_ES_Global.BackgroundPerfDumpState));
UT_SetDefaultReturnValue(UT_KEY(OS_write), -10);
CFE_ES_Global.BackgroundPerfDumpState.PendingState = CFE_ES_PerfDumpState_INIT;
CFE_ES_RunPerfLogDump(1000, &CFE_ES_Global.BackgroundPerfDumpState);
UtAssert_UINT32_EQ(CFE_ES_Global.BackgroundPerfDumpState.CurrentState, CFE_ES_PerfDumpState_DELAY);
/* This will trigger the OS_write() failure, which should go through up to the remainder of states, back to IDLE */
CFE_ES_RunPerfLogDump(1000, &CFE_ES_Global.BackgroundPerfDumpState);
UtAssert_UINT32_EQ(CFE_ES_Global.BackgroundPerfDumpState.CurrentState, CFE_ES_PerfDumpState_IDLE);
CFE_UtAssert_EVENTSENT(CFE_ES_FILEWRITE_ERR_EID);
/* Test the ability of the file writer to handle the "wrap around" from the end of
* the perflog buffer back to the beginning. Just need to set up the metadata
* so that the writing position is toward the end of the buffer.
*/
ES_ResetUnitTest();
memset(&CFE_ES_Global.BackgroundPerfDumpState, 0, sizeof(CFE_ES_Global.BackgroundPerfDumpState));
OS_OpenCreate(&CFE_ES_Global.BackgroundPerfDumpState.FileDesc, "UT", 0, OS_WRITE_ONLY);
CFE_ES_Global.BackgroundPerfDumpState.CurrentState = CFE_ES_PerfDumpState_WRITE_PERF_ENTRIES;
CFE_ES_Global.BackgroundPerfDumpState.PendingState = CFE_ES_PerfDumpState_WRITE_PERF_ENTRIES;
CFE_ES_Global.BackgroundPerfDumpState.DataPos = CFE_PLATFORM_ES_PERF_DATA_BUFFER_SIZE - 2;
CFE_ES_Global.BackgroundPerfDumpState.StateCounter = 4;
CFE_ES_RunPerfLogDump(1000, &CFE_ES_Global.BackgroundPerfDumpState);
/* check that the wraparound occurred */
UtAssert_UINT32_EQ(CFE_ES_Global.BackgroundPerfDumpState.DataPos, 2);
/* should have written 4 entries to the log */
UtAssert_UINT32_EQ(CFE_ES_Global.BackgroundPerfDumpState.FileSize, sizeof(CFE_ES_PerfDataEntry_t) * 4);
/* Confirm that the "CFE_ES_GetPerfLogDumpRemaining" function works.
* This requires that the state is not idle, in order to get nonzero results.
*/
ES_ResetUnitTest();
memset(&CFE_ES_Global.BackgroundPerfDumpState, 0, sizeof(CFE_ES_Global.BackgroundPerfDumpState));
OS_OpenCreate(&CFE_ES_Global.BackgroundPerfDumpState.FileDesc, "UT", 0, OS_WRITE_ONLY);
CFE_ES_Global.BackgroundPerfDumpState.CurrentState = CFE_ES_PerfDumpState_WRITE_PERF_METADATA;
CFE_ES_Global.BackgroundPerfDumpState.StateCounter = 10;
Perf->MetaData.DataCount = 100;
/* in states other than WRITE_PERF_ENTRIES, it should report the full size of the log */
UtAssert_UINT32_EQ(CFE_ES_GetPerfLogDumpRemaining(), 100);
/* in WRITE_PERF_ENTRIES, it should report the StateCounter */
CFE_ES_Global.BackgroundPerfDumpState.CurrentState = CFE_ES_PerfDumpState_WRITE_PERF_ENTRIES;
UtAssert_UINT32_EQ(CFE_ES_GetPerfLogDumpRemaining(), 10);
}
void TestAPI(void)
{
osal_id_t TestObjId;
char AppName[OS_MAX_API_NAME + 12];
uint32 StackBuf[8];
uint8 Data[12];
uint32 ResetType;
CFE_ES_AppId_t AppId;
CFE_ES_TaskId_t TaskId;
uint32 RunStatus;
CFE_ES_TaskInfo_t TaskInfo;
CFE_ES_AppInfo_t AppInfo;
CFE_ES_AppRecord_t * UtAppRecPtr;
CFE_ES_TaskRecord_t *UtTaskRecPtr;
UtPrintf("Begin Test API");
/* Test resetting the cFE with a processor reset */
ES_ResetUnitTest();
ResetType = CFE_PSP_RST_TYPE_PROCESSOR;
CFE_ES_Global.ResetDataPtr->ResetVars.ProcessorResetCount =
CFE_ES_Global.ResetDataPtr->ResetVars.MaxProcessorResetCount - 1;
CFE_ES_ResetCFE(ResetType);
CFE_ES_Global.ResetDataPtr->ResetVars.ProcessorResetCount =
CFE_ES_Global.ResetDataPtr->ResetVars.MaxProcessorResetCount;
UtAssert_INT32_EQ(CFE_ES_ResetCFE(ResetType), CFE_ES_NOT_IMPLEMENTED);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_POR_MAX_PROC_RESETS]);
/* Test getting the reset type using a valid pointer and a null pointer */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_GetResetType(&ResetType), CFE_PSP_RST_TYPE_PROCESSOR);
UtAssert_INT32_EQ(CFE_ES_GetResetType(NULL), CFE_PSP_RST_TYPE_PROCESSOR);
/* Test resetting the cFE with a power on reset */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_ResetCFE(CFE_PSP_RST_TYPE_POWERON), CFE_ES_NOT_IMPLEMENTED);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_POR_COMMANDED]);
/* Test resetting the cFE with an invalid argument */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_ResetCFE(CFE_PSP_RST_TYPE_POWERON + 3), CFE_ES_BAD_ARGUMENT);
/* Test restarting an app that doesn't exist */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_STOPPED, NULL, &UtAppRecPtr, NULL);
AppId = CFE_ES_APPID_C(
ES_UT_MakeAppIdForIndex(CFE_PLATFORM_ES_MAX_APPLICATIONS - 1)); /* Should be within range, but not used */
UtAssert_INT32_EQ(CFE_ES_RestartApp(AppId), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test restarting an app with an ID out of range (high) */
ES_ResetUnitTest();
AppId = CFE_ES_APPID_C(ES_UT_MakeAppIdForIndex(99999));
UtAssert_INT32_EQ(CFE_ES_RestartApp(AppId), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test CFE_ES_ReloadApp with bad AppID argument */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_ReloadApp(CFE_ES_APPID_UNDEFINED, "filename"), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test reloading a core app */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
UtAssert_INT32_EQ(CFE_ES_ReloadApp(AppId, "filename"), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test reloading an app that is currently not running */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_STOPPED, NULL, &UtAppRecPtr, NULL);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
UtAssert_INT32_EQ(CFE_ES_ReloadApp(AppId, "filename"), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test success initiating an app reload */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
UtAssert_INT32_EQ(CFE_ES_ReloadApp(AppId, "filename"), CFE_SUCCESS);
/* Test Reload app: file doesn't exist*/
ES_ResetUnitTest();
UT_SetDefaultReturnValue(UT_KEY(OS_stat), OS_ERROR);
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
UtAssert_INT32_EQ(CFE_ES_ReloadApp(AppId, "missingfile"), CFE_ES_FILE_IO_ERR);
/* Test deleting an app that doesn't exist */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_STOPPED, NULL, &UtAppRecPtr, NULL);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
UtAssert_INT32_EQ(CFE_ES_DeleteApp(AppId), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test exiting an app with an init error */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_STOPPED, NULL, &UtAppRecPtr, NULL);
CFE_ES_ExitApp(CFE_ES_RunStatus_CORE_APP_INIT_ERROR);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_CORE_INIT]);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_POR_MAX_PROC_RESETS]);
/* Test exiting an app with a runtime error */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_STOPPED, NULL, &UtAppRecPtr, NULL);
CFE_ES_ExitApp(CFE_ES_RunStatus_CORE_APP_RUNTIME_ERROR);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_CORE_RUNTIME]);
/* Test exiting an app with an exit error */
/* Note - this exit code of 1000 is invalid, which causes
* an extra message to be logged in syslog about this. This
* should also be stored in the AppControlRequest as APP_ERROR. */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_STOPPED, "UT", &UtAppRecPtr, NULL);
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_APP_RUN;
CFE_ES_ExitApp(1000);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_CORE_APP_EXIT]);
UtAssert_UINT32_EQ(UtAppRecPtr->ControlReq.AppControlRequest, CFE_ES_RunStatus_APP_ERROR);
#if 0
/* Can't cover this path since it contains a while(1) (i.e.,
* infinite) loop
*/
OS_TaskCreate(&TestObjId, "UT", NULL, NULL, 0, 0, 0);
Id = ES_UT_OSALID_TO_ARRAYIDX(TestObjId);
CFE_ES_TaskRecordSetUsed(TaskRecPtr);
TaskRecPtr->AppId = Id;
AppRecPtr->Type = CFE_ES_AppType_EXTERNAL;
AppRecPtr->AppState = CFE_ES_AppState_RUNNING;
CFE_ES_ExitApp(CFE_ES_RunStatus_CORE_APP_RUNTIME_ERROR);
#endif
/* Test successful run loop app run request */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
RunStatus = CFE_ES_RunStatus_APP_RUN;
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_APP_RUN;
CFE_UtAssert_TRUE(CFE_ES_RunLoop(&RunStatus));
/* Test successful run loop app stop request */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
RunStatus = CFE_ES_RunStatus_APP_RUN;
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_APP_EXIT;
CFE_UtAssert_FALSE(CFE_ES_RunLoop(&RunStatus));
/* Test successful run loop app exit request */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
RunStatus = CFE_ES_RunStatus_APP_EXIT;
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_APP_EXIT;
CFE_UtAssert_FALSE(CFE_ES_RunLoop(&RunStatus));
/* Test run loop with bad app ID */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, &UtTaskRecPtr);
RunStatus = CFE_ES_RunStatus_APP_RUN;
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_APP_RUN;
CFE_ES_TaskRecordSetFree(UtTaskRecPtr); /* make it so task ID is bad */
CFE_UtAssert_FALSE(CFE_ES_RunLoop(&RunStatus));
/* Test run loop with an invalid run status */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
RunStatus = 1000;
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_APP_EXIT;
CFE_UtAssert_FALSE(CFE_ES_RunLoop(&RunStatus));
/* Test run loop with a NULL run status */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_APP_RUN;
CFE_UtAssert_TRUE(CFE_ES_RunLoop(NULL));
/* Test run loop with startup sync code */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_LATE_INIT, NULL, &UtAppRecPtr, NULL);
RunStatus = CFE_ES_RunStatus_APP_RUN;
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_APP_RUN;
CFE_UtAssert_TRUE(CFE_ES_RunLoop(&RunStatus));
UtAssert_UINT32_EQ(UtAppRecPtr->AppState, CFE_ES_AppState_RUNNING);
/* Test getting the cFE application and task ID by context */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, "UT", NULL, NULL);
CFE_UtAssert_SUCCESS(CFE_ES_GetAppID(&AppId));
CFE_UtAssert_SUCCESS(CFE_ES_GetTaskID(&TaskId));
/* Test CFE_ES_GetAppID error with null pointer parameter */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_GetAppID(NULL), CFE_ES_BAD_ARGUMENT);
/* Test CFE_ES_GetAppIDByName error with null AppID pointer and valid name */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_GetAppIDByName(NULL, "UT"), CFE_ES_BAD_ARGUMENT);
/* Test CFE_ES_GetAppIDByName error with valid AppID and NULL name */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, "UT", NULL, NULL);
UtAssert_INT32_EQ(CFE_ES_GetAppIDByName(&AppId, NULL), CFE_ES_BAD_ARGUMENT);
/* Test getting the app name with a bad app ID */
ES_ResetUnitTest();
AppId = CFE_ES_APPID_C(ES_UT_MakeAppIdForIndex(99999));
UtAssert_INT32_EQ(CFE_ES_GetAppName(AppName, AppId, sizeof(AppName)), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test getting the app name with that app ID out of range */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, "UT", NULL, NULL);
AppId = CFE_ES_APPID_C(ES_UT_MakeAppIdForIndex(99999));
UtAssert_INT32_EQ(CFE_ES_GetAppName(AppName, AppId, sizeof(AppName)), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test successfully getting the app name using the app ID */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, "UT", &UtAppRecPtr, NULL);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr);
CFE_UtAssert_SUCCESS(CFE_ES_GetAppName(AppName, AppId, sizeof(AppName)));
/* Test getting task information using the task ID - NULL buffer */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, &UtTaskRecPtr);
TaskId = CFE_ES_TaskRecordGetID(UtTaskRecPtr);
UtAssert_INT32_EQ(CFE_ES_GetTaskInfo(NULL, TaskId), CFE_ES_BAD_ARGUMENT);
/* Test getting task information using the task ID - bad task ID */
UT_SetDefaultReturnValue(UT_KEY(OS_ObjectIdToArrayIndex), OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_GetTaskInfo(&TaskInfo, TaskId), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test getting task information using the task ID */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, &UtTaskRecPtr);
TaskId = CFE_ES_TaskRecordGetID(UtTaskRecPtr);
UtAppRecPtr->AppState = CFE_ES_AppState_RUNNING;
CFE_UtAssert_SUCCESS(CFE_ES_GetTaskInfo(&TaskInfo, TaskId));
/* Test getting task information using the task ID with parent inactive */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, "UT", &UtAppRecPtr, &UtTaskRecPtr);
TaskId = CFE_ES_TaskRecordGetID(UtTaskRecPtr);
CFE_ES_AppRecordSetFree(UtAppRecPtr);
UtAssert_INT32_EQ(CFE_ES_GetTaskInfo(&TaskInfo, TaskId), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test getting task information using the task ID with task inactive */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, "UT", NULL, &UtTaskRecPtr);
TaskId = CFE_ES_TaskRecordGetID(UtTaskRecPtr);
CFE_ES_TaskRecordSetFree(UtTaskRecPtr);
UtAssert_INT32_EQ(CFE_ES_GetTaskInfo(&TaskInfo, TaskId), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test getting task information using the task ID with invalid task ID */
ES_ResetUnitTest();
TaskId = CFE_ES_TASKID_UNDEFINED;
UtAssert_INT32_EQ(CFE_ES_GetTaskInfo(&TaskInfo, TaskId), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test creating a child task with a bad app ID */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_CreateChildTask(&TaskId, "TaskName", TestAPI, StackBuf, sizeof(StackBuf), 400, 0),
CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test creating a child task with an OS task create failure */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, NULL, NULL);
UT_SetDefaultReturnValue(UT_KEY(OS_TaskCreate), OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_CreateChildTask(&TaskId, "TaskName", TestAPI, StackBuf, sizeof(StackBuf), 400, 0),
CFE_STATUS_EXTERNAL_RESOURCE_FAIL);
/* Test creating a child task with a null task ID */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_CreateChildTask(NULL, "TaskName", TestAPI, StackBuf, sizeof(StackBuf), 400, 0),
CFE_ES_BAD_ARGUMENT);
/* Test creating a child task with a null task name */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_CreateChildTask(&TaskId, NULL, TestAPI, StackBuf, sizeof(StackBuf), 400, 0),
CFE_ES_BAD_ARGUMENT);
/* Test creating a child task with a null task ID and name */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_CreateChildTask(NULL, NULL, TestAPI, StackBuf, sizeof(StackBuf), 400, 0),
CFE_ES_BAD_ARGUMENT);
/* Test creating a child task with a null function pointer */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_CreateChildTask(&TaskId, "TaskName", NULL, StackBuf, sizeof(StackBuf), 2, 0),
CFE_ES_BAD_ARGUMENT);
/* Test creating a child task within a child task */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
ES_UT_SetupChildTaskId(UtAppRecPtr, NULL, &UtTaskRecPtr);
TestObjId = CFE_ES_TaskId_ToOSAL(CFE_ES_TaskRecordGetID(UtTaskRecPtr));
UT_SetDefaultReturnValue(UT_KEY(OS_TaskGetId), OS_ObjectIdToInteger(TestObjId)); /* Set context to that of child */
UtAssert_INT32_EQ(CFE_ES_CreateChildTask(&TaskId, "TaskName", TestAPI, StackBuf, sizeof(StackBuf), 400, 0),
CFE_ES_ERR_CHILD_TASK_CREATE);
/* Test successfully creating a child task */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
CFE_UtAssert_SUCCESS(CFE_ES_CreateChildTask(&TaskId, "TaskName", TestAPI, StackBuf, sizeof(StackBuf), 400, 0));
/* Test common entry point */
ES_ResetUnitTest();
/*
* Without no app/task set up the entry point will not be found.
* There is no return value to check here, it just will not do anything.
*/
CFE_ES_TaskEntryPoint();
/* Now set up an app+task */
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, &UtTaskRecPtr);
/* Test with app/task set up but no entry point defined */
CFE_ES_TaskEntryPoint();
/* Finally set entry point, nominal mode */
UtTaskRecPtr->EntryFunc = ES_UT_TaskFunction;
CFE_ES_TaskEntryPoint();
UtAssert_STUB_COUNT(ES_UT_TaskFunction, 1);
/* Test deleting a child task when task is not active/valid */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, "UT", NULL, &UtTaskRecPtr);
TaskId = CFE_ES_TaskRecordGetID(UtTaskRecPtr);
UtTaskRecPtr->TaskId = CFE_ES_TASKID_UNDEFINED; /* UtTaskRecPtr->TaskId shouldn't match the Child Task ID */
UtAssert_INT32_EQ(CFE_ES_DeleteChildTask(TaskId), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test deleting a child task using a main task's ID */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, "UT", NULL, &UtTaskRecPtr);
TaskId = CFE_ES_TaskRecordGetID(UtTaskRecPtr);
UtAssert_INT32_EQ(CFE_ES_DeleteChildTask(TaskId), CFE_ES_ERR_CHILD_TASK_DELETE_MAIN_TASK);
/* Test deleting a child task with an invalid task ID */
UT_SetDefaultReturnValue(UT_KEY(OS_ObjectIdToArrayIndex), OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_DeleteChildTask(TaskId), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test successfully deleting a child task */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, "UT", &UtAppRecPtr, NULL);
ES_UT_SetupChildTaskId(UtAppRecPtr, NULL, &UtTaskRecPtr);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr); /* the app ID */
TaskId = CFE_ES_TaskRecordGetID(UtTaskRecPtr); /* the child task ID */
CFE_UtAssert_SUCCESS(CFE_ES_GetAppInfo(&AppInfo, AppId));
UtAssert_UINT32_EQ(AppInfo.NumOfChildTasks, 1);
CFE_UtAssert_SUCCESS(CFE_ES_DeleteChildTask(TaskId));
CFE_UtAssert_SUCCESS(CFE_ES_GetAppInfo(&AppInfo, AppId));
UtAssert_UINT32_EQ(AppInfo.NumOfChildTasks, 0);
/* Test deleting a child task with an OS task delete failure */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
ES_UT_SetupChildTaskId(UtAppRecPtr, NULL, &UtTaskRecPtr);
AppId = CFE_ES_AppRecordGetID(UtAppRecPtr); /* the app ID */
TaskId = CFE_ES_TaskRecordGetID(UtTaskRecPtr); /* the child task ID */
UT_SetDefaultReturnValue(UT_KEY(OS_TaskDelete), OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_DeleteChildTask(TaskId), CFE_ES_ERR_CHILD_TASK_DELETE);
/* Test deleting a child task with the task ID out of range */
ES_ResetUnitTest();
TaskId = CFE_ES_TASKID_UNDEFINED;
UtAssert_INT32_EQ(CFE_ES_DeleteChildTask(TaskId), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test successfully exiting a child task */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
ES_UT_SetupChildTaskId(UtAppRecPtr, NULL, &UtTaskRecPtr);
TestObjId = CFE_ES_TaskId_ToOSAL(CFE_ES_TaskRecordGetID(UtTaskRecPtr));
UT_SetDefaultReturnValue(UT_KEY(OS_TaskGetId), OS_ObjectIdToInteger(TestObjId)); /* Set context to that of child */
CFE_ES_ExitChildTask();
UtAssert_STUB_COUNT(OS_TaskExit, 1);
/* Test exiting a child task within an app main task */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, NULL, &UtAppRecPtr, NULL);
ES_UT_SetupChildTaskId(UtAppRecPtr, NULL, &UtTaskRecPtr);
CFE_ES_ExitChildTask();
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_CANNOT_CALL_APP_MAIN]);
/* Test exiting a child task with an error retrieving the app ID */
ES_ResetUnitTest();
CFE_ES_ExitChildTask();
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_TASKEXIT_BAD_CONTEXT]);
/* Test successfully adding a time-stamped message to the system log that
* must be truncated
*/
ES_ResetUnitTest();
CFE_ES_Global.ResetDataPtr->SystemLogWriteIdx = CFE_PLATFORM_ES_SYSTEM_LOG_SIZE - CFE_TIME_PRINTED_STRING_SIZE - 4;
CFE_ES_Global.ResetDataPtr->SystemLogEndIdx = CFE_ES_Global.ResetDataPtr->SystemLogWriteIdx;
CFE_ES_Global.ResetDataPtr->SystemLogMode = CFE_ES_LogMode_DISCARD;
UtAssert_INT32_EQ(CFE_ES_SysLogWrite_Unsync("SysLogText This message should be truncated"),
CFE_ES_ERR_SYS_LOG_TRUNCATED);
/* Reset the system log index to prevent an overflow in later tests */
CFE_ES_Global.ResetDataPtr->SystemLogWriteIdx = 0;
CFE_ES_Global.ResetDataPtr->SystemLogEndIdx = 0;
/* Test calculating a CRC on a range of memory using CRC type 8
* NOTE: This capability is not currently implemented in cFE
*/
memset(Data, 1, sizeof(Data));
ES_ResetUnitTest();
UtAssert_UINT32_EQ(CFE_ES_CalculateCRC(&Data, 12, 345353, CFE_MISSION_ES_CRC_8), 0);
/* Test calculating a CRC on a range of memory using CRC type 16 */
ES_ResetUnitTest();
UtAssert_UINT32_EQ(CFE_ES_CalculateCRC(&Data, 12, 345353, CFE_MISSION_ES_CRC_16), 2688);
/*
* CRC memory read failure test case removed in #322 -
* deprecated CFE_PSP_MemRead8, now the FSW code does a direct read
* which has no failure path.
*/
/* Test calculating a CRC on a range of memory using CRC type 32
* NOTE: This capability is not currently implemented in cFE
*/
ES_ResetUnitTest();
UtAssert_UINT32_EQ(CFE_ES_CalculateCRC(&Data, 12, 345353, CFE_MISSION_ES_CRC_32), 0);
/* Test calculating a CRC on a range of memory using an invalid CRC type
*/
ES_ResetUnitTest();
UtAssert_UINT32_EQ(CFE_ES_CalculateCRC(&Data, 12, 345353, -1), 0);
/* Test shared mutex take with a take error */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, "UT", NULL, NULL);
UT_SetDeferredRetcode(UT_KEY(OS_MutSemTake), 1, -1);
CFE_ES_LockSharedData(__func__, 12345);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_MUTEX_TAKE]);
/* Test shared mutex release with a release error */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, "UT", NULL, NULL);
UT_SetDeferredRetcode(UT_KEY(OS_MutSemGive), 1, -1);
CFE_ES_UnlockSharedData(__func__, 98765);
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_MUTEX_GIVE]);
/* Test waiting for apps to initialize before continuing; transition from
* initializing to running
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_EARLY_INIT, "UT", &UtAppRecPtr, NULL);
CFE_ES_Global.SystemState = CFE_ES_SystemState_OPERATIONAL;
CFE_ES_WaitForStartupSync(0);
UtAssert_INT32_EQ(UtAppRecPtr->AppState, CFE_ES_AppState_RUNNING);
/* Test waiting for apps to initialize before continuing with the semaphore
* already released
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, "UT", &UtAppRecPtr, NULL);
CFE_ES_Global.SystemState = CFE_ES_SystemState_CORE_READY;
/* Note - CFE_ES_WaitForStartupSync() returns void, nothing to check for
* here. This is for code coverage
*/
CFE_UtAssert_VOIDCALL(CFE_ES_WaitForStartupSync(99));
/* Test waiting for apps to initialize as an external app
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_EARLY_INIT, "UT", &UtAppRecPtr, NULL);
CFE_ES_Global.SystemState = CFE_ES_SystemState_CORE_READY;
/* Note - CFE_ES_WaitForStartupSync() returns void, nothing to check for
* here. This is for code coverage
*/
CFE_UtAssert_VOIDCALL(CFE_ES_WaitForStartupSync(99));
/* Test adding a time-stamped message to the system log using an invalid
* log mode
*
* TEST CASE REMOVED as the invalid log mode follow the same path as Discard,
* this test case added nothing new
*/
/* Test successfully adding a time-stamped message to the system log that
* causes the log index to be reset
*/
ES_ResetUnitTest();
CFE_ES_Global.ResetDataPtr->SystemLogWriteIdx = CFE_PLATFORM_ES_SYSTEM_LOG_SIZE;
CFE_ES_Global.ResetDataPtr->SystemLogEndIdx = CFE_ES_Global.ResetDataPtr->SystemLogWriteIdx;
CFE_ES_Global.ResetDataPtr->SystemLogMode = CFE_ES_LogMode_DISCARD;
UtAssert_INT32_EQ(CFE_ES_WriteToSysLog("SysLogText"), CFE_ES_ERR_SYS_LOG_FULL);
/* Test successfully adding a time-stamped message to the system log that
* causes the log index to be reset
*/
ES_ResetUnitTest();
CFE_ES_Global.ResetDataPtr->SystemLogWriteIdx = CFE_PLATFORM_ES_SYSTEM_LOG_SIZE;
CFE_ES_Global.ResetDataPtr->SystemLogEndIdx = CFE_ES_Global.ResetDataPtr->SystemLogWriteIdx;
CFE_ES_Global.ResetDataPtr->SystemLogMode = CFE_ES_LogMode_OVERWRITE;
CFE_UtAssert_SUCCESS(CFE_ES_WriteToSysLog("SysLogText"));
CFE_UtAssert_ATMOST(CFE_ES_Global.ResetDataPtr->SystemLogWriteIdx, CFE_PLATFORM_ES_SYSTEM_LOG_SIZE - 1);
/* Test run loop with an application error status */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, "UT", &UtAppRecPtr, NULL);
RunStatus = CFE_ES_RunStatus_APP_ERROR;
UtAppRecPtr->ControlReq.AppControlRequest = CFE_ES_RunStatus_APP_ERROR;
CFE_UtAssert_FALSE(CFE_ES_RunLoop(&RunStatus));
/*
* Test public Name+ID query/lookup API for tasks
* This just uses OSAL routines to implement, but need to cover error paths.
*/
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_EXTERNAL, CFE_ES_AppState_RUNNING, "UT", &UtAppRecPtr, &UtTaskRecPtr);
TaskId = CFE_ES_TaskRecordGetID(UtTaskRecPtr);
UtAssert_INT32_EQ(CFE_ES_GetTaskName(AppName, CFE_ES_TASKID_UNDEFINED, sizeof(AppName)),
CFE_ES_ERR_RESOURCEID_NOT_VALID);
UtAssert_INT32_EQ(CFE_ES_GetTaskName(NULL, TaskId, sizeof(AppName)), CFE_ES_BAD_ARGUMENT);
CFE_UtAssert_SUCCESS(CFE_ES_GetTaskName(AppName, TaskId, sizeof(AppName)));
UT_SetDeferredRetcode(UT_KEY(OS_GetResourceName), 1, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_GetTaskName(AppName, TaskId, sizeof(AppName)), CFE_ES_ERR_RESOURCEID_NOT_VALID);
UtAssert_INT32_EQ(CFE_ES_GetTaskIDByName(&TaskId, NULL), CFE_ES_BAD_ARGUMENT);
CFE_UtAssert_SUCCESS(CFE_ES_GetTaskIDByName(&TaskId, AppName));
UT_SetDeferredRetcode(UT_KEY(OS_TaskGetIdByName), 1, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_GetTaskIDByName(&TaskId, "Nonexistent"), CFE_ES_ERR_NAME_NOT_FOUND);
}
void TestGenericCounterAPI(void)
{
char CounterName[11];
CFE_ES_CounterId_t CounterId;
CFE_ES_CounterId_t CounterId2;
uint32 CounterCount;
int i;
/* Test successfully registering a generic counter */
ES_ResetUnitTest();
CFE_UtAssert_SUCCESS(CFE_ES_RegisterGenCounter(&CounterId, "Counter1"));
/* Test registering a generic counter that is already registered */
UtAssert_INT32_EQ(CFE_ES_RegisterGenCounter(&CounterId, "Counter1"), CFE_ES_ERR_DUPLICATE_NAME);
/* Test registering the maximum number of generic counters */
for (i = 1; i < CFE_PLATFORM_ES_MAX_GEN_COUNTERS; i++)
{
snprintf(CounterName, sizeof(CounterName), "Counter%d", i + 1);
if (CFE_ES_RegisterGenCounter(&CounterId, CounterName) != CFE_SUCCESS)
{
break;
}
}
UtAssert_INT32_EQ(i, CFE_PLATFORM_ES_MAX_GEN_COUNTERS);
/* Test registering a generic counter after the maximum are registered */
UT_SetDefaultReturnValue(UT_KEY(CFE_ResourceId_FindNext), OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_RegisterGenCounter(&CounterId, "Counter999"), CFE_ES_NO_RESOURCE_IDS_AVAILABLE);
UT_ResetState(UT_KEY(CFE_ResourceId_FindNext));
/* Check operation of the CFE_ES_CheckCounterIdSlotUsed() helper function */
CFE_ES_Global.CounterTable[1].CounterId = CFE_ES_COUNTERID_C(ES_UT_MakeCounterIdForIndex(1));
CFE_ES_Global.CounterTable[2].CounterId = CFE_ES_COUNTERID_UNDEFINED;
CFE_UtAssert_TRUE(CFE_ES_CheckCounterIdSlotUsed(ES_UT_MakeCounterIdForIndex(1)));
CFE_UtAssert_FALSE(CFE_ES_CheckCounterIdSlotUsed(ES_UT_MakeCounterIdForIndex(2)));
/* Test getting a registered generic counter that doesn't exist */
UtAssert_INT32_EQ(CFE_ES_GetGenCounterIDByName(&CounterId, "Counter999"), CFE_ES_ERR_NAME_NOT_FOUND);
/* Test successfully getting a registered generic counter ID by name */
CFE_UtAssert_SUCCESS(CFE_ES_GetGenCounterIDByName(&CounterId, "Counter5"));
/* Test deleting a registered generic counter that doesn't exist */
UtAssert_INT32_EQ(CFE_ES_DeleteGenCounter(CFE_ES_COUNTERID_UNDEFINED), CFE_ES_BAD_ARGUMENT);
/* Test successfully deleting a registered generic counter by ID */
CFE_UtAssert_SUCCESS(CFE_ES_DeleteGenCounter(CounterId));
/* Test successfully registering a generic counter to verify a place for
* it is now available and to provide an ID for subsequent tests
*/
CFE_UtAssert_SUCCESS(CFE_ES_RegisterGenCounter(&CounterId, "CounterX"));
/* Test incrementing a generic counter that doesn't exist */
UtAssert_INT32_EQ(CFE_ES_IncrementGenCounter(CFE_ES_COUNTERID_UNDEFINED), CFE_ES_BAD_ARGUMENT);
/* Test successfully incrementing a generic counter */
CFE_UtAssert_SUCCESS(CFE_ES_IncrementGenCounter(CounterId));
/* Test getting a generic counter value for a counter that doesn't exist */
UtAssert_INT32_EQ(CFE_ES_GetGenCount(CFE_ES_COUNTERID_UNDEFINED, &CounterCount), CFE_ES_BAD_ARGUMENT);
/* Test successfully getting a generic counter value */
UtAssert_INT32_EQ(CFE_ES_GetGenCount(CounterId, &CounterCount) == CFE_SUCCESS && CounterCount, 1);
/* Test setting a generic counter value for a counter that doesn't exist */
UtAssert_INT32_EQ(CFE_ES_SetGenCount(CFE_ES_COUNTERID_UNDEFINED, 5), CFE_ES_BAD_ARGUMENT);
/* Test successfully setting a generic counter value */
CFE_UtAssert_SUCCESS(CFE_ES_SetGenCount(CounterId, 5));
/* Test value retrieved from a generic counter value */
CFE_ES_GetGenCount(CounterId, &CounterCount);
UtAssert_INT32_EQ(CounterCount, 5);
/* Test registering a generic counter with a null counter ID pointer */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_RegisterGenCounter(NULL, "Counter1"), CFE_ES_BAD_ARGUMENT);
/* Test registering a generic counter with a null counter name */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_RegisterGenCounter(&CounterId, NULL), CFE_ES_BAD_ARGUMENT);
/* Test incrementing a generic counter where the record is not in use */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_IncrementGenCounter(CounterId), CFE_ES_BAD_ARGUMENT);
/* Test setting a generic counter where the record is not in use */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_SetGenCount(CounterId, 0), CFE_ES_BAD_ARGUMENT);
/* Test getting a generic counter where the record is not in use */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_GetGenCount(CounterId, &CounterCount), CFE_ES_BAD_ARGUMENT);
/* Test getting a generic counter where the count is null */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_GetGenCount(CounterId, NULL), CFE_ES_BAD_ARGUMENT);
/* Test getting a registered generic counter ID using a null counter
* pointer
*/
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_GetGenCounterIDByName(NULL, "CounterX"), CFE_ES_BAD_ARGUMENT);
/*
* Test Name-ID query/conversion API
*/
ES_ResetUnitTest();
CFE_UtAssert_SUCCESS(CFE_ES_RegisterGenCounter(&CounterId, "Counter1"));
CFE_UtAssert_SUCCESS(CFE_ES_GetGenCounterName(CounterName, CounterId, sizeof(CounterName)));
UtAssert_INT32_EQ(CFE_ES_GetGenCounterIDByName(&CounterId2, "Nonexistent"), CFE_ES_ERR_NAME_NOT_FOUND);
CFE_UtAssert_SUCCESS(CFE_ES_GetGenCounterIDByName(&CounterId2, CounterName));
CFE_UtAssert_RESOURCEID_EQ(CounterId, CounterId2);
UtAssert_INT32_EQ(CFE_ES_GetGenCounterName(CounterName, CFE_ES_COUNTERID_UNDEFINED, sizeof(CounterName)),
CFE_ES_ERR_RESOURCEID_NOT_VALID);
UtAssert_INT32_EQ(CFE_ES_GetGenCounterName(NULL, CounterId, sizeof(CounterName)), CFE_ES_BAD_ARGUMENT);
UtAssert_INT32_EQ(CFE_ES_GetGenCounterIDByName(&CounterId, NULL), CFE_ES_BAD_ARGUMENT);
}
void TestCDS()
{
size_t CdsSize;
uint8 * CdsPtr;
char CDSName[CFE_MISSION_ES_CDS_MAX_FULL_NAME_LEN + 4];
CFE_ES_CDSHandle_t CDSHandle;
CFE_ES_CDS_RegRec_t *UtCDSRegRecPtr;
uint32 i;
uint32 TempSize;
uint8 BlockData[ES_UT_CDS_BLOCK_SIZE];
UtPrintf("Begin Test CDS");
/* Test init with a mutex create failure */
UT_SetDeferredRetcode(UT_KEY(OS_MutSemCreate), 1, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_CDS_EarlyInit(), CFE_STATUS_EXTERNAL_RESOURCE_FAIL);
/* Test locking the CDS registry with a mutex take failure */
UT_SetDeferredRetcode(UT_KEY(OS_MutSemTake), 1, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_LockCDS(), CFE_STATUS_EXTERNAL_RESOURCE_FAIL);
/* Test unlocking the CDS registry with a mutex give failure */
UT_SetDeferredRetcode(UT_KEY(OS_MutSemGive), 1, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_UnlockCDS(), CFE_STATUS_EXTERNAL_RESOURCE_FAIL);
/* Set up the PSP stubs for CDS testing */
UT_SetCDSSize(128 * 1024);
/* Test the CDS Cache Fetch/Flush/Load routine error cases */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_CDS_CacheFetch(&CFE_ES_Global.CDSVars.Cache, 4, 0), CFE_ES_CDS_INVALID_SIZE);
UtAssert_INT32_EQ(CFE_ES_CDS_CacheFlush(&CFE_ES_Global.CDSVars.Cache), CFE_ES_CDS_INVALID_SIZE);
UtAssert_INT32_EQ(CFE_ES_CDS_CachePreload(&CFE_ES_Global.CDSVars.Cache, NULL, 4, 0), CFE_ES_CDS_INVALID_SIZE);
TempSize = 5;
CFE_UtAssert_SUCCESS(CFE_ES_CDS_CachePreload(&CFE_ES_Global.CDSVars.Cache, &TempSize, 4, 4));
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_ReadFromCDS), 1, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_CDS_CacheFetch(&CFE_ES_Global.CDSVars.Cache, 4, 4), CFE_ES_CDS_ACCESS_ERROR);
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_WriteToCDS), 1, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_CDS_CacheFlush(&CFE_ES_Global.CDSVars.Cache), CFE_ES_CDS_ACCESS_ERROR);
/* Test CDS registering with null Handle pointer */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_RegisterCDS(NULL, 4, "Name3"), CFE_ES_BAD_ARGUMENT);
/* Test CDS registering with null name */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_RegisterCDS(&CDSHandle, 4, NULL), CFE_ES_BAD_ARGUMENT);
/* Test CDS registering with a write CDS failure */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, "UT", NULL, NULL);
ES_UT_SetupCDSGlobal(ES_UT_CDS_SMALL_TEST_SIZE);
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_WriteToCDS), 2, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_RegisterCDS(&CDSHandle, 4, "Name3"), CFE_ES_CDS_ACCESS_ERROR);
/* Test successful CDS registering */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, "UT", NULL, NULL);
ES_UT_SetupCDSGlobal(ES_UT_CDS_SMALL_TEST_SIZE);
CFE_UtAssert_SUCCESS(CFE_ES_RegisterCDS(&CDSHandle, 4, "Name"));
/* Test CDS registering using an already registered name */
/* No reset here -- just attempt to register the same name again */
UtAssert_INT32_EQ(CFE_ES_RegisterCDS(&CDSHandle, 4, "Name"), CFE_ES_CDS_ALREADY_EXISTS);
/* Test CDS registering using the same name, but a different size */
/* No reset here -- just attempt to register the same name again */
CFE_UtAssert_SUCCESS(CFE_ES_RegisterCDS(&CDSHandle, 6, "Name"));
/* Test CDS registering using a null name */
UtAssert_INT32_EQ(CFE_ES_RegisterCDS(&CDSHandle, 4, ""), CFE_ES_CDS_INVALID_NAME);
/* Test CDS registering with a block size of zero */
UtAssert_INT32_EQ(CFE_ES_RegisterCDS(&CDSHandle, 0, "Name"), CFE_ES_CDS_INVALID_SIZE);
/* Test CDS registering with no memory pool available */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, "UT", NULL, NULL);
UtAssert_INT32_EQ(CFE_ES_RegisterCDS(&CDSHandle, 4, "Name"), CFE_ES_NOT_IMPLEMENTED);
/* Test CDS registering with all the CDS registries taken */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, "UT", NULL, NULL);
ES_UT_SetupCDSGlobal(ES_UT_CDS_SMALL_TEST_SIZE);
/* Set all the CDS registries to 'taken' */
UT_SetDefaultReturnValue(UT_KEY(CFE_ResourceId_FindNext), OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_RegisterCDS(&CDSHandle, 4, "Name2"), CFE_ES_NO_RESOURCE_IDS_AVAILABLE);
/* Check operation of the CFE_ES_CheckCDSHandleSlotUsed() helper function */
CFE_ES_Global.CDSVars.Registry[1].BlockID = CFE_ES_CDSHANDLE_C(ES_UT_MakeCDSIdForIndex(1));
CFE_ES_Global.CDSVars.Registry[2].BlockID = CFE_ES_CDS_BAD_HANDLE;
CFE_UtAssert_TRUE(CFE_ES_CheckCDSHandleSlotUsed(ES_UT_MakeCDSIdForIndex(1)));
CFE_UtAssert_FALSE(CFE_ES_CheckCDSHandleSlotUsed(ES_UT_MakeCDSIdForIndex(2)));
/* Test CDS registering using a bad app ID */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_RegisterCDS(&CDSHandle, 4, "Name2"), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test copying to CDS with bad handle */
CDSHandle = CFE_ES_CDS_BAD_HANDLE;
UtAssert_INT32_EQ(CFE_ES_CopyToCDS(CDSHandle, &TempSize), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test restoring from a CDS with bad handle */
UtAssert_INT32_EQ(CFE_ES_RestoreFromCDS(&TempSize, CDSHandle), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test successfully copying to a CDS */
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_ReadFromCDS), 1, OS_SUCCESS);
ES_UT_SetupSingleCDSRegistry("UT", ES_UT_CDS_BLOCK_SIZE, false, &UtCDSRegRecPtr);
CDSHandle = CFE_ES_CDSBlockRecordGetID(UtCDSRegRecPtr);
CFE_UtAssert_SUCCESS(CFE_ES_CopyToCDS(CDSHandle, &BlockData));
/* Test successfully restoring from a CDS */
CFE_UtAssert_SUCCESS(CFE_ES_RestoreFromCDS(&BlockData, CDSHandle));
/* Test CDS registering using a name longer than the maximum allowed */
ES_ResetUnitTest();
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, "UT", NULL, NULL);
ES_UT_SetupCDSGlobal(ES_UT_CDS_SMALL_TEST_SIZE);
for (i = 0; i < CFE_MISSION_ES_CDS_MAX_NAME_LENGTH + 1; i++)
{
CDSName[i] = 'a';
}
CDSName[i] = '\0';
UtAssert_INT32_EQ(CFE_ES_RegisterCDS(&CDSHandle, 4, CDSName), CFE_ES_CDS_INVALID_NAME);
/* Test unsuccessful CDS registering */
UtAssert_INT32_EQ(CFE_ES_RegisterCDS(&CDSHandle, CDS_ABS_MAX_BLOCK_SIZE + 1, "Name"), CFE_ES_CDS_INVALID_SIZE);
UtAssert_INT32_EQ(CFE_ES_RegisterCDS(&CDSHandle, CDS_ABS_MAX_BLOCK_SIZE - 1, "Name"), CFE_ES_ERR_MEM_BLOCK_SIZE);
/* Test memory pool rebuild and registry recovery with an
* unreadable registry
*/
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_ReadFromCDS), 1, -1);
UtAssert_INT32_EQ(CFE_ES_RebuildCDS(), CFE_ES_CDS_INVALID);
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_ReadFromCDS), 2, -1);
UtAssert_INT32_EQ(CFE_ES_RebuildCDS(), CFE_ES_CDS_INVALID);
/* Test CDS registry initialization with a CDS write failure */
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_WriteToCDS), 1, -1);
UtAssert_INT32_EQ(CFE_ES_InitCDSRegistry(), CFE_ES_CDS_ACCESS_ERROR);
/* Test successful CDS initialization */
ES_ResetUnitTest();
CFE_UtAssert_SUCCESS(CFE_ES_CDS_EarlyInit());
/* Test CDS initialization with a read error */
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_ReadFromCDS), 1, -1);
UtAssert_INT32_EQ(CFE_ES_CDS_EarlyInit(), CFE_ES_CDS_ACCESS_ERROR);
/* Test CDS initialization with size below the minimum */
ES_ResetUnitTest();
UT_SetCDSSize(1024);
CFE_UtAssert_SUCCESS(CFE_ES_CDS_EarlyInit());
UtAssert_STUB_COUNT(CFE_PSP_GetCDSSize, 1);
/* Test CDS initialization with size not obtainable */
ES_ResetUnitTest();
UT_SetDefaultReturnValue(UT_KEY(CFE_PSP_GetCDSSize), -1);
UtAssert_INT32_EQ(CFE_ES_CDS_EarlyInit(), OS_ERROR);
/* Reset back to a sufficient CDS size */
UT_SetCDSSize(128 * 1024);
UT_GetDataBuffer(UT_KEY(CFE_PSP_ReadFromCDS), (void **)&CdsPtr, &CdsSize, NULL);
/* Test CDS initialization with rebuilding not possible */
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_ReadFromCDS), 3, OS_ERROR);
CFE_UtAssert_SUCCESS(CFE_ES_CDS_EarlyInit());
/* Test CDS validation with first CDS read call failure */
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_ReadFromCDS), 1, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_ValidateCDS(), CFE_ES_CDS_ACCESS_ERROR);
/* Test CDS validation with second CDS read call failure */
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_ReadFromCDS), 2, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_ValidateCDS(), CFE_ES_CDS_ACCESS_ERROR);
/* Test CDS validation with CDS read end check failure */
memset(CdsPtr + CdsSize - CFE_ES_CDS_SIGNATURE_LEN, 'x', CFE_ES_CDS_SIGNATURE_LEN);
UtAssert_INT32_EQ(CFE_ES_ValidateCDS(), CFE_ES_CDS_INVALID);
/* Test CDS validation with CDS read begin check failure */
UT_GetDataBuffer(UT_KEY(CFE_PSP_ReadFromCDS), (void **)&CdsPtr, &CdsSize, NULL);
memset(CdsPtr, 'x', CFE_ES_CDS_SIGNATURE_LEN);
UtAssert_INT32_EQ(CFE_ES_ValidateCDS(), CFE_ES_CDS_INVALID);
/* Test CDS initialization where first write call to the CDS fails */
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_WriteToCDS), 1, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_InitCDSSignatures(), CFE_ES_CDS_ACCESS_ERROR);
/* Test CDS initialization where second write call to the CDS fails */
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_WriteToCDS), 2, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_InitCDSSignatures(), CFE_ES_CDS_ACCESS_ERROR);
/* Test CDS clear where write call to the CDS fails */
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_WriteToCDS), 2, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_ClearCDS(), CFE_ES_CDS_ACCESS_ERROR);
/* Test rebuilding the CDS where the registry is not the same size */
ES_ResetUnitTest();
UT_GetDataBuffer(UT_KEY(CFE_PSP_ReadFromCDS), (void **)&CdsPtr, &CdsSize, NULL);
TempSize = CFE_PLATFORM_ES_CDS_MAX_NUM_ENTRIES + 1;
memcpy(CdsPtr + CDS_REG_SIZE_OFFSET, &TempSize, sizeof(TempSize));
UtAssert_INT32_EQ(CFE_ES_RebuildCDS(), CFE_ES_CDS_INVALID);
/* Test clearing CDS where size is an odd number (requires partial write) */
ES_ResetUnitTest();
CFE_ES_Global.CDSVars.TotalSize = 53;
CFE_UtAssert_SUCCESS(CFE_ES_ClearCDS());
/*
* To prepare for the rebuild tests, set up a clean area in PSP mem,
* and make a registry entry.
*/
ES_UT_SetupCDSGlobal(ES_UT_CDS_SMALL_TEST_SIZE);
ES_UT_SetupSingleCDSRegistry("UT", 8, false, &UtCDSRegRecPtr);
UtAssert_NONZERO(UtCDSRegRecPtr->BlockOffset);
UtAssert_NONZERO(UtCDSRegRecPtr->BlockSize);
CFE_UtAssert_SUCCESS(CFE_ES_UpdateCDSRegistry());
/* Test successfully rebuilding the CDS */
ES_ResetUnitTest();
/* The reset would have cleared the registry data */
UtAssert_ZERO(UtCDSRegRecPtr->BlockOffset);
UtAssert_ZERO(UtCDSRegRecPtr->BlockSize);
CFE_UtAssert_SUCCESS(CFE_ES_CDS_EarlyInit());
/* Check that the registry entry exists again (was recovered) */
UtAssert_NONZERO(UtCDSRegRecPtr->BlockOffset);
UtAssert_NONZERO(UtCDSRegRecPtr->BlockSize);
/* Test rebuilding the CDS with the registry unreadable */
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_ReadFromCDS), 2, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_RebuildCDS(), CFE_ES_CDS_INVALID);
/* Test deleting the CDS from the registry with a registry write failure */
ES_ResetUnitTest();
ES_UT_SetupSingleCDSRegistry("NO_APP.CDS_NAME", ES_UT_CDS_BLOCK_SIZE, true, NULL);
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_WriteToCDS), 1, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_DeleteCDS("NO_APP.CDS_NAME", true), -1);
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_WriteToCDS), 2, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_DeleteCDS("NO_APP.CDS_NAME", true), CFE_ES_CDS_ACCESS_ERROR);
/* Test deleting the CDS from the registry with the owner application
* still active
*/
ES_ResetUnitTest();
ES_UT_SetupSingleCDSRegistry("CFE_ES.CDS_NAME", ES_UT_CDS_BLOCK_SIZE, true, NULL);
ES_UT_SetupSingleAppId(CFE_ES_AppType_CORE, CFE_ES_AppState_RUNNING, "CFE_ES", NULL, NULL);
UtAssert_INT32_EQ(CFE_ES_DeleteCDS("CFE_ES.CDS_NAME", true), CFE_ES_CDS_OWNER_ACTIVE_ERR);
/*
* To prepare for the rebuild tests, set up a clean area in PSP mem
*/
ES_UT_SetupCDSGlobal(ES_UT_CDS_LARGE_TEST_SIZE);
/* Test CDS initialization where rebuilding the CDS is successful */
ES_ResetUnitTest();
CFE_UtAssert_SUCCESS(CFE_ES_CDS_EarlyInit());
/* Test CDS initialization where rebuilding the CDS is unsuccessful */
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_ReadFromCDS), 3, OS_ERROR);
CFE_UtAssert_SUCCESS(CFE_ES_CDS_EarlyInit());
/* Test CDS initialization where initializing the CDS registry fails */
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_WriteToCDS), 1, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_InitCDSRegistry(), CFE_ES_CDS_ACCESS_ERROR);
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_WriteToCDS), 2, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_InitCDSRegistry(), CFE_ES_CDS_ACCESS_ERROR);
/* Test deleting the CDS from the registry with a CDS name longer than the
* maximum allowed
*/
ES_ResetUnitTest();
memset(CDSName, 'a', sizeof(CDSName) - 1);
CDSName[sizeof(CDSName) - 1] = '\0';
ES_UT_SetupSingleCDSRegistry(CDSName, ES_UT_CDS_BLOCK_SIZE, true, NULL);
UtAssert_INT32_EQ(CFE_ES_DeleteCDS(CDSName, true), CFE_ES_ERR_NAME_NOT_FOUND);
/*
* Test Name-ID query/conversion API
*/
ES_ResetUnitTest();
ES_UT_SetupSingleCDSRegistry("CDS1", ES_UT_CDS_BLOCK_SIZE, false, &UtCDSRegRecPtr);
CDSHandle = CFE_ES_CDSBlockRecordGetID(UtCDSRegRecPtr);
CFE_UtAssert_SUCCESS(CFE_ES_GetCDSBlockName(CDSName, CDSHandle, sizeof(CDSName)));
UtAssert_INT32_EQ(CFE_ES_GetCDSBlockIDByName(&CDSHandle, "Nonexistent"), CFE_ES_ERR_NAME_NOT_FOUND);
CFE_UtAssert_SUCCESS(CFE_ES_GetCDSBlockIDByName(&CDSHandle, CDSName));
CFE_UtAssert_RESOURCEID_EQ(CDSHandle, CFE_ES_CDSBlockRecordGetID(UtCDSRegRecPtr));
UtAssert_INT32_EQ(CFE_ES_GetCDSBlockName(CDSName, CFE_ES_CDS_BAD_HANDLE, sizeof(CDSName)),
CFE_ES_ERR_RESOURCEID_NOT_VALID);
UtAssert_INT32_EQ(CFE_ES_GetCDSBlockName(NULL, CDSHandle, sizeof(CDSName)), CFE_ES_BAD_ARGUMENT);
UtAssert_INT32_EQ(CFE_ES_GetCDSBlockIDByName(&CDSHandle, NULL), CFE_ES_BAD_ARGUMENT);
} /* End TestCDS */
void TestCDSMempool(void)
{
CFE_ES_CDS_RegRec_t *UtCdsRegRecPtr;
int Data;
CFE_ES_CDSHandle_t BlockHandle;
size_t SavedSize;
size_t SavedOffset;
uint8 * CdsPtr;
UtPrintf("Begin Test CDS memory pool");
ES_UT_SetupCDSGlobal(0);
/* Test creating the CDS pool with the pool size too small */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_CreateCDSPool(2, 1), CFE_ES_CDS_INVALID_SIZE);
/* Test rebuilding the CDS pool with the pool size too small */
UtAssert_INT32_EQ(CFE_ES_RebuildCDSPool(2, 1), CFE_ES_CDS_INVALID_SIZE);
/* Test rebuilding CDS pool with CDS access errors */
/*
* To setup - Create a CDS registry and delete it, which creates
* a freed block in the pool. Then attempt to rebuild.
*/
ES_ResetUnitTest();
ES_UT_SetupCDSGlobal(ES_UT_CDS_SMALL_TEST_SIZE);
SavedSize = CFE_ES_Global.CDSVars.TotalSize;
SavedOffset = CFE_ES_Global.CDSVars.Pool.TailPosition;
ES_UT_SetupSingleCDSRegistry("UT", sizeof(Data) + sizeof(CFE_ES_CDS_BlockHeader_t), false, &UtCdsRegRecPtr);
UtAssert_NONZERO(UtCdsRegRecPtr->BlockOffset);
UtAssert_NONZERO(UtCdsRegRecPtr->BlockSize);
CFE_ES_DeleteCDS("UT", false);
CFE_UtAssert_SUCCESS(CFE_ES_UpdateCDSRegistry());
/* Clear/reset the global state */
ES_ResetUnitTest();
/* Test rebuilding the CDS pool with a descriptor retrieve error */
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_ReadFromCDS), 1, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_RebuildCDSPool(SavedSize, SavedOffset), CFE_ES_CDS_ACCESS_ERROR);
/* Test rebuilding the CDS pool with a descriptor commit error */
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_WriteToCDS), 1, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_RebuildCDSPool(SavedSize, SavedOffset), CFE_ES_CDS_ACCESS_ERROR);
/* Test CDS block write using an invalid memory handle */
ES_ResetUnitTest();
BlockHandle = CFE_ES_CDSHANDLE_C(CFE_ResourceId_FromInteger(7));
UtAssert_INT32_EQ(CFE_ES_CDSBlockWrite(BlockHandle, &Data), CFE_ES_ERR_RESOURCEID_NOT_VALID);
UtAssert_INT32_EQ(CFE_ES_CDSBlockRead(&Data, BlockHandle), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test CDS block access */
ES_ResetUnitTest();
ES_UT_SetupCDSGlobal(ES_UT_CDS_SMALL_TEST_SIZE);
ES_UT_SetupSingleCDSRegistry("UT", sizeof(Data) + sizeof(CFE_ES_CDS_BlockHeader_t), false, &UtCdsRegRecPtr);
BlockHandle = CFE_ES_CDSBlockRecordGetID(UtCdsRegRecPtr);
Data = 42;
/* Basic success path */
CFE_UtAssert_SUCCESS(CFE_ES_CDSBlockWrite(BlockHandle, &Data));
Data = 0;
CFE_UtAssert_SUCCESS(CFE_ES_CDSBlockRead(&Data, BlockHandle));
UtAssert_INT32_EQ(Data, 42);
/* Corrupt/change the block offset, should fail validation */
--UtCdsRegRecPtr->BlockOffset;
UtAssert_INT32_EQ(CFE_ES_CDSBlockWrite(BlockHandle, &Data), CFE_ES_POOL_BLOCK_INVALID);
UtAssert_INT32_EQ(CFE_ES_CDSBlockRead(&Data, BlockHandle), CFE_ES_POOL_BLOCK_INVALID);
++UtCdsRegRecPtr->BlockOffset;
/* Corrupt/change the block size, should trigger invalid size error */
--UtCdsRegRecPtr->BlockSize;
UtAssert_INT32_EQ(CFE_ES_CDSBlockWrite(BlockHandle, &Data), CFE_ES_CDS_INVALID_SIZE);
UtAssert_INT32_EQ(CFE_ES_CDSBlockRead(&Data, BlockHandle), CFE_ES_CDS_INVALID_SIZE);
++UtCdsRegRecPtr->BlockSize;
/* Test CDS block read/write with a CDS read error (block descriptor) */
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_ReadFromCDS), 1, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_CDSBlockWrite(BlockHandle, &Data), CFE_ES_CDS_ACCESS_ERROR);
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_ReadFromCDS), 1, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_CDSBlockRead(&Data, BlockHandle), CFE_ES_CDS_ACCESS_ERROR);
/* Test CDS block write with a CDS write error (block header) */
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_WriteToCDS), 1, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_CDSBlockWrite(BlockHandle, &Data), CFE_ES_CDS_ACCESS_ERROR);
/* Test CDS block read with a CDS read error (block header) */
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_ReadFromCDS), 2, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_CDSBlockRead(&Data, BlockHandle), CFE_ES_CDS_ACCESS_ERROR);
/* Test CDS block write with a CDS write error (data content) */
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_WriteToCDS), 2, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_CDSBlockWrite(BlockHandle, &Data), OS_ERROR);
/* Test CDS block read with a CDS read error (data content) */
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_ReadFromCDS), 3, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_CDSBlockRead(&Data, BlockHandle), OS_ERROR);
/* Corrupt the data as to cause a CRC mismatch */
UT_GetDataBuffer(UT_KEY(CFE_PSP_ReadFromCDS), (void **)&CdsPtr, NULL, NULL);
CdsPtr[UtCdsRegRecPtr->BlockOffset] ^= 0x02; /* Bit flip */
UtAssert_INT32_EQ(CFE_ES_CDSBlockRead(&Data, BlockHandle), CFE_ES_CDS_BLOCK_CRC_ERR);
CdsPtr[UtCdsRegRecPtr->BlockOffset] ^= 0x02; /* Fix Bit */
}
void TestESMempool(void)
{
CFE_ES_MemHandle_t PoolID1; /* Poo1 1 handle, no mutex */
CFE_ES_MemHandle_t PoolID2; /* Poo1 2 handle, with mutex */
uint8 Buffer1[1024];
uint8 Buffer2[1024];
CFE_ES_MemPoolBuf_t addressp1 = CFE_ES_MEMPOOLBUF_C(0); /* Pool 1 buffer address */
CFE_ES_MemPoolBuf_t addressp2 = CFE_ES_MEMPOOLBUF_C(0); /* Pool 2 buffer address */
CFE_ES_MemPoolRecord_t *PoolPtr;
CFE_ES_MemPoolStats_t Stats;
size_t BlockSizes[CFE_PLATFORM_ES_POOL_MAX_BUCKETS + 2];
CFE_ES_GenPoolBD_t * BdPtr;
uint32 i;
UtPrintf("Begin Test ES memory pool");
memset(BlockSizes, 0, sizeof(BlockSizes));
/* Test creating memory pool without using a mutex with the pool size
* too small
*/
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_PoolCreateNoSem(&PoolID1, Buffer1, 0), CFE_ES_BAD_ARGUMENT);
/* Test successfully creating memory pool without using a mutex */
CFE_UtAssert_SUCCESS(CFE_ES_PoolCreateNoSem(&PoolID1, Buffer1, sizeof(Buffer1)));
/* Test creating memory pool using a mutex with the pool size too small */
UtAssert_INT32_EQ(CFE_ES_PoolCreate(&PoolID2, Buffer2, 0), CFE_ES_BAD_ARGUMENT);
/* Test successfully creating memory pool using a mutex */
CFE_UtAssert_SUCCESS(CFE_ES_PoolCreate(&PoolID2, Buffer2, sizeof(Buffer2)));
/* Test successfully allocating a pool buffer */
UtAssert_INT32_EQ(CFE_ES_GetPoolBuf(&addressp1, PoolID1, 256), 256);
UtAssert_INT32_EQ(CFE_ES_GetPoolBuf(&addressp2, PoolID2, 256), 256);
/* Test successfully getting the size of an existing pool buffer */
UtAssert_INT32_EQ(CFE_ES_GetPoolBufInfo(PoolID2, addressp2), 256);
/* Test successfully getting the size of an existing pool buffer. Use no
* mutex in order to get branch path coverage
*/
UtAssert_INT32_EQ(CFE_ES_GetPoolBufInfo(PoolID1, addressp1), 256);
/* Test successfully returning a pool buffer to the memory pool */
UtAssert_INT32_EQ(CFE_ES_PutPoolBuf(PoolID1, addressp1), 256);
UtAssert_INT32_EQ(CFE_ES_PutPoolBuf(PoolID2, addressp2), 256);
/* Test successfully allocating an additional pool buffer */
UtAssert_INT32_EQ(CFE_ES_GetPoolBuf(&addressp2, PoolID2, 256), 256);
/* Test successfully returning a pool buffer to the second memory pool.
* Use no mutex in order to get branch path coverage
*/
UtAssert_INT32_EQ(CFE_ES_PutPoolBuf(PoolID2, addressp2), 256);
/* Test handle validation using a handle with an invalid memory address */
UT_SetDeferredRetcode(UT_KEY(CFE_PSP_MemValidateRange), 1, -1);
CFE_UtAssert_FALSE(CFE_ES_ValidateHandle(PoolID2));
/* Test handle validation using a handle where the first pool structure
* field is not the pool start address
*/
PoolPtr = CFE_ES_LocateMemPoolRecordByID(PoolID2);
/*
* Intentionally corrupt the Pool ID value - whether strict or simple
* types are in use, underneath the wrapper(s) lies a uint32 eventually.
* This is intentionally a type-UNSAFE access to this value.
*/
*((uint32 *)&PoolPtr->PoolID) ^= 10; /* cause it to fail validation */
CFE_UtAssert_FALSE(CFE_ES_ValidateHandle(PoolID2));
/* Test allocating a pool buffer where the memory handle is not the pool
* start address
*/
UtAssert_INT32_EQ(CFE_ES_GetPoolBuf(&addressp2, PoolID2, 256), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test getting memory pool statistics where the memory handle is not
* the pool start address
*/
UtAssert_INT32_EQ(CFE_ES_GetMemPoolStats(&Stats, CFE_ES_MEMHANDLE_UNDEFINED), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test allocating a pool buffer where the memory block doesn't fit within
* the remaining memory
*/
UtAssert_INT32_EQ(CFE_ES_GetPoolBuf(&addressp1, PoolID1, 75000), CFE_ES_ERR_MEM_BLOCK_SIZE);
/* Test getting the size of an existing pool buffer using an
* invalid handle
*/
UtAssert_INT32_EQ(CFE_ES_GetPoolBufInfo(PoolID2, addressp2), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Undo the previous memory corruption */
*((uint32 *)&PoolPtr->PoolID) ^= 10; /* Repair Pool2 ID */
/* Test returning a pool buffer using an invalid memory block */
UtAssert_INT32_EQ(CFE_ES_PutPoolBuf(PoolID2, CFE_ES_MEMPOOLBUF_C((cpuaddr)addressp2 - 40)),
CFE_ES_BUFFER_NOT_IN_POOL);
/* Test initializing a pre-allocated pool specifying a number of block
* sizes greater than the maximum
*/
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_PoolCreateEx(&PoolID1, Buffer1, sizeof(Buffer1), CFE_PLATFORM_ES_POOL_MAX_BUCKETS + 2,
BlockSizes, CFE_ES_USE_MUTEX),
CFE_ES_BAD_ARGUMENT);
/* Test initializing a pre-allocated pool specifying a pool size that
* is too small and using the default block size
*/
UtAssert_INT32_EQ(CFE_ES_PoolCreateEx(&PoolID1, Buffer1, sizeof(CFE_ES_GenPoolBD_t) / 2,
CFE_PLATFORM_ES_POOL_MAX_BUCKETS - 2, BlockSizes, CFE_ES_USE_MUTEX),
CFE_ES_BAD_ARGUMENT);
/* Test calling CFE_ES_PoolCreateEx() with NULL pointer arguments
*/
UtAssert_INT32_EQ(CFE_ES_PoolCreateEx(NULL, Buffer1, sizeof(Buffer1), CFE_PLATFORM_ES_POOL_MAX_BUCKETS, BlockSizes,
CFE_ES_USE_MUTEX),
CFE_ES_BAD_ARGUMENT);
UtAssert_INT32_EQ(CFE_ES_PoolCreateEx(&PoolID1, NULL, sizeof(Buffer1), CFE_PLATFORM_ES_POOL_MAX_BUCKETS, BlockSizes,
CFE_ES_USE_MUTEX),
CFE_ES_BAD_ARGUMENT);
/*
* Test to use default block sizes if none are given
*/
CFE_UtAssert_SUCCESS(CFE_ES_PoolCreateEx(&PoolID1, Buffer1, sizeof(Buffer1), 0, NULL, CFE_ES_USE_MUTEX));
/*
* Test creating a memory pool after the limit reached (no slots)
*/
ES_ResetUnitTest();
UT_SetDefaultReturnValue(UT_KEY(CFE_ResourceId_FindNext), OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_PoolCreateEx(&PoolID1, Buffer1, sizeof(Buffer1), CFE_PLATFORM_ES_POOL_MAX_BUCKETS,
BlockSizes, CFE_ES_USE_MUTEX),
CFE_ES_NO_RESOURCE_IDS_AVAILABLE);
/* Check operation of the CFE_ES_CheckCounterIdSlotUsed() helper function */
CFE_ES_Global.MemPoolTable[1].PoolID = CFE_ES_MEMHANDLE_C(ES_UT_MakePoolIdForIndex(1));
CFE_ES_Global.MemPoolTable[2].PoolID = CFE_ES_MEMHANDLE_UNDEFINED;
CFE_UtAssert_TRUE(CFE_ES_CheckMemPoolSlotUsed(ES_UT_MakePoolIdForIndex(1)));
CFE_UtAssert_FALSE(CFE_ES_CheckMemPoolSlotUsed(ES_UT_MakePoolIdForIndex(2)));
/*
* Test creating a memory pool with a semaphore error
*/
ES_ResetUnitTest();
UT_SetDeferredRetcode(UT_KEY(OS_MutSemCreate), 1, OS_ERROR);
UtAssert_INT32_EQ(CFE_ES_PoolCreate(&PoolID1, Buffer1, sizeof(Buffer1)), CFE_STATUS_EXTERNAL_RESOURCE_FAIL);
/*
* Test creating a memory pool with a semaphore error
* This still returns success as there is no recourse, but there
* should be a syslog about it.
*/
ES_UT_SetupMemPoolId(&PoolPtr);
OS_MutSemCreate(&PoolPtr->MutexId, "UT", 0);
UT_SetDeferredRetcode(UT_KEY(OS_MutSemDelete), 1, OS_ERROR);
PoolID1 = CFE_ES_MemPoolRecordGetID(PoolPtr);
CFE_UtAssert_SUCCESS(CFE_ES_PoolDelete(PoolID1));
/* Test initializing a pre-allocated pool specifying
* the block size with one block size set to zero
*/
ES_ResetUnitTest();
BlockSizes[0] = 10;
BlockSizes[1] = 50;
BlockSizes[2] = 100;
BlockSizes[3] = 0;
UtAssert_INT32_EQ(CFE_ES_PoolCreateEx(&PoolID1, Buffer1, sizeof(Buffer1), 4, BlockSizes, CFE_ES_USE_MUTEX),
CFE_ES_ERR_MEM_BLOCK_SIZE);
BlockSizes[0] = 10;
BlockSizes[1] = 50;
CFE_UtAssert_SUCCESS(CFE_ES_PoolCreateEx(&PoolID1, Buffer1, sizeof(Buffer1), 2, BlockSizes, CFE_ES_USE_MUTEX));
/* Test successfully creating memory pool using a mutex for
* subsequent tests
*/
ES_ResetUnitTest();
CFE_UtAssert_SUCCESS(CFE_ES_PoolCreate(&PoolID1, Buffer1, sizeof(Buffer1)));
CFE_UtAssert_SUCCESS(CFE_ES_PoolCreate(&PoolID2, Buffer2, sizeof(Buffer2)));
/* Test successfully allocating an additional pool buffer for
* subsequent tests
*/
UtAssert_INT32_EQ(CFE_ES_GetPoolBuf(&addressp1, PoolID1, 256), 256);
UtAssert_INT32_EQ(CFE_ES_GetPoolBuf(&addressp2, PoolID2, 256), 256);
/* Test getting the size of an existing pool buffer using an
* unallocated block
*/
BdPtr = ((CFE_ES_GenPoolBD_t *)addressp1) - 1;
BdPtr->Allocated ^= 717;
UtAssert_INT32_EQ(CFE_ES_GetPoolBufInfo(PoolID1, addressp1), CFE_ES_POOL_BLOCK_INVALID);
/* Test returning a pool buffer using an unallocated block */
UtAssert_INT32_EQ(CFE_ES_PutPoolBuf(PoolID1, addressp1), CFE_ES_POOL_BLOCK_INVALID);
BdPtr->Allocated ^= 717; /* repair */
/* Test getting the size of an existing pool buffer using an
* invalid check bit pattern
*/
BdPtr->Allocated = 0xaaaa;
BdPtr->CheckBits ^= 717;
UtAssert_INT32_EQ(CFE_ES_GetPoolBufInfo(PoolID1, addressp1), CFE_ES_POOL_BLOCK_INVALID);
BdPtr->CheckBits ^= 717; /* repair */
/* Test returning a pool buffer using an invalid or corrupted
* memory descriptor
*/
BdPtr->ActualSize = 0xFFFFFFFF;
UtAssert_INT32_EQ(CFE_ES_PutPoolBuf(PoolID1, addressp1), CFE_ES_POOL_BLOCK_INVALID);
/* Test getting the size of an existing pool buffer using an
* unallocated block. Use no mutex in order to get branch path coverage
*/
BdPtr = ((CFE_ES_GenPoolBD_t *)addressp2) - 1;
BdPtr->Allocated ^= 717;
UtAssert_INT32_EQ(CFE_ES_GetPoolBufInfo(PoolID2, addressp2), CFE_ES_POOL_BLOCK_INVALID);
/* Test returning a pool buffer using an unallocated block. Use no mutex
* in order to get branch path coverage
*/
UtAssert_INT32_EQ(CFE_ES_PutPoolBuf(PoolID2, addressp2), CFE_ES_POOL_BLOCK_INVALID);
BdPtr->Allocated ^= 717; /* repair */
/* Test getting the size of an existing pool buffer using an
* invalid check bit pattern. Use no mutex in order to get branch path
* coverage
*/
BdPtr->CheckBits ^= 717;
UtAssert_INT32_EQ(CFE_ES_GetPoolBufInfo(PoolID2, addressp2), CFE_ES_POOL_BLOCK_INVALID);
BdPtr->CheckBits ^= 717; /* repair */
/* Test returning a pool buffer using an invalid or corrupted
* memory descriptor. Use no mutex in order to get branch path coverage
*/
BdPtr->ActualSize = 0xFFFFFFFF;
UtAssert_INT32_EQ(CFE_ES_PutPoolBuf(PoolID2, addressp2), CFE_ES_POOL_BLOCK_INVALID);
/* Test successfully creating memory pool using a mutex for
* subsequent tests
*/
ES_ResetUnitTest();
CFE_UtAssert_SUCCESS(CFE_ES_PoolCreate(&PoolID1, Buffer1, sizeof(Buffer1)));
/* Test successfully allocating an additional pool buffer for
* subsequent tests. Use no mutex in order to get branch path coverage
*/
CFE_UtAssert_SUCCESS(CFE_ES_PoolCreate(&PoolID2, Buffer2, sizeof(Buffer2)));
/* Test successfully allocating an additional pool buffer for
* subsequent tests
*/
UtAssert_INT32_EQ(CFE_ES_GetPoolBuf(&addressp1, PoolID1, 256), 256);
UtAssert_INT32_EQ(CFE_ES_GetPoolBuf(&addressp2, PoolID2, 256), 256);
/* Test returning a pool buffer using a buffer size larger than
* the maximum
*/
BdPtr = ((CFE_ES_GenPoolBD_t *)addressp1) - 1;
BdPtr->ActualSize = CFE_PLATFORM_ES_MAX_BLOCK_SIZE + 1;
UtAssert_INT32_EQ(CFE_ES_PutPoolBuf(PoolID1, addressp1), CFE_ES_POOL_BLOCK_INVALID);
/* Test returning a pool buffer using a buffer size larger than
* the maximum. Use no mutex in order to get branch path coverage
*/
BdPtr = ((CFE_ES_GenPoolBD_t *)addressp2) - 1;
BdPtr->ActualSize = CFE_PLATFORM_ES_MAX_BLOCK_SIZE + 1;
UtAssert_INT32_EQ(CFE_ES_PutPoolBuf(PoolID2, addressp2), CFE_ES_POOL_BLOCK_INVALID);
/* Test allocating an additional pool buffer using a buffer size larger
* than the maximum
*/
UtAssert_INT32_EQ(CFE_ES_GetPoolBuf(&addressp2, PoolID1, 99000), CFE_ES_ERR_MEM_BLOCK_SIZE);
/* Test handle validation using a null handle */
CFE_UtAssert_FALSE(CFE_ES_ValidateHandle(CFE_ES_MEMHANDLE_UNDEFINED));
/* Test returning a pool buffer using a null handle */
UtAssert_INT32_EQ(CFE_ES_PutPoolBuf(CFE_ES_MEMHANDLE_UNDEFINED, addressp2), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test allocating a pool buffer using a null handle */
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_GetPoolBuf(&addressp2, CFE_ES_MEMHANDLE_UNDEFINED, 256), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test getting the size of an existing pool buffer using a null handle */
UtAssert_INT32_EQ(CFE_ES_GetPoolBufInfo(CFE_ES_MEMHANDLE_UNDEFINED, addressp1), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* Test initializing a pre-allocated pool specifying a small block size */
ES_ResetUnitTest();
BlockSizes[0] = 16;
CFE_UtAssert_SUCCESS(CFE_ES_PoolCreateEx(&PoolID1, Buffer1, 128, 1, BlockSizes, CFE_ES_USE_MUTEX));
/* Test allocating an additional pool buffer using a buffer size larger
* than the maximum.
*/
UtAssert_INT32_EQ(CFE_ES_GetPoolBuf(&addressp1, PoolID1, 32), CFE_ES_ERR_MEM_BLOCK_SIZE);
/*
* Test allocating a pool buffer where the memory block doesn't fit within
* the remaining memory. Use no mutex in order to get branch path coverage
*
* NOTE: Theoretically with a 128 byte pool this should fail after ~4 allocations.
* (16 byte block plus 12 byte BD = 28 bytes each)
*
* However due to alignment requirements of the local CPU padding might be added
* and the sizeof(BD_t) might be bigger too, resulting in fewer allocations.
*
* There should always be at least 1 successful allocation, but the number of
* successful ones is dependent on the CPU architecture and the setting of
* CFE_PLATFORM_ES_MEMPOOL_ALIGN_SIZE_MIN. Expect a failure within 20 allocations.
*/
for (i = 0; i < 25; ++i)
{
if (CFE_ES_GetPoolBuf(&addressp1, PoolID1, 12) == CFE_ES_ERR_MEM_BLOCK_SIZE)
{
break;
}
}
UtAssert_NONZERO(i);
CFE_UtAssert_ATMOST(i, 20);
/* Test getting the size of a pool buffer that is not in the pool */
UtAssert_INT32_EQ(CFE_ES_GetPoolBufInfo(PoolID1, CFE_ES_MEMPOOLBUF_C((cpuaddr)addressp1 + 400)),
CFE_ES_BUFFER_NOT_IN_POOL);
/* Test getting the size of a pool buffer with an invalid memory handle */
UtAssert_INT32_EQ(CFE_ES_PutPoolBuf(CFE_ES_MEMHANDLE_UNDEFINED, addressp1), CFE_ES_ERR_RESOURCEID_NOT_VALID);
}
/* Tests to fill gaps in coverage in SysLog */
void TestSysLog(void)
{
CFE_ES_SysLogReadBuffer_t SysLogBuffer;
char LogString[(CFE_PLATFORM_ES_SYSTEM_LOG_SIZE / 2) + 2];
char TmpString[CFE_ES_MAX_SYSLOG_MSG_SIZE + 1];
UtPrintf("Begin Test Sys Log");
/* Test loop in CFE_ES_SysLogReadStart_Unsync that ensures
* reading at the start of a message */
ES_ResetUnitTest();
CFE_ES_Global.ResetDataPtr->SystemLogWriteIdx = 0;
CFE_ES_Global.ResetDataPtr->SystemLogEndIdx = sizeof(CFE_ES_Global.ResetDataPtr->SystemLog) - 1;
memset(CFE_ES_Global.ResetDataPtr->SystemLog, 'a', CFE_ES_Global.ResetDataPtr->SystemLogEndIdx);
CFE_ES_Global.ResetDataPtr->SystemLog[CFE_ES_Global.ResetDataPtr->SystemLogEndIdx - 1] = '\n';
CFE_ES_SysLogReadStart_Unsync(&SysLogBuffer);
CFE_UtAssert_MEMOFFSET_EQ(SysLogBuffer.EndIdx, sizeof(CFE_ES_Global.ResetDataPtr->SystemLog) - 1);
CFE_UtAssert_MEMOFFSET_EQ(SysLogBuffer.LastOffset, sizeof(CFE_ES_Global.ResetDataPtr->SystemLog) - 1);
UtAssert_ZERO(SysLogBuffer.BlockSize);
UtAssert_ZERO(SysLogBuffer.SizeLeft);
/* Test truncation of a sys log message that is over half
* the size of the total log */
ES_ResetUnitTest();
memset(LogString, 'a', (CFE_PLATFORM_ES_SYSTEM_LOG_SIZE / 2) + 1);
LogString[(CFE_PLATFORM_ES_SYSTEM_LOG_SIZE / 2) + 1] = '\0';
UtAssert_INT32_EQ(CFE_ES_SysLogAppend_Unsync(LogString), CFE_ES_ERR_SYS_LOG_TRUNCATED);
/* Test code that skips writing an empty string to the sys log */
ES_ResetUnitTest();
memset(LogString, 'a', (CFE_PLATFORM_ES_SYSTEM_LOG_SIZE / 2) + 1);
LogString[0] = '\0';
CFE_UtAssert_SUCCESS(CFE_ES_SysLogAppend_Unsync(LogString));
/* Test Reading space between the current read offset and end of the log buffer */
ES_ResetUnitTest();
SysLogBuffer.EndIdx = 3;
SysLogBuffer.LastOffset = 0;
SysLogBuffer.BlockSize = 3;
SysLogBuffer.SizeLeft = 1;
CFE_ES_SysLogReadData(&SysLogBuffer);
UtAssert_UINT32_EQ(SysLogBuffer.EndIdx, 3);
CFE_UtAssert_MEMOFFSET_EQ(SysLogBuffer.LastOffset, 1);
CFE_UtAssert_MEMOFFSET_EQ(SysLogBuffer.BlockSize, 1);
UtAssert_ZERO(SysLogBuffer.SizeLeft);
/* Test nominal flow through CFE_ES_SysLogDump
* with multiple reads and writes */
ES_ResetUnitTest();
CFE_ES_Global.ResetDataPtr->SystemLogWriteIdx = 0;
CFE_ES_Global.ResetDataPtr->SystemLogEndIdx = sizeof(CFE_ES_Global.ResetDataPtr->SystemLog) - 1;
CFE_UtAssert_VOIDCALL(CFE_ES_SysLogDump("fakefilename"));
/* Test "message got truncated" */
ES_ResetUnitTest();
memset(TmpString, 'a', CFE_ES_MAX_SYSLOG_MSG_SIZE);
TmpString[CFE_ES_MAX_SYSLOG_MSG_SIZE] = '\0';
CFE_UtAssert_SUCCESS(CFE_ES_WriteToSysLog("%s", TmpString));
}
void TestBackground(void)
{
/* CFE_ES_BackgroundInit() with default setup
* causes CFE_ES_CreateChildTask to fail.
*/
ES_ResetUnitTest();
UtAssert_INT32_EQ(CFE_ES_BackgroundInit(), CFE_ES_ERR_RESOURCEID_NOT_VALID);
/* The CFE_ES_BackgroundCleanup() function has no conditionals -
* it just needs to be executed as part of this routine,
* and confirm that it deleted the semaphore.
*/
ES_ResetUnitTest();
OS_BinSemCreate(&CFE_ES_Global.BackgroundTask.WorkSem, "UT", 0, 0);
CFE_ES_BackgroundCleanup();
UtAssert_STUB_COUNT(OS_BinSemDelete, 1);
/*
* When testing the background task loop, it is normally an infinite loop,
* so this is needed to set a condition for the loop to exit.
*
* This also sets a state so the background perf log dump will be "Active" to
* execute the code which counts the number of active jobs.
*/
ES_ResetUnitTest();
memset(&CFE_ES_Global.BackgroundPerfDumpState, 0, sizeof(CFE_ES_Global.BackgroundPerfDumpState));
UT_SetDefaultReturnValue(UT_KEY(OS_write), -10);
CFE_ES_Global.BackgroundPerfDumpState.CurrentState = CFE_ES_PerfDumpState_INIT;
UT_SetDeferredRetcode(UT_KEY(OS_BinSemTimedWait), 3, -4);
CFE_ES_BackgroundTask();
CFE_UtAssert_PRINTF(UT_OSP_MESSAGES[UT_OSP_BACKGROUND_TAKE]);
/* The number of jobs running should be 1 (perf log dump) */
UtAssert_UINT32_EQ(CFE_ES_Global.BackgroundTask.NumJobsRunning, 1);
}
| 48.15769 | 120 | 0.743151 | [
"object"
] |
d2c98363dcd674f0805067089e601874bfb42c4e | 455 | h | C | backend/messageSender/Message.h | Azbesciak/MusicStreamer | 0b4f2979c937e7424dcd72e76d63690a55ce34b7 | [
"MIT"
] | null | null | null | backend/messageSender/Message.h | Azbesciak/MusicStreamer | 0b4f2979c937e7424dcd72e76d63690a55ce34b7 | [
"MIT"
] | null | null | null | backend/messageSender/Message.h | Azbesciak/MusicStreamer | 0b4f2979c937e7424dcd72e76d63690a55ce34b7 | [
"MIT"
] | null | null | null |
#include <vector>
#include <unordered_set>
using namespace std;
#ifndef MUSICSTREAMER_MESSAGE_H
#define MUSICSTREAMER_MESSAGE_H
class StreamerClient;
class Message {
unordered_set<StreamerClient*> receivers;
string content;
public:
Message(const unordered_set<StreamerClient*> &receivers, const string &message);
unordered_set<StreamerClient*> getReceivers() const;
string getContent() const;
};
#endif //MUSICSTREAMER_MESSAGE_H
| 20.681818 | 84 | 0.775824 | [
"vector"
] |
d2cdea3e5f3d993d87245e300a2916f26d24107d | 3,813 | h | C | aws-cpp-sdk-ec2/include/aws/ec2/model/GetConsoleScreenshotResponse.h | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-01-05T18:20:03.000Z | 2022-01-05T18:20:03.000Z | aws-cpp-sdk-ec2/include/aws/ec2/model/GetConsoleScreenshotResponse.h | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-ec2/include/aws/ec2/model/GetConsoleScreenshotResponse.h | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/ec2/EC2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/ec2/model/ResponseMetadata.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Xml
{
class XmlDocument;
} // namespace Xml
} // namespace Utils
namespace EC2
{
namespace Model
{
class AWS_EC2_API GetConsoleScreenshotResponse
{
public:
GetConsoleScreenshotResponse();
GetConsoleScreenshotResponse(const Aws::AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
GetConsoleScreenshotResponse& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
/**
* <p>The data that comprises the image.</p>
*/
inline const Aws::String& GetImageData() const{ return m_imageData; }
/**
* <p>The data that comprises the image.</p>
*/
inline void SetImageData(const Aws::String& value) { m_imageData = value; }
/**
* <p>The data that comprises the image.</p>
*/
inline void SetImageData(Aws::String&& value) { m_imageData = std::move(value); }
/**
* <p>The data that comprises the image.</p>
*/
inline void SetImageData(const char* value) { m_imageData.assign(value); }
/**
* <p>The data that comprises the image.</p>
*/
inline GetConsoleScreenshotResponse& WithImageData(const Aws::String& value) { SetImageData(value); return *this;}
/**
* <p>The data that comprises the image.</p>
*/
inline GetConsoleScreenshotResponse& WithImageData(Aws::String&& value) { SetImageData(std::move(value)); return *this;}
/**
* <p>The data that comprises the image.</p>
*/
inline GetConsoleScreenshotResponse& WithImageData(const char* value) { SetImageData(value); return *this;}
/**
* <p>The ID of the instance.</p>
*/
inline const Aws::String& GetInstanceId() const{ return m_instanceId; }
/**
* <p>The ID of the instance.</p>
*/
inline void SetInstanceId(const Aws::String& value) { m_instanceId = value; }
/**
* <p>The ID of the instance.</p>
*/
inline void SetInstanceId(Aws::String&& value) { m_instanceId = std::move(value); }
/**
* <p>The ID of the instance.</p>
*/
inline void SetInstanceId(const char* value) { m_instanceId.assign(value); }
/**
* <p>The ID of the instance.</p>
*/
inline GetConsoleScreenshotResponse& WithInstanceId(const Aws::String& value) { SetInstanceId(value); return *this;}
/**
* <p>The ID of the instance.</p>
*/
inline GetConsoleScreenshotResponse& WithInstanceId(Aws::String&& value) { SetInstanceId(std::move(value)); return *this;}
/**
* <p>The ID of the instance.</p>
*/
inline GetConsoleScreenshotResponse& WithInstanceId(const char* value) { SetInstanceId(value); return *this;}
inline const ResponseMetadata& GetResponseMetadata() const{ return m_responseMetadata; }
inline void SetResponseMetadata(const ResponseMetadata& value) { m_responseMetadata = value; }
inline void SetResponseMetadata(ResponseMetadata&& value) { m_responseMetadata = std::move(value); }
inline GetConsoleScreenshotResponse& WithResponseMetadata(const ResponseMetadata& value) { SetResponseMetadata(value); return *this;}
inline GetConsoleScreenshotResponse& WithResponseMetadata(ResponseMetadata&& value) { SetResponseMetadata(std::move(value)); return *this;}
private:
Aws::String m_imageData;
Aws::String m_instanceId;
ResponseMetadata m_responseMetadata;
};
} // namespace Model
} // namespace EC2
} // namespace Aws
| 28.244444 | 143 | 0.675846 | [
"model"
] |
d2d72fab47dc5821b6d12e20cdc72a81c246ae8b | 7,173 | h | C | IO/Parallel/vtkMultiBlockPLOT3DReaderInternals.h | keithroe/vtkoptix | c5bbfa0105552af3022811a7c81efec640fb810f | [
"BSD-3-Clause"
] | null | null | null | IO/Parallel/vtkMultiBlockPLOT3DReaderInternals.h | keithroe/vtkoptix | c5bbfa0105552af3022811a7c81efec640fb810f | [
"BSD-3-Clause"
] | null | null | null | IO/Parallel/vtkMultiBlockPLOT3DReaderInternals.h | keithroe/vtkoptix | c5bbfa0105552af3022811a7c81efec640fb810f | [
"BSD-3-Clause"
] | 1 | 2019-08-30T08:41:21.000Z | 2019-08-30T08:41:21.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: vtkMultiBlockPLOT3DReaderInternals.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#ifndef vtkMultiBlockPLOT3DReaderInternals_h
#define vtkMultiBlockPLOT3DReaderInternals_h
#include "vtkIOParallelModule.h" // For export macro
#include "vtkByteSwap.h"
#include "vtkMultiBlockPLOT3DReader.h"
#include "vtkSmartPointer.h"
#include "vtkStructuredGrid.h"
#include <exception>
#include <vector>
class vtkMultiProcessController;
#ifdef _WIN64
# define vtk_fseek _fseeki64
# define vtk_ftell _ftelli64
# define vtk_off_t __int64
#else
# define vtk_fseek fseek
# define vtk_ftell ftell
# define vtk_off_t long
#endif
struct vtkMultiBlockPLOT3DReaderInternals
{
struct Dims
{
Dims()
{
memset(this->Values, 0, 3*sizeof(int));
}
int Values[3];
};
std::vector<Dims> Dimensions;
std::vector<vtkSmartPointer<vtkStructuredGrid> > Blocks;
struct InternalSettings
{
int BinaryFile;
int ByteOrder;
int HasByteCount;
int MultiGrid;
int NumberOfDimensions;
int Precision; // in bytes
int IBlanking;
InternalSettings() :
BinaryFile(1),
ByteOrder(vtkMultiBlockPLOT3DReader::FILE_BIG_ENDIAN),
HasByteCount(1),
MultiGrid(0),
NumberOfDimensions(3),
Precision(4),
IBlanking(0)
{
}
};
InternalSettings Settings;
bool NeedToCheckXYZFile;
vtkMultiBlockPLOT3DReaderInternals() :
NeedToCheckXYZFile(true)
{
}
int ReadInts(FILE* fp, int n, int* val);
void CheckBinaryFile(FILE *fp, size_t fileSize);
int CheckByteOrder(FILE* fp);
int CheckByteCount(FILE* fp);
int CheckMultiGrid(FILE* fp);
int Check2DGeom(FILE* fp);
int CheckBlankingAndPrecision(FILE* fp);
int CheckCFile(FILE* fp, size_t fileSize);
size_t CalculateFileSize(int mgrid,
int precision, // in bytes
int blanking,
int ndims,
int hasByteCount,
int nGrids,
int* gridDims);
size_t CalculateFileSizeForBlock(int precision, // in bytes
int blanking,
int ndims,
int hasByteCount,
int* gridDims);
static void CalculateSkips(const int extent[6], const int wextent[6],
vtkIdType& preskip, vtkIdType& postskip)
{
vtkIdType nPtsInPlane = static_cast<vtkIdType>(wextent[1]+1)*(wextent[3]+1);
preskip = nPtsInPlane * extent[4];
postskip = nPtsInPlane * (wextent[5] - extent[5]);
}
};
namespace
{
class Plot3DException : public std::exception
{
};
}
// Description:
// vtkMultiBlockPLOT3DReaderRecord represents a data record in the file. For
// binary Plot3D files with record separators (i.e. leading and trailing length
// field per record see: https://software.intel.com/en-us/node/525311), if the
// record length is greater than 2,147,483,639 bytes, the record get split into
// multiple records. This class allows use to manage that.
// It corresponds to a complete record i.e. including all the records when split
// among multiple records due to length limit.
class VTKIOPARALLEL_EXPORT vtkMultiBlockPLOT3DReaderRecord
{
struct vtkSubRecord
{
vtkTypeUInt64 HeaderOffset;
vtkTypeUInt64 FooterOffset;
};
typedef std::vector<vtkSubRecord> VectorOfSubRecords;
VectorOfSubRecords SubRecords;
public:
// Description:
// A type for collection of sub-record separators i.e. separators encountered
// within a record when the record length is greater than 2,147,483,639 bytes.
typedef std::vector<vtkTypeUInt64> SubRecordSeparators;
// Description:
// Since a sub-record separator is made up of the trailing length field of a
// sub-record and the leading length field of the next sub-record, it's length
// is two ints.
static const int SubRecordSeparatorWidth = sizeof(int) * 2;
// Description:
// Initialize metadata about the record located at the given offset.
// This reads the file on the root node to populate record information,
// seeking and marching forward through the file if the record comprises of
// multiple sub-records. The file is reset back to the original starting
// position when done.
//
// This method has no effect for non-binary files or files that don't have
// record separators i.e. HasByteCount == 0.
bool Initialize(FILE* fp, vtkTypeUInt64 offset,
const vtkMultiBlockPLOT3DReaderInternals::InternalSettings& settings,
vtkMultiProcessController* controller);
// Description:
// Returns true if:
// 1. file doesn't comprise of records i.e. ASCII or doesn't have byte-count markers.
// 2. offset is same as the start offset for this record.
bool AtStart(vtkTypeUInt64 offset)
{
return (this->SubRecords.size()==0 || this->SubRecords.front().HeaderOffset == offset);
}
// Description:
// Returns true if:
// 1. file doesn't comprise of records i.e. ASCII or doesn't have byte-count markers.
// 2. offset is at the end of this record i.e. the start of the next record.
bool AtEnd(vtkTypeUInt64 offset)
{
return (this->SubRecords.size()==0 ||
(this->SubRecords.back().FooterOffset + sizeof(int) == offset));
}
// Description:
// Returns the location of SubRecordSeparators (bad two 4-byte ints) between startOffset and
// (startOffset + length).
SubRecordSeparators GetSubRecordSeparators(vtkTypeUInt64 startOffset, vtkTypeUInt64 length) const;
// Description:
// When reading between file offsets \c start and \c (start + length) from the file, if it has any
// sub-record separators, this method splits the read into chunks so that it
// skips the sub-record separators. The returned value is a vector of pairs
// (offset, length-in-bytes).
static std::vector<std::pair<vtkTypeUInt64, vtkTypeUInt64> > GetChunksToRead(
vtkTypeUInt64 start, vtkTypeUInt64 length, const std::vector<vtkTypeUInt64> &markers);
// Description:
// If the block in file (start, start+length) steps over sub-record separators
// within this record, then this method will return a new length that includes
// the bytes for the separators to be skipped. Otherwise, simply returns the
// length.
vtkTypeUInt64 GetLengthWithSeparators(vtkTypeUInt64 start, vtkTypeUInt64 length) const;
std::vector<std::pair<vtkTypeUInt64, vtkTypeUInt64> > GetChunksToRead(
vtkTypeUInt64 start, vtkTypeUInt64 length) const
{
return this->GetChunksToRead(start, length, this->GetSubRecordSeparators(start, length));
}
};
#endif
// VTK-HeaderTest-Exclude: vtkMultiBlockPLOT3DReaderInternals.h
| 33.518692 | 101 | 0.689809 | [
"vector"
] |
d2d76cff015496aa999a95c48b003d9e8caae41a | 9,638 | c | C | device/sensor/drv/drv_acc_mir3_da213B.c | jinlongliu/AliOS-Things | ce051172a775f987183e7aca88bb6f3b809ea7b0 | [
"Apache-2.0"
] | 4 | 2019-03-12T11:04:48.000Z | 2019-10-22T06:06:53.000Z | device/sensor/drv/drv_acc_mir3_da213B.c | IamBaoMouMou/AliOS-Things | 195a9160b871b3d78de6f8cf6c2ab09a71977527 | [
"Apache-2.0"
] | 3 | 2018-12-17T13:06:46.000Z | 2018-12-28T01:40:59.000Z | device/sensor/drv/drv_acc_mir3_da213B.c | IamBaoMouMou/AliOS-Things | 195a9160b871b3d78de6f8cf6c2ab09a71977527 | [
"Apache-2.0"
] | 2 | 2018-01-23T07:54:08.000Z | 2018-01-23T11:38:59.000Z | /*
* Copyright (C) 2015-2017 Alibaba Group Holding Limited
*
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <aos/aos.h>
#include <vfs_conf.h>
#include <vfs_err.h>
#include <vfs_register.h>
#include <hal/base.h>
#include "common.h"
#include "sensor.h"
#include "sensor_drv_api.h"
#include "sensor_hal.h"
#define NSA_REG_SPI_I2C 0x00
#define NSA_REG_WHO_AM_I 0x01
#define NSA_REG_ACC_X_LSB 0x02
#define NSA_REG_ACC_X_MSB 0x03
#define NSA_REG_ACC_Y_LSB 0x04
#define NSA_REG_ACC_Y_MSB 0x05
#define NSA_REG_ACC_Z_LSB 0x06
#define NSA_REG_ACC_Z_MSB 0x07
#define NSA_REG_MOTION_FLAG 0x09
#define NSA_REG_NEWDATA_FLAG 0x0A
#define NSA_REG_G_RANGE 0x0f
#define NSA_REG_ODR_AXIS_DISABLE 0x10
#define NSA_REG_POWERMODE_BW 0x11
#define NSA_REG_SWAP_POLARITY 0x12
#define NSA_REG_INTERRUPT_SETTINGS0 0x15
#define NSA_REG_INTERRUPT_SETTINGS1 0x16
#define NSA_REG_INTERRUPT_SETTINGS2 0x17
#define NSA_REG_INTERRUPT_MAPPING1 0x19
#define NSA_REG_INTERRUPT_MAPPING2 0x1a
#define NSA_REG_INTERRUPT_MAPPING3 0x1b
#define NSA_REG_INT_PIN_CONFIG 0x20
#define NSA_REG_INT_LATCH 0x21
#define NSA_REG_ACTIVE_DURATION 0x27
#define NSA_REG_ACTIVE_THRESHOLD 0x28
#define NSA_REG_CUSTOM_OFFSET_X 0x38
#define NSA_REG_CUSTOM_OFFSET_Y 0x39
#define NSA_REG_CUSTOM_OFFSET_Z 0x3a
#define NSA_REG_ENGINEERING_MODE 0x7f
#define NSA_REG_SENSITIVITY_TRIM_X 0x80
#define NSA_REG_SENSITIVITY_TRIM_Y 0x81
#define NSA_REG_SENSITIVITY_TRIM_Z 0x82
#define NSA_REG_COARSE_OFFSET_TRIM_X 0x83
#define NSA_REG_COARSE_OFFSET_TRIM_Y 0x84
#define NSA_REG_COARSE_OFFSET_TRIM_Z 0x85
#define NSA_REG_FINE_OFFSET_TRIM_X 0x86
#define NSA_REG_FINE_OFFSET_TRIM_Y 0x87
#define NSA_REG_FINE_OFFSET_TRIM_Z 0x88
#define NSA_REG_SENS_COMP 0x8c
#define NSA_REG_SENS_COARSE_TRIM 0xd1
#define DA213B_NORMAL_MODE 0x00
#define DA213B_SUSPEND_MODE 0x01
#define DA213B_I2C_SLAVE_ADDR (0x27)
#define DA213B_ACC_DATA_SIZE 6
#define DA213B_CHIP_ID_VAL 0x13
#define DA213B_ADDR_TRANS(n) ((n) << 1)
#define DA213B_GET_BITSLICE(regvar, bitname) ((regvar & bitname##__MSK) >> bitname##__POS)
#define DA213B_SET_BITSLICE(regvar, bitname, val) ((regvar & ~bitname##__MSK) | ((val<<bitname##__POS)&bitname##__MSK))
i2c_dev_t da213B_ctx = {
.port = 2,
.config.address_width = 8,
.config.freq = 100000,
.config.dev_addr = DA213B_ADDR_TRANS(DA213B_I2C_SLAVE_ADDR)
};
static int drv_acc_mir3_da213B_validate_id(i2c_dev_t* drv, uint8_t id_value)
{
int ret = 0;
uint8_t value = 0;
if(drv == NULL){
return -1;
}
ret = sensor_i2c_read(drv, NSA_REG_WHO_AM_I, &value, I2C_DATA_LEN, I2C_OP_RETRIES);
if(unlikely(ret)) {
return ret;
}
if (id_value != value){
return -1;
}
return 0;
}
static int drv_acc_mir3_da213B_set_power_mode(i2c_dev_t* drv, dev_power_mode_e mode)
{
int ret = 0;
uint8_t dev_mode;
switch(mode){
case DEV_POWER_OFF:
case DEV_SLEEP:{
dev_mode = (uint8_t)0x80;
break;
}
case DEV_POWER_ON:{
dev_mode = (uint8_t)0x34;
break;
}
default:return -1;
}
ret = sensor_i2c_write(drv, NSA_REG_POWERMODE_BW, &dev_mode, I2C_DATA_LEN, I2C_OP_RETRIES);
if(unlikely(ret)) {
return ret;
}
return 0;
}
static int drv_acc_mir3_da213B_set_default_config(i2c_dev_t* drv)
{
int ret = 0;
uint8_t value = 0;
value = 0x83;
ret = sensor_i2c_write(drv, NSA_REG_ENGINEERING_MODE,
&value, I2C_DATA_LEN, I2C_OP_RETRIES);
if (unlikely(ret)) {
return ret;
}
value = 0x69;
ret = sensor_i2c_write(drv, NSA_REG_ENGINEERING_MODE,
&value, I2C_DATA_LEN, I2C_OP_RETRIES);
if (unlikely(ret)) {
return ret;
}
value = 0xbd;
ret = sensor_i2c_write(drv, NSA_REG_ENGINEERING_MODE,
&value, I2C_DATA_LEN, I2C_OP_RETRIES);
if (unlikely(ret)) {
return ret;
}
ret = sensor_i2c_read(drv, 0x8e, &value, I2C_DATA_LEN, I2C_OP_RETRIES);
if (unlikely(ret)) {
return ret;
}
if (value == 0) {
value = 0x50;
ret = sensor_i2c_write(drv, 0x8e, &value, I2C_DATA_LEN, I2C_OP_RETRIES);
if (unlikely(ret)) {
return ret;
}
}
value = 0x40;
ret = sensor_i2c_write(drv, NSA_REG_G_RANGE,
&value, I2C_DATA_LEN, I2C_OP_RETRIES);
if (unlikely(ret)) {
return ret;
}
value = 0x00;
ret = sensor_i2c_write(drv, NSA_REG_INT_PIN_CONFIG,
&value, I2C_DATA_LEN, I2C_OP_RETRIES);
if (unlikely(ret)) {
return ret;
}
ret = drv_acc_mir3_da213B_set_power_mode(drv, DEV_SLEEP);
if (unlikely(ret)) {
return ret;
}
value = 0x07;
ret = sensor_i2c_write(drv, NSA_REG_ODR_AXIS_DISABLE,
&value, I2C_DATA_LEN, I2C_OP_RETRIES);
if (unlikely(ret)) {
return ret;
}
value = 0x04;
ret = sensor_i2c_write(drv, NSA_REG_INTERRUPT_MAPPING2,
&value, I2C_DATA_LEN, I2C_OP_RETRIES);
if (unlikely(ret)) {
return ret;
}
value = 0x04;
ret = sensor_i2c_write(drv, NSA_REG_INTERRUPT_SETTINGS0,
&value, I2C_DATA_LEN, I2C_OP_RETRIES);
if (unlikely(ret)) {
return ret;
}
return 0;
}
static void drv_acc_mir3_da213B_irq_handle(void)
{
/* no handle so far */
}
static int drv_acc_mir3_da213B_open(void)
{
int ret = 0;
ret = drv_acc_mir3_da213B_set_power_mode(&da213B_ctx, DEV_POWER_ON);
if(unlikely(ret)) {
return -1;
}
LOG("%s %s successfully \n", SENSOR_STR, __func__);
return 0;
}
static int drv_acc_mir3_da213B_close(void)
{
int ret = 0;
ret = drv_acc_mir3_da213B_set_power_mode(&da213B_ctx, DEV_POWER_OFF);
if(unlikely(ret)) {
return -1;
}
LOG("%s %s successfully \n", SENSOR_STR, __func__);
return 0;
}
static int drv_acc_mir3_da213B_read(void *buf, size_t len)
{
int ret = 0;
size_t size;
uint8_t acc_raw[DA213B_ACC_DATA_SIZE] = {0};
accel_data_t* pdata = (accel_data_t*)buf;
if(buf == NULL){
return -1;
}
size = sizeof(accel_data_t);
if(len < size){
return -1;
}
ret = sensor_i2c_read(&da213B_ctx, NSA_REG_ACC_X_LSB, acc_raw, DA213B_ACC_DATA_SIZE, I2C_OP_RETRIES);
if (unlikely(ret)) {
return -1;
}
pdata->data[0] = (int32_t)((int16_t)(acc_raw[1] << 8 | acc_raw[0]) >> 4);
pdata->data[1] = (int32_t)((int16_t)(acc_raw[3] << 8 | acc_raw[2]) >> 4);
pdata->data[2] = (int32_t)((int16_t)(acc_raw[5] << 8 | acc_raw[4]) >> 4);
pdata->timestamp = aos_now_ms();
return (int)size;
}
static int drv_acc_mir3_da213B_write(const void *buf, size_t len)
{
(void)buf;
(void)len;
return 0;
}
static int drv_acc_mir3_da213B_ioctl(int cmd, unsigned long arg)
{
int ret = 0;
switch (cmd) {
case SENSOR_IOCTL_SET_POWER:{
ret = drv_acc_mir3_da213B_set_power_mode(&da213B_ctx, arg);
if(unlikely(ret)) {
return -1;
}
}break;
case SENSOR_IOCTL_GET_INFO:{
/* fill the dev info here */
dev_sensor_info_t *info = (dev_sensor_info_t *)arg;
info->model = "DA213B";
info->unit = mg;
}break;
default:
return -1;
}
LOG("%s %s successfully \n", SENSOR_STR, __func__);
return 0;
}
int drv_acc_mir3_da213B_init(void)
{
int ret = 0;
sensor_obj_t sensor;
memset(&sensor, 0, sizeof(sensor));
/* fill the sensor obj parameters here */
sensor.tag = TAG_DEV_ACC;
sensor.path = dev_acc_path;
sensor.io_port = I2C_PORT;
sensor.open = drv_acc_mir3_da213B_open;
sensor.close = drv_acc_mir3_da213B_close;
sensor.read = drv_acc_mir3_da213B_read;
sensor.write = drv_acc_mir3_da213B_write;
sensor.ioctl = drv_acc_mir3_da213B_ioctl;
sensor.irq_handle = drv_acc_mir3_da213B_irq_handle;
ret = sensor_create_obj(&sensor);
if(unlikely(ret)) {
return -1;
}
ret = drv_acc_mir3_da213B_validate_id(&da213B_ctx, DA213B_CHIP_ID_VAL);
if(unlikely(ret)) {
return -1;
}
ret = drv_acc_mir3_da213B_set_default_config(&da213B_ctx);
if(unlikely(ret)) {
return -1;
}
LOG("%s %s successfully \n", SENSOR_STR, __func__);
return 0;
}
| 28.599407 | 126 | 0.577298 | [
"model"
] |
d2d91af6ff828551a84ddebb7a05aa020b03ecfa | 3,829 | h | C | dbms/src/Interpreters/PredicateExpressionsOptimizer.h | anrodigina/ClickHouse | 7a4dc5a212ccbf8d0730db2d3fb25fc23574d803 | [
"Apache-2.0"
] | null | null | null | dbms/src/Interpreters/PredicateExpressionsOptimizer.h | anrodigina/ClickHouse | 7a4dc5a212ccbf8d0730db2d3fb25fc23574d803 | [
"Apache-2.0"
] | 4 | 2020-01-28T22:10:11.000Z | 2021-08-25T14:46:07.000Z | dbms/src/Interpreters/PredicateExpressionsOptimizer.h | anrodigina/ClickHouse | 7a4dc5a212ccbf8d0730db2d3fb25fc23574d803 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "DatabaseAndTableWithAlias.h"
#include "ExpressionAnalyzer.h"
#include <Parsers/ASTSelectQuery.h>
#include <map>
namespace DB
{
class ASTIdentifier;
class ASTSubquery;
class Context;
/** This class provides functions for Push-Down predicate expressions
*
* The Example:
* - Query before optimization :
* SELECT id_1, name_1 FROM (SELECT id_1, name_1 FROM table_a UNION ALL SELECT id_2, name_2 FROM table_b)
* WHERE id_1 = 1
* - Query after optimization :
* SELECT id_1, name_1 FROM (SELECT id_1, name_1 FROM table_a WHERE id_1 = 1 UNION ALL SELECT id_2, name_2 FROM table_b WHERE id_2 = 1)
* WHERE id_1 = 1
* For more details : https://github.com/yandex/ClickHouse/pull/2015#issuecomment-374283452
*/
class PredicateExpressionsOptimizer
{
using ProjectionWithAlias = std::pair<ASTPtr, String>;
using SubqueriesProjectionColumns = std::map<ASTSelectQuery *, std::vector<ProjectionWithAlias>>;
using IdentifierWithQualifier = std::pair<ASTIdentifier *, String>;
/// Extracts settings, mostly to show which are used and which are not.
struct ExtractedSettings
{
/// QueryNormalizer settings
const UInt64 max_ast_depth;
const UInt64 max_expanded_ast_elements;
const String count_distinct_implementation;
/// for PredicateExpressionsOptimizer
const bool enable_optimize_predicate_expression;
template<typename T>
ExtractedSettings(const T & settings)
: max_ast_depth(settings.max_ast_depth),
max_expanded_ast_elements(settings.max_expanded_ast_elements),
count_distinct_implementation(settings.count_distinct_implementation),
enable_optimize_predicate_expression(settings.enable_optimize_predicate_expression)
{}
};
public:
PredicateExpressionsOptimizer(ASTSelectQuery * ast_select_, ExtractedSettings && settings_, const Context & context_);
bool optimize();
private:
ASTSelectQuery * ast_select;
const ExtractedSettings settings;
const Context & context;
enum OptimizeKind
{
NONE,
PUSH_TO_PREWHERE,
PUSH_TO_WHERE,
PUSH_TO_HAVING,
};
bool isArrayJoinFunction(const ASTPtr & node);
std::vector<ASTPtr> splitConjunctionPredicate(const ASTPtr & predicate_expression);
std::vector<IdentifierWithQualifier> getDependenciesAndQualifiers(ASTPtr & expression,
std::vector<TableWithColumnNames> & tables_with_aliases);
bool optimizeExpression(const ASTPtr & outer_expression, ASTSelectQuery * subquery, ASTSelectQuery::Expression expr);
bool optimizeImpl(const ASTPtr & outer_expression, const SubqueriesProjectionColumns & subqueries_projection_columns, OptimizeKind optimize_kind);
bool allowPushDown(const ASTSelectQuery * subquery);
bool canPushDownOuterPredicate(const std::vector<ProjectionWithAlias> & subquery_projection_columns,
const std::vector<IdentifierWithQualifier> & outer_predicate_dependencies,
OptimizeKind & optimize_kind);
void setNewAliasesForInnerPredicate(const std::vector<ProjectionWithAlias> & projection_columns,
const std::vector<IdentifierWithQualifier> & inner_predicate_dependencies);
SubqueriesProjectionColumns getAllSubqueryProjectionColumns();
void getSubqueryProjectionColumns(const ASTPtr & subquery, SubqueriesProjectionColumns & all_subquery_projection_columns);
ASTs getSelectQueryProjectionColumns(ASTPtr & ast);
ASTs evaluateAsterisk(ASTSelectQuery * select_query, const ASTPtr & asterisk);
void cleanExpressionAlias(ASTPtr & expression);
};
}
| 37.539216 | 150 | 0.71533 | [
"vector"
] |
d2d97c2e57d2f0a8098f1a46e046f030f43d514a | 3,836 | h | C | parsers/http/include/zapata/http/HTTPTokenizerbase.h | naazgull/zapata | e5734ff88a17b261a2f4547fa47f01dbb1a69d84 | [
"Unlicense"
] | 9 | 2016-08-10T16:51:23.000Z | 2020-04-08T22:07:47.000Z | parsers/http/include/zapata/http/HTTPTokenizerbase.h | naazgull/zapata | e5734ff88a17b261a2f4547fa47f01dbb1a69d84 | [
"Unlicense"
] | 78 | 2015-02-25T15:16:02.000Z | 2021-10-31T15:58:15.000Z | parsers/http/include/zapata/http/HTTPTokenizerbase.h | naazgull/zapata | e5734ff88a17b261a2f4547fa47f01dbb1a69d84 | [
"Unlicense"
] | 7 | 2015-01-13T14:39:21.000Z | 2018-11-24T06:48:09.000Z | // Generated by Bisonc++ V6.03.00 on Wed, 16 Sep 2020 17:20:23 -44452020
// hdr/includes
#ifndef zptHTTPTokenizerBase_h_included
#define zptHTTPTokenizerBase_h_included
#include <exception>
#include <vector>
#include <iostream>
// $insert preincludes
#include <zapata/http/HTTPinc.h>
// hdr/baseclass
namespace // anonymous
{
struct PI_;
}
// $insert namespace-open
namespace zpt {
class HTTPTokenizerBase {
public:
enum DebugMode_ { OFF = 0, ON = 1 << 0, ACTIONCASES = 1 << 1 };
// $insert tokens
// Symbolic tokens:
enum Tokens_ {
METHOD = 257,
HTTP_VERSION,
URL,
STATUS,
CR_LF,
COLON,
STRING,
SPACE,
BODY,
QMARK,
EQ,
E,
};
// $insert STYPE
typedef int STYPE_;
private:
// state semval
typedef std::pair<size_t, STYPE_> StatePair;
// token semval
typedef std::pair<int, STYPE_> TokenPair;
int d_stackIdx = -1;
std::vector<StatePair> d_stateStack;
StatePair* d_vsp = 0; // points to the topmost value stack
size_t d_state = 0;
TokenPair d_next;
int d_token;
bool d_terminalToken = false;
bool d_recovery = false;
protected:
enum Return_ {
PARSE_ACCEPT_ = 0, // values used as parse()'s return values
PARSE_ABORT_ = 1
};
enum ErrorRecovery_ {
UNEXPECTED_TOKEN_,
};
bool d_actionCases_ = false; // set by options/directives
bool d_debug_ = true;
size_t d_requiredTokens_;
size_t d_nErrors_; // initialized by clearin()
size_t d_acceptedTokens_;
STYPE_ d_val_;
HTTPTokenizerBase();
void ABORT() const;
void ACCEPT() const;
void ERROR() const;
STYPE_& vs_(int idx); // value stack element idx
int lookup_() const;
int savedToken_() const;
int token_() const;
size_t stackSize_() const;
size_t state_() const;
size_t top_() const;
void clearin_();
void errorVerbose_();
void lex_(int token);
void popToken_();
void pop_(size_t count = 1);
void pushToken_(int token);
void push_(size_t nextState);
void redoToken_();
bool recovery_() const;
void reduce_(int rule);
void shift_(int state);
void startRecovery_();
public:
void setDebug(bool mode);
void setDebug(DebugMode_ mode);
};
// hdr/abort
inline void
HTTPTokenizerBase::ABORT() const {
throw PARSE_ABORT_;
}
// hdr/accept
inline void
HTTPTokenizerBase::ACCEPT() const {
throw PARSE_ACCEPT_;
}
// hdr/error
inline void
HTTPTokenizerBase::ERROR() const {
throw UNEXPECTED_TOKEN_;
}
// hdr/savedtoken
inline int
HTTPTokenizerBase::savedToken_() const {
return d_next.first;
}
// hdr/opbitand
inline HTTPTokenizerBase::DebugMode_
operator&(HTTPTokenizerBase::DebugMode_ lhs, HTTPTokenizerBase::DebugMode_ rhs) {
return static_cast<HTTPTokenizerBase::DebugMode_>(static_cast<int>(lhs) & rhs);
}
// hdr/opbitor
inline HTTPTokenizerBase::DebugMode_
operator|(HTTPTokenizerBase::DebugMode_ lhs, HTTPTokenizerBase::DebugMode_ rhs) {
return static_cast<HTTPTokenizerBase::DebugMode_>(static_cast<int>(lhs) | rhs);
};
// hdr/recovery
inline bool
HTTPTokenizerBase::recovery_() const {
return d_recovery;
}
// hdr/stacksize
inline size_t
HTTPTokenizerBase::stackSize_() const {
return d_stackIdx + 1;
}
// hdr/state
inline size_t
HTTPTokenizerBase::state_() const {
return d_state;
}
// hdr/token
inline int
HTTPTokenizerBase::token_() const {
return d_token;
}
// hdr/vs
inline HTTPTokenizerBase::STYPE_&
HTTPTokenizerBase::vs_(int idx) {
return (d_vsp + idx)->second;
}
// hdr/tail
// For convenience, when including ParserBase.h its symbols are available as
// symbols in the class Parser, too.
#define HTTPTokenizer HTTPTokenizerBase
// $insert namespace-close
}
#endif
| 20.513369 | 83 | 0.673879 | [
"vector"
] |
d2d9d6ffcebf4188ceae29a3691c55042a46fc92 | 1,761 | h | C | src/console/model/timeaggregationmodel.h | KDE/kuserfeedback | 7dea960e4e83a5a002ad9d3fd53ad32c9b46e96c | [
"MIT",
"BSD-3-Clause"
] | 7 | 2017-04-26T07:00:24.000Z | 2020-07-30T10:19:36.000Z | src/console/model/timeaggregationmodel.h | KDE/kuserfeedback | 7dea960e4e83a5a002ad9d3fd53ad32c9b46e96c | [
"MIT",
"BSD-3-Clause"
] | null | null | null | src/console/model/timeaggregationmodel.h | KDE/kuserfeedback | 7dea960e4e83a5a002ad9d3fd53ad32c9b46e96c | [
"MIT",
"BSD-3-Clause"
] | 3 | 2017-06-17T19:16:07.000Z | 2021-12-13T20:40:51.000Z | /*
SPDX-FileCopyrightText: 2016 Volker Krause <vkrause@kde.org>
SPDX-License-Identifier: MIT
*/
#ifndef KUSERFEEDBACK_CONSOLE_TIMEAGGREGATIONMODEL_H
#define KUSERFEEDBACK_CONSOLE_TIMEAGGREGATIONMODEL_H
#include <QAbstractTableModel>
#include <QDateTime>
#include <QVector>
namespace KUserFeedback {
namespace Console {
class Sample;
class TimeAggregationModel : public QAbstractTableModel
{
Q_OBJECT
public:
enum AggregationMode {
AggregateYear,
AggregateMonth,
AggregateWeek,
AggregateDay
};
enum Role {
DateTimeRole = Qt::UserRole + 1,
MaximumValueRole,
TimeDisplayRole,
DataDisplayRole,
AccumulatedDisplayRole,
SamplesRole,
AllSamplesRole
};
explicit TimeAggregationModel(QObject *parent = nullptr);
~TimeAggregationModel() override;
void setSourceModel(QAbstractItemModel *model);
AggregationMode aggregationMode() const;
void setAggregationMode(AggregationMode mode);
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
private:
void reload();
QDateTime aggregate(const QDateTime &dt) const;
QString timeToString(const QDateTime &dt) const;
QAbstractItemModel *m_sourceModel = nullptr;
struct Data {
QDateTime time;
QVector<Sample> samples;
};
QVector<Data> m_data;
int m_maxValue = 0;
AggregationMode m_mode = AggregateYear;
};
}
}
#endif // KUSERFEEDBACK_CONSOLE_TIMEAGGREGATIONMODEL_H
| 24.458333 | 91 | 0.717774 | [
"model"
] |
d2e2f79d48b3b2ae50255365c38ec5c7b49bc5d3 | 1,787 | h | C | libgpopt/include/gpopt/xforms/CXformProject2ComputeScalar.h | khannaekta/gporca | 94e509d0a2456851a2cabf02e933c3523946b87b | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-03-05T10:08:56.000Z | 2019-03-05T10:08:56.000Z | libgpopt/include/gpopt/xforms/CXformProject2ComputeScalar.h | khannaekta/gporca | 94e509d0a2456851a2cabf02e933c3523946b87b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | libgpopt/include/gpopt/xforms/CXformProject2ComputeScalar.h | khannaekta/gporca | 94e509d0a2456851a2cabf02e933c3523946b87b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | //---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2011 EMC Corp.
//
// @filename:
// CXformProject2ComputeScalar.h
//
// @doc:
// Transform Project to ComputeScalar
//---------------------------------------------------------------------------
#ifndef GPOPT_CXformProject2ComputeScalar_H
#define GPOPT_CXformProject2ComputeScalar_H
#include "gpos/base.h"
#include "gpopt/xforms/CXformImplementation.h"
namespace gpopt
{
using namespace gpos;
//---------------------------------------------------------------------------
// @class:
// CXformProject2ComputeScalar
//
// @doc:
// Transform Project to ComputeScalar
//
//---------------------------------------------------------------------------
class CXformProject2ComputeScalar : public CXformImplementation
{
private:
// private copy ctor
CXformProject2ComputeScalar(const CXformProject2ComputeScalar &);
public:
// ctor
explicit
CXformProject2ComputeScalar(IMemoryPool *pmp);
// dtor
virtual
~CXformProject2ComputeScalar()
{}
// ident accessors
virtual
EXformId Exfid() const
{
return ExfProject2ComputeScalar;
}
virtual
const CHAR *SzId() const
{
return "CXformProject2ComputeScalar";
}
// compute xform promise for a given expression handle
virtual
EXformPromise Exfp
(
CExpressionHandle &exprhdl
)
const
{
if (exprhdl.Pdpscalar(1)->FHasSubquery())
{
return CXform::ExfpNone;
}
return CXform::ExfpHigh;
}
// actual transform
virtual
void Transform(CXformContext *, CXformResult *, CExpression *) const;
}; // class CXformProject2ComputeScalar
}
#endif // !GPOPT_CXformProject2ComputeScalar_H
// EOF
| 20.306818 | 78 | 0.573587 | [
"transform"
] |
d2e47c958f5afca4a34b677dea411f249d2eb22f | 8,482 | h | C | aws-cpp-sdk-neptune/include/aws/neptune/model/DomainMembership.h | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-neptune/include/aws/neptune/model/DomainMembership.h | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-neptune/include/aws/neptune/model/DomainMembership.h | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/neptune/Neptune_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Xml
{
class XmlNode;
} // namespace Xml
} // namespace Utils
namespace Neptune
{
namespace Model
{
/**
* <p>An Active Directory Domain membership record associated with the DB
* instance.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/neptune-2014-10-31/DomainMembership">AWS
* API Reference</a></p>
*/
class AWS_NEPTUNE_API DomainMembership
{
public:
DomainMembership();
DomainMembership(const Aws::Utils::Xml::XmlNode& xmlNode);
DomainMembership& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);
void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
void OutputToStream(Aws::OStream& oStream, const char* location) const;
/**
* <p>The identifier of the Active Directory Domain.</p>
*/
inline const Aws::String& GetDomain() const{ return m_domain; }
/**
* <p>The identifier of the Active Directory Domain.</p>
*/
inline bool DomainHasBeenSet() const { return m_domainHasBeenSet; }
/**
* <p>The identifier of the Active Directory Domain.</p>
*/
inline void SetDomain(const Aws::String& value) { m_domainHasBeenSet = true; m_domain = value; }
/**
* <p>The identifier of the Active Directory Domain.</p>
*/
inline void SetDomain(Aws::String&& value) { m_domainHasBeenSet = true; m_domain = std::move(value); }
/**
* <p>The identifier of the Active Directory Domain.</p>
*/
inline void SetDomain(const char* value) { m_domainHasBeenSet = true; m_domain.assign(value); }
/**
* <p>The identifier of the Active Directory Domain.</p>
*/
inline DomainMembership& WithDomain(const Aws::String& value) { SetDomain(value); return *this;}
/**
* <p>The identifier of the Active Directory Domain.</p>
*/
inline DomainMembership& WithDomain(Aws::String&& value) { SetDomain(std::move(value)); return *this;}
/**
* <p>The identifier of the Active Directory Domain.</p>
*/
inline DomainMembership& WithDomain(const char* value) { SetDomain(value); return *this;}
/**
* <p>The status of the DB instance's Active Directory Domain membership, such as
* joined, pending-join, failed etc).</p>
*/
inline const Aws::String& GetStatus() const{ return m_status; }
/**
* <p>The status of the DB instance's Active Directory Domain membership, such as
* joined, pending-join, failed etc).</p>
*/
inline bool StatusHasBeenSet() const { return m_statusHasBeenSet; }
/**
* <p>The status of the DB instance's Active Directory Domain membership, such as
* joined, pending-join, failed etc).</p>
*/
inline void SetStatus(const Aws::String& value) { m_statusHasBeenSet = true; m_status = value; }
/**
* <p>The status of the DB instance's Active Directory Domain membership, such as
* joined, pending-join, failed etc).</p>
*/
inline void SetStatus(Aws::String&& value) { m_statusHasBeenSet = true; m_status = std::move(value); }
/**
* <p>The status of the DB instance's Active Directory Domain membership, such as
* joined, pending-join, failed etc).</p>
*/
inline void SetStatus(const char* value) { m_statusHasBeenSet = true; m_status.assign(value); }
/**
* <p>The status of the DB instance's Active Directory Domain membership, such as
* joined, pending-join, failed etc).</p>
*/
inline DomainMembership& WithStatus(const Aws::String& value) { SetStatus(value); return *this;}
/**
* <p>The status of the DB instance's Active Directory Domain membership, such as
* joined, pending-join, failed etc).</p>
*/
inline DomainMembership& WithStatus(Aws::String&& value) { SetStatus(std::move(value)); return *this;}
/**
* <p>The status of the DB instance's Active Directory Domain membership, such as
* joined, pending-join, failed etc).</p>
*/
inline DomainMembership& WithStatus(const char* value) { SetStatus(value); return *this;}
/**
* <p>The fully qualified domain name of the Active Directory Domain.</p>
*/
inline const Aws::String& GetFQDN() const{ return m_fQDN; }
/**
* <p>The fully qualified domain name of the Active Directory Domain.</p>
*/
inline bool FQDNHasBeenSet() const { return m_fQDNHasBeenSet; }
/**
* <p>The fully qualified domain name of the Active Directory Domain.</p>
*/
inline void SetFQDN(const Aws::String& value) { m_fQDNHasBeenSet = true; m_fQDN = value; }
/**
* <p>The fully qualified domain name of the Active Directory Domain.</p>
*/
inline void SetFQDN(Aws::String&& value) { m_fQDNHasBeenSet = true; m_fQDN = std::move(value); }
/**
* <p>The fully qualified domain name of the Active Directory Domain.</p>
*/
inline void SetFQDN(const char* value) { m_fQDNHasBeenSet = true; m_fQDN.assign(value); }
/**
* <p>The fully qualified domain name of the Active Directory Domain.</p>
*/
inline DomainMembership& WithFQDN(const Aws::String& value) { SetFQDN(value); return *this;}
/**
* <p>The fully qualified domain name of the Active Directory Domain.</p>
*/
inline DomainMembership& WithFQDN(Aws::String&& value) { SetFQDN(std::move(value)); return *this;}
/**
* <p>The fully qualified domain name of the Active Directory Domain.</p>
*/
inline DomainMembership& WithFQDN(const char* value) { SetFQDN(value); return *this;}
/**
* <p>The name of the IAM role to be used when making API calls to the Directory
* Service.</p>
*/
inline const Aws::String& GetIAMRoleName() const{ return m_iAMRoleName; }
/**
* <p>The name of the IAM role to be used when making API calls to the Directory
* Service.</p>
*/
inline bool IAMRoleNameHasBeenSet() const { return m_iAMRoleNameHasBeenSet; }
/**
* <p>The name of the IAM role to be used when making API calls to the Directory
* Service.</p>
*/
inline void SetIAMRoleName(const Aws::String& value) { m_iAMRoleNameHasBeenSet = true; m_iAMRoleName = value; }
/**
* <p>The name of the IAM role to be used when making API calls to the Directory
* Service.</p>
*/
inline void SetIAMRoleName(Aws::String&& value) { m_iAMRoleNameHasBeenSet = true; m_iAMRoleName = std::move(value); }
/**
* <p>The name of the IAM role to be used when making API calls to the Directory
* Service.</p>
*/
inline void SetIAMRoleName(const char* value) { m_iAMRoleNameHasBeenSet = true; m_iAMRoleName.assign(value); }
/**
* <p>The name of the IAM role to be used when making API calls to the Directory
* Service.</p>
*/
inline DomainMembership& WithIAMRoleName(const Aws::String& value) { SetIAMRoleName(value); return *this;}
/**
* <p>The name of the IAM role to be used when making API calls to the Directory
* Service.</p>
*/
inline DomainMembership& WithIAMRoleName(Aws::String&& value) { SetIAMRoleName(std::move(value)); return *this;}
/**
* <p>The name of the IAM role to be used when making API calls to the Directory
* Service.</p>
*/
inline DomainMembership& WithIAMRoleName(const char* value) { SetIAMRoleName(value); return *this;}
private:
Aws::String m_domain;
bool m_domainHasBeenSet;
Aws::String m_status;
bool m_statusHasBeenSet;
Aws::String m_fQDN;
bool m_fQDNHasBeenSet;
Aws::String m_iAMRoleName;
bool m_iAMRoleNameHasBeenSet;
};
} // namespace Model
} // namespace Neptune
} // namespace Aws
| 33.928 | 121 | 0.663641 | [
"model"
] |
d2e8ee32a6dc47831d475ae4e7c62c7d530663f8 | 14,175 | h | C | src/pbaas/notarization.h | reclaim-privacy/btq | 7463d7411d05ea487eec3f2c457bdd82187697d9 | [
"Unlicense"
] | 5 | 2020-10-09T05:47:25.000Z | 2022-03-22T08:38:48.000Z | src/pbaas/notarization.h | reclaim-privacy/btq | 7463d7411d05ea487eec3f2c457bdd82187697d9 | [
"Unlicense"
] | null | null | null | src/pbaas/notarization.h | reclaim-privacy/btq | 7463d7411d05ea487eec3f2c457bdd82187697d9 | [
"Unlicense"
] | 1 | 2018-05-18T01:16:53.000Z | 2018-05-18T01:16:53.000Z | /********************************************************************
* (C) 2019 Michael Toutonghi
*
* Distributed under the MIT software license, see the accompanying
* file COPYING or http://www.opensource.org/licenses/mit-license.php.
*
* This defines the public blockchains as a service (PBaaS) notarization protocol, VerusLink.
* VerusLink is a new distributed consensus protocol that enables multiple public blockchains
* to operate as a decentralized ecosystem of chains, which can interact and easily engage in cross
* chain transactions.
*
* In all notarization services, there is notarizing chain and a chain paying notarization rewards. They are not the same.
* The notarizing chain earns the right to submit notarizations onto the paying chain, which uses provable Verus chain power
* of each chain combined with a confirmation process to validate the correct version of one chain to another and vice versa.
* Generally, the paying chain will be Verus, and the notarizing chain will be the PBaaS chain started with a root of Verus
* notarization.
*
* On each chain, notarizations spend the output of the prior transaction that spent the notarization output, which has some spending
* rules that create a thread of one attempted notarization per block, each of them properly representing the current chain, whether
* the prior transaction represents a valid representation of the other chain or not. In order to move the notarization forward,
* it must also be accepted onto the paying chain, then referenced to move confirmed notarization forward again on the current chain.
* All notarization threads are started with a chain definition on the paying chain, or at block 1 on the PBaaS chain.
*
* Every notarization besides the chain definition is initiated on the PBaaS chain as an effort to create a notarization that is accepted
* and confirmed on the paying chain by first being accepted by a Verus miner before a more valuable
* notarization is completed and available for acceptance, then being confirmed by multiple cross notarizations.
*
* A notarization submission is earned when a block is won by staking or mining on the PBaaS chain. The miner puts a notarization
* of the paying chain into the block mined, spending the notarization thread. In order for the miner to have a transaction output to spend from,
* all PBaaS chains have a block 1 output of a small, transferable amount of Verus, which is only used as a notarization thread.
*
* After "n" blocks, currently 8, from the block won, the earned notarization may be submitted, proving the last notarization and
* including an MMR root that is 8 blocks after the asserted winning block, which must also be proven along with at least one staked block.
* Once accepted and confirmed, the notarization transaction itself may be used to spend from the pool of notarization rewards,
* with an output that pays 50% to the notary and 50% to the block miner/staker recipient on the paying chain.
*
* A notarizaton must be either the first in the chain or refer to a prior notarization with which it agrees. If it skips existing
* notarizations, referring to a prior notarization as valid, that is the same as asserting that the skipped notarizations are invalid.
* In that case, the notarization and 2 after it must prove one additional block since the notarization skipped.
*
* The intent is to make it extremely improbable cryptographically to achieve full confirmation of any notarization unless an alternate
* fork actually represents a valid chain with a majority of combined work and stake, even if more than the majority of notarizers are
* attempting to notarize an invalid chain.
*
* to accept an earned notarization as valid on the Verus blockchain, it must prove a transaction on the alternate chain, which is
* either the original chain definition transaction, which CAN and MUST be proven ONLY in block 1, or the latest notarization transaction
* on the alternate chain that represents an accurate MMR for the accepting chain.
* In addition, any accepted notarization must fullfill the following requirements:
* 1) Must prove either a PoS block from the alternate chain or a merge mined
* block that is owned by the submitter and exactly 8 blocks behind the submitted MMR, which is used for proof.
* 2) must prove a chain definition tx and be block 1 or contain a notarization tx, which asserts a previous, valid MMR for this
* chain and properly proves objects using that MMR, as well as has the proper notarization thread inputs and outputs.
* 3) must spend the notarization thread to the specified chainID in a fee free transaction with notarization thread input and output
*
* to agree with a previous notarization, we must:
* 1) agree that at the indicated block height, the MMR root is the root claimed, and is a correct representation of the best chain.
*
*/
#ifndef NOTARIZATION_H
#define NOTARIZATION_H
#include "pbaas/pbaas.h"
#include "key_io.h"
// This is the data for a PBaaS notarization transaction, either of a PBaaS chain into the Verus chain, or the Verus
// chain into a PBaaS chain.
// Part of a transaction with an opret that contains only the hashes and proofs, without the source
// headers, transactions, and objects. This type of notarizatoin is mined into a block by the miner, and is created on the PBaaS
// chain.
//
// Notarizations include the following elements in order:
// Latest block header being notarized, or a header ref for a merge-mined header
// Proof of the header using the latest MMR root
// Cross notarization transaction less its op_ret
// Proof of the cross notarization using the latest MMR root
class CPBaaSNotarization
{
public:
static const int FINAL_CONFIRMATIONS = 10;
static const int MIN_BLOCKS_BETWEEN_ACCEPTED = 8;
static const int CURRENT_VERSION = PBAAS_VERSION;
uint32_t nVersion; // PBAAS version
uint160 chainID; // chain being notarized
uint160 notaryKeyID; // confirmed notary rewards are spent to this address when this notarization is confirmed
uint32_t notarizationHeight; // height of the notarization we certify
uint256 mmrRoot; // latest MMR root of the notarization height
uint256 notarizationPreHash; // combination of block hash, merkle root, and compact power for the notarization height
uint256 compactPower; // compact power of the block height notarization to compare
uint256 prevNotarization; // txid of the prior notarization on this chain that we agree with, even those not accepted yet
int32_t prevHeight;
uint256 crossNotarization; // hash of previous notarization transaction on the other chain, which is the first tx object in the opret input
int32_t crossHeight;
COpRetProof opRetProof; // hashes and types of all objects in our opret, enabling reconstruction without the opret on notarized chain
std::vector<CNodeData> nodes; // network nodes
CPBaaSNotarization() : nVersion(PBAAS_VERSION_INVALID) { }
CPBaaSNotarization(uint32_t version,
uint160 chainid,
uint160 notarykey,
int32_t notarizationheight,
uint256 MMRRoot,
uint256 preHash,
uint256 compactpower,
uint256 prevnotarization,
int32_t prevheight,
uint256 crossnotarization,
int32_t crossheight,
COpRetProof orp,
std::vector<CNodeData> &Nodes) :
nVersion(version),
chainID(chainid),
notaryKeyID(notarykey),
notarizationHeight(notarizationheight),
mmrRoot(MMRRoot),
notarizationPreHash(preHash),
compactPower(compactpower),
prevNotarization(prevnotarization),
prevHeight(prevheight),
crossNotarization(crossnotarization),
crossHeight(crossheight),
opRetProof(orp),
nodes(Nodes)
{ }
CPBaaSNotarization(const std::vector<unsigned char> &asVector)
{
::FromVector(asVector, *this);
}
CPBaaSNotarization(const CTransaction &tx, bool validate = false);
CPBaaSNotarization(const UniValue &obj);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(VARINT(nVersion));
READWRITE(chainID);
READWRITE(notaryKeyID);
READWRITE(notarizationHeight);
READWRITE(mmrRoot);
READWRITE(notarizationPreHash);
READWRITE(compactPower);
READWRITE(prevNotarization);
READWRITE(prevHeight);
READWRITE(crossNotarization);
READWRITE(crossHeight);
READWRITE(opRetProof);
READWRITE(nodes);
}
std::vector<unsigned char> AsVector()
{
return ::AsVector(*this);
}
bool IsValid()
{
return !mmrRoot.IsNull();
}
UniValue ToUniValue() const;
};
class CNotarizationFinalization
{
public:
int32_t confirmedInput;
CNotarizationFinalization() : confirmedInput(-1) {}
CNotarizationFinalization(int32_t nIn) : confirmedInput(nIn) {}
CNotarizationFinalization(std::vector<unsigned char> vch)
{
::FromVector(vch, *this);
}
CNotarizationFinalization(const CTransaction &tx, bool validate=false);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(confirmedInput);
}
bool IsValid()
{
return confirmedInput != -1;
}
std::vector<unsigned char> AsVector()
{
return ::AsVector(*this);
}
UniValue ToUniValue() const
{
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("confirmedinput", confirmedInput));
return ret;
}
};
class CChainNotarizationData
{
public:
static const int CURRENT_VERSION = PBAAS_VERSION;
uint32_t version;
std::vector<std::pair<uint256, CPBaaSNotarization>> vtx;
int32_t lastConfirmed; // last confirmed notarization
std::vector<std::vector<int32_t>> forks; // chains that represent alternate branches from the last confirmed notarization
int32_t bestChain; // index in forks of the chain, beginning with the last confirmed notarization, that has the most power
CChainNotarizationData() : version(0), lastConfirmed(-1) {}
CChainNotarizationData(uint32_t ver, int32_t start, int32_t end,
std::vector<std::pair<uint256, CPBaaSNotarization>> txes,
int32_t lastConf,
std::vector<std::vector<int32_t>> &Forks,
int32_t Best) :
version(ver),
vtx(txes), lastConfirmed(lastConf), bestChain(Best), forks(Forks) {}
CChainNotarizationData(std::vector<unsigned char> vch)
{
::FromVector(vch, *this);
}
CChainNotarizationData(UniValue &obj);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(version);
READWRITE(vtx);
READWRITE(bestChain);
READWRITE(forks);
}
std::vector<unsigned char> AsVector()
{
return ::AsVector(*this);
}
bool IsValid()
{
// this needs an actual check
return version != 0;
}
bool IsConfirmed()
{
return lastConfirmed != -1;
}
UniValue ToUniValue() const;
};
class CInputDescriptor
{
public:
CScript scriptPubKey;
CAmount nValue;
CTxIn txIn;
CInputDescriptor() : nValue(0) {}
CInputDescriptor(CScript script, CAmount value, CTxIn input) : scriptPubKey(script), nValue(value), txIn(input) {}
};
bool CreateEarnedNotarization(CMutableTransaction &mnewTx, std::vector<CInputDescriptor> &inputs, CTransaction &lastTx, CTransaction &crossTx, int32_t height, int32_t *confirmedInput, CTxDestination *confirmedDest);
uint256 CreateAcceptedNotarization(const CBlock &blk, int32_t txIndex, int32_t height);
std::vector<CInputDescriptor> AddSpendsAndFinalizations(const CChainNotarizationData &cnd,
const uint256 &lastNotarizationID,
const CTransaction &lastTx,
CMutableTransaction &mnewTx,
int32_t *pConfirmedInput,
int32_t *pConfirmedIdx,
CTxDestination *pConfirmedDest);
bool GetNotarizationAndFinalization(int32_t ecode, CMutableTransaction mtx, CPBaaSNotarization &pbn, uint32_t *pNotarizeOutIndex, uint32_t *pFinalizeOutIndex);
bool ValidateEarnedNotarization(CTransaction &ntx, CPBaaSNotarization *notarization = NULL);
bool ValidateEarnedNotarization(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn);
bool IsEarnedNotarizationInput(const CScript &scriptSig);
bool ValidateAcceptedNotarization(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn);
bool IsAcceptedNotarizationInput(const CScript &scriptSig);
bool ValidateFinalizeNotarization(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn);
bool IsFinalizeNotarizationInput(const CScript &scriptSig);
bool IsServiceRewardInput(const CScript &scriptSig);
bool IsBlockBoundTransaction(const CTransaction &tx);
#endif
| 46.782178 | 215 | 0.681834 | [
"object",
"vector"
] |
d2e960d88147f77ceefa81212f6ee09a690070bd | 18,206 | h | C | WickedEngine/shaders/ShaderInterop_Renderer.h | niansa/WickedEngine | f728b1beef81dd907f2ae0f1401de9705a9b20c5 | [
"MIT"
] | null | null | null | WickedEngine/shaders/ShaderInterop_Renderer.h | niansa/WickedEngine | f728b1beef81dd907f2ae0f1401de9705a9b20c5 | [
"MIT"
] | null | null | null | WickedEngine/shaders/ShaderInterop_Renderer.h | niansa/WickedEngine | f728b1beef81dd907f2ae0f1401de9705a9b20c5 | [
"MIT"
] | null | null | null | #ifndef WI_SHADERINTEROP_RENDERER_H
#define WI_SHADERINTEROP_RENDERER_H
#include "ShaderInterop.h"
#include "ShaderInterop_Weather.h"
struct ShaderScene
{
int instancebuffer;
int meshbuffer;
int materialbuffer;
int envmaparray;
int globalenvmap;
int padding0;
int padding1;
int padding2;
int TLAS;
int BVH_counter;
int BVH_nodes;
int BVH_primitives;
float3 aabb_min;
float padding3;
float3 aabb_max;
float padding4;
float3 aabb_extents; // enclosing AABB abs(max - min)
float padding5;
float3 aabb_extents_rcp; // enclosing AABB 1.0f / abs(max - min)
float padding6;
ShaderWeather weather;
};
static const uint SHADERMATERIAL_OPTION_BIT_USE_VERTEXCOLORS = 1 << 0;
static const uint SHADERMATERIAL_OPTION_BIT_SPECULARGLOSSINESS_WORKFLOW = 1 << 1;
static const uint SHADERMATERIAL_OPTION_BIT_OCCLUSION_PRIMARY = 1 << 2;
static const uint SHADERMATERIAL_OPTION_BIT_OCCLUSION_SECONDARY = 1 << 3;
static const uint SHADERMATERIAL_OPTION_BIT_USE_WIND = 1 << 4;
static const uint SHADERMATERIAL_OPTION_BIT_RECEIVE_SHADOW = 1 << 5;
static const uint SHADERMATERIAL_OPTION_BIT_CAST_SHADOW = 1 << 6;
static const uint SHADERMATERIAL_OPTION_BIT_DOUBLE_SIDED = 1 << 7;
static const uint SHADERMATERIAL_OPTION_BIT_TRANSPARENT = 1 << 8;
static const uint SHADERMATERIAL_OPTION_BIT_ADDITIVE = 1 << 9;
static const uint SHADERMATERIAL_OPTION_BIT_UNLIT = 1 << 10;
struct ShaderMaterial
{
float4 baseColor;
float4 subsurfaceScattering;
float4 subsurfaceScattering_inv;
float4 texMulAdd;
float roughness;
float reflectance;
float metalness;
float refraction;
float normalMapStrength;
float parallaxOcclusionMapping;
float alphaTest;
float displacementMapping;
float transmission;
uint options;
uint emissive_r11g11b10;
uint specular_r11g11b10;
uint layerMask;
int uvset_baseColorMap;
int uvset_surfaceMap;
int uvset_normalMap;
int uvset_displacementMap;
int uvset_emissiveMap;
int uvset_occlusionMap;
int uvset_transmissionMap;
int uvset_sheenColorMap;
int uvset_sheenRoughnessMap;
int uvset_clearcoatMap;
int uvset_clearcoatRoughnessMap;
int uvset_clearcoatNormalMap;
int uvset_specularMap;
int padding2;
int padding3;
uint sheenColor_r11g11b10;
float sheenRoughness;
float clearcoat;
float clearcoatRoughness;
int texture_basecolormap_index;
int texture_surfacemap_index;
int texture_emissivemap_index;
int texture_normalmap_index;
int texture_displacementmap_index;
int texture_occlusionmap_index;
int texture_transmissionmap_index;
int texture_sheencolormap_index;
int texture_sheenroughnessmap_index;
int texture_clearcoatmap_index;
int texture_clearcoatroughnessmap_index;
int texture_clearcoatnormalmap_index;
int texture_specularmap_index;
int padding5;
int padding6;
int padding7;
#ifndef __cplusplus
float3 GetEmissive() { return Unpack_R11G11B10_FLOAT(emissive_r11g11b10); }
float3 GetSpecular() { return Unpack_R11G11B10_FLOAT(specular_r11g11b10); }
float3 GetSheenColor() { return Unpack_R11G11B10_FLOAT(sheenColor_r11g11b10); }
#endif // __cplusplus
inline bool IsUsingVertexColors() { return options & SHADERMATERIAL_OPTION_BIT_USE_VERTEXCOLORS; }
inline bool IsUsingSpecularGlossinessWorkflow() { return options & SHADERMATERIAL_OPTION_BIT_SPECULARGLOSSINESS_WORKFLOW; }
inline bool IsOcclusionEnabled_Primary() { return options & SHADERMATERIAL_OPTION_BIT_OCCLUSION_PRIMARY; }
inline bool IsOcclusionEnabled_Secondary() { return options & SHADERMATERIAL_OPTION_BIT_OCCLUSION_SECONDARY; }
inline bool IsUsingWind() { return options & SHADERMATERIAL_OPTION_BIT_USE_WIND; }
inline bool IsReceiveShadow() { return options & SHADERMATERIAL_OPTION_BIT_RECEIVE_SHADOW; }
inline bool IsCastingShadow() { return options & SHADERMATERIAL_OPTION_BIT_CAST_SHADOW; }
inline bool IsUnlit() { return options & SHADERMATERIAL_OPTION_BIT_UNLIT; }
};
static const uint SHADERMESH_FLAG_DOUBLE_SIDED = 1 << 0;
static const uint SHADERMESH_FLAG_HAIRPARTICLE = 1 << 1;
static const uint SHADERMESH_FLAG_EMITTEDPARTICLE = 1 << 2;
struct ShaderMesh
{
int ib;
int vb_pos_nor_wind;
int vb_tan;
int vb_col;
int vb_uv0;
int vb_uv1;
int vb_atl;
int vb_pre;
int subsetbuffer;
uint blendmaterial1;
uint blendmaterial2;
uint blendmaterial3;
float3 aabb_min;
uint flags;
float3 aabb_max;
float tessellation_factor;
void init()
{
ib = -1;
vb_pos_nor_wind = -1;
vb_tan = -1;
vb_col = -1;
vb_uv0 = -1;
vb_uv1 = -1;
vb_atl = -1;
vb_pre = -1;
subsetbuffer = -1;
blendmaterial1 = 0;
blendmaterial2 = 0;
blendmaterial3 = 0;
aabb_min = float3(0, 0, 0);
aabb_max = float3(0, 0, 0);
flags = 0;
}
};
struct ShaderMeshSubset
{
uint indexOffset;
uint materialIndex;
void init()
{
indexOffset = 0;
materialIndex = 0;
}
};
struct ShaderTransform
{
float4 mat0;
float4 mat1;
float4 mat2;
void init()
{
mat0 = float4(1, 0, 0, 0);
mat1 = float4(0, 1, 0, 0);
mat2 = float4(0, 0, 1, 0);
}
void Create(float4x4 mat)
{
mat0 = float4(mat._11, mat._21, mat._31, mat._41);
mat1 = float4(mat._12, mat._22, mat._32, mat._42);
mat2 = float4(mat._13, mat._23, mat._33, mat._43);
}
float4x4 GetMatrix()
#ifdef __cplusplus
const
#endif // __cplusplus
{
return float4x4(
mat0.x, mat0.y, mat0.z, mat0.w,
mat1.x, mat1.y, mat1.z, mat1.w,
mat2.x, mat2.y, mat2.z, mat2.w,
0, 0, 0, 1
);
}
};
struct ShaderMeshInstance
{
uint uid;
uint flags;
uint meshIndex;
uint color;
uint emissive;
int lightmap;
int padding0;
int padding1;
ShaderTransform transform;
ShaderTransform transformInverseTranspose; // This correctly handles non uniform scaling for normals
ShaderTransform transformPrev;
void init()
{
uid = 0;
flags = 0;
meshIndex = ~0;
color = ~0u;
emissive = ~0u;
lightmap = -1;
transform.init();
transformInverseTranspose.init();
transformPrev.init();
}
};
struct ShaderMeshInstancePointer
{
uint instanceID;
uint userdata;
void init()
{
instanceID = ~0;
userdata = 0;
}
void Create(uint _instanceID, uint frustum_index, float dither)
{
instanceID = _instanceID;
userdata = 0;
userdata |= frustum_index & 0xF;
userdata |= (uint(dither * 255.0f) & 0xFF) << 4u;
}
uint GetFrustumIndex()
{
return userdata & 0xF;
}
float GetDither()
{
return ((userdata >> 4u) & 0xFF) / 255.0f;
}
};
struct ObjectPushConstants
{
uint meshIndex_subsetIndex; // 24-bit mesh, 8-bit subset
uint materialIndex;
int instances;
uint instance_offset;
void init(
uint _meshIndex,
uint _subsetIndex,
uint _materialIndex,
int _instances,
uint _instance_offset
)
{
meshIndex_subsetIndex = 0;
meshIndex_subsetIndex |= _meshIndex & 0xFFFFFF;
meshIndex_subsetIndex |= (_subsetIndex & 0xFF) << 24u;
materialIndex = _materialIndex;
instances = _instances;
instance_offset = _instance_offset;
}
uint GetMeshIndex()
{
return meshIndex_subsetIndex & 0xFFFFFF;
}
uint GetSubsetIndex()
{
return (meshIndex_subsetIndex >> 24u) & 0xFF;
}
uint GetMaterialIndex()
{
return materialIndex;
}
};
struct PrimitiveID
{
uint primitiveIndex;
uint instanceIndex;
uint subsetIndex;
uint2 pack()
{
// 32 bit primitiveID
// 24 bit instanceID
// 8 bit subsetID
return uint2(primitiveIndex, (instanceIndex & 0xFFFFFF) | ((subsetIndex & 0xFF) << 24u));
}
void unpack(uint2 value)
{
primitiveIndex = value.x;
instanceIndex = value.y & 0xFFFFFF;
subsetIndex = (value.y >> 24u) & 0xFF;
}
};
// Warning: the size of this structure directly affects shader performance.
// Try to reduce it as much as possible!
// Keep it aligned to 16 bytes for best performance!
// Right now, this is 48 bytes total
struct ShaderEntity
{
float3 position;
uint type8_flags8_range16;
uint2 direction16_coneAngleCos16;
uint energy16_X16; // 16 bits free
uint color;
uint layerMask;
uint indices;
uint cubeRemap;
uint userdata;
#ifndef __cplusplus
// Shader-side:
inline uint GetType()
{
return type8_flags8_range16 & 0xFF;
}
inline uint GetFlags()
{
return (type8_flags8_range16 >> 8) & 0xFF;
}
inline float GetRange()
{
return f16tof32((type8_flags8_range16 >> 16) & 0xFFFF);
}
inline float3 GetDirection()
{
return float3(
f16tof32(direction16_coneAngleCos16.x & 0xFFFF),
f16tof32((direction16_coneAngleCos16.x >> 16) & 0xFFFF),
f16tof32(direction16_coneAngleCos16.y & 0xFFFF)
);
}
inline float GetConeAngleCos()
{
return f16tof32((direction16_coneAngleCos16.y >> 16) & 0xFFFF);
}
inline float GetEnergy()
{
return f16tof32(energy16_X16 & 0xFFFF);
}
inline float GetCubemapDepthRemapNear()
{
return f16tof32(cubeRemap & 0xFFFF);
}
inline float GetCubemapDepthRemapFar()
{
return f16tof32((cubeRemap >> 16) & 0xFFFF);
}
inline float4 GetColor()
{
float4 fColor;
fColor.x = (float)((color >> 0) & 0xFF) / 255.0f;
fColor.y = (float)((color >> 8) & 0xFF) / 255.0f;
fColor.z = (float)((color >> 16) & 0xFF) / 255.0f;
fColor.w = (float)((color >> 24) & 0xFF) / 255.0f;
return fColor;
}
inline uint GetMatrixIndex()
{
return indices & 0xFFFF;
}
inline uint GetTextureIndex()
{
return (indices >> 16) & 0xFFFF;
}
inline bool IsCastingShadow()
{
return indices != ~0;
}
// Load decal props:
inline float GetEmissive() { return GetEnergy(); }
#else
// Application-side:
inline void SetType(uint type)
{
type8_flags8_range16 |= type & 0xFF;
}
inline void SetFlags(uint flags)
{
type8_flags8_range16 |= (flags & 0xFF) << 8;
}
inline void SetRange(float value)
{
type8_flags8_range16 |= XMConvertFloatToHalf(value) << 16;
}
inline void SetDirection(float3 value)
{
direction16_coneAngleCos16.x |= XMConvertFloatToHalf(value.x);
direction16_coneAngleCos16.x |= XMConvertFloatToHalf(value.y) << 16;
direction16_coneAngleCos16.y |= XMConvertFloatToHalf(value.z);
}
inline void SetConeAngleCos(float value)
{
direction16_coneAngleCos16.y |= XMConvertFloatToHalf(value) << 16;
}
inline void SetEnergy(float value)
{
energy16_X16 |= XMConvertFloatToHalf(value);
}
inline void SetCubeRemapNear(float value)
{
cubeRemap |= XMConvertFloatToHalf(value);
}
inline void SetCubeRemapFar(float value)
{
cubeRemap |= XMConvertFloatToHalf(value) << 16;
}
inline void SetIndices(uint matrixIndex, uint textureIndex)
{
indices = matrixIndex & 0xFFFF;
indices |= (textureIndex & 0xFFFF) << 16;
}
#endif // __cplusplus
};
static const uint ENTITY_TYPE_DIRECTIONALLIGHT = 0;
static const uint ENTITY_TYPE_POINTLIGHT = 1;
static const uint ENTITY_TYPE_SPOTLIGHT = 2;
static const uint ENTITY_TYPE_DECAL = 100;
static const uint ENTITY_TYPE_ENVMAP = 101;
static const uint ENTITY_TYPE_FORCEFIELD_POINT = 200;
static const uint ENTITY_TYPE_FORCEFIELD_PLANE = 201;
static const uint ENTITY_FLAG_LIGHT_STATIC = 1 << 0;
static const uint SHADER_ENTITY_COUNT = 256;
static const uint SHADER_ENTITY_TILE_BUCKET_COUNT = SHADER_ENTITY_COUNT / 32;
static const uint MATRIXARRAY_COUNT = 128;
static const uint TILED_CULLING_BLOCKSIZE = 16;
static const uint TILED_CULLING_THREADSIZE = 8;
static const uint TILED_CULLING_GRANULARITY = TILED_CULLING_BLOCKSIZE / TILED_CULLING_THREADSIZE;
static const int impostorCaptureAngles = 36;
// These option bits can be read from Options constant buffer value:
static const uint OPTION_BIT_TEMPORALAA_ENABLED = 1 << 0;
static const uint OPTION_BIT_TRANSPARENTSHADOWS_ENABLED = 1 << 1;
static const uint OPTION_BIT_VOXELGI_ENABLED = 1 << 2;
static const uint OPTION_BIT_VOXELGI_REFLECTIONS_ENABLED = 1 << 3;
static const uint OPTION_BIT_VOXELGI_RETARGETTED = 1 << 4;
static const uint OPTION_BIT_SIMPLE_SKY = 1 << 5;
static const uint OPTION_BIT_REALISTIC_SKY = 1 << 6;
static const uint OPTION_BIT_HEIGHT_FOG = 1 << 7;
static const uint OPTION_BIT_RAYTRACED_SHADOWS = 1 << 8;
static const uint OPTION_BIT_SHADOW_MASK = 1 << 9;
static const uint OPTION_BIT_SURFELGI_ENABLED = 1 << 10;
static const uint OPTION_BIT_DISABLE_ALBEDO_MAPS = 1 << 11;
static const uint OPTION_BIT_FORCE_DIFFUSE_LIGHTING = 1 << 12;
static const uint OPTION_BIT_STATIC_SKY_HDR = 1 << 13;
// ---------- Common Constant buffers: -----------------
struct FrameCB
{
uint Options; // wiRenderer bool options packed into bitmask
uint ShadowCascadeCount;
float ShadowKernel2D;
float ShadowKernelCube;
float Time;
float TimePrev;
float DeltaTime;
uint FrameCount;
float3 VoxelRadianceDataCenter; // center of the voxel grid in world space units
float VoxelRadianceMaxDistance; // maximum raymarch distance for voxel GI in world-space
float VoxelRadianceDataSize; // voxel half-extent in world space units
float VoxelRadianceDataSize_rcp; // 1.0 / voxel-half extent
uint VoxelRadianceDataRes; // voxel grid resolution
float VoxelRadianceDataRes_rcp; // 1.0 / voxel grid resolution
uint VoxelRadianceDataMIPs; // voxel grid mipmap count
uint VoxelRadianceNumCones; // number of diffuse cones to trace
float VoxelRadianceNumCones_rcp; // 1.0 / number of diffuse cones to trace
float VoxelRadianceRayStepSize; // raymarch step size in voxel space units
uint EnvProbeMipCount;
float EnvProbeMipCount_rcp;
uint LightArrayOffset; // indexing into entity array
uint LightArrayCount; // indexing into entity array
uint DecalArrayOffset; // indexing into entity array
uint DecalArrayCount; // indexing into entity array
uint ForceFieldArrayOffset; // indexing into entity array
uint ForceFieldArrayCount; // indexing into entity array
uint EnvProbeArrayOffset; // indexing into entity array
uint EnvProbeArrayCount; // indexing into entity array
uint TemporalAASampleRotation;
float BlueNoisePhase;
int sampler_objectshader_index;
int texture_random64x64_index;
int texture_bluenoise_index;
int texture_sheenlut_index;
int texture_skyviewlut_index;
int texture_transmittancelut_index;
int texture_multiscatteringlut_index;
int texture_skyluminancelut_index;
int texture_shadowarray_2d_index;
int texture_shadowarray_cube_index;
int texture_shadowarray_transparent_2d_index;
int texture_shadowarray_transparent_cube_index;
int texture_voxelgi_index;
int buffer_entityarray_index;
int buffer_entitymatrixarray_index;
int padding0;
ShaderScene scene;
};
struct CameraCB
{
float4x4 VP; // View*Projection
float4 ClipPlane;
float3 CamPos;
float DistanceFromOrigin;
float3 At;
float ZNearP;
float3 Up;
float ZFarP;
float ZNearP_rcp;
float ZFarP_rcp;
float ZRange;
float ZRange_rcp;
float4x4 View;
float4x4 Proj;
float4x4 InvV; // Inverse View
float4x4 InvP; // Inverse Projection
float4x4 InvVP; // Inverse View-Projection
// Frustum planes:
// 0 : near
// 1 : far
// 2 : left
// 3 : right
// 4 : top
// 5 : bottom
float4 FrustumPlanes[6];
float2 TemporalAAJitter;
float2 TemporalAAJitterPrev;
float4x4 PrevV;
float4x4 PrevP;
float4x4 PrevVP; // PrevView*PrevProjection
float4x4 PrevInvVP; // Inverse(PrevView*PrevProjection)
float4x4 ReflVP; // ReflectionView*ReflectionProjection
float4x4 Reprojection; // view_projection_inverse_matrix * previous_view_projection_matrix
float2 ApertureShape;
float ApertureSize;
float FocalLength;
float2 CanvasSize;
float2 CanvasSize_rcp;
uint2 InternalResolution;
float2 InternalResolution_rcp;
uint3 EntityCullingTileCount;
int padding0;
int texture_depth_index;
int texture_lineardepth_index;
int texture_gbuffer0_index;
int texture_gbuffer1_index;
int buffer_entitytiles_opaque_index;
int buffer_entitytiles_transparent_index;
int texture_reflection_index;
int texture_refraction_index;
int texture_waterriples_index;
int texture_ao_index;
int texture_ssr_index;
int texture_rtshadow_index;
int texture_surfelgi_index;
int texture_depth_index_prev;
int padding1;
int padding2;
};
CONSTANTBUFFER(g_xFrame, FrameCB, CBSLOT_RENDERER_FRAME);
CONSTANTBUFFER(g_xCamera, CameraCB, CBSLOT_RENDERER_CAMERA);
// ------- On demand Constant buffers: ----------
CBUFFER(MiscCB, CBSLOT_RENDERER_MISC)
{
float4x4 g_xTransform;
float4 g_xColor;
};
CBUFFER(ForwardEntityMaskCB, CBSLOT_RENDERER_FORWARD_LIGHTMASK)
{
uint2 xForwardLightMask; // supports indexing 64 lights
uint xForwardDecalMask; // supports indexing 32 decals
uint xForwardEnvProbeMask; // supports indexing 32 environment probes
};
CBUFFER(VolumeLightCB, CBSLOT_RENDERER_VOLUMELIGHT)
{
float4x4 lightWorld;
float4 lightColor;
float4 lightEnerdis;
};
struct LensFlarePush
{
float3 xLensFlarePos;
float xLensFlareOffset;
float2 xLensFlareSize;
float2 xLensFlare_padding;
};
struct CubemapRenderCam
{
float4x4 VP;
uint4 properties;
};
CBUFFER(CubemapRenderCB, CBSLOT_RENDERER_CUBEMAPRENDER)
{
CubemapRenderCam xCubemapRenderCams[6];
};
// MIP Generator params:
static const uint GENERATEMIPCHAIN_1D_BLOCK_SIZE = 64;
static const uint GENERATEMIPCHAIN_2D_BLOCK_SIZE = 8;
static const uint GENERATEMIPCHAIN_3D_BLOCK_SIZE = 4;
struct MipgenPushConstants
{
uint3 outputResolution;
uint arrayIndex;
float3 outputResolution_rcp;
uint mipgen_options;
int texture_input;
int texture_output;
int sampler_index;
};
static const uint MIPGEN_OPTION_BIT_PRESERVE_COVERAGE = 1 << 0;
struct FilterEnvmapPushConstants
{
uint2 filterResolution;
float2 filterResolution_rcp;
uint filterArrayIndex;
float filterRoughness;
uint filterRayCount;
uint padding_filterCB;
int texture_input;
int texture_output;
};
// CopyTexture2D params:
struct CopyTextureCB
{
int2 xCopyDest;
int2 xCopySrcSize;
int2 padding0;
int xCopySrcMIP;
int xCopyBorderExpandStyle;
};
static const uint PAINT_TEXTURE_BLOCKSIZE = 8;
struct PaintTextureCB
{
uint2 xPaintBrushCenter;
uint xPaintBrushRadius;
float xPaintBrushAmount;
float xPaintBrushFalloff;
uint xPaintBrushColor;
uint2 padding0;
};
CBUFFER(PaintRadiusCB, CBSLOT_RENDERER_MISC)
{
uint2 xPaintRadResolution;
uint2 xPaintRadCenter;
uint xPaintRadUVSET;
float xPaintRadRadius;
uint2 pad;
};
struct SkinningPushConstants
{
int bonebuffer_index;
int vb_pos_nor_wind;
int vb_tan;
int vb_bon;
int so_pos_nor_wind;
int so_tan;
};
#endif // WI_SHADERINTEROP_RENDERER_H
| 23.767624 | 124 | 0.756344 | [
"mesh",
"transform"
] |
d2eca06920e4e89a8cb5f6e9fb45805d697d59ff | 6,944 | h | C | api/kilosim/World.h | jtebert/kilosim | cf7448950dd19e956ae75a605b3d28001f3bc310 | [
"MIT"
] | 6 | 2020-04-07T10:22:10.000Z | 2021-06-30T15:42:08.000Z | api/kilosim/World.h | jtebert/kilosim | cf7448950dd19e956ae75a605b3d28001f3bc310 | [
"MIT"
] | 3 | 2019-09-13T17:20:18.000Z | 2021-02-18T20:22:40.000Z | api/kilosim/World.h | jtebert/kilosim | cf7448950dd19e956ae75a605b3d28001f3bc310 | [
"MIT"
] | 2 | 2020-03-07T16:54:46.000Z | 2020-07-21T14:03:03.000Z | /*
Kilobot simulator where the simulator is no longer the master
Created 2018-10 by Julia Ebert
Based on Kilobot simulator by Michael Rubenstein
*/
#ifndef __KILOSIM_H
#define __KILOSIM_H
#include <kilosim/Robot.h>
#include <kilosim/LightPattern.h>
#include <kilosim/CollisionBoxes.h>
#include <kilosim/Timer.h>
#include <SFML/Graphics.hpp>
#include <string>
#ifdef _OPENMP
#include <omp.h>
#endif
namespace Kilosim
{
/*!
* The `World` provides the base environment for running simulations. It
* represents a two-dimensional bounded arena for simulating Kilobots.
*
* The user can configure the World dimensions and the monochrome light
* intensity at every point in the World (with a `LightPattern`), and add
* `Robot`s to the World to simulate.
*
* After initial configuration, the simulation is run simply by invoking the
* `step()` method, which processes a single time step (1/32 second, by default)
* for all `Robot`s.
*
* References to a `World` are used by both the `Logger` (to save information
* about the `Robot`s during simulation) and the `Viewer` (to visualize the
* simulation).
*
* It manages fixed-step simulated control over all `Robot`s placed in it.
*
*/
class World
{
private:
//! Robots in the world
std::vector<Robot *> m_robots;
//! How many ticks per second in simulation
const uint16_t m_tick_rate = 32;
//! Current tick of the system (starts at 0)
uint32_t m_tick = 0;
//! Duration (seconds) of a tick
const double m_tick_delta_t = 1.0 / m_tick_rate;
//! Number of ticks between messages (eg, 3 means 10 messages per second)
const uint32_t m_comm_rate = 3;
//! Height of the arena in mm
const double m_arena_width;
//! Width of the arena in mm
const double m_arena_height;
//! probability of a controller executing its time step
const double m_prob_control_execute = .99;
//! Background light pattern image
LightPattern m_light_pattern;
private:
CollisionBoxes cb;
Timer timer_controllers;
Timer timer_collisions;
Timer timer_move;
Timer timer_compute_next_step;
Timer timer_communicate;
Timer timer_step;
Timer timer_step_memory;
protected:
//! Run the controllers (kilolib) for all robots
void run_controllers();
//! Send messages between robots
void communicate();
/*!
* Compute the next positions of the robots from positions and motor commands
* @param new_poses Shared reference of new positions to compute over all of
* the robots. (This is passed as a parameter so it can be initialized outside
* of the parallelization)
*/
void compute_next_step(std::vector<RobotPose> &new_poses);
/*!
* Check to see if motion causes robots to collide
* @param new_poses Check for collisions between these would-be next positions
* @param collisions Vector of whether/how each Robot is colliding (to be
* filled by this function)
* @return For each robot: 0 if no collision; -1 if wall collision; 1 if
* collision with another robot
*/
void find_collisions(const std::vector<RobotPose> &new_poses,
std::vector<int16_t> &collisions);
/*!
* Move the robots based on new positions and collisions. This modifies the
* internal positions of all robots in m_robots vector
* @param new_poses Possible next step positions from compute_next_step()
* @param collisions Whether or not robots are colliding, from
* find_collisions()
*/
void move_robots(std::vector<RobotPose> &new_poses,
const std::vector<int16_t> &collisions);
public:
/*!
* Construct a world of a fixed size with the background light pattern
*
* @param arena_width Width of the rectangular World/arena in mm
* @param arena_height Height of the rectangular World/arena in mm
* @param light_pattern_src Name of image file of the light pattern to use.
* Aspect ratio should match the arena, but no specific resolution is
* mandated. If no light_pattern_src is provided (empty string), the
* background will be black.
* @param num_threads How many threads to parallelize the simulation over. If
* set to 0 (default), dynamic threading will be used.
*/
World(const double arena_width, const double arena_height,
const std::string light_pattern_src = "", const uint32_t num_threads = 0);
//! Destructor, destroy all objects within the world
/*!
* This does not destroy any Robots that have pointers stored in the world.
*/
virtual ~World();
/*!
* Run a step of the simulator.
* This runs the controllers, communication, pseudo-physics, and movement
* for all Robots. It also increments the tick time.
*
* This is what you should call in your main function to run the simulation.
*/
void step();
/*!
* Get the current light in the world
* @return SFML Image showing the visible light in the world
*/
sf::Image get_light_pattern() const;
/*!
* Check whether the World has a light pattern image set
* @return Whether LightPattern has an image source
*/
bool has_light_pattern() const;
/*!
* Set the world's light pattern using the given image file.
* The image type must be supported by SFML's [Image::loadFromFile](https://www.sfml-dev.org/documentation/2.5.1/classsf_1_1Image.php#a9e4f2aa8e36d0cabde5ed5a4ef80290b)
*
* @param light_img_src Name and location of the image file to use for light
* pattern
*/
void set_light_pattern(const std::string light_img_src);
/*!
* Add a robot to the world by its pointer.
* @warning It is possible right now to add a Robot twice, so be careful.
*/
void add_robot(Robot *robot);
/*!
* Remove a robot from the world by its pointer
*
* TODO: `remove_robot` is currently unimplemented...
* @warning ...I haven't implemented this yet.
*/
void remove_robot(Robot *robot);
/*!
* Get the tick rate (should be 32)
* @return Number of simulation ticks per second of real-world (wall clock)
* time
*/
uint16_t get_tick_rate() const;
/*!
* Get the current tick of the simulation (only set by simulator)
* @return Number of ticks since simulation started
*/
uint32_t get_tick() const;
/*!
* Get the current computed time in seconds (from tick and tickRate)
* @return Time since simulation started (in seconds)
*/
double get_time() const;
/*!
* Get a reference to a vector of pointers to all robots in the world
* This is useful for Logger and Viewer functions
* @return All the Robots added to the world
*/
std::vector<Robot *> &get_robots();
/*!
* Get the dimensions of the world (in mm)
* @return 2-element [width, height] vector of dimensions in mm
*/
std::vector<double> get_dimensions() const;
void printTimes() const;
/*!
* Check that the world is in a valid state. Throws an exception if a problem
* is found.
*/
void check_validity() const;
};
} // namespace Kilosim
#endif | 32.148148 | 170 | 0.707373 | [
"vector"
] |
d2f7a50d176351e2c36113fc2f439be8766bb7f7 | 16,688 | c | C | sys/dev/c_can/if_c_can.c | hmatyschok/netcan | 3fed71419d7e1507323e69705e8bcd36999ddde1 | [
"BSD-2-Clause-NetBSD"
] | 4 | 2018-10-30T19:20:34.000Z | 2021-12-17T13:00:58.000Z | sys/dev/c_can/if_c_can.c | hmatyschok/netcan | 3fed71419d7e1507323e69705e8bcd36999ddde1 | [
"BSD-2-Clause-NetBSD"
] | null | null | null | sys/dev/c_can/if_c_can.c | hmatyschok/netcan | 3fed71419d7e1507323e69705e8bcd36999ddde1 | [
"BSD-2-Clause-NetBSD"
] | null | null | null | /*
* Copyright (c) 2018, 2019, 2021 Henning Andersen Matyschok, DARPA/AFRL
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/socket.h>
#include <sys/malloc.h>
#include <sys/module.h>
#include <sys/bus.h>
#include <net/if.h>
#include <net/if_can.h>
#include <net/if_var.h>
#include <net/if_types.h>
/*
* XXX:
* Work in progres..
*/
#include <dev/c_can/if_c_canreg.h>
#include "c_can_if.h"
/*
* Subr.
*/
static void c_can_rxeof(struct c_can_softc *);
static void c_can_txeof(struct c_can_softc *);
static void c_can_error(struct c_can_softc *, uint8_t);
static int c_can_intr(void *);
static void c_can_start(struct ifnet *);
static void c_can_start_locked(struct ifnet *);
static void c_can_encap(struct c_can_softc *, struct mbuf **);
static int c_can_ioctl(struct ifnet *, u_long, caddr_t data);
static void c_can_init(void *);
static void c_can_init_locked(struct c_can_softc *);
static int c_can_reset(struct c_can_softc *);
static int c_can_normal_mode(struct c_can_softc *);
static int c_can_set_link_timings(struct can_ifsoftc *);
/*
* can(4) link timing capabilities
*/
static const struct can_link_timecaps c_can_timecaps = {
.cltc_ps1_min = 2,
.cltc_ps1_max = 16,
.cltc_ps2_min = 1,
.cltc_ps2_max = 8,
.cltc_sjw_max = 4,
.cltc_brp_min = 1,
.cltc_brp_max = 1024,
.cltc_brp_inc = 1,
.cltc_linkmode_caps = C_CAN_LINKMODE_CAPS,
};
/*
* XXX
* Work in progres..
*/
static int
c_can_probe(device_t dev)
{
device_set_desc(dev, "Bosch C_CAN network interface");
return (BUS_PROBE_SPECIFIC);
}
static int
c_can_attach(device_t dev)
{
struct c_can_softc *cc;
struct ifnet *ifp;
struct canif_softc *csc;
int rid, i, error;
uint16_t status;
cc = device_get_softc(dev);
cc->cc_dev = dev;
cc->cc_freq = *(uint32_t *)device_get_ivar(dev);
mtx_init(&cc->cc_mtx, device_get_nameunit(dev),
MTX_NETWORK_LOCK, MTX_DEF);
C_CAN_RESET(cc->cc_dev);
/* allocate interrupt */
rid = 0;
cc->cc_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ,
&rid, RF_SHAREABLE | RF_ACTIVE);
if (cc->cc_irq == NULL) {
device_printf(dev, "couldn't map interrupt\n");
error = ENXIO;
goto fail;
}
/* allocate and initialize ifnet(9) structure */
if ((ifp = cc->cc_ifp = if_alloc(IFT_CAN)) == NULL) {
device_printf(dev, "couldn't if_alloc(9)\n");
error = ENOSPC;
goto fail;
}
ifp->if_softc = cc;
if_initname(ifp, device_get_name(dev), device_get_unit(dev));
ifp->if_flags = (IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
ifp->if_init = c_can_init;
ifp->if_start = c_can_start;
ifp->if_ioctl = c_can_ioctl;
can_ifattach(ifp, &c_can_timecaps, cc->cc_freq);
IFQ_SET_MAXLEN(&ifp->if_snd, C_CAN_IFQ_MAXLEN);
ifp->if_snd.ifq_drv_maxlen = C_CAN_IFQ_MAXLEN;
IFQ_SET_READY(&ifp->if_snd);
/* initialize taskqueue(9) */
TASK_INIT(&cc->cc_intr_task, 0, c_can_intr_task, cc);
/* enable automatic retransmission */
status = C_CAN_READ_2(dev, C_CAN_CR);
status &= ~C_CAN_CR_DAR;
C_CAN_WRITE_2(cc->cc_dev, C_CAN_CR, status);
/* configure message objects */
for (i = 1; i < 33; i++) { /* XXX */
C_CAN_WRITE_2(cc->cc_dev, C_CAN_IF1_ID0, 0x0000);
C_CAN_WRITE_2(cc->cc_dev, C_CAN_IF1_ID1, 0x0000);
C_CAN_WRITE_2(cc->cc_dev, C_CAN_IF1_MCR, 0x0000);
c_can_msg_obj_upd(cc, i,
(C_CAN_IFX_CMMR_MO_INVAL | C_CAN_IFX_CMMR_WR_RD),
C_CAN_IFX_RX);
}
for (i = 1; i < 17; i++) { /* XXX */
C_CAN_WRITE_4(cc->cc_dev, C_CAN_IF1_MASK0, 0x20000000);
C_CAN_WRITE_4(cc->cc_dev, C_CAN_IF1_ID0, C_CAN_IFX_ARB_MSG_VAL);
C_CAN_WRITE_2(cc->cc_dev, C_CAN_IF1_MCR, C_CAN_IFX_MCR_RX);
c_can_msg_obj_upd(cc, i, C_CAN_IFX_CMMR_RX_INIT, C_CAN_IFX_RX);
}
/* set-up status register */
C_CAN_WRITE_2(cc->cc_dev, C_CAN_SR, C_CAN_SR_UNUSED_ERR);
error = c_can_set_link_timings(cc);
if (error != 0) {
device_printf(dev, "couldn't set up Bit Timing Register\n");
goto fail1;
}
/* XXX: trigger led(4)s ... */
/* hook interrupts */
error = bus_setup_intr(dev, cc->cc_irq,
INTR_TYPE_NET | INTR_MPSAFE, cc_intr,
NULL, sja, &cc->cc_intr);
if (error != 0) {
device_printf(dev, "couldn't set up irq\n");
goto fail1;
}
/* enable interrupts */
status = C_CAN_READ_2(cc->cc_dev, C_CAN_CR);
status |= C_CAN_CR_INTR_MASK;
C_CAN_WRITE_2(cc->cc_dev, C_CAN_CR, status);
out:
return (error);
fail1:
can_ifdetach(ifp);
fail:
(void)c_can_detach(dev);
goto out;
}
static int
c_can_detach(device_t dev)
{
struct c_can_softc *cc;
struct ifnet *ifp;
cc = device_get_softc(dev);
ifp = cc->cc_ifp;
if (device_is_attached(dev) != 0) {
C_CAN_LOCK(cc);
c_can_stop(cc);
C_CAN_UNLOCK(cc);
taskqueue_drain(taskqueue_fast, &cc->cc_intr_task);
can_ifdetach(ifp);
}
if (cc->cc_intr != NULL) {
(void)bus_teardown_intr(dev, cc->cc_irq, cc->cc_intr);
cc->cc_intr = NULL;
}
if (cc->cc_irq != NULL)
(void)bus_release_resource(dev, SYS_RES_IRQ, cc->cc_irq);
if (ifp != NULL)
if_free(ifp);
mtx_destroy(&cc->cc_mtx);
C_CAN_RESET(dev);
return (0);
}
static void
c_can_rxeof(struct c_can_softc *cc)
{
struct ifnet *ifp;
struct mbuf *m;
uint16_t rxd, i, j, mask, status, k;
uint32_t arb;
uint8_t addr;
C_CAN_LOCK_ASSERT(cc);
ifp = cc->cc_ifp;
rxd = C_CAN_READ_2(cc->cc_dev, C_CAN_NEW_DAT0);
for (i = 0, j = 1; rxd != 0 || i < 16; i++, j++) { /* XXX */
/* fetch mesg. object, if any */
mask = (1 << i);
if ((rxd & mask) == 0)
continue;
rxd &= ~mask;
c_can_msg_obj_upd(cc, j, C_CAN_IFX_CMMR_RX_LOW, C_CAN_IFX_RX);
status = C_CAN_READ_2(cc->cc_dev, C_CAN_IF1_MCR);
if ((status & IF_MCONT_NEWDAT) == 0)
continue;
if ((m = m_gethdr(M_NOWAIT, MT_DATA) == NULL)) {
if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1);
continue;
}
(void)memset(mtod(m, caddr_t), 0, MHLEN);
cf = mtod(m, struct can_frame *);
if (status & C_CAN_IFX_MCR_MSG_LST) {
if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
status &= ~(C_CAN_IFX_MCR_INT_PND
| C_CAN_IFX_MCR_MSG_LST
| C_CAN_IFX_MCR_NEW_DAT);
C_CAN_WRITE_2(cc->cc_dev, C_CAN_IF1_MCR, status);
c_can_obj_upd(cc, j,
(C_CAN_IFX_CMMR_CONTROL | C_CAN_IFX_CMMR_WR_RD),
C_CAN_IF_RX);
cf->can_id |= (CAN_ERR_FLAG|CAN_ERR_DEV);
cf->can_data[CAN_ERR_DF_DEV] = CAN_ERR_DEV_RX_OVF;
} else {
/* determine frame type and map id */
arb = C_CAN_READ_4(cc->cc_dev, C_CAN_IF1_ARB0);
if (arb &C_CAN_IFX_ARBX_MSG_XTD) {
cf->can_id |= CAN_EFF_FLAG;
cf->can_id |= (arb & CAN_EFF_MASK);
} else
cf->can_id |= ((arb >> 18) & CAN_SFF_MASK);
/* map dlc and data region */
if (arb & C_CAN_IFX_ARBX_TX) {
cf->can_id |= CAN_RTR_FLAG;
cf->can_dlc = addr = 0;
} else {
cf->can_dlc = status & C_CAN_IFX_MCR_DLC_MASK;
addr = C_CAN_IF1_DATA0;
}
for (k = 0; k < cf->can_dlc; addr++, k++)
cf->can_data[k] = C_CAN_READ_1(cc->cc_dev, addr);
/* finalize mesg. object */
c_can_msg_obj_upd(cc, j, C_CAN_IFX_CMMR_NEW_DAT, C_CAN_IF_RX);
}
/* pass can(4) frame to upper layer */
m->m_len = m->m_pkthdr.len = sizeof(*cf);
m->m_pkthdr.rcvif = ifp;
C_CAN_UNLOCK(cc);
(*ifp->if_input)(ifp, m);
C_CAN_LOCK(cc);
}
}
static void
c_can_txeof(struct c_can_softc *cc)
{
}
/*
* ...
*/
static void
c_can_msg_obj_upd(struct c_can_softc *cc, int n, int cmd, int ifx)
{
int port, val, i;
uint16_t status;
port = C_CAN_IF1_CMR + ifx * (C_CAN_IF2_CMR - C_CAN_IF1_CMR);
val = (cmd << 0x10) | n;
C_CAN_WRITE_4(cc->cc_dev, port, val);
for (i = 0; i < 6; i++) { /* XXX */
status = C_CAN_READ_2(cc->cc_dev, port);
if ((status & C_CAN_IFX_CMR_BUSY) == 0)
break;
DELAY(1);
}
}
/*
* ...
*/
static int
c_can_intr(void *arg)
{
struct c_can_softc *cc;
uint16_t status;
cc = (struct c_can_softc *)arg;
status = C_CAN_READ_2(cc->cc_dev, C_CAN_IR);
if (status == 0)
return (FILTER_STRAY);
/* disable interrupts */
status = C_CAN_READ_2(cc->cc_dev, C_CAN_CR);
status &= ~C_CAN_CR_INTR_MASK
C_CAN_WRITE_2(cc->cc_dev, C_CAN_CR, status);
taskqueue_enqueue(taskqueue_fast, &cc->cc_inttr_task);
return (FILTER_HANDLED);
}
static void
c_can_intr_task(void *arg, int npending)
{
struct c_can_softc *cc;
uint16_t status;
cc = (struct c_can_softc *)arg;
status = C_CAN_READ_2(cc->cc_dev, C_CAN_SR);
C_CAN_WRITE_2(cc->cc_dev, C_CAN_SR, C_CAN_SR_UNUSED_ERR);
if (status & C_CAN_SR_ERR_MASK)
c_can_error(cc, status);
/*
* ...
*/
c_can_rxeof(cc);
c_can_txeof(cc);
/* enable interrupts */
status = C_CAN_READ_2(cc->cc_dev, C_CAN_CR);
status |= C_CAN_CR_INTR_MASK;
C_CAN_WRITE_2(cc->cc_dev, C_CAN_CR, status);
}
/*
* Transmit can(4) frame.
*/
static void
c_can_start(struct ifnet *ifp)
{
struct c_can_softc *cc;
sja = ifp->if_softc;
C_CAN_LOCK(cc);
c_can_start_locked(ifp);
C_CAN_UNLOCK(cc);
}
static void
c_can_start_locked(struct ifnet *ifp)
{
struct c_can_softc *cc;
struct can_ifsoftc *csc;
struct mbuf *m;
uint8_t status;
cc = ifp->if_softc;
C_CAN_LOCK_ASSERT(cc);
csc = ifp->if_l2com;
if ((ifp->if_drv_flags & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) !=
IFF_DRV_RUNNING)
return;
for (;;) {
IFQ_DEQUEUE(&ifp->if_snd, m);
if (m == NULL)
break;
if (c_can_encap(cc, &m) != 0) {
if (m == NULL)
break;
IFQ_DRV_PREPEND(&ifp->if_snd, m);
ifp->if_drv_flags |= IFF_DRV_OACTIVE;
break;
}
/* IAP on bpf(4) */
can_bpf_mtap(ifp, &m);
/* notify controller for transmission */
if (csc->csc_linkmodes & CAN_LINKMODE_ONE_SHOT)
status = SJA_CMR_AT;
else
status = 0x00;
if (csc->csc_linkmodes & CAN_LINKMODE_LOOPBACK)
status |= SJA_CMR_SRR;
else
ststus |= SJA_CMR_TR;
SJA_WRITE_1(sja->c_can_dev, var, SJA_CMR, status);
status = SJA_READ_1(sja->c_can_dev, var, SJA_SR);
}
}
/*
* ...
*/
static int
c_can_cr_wait(struct c_can_softc *cc, uint16_t control, int iswitch)
{
struct timeval tv0, tv;
uint16_t status, eval;
int error;
getmicrotime(&tv0);
getmicrotime(&tv);
C_CAN_WRITE_2(cc->cc_dev, C_CAN_CR, control);
status = C_CAN_READ_2(cc->cc_dev, C_CAN_CR);
eval = (iswitch != 0) ? C_CAN_CR_INIT : 0;
for (error = EIO; c_can_timercmp(&tv0, &tv, 10000);) {
DELAY(10);
if ((status & C_CAN_CR_INIT) == eval) {
error = 0;
break;
}
status = C_CAN_READ_2(cc->cc_dev, C_CAN_CR);
getmicrotime(&tv);
}
return (error);
}
static int
c_can_set_link_timings(struct c_can_softc *cc)
{
struct can_ifsoftc *csc
struct can_link_timings *clt;
uint16_t btr, brpe, status;
int error;
csc = cc->cc_ifp->if_l2com;
clt = &csc->csc_timings;
btr = ((clt->clt_brp - 1) & C_CAN_BTR_BRP_MASK);
btr |= ((clt->clt_sjw - 1) << 6);
btr |= ((clt->clt_prop + clt->clt_ps1 - 1) << 8);
btr |= ((clt->clt_ps2 - 1) << 12);
brpe = (((clt->clt_brp - 1) & C_CAN_BTR_BRP_MASK) >> 6);
status = C_CAN_READ_2(cc->cc_dev, C_CAN_CR);
status &= ~C_CAN_CR_INIT;
error = c_can_cr_wait(cc, (C_CAN_CR_CCE|C_CAN_CR_INIT), 1);
if (error == 0) {
C_CAN_WRITE_2(cc->cc_dev, C_CAN_BTR, btr);
C_CAN_WRITE_2(cc->cc_dev, C_CAN_BRPER, brpe);
error = c_can_cr_wait(cc, status, 0);
}
return (error);
}
/*
* ...
*/
static void
c_can_stop(struct c_can_softc *cc)
{
struct ifnet *ifp;
uint16_t status;
C_CAN_LOCK_ASSERT(cc);
ifp = cc->cc_ifp;
ifp->if_drv_flags |= ~(IFF_DRV_RUNNNING | IFF_DRV_OACTIVE);
status = C_CAN_READ_2(cc->cc_dev, C_CAN_CR);
status &= ~C_CAN_CR_INTR_MASK
C_CAN_WRITE_2(cc->cc_dev, C_CAN_CR, status);
}
/*
* ...
*/
static int
c_can_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
{
struct c_can_softc *cc;
struct ifreq *ifr;
struct ifdrv *ifd;
int error;
sja = ifp->if_softc;
ifr = (struct ifreq *)data;
ifd = (struct ifdrv *)data;
error = 0;
switch (cmd) {
case SIOCGDRVSPEC:
case SIOCSDRVSPEC:
switch (ifd->ifd_cmd) {
case CANSLINKTIMINGS:
C_CAN_LOCK(cc);
error = c_can_set_link_timings(cc);
C_CAN_UNLOCK(cc);
break;
default:
break;
}
break;
case SIOCSIFFLAGS:
C_CAN_LOCK(cc);
if (ifp->if_flags & IFF_UP)
c_can_init_locked(cc);
else {
if (ifp->if_drv_flags & IFF_DRV_RUNNING)
c_can_stop(cc);
}
C_CAN_UNLOCK(cc);
break;
default:
error = can_ioctl(ifp, cmd, data);
break;
}
return (error);
}
/*
* Common I/O subr.
*/
static uint8_t
c_can_read_1(device_t dev, int port)
{
return (C_CAN_READ_1(device_get_parent(dev), port));
}
static uint16_t
c_can_read_2(device_t dev, int port)
{
return (C_CAN_READ_2(device_get_parent(dev), port));
}
static uint32_t
c_can_read_4(device_t dev, int port)
{
return (C_CAN_READ_4(device_get_parent(dev), port));
}
static void
c_can_write_1(device_t dev, int port, uint8_t val)
{
C_CAN_WRITE_1(device_get_parent(dev), port, val);
}
static void
c_can_write_2(device_t dev, int port, uint16_t val)
{
C_CAN_WRITE_2(device_get_parent(dev), port, val);
}
static void
c_can_write_4(device_t dev, int port, uint32_t val)
{
C_CAN_WRITE_4(device_get_parent(dev), port, val);
}
/*
* Software reset.
*/
static void
c_can_reset(device_t dev)
{
C_CAN_RESET(device_get_parent(dev));
}
/*
* Hooks for the operating system.
*/
static device_method_t c_can_methods[] = {
/* device(9) interface */
DEVMETHOD(device_probe, c_can_probe),
DEVMETHOD(device_attach, c_can_attach),
DEVMETHOD(device_detach, c_can_detach),
/* c_can(4) interface */
DEVMETHOD(c_can_read_1, c_can_read_1),
DEVMETHOD(c_can_read_2, c_can_read_2),
DEVMETHOD(c_can_read_4, c_can_read_4),
DEVMETHOD(c_can_write_1, c_can_write_1),
DEVMETHOD(c_can_write_2, c_can_write_2),
DEVMETHOD(c_can_write_4, c_can_write_4),
DEVMETHOD(c_can_reset), c_can_reset),
DEVMETHOD_END
};
static driver_t c_can_driver = {
"c_can",
c_can_methods,
sizeof(struct c_can_softc)
};
devclass_t c_can_devclass;
MODULE_VERSION(c_can, 1);
| 23.537377 | 75 | 0.61733 | [
"object"
] |
d2fc572b02f84ee45c5a7b5ba8dbc0a396d00925 | 45,713 | c | C | src/api/cm/xml/code/cmx_entity.c | brezillon/opensplice | 725ae9d949c83fce1746bd7d8a154b9d0a81fe3e | [
"Apache-2.0"
] | 133 | 2017-11-09T02:10:00.000Z | 2022-03-29T09:45:10.000Z | src/api/cm/xml/code/cmx_entity.c | brezillon/opensplice | 725ae9d949c83fce1746bd7d8a154b9d0a81fe3e | [
"Apache-2.0"
] | 131 | 2017-11-07T14:48:43.000Z | 2022-03-13T15:30:47.000Z | src/api/cm/xml/code/cmx_entity.c | brezillon/opensplice | 725ae9d949c83fce1746bd7d8a154b9d0a81fe3e | [
"Apache-2.0"
] | 94 | 2017-11-09T02:26:19.000Z | 2022-02-24T06:38:25.000Z | /*
* Vortex OpenSplice
*
* This software and documentation are Copyright 2006 to TO_YEAR ADLINK
* Technology Limited, its affiliated companies and licensors. 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.
*
*/
#include "cmx_entity.h"
#include "cmx__entity.h"
#include "cmx__factory.h"
#include "cmx__participant.h"
#include "cmx__service.h"
#include "cmx__serviceState.h"
#include "cmx__publisher.h"
#include "cmx__subscriber.h"
#include "cmx__writer.h"
#include "cmx__query.h"
#include "cmx__domain.h"
#include "cmx__reader.h"
#include "cmx__topic.h"
#include "cmx__waitset.h"
#include "cmx__factory.h"
#include "sd_serializer.h"
#include "sd_serializerXML.h"
#include "u_observable.h"
#include "u_entity.h"
#include "u__entity.h"
#include "u_participant.h"
#include "u__participant.h"
#include "u_service.h"
#include "u_dataReader.h"
#include "u_networkReader.h"
#include "u_topic.h"
#include "u_groupQueue.h"
#include "u_partition.h"
#include "u_query.h"
#include "u_waitsetEntry.h"
#include "u_publisher.h"
#include "u_subscriber.h"
#include "v_kernel.h"
#include "v_entity.h"
#include "v_dataReader.h"
#include "v_dataReaderQuery.h"
#include "v_dataViewQuery.h"
#include "v_groupQueue.h"
#include "v_networking.h"
#include "v_networkQueue.h"
#include "v_durability.h"
#include "v_cmsoap.h"
#include "v_statistics.h"
#include "v_kernelStatistics.h"
#include "v_writerStatistics.h"
#include "v_dataReaderStatistics.h"
#include "v_queryStatistics.h"
#include "v_networkReader.h"
#include "v_networkReaderStatistics.h"
#include "v_networkingStatistics.h"
#include "v_durabilityStatistics.h"
#include "v_groupQueueStatistics.h"
#include "v_cmsoapStatistics.h"
#include "c_typebase.h"
#include "v_public.h"
#include "v_qos.h"
#include "vortex_os.h"
#include "os_stdlib.h"
#include "sd_serializer.h"
#include "os_abstract.h"
#include "os_stdlib.h"
#include <stdio.h>
/* Number of escape-characters. This determines the size of the arrays used for
* the replacements. */
#define CMX_XML_NUM_ESCAPE_CHARS (5)
/* Array containing the characters that need to be escaped. The character will
* be replaced by the string in CMX_XML_REPLACE_CHARS[] with the same index, so
* indices of this array must match the indices of CMX_XML_REPLACE_CHARS[]. */
static c_char CMX_XML_ESCAPE_CHARS[CMX_XML_NUM_ESCAPE_CHARS] = {'\'', '"', '&', '>', '<'};
/* Array containing the replacement strings of the characters that need to be
* escaped, as specified in CMX_XML_ESCAPE_CHARS[]. The escaped character will
* be replaced by the string in CMX_XML_REPLACE_CHARS[] with the same index, so
* indices of this array must match the indices of CMX_XML_ESCAPE_CHARS[]. */
static c_char* CMX_XML_REPLACE_CHARS[CMX_XML_NUM_ESCAPE_CHARS] = {"'", """, "&", ">", "<"};
/* Array containing the strlen's of the replace-sequences. Indices must match
* with CMX_XML_REPLACE_CHARS[].*/
static c_ulong CMX_XML_REPLACE_CHARS_LEN[CMX_XML_NUM_ESCAPE_CHARS] = {6, 6, 5, 4, 4};
/* Please note that the understanding documentation is written for HTML display.
*
* The strange part reads:
* '''->''',
* '"'->'"',
* '&'->'&',
* '>'->'>' and
* '<'->'<'.
*/
/**
* Escapes a string so it can be stored in an XML-container.
*
* It will replace all occurrences of characters in CMX_XML_ESCAPE_CHARS[] with
* the strings in the same index in CMX_XML_REPLACE_CHARS[]. It will thus replace
* '''->'&apos;',
* '''->'&quot;',
* '&'->'&amp;',
* '>'->'&gt;' and
* '<'->'&lt;'.
* @param string The string to be escaped.
* @return An escaped copy of string. Needs to be freed with os_free().
*/
static c_char*
getXMLEscapedString(
const c_char* string)
{
c_ulong strLen = 0;
c_ulong extraStrLen = 0;
c_ulong i, j, inserts;
c_char* result = NULL;
c_bool match, shouldReplace = FALSE;
if(string){
/* Calculate length of resulting string */
strLen = 0;
while(string[strLen] != '\0'){
match = FALSE;
for(j = 0; !match && j < CMX_XML_NUM_ESCAPE_CHARS; j++){
if(string[strLen] == CMX_XML_ESCAPE_CHARS[j]){
/* Count extra length. The original character is counted
* by strLen, so count with original character excluded. */
extraStrLen += CMX_XML_REPLACE_CHARS_LEN[j] - 1;
match = TRUE; /* And we can stop looking */
}
}
strLen++;
shouldReplace |= match;
}
if(shouldReplace){
/* Replacements needed, so allocate memory for result-string */
result = (c_char*)os_malloc(strLen + extraStrLen + 1);
if(result){
inserts = 0;
/* Now insert the escapes */
for(i = 0; i < strLen; i++){
match = FALSE;
for(j = 0; !match && j < CMX_XML_NUM_ESCAPE_CHARS; j++){
if(string[i] == CMX_XML_ESCAPE_CHARS[j]){
os_strncpy(&result[i + inserts], CMX_XML_REPLACE_CHARS[j], CMX_XML_REPLACE_CHARS_LEN[j]);
/* Count extra length. The original character is counted
* by strLen, so count with original character excluded. */
inserts += CMX_XML_REPLACE_CHARS_LEN[j] - 1;
match = TRUE; /* We can stop looking */
}
}
if(!match){
/* No replace happened, so include original character */
result[i + inserts] = string[i];
}
}
/* NUL-terminate result */
result[strLen + extraStrLen] = '\0';
} else {
/* Memory-claim denied, return NULL */
OS_REPORT(OS_ERROR, CM_XML_CONTEXT, 0,
"Heap-memory claim of size %d denied, cannot generate escaped XML string.",
strLen + extraStrLen + 1);
}
} else {
/* No replacements needed, so just duplicate the string */
result = os_strdup(string);
}
}
return result;
}
/**
* Resolves the user entities that match the supplied XML entities. This is done
* by casting the contents of the pointer tags in the XML entity to user
* entities.
*
* @param xmlEntities The XML representation of the user entities to resolve.
* @return The user entities that match the supplied XML entities.
*/
static c_iter
cmx_entityCmxEntities(
const c_char* xmlEntities)
{
size_t length = 0;
c_ulong i = 0;
c_ulong nrOfEntities = 0;
c_char * substring;
c_char * xmlEntity = NULL;
cmx_entity cmEntity;
c_iter cmEntities = NULL;
c_iter xmlEntityList = c_iterNew(NULL);
if (!xmlEntityList) goto err_iterNewEntityList;
cmEntities = c_iterNew(NULL);
if (!cmEntities) goto err_iterNewEntities;
xmlEntities+=12; /*<entityList>*/
substring = strstr(xmlEntities, "</entity>");
while(substring){
length = (size_t) (substring - xmlEntities + 9); /*</entity>*/
xmlEntity = os_malloc((length+1) * sizeof(c_char));
os_strncpy(xmlEntity, xmlEntities, length);
xmlEntity[length] = '\0';
c_iterAppend(xmlEntityList, xmlEntity);
xmlEntities = xmlEntities + length;
substring = strstr(xmlEntities, "</entity>");
}
nrOfEntities = c_iterLength(xmlEntityList);
for(i = 0 ; i<nrOfEntities; i++){
xmlEntity = (c_char*)c_iterTakeFirst(xmlEntityList);
cmEntity = cmx_entityClaim(xmlEntity);
if(cmEntity){
c_iterAppend(cmEntities, cmEntity);
}
os_free(xmlEntity);
}
err_iterNewEntities:
c_iterFree(xmlEntityList);
err_iterNewEntityList:
return cmEntities;
}
_Ret_z_
const c_char *
cmx__uresult (
_In_ u_result ures)
{
switch(ures) {
case U_RESULT_OK:
return CMX_RESULT_OK;
case U_RESULT_ILL_PARAM:
return CMX_RESULT_ILL_PARAM;
case U_RESULT_IMMUTABLE_POLICY:
return CMX_RESULT_IMMUTABLE_POLICY;
case U_RESULT_INCONSISTENT_QOS:
return CMX_RESULT_INCONSISTENT_QOS;
case U_RESULT_TIMEOUT:
return CMX_RESULT_TIMEOUT;
case U_RESULT_PRECONDITION_NOT_MET:
return CMX_RESULT_PRECONDITION_NOT_MET;
default:
return CMX_RESULT_FAILED;
}
}
void
cmx_entityNewFromAction(
v_public entity,
c_voidp args)
{
(void)cmx_entityNewFromWalk(entity, args);
}
static c_bool
cmx_entityNewEntityFromWalk(
v_entity entity,
cmx_entityArg arg)
{
cmx_entity participant;
c_char* special;
c_bool result = FALSE;
special = cmx_entityGetTypeXml(v_public(entity));
if (special != NULL) {
u_object proxy;
if (arg->create == TRUE) {
if (arg->entity->participant) {
participant = arg->entity->participant;
} else {
participant = arg->entity;
}
assert(u_objectKind(participant->uentity) == U_PARTICIPANT);
proxy = u_object(u_observableCreateProxy(v_public(entity),
u_participant(participant->uentity)));
if (proxy != NULL) {
cmx_registerObject(proxy,participant);
}
} else {
proxy = arg->entity->uentity;
}
/* Get the entity XML representation. */
arg->result = (c_voidp)cmx_entityXml(entity->name,
(c_address)proxy,
&(v_public(entity)->handle),
v_entityEnabled(entity),
special);
os_free(special);
result = TRUE;
}
return result;
}
static c_bool
cmx_entityNewWaitSetFromWalk(
v_waitset waitset,
cmx_entityArg arg)
{
cmx_entity participant;
c_char* special;
c_bool result = FALSE;
special = cmx_entityGetTypeXml(v_public(waitset));
if(special != NULL){
u_object proxy = NULL;
if(arg->create == TRUE){
if (arg->entity->participant) {
participant = arg->entity->participant;
} else {
participant = arg->entity;
}
proxy = u_object(u_observableCreateProxy(v_public(waitset),
u_participant(participant->uentity)));
if (proxy != NULL) {
cmx_registerObject(u_object(proxy), participant);
}
}
/* Get the waitset XML representation. */
arg->result = (c_voidp)cmx_entityXml(NULL,
(c_address)proxy,
&(v_public(waitset)->handle),
TRUE,
special);
os_free(special);
result = TRUE;
}
return result;
}
c_bool
cmx_entityNewFromWalk(
v_public object,
c_voidp args)
{
cmx_entityArg arg = cmx_entityArg(args);
c_bool result = FALSE;
assert(object);
assert(arg);
if (c_instanceOf(object, "v_entity")) {
/* Is this really an entity? */
result = cmx_entityNewEntityFromWalk((v_entity)object, arg);
} else if (c_instanceOf(object, "v_waitset")) {
/* Or is this entity actually a waitset? */
result = cmx_entityNewWaitSetFromWalk((v_waitset)object, arg);
} else if (c_instanceOf(object, "v_listener")) {
/* Ignore listeners, these are (for now) internal objects */
} else {
/* Should never come here. */
OS_REPORT(OS_ERROR, CM_XML_CONTEXT, 0,
"Unknown object kind: '%d'\n",
v_object(object)->kind);
assert(FALSE);
}
return result;
}
c_char*
cmx_entityGetTypeXml(
v_public object)
{
c_char* result;
result = NULL;
switch(v_object(object)->kind){
case K_PARTICIPANT:
result = cmx_participantInit((v_participant)object);
break;
case K_NETWORKING:
/*fallthrough on purpose.*/
case K_DURABILITY:
case K_NWBRIDGE:
case K_CMSOAP:
case K_SPLICED:
case K_RNR:
case K_DBMSCONNECT:
case K_SERVICE:
result = cmx_serviceInit((v_service)object);
break;
case K_PUBLISHER:
result = cmx_publisherInit((v_publisher)object);
break;
case K_SERVICESTATE:
result = cmx_serviceStateInit((v_serviceState)object);
break;
case K_SUBSCRIBER:
result = cmx_subscriberInit((v_subscriber)object);
break;
case K_WRITER:
result = cmx_writerInit((v_writer)object);
break;
case K_QUERY:
/*fallthrough on purpose.*/
case K_DATAREADERQUERY:
result = cmx_queryInit((v_query)object);
break;
case K_DOMAIN:
result = cmx_domainInit((v_partition)object);
break;
case K_NETWORKREADER: /*fallthrough on purpose.*/
case K_DATAREADER: /*fallthrough on purpose.*/
case K_DATAVIEW: /*fallthrough on purpose.*/
case K_DELIVERYSERVICE: /*fallthrough on purpose.*/
case K_GROUPQUEUE:
result = cmx_readerInit((v_reader)object);
break;
case K_TOPIC:
case K_TOPIC_ADAPTER:
result = cmx_topicInit((v_topic)object);
break;
case K_WAITSET:
result = cmx_waitsetInit((v_waitset)object);
break;
case K_LISTENER:
break;
default:
OS_REPORT(OS_ERROR, CM_XML_CONTEXT, 0,
"Unknown entity kind: '%d'\n",
v_object(object)->kind);
assert(FALSE);
break;
}
return result;
}
c_char*
cmx_entityInit(
v_entity entity,
u_entity proxy,
c_bool init)
{
c_char* result;
u_result ur;
ur = U_RESULT_OK;
result = NULL;
if((proxy == NULL) && (init == TRUE)){
ur = U_RESULT_ILL_PARAM;
}
if(ur == U_RESULT_OK){
switch(v_object(entity)->kind){
case K_PARTICIPANT:
result = cmx_participantInit((v_participant)entity);
break;
case K_NETWORKING:
/*fallthrough on purpose.*/
case K_DURABILITY:
case K_NWBRIDGE:
case K_CMSOAP:
case K_SPLICED:
case K_RNR:
case K_DBMSCONNECT:
case K_SERVICE:
result = cmx_serviceInit((v_service)entity);
break;
case K_PUBLISHER:
result = cmx_publisherInit((v_publisher)entity);
break;
case K_SERVICESTATE:
result = cmx_serviceStateInit((v_serviceState)entity);
break;
case K_SUBSCRIBER:
result = cmx_subscriberInit((v_subscriber)entity);
break;
case K_WRITER:
result = cmx_writerInit((v_writer)entity);
break;
case K_QUERY:
/*fallthrough on purpose.*/
case K_DATAREADERQUERY:
result = cmx_queryInit((v_query)entity);
break;
case K_DOMAIN:
result = cmx_domainInit((v_partition)entity);
break;
case K_NETWORKREADER:
/*fallthrough on purpose.*/
case K_DATAREADER:
/*fallthrough on purpose.*/
case K_DELIVERYSERVICE:
/*fallthrough on purpose.*/
case K_GROUPQUEUE:
result = cmx_readerInit((v_reader)entity);
break;
case K_TOPIC:
case K_TOPIC_ADAPTER:
result = cmx_topicInit((v_topic)entity);
break;
case K_WAITSET:
result = cmx_waitsetInit((v_waitset)entity);
break;
default:
OS_REPORT(OS_ERROR, CM_XML_CONTEXT, 0,
"Unknown entity kind: '%d'\n",
v_object(entity)->kind);
assert(0);
break;
}
} else {
OS_REPORT(OS_ERROR, CM_XML_CONTEXT, 0,
"cmx_entityInit ur != U_RESULT_OK.");
cmx_deregisterObject(u_object(proxy));
assert(0);
}
return result;
}
void
cmx_entityFree(
c_char* entity)
{
cmx_entity e;
if(entity != NULL){
e = cmx_entityClaim(entity);
if(e != NULL){
cmx_deregisterObject(u_object(e->uentity));
cmx_factoryReleaseEntity(e);
}
os_free(entity);
}
}
void
cmx_entityKindAction(
v_public object,
c_voidp args)
{
cmx_entityKindArg arg;
arg = cmx_entityKindArg(args);
arg->kind = v_object(object)->kind;
}
c_bool
cmx_entityWalkAction(
v_entity e,
c_voidp args)
{
cmx_walkEntityArg arg;
c_char* xmlEntity;
c_bool add;
c_bool proceed;
v_object object;
/*
* This is the callback of a call to u_entityWalkEntities().
* In contradication of the function name, it will return a waitset
* when it was called with a participant. This is because the waitset
* was a entity in the past.
*
* So, an entity pointer is given, even while it can be a waitset. This
* still works, but off course should change in the future.
*
* For now, just cast the entity to an object to indicate that we're not
* always dealing with an entity here.
*/
object = (v_object)e;
arg = cmx_walkEntityArg(args);
add = FALSE;
if(object != NULL){
switch(arg->filter){
/*User filter, select all entities of the supplied+inherited kinds */
case K_ENTITY:/*Always add the entity.*/
if(object->kind != K_DELIVERYSERVICE){
add = TRUE;
}
break;
case K_QUERY:
switch(object->kind){
case K_QUERY:
case K_DATAREADERQUERY:
add = TRUE; break;
default: break;
}
break;
case K_TOPIC:
switch(object->kind){
case K_TOPIC: add = TRUE; break;
default: break;
}
break;
case K_TOPIC_ADAPTER:
switch(object->kind){
case K_TOPIC_ADAPTER:add = TRUE; break;
default: break;
}
break;
case K_PUBLISHER:
switch(object->kind){
case K_PUBLISHER: add = TRUE; break;
default: break;
}
break;
case K_SUBSCRIBER:
switch(object->kind){
case K_SUBSCRIBER: add = TRUE; break;
default: break;
}
break;
case K_DOMAIN:
switch(object->kind){
case K_DOMAIN: add = TRUE; break;
default: break;
}
break;
case K_READER:
switch(object->kind){
case K_READER:
case K_DATAREADER:
case K_NETWORKREADER:
case K_GROUPQUEUE:
case K_QUERY:
case K_DATAREADERQUERY:
add = TRUE; break;
default: break;
}
break;
case K_DATAREADER:
switch(object->kind){
case K_DATAREADER: add = TRUE; break;
default: break;
}
break;
case K_GROUPQUEUE:
switch(object->kind){
case K_GROUPQUEUE: add = TRUE; break;
default: break;
}
break;
case K_NETWORKREADER:
switch(object->kind){
case K_NETWORKREADER: add = TRUE; break;
default: break;
}
break;
case K_WRITER:
switch(object->kind){
case K_WRITER: add = TRUE; break;
default: break;
}
break;
case K_PARTICIPANT:
switch(object->kind){
case K_PARTICIPANT:
case K_SERVICE:
case K_SPLICED:
case K_NETWORKING:
case K_DURABILITY:
case K_NWBRIDGE:
case K_CMSOAP:
case K_RNR:
case K_DBMSCONNECT:
add = TRUE; break;
default: break;
}
break;
case K_SERVICE:
switch(object->kind){
case K_SERVICE:
case K_SPLICED:
case K_NETWORKING:
case K_DURABILITY:
case K_NWBRIDGE:
case K_CMSOAP:
case K_RNR:
case K_DBMSCONNECT:
add = TRUE; break;
default: break;
}
break;
case K_SERVICESTATE:
switch(object->kind){
case K_SERVICESTATE:add = TRUE; break;
default: break;
}
break;
case K_WAITSET:
switch(object->kind){
case K_WAITSET: add = TRUE; break;
default: break;
}
break;
default:
OS_REPORT(OS_ERROR, CM_XML_CONTEXT, 0,
"Unknown Entity found in cmx_entityWalkAction: %d\n",
object->kind);
break;
}
}
if(add == TRUE){
proceed = cmx_entityNewFromWalk(v_public(object), &arg->entityArg);
if(proceed == TRUE){
xmlEntity = arg->entityArg.result;
if(xmlEntity == NULL){
OS_REPORT(OS_ERROR, CM_XML_CONTEXT, 0,
"Entity found: %d\n",
object->kind);
assert(FALSE);
} else {
arg->list = c_iterInsert(arg->list, xmlEntity);
arg->length += strlen(xmlEntity);
}
}
}
return TRUE;
}
c_char *
cmx_entityOwnedEntities(
const c_char* entity,
const c_char* filter)
{
cmx_entity ce;
c_char* result;
u_result walkSuccess;
cmx_walkEntityArg arg;
result = NULL;
ce = cmx_entityClaim(entity);
if(ce != NULL){
if (u_objectKind(u_object(ce->uentity)) == U_WAITSETENTRY) {
/* Waitset: return an empty list.
* Waitsets aren't and weren't supported by u_entityWalkEntities() anyway. */
result = cmx_convertToXMLList(NULL, 0);
} else {
arg = cmx_walkEntityArg(os_malloc(C_SIZEOF(cmx_walkEntityArg)));
arg->length = 0;
arg->filter = cmx_resolveKind(filter);
arg->list = NULL;
arg->entityArg.entity = ce;
arg->entityArg.create = TRUE;
arg->entityArg.result = NULL;
walkSuccess = u_entityWalkEntities(u_entity(ce->uentity),
cmx_entityWalkAction,
(c_voidp)(arg));
if (walkSuccess == U_RESULT_OK) {
result = cmx_convertToXMLList(arg->list, arg->length);
}
os_free(arg);
}
cmx_entityRelease(ce);
}
return result;
}
struct cmx_entityHandleArg {
c_ulong index;
c_ulong serial;
};
void
getHandleAction(
v_public object,
c_voidp args)
{
struct cmx_entityHandleArg *arg;
arg = (struct cmx_entityHandleArg *)args;
arg->index = object->handle.index;
arg->serial = object->handle.serial;
}
c_ulong
cmx_entityPathFinder(const c_char* entity,
c_ulong childIndex, c_ulong childSerial, c_iter* resultPath){
cmx_entity ce;
cmx_entity tempChild;
c_char* xmlTempChild;
v_kind kind;
u_result walkSuccess;
cmx_walkEntityArg arg;
struct cmx_entityHandleArg handle;
c_ulong resultLength=0;
ce = cmx_entityClaim(entity);
if(ce != NULL){
kind = K_ENTITY; /*FORCED*/
arg = cmx_walkEntityArg(os_malloc(C_SIZEOF(cmx_walkEntityArg)));
if(arg){
arg->length = 0;
arg->filter = kind;
arg->list = NULL;
arg->entityArg.entity = ce;
arg->entityArg.create = TRUE;
arg->entityArg.result = NULL;
walkSuccess = u_entityWalkEntities(u_entity(ce->uentity),
cmx_entityWalkAction,
(c_voidp)(arg));
if (walkSuccess == U_RESULT_OK) {
/*First level of children*/
if(arg->list != NULL && arg->length > 0){
xmlTempChild = (c_char*)c_iterTakeFirst(arg->list);
while(xmlTempChild){
tempChild = cmx_entityClaim(xmlTempChild);
if(tempChild != NULL){
(void)u_observableAction(u_observable(ce->uentity),
getHandleAction,
(c_voidp)&handle);
if((handle.index == childIndex) && (handle.serial == childSerial)){
c_iterInsert(*resultPath, xmlTempChild);
resultLength+=strlen(xmlTempChild);
xmlTempChild = NULL;
break;
}else{
resultLength+=cmx_entityPathFinder(xmlTempChild, childIndex, childSerial, resultPath);
if(c_iterLength(*resultPath)==0){
cmx_entityFree(xmlTempChild);
xmlTempChild = (c_char*)c_iterTakeFirst(arg->list);
}else{
c_iterInsert(*resultPath, xmlTempChild);
resultLength+=strlen(xmlTempChild);
xmlTempChild = NULL;
break;
}
}
}
}
}
}
if(c_iterLength(arg->list)>0){
xmlTempChild = (c_char*)c_iterTakeFirst(arg->list);
while(xmlTempChild){
cmx_entityFree(xmlTempChild);
xmlTempChild = (c_char*)c_iterTakeFirst(arg->list);
}
}
c_iterFree(arg->list);
os_free(arg);
}
}
return resultLength;
}
c_char *
cmx_entityGetEntityTree(
const c_char* entity,
const c_char* childIndex,
const c_char* childSerial)
{
c_char* result;
c_ulong resultLength = 0;
c_iter resultPath = c_iterNew(NULL);
c_ulong _childIndex = 0;
c_ulong _childSerial = 0;
if(sscanf(childIndex,"%u", &_childIndex) && sscanf(childSerial,"%u", &_childSerial)){
resultLength = cmx_entityPathFinder(entity, _childIndex, _childSerial, &resultPath);
}
result = cmx_convertToXMLList(resultPath, resultLength);
return result;
}
c_char *
cmx_entityDependantEntities(
const c_char* entity,
const c_char* filter)
{
cmx_entity ce;
c_char* result;
u_result walkSuccess;
cmx_walkEntityArg arg;
result = NULL;
ce = cmx_entityClaim(entity);
if(ce != NULL){
switch (u_objectKind(u_object(ce->uentity))) {
case U_WAITSET:
/* Waitset: return an empty list.
* Waitsets aren't and weren't supported by u_entityWalkEntities() anyway. */
result = cmx_convertToXMLList(NULL, 0);
break;
default:
arg = cmx_walkEntityArg(os_malloc(C_SIZEOF(cmx_walkEntityArg)));
arg->length = 0;
arg->filter = cmx_resolveKind(filter);
arg->list = NULL;
arg->entityArg.entity = ce;
arg->entityArg.create = TRUE;
arg->entityArg.result = NULL;
walkSuccess = u_entityWalkDependantEntities(u_entity(ce->uentity),
cmx_entityWalkAction,
(c_voidp)(arg));
if (walkSuccess == U_RESULT_OK) {
result = cmx_convertToXMLList(arg->list, arg->length);
}
os_free(arg);
break;
}
cmx_entityRelease(ce);
}
return result;
}
struct cmx_statusArg {
c_char* result;
};
c_char*
cmx_entityStatus(
const c_char* entity)
{
cmx_entity ce;
struct cmx_statusArg arg;
arg.result = NULL;
ce = cmx_entityClaim(entity);
if(ce != NULL){
if (u_objectKind(u_object(ce->uentity)) != U_WAITSET) {
(void)u_observableAction(u_observable(ce->uentity), cmx_entityStatusAction, &arg);
}
cmx_entityRelease(ce);
}
return arg.result;
}
void
cmx_entityStatusAction(
v_public entity,
c_voidp args)
{
sd_serializer ser;
sd_serializedData data;
struct cmx_statusArg *arg;
arg = (struct cmx_statusArg *)args;
/* Only entities will enter this function (no waitsets). */
ser = sd_serializerXMLNewTyped(c_getType(c_object(v_entity(entity)->status)));
data = sd_serializerSerialize(ser, c_object(v_entity(entity)->status));
arg->result = sd_serializerToString(ser, data);
sd_serializedDataFree(data);
sd_serializerFree(ser);
}
struct cmx_statisticsArg {
c_char* result;
};
c_char*
cmx_entityStatistics(
const c_char* entity)
{
cmx_entity ce;
struct cmx_statisticsArg arg;
arg.result = NULL;
ce = cmx_entityClaim(entity);
if(ce != NULL){
if (u_objectKind(u_object(ce->uentity)) != U_WAITSET) {
(void)u_observableAction(u_observable(ce->uentity), cmx_entityStatisticsAction, &arg);
}
cmx_entityRelease(ce);
}
return arg.result;
}
c_char*
cmx_entitiesStatistics(
const c_char* entities)
{
c_iter cmEntityList;
c_iter cmStatisticsList = c_iterNew(NULL);
cmx_entity cmEntity;
struct cmx_statisticsArg temp, arg;
size_t statisticsSize = 0;
c_char* openTag = "<statistics>";
c_char* closeTag = "</statistics>";
c_char* emptyStat = "<object></object>";
c_char* cmStatistics = NULL;
u_result result;
cmEntityList = cmx_entityCmxEntities(entities);
arg.result = NULL;
temp.result = NULL;
if(cmEntityList != NULL && c_iterLength(cmEntityList) > 0){
cmEntity = (cmx_entity) c_iterTakeFirst(cmEntityList);
while(cmEntity){
if (u_objectKind(u_object(cmEntity->uentity)) != U_WAITSET) {
result = u_observableAction(u_observable(cmEntity->uentity),
cmx_entityStatisticsAction,
&temp);
if(temp.result != NULL && result == U_RESULT_OK){
statisticsSize += strlen(temp.result);
c_iterAppend(cmStatisticsList, temp.result);
temp.result = NULL;
} else {
statisticsSize += strlen(emptyStat);
c_iterAppend(cmStatisticsList, os_strdup(emptyStat));
}
}
cmx_entityRelease(cmEntity);
cmEntity = (cmx_entity) c_iterTakeFirst(cmEntityList);
}
}
c_iterFree(cmEntityList);
arg.result = os_malloc((statisticsSize+strlen(openTag)+strlen(closeTag)+1)*sizeof(c_char));
*arg.result = '\0';
os_strcat(arg.result, openTag);
if(c_iterLength(cmStatisticsList) > 0){
cmStatistics = (c_char*)c_iterTakeFirst(cmStatisticsList);
while(cmStatistics){
os_strcat(arg.result, cmStatistics);
os_free(cmStatistics);
cmStatistics = (c_char*)c_iterTakeFirst(cmStatisticsList);
}
}
os_strcat(arg.result, closeTag);
c_iterFree(cmStatisticsList);
return arg.result;
}
void
cmx_entityStatisticsAction(
v_public object,
c_voidp args)
{
sd_serializer ser;
sd_serializedData data;
struct cmx_statisticsArg *arg;
v_statistics statistics;
arg = (struct cmx_statisticsArg *)args;
if (object == NULL) {
/* Somebody actually tries to get statistics of a non-entity.
* There are none. */
arg->result = NULL;
} else {
switch(v_objectKind(object)) {
case K_WRITER:
statistics = v_statistics(v_writer(object)->statistics);
break;
case K_DATAREADER:
statistics = v_statistics(v_dataReader(object)->statistics);
break;
case K_QUERY:
case K_DATAREADERQUERY:
case K_DATAVIEWQUERY:
statistics = v_statistics(v_query(object)->statistics);
break;
case K_NETWORKREADER:
statistics = v_statistics(v_networkReader(object)->statistics);
break;
case K_NETWORKING:
statistics = v_statistics(v_networking(object)->statistics);
break;
case K_KERNEL:
statistics = v_statistics(v_kernel(object)->statistics);
break;
case K_DURABILITY:
statistics = v_statistics(v_durability(object)->statistics);
break;
case K_CMSOAP:
statistics = v_statistics(v_cmsoap(object)->statistics);
break;
default:
/* Remaining entities don't have specific statistics yet. */
statistics = NULL;
arg->result = NULL;
break;
}
if(statistics != NULL){
ser = sd_serializerXMLNewTyped(c_getType((c_object)statistics));
data = sd_serializerSerialize(ser, statistics);
arg->result = sd_serializerToString(ser, data);
sd_serializedDataFree(data);
sd_serializerFree(ser);
}
}
}
struct cmx_resetStatisticsArg {
const c_char* fieldName;
const c_char* result;
};
const c_char*
cmx_entityResetStatistics(
const c_char* entity,
const c_char* fieldName)
{
cmx_entity ce;
struct cmx_resetStatisticsArg arg;
arg.result = CMX_RESULT_ENTITY_NOT_AVAILABLE;
ce = cmx_entityClaim(entity);
if(ce != NULL){
arg.fieldName = fieldName;
if (u_objectKind(u_object(ce->uentity)) != U_WAITSET) {
(void)u_observableAction(u_observable(ce->uentity),
cmx_entityStatisticsResetAction,
&arg);
}
cmx_entityRelease(ce);
}
return arg.result;
}
void
cmx_entityStatisticsResetAction(
v_public object,
c_voidp args)
{
struct cmx_resetStatisticsArg *arg;
c_bool result = TRUE;
arg = (struct cmx_resetStatisticsArg *)args;
switch (v_objectKind(object)) {
case K_KERNEL:
if (arg->fieldName) {
result = v_statisticsResetField(v_statistics(v_kernel(object)->statistics), arg->fieldName);
} else {
v_kernelStatisticsInit(v_kernel(object)->statistics);
}
break;
case K_WRITER:
if (arg->fieldName) {
result = v_statisticsResetField(v_statistics(v_writer(object)->statistics), arg->fieldName);
} else {
v_writerStatisticsInit(v_writer(object)->statistics);
}
break;
case K_DATAREADER:
if (arg->fieldName) {
result = v_statisticsResetField(v_statistics(v_dataReader(object)->statistics), arg->fieldName);
} else {
v_dataReaderStatisticsInit(v_dataReader(object)->statistics);
}
break;
case K_DATAVIEWQUERY:
case K_QUERY:
if (arg->fieldName) {
result = v_statisticsResetField(v_statistics(v_query(object)->statistics), arg->fieldName);
} else {
v_queryStatisticsInit(v_query(object)->statistics);
}
break;
case K_NETWORKREADER:
if (arg->fieldName) {
result = v_statisticsResetField(v_statistics(v_networkReader(object)->statistics), arg->fieldName);
} else {
v_networkReaderStatisticsInit(v_networkReader(object)->statistics);
}
break;
case K_DURABILITY:
if (arg->fieldName) {
result = v_statisticsResetField(v_statistics(v_durability(object)->statistics), arg->fieldName);
} else {
v_durabilityStatisticsInit(v_durability(object)->statistics);
}
break;
case K_NWBRIDGE:
break;
case K_CMSOAP:
if (arg->fieldName) {
result = v_statisticsResetField(v_statistics(v_cmsoap(object)->statistics), arg->fieldName);
} else {
v_cmsoapStatisticsInit(v_cmsoap(object)->statistics);
}
break;
case K_NETWORKING:
if (arg->fieldName) {
result = v_statisticsResetField(v_statistics(v_networking(object)->statistics), arg->fieldName);
} else {
v_networkingStatisticsInit(v_networking(object)->statistics);
}
break;
case K_RNR:
break;
case K_DBMSCONNECT:
break;
case K_GROUPQUEUE:
if (arg->fieldName) {
result = v_statisticsResetField(v_statistics(v_groupQueue(object)->statistics), arg->fieldName);
} else {
v_groupQueueStatisticsInit(v_groupQueue(object)->statistics);
}
break;
default:
result = FALSE;
break;
}
if(result == TRUE){
arg->result = CMX_RESULT_OK;
} else {
arg->result = CMX_RESULT_FAILED;
}
}
void
cmx_entityStatisticsFieldResetAction(
v_public object,
c_voidp args)
{
struct cmx_resetStatisticsArg *arg;
c_bool result = FALSE;
v_statistics statistics = NULL;
arg = (struct cmx_resetStatisticsArg *)args;
switch (v_objectKind(object)) {
case K_KERNEL:
statistics = v_statistics(v_kernel(object)->statistics);
break;
case K_WRITER:
statistics = v_statistics(v_writer(object)->statistics);
break;
case K_DATAREADER:
statistics = v_statistics(v_dataReader(object)->statistics);
break;
case K_DATAVIEWQUERY:
case K_QUERY:
statistics = v_statistics(v_query(object)->statistics);
break;
case K_NETWORKREADER:
statistics = v_statistics(v_networkReader(object)->statistics);
break;
case K_DURABILITY:
statistics = v_statistics(v_durability(object)->statistics);
break;
case K_NWBRIDGE:
break;
case K_CMSOAP:
statistics = v_statistics(v_cmsoap(object)->statistics);
break;
case K_NETWORKING:
statistics = v_statistics(v_networking(object)->statistics);
break;
case K_RNR:
break;
case K_DBMSCONNECT:
break;
case K_GROUPQUEUE:
break;
default:
statistics = NULL;
break;
}
if(statistics != NULL){
result = v_statisticsResetField(statistics, arg->fieldName);
}
if(result == TRUE){
arg->result = CMX_RESULT_OK;
} else {
arg->result = CMX_RESULT_FAILED;
}
}
c_char*
cmx_entityQoS(
const c_char* entity)
{
c_char* result;
cmx_entity ce;
result = NULL;
ce = cmx_entityClaim(entity);
if (ce != NULL) {
if (u_objectKind(u_object(ce->uentity)) != U_WAITSET) {
(void)u_entityGetXMLQos(u_entity(ce->uentity), &result);
}
cmx_entityRelease(ce);
}
return result;
}
const c_char*
cmx_entitySetQoS(
const c_char* entity,
const c_char* qos)
{
cmx_entity ce;
u_result ur;
const c_char* result;
result = CMX_RESULT_FAILED;
if (qos != NULL && (strlen(qos) > 0)) {
ce = cmx_entityClaim(entity);
if(ce != NULL){
if (u_objectKind(u_object(ce->uentity)) != U_WAITSET) {
ur = u_entitySetXMLQos(u_entity(ce->uentity), qos);
if(ur == U_RESULT_OK){
result = CMX_RESULT_OK;
} else if(ur == U_RESULT_ILL_PARAM){
result = CMX_RESULT_ILL_PARAM;
} else if(ur == U_RESULT_INCONSISTENT_QOS){
result = CMX_RESULT_INCONSISTENT_QOS;
} else if(ur == U_RESULT_IMMUTABLE_POLICY){
result = CMX_RESULT_IMMUTABLE_POLICY;
} else {
result = CMX_RESULT_FAILED;
}
} else {
result = CMX_RESULT_ILL_PARAM;
}
cmx_entityRelease(ce);
}
} else {
result = CMX_RESULT_ILL_PARAM;
}
return result;
}
const c_char*
cmx_entityEnable(
const c_char* entity)
{
cmx_entity ce;
const c_char* result;
u_result ures;
result = CMX_RESULT_ENTITY_NOT_AVAILABLE;
ce = cmx_entityClaim(entity);
if(ce != NULL){
if (u_objectKind(ce->uentity) != U_WAITSET) {
ures = u_entityEnable(u_entity(ce->uentity));
if(ures == U_RESULT_OK) {
/* TODO: update XML-entity? */
}
result = cmx__uresult(ures);
} else {
result = CMX_RESULT_ILL_PARAM;
}
cmx_entityRelease(ce);
}
return result;
}
c_char*
cmx_entityXml(
const c_string name,
const c_address proxy,
const v_handle *handle,
const c_bool enabled,
const c_string special)
{
c_char* xml_enabled;
c_char* xml_name;
c_ulong xml_hdl_index = 0;
c_ulong xml_hdl_serial = 0;
char buf[1024];
assert(special);
if(enabled){
xml_enabled = "TRUE";
} else {
xml_enabled = "FALSE";
}
if(name){
xml_name = getXMLEscapedString(name);
} else {
xml_name = os_strdup("NULL");
}
if (handle) {
xml_hdl_index = handle->index;
xml_hdl_serial = handle->serial;
}
os_sprintf(buf, "<entity><pointer>"PA_ADDRFMT"</pointer><handle_index>%u</handle_index><handle_serial>%u</handle_serial><name>%s</name><enabled>%s</enabled>%s</entity>",
proxy,
xml_hdl_index,
xml_hdl_serial,
xml_name,
xml_enabled,
special);
os_free(xml_name);
return os_strdup(buf);
}
cmx_entity
cmx_entityClaim(
const c_char* xmlEntity)
{
c_char* copy;
c_char* temp;
c_char* savePtr;
u_object e;
int assigned;
cmx_entity entity;
entity = NULL;
if(xmlEntity != NULL){
if(cmx_isInitialized() == OS_TRUE){
copy = (c_char*)(os_malloc(strlen(xmlEntity) + 1));
if(copy != NULL){
(void)os_strcpy(copy, xmlEntity);
temp = os_strtok_r((c_char*)copy, "</>", &savePtr);/*<entity>*/
if(temp != NULL){
temp = os_strtok_r(NULL, "</>", &savePtr);/*<pointer>*/
if(temp != NULL){
temp = os_strtok_r(NULL, "</>", &savePtr);/*...the pointer*/
if(temp != NULL){
assigned = sscanf(temp, PA_ADDRFMT, (c_address *)(&e));
if (assigned != 1) {
OS_REPORT(OS_ERROR, CM_XML_CONTEXT, 0,
"Failed to retrieve entity address from xml string '%s' and address 0x%s",
xmlEntity, temp);
} else {
entity = cmx_factoryClaimEntity(e);
if(entity == NULL){
OS_REPORT(OS_WARNING, CM_XML_CONTEXT, 0,
"Entity "PA_ADDRFMT" (0x%s) from string '%s' has already been freed.\n",
(c_address)e, temp, xmlEntity);
}
}
}
}
}
}
os_free(copy);
} else {
cmx_detach();
}
}
return entity;
}
void
cmx_entityKernelAction(
v_public object,
c_voidp args)
{
cmx_entityKernelArg arg;
arg = cmx_entityKernelArg(args);
if(object != NULL){
arg->kernel = v_objectKernel(object);
}
}
u_result
cmx_entityRegister (
u_object object,
cmx_entity participant,
c_char **xml)
{
u_result ur = U_RESULT_ILL_PARAM;
if (object && xml) {
C_STRUCT(cmx_entityArg) arg;
arg.create = FALSE;
arg.result = NULL;
arg.entity = cmx_registerObject(object, participant);
ur = u_observableAction(u_observable(object),
cmx_entityNewFromAction,
(c_voidp)&arg);
if(ur == U_RESULT_OK){
*xml = arg.result;
} else {
cmx_deregisterObject(object);
}
}
return ur;
}
| 29.936477 | 173 | 0.563669 | [
"object"
] |
9602df1a89ca45a98bfbbe77b22d08d6b3d002f7 | 5,932 | h | C | src/PlateletForceDevice.h | sambritton/Fibrin_Network | cdfbc878b24e436bc333e94eb9aade801a355ff1 | [
"MIT"
] | null | null | null | src/PlateletForceDevice.h | sambritton/Fibrin_Network | cdfbc878b24e436bc333e94eb9aade801a355ff1 | [
"MIT"
] | null | null | null | src/PlateletForceDevice.h | sambritton/Fibrin_Network | cdfbc878b24e436bc333e94eb9aade801a355ff1 | [
"MIT"
] | null | null | null |
#ifndef PLATELETFORCEDEVICE_H_
#define PLATELETFORCEDEVICE_H_
#include <vector>
typedef thrust::tuple<unsigned, bool> Tub; //tuple holding id of a node and if that node is within reach of the platelet
//look up forward declaration if this doesn't make sense.
struct NodeInfoVecs;
struct WLCInfoVecs;
struct GeneralParams;
struct PlateletParams;
struct PlateletInfoVecs;
__host__ __device__
void PlateletForceOnDevice(
NodeInfoVecs& nodeInfoVecs,
WLCInfoVecs& wlcInfoVecs,
GeneralParams& generalParams,
PlateletParams& plateletParams,
PlateletInfoVecs& plateletInfoVecs);
void AdvancePlateletPosition(stuff here);
struct AdvancePosition {
}
//go through and add appropriate entries for input
struct PlateletForceFunctor {
double* plateletLocXAddr;
double* plateletLocYAddr;
double* plateletLocZAddr;
double* plateletForceXAddr;
double* plateletForceYAddr;
double* plateletForceZAddr;
bool* plateletCanPullAddr;
double bodyRadius;
double armDist;
unsigned numberOfArms;
unsigned maxPlateletCount;
double pullingForce;
double* nodeLocXAddr;
double* nodeLocYAddr;
double* nodeLocZAddr;
double* nodeForceXAddr;
double* nodeForceYAddr;
double* nodeForceZAddr;
unsigned* bucketValues;
unsigned* bucketNbrsExp;
unsigned* keyBegin;
unsigned* keyEnd;
__host__ __device__
PlateletForceFunctor(
double* _plateletLocXAddr,
double* _plateletLocYAddr,
double* _plateletLocZAddr,
double* _plateletForceXAddr,
double* _plateletForceYAddr,
double* _plateletForceZAddr,
unsigned& _numberOfArms,
double& pullingForce,
double* _nodeLocXAddr,
double* _nodeLocYAddr,
double* _nodeLocZAddr,
double* _nodeForceXAddr,
double* _nodeForceYAddr,
double* _nodeForceZAddr) :
plateletLocXAddr(_plateletLocXAddr),
plateletLocYAddr(_plateletLocYAddr),
plateletLocZAddr(_plateletLocZAddr),
plateletForceXAddr(_plateletForceXAddr),
plateletForceYAddr(_plateletForceYAddr),
plateletForceZAddr(_plateletForceZAddr),
numberOfArms(_numberOfArms),
pullingForce(_pullingForce),
nodeLocXAddr(_nodeLocXAddr),
nodeLocYAddr(_nodeLocYAddr),
nodeLocZAddr(_nodeLocZAddr),
nodeForceXAddr(_nodeForceXAddr),
nodeForceYAddr(_nodeForceYAddr),
nodeForceZAddr(_nodeForceZAddr),
bucketValues(_bucketValues),
bucketNbrsExp(_bucketNbrsExp),
keyBegin(_keyBegin),
keyEnd(_keyEnd), {}
__device__
void operator() (const Tuu& u2) {
//choice 1: functor pulls 4 times
//choice 2:
unsigned id = thrust::get<0>(u1);
unsigned bucketId = thrust::get<0>(u1);
//beginning and end of attempted interaction network nodes.
unsigned beginIndex = keyBegin[bucketId];
unsigned endIndex = keyEnd[bucketId];
unsigned storageLocation = id * maxPlateletCount;
double pLocX = plateletLocXAddr[id];
double pLocY = plateletLocYAddr[id];
double pLocZ = plateletLocZAddr[id];
double sumPlateletForceX = 0;
double sumPlateletForceY = 0;
double sumPlateletForceZ = 0;
double forcePerArm = pullingforce / numberOfArms;
//Loop through the number of available neighbors for each platelet.
for(unsigned i=beginIndex; i < endIndex; i++) {
//Choose a neighbor.
unsigned pullNode_id = bucketNbrsExp[i];
bool plateletCanPull = plateletCanPullAddr[pullNode_id];
//Get position of node
double vecN_PX = pLocX - nodeLocXAddr[pullNode_id];
double vecN_PY = pLocY - nodeLocYAddr[pullNode_id];
double vecN_PZ = pLocZ - nodeLocZAddr[pullNode_id];
//Calculate distance from platelet to node.
double dist = sqrt(
(vecN_PX) * (vecN_PX) +
(vecN_PY) * (vecN_PY) +
(vecN_PZ) * (vecN_PZ));
if (dist < bodyRadius) && (plateletCanPull) {
//then we detach the node from the network and make sure it is never pulled again.
plateletCanPullAddr[pullNode_id] = false;
//loop through global neighbors and set all edges of pullNode_id equal to ULONG_MAX.
//you'll need to add global neighbors
}
//only pull as many as are arms.
if (pullCounter < numberOfArms) {
if ((dist < armDist) && dist > (bodyRadius)) {
//node only affects platelet position if it is pulled.
//Determine direction of force based on positions and multiply magnitude force
double forceNodeX = (vecP_NX / dist) * (forcePerArm);
double forceNodeY = (vecP_NY / dist) * (forcePerArm);
double forceNodeZ = (vecP_NZ / dist) * (forcePerArm);
//count force for platelet.
sumPlateletForceX += (-1)*forceNodeX;
sumPlateletForceY += (-1)*forceNodeY;
sumPlateletForceZ += (-1)*forceNodeZ;
//store force in temporary vector. Call reduction later.
forceAppliedXAddr[storageLocation + pullCounter] = forceNodeX;
forceAppliedYAddr[storageLocation + pullCounter] = forceNodeY;
forceAppliedZAddr[storageLocation + pullCounter] = forceNodeZ;
idForceAppliedAddr[storageLocation + pullCounter] = pullNode_id;
pullCounter++
}
}
}
plateletForceX[id] = sumPlateletForceX;
plateletForceY[id] = sumPlateletForceY;
plateletForceZ[id] = sumPlateletForceZ;
}
} | 31.721925 | 121 | 0.63503 | [
"vector"
] |
96096f52eb45215a082b5ec1eada234f7940a973 | 462 | h | C | examples/external/mLib/include/application-d3d11/D3D11Utility.h | zhangxaochen/Opt | 7f1af802bfc84cc9ef1adb9facbe4957078f529a | [
"MIT"
] | 260 | 2017-03-02T19:57:51.000Z | 2022-01-21T03:52:03.000Z | examples/external/mLib/include/application-d3d11/D3D11Utility.h | zhangxaochen/Opt | 7f1af802bfc84cc9ef1adb9facbe4957078f529a | [
"MIT"
] | 102 | 2017-03-03T00:42:56.000Z | 2022-03-30T14:15:20.000Z | examples/external/mLib/include/application-d3d11/D3D11Utility.h | zhangxaochen/Opt | 7f1af802bfc84cc9ef1adb9facbe4957078f529a | [
"MIT"
] | 71 | 2017-03-02T20:22:33.000Z | 2022-01-02T03:49:04.000Z |
#ifndef APPLICATION_D3D11_D3D11UTILITY_H_
#define APPLICATION_D3D11_D3D11UTILITY_H_
namespace ml {
class D3D11Utility
{
public:
static ID3DBlob* CompileShader(
const std::string &filename,
const std::string &entryPoint,
const std::string &shaderModel,
const std::vector<std::pair<std::string, std::string>>& macros = std::vector<std::pair<std::string, std::string>>());
};
} // namespace ml
#endif // APPLICATION_D3D11_D3D11UTILITY_H_
| 23.1 | 121 | 0.731602 | [
"vector"
] |
9610271ae2739eb5252b9834e6b930e31882e131 | 2,343 | h | C | src/SHADERed/Objects/WebAPI.h | stef-levesque/SHADERed | 5895eea75e9cdc1cd71dc0572513c073db033364 | [
"MIT"
] | 2 | 2020-05-29T21:40:02.000Z | 2021-01-05T03:25:38.000Z | src/SHADERed/Objects/WebAPI.h | stef-levesque/SHADERed | 5895eea75e9cdc1cd71dc0572513c073db033364 | [
"MIT"
] | null | null | null | src/SHADERed/Objects/WebAPI.h | stef-levesque/SHADERed | 5895eea75e9cdc1cd71dc0572513c073db033364 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <thread>
#include <functional>
namespace ed {
class WebAPI {
public:
static const std::string URL;
static const int InternalVersion = 16;
// info that /api/search will return
struct ShaderResult
{
std::string ID;
std::string Title;
std::string Description;
std::string Owner;
int Views;
std::string Language;
};
struct PluginResult
{
std::string ID;
std::string Title;
std::string Description;
std::string Owner;
std::string Thumbnail;
int Downloads;
};
struct ThemeResult {
std::string ID;
std::string Title;
std::string Description;
std::string Owner;
std::string Thumbnail;
int Downloads;
};
WebAPI();
~WebAPI();
/* max count, index, title, text*/
void FetchTips(std::function<void(int, int, const std::string&, const std::string&)> onFetch);
/* changelog content */
void FetchChangelog(std::function<void(const std::string&)> onFetch);
/* called when update required */
void CheckForApplicationUpdates(std::function<void()> onUpdate);
/* list of shaders */
std::vector<ShaderResult> SearchShaders(const std::string& query, int page, const std::string& sort, const std::string& language, const std::string& owner, bool excludeGodotShaders);
/* bytes, bytecount <- download thumbnail */
char* AllocateThumbnail(const std::string& id, size_t& length);
/* download project in temp directory */
bool DownloadShaderProject(const std::string& id);
/* search plugins */
std::vector<PluginResult> SearchPlugins(const std::string& query, int page, const std::string& sort, const std::string& owner);
/* decode thumbnail */
char* DecodeThumbnail(const std::string& base64, size_t& length);
/* download plugin */
void DownloadPlugin(const std::string& id);
/* search themes */
std::vector<ThemeResult> SearchThemes(const std::string& query, int page, const std::string& sort, const std::string& owner);
/* download theme */
void DownloadTheme(const std::string& id);
/* get plugin version */
int GetPluginVersion(const std::string& id);
private:
// TODO: maybe have one thread + some kind of job queue system... lazy rn to fix this, just copy pasting old code
std::thread* m_tipsThread;
std::thread* m_changelogThread;
std::thread* m_updateThread;
};
} | 27.564706 | 184 | 0.691848 | [
"vector"
] |
96121a6a24ac28babe9f3a8c29fce09319757ccc | 14,087 | h | C | c4/c4encode.h | Stanley2015/c4-lib | dca7f1b22c2c81bfa47135fde09724ff0ec08857 | [
"Apache-2.0"
] | null | null | null | c4/c4encode.h | Stanley2015/c4-lib | dca7f1b22c2c81bfa47135fde09724ff0ec08857 | [
"Apache-2.0"
] | null | null | null | c4/c4encode.h | Stanley2015/c4-lib | dca7f1b22c2c81bfa47135fde09724ff0ec08857 | [
"Apache-2.0"
] | null | null | null | /************************************************************************/
/* */
/* c4-lib */
/* c4-lib is A Common Codes Converting Context library. */
/* */
/* Version: 0.1 */
/* Author: wei_w (weiwl07@gmail.com) */
/* Published under Apache License 2.0 */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Project URL: http://code.google.com/p/c4-lib */
/* */
/* Copyright 2011 wei_w */
/* */
/************************************************************************/
#pragma once
// c4encode.h
#ifndef C4ENCODE_H_
#define C4ENCODE_H_
#include <string>
#include <vector>
#include "c4policy.h"
#include "c4segment.h"
typedef wchar_t encode_features;
class CC4Encode;
class CC4EncodeBase;
class CC4EncodeUTF16;
class CC4EncodeUTF8;
class CC4Encode
{
public :
static const wchar_t UNKNOWN_CHAR = 0xFFFD;
static const wchar_t LITTLEENDIAN_MARK = 0xFEFF;
static const wchar_t BIGENDIAN_MARK = 0xFFFE;
static const char LITTLEENDIAN_BOM[2];
static const char BIGENDIAN_BOM[2];
static const char UTF_8_BOM[3];
enum encodeFeature {
typeNoFeature = 0x0000,
typeBaseOnAnsi = 0x0001, /* InputStream: Multibyte encoding. High byte is at first */
typeBaseOnUnicode = 0x0002, /* InputStream: Unicode encoding. Low byte is at first */
typeFixed = 0x0004, /* InputStream: Fixed bytes of per character */
typeVariable = 0x0008, /* InputStream: Variable bytes of per character */
typeResultAnsi = 0x0010, /* OutputStream: multibyte string: std::string */
typeResultUnicode = 0x0020, /* OutputStream: Unicode string: std::wstring */
typeExternal = 0x0040, /* Load from external config file */
typeInternal = 0x0080, /* Build-in encoding */
typeUTF16 = typeBaseOnUnicode|typeFixed|typeResultAnsi|typeInternal, /* UTF-16 */
typeUTF8 = typeBaseOnUnicode|typeVariable|typeResultUnicode|typeInternal /* UTF-8 */
};
static encodeFeature toEncodeFeature(const char* feature_text)
{
if (NULL == feature_text) return typeNoFeature;
if (strcmp("BaseOnMultibyte", feature_text) == 0) return typeBaseOnAnsi;
if (strcmp("BaseOnUnicode", feature_text) == 0) return typeBaseOnUnicode;
if (strcmp("ResultIsMultibyte", feature_text) == 0) return typeResultAnsi;
if (strcmp("ResultIsUnicode", feature_text) == 0) return typeResultUnicode;
return typeNoFeature;
};
static bool checkFeatureValid(encode_features features)
{
if (((features&typeBaseOnAnsi) != 0) && ((features&typeBaseOnUnicode) != 0))
return false;
if (((features&typeFixed) != 0) && ((features&typeVariable) != 0))
return false;
if (((features&typeResultAnsi) != 0) && ((features&typeResultUnicode) != 0))
return false;
if (((features&typeExternal) != 0) && ((features&typeInternal) != 0))
return false;
return true;
};
public:
CC4Encode(const std::wstring& name, const std::wstring& version, const std::wstring& description, encode_features features, bool is_auto_check);
virtual ~CC4Encode() {};
std::wstring toString() const;
bool isAutoCheck() const;
void setAutoCheck(bool is_auto_check);
std::wstring getName() const;
std::wstring getVersion() const;
std::wstring getDescription() const;
encode_features getEncodeFeatures() const;
bool hasFeature(CC4Encode::encodeFeature encode_feature) const;
/* Input string(Multibyte) matches this encode or not. */
bool virtual match(const char *src, unsigned int src_length) const = 0;
/* Input string(Unicode) matches this encode or not */
bool virtual wmatch(const wchar_t *src, unsigned int src_str_length) const = 0;
/* Convert input string(Multibyte) to multibyte string */
std::string virtual convertText(const char *src, unsigned int src_length) const = 0;
std::string virtual convertString(const char *src) const = 0;
/* Convert input string(Multibyte/Unicode) to Unicode string */
std::wstring virtual wconvertText(const char *src, unsigned int src_length) const = 0;
std::wstring virtual wconvertString(const char *src) const = 0;
/* Convert input string(Unicode) to multibyte string */
std::string virtual convertWideText(const wchar_t *src, unsigned int src_str_length) const = 0;
std::string virtual convertWideString(const wchar_t *src) const = 0;
/* Convert input string(Unicode) to Unicode string */
std::wstring virtual wconvertWideText(const wchar_t *src, unsigned int src_str_length) const = 0;
std::wstring virtual wconvertWideString(const wchar_t *src) const = 0;
private:
std::wstring m_name; // name of the encode, for example: Shift-JIS
std::wstring m_version; // version of the encode, for example: Microsoft CP932
std::wstring m_description; // description
encode_features m_encodeFeatures; // encode type
bool m_autoCheck; // the encode is used in auto-_match mode or not
};
/************************************************************************/
/* CC4EncodeBase */
/* Encode loaded from config file */
/************************************************************************/
class CC4EncodeBase : CC4Encode
{
private:
const unsigned char* m_mapBuffer; // map buffer
const unsigned int m_mapBufferLength; // map buffer length
const CC4Policies* m_policies;
const CC4Segments* m_segments;
public:
CC4EncodeBase(const std::wstring& name, const std::wstring& version, const std::wstring& description, encode_features features, bool is_auto_check, const unsigned char *buffer, unsigned int buffer_length);
~CC4EncodeBase() {}
// override
/* Input string(Multibyte) matches this encode or not. */
bool match(const char *src, unsigned int src_length) const;
/* Input string(Unicode) matches this encode or not */
bool wmatch(const wchar_t *src, unsigned int src_str_length) const;
/* Convert input string(Multibyte) to multibyte string */
std::string convertText(const char *src, unsigned int src_length) const {return std::string();};
std::string convertString(const char *src) const {return std::string();};
/* Convert input string(Multibyte/Unicode) to Unicode string */
std::wstring wconvertText(const char *src, unsigned int src_length) const;
std::wstring wconvertString(const char *src) const;
/* Convert input string(Unicode) to multibyte string */
std::string convertWideText(const wchar_t *src, unsigned int src_str_length) const {return std::string();};
std::string convertWideString(const wchar_t *src) const {return std::string();};
/* Convert input string(Unicode) to Unicode string */
std::wstring wconvertWideText(const wchar_t *src, unsigned int src_str_length) const;
std::wstring wconvertWideString(const wchar_t *src) const;
/* convert single char */
wchar_t convertChar_A2U(char high_byte, char low_byte) const;
wchar_t convertChar_A2U(wchar_t ansi_char) const;
wchar_t convertChar_U2U(wchar_t unicode_char) const;
unsigned int calcUnicodeStringLength(const char *src, unsigned int src_length) const;
/* multibyte string to unicode string */
bool convertAnsi2Unicode(const char *src, unsigned int src_length, char *dest, unsigned int dest_length, bool check_dest_length = false) const;
bool convertAnsi2Unicode(const char *src, unsigned int src_length, wchar_t *dest, unsigned int dest_str_length, bool check_dest_length = false) const;
/* unicode string to unicode string */
bool convertUnicode2Unicode(const wchar_t *src, unsigned int src_str_length, wchar_t *dest, unsigned int dest_str_length) const;
bool setPolicies(const CC4Policies* ptr_policies);
bool setSegments(const CC4Segments* ptr_segments);
const CC4Policies* getPolicies() const;
const CC4Segments* getSegments() const;
};
/************************************************************************/
/* CC4EncodeUTF16 */
/* Notice: will treat all input as Unicode string */
/************************************************************************/
class CC4EncodeUTF16 : CC4Encode
{
public:
static CC4EncodeUTF16* getInstance();
private:
static CC4EncodeUTF16 *s_instance; // Unicode instance. Singleton pattern
CC4EncodeUTF16(const std::wstring& name, const std::wstring& version, const std::wstring& description, bool is_auto_check);
~CC4EncodeUTF16() {/*s_instance = NULL;*/};
class CGarbo
{
public:
~CGarbo()
{
if (s_instance)
delete s_instance;
}
};
static CGarbo garbo;
public:
static std::wstring _getName();
static std::wstring _getVersion();
static std::wstring _getDescription();
static encode_features _getEncodeFeatures();
bool match(const char *src, unsigned int src_length) const;
bool wmatch(const wchar_t *src, unsigned int src_str_length) const;
static bool _match(const char *src, unsigned int src_length);
/* convert to utf-8 string */
std::string convertText(const char *src, unsigned int src_length) const;
std::string convertString(const char *src) const;
/* simply build a Unicode string */
std::wstring wconvertText(const char *src, unsigned int src_length) const;
std::wstring wconvertString(const char *src) const;
/* convert to utf-8 string */
std::string convertWideText(const wchar_t *src, unsigned int src_str_length) const;
std::string convertWideString(const wchar_t *src) const;
/* simply build a Unicode string */
std::wstring wconvertWideText(const wchar_t *src, unsigned int src_str_length) const;
std::wstring wconvertWideString(const wchar_t *src) const;
/* static converting functions */
static std::string convert2utf8(const char *src, unsigned int src_length, bool is_little_endian = true);
static std::string convert2utf8(const wchar_t *src, unsigned int src_str_length);
static bool convert2utf8(const char *src, unsigned int src_length, char *dest, unsigned int dest_length, bool is_little_endian = true, bool check_dest_length = false);
static unsigned int calcUtf8StringLength(const char *src, unsigned int src_length, bool is_little_endian = true);
};
/************************************************************************/
/* CC4EncodeUTF8 */
/* Notice: will treat all input as UTF-8 string */
/************************************************************************/
class CC4EncodeUTF8 : CC4Encode
{
public:
static CC4EncodeUTF8* getInstance();
private:
static CC4EncodeUTF8 *s_instance; // Utf-8 instance. Singleton pattern
CC4EncodeUTF8(const std::wstring& name, const std::wstring& version, const std::wstring& description, bool is_auto_check);
~CC4EncodeUTF8() {/*s_instance = NULL;*/};
class CGarbo
{
public:
~CGarbo()
{
if (s_instance)
delete s_instance;
}
};
static CGarbo garbo;
public:
static std::wstring _getName();
static std::wstring _getVersion();
static std::wstring _getDescription();
static encode_features _getEncodeFeatures();
bool match(const char *src, unsigned int src_length) const;
bool wmatch(const wchar_t *src, unsigned int src_str_length) const;
static bool _match(const char *src, unsigned int src_length);
/* simply build a utf-8 string */
std::string convertText(const char *src, unsigned int src_length) const;
std::string convertString(const char *src) const;
/* convert to Unicode string */
std::wstring wconvertText(const char *src, unsigned int src_length) const;
std::wstring wconvertString(const char *src) const;
/* Error input. Return empty string. */
std::string convertWideText(const wchar_t *src, unsigned int src_str_length) const {return std::string();};
std::string convertWideString(const wchar_t *src) const {return std::string();};
/* Error input. Return empty string. */
std::wstring wconvertWideText(const wchar_t *src, unsigned int src_str_length) const {return std::wstring();};
std::wstring wconvertWideString(const wchar_t *src) const {return std::wstring();};
/* static converting functions */
static std::wstring convert2unicode(const char *src, unsigned int src_length);
static bool convert2unicode(const char *src, unsigned int src_length, char *dest, unsigned int dest_length, bool check_dest_length = false);
static bool convert2unicode(const char *src, unsigned int src_length, wchar_t *dest, unsigned int dest_str_length, bool check_dest_length = false);
static unsigned int calcUnicodeStringLength(const char *src, unsigned int src_length);
};
#endif // C4ENCODE_H_ | 49.083624 | 210 | 0.61248 | [
"vector"
] |
c54f5845a8db1aa1905b384389118569034caa49 | 16,487 | c | C | src/libmime/images.c | rspamd-internal/rspamd | ad7718d3e8f124504edbb4c452083c6d2e2add80 | [
"Apache-2.0"
] | 2 | 2019-11-27T11:32:14.000Z | 2020-11-12T14:10:20.000Z | src/libmime/images.c | rspamd-internal/rspamd | ad7718d3e8f124504edbb4c452083c6d2e2add80 | [
"Apache-2.0"
] | null | null | null | src/libmime/images.c | rspamd-internal/rspamd | ad7718d3e8f124504edbb4c452083c6d2e2add80 | [
"Apache-2.0"
] | null | null | null | /*-
* Copyright 2016 Vsevolod Stakhov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "config.h"
#include "images.h"
#include "task.h"
#include "message.h"
#include "html.h"
#define msg_debug_images(...) rspamd_conditional_debug_fast (NULL, NULL, \
rspamd_images_log_id, "images", task->task_pool->tag.uid, \
G_STRFUNC, \
__VA_ARGS__)
INIT_LOG_MODULE(images)
#ifdef USABLE_GD
#include "gd.h"
#include "hash.h"
#include <math.h>
#define RSPAMD_NORMALIZED_DIM 64
static rspamd_lru_hash_t *images_hash = NULL;
#endif
static const guint8 png_signature[] = {137, 80, 78, 71, 13, 10, 26, 10};
static const guint8 jpg_sig1[] = {0xff, 0xd8};
static const guint8 jpg_sig_jfif[] = {0xff, 0xe0};
static const guint8 jpg_sig_exif[] = {0xff, 0xe1};
static const guint8 gif_signature[] = {'G', 'I', 'F', '8'};
static const guint8 bmp_signature[] = {'B', 'M'};
static bool process_image (struct rspamd_task *task, struct rspamd_mime_part *part);
bool
rspamd_images_process_mime_part_maybe (struct rspamd_task *task,
struct rspamd_mime_part *part)
{
if (part->part_type == RSPAMD_MIME_PART_UNDEFINED) {
if (part->detected_type &&
strcmp (part->detected_type, "image") == 0 &&
part->parsed_data.len > 0) {
return process_image (task, part);
}
}
return false;
}
void
rspamd_images_process (struct rspamd_task *task)
{
guint i;
struct rspamd_mime_part *part;
PTR_ARRAY_FOREACH (MESSAGE_FIELD (task, parts), i, part) {
rspamd_images_process_mime_part_maybe (task, part);
}
}
static enum rspamd_image_type
detect_image_type (rspamd_ftok_t *data)
{
if (data->len > sizeof (png_signature) / sizeof (png_signature[0])) {
if (memcmp (data->begin, png_signature, sizeof (png_signature)) == 0) {
return IMAGE_TYPE_PNG;
}
}
if (data->len > 10) {
if (memcmp (data->begin, jpg_sig1, sizeof (jpg_sig1)) == 0) {
if (memcmp (data->begin + 2, jpg_sig_jfif, sizeof (jpg_sig_jfif)) == 0 ||
memcmp (data->begin + 2, jpg_sig_exif, sizeof (jpg_sig_exif)) == 0) {
return IMAGE_TYPE_JPG;
}
}
}
if (data->len > sizeof (gif_signature) / sizeof (gif_signature[0])) {
if (memcmp (data->begin, gif_signature, sizeof (gif_signature)) == 0) {
return IMAGE_TYPE_GIF;
}
}
if (data->len > sizeof (bmp_signature) / sizeof (bmp_signature[0])) {
if (memcmp (data->begin, bmp_signature, sizeof (bmp_signature)) == 0) {
return IMAGE_TYPE_BMP;
}
}
return IMAGE_TYPE_UNKNOWN;
}
static struct rspamd_image *
process_png_image (rspamd_mempool_t *pool, rspamd_ftok_t *data)
{
struct rspamd_image *img;
guint32 t;
const guint8 *p;
if (data->len < 24) {
msg_info_pool ("bad png detected (maybe striped)");
return NULL;
}
/* In png we should find iHDR section and get data from it */
/* Skip signature and read header section */
p = data->begin + 12;
if (memcmp (p, "IHDR", 4) != 0) {
msg_info_pool ("png doesn't begins with IHDR section");
return NULL;
}
img = rspamd_mempool_alloc0 (pool, sizeof (struct rspamd_image));
img->type = IMAGE_TYPE_PNG;
img->data = data;
p += 4;
memcpy (&t, p, sizeof (guint32));
img->width = ntohl (t);
p += 4;
memcpy (&t, p, sizeof (guint32));
img->height = ntohl (t);
return img;
}
static struct rspamd_image *
process_jpg_image (rspamd_mempool_t *pool, rspamd_ftok_t *data)
{
const guint8 *p, *end;
guint16 h, w;
struct rspamd_image *img;
img = rspamd_mempool_alloc0 (pool, sizeof (struct rspamd_image));
img->type = IMAGE_TYPE_JPG;
img->data = data;
p = data->begin;
end = p + data->len - 8;
p += 2;
while (p < end) {
if (p[0] == 0xFF && p[1] != 0xFF) {
guint len = p[2] * 256 + p[3];
p ++;
if (*p == 0xc0 || *p == 0xc1 || *p == 0xc2 || *p == 0xc3 ||
*p == 0xc9 || *p == 0xca || *p == 0xcb) {
memcpy (&h, p + 4, sizeof (guint16));
h = p[4] * 0xff + p[5];
img->height = h;
w = p[6] * 0xff + p[7];
img->width = w;
return img;
}
p += len;
}
else {
p++;
}
}
return NULL;
}
static struct rspamd_image *
process_gif_image (rspamd_mempool_t *pool, rspamd_ftok_t *data)
{
struct rspamd_image *img;
const guint8 *p;
guint16 t;
if (data->len < 10) {
msg_info_pool ("bad gif detected (maybe striped)");
return NULL;
}
img = rspamd_mempool_alloc0 (pool, sizeof (struct rspamd_image));
img->type = IMAGE_TYPE_GIF;
img->data = data;
p = data->begin + 6;
memcpy (&t, p, sizeof (guint16));
img->width = GUINT16_FROM_LE (t);
memcpy (&t, p + 2, sizeof (guint16));
img->height = GUINT16_FROM_LE (t);
return img;
}
static struct rspamd_image *
process_bmp_image (rspamd_mempool_t *pool, rspamd_ftok_t *data)
{
struct rspamd_image *img;
gint32 t;
const guint8 *p;
if (data->len < 28) {
msg_info_pool ("bad bmp detected (maybe striped)");
return NULL;
}
img = rspamd_mempool_alloc0 (pool, sizeof (struct rspamd_image));
img->type = IMAGE_TYPE_BMP;
img->data = data;
p = data->begin + 18;
memcpy (&t, p, sizeof (gint32));
img->width = abs (GINT32_FROM_LE (t));
memcpy (&t, p + 4, sizeof (gint32));
img->height = abs (GINT32_FROM_LE (t));
return img;
}
#ifdef USABLE_GD
/*
* DCT from Emil Mikulic.
* http://unix4lyfe.org/dct/
*/
static void
rspamd_image_dct_block (gint pixels[8][8], gdouble *out)
{
gint i;
gint rows[8][8];
static const gint c1 = 1004 /* cos(pi/16) << 10 */,
s1 = 200 /* sin(pi/16) */,
c3 = 851 /* cos(3pi/16) << 10 */,
s3 = 569 /* sin(3pi/16) << 10 */,
r2c6 = 554 /* sqrt(2)*cos(6pi/16) << 10 */,
r2s6 = 1337 /* sqrt(2)*sin(6pi/16) << 10 */,
r2 = 181; /* sqrt(2) << 7*/
gint x0, x1, x2, x3, x4, x5, x6, x7, x8;
/* transform rows */
for (i = 0; i < 8; i++) {
x0 = pixels[0][i];
x1 = pixels[1][i];
x2 = pixels[2][i];
x3 = pixels[3][i];
x4 = pixels[4][i];
x5 = pixels[5][i];
x6 = pixels[6][i];
x7 = pixels[7][i];
/* Stage 1 */
x8 = x7 + x0;
x0 -= x7;
x7 = x1 + x6;
x1 -= x6;
x6 = x2 + x5;
x2 -= x5;
x5 = x3 + x4;
x3 -= x4;
/* Stage 2 */
x4 = x8 + x5;
x8 -= x5;
x5 = x7 + x6;
x7 -= x6;
x6 = c1 * (x1 + x2);
x2 = (-s1 - c1) * x2 + x6;
x1 = (s1 - c1) * x1 + x6;
x6 = c3 * (x0 + x3);
x3 = (-s3 - c3) * x3 + x6;
x0 = (s3 - c3) * x0 + x6;
/* Stage 3 */
x6 = x4 + x5;
x4 -= x5;
x5 = r2c6 * (x7 + x8);
x7 = (-r2s6 - r2c6) * x7 + x5;
x8 = (r2s6 - r2c6) * x8 + x5;
x5 = x0 + x2;
x0 -= x2;
x2 = x3 + x1;
x3 -= x1;
/* Stage 4 and output */
rows[i][0] = x6;
rows[i][4] = x4;
rows[i][2] = x8 >> 10;
rows[i][6] = x7 >> 10;
rows[i][7] = (x2 - x5) >> 10;
rows[i][1] = (x2 + x5) >> 10;
rows[i][3] = (x3 * r2) >> 17;
rows[i][5] = (x0 * r2) >> 17;
}
/* transform columns */
for (i = 0; i < 8; i++) {
x0 = rows[0][i];
x1 = rows[1][i];
x2 = rows[2][i];
x3 = rows[3][i];
x4 = rows[4][i];
x5 = rows[5][i];
x6 = rows[6][i];
x7 = rows[7][i];
/* Stage 1 */
x8 = x7 + x0;
x0 -= x7;
x7 = x1 + x6;
x1 -= x6;
x6 = x2 + x5;
x2 -= x5;
x5 = x3 + x4;
x3 -= x4;
/* Stage 2 */
x4 = x8 + x5;
x8 -= x5;
x5 = x7 + x6;
x7 -= x6;
x6 = c1 * (x1 + x2);
x2 = (-s1 - c1) * x2 + x6;
x1 = (s1 - c1) * x1 + x6;
x6 = c3 * (x0 + x3);
x3 = (-s3 - c3) * x3 + x6;
x0 = (s3 - c3) * x0 + x6;
/* Stage 3 */
x6 = x4 + x5;
x4 -= x5;
x5 = r2c6 * (x7 + x8);
x7 = (-r2s6 - r2c6) * x7 + x5;
x8 = (r2s6 - r2c6) * x8 + x5;
x5 = x0 + x2;
x0 -= x2;
x2 = x3 + x1;
x3 -= x1;
/* Stage 4 and output */
out[i * 8] = (double) ((x6 + 16) >> 3);
out[i * 8 + 1] = (double) ((x4 + 16) >> 3);
out[i * 8 + 2] = (double) ((x8 + 16384) >> 13);
out[i * 8 + 3] = (double) ((x7 + 16384) >> 13);
out[i * 8 + 4] = (double) ((x2 - x5 + 16384) >> 13);
out[i * 8 + 5] = (double) ((x2 + x5 + 16384) >> 13);
out[i * 8 + 6] = (double) (((x3 >> 8) * r2 + 8192) >> 12);
out[i * 8 + 7] = (double) (((x0 >> 8) * r2 + 8192) >> 12);
}
}
struct rspamd_image_cache_entry {
guchar digest[64];
guchar dct[RSPAMD_DCT_LEN / NBBY];
};
static void
rspamd_image_cache_entry_dtor (gpointer p)
{
struct rspamd_image_cache_entry *entry = p;
g_free (entry);
}
static guint32
rspamd_image_dct_hash (gconstpointer p)
{
return rspamd_cryptobox_fast_hash (p, rspamd_cryptobox_HASHBYTES,
rspamd_hash_seed ());
}
static gboolean
rspamd_image_dct_equal (gconstpointer a, gconstpointer b)
{
return memcmp (a, b, rspamd_cryptobox_HASHBYTES) == 0;
}
static void
rspamd_image_create_cache (struct rspamd_config *cfg)
{
images_hash = rspamd_lru_hash_new_full (cfg->images_cache_size, NULL,
rspamd_image_cache_entry_dtor,
rspamd_image_dct_hash, rspamd_image_dct_equal);
}
static gboolean
rspamd_image_check_hash (struct rspamd_task *task, struct rspamd_image *img)
{
struct rspamd_image_cache_entry *found;
if (images_hash == NULL) {
rspamd_image_create_cache (task->cfg);
}
found = rspamd_lru_hash_lookup (images_hash, img->parent->digest,
task->tv.tv_sec);
if (found) {
/* We need to decompress */
img->dct = g_malloc (RSPAMD_DCT_LEN / NBBY);
rspamd_mempool_add_destructor (task->task_pool, g_free,
img->dct);
/* Copy as found could be destroyed by LRU */
memcpy (img->dct, found->dct, RSPAMD_DCT_LEN / NBBY);
img->is_normalized = TRUE;
return TRUE;
}
return FALSE;
}
static void
rspamd_image_save_hash (struct rspamd_task *task, struct rspamd_image *img)
{
struct rspamd_image_cache_entry *found;
if (img->is_normalized) {
found = rspamd_lru_hash_lookup (images_hash, img->parent->digest,
task->tv.tv_sec);
if (!found) {
found = g_malloc0 (sizeof (*found));
memcpy (found->dct, img->dct, RSPAMD_DCT_LEN / NBBY);
memcpy (found->digest, img->parent->digest, sizeof (found->digest));
rspamd_lru_hash_insert (images_hash, found->digest, found,
task->tv.tv_sec, 0);
}
}
}
#endif
void
rspamd_image_normalize (struct rspamd_task *task, struct rspamd_image *img)
{
#ifdef USABLE_GD
gdImagePtr src = NULL, dst = NULL;
guint i, j, k, l;
gdouble *dct;
if (img->data->len == 0 || img->data->len > G_MAXINT32) {
return;
}
if (img->height <= RSPAMD_NORMALIZED_DIM ||
img->width <= RSPAMD_NORMALIZED_DIM) {
return;
}
if (img->data->len > task->cfg->max_pic_size) {
return;
}
if (rspamd_image_check_hash (task, img)) {
return;
}
switch (img->type) {
case IMAGE_TYPE_JPG:
src = gdImageCreateFromJpegPtr (img->data->len, (void *)img->data->begin);
break;
case IMAGE_TYPE_PNG:
src = gdImageCreateFromPngPtr (img->data->len, (void *)img->data->begin);
break;
case IMAGE_TYPE_GIF:
src = gdImageCreateFromGifPtr (img->data->len, (void *)img->data->begin);
break;
case IMAGE_TYPE_BMP:
src = gdImageCreateFromBmpPtr (img->data->len, (void *)img->data->begin);
break;
default:
return;
}
if (src == NULL) {
msg_info_task ("cannot load image of type %s from %T",
rspamd_image_type_str (img->type), img->filename);
}
else {
gdImageSetInterpolationMethod (src, GD_BILINEAR_FIXED);
dst = gdImageScale (src, RSPAMD_NORMALIZED_DIM, RSPAMD_NORMALIZED_DIM);
gdImageGrayScale (dst);
gdImageDestroy (src);
img->is_normalized = TRUE;
dct = g_malloc0 (sizeof (gdouble) * RSPAMD_DCT_LEN);
img->dct = g_malloc0 (RSPAMD_DCT_LEN / NBBY);
rspamd_mempool_add_destructor (task->task_pool, g_free,
img->dct);
/*
* Split message into blocks:
*
* ****
* ****
*
* Get sum of saturation values, and set bit if sum is > avg
* Then go further
*
* ****
* ****
*
* and repeat this algorithm.
*
* So on each iteration we move by 16 pixels and calculate 2 elements of
* signature
*/
for (i = 0; i < RSPAMD_NORMALIZED_DIM; i += 8) {
for (j = 0; j < RSPAMD_NORMALIZED_DIM; j += 8) {
gint p[8][8];
for (k = 0; k < 8; k ++) {
p[k][0] = gdImageGetPixel (dst, i + k, j);
p[k][1] = gdImageGetPixel (dst, i + k, j + 1);
p[k][2] = gdImageGetPixel (dst, i + k, j + 2);
p[k][3] = gdImageGetPixel (dst, i + k, j + 3);
p[k][4] = gdImageGetPixel (dst, i + k, j + 4);
p[k][5] = gdImageGetPixel (dst, i + k, j + 5);
p[k][6] = gdImageGetPixel (dst, i + k, j + 6);
p[k][7] = gdImageGetPixel (dst, i + k, j + 7);
}
rspamd_image_dct_block (p,
dct + i * RSPAMD_NORMALIZED_DIM + j);
gdouble avg = 0.0;
for (k = 0; k < 8; k ++) {
for (l = 0; l < 8; l ++) {
gdouble x = *(dct +
i * RSPAMD_NORMALIZED_DIM + j + k * 8 + l);
avg += (x - avg) / (gdouble)(k * 8 + l + 1);
}
}
for (k = 0; k < 8; k ++) {
for (l = 0; l < 8; l ++) {
guint idx = i * RSPAMD_NORMALIZED_DIM + j + k * 8 + l;
if (dct[idx] >= avg) {
setbit (img->dct, idx);
}
}
}
}
}
gdImageDestroy (dst);
g_free (dct);
rspamd_image_save_hash (task, img);
}
#endif
}
struct rspamd_image*
rspamd_maybe_process_image (rspamd_mempool_t *pool,
rspamd_ftok_t *data)
{
enum rspamd_image_type type;
struct rspamd_image *img = NULL;
if ((type = detect_image_type (data)) != IMAGE_TYPE_UNKNOWN) {
switch (type) {
case IMAGE_TYPE_PNG:
img = process_png_image (pool, data);
break;
case IMAGE_TYPE_JPG:
img = process_jpg_image (pool, data);
break;
case IMAGE_TYPE_GIF:
img = process_gif_image (pool, data);
break;
case IMAGE_TYPE_BMP:
img = process_bmp_image (pool, data);
break;
default:
img = NULL;
break;
}
}
return img;
}
static bool
process_image (struct rspamd_task *task, struct rspamd_mime_part *part)
{
struct rspamd_image *img;
img = rspamd_maybe_process_image (task->task_pool, &part->parsed_data);
if (img != NULL) {
msg_debug_images ("detected %s image of size %ud x %ud",
rspamd_image_type_str (img->type),
img->width, img->height);
if (part->cd) {
img->filename = &part->cd->filename;
}
img->parent = part;
part->part_type = RSPAMD_MIME_PART_IMAGE;
part->specific.img = img;
return true;
}
return false;
}
const gchar *
rspamd_image_type_str (enum rspamd_image_type type)
{
switch (type) {
case IMAGE_TYPE_PNG:
return "PNG";
break;
case IMAGE_TYPE_JPG:
return "JPEG";
break;
case IMAGE_TYPE_GIF:
return "GIF";
break;
case IMAGE_TYPE_BMP:
return "BMP";
break;
default:
break;
}
return "unknown";
}
static void
rspamd_image_process_part (struct rspamd_task *task, struct rspamd_mime_part *part)
{
struct rspamd_mime_header *rh;
struct rspamd_mime_text_part *tp;
struct html_image *himg;
const gchar *cid, *html_cid;
guint cid_len, i, j;
struct rspamd_image *img;
img = (struct rspamd_image *)part->specific.img;
if (img) {
/* Check Content-Id */
rh = rspamd_message_get_header_from_hash (part->raw_headers,
"Content-Id");
if (rh) {
cid = rh->decoded;
if (*cid == '<') {
cid ++;
}
cid_len = strlen (cid);
if (cid_len > 0) {
if (cid[cid_len - 1] == '>') {
cid_len --;
}
PTR_ARRAY_FOREACH (MESSAGE_FIELD (task, text_parts), i, tp) {
if (IS_PART_HTML (tp) && tp->html != NULL &&
tp->html->images != NULL) {
for (j = 0; j < tp->html->images->len; j ++) {
himg = g_ptr_array_index (tp->html->images, j);
if ((himg->flags & RSPAMD_HTML_FLAG_IMAGE_EMBEDDED) &&
himg->src) {
html_cid = himg->src;
if (strncmp (html_cid, "cid:", 4) == 0) {
html_cid += 4;
}
if (strlen (html_cid) == cid_len &&
memcmp (html_cid, cid, cid_len) == 0) {
img->html_image = himg;
himg->embedded_image = img;
msg_debug_images ("found linked image by cid: <%s>",
cid);
if (himg->height == 0) {
himg->height = img->height;
}
if (himg->width == 0) {
himg->width = img->width;
}
}
}
}
}
}
}
}
}
}
void
rspamd_images_link (struct rspamd_task *task)
{
struct rspamd_mime_part *part;
guint i;
PTR_ARRAY_FOREACH (MESSAGE_FIELD (task, parts), i, part) {
if (part->part_type == RSPAMD_MIME_PART_IMAGE) {
rspamd_image_process_part (task, part);
}
}
} | 22.400815 | 84 | 0.607448 | [
"transform"
] |
c55aa3ec8c8c26d3d06ab866495a5437e8538a0d | 5,374 | h | C | webkit/appcache/appcache.h | meego-tablet-ux/meego-app-browser | 0f4ef17bd4b399c9c990a2f6ca939099495c2b9c | [
"BSD-3-Clause"
] | 1 | 2015-10-12T09:14:22.000Z | 2015-10-12T09:14:22.000Z | webkit/appcache/appcache.h | meego-tablet-ux/meego-app-browser | 0f4ef17bd4b399c9c990a2f6ca939099495c2b9c | [
"BSD-3-Clause"
] | null | null | null | webkit/appcache/appcache.h | meego-tablet-ux/meego-app-browser | 0f4ef17bd4b399c9c990a2f6ca939099495c2b9c | [
"BSD-3-Clause"
] | 1 | 2020-11-04T07:22:28.000Z | 2020-11-04T07:22:28.000Z | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef WEBKIT_APPCACHE_APPCACHE_H_
#define WEBKIT_APPCACHE_APPCACHE_H_
#include <map>
#include <set>
#include <vector>
#include "base/gtest_prod_util.h"
#include "base/memory/ref_counted.h"
#include "base/time.h"
#include "googleurl/src/gurl.h"
#include "webkit/appcache/appcache_database.h"
#include "webkit/appcache/appcache_entry.h"
#include "webkit/appcache/manifest_parser.h"
namespace appcache {
class AppCacheGroup;
class AppCacheHost;
class AppCacheService;
// Set of cached resources for an application. A cache exists as long as a
// host is associated with it, the cache is in an appcache group or the
// cache is being created during an appcache upate.
class AppCache : public base::RefCounted<AppCache> {
public:
typedef std::map<GURL, AppCacheEntry> EntryMap;
typedef std::set<AppCacheHost*> AppCacheHosts;
AppCache(AppCacheService *service, int64 cache_id);
int64 cache_id() const { return cache_id_; }
AppCacheGroup* owning_group() const { return owning_group_; }
bool is_complete() const { return is_complete_; }
void set_complete(bool value) { is_complete_ = value; }
AppCacheService* service() const { return service_; }
// Adds a new entry. Entry must not already be in cache.
void AddEntry(const GURL& url, const AppCacheEntry& entry);
// Adds a new entry or modifies an existing entry by merging the types
// of the new entry with the existing entry. Returns true if a new entry
// is added, false if the flags are merged into an existing entry.
bool AddOrModifyEntry(const GURL& url, const AppCacheEntry& entry);
// Removes an entry from the EntryMap, the URL must be in the set.
void RemoveEntry(const GURL& url);
// Do not store the returned object as it could be deleted anytime.
AppCacheEntry* GetEntry(const GURL& url);
const EntryMap& entries() const { return entries_; }
// Returns the URL of the resource used as the fallback for 'namespace_url'.
GURL GetFallbackEntryUrl(const GURL& namespace_url) const;
AppCacheHosts& associated_hosts() { return associated_hosts_; }
bool IsNewerThan(AppCache* cache) const {
// TODO(michaeln): revisit, the system clock can be set
// back in time which would confuse this logic.
if (update_time_ > cache->update_time_)
return true;
// Tie breaker. Newer caches have a larger cache ID.
if (update_time_ == cache->update_time_)
return cache_id_ > cache->cache_id_;
return false;
}
base::Time update_time() const { return update_time_; }
int64 cache_size() const { return cache_size_; }
void set_update_time(base::Time ticks) { update_time_ = ticks; }
// Initializes the cache with information in the manifest.
// Do not use the manifest after this call.
void InitializeWithManifest(Manifest* manifest);
// Initializes the cache with the information in the database records.
void InitializeWithDatabaseRecords(
const AppCacheDatabase::CacheRecord& cache_record,
const std::vector<AppCacheDatabase::EntryRecord>& entries,
const std::vector<AppCacheDatabase::FallbackNameSpaceRecord>& fallbacks,
const std::vector<AppCacheDatabase::OnlineWhiteListRecord>& whitelists);
// Returns the database records to be stored in the AppCacheDatabase
// to represent this cache.
void ToDatabaseRecords(
const AppCacheGroup* group,
AppCacheDatabase::CacheRecord* cache_record,
std::vector<AppCacheDatabase::EntryRecord>* entries,
std::vector<AppCacheDatabase::FallbackNameSpaceRecord>* fallbacks,
std::vector<AppCacheDatabase::OnlineWhiteListRecord>* whitelists);
bool FindResponseForRequest(const GURL& url,
AppCacheEntry* found_entry, AppCacheEntry* found_fallback_entry,
GURL* found_fallback_namespace, bool* found_network_namespace);
static bool IsInNetworkNamespace(
const GURL& url,
const std::vector<GURL> &namespaces);
private:
friend class AppCacheGroup;
friend class AppCacheHost;
friend class AppCacheStorageImplTest;
friend class AppCacheUpdateJobTest;
friend class base::RefCounted<AppCache>;
~AppCache();
// Use AppCacheGroup::Add/RemoveCache() to manipulate owning group.
void set_owning_group(AppCacheGroup* group) { owning_group_ = group; }
// FindResponseForRequest helpers
FallbackNamespace* FindFallbackNamespace(const GURL& url);
// Use AppCacheHost::AssociateCache() to manipulate host association.
void AssociateHost(AppCacheHost* host) {
associated_hosts_.insert(host);
}
void UnassociateHost(AppCacheHost* host);
const int64 cache_id_;
scoped_refptr<AppCacheGroup> owning_group_;
AppCacheHosts associated_hosts_;
EntryMap entries_; // contains entries of all types
std::vector<FallbackNamespace> fallback_namespaces_;
std::vector<GURL> online_whitelist_namespaces_;
bool online_whitelist_all_;
bool is_complete_;
// when this cache was last updated
base::Time update_time_;
int64 cache_size_;
// to notify service when cache is deleted
AppCacheService* service_;
FRIEND_TEST_ALL_PREFIXES(AppCacheTest, InitializeWithManifest);
DISALLOW_COPY_AND_ASSIGN(AppCache);
};
} // namespace appcache
#endif // WEBKIT_APPCACHE_APPCACHE_H_
| 33.17284 | 78 | 0.754373 | [
"object",
"vector"
] |
c55c5b24343fd1e7eb7c6280fc1343e1a081fe98 | 16,391 | c | C | HotSniper/hotspot/RCutil.c | fklemme/HotSniper | d75afd0636350685967e2ebad0fecc1f0a3b31e3 | [
"MIT"
] | null | null | null | HotSniper/hotspot/RCutil.c | fklemme/HotSniper | d75afd0636350685967e2ebad0fecc1f0a3b31e3 | [
"MIT"
] | null | null | null | HotSniper/hotspot/RCutil.c | fklemme/HotSniper | d75afd0636350685967e2ebad0fecc1f0a3b31e3 | [
"MIT"
] | null | null | null | /*
* Thanks to Greg Link from Penn State University
* for his math acceleration engine. Where available,
* the modified version of the engine found here, uses
* the fast, vendor-provided linear algebra routines
* from the BLAS and LAPACK packages in lieu of
* the vanilla C code present in the matrix functions
* of the previous versions of HotSpot.
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <math.h>
#include "temperature.h"
#include "flp.h"
#include "util.h"
/* thermal resistance calculation */
double getr(double conductivity, double thickness, double area)
{
return thickness / (conductivity * area);
}
/* thermal capacitance calculation */
double getcap(double sp_heat, double thickness, double area)
{
/* include lumped vs. distributed correction */
return C_FACTOR * sp_heat * thickness * area;
}
/*
* LUP decomposition from the pseudocode given in the CLR
* 'Introduction to Algorithms' textbook. The matrix 'a' is
* transformed into an in-place lower/upper triangular matrix
* and the vector'p' carries the permutation vector such that
* Pa = lu, where 'P' is the matrix form of 'p'. The 'spd' flag
* indicates that 'a' is symmetric and positive definite
*/
void lupdcmp(double**a, int n, int *p, int spd)
{
#if(MATHACCEL == MA_INTEL)
int info = 0;
if (!spd)
dgetrf(&n, &n, a[0], &n, p, &info);
else
dpotrf("U", &n, a[0], &n, &info);
assert(info == 0);
#elif(MATHACCEL == MA_AMD)
int info = 0;
if (!spd)
dgetrf_(&n, &n, a[0], &n, p, &info);
else
dpotrf_("U", &n, a[0], &n, &info, 1);
assert(info == 0);
#elif(MATHACCEL == MA_APPLE)
int info = 0;
if (!spd)
dgetrf_((__CLPK_integer *)&n, (__CLPK_integer *)&n, a[0],
(__CLPK_integer *)&n, (__CLPK_integer *)p,
(__CLPK_integer *)&info);
else
dpotrf_("U", (__CLPK_integer *)&n, a[0], (__CLPK_integer *)&n,
(__CLPK_integer *)&info);
assert(info == 0);
#elif(MATHACCEL == MA_SUN)
int info = 0;
if (!spd)
dgetrf_(&n, &n, a[0], &n, p, &info);
else
dpotrf_("U", &n, a[0], &n, &info);
assert(info == 0);
#else
int i, j, k, pivot=0;
double max = 0;
/* start with identity permutation */
for (i=0; i < n; i++)
p[i] = i;
for (k=0; k < n-1; k++) {
max = 0;
for (i = k; i < n; i++) {
if (fabs(a[i][k]) > max) {
max = fabs(a[i][k]);
pivot = i;
}
}
if (eq (max, 0))
fatal ("singular matrix in lupdcmp\n");
/* bring pivot element to position */
swap_ival (&p[k], &p[pivot]);
for (i=0; i < n; i++)
swap_dval (&a[k][i], &a[pivot][i]);
for (i=k+1; i < n; i++) {
a[i][k] /= a[k][k];
for (j=k+1; j < n; j++)
a[i][j] -= a[i][k] * a[k][j];
}
}
#endif
}
/*
* the matrix a is an in-place lower/upper triangular matrix
* the following macros split them into their constituents
*/
#define LOWER(a, i, j) ((i > j) ? a[i][j] : 0)
#define UPPER(a, i, j) ((i <= j) ? a[i][j] : 0)
/*
* LU forward and backward substitution from the pseudocode given
* in the CLR 'Introduction to Algorithms' textbook. It solves ax = b
* where, 'a' is an in-place lower/upper triangular matrix. The vector
* 'x' carries the solution vector. 'p' is the permutation vector. The
* 'spd' flag indicates that 'a' is symmetric and positive definite
*/
void lusolve(double **a, int n, int *p, double *b, double *x, int spd)
{
#if(MATHACCEL == MA_INTEL)
int one = 1, info = 0;
cblas_dcopy(n, b, 1, x, 1);
if (!spd)
dgetrs("T", &n, &one, a[0], &n, p, x, &n, &info);
else
dpotrs("U", &n, &one, a[0], &n, x, &n, &info);
assert(info == 0);
#elif(MATHACCEL == MA_AMD)
int one = 1, info = 0;
dcopy(n, b, 1, x, 1);
if (!spd)
dgetrs_("T", &n, &one, a[0], &n, p, x, &n, &info, 1);
else
dpotrs_("U", &n, &one, a[0], &n, x, &n, &info, 1);
assert(info == 0);
#elif(MATHACCEL == MA_APPLE)
int one = 1, info = 0;
cblas_dcopy(n, b, 1, x, 1);
if (!spd)
dgetrs_("T", (__CLPK_integer *)&n, (__CLPK_integer *)&one, a[0],
(__CLPK_integer *)&n, (__CLPK_integer *)p, x,
(__CLPK_integer *)&n, (__CLPK_integer *)&info);
else
dpotrs_("U", (__CLPK_integer *)&n, (__CLPK_integer *)&one, a[0],
(__CLPK_integer *)&n, x, (__CLPK_integer *)&n,
(__CLPK_integer *)&info);
assert(info == 0);
#elif(MATHACCEL == MA_SUN)
int one = 1, info = 0;
dcopy(n, b, 1, x, 1);
if (!spd)
dgetrs_("T", &n, &one, a[0], &n, p, x, &n, &info);
else
dpotrs_("U", &n, &one, a[0], &n, x, &n, &info);
assert(info == 0);
#else
int i, j;
double *y = dvector (n);
double sum;
/* forward substitution - solves ly = pb */
for (i=0; i < n; i++) {
for (j=0, sum=0; j < i; j++)
sum += y[j] * LOWER(a, i, j);
y[i] = b[p[i]] - sum;
}
/* backward substitution - solves ux = y */
for (i=n-1; i >= 0; i--) {
for (j=i+1, sum=0; j < n; j++)
sum += x[j] * UPPER(a, i, j);
x[i] = (y[i] - sum) / UPPER(a, i, i);
}
free_dvector(y);
#endif
}
/* core of the 4th order Runge-Kutta method, where the Euler step
* (y(n+1) = y(n) + h * k1 where k1 = dydx(n)) is provided as an input.
* to evaluate dydx at different points, a call back function f (slope
* function) is also passed as a parameter. Given values for y, and k1,
* this function advances the solution over an interval h, and returns
* the solution in yout. For details, see the discussion in "Numerical
* Recipes in C", Chapter 16, from
* http://www.nrbook.com/a/bookcpdf/c16-1.pdf
*/
void rk4_core(void *model, double *y, double *k1, void *p, int n, double h, double *yout, slope_fn_ptr f)
{
int i;
double *t, *k2, *k3, *k4;
k2 = dvector(n);
k3 = dvector(n);
k4 = dvector(n);
t = dvector(n);
/* k2 is the slope at the trial midpoint (t) found using
* slope k1 (which is at the starting point).
*/
/* t = y + h/2 * k1 (t = y; t += h/2 * k1) */
#if (MATHACCEL == MA_INTEL || MATHACCEL == MA_APPLE)
cblas_dcopy(n, y, 1, t, 1);
cblas_daxpy(n, h/2.0, k1, 1, t, 1);
#elif (MATHACCEL == MA_AMD || MATHACCEL == MA_SUN)
dcopy(n, y, 1, t, 1);
daxpy(n, h/2.0, k1, 1, t, 1);
#else
for(i=0; i < n; i++)
t[i] = y[i] + h/2.0 * k1[i];
#endif
/* k2 = slope at t */
(*f)(model, t, p, k2);
/* k3 is the slope at the trial midpoint (t) found using
* slope k2 found above.
*/
/* t = y + h/2 * k2 (t = y; t += h/2 * k2) */
#if (MATHACCEL == MA_INTEL || MATHACCEL == MA_APPLE)
cblas_dcopy(n, y, 1, t, 1);
cblas_daxpy(n, h/2.0, k2, 1, t, 1);
#elif (MATHACCEL == MA_AMD || MATHACCEL == MA_SUN)
dcopy(n, y, 1, t, 1);
daxpy(n, h/2.0, k2, 1, t, 1);
#else
for(i=0; i < n; i++)
t[i] = y[i] + h/2.0 * k2[i];
#endif
/* k3 = slope at t */
(*f)(model, t, p, k3);
/* k4 is the slope at trial endpoint (t) found using
* slope k3 found above.
*/
/* t = y + h * k3 (t = y; t += h * k3) */
#if (MATHACCEL == MA_INTEL || MATHACCEL == MA_APPLE)
cblas_dcopy(n, y, 1, t, 1);
cblas_daxpy(n, h, k3, 1, t, 1);
#elif (MATHACCEL == MA_AMD || MATHACCEL == MA_SUN)
dcopy(n, y, 1, t, 1);
daxpy(n, h, k3, 1, t, 1);
#else
for(i=0; i < n; i++)
t[i] = y[i] + h * k3[i];
#endif
/* k4 = slope at t */
(*f)(model, t, p, k4);
/* yout = y + h*(k1/6 + k2/3 + k3/3 + k4/6) */
#if (MATHACCEL == MA_INTEL || MATHACCEL == MA_APPLE)
/* yout = y */
cblas_dcopy(n, y, 1, yout, 1);
/* yout += h*k1/6 */
cblas_daxpy(n, h/6.0, k1, 1, yout, 1);
/* yout += h*k2/3 */
cblas_daxpy(n, h/3.0, k2, 1, yout, 1);
/* yout += h*k3/3 */
cblas_daxpy(n, h/3.0, k3, 1, yout, 1);
/* yout += h*k4/6 */
cblas_daxpy(n, h/6.0, k4, 1, yout, 1);
#elif (MATHACCEL == MA_AMD || MATHACCEL == MA_SUN)
dcopy(n, y, 1, yout, 1);
/* yout += h*k1/6 */
daxpy(n, h/6.0, k1, 1, yout, 1);
/* yout += h*k2/3 */
daxpy(n, h/3.0, k2, 1, yout, 1);
/* yout += h*k3/3 */
daxpy(n, h/3.0, k3, 1, yout, 1);
/* yout += h*k4/6 */
daxpy(n, h/6.0, k4, 1, yout, 1);
#else
for (i =0; i < n; i++)
yout[i] = y[i] + h * (k1[i] + 2*k2[i] + 2*k3[i] + k4[i])/6.0;
#endif
free_dvector(k2);
free_dvector(k3);
free_dvector(k4);
free_dvector(t);
}
/*
* 4th order Runge Kutta solver with adaptive step sizing.
* It integrates and solves the ODE dy + cy = p between
* t and t+h. It returns the correct step size to be used
* next time. slope function f is the call back used to
* evaluate the derivative at each point
*/
#define RK4_SAFETY 0.95
#define RK4_MAXUP 5.0
#define RK4_MAXDOWN 10.0
#define RK4_PRECISION 0.01
double rk4(void *model, double *y, void *p, int n, double *h, double *yout, slope_fn_ptr f)
{
int i;
double *k1, *t1, *t2, *ytemp, max, new_h = (*h);
k1 = dvector(n);
t1 = dvector(n);
t2 = dvector(n);
ytemp = dvector(n);
/* evaluate the slope k1 at the beginning */
(*f)(model, y, p, k1);
/* try until accuracy is achieved */
do {
(*h) = new_h;
/* try RK4 once with normal step size */
rk4_core(model, y, k1, p, n, (*h), ytemp, f);
/* repeat it with two half-steps */
rk4_core(model, y, k1, p, n, (*h)/2.0, t1, f);
/* y after 1st half-step is in t1. re-evaluate k1 for this */
(*f)(model, t1, p, k1);
/* get output of the second half-step in t2 */
rk4_core(model, t1, k1, p, n, (*h)/2.0, t2, f);
/* find the max diff between these two results:
* use t1 to store the diff
*/
#if (MATHACCEL == MA_INTEL || MATHACCEL == MA_APPLE)
/* t1 = ytemp */
cblas_dcopy(n, ytemp, 1, t1, 1);
/* t1 = -1 * t2 + t1 = ytemp - t2 */
cblas_daxpy(n, -1.0, t2, 1, t1, 1);
/* max = |t1[max_abs_index]| */
max = fabs(t1[cblas_idamax(n, t1, 1)]);
#elif (MATHACCEL == MA_AMD || MATHACCEL == MA_SUN)
/* t1 = ytemp */
dcopy(n, ytemp, 1, t1, 1);
/* t1 = -1 * t2 + t1 = ytemp - t2 */
daxpy(n, -1.0, t2, 1, t1, 1);
/*
* max = |t1[max_abs_index]| note: FORTRAN BLAS
* indices start from 1 as opposed to CBLAS where
* indices start from 0
*/
max = fabs(t1[idamax(n, t1, 1)-1]);
#else
for(i=0; i < n; i++)
t1[i] = fabs(ytemp[i] - t2[i]);
max = t1[0];
for(i=1; i < n; i++)
if (max < t1[i])
max = t1[i];
#endif
/*
* compute the correct step size: see equation
* 16.2.10 in chapter 16 of "Numerical Recipes
* in C"
*/
/* accuracy OK. increase step size */
if (max <= RK4_PRECISION) {
new_h = RK4_SAFETY * (*h) * pow(fabs(RK4_PRECISION/max), 0.2);
if (new_h > RK4_MAXUP * (*h))
new_h = RK4_MAXUP * (*h);
/* inaccuracy error. decrease step size and compute again */
} else {
new_h = RK4_SAFETY * (*h) * pow(fabs(RK4_PRECISION/max), 0.25);
if (new_h < (*h) / RK4_MAXDOWN)
new_h = (*h) / RK4_MAXDOWN;
}
} while (new_h < (*h));
/* commit ytemp to yout */
#if (MATHACCEL == MA_INTEL || MATHACCEL == MA_APPLE)
cblas_dcopy(n, ytemp, 1, yout, 1);
#elif (MATHACCEL == MA_AMD || MATHACCEL == MA_SUN)
dcopy(n, ytemp, 1, yout, 1);
#else
copy_dvector(yout, ytemp, n);
#endif
/* clean up */
free_dvector(k1);
free_dvector(t1);
free_dvector(t2);
free_dvector(ytemp);
/* return the step-size */
return new_h;
}
/* matmult: C = AB, A, B are n x n square matrices */
void matmult(double **c, double **a, double **b, int n)
{
#if (MATHACCEL == MA_INTEL || MATHACCEL == MA_APPLE)
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
n, n, n, 1.0, a[0], n, b[0], n, 0.0, c[0], n);
#elif (MATHACCEL == MA_AMD || MATHACCEL == MA_SUN)
/* B^T * A^T = (A * B)^T */
dgemm('N', 'N', n, n, n, 1.0, b[0], n, a[0], n, 0.0, c[0], n);
#else
int i, j, k;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++) {
c[i][j] = 0;
for (k = 0; k < n; k++)
c[i][j] += a[i][k] * b[k][j];
}
#endif
}
/* same as above but 'a' is a diagonal matrix stored as a 1-d array */
void diagmatmult(double **c, double *a, double **b, int n)
{
int i;
#if (MATHACCEL == MA_INTEL || MATHACCEL == MA_APPLE)
zero_dmatrix(c, n, n);
for(i=0; i < n; i++)
cblas_daxpy(n, a[i], b[i], 1, c[i], 1);
#elif (MATHACCEL == MA_AMD || MATHACCEL == MA_SUN)
zero_dmatrix(c, n, n);
for(i=0; i < n; i++)
daxpy(n, a[i], b[i], 1, c[i], 1);
#else
int j;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
c[i][j] = a[i] * b[i][j];
#endif
}
/* mult of an n x n matrix and an n x 1 column vector */
void matvectmult(double *vout, double **m, double *vin, int n)
{
#if (MATHACCEL == MA_INTEL || MATHACCEL == MA_APPLE)
cblas_dgemv(CblasRowMajor, CblasNoTrans, n, n, 1.0, m[0],
n, vin, 1, 0.0, vout, 1);
#elif (MATHACCEL == MA_AMD || MATHACCEL == MA_SUN)
dgemv('T', n, n, 1.0, m[0], n, vin, 1, 0.0, vout, 1);
#else
int i, j;
for (i = 0; i < n; i++) {
vout[i] = 0;
for (j = 0; j < n; j++)
vout[i] += m[i][j] * vin[j];
}
#endif
}
/* same as above but 'm' is a diagonal matrix stored as a 1-d array */
void diagmatvectmult(double *vout, double *m, double *vin, int n)
{
#if (MATHACCEL == MA_INTEL || MATHACCEL == MA_APPLE)
cblas_dsbmv(CblasRowMajor, CblasUpper, n, 0, 1.0, m, 1, vin,
1, 0.0, vout, 1);
#elif (MATHACCEL == MA_AMD || MATHACCEL == MA_SUN)
dsbmv('U', n, 0, 1.0, m, 1, vin, 1, 0.0, vout, 1);
#else
int i;
for (i = 0; i < n; i++)
vout[i] = m[i] * vin[i];
#endif
}
/*
* inv = m^-1, inv, m are n by n matrices.
* the spd flag indicates that m is symmetric
* and positive definite
*/
#define BLOCK_SIZE 256
void matinv(double **inv, double **m, int n, int spd)
{
int *p, lwork;
double *work;
int i, j;
#if (MATHACCEL != MA_NONE)
int info;
#endif
double *col;
p = ivector(n);
lwork = n * BLOCK_SIZE;
work = dvector(lwork);
#if (MATHACCEL == MA_INTEL)
info = 0;
cblas_dcopy(n*n, m[0], 1, inv[0], 1);
if (!spd) {
dgetrf(&n, &n, inv[0], &n, p, &info);
assert(info == 0);
dgetri(&n, inv[0], &n, p, work, &lwork, &info);
assert(info == 0);
} else {
dpotrf("U", &n, inv[0], &n, &info);
assert(info == 0);
dpotri("U", &n, inv[0], &n, &info);
assert(info == 0);
mirror_dmatrix(inv, n);
}
#elif(MATHACCEL == MA_AMD)
info = 0;
dcopy(n*n, m[0], 1, inv[0], 1);
if (!spd) {
dgetrf_(&n, &n, inv[0], &n, p, &info);
assert(info == 0);
dgetri_(&n, inv[0], &n, p, work, &lwork, &info);
assert(info == 0);
} else {
dpotrf_("U", &n, inv[0], &n, &info, 1);
assert(info == 0);
dpotri_("U", &n, inv[0], &n, &info, 1);
assert(info == 0);
mirror_dmatrix(inv, n);
}
#elif (MATHACCEL == MA_APPLE)
info = 0;
cblas_dcopy(n*n, m[0], 1, inv[0], 1);
if (!spd) {
dgetrf_((__CLPK_integer *)&n, (__CLPK_integer *)&n,
inv[0], (__CLPK_integer *)&n, (__CLPK_integer *)p,
(__CLPK_integer *)&info);
assert(info == 0);
dgetri_((__CLPK_integer *)&n, inv[0], (__CLPK_integer *)&n,
(__CLPK_integer *)p, work, (__CLPK_integer *)&lwork,
(__CLPK_integer *)&info);
assert(info == 0);
} else {
dpotrf_("U", (__CLPK_integer *)&n, inv[0], (__CLPK_integer *)&n,
(__CLPK_integer *)&info);
assert(info == 0);
dpotri_("U", (__CLPK_integer *)&n, inv[0], (__CLPK_integer *)&n,
(__CLPK_integer *)&info);
assert(info == 0);
mirror_dmatrix(inv, n);
}
#elif(MATHACCEL == MA_SUN)
info = 0;
dcopy(n*n, m[0], 1, inv[0], 1);
if (!spd) {
dgetrf_(&n, &n, inv[0], &n, p, &info);
assert(info == 0);
dgetri_(&n, inv[0], &n, p, work, &lwork, &info);
assert(info == 0);
} else {
dpotrf_("U", &n, inv[0], &n, &info);
assert(info == 0);
dpotri_("U", &n, inv[0], &n, &info);
assert(info == 0);
mirror_dmatrix(inv, n);
}
#else
col = dvector(n);
lupdcmp(m, n, p, spd);
for (j = 0; j < n; j++) {
for (i = 0; i < n; i++) col[i]=0.0;
col[j] = 1.0;
lusolve(m, n, p, col, work, spd);
for (i = 0; i < n; i++) inv[i][j]=work[i];
}
free_dvector(col);
#endif
free_ivector(p);
free_dvector(work);
}
/* dst = src1 + scale * src2 */
void scaleadd_dvector (double *dst, double *src1, double *src2, int n, double scale)
{
#if (MATHACCEL == MA_NONE)
int i;
for(i=0; i < n; i++)
dst[i] = src1[i] + scale * src2[i];
#else
/* dst == src2. so, dst *= scale, dst += src1 */
if (dst == src2 && dst != src1) {
#if (MATHACCEL == MA_INTEL || MATHACCEL == MA_APPLE)
cblas_dscal(n, scale, dst, 1);
cblas_daxpy(n, 1.0, src1, 1, dst, 1);
#elif (MATHACCEL == MA_AMD || MATHACCEL == MA_SUN)
dscal(n, scale, dst, 1);
daxpy(n, 1.0, src1, 1, dst, 1);
#else
fatal("unknown math acceleration\n");
#endif
/* dst = src1; dst += scale * src2 */
} else {
#if (MATHACCEL == MA_INTEL || MATHACCEL == MA_APPLE)
cblas_dcopy(n, src1, 1, dst, 1);
cblas_daxpy(n, scale, src2, 1, dst, 1);
#elif (MATHACCEL == MA_AMD || MATHACCEL == MA_SUN)
dcopy(n, src1, 1, dst, 1);
daxpy(n, scale, src2, 1, dst, 1);
#else
fatal("unknown math acceleration\n");
#endif
}
#endif
}
| 26.914614 | 105 | 0.569581 | [
"vector",
"model"
] |
c55e2f01fb280685e7c035d85b74e89173b3e295 | 7,928 | h | C | src/kvstore/plugins/hbase/HBaseStore.h | nianiaJR/nebula | ec283188cb18466542954d1f8d2c9346563a1a40 | [
"Apache-2.0"
] | 1 | 2020-03-06T02:30:55.000Z | 2020-03-06T02:30:55.000Z | src/kvstore/plugins/hbase/HBaseStore.h | nianiaJR/nebula | ec283188cb18466542954d1f8d2c9346563a1a40 | [
"Apache-2.0"
] | null | null | null | src/kvstore/plugins/hbase/HBaseStore.h | nianiaJR/nebula | ec283188cb18466542954d1f8d2c9346563a1a40 | [
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2019 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#ifndef KVSTORE_PLUGINS_HBASE_HBASESTORE_H_
#define KVSTORE_PLUGINS_HBASE_HBASESTORE_H_
#include "base/Base.h"
#include "meta/SchemaProviderIf.h"
#include "meta/SchemaManager.h"
#include "kvstore/KVStore.h"
#include "kvstore/KVIterator.h"
#include "kvstore/plugins/hbase/HBaseClient.h"
#include <gtest/gtest_prod.h>
namespace nebula {
namespace kvstore {
class HBaseRangeIter : public KVIterator {
public:
HBaseRangeIter(KVArrayIterator begin, KVArrayIterator end)
: current_(begin)
, begin_(begin)
, end_(end) {}
~HBaseRangeIter() = default;
bool valid() const override {
return current_ != end_;
}
void next() override {
CHECK(current_ != end_);
current_++;
}
void prev() override {
CHECK(current_ != begin_);
current_--;
}
folly::StringPiece key() const override {
return folly::StringPiece(current_->first);
}
folly::StringPiece val() const override {
return folly::StringPiece(current_->second);
}
private:
KVArrayIterator current_;
KVArrayIterator begin_;
KVArrayIterator end_;
};
class HBaseStore : public KVStore {
public:
explicit HBaseStore(KVOptions options);
~HBaseStore() = default;
// Connect to the HBase thrift server.
void init();
uint32_t capability() const override {
return 0;
}
// Return the current leader
ErrorOr<ResultCode, HostAddr> partLeader(GraphSpaceID spaceId, PartitionID partId) override {
UNUSED(spaceId);
UNUSED(partId);
return {-1, -1};
}
ResultCode get(GraphSpaceID spaceId,
PartitionID partId,
const std::string& key,
std::string* value) override;
std::pair<ResultCode, std::vector<Status>> multiGet(
GraphSpaceID spaceId,
PartitionID partId,
const std::vector<std::string>& keys,
std::vector<std::string>* values) override;
// Get all results in range [start, end)
ResultCode range(GraphSpaceID spaceId,
PartitionID partId,
const std::string& start,
const std::string& end,
std::unique_ptr<KVIterator>* iter) override;
// Since the `range' interface will hold references to its 3rd & 4th parameter, in `iter',
// thus the arguments must outlive `iter'.
// Here we forbid one to invoke `range' with rvalues, which is the common mistake.
ResultCode range(GraphSpaceID spaceId,
PartitionID partId,
std::string&& start,
std::string&& end,
std::unique_ptr<KVIterator>* iter) override = delete;
// Get all results with prefix.
ResultCode prefix(GraphSpaceID spaceId,
PartitionID partId,
const std::string& prefix,
std::unique_ptr<KVIterator>* iter) override;
// To forbid to pass rvalue via the `prefix' parameter.
ResultCode prefix(GraphSpaceID spaceId,
PartitionID partId,
std::string&& prefix,
std::unique_ptr<KVIterator>* iter) override = delete;
// Get all results with prefix starting from start
ResultCode rangeWithPrefix(GraphSpaceID spaceId,
PartitionID partId,
const std::string& start,
const std::string& prefix,
std::unique_ptr<KVIterator>* iter) override;
// To forbid to pass rvalue via the `rangeWithPrefix' parameter.
ResultCode rangeWithPrefix(GraphSpaceID spaceId,
PartitionID partId,
std::string&& start,
std::string&& prefix,
std::unique_ptr<KVIterator>* iter) override = delete;
ResultCode sync(GraphSpaceID spaceId, PartitionID partId) override;
// async batch put.
void asyncMultiPut(GraphSpaceID spaceId,
PartitionID partId,
std::vector<KV> keyValues,
KVCallback cb) override;
void asyncRemove(GraphSpaceID spaceId,
PartitionID partId,
const std::string& key,
KVCallback cb) override;
void asyncMultiRemove(GraphSpaceID spaceId,
PartitionID partId,
std::vector<std::string> keys,
KVCallback cb) override;
void asyncRemoveRange(GraphSpaceID spaceId,
PartitionID partId,
const std::string& start,
const std::string& end,
KVCallback cb) override;
void asyncRemovePrefix(GraphSpaceID spaceId,
PartitionID partId,
const std::string& prefix,
KVCallback cb) override;
void asyncAtomicOp(GraphSpaceID,
PartitionID,
raftex::AtomicOp,
KVCallback) override {
LOG(FATAL) << "Not supportted yet!";
}
ResultCode ingest(GraphSpaceID spaceId) override;
int32_t allLeader(std::unordered_map<GraphSpaceID,
std::vector<PartitionID>>& leaderIds) override;
ErrorOr<ResultCode, std::shared_ptr<Part>> part(GraphSpaceID,
PartitionID) override {
return ResultCode::ERR_UNSUPPORTED;
}
ResultCode compact(GraphSpaceID) override {
return ResultCode::ERR_UNSUPPORTED;
}
ResultCode flush(GraphSpaceID) override {
return ResultCode::ERR_UNSUPPORTED;
}
ResultCode createCheckpoint(GraphSpaceID, const std::string&) override {
return ResultCode::ERR_UNSUPPORTED;
}
ResultCode dropCheckpoint(GraphSpaceID, const std::string&) override {
return ResultCode::ERR_UNSUPPORTED;
}
ResultCode setWriteBlocking(GraphSpaceID, bool) override {
return ResultCode::ERR_UNSUPPORTED;
}
private:
std::string getRowKey(const std::string& key) {
return key.substr(sizeof(PartitionID), key.size() - sizeof(PartitionID));
}
inline std::string spaceIdToTableName(GraphSpaceID spaceId);
std::shared_ptr<const meta::SchemaProviderIf> getSchema(GraphSpaceID spaceId,
const std::string& key,
SchemaVer version = -1);
std::string encode(GraphSpaceID spaceId,
const std::string& key,
KVMap& values);
std::vector<KV> decode(GraphSpaceID spaceId,
const std::string& key,
std::string& encoded);
ResultCode range(GraphSpaceID spaceId,
const std::string& start,
const std::string& end,
std::unique_ptr<KVIterator>* iter);
ResultCode prefix(GraphSpaceID spaceId,
const std::string& prefix,
std::unique_ptr<KVIterator>* iter);
ResultCode multiRemove(GraphSpaceID spaceId,
std::vector<std::string>& keys);
private:
KVOptions options_;
std::unique_ptr<meta::SchemaManager> schemaMan_{nullptr};
std::unique_ptr<HBaseClient> client_{nullptr};
};
} // namespace kvstore
} // namespace nebula
#endif // KVSTORE_PLUGINS_HBASE_HBASESTORE_H_
| 32.896266 | 97 | 0.575807 | [
"vector"
] |
c55f64878e2a15fb99d55c30dc7749468eaba446 | 3,434 | h | C | Code/Libraries/3D/src/material.h | xordspar0/eldritch | 895639bbb7ccf72e0e8e7a4c5cf72a7915467679 | [
"Zlib"
] | null | null | null | Code/Libraries/3D/src/material.h | xordspar0/eldritch | 895639bbb7ccf72e0e8e7a4c5cf72a7915467679 | [
"Zlib"
] | null | null | null | Code/Libraries/3D/src/material.h | xordspar0/eldritch | 895639bbb7ccf72e0e8e7a4c5cf72a7915467679 | [
"Zlib"
] | 1 | 2020-06-28T13:27:34.000Z | 2020-06-28T13:27:34.000Z | #ifndef MATERIAL_H
#define MATERIAL_H
#include "3d.h"
#include "vector4.h"
#include "simplestring.h"
#include "array.h"
#include "vector2.h"
#include "vector.h"
#include "renderstates.h"
#include "shaderdataprovider.h"
#include "hashedstring.h"
class ITexture;
class IShaderProgram;
class IVertexDeclaration;
#define DEFAULT_NEWMATERIAL "Material_Min"
#define DEFAULT_NEWMATERIALHUD "Material_MinHUD"
#define MAT_NONE 0x00000000
#define MAT_PRESCRIBED 0x00000001 // For buckets that can only accept meshes when prescribed
#define MAT_ALPHA 0x00000002
#define MAT_HUD 0x00000004
#define MAT_WORLD 0x00000008 // i.e., not HUD
#define MAT_ANIMATED 0x00000010
#define MAT_FOREGROUND 0x00000020
#define MAT_INWORLDHUD 0x00000040
#define MAT_DYNAMIC 0x00000080
#define MAT_SHADOW 0x00000100 // shadow-caster, rendered again for every shadow-casting light
#define MAT_DEBUG_WORLD 0x10000000
#define MAT_DEBUG_HUD 0x20000000
#if BUILD_DEV
#define MAT_DEBUG_ALWAYS 0x40000000 // Always draw this, even if frustum-culled, etc.
#endif
#define MAT_ALWAYS 0x80000000 // Always draw this, even if frustum-culled, etc.
#define MAT_ALL 0xffffffff
class Material
{
public:
Material();
~Material();
void SetDefinition( const SimpleString& DefinitionName, IRenderer* const pRenderer, const uint VertexSignature );
void SetSamplerDefinition( const uint SamplerStage, const SimpleString& SamplerDefinitionName );
void SetTexture( const uint SamplerStage, ITexture* const pTexture );
HashedString GetName() const { return m_Name; }
IShaderProgram* GetShaderProgram() const { return m_ShaderProgram; }
ITexture* GetTexture( const uint SamplerStage ) const;
ShaderDataProvider* GetSDP() const { return m_SDP; }
const SRenderOps& GetRenderOps() const { return m_RenderOps; }
const SRenderState& GetRenderState() const { return m_RenderState; }
const SSamplerState& GetSamplerState( const uint SamplerStage ) const;
uint GetNumSamplers() const { return m_NumSamplers; }
#if BUILD_DEBUG
uint GetExpectedVD() const { return m_ExpectedVD; }
#endif
bool SupportsTexture( const uint SamplerStage ) const;
bool SupportsAlphaBlend() const;
uint GetFlags() const { return m_Flags; }
void SetFlags( const uint Flags, const uint Mask = MAT_ALL );
void SetFlag( const uint Flag, const bool Set );
const HashedString& GetBucket() const { return m_Bucket; }
void SetBucket( const HashedString& PrescribedBucket ) { m_Bucket = PrescribedBucket; }
uint GetLightCubeMask() const { return m_LightCubeMask; }
void SetLightCubeMask( const uint LightCubeMask ) { m_LightCubeMask = LightCubeMask; }
void CopySamplerStatesFrom( const Material& OtherMaterial );
void Tick( const float DeltaTime ) { GetSDP()->Tick( DeltaTime ); }
private:
HashedString m_Name;
IShaderProgram* m_ShaderProgram;
ShaderDataProvider* m_SDP;
uint m_Flags; // TODO: Move to a data-driven/project-specific system for declaring flags
HashedString m_Bucket; // Prescribed bucket to minimize material flags
uint m_LightCubeMask; // HACKHACK for shadow lights
SRenderOps m_RenderOps;
SRenderState m_RenderState;
SSamplerState m_SamplerStates[ MAX_TEXTURE_STAGES ];
uint m_NumSamplers;
#if BUILD_DEBUG
uint m_ExpectedVD;
#endif
};
#endif // MATERIAL_H | 34 | 115 | 0.742283 | [
"vector",
"3d"
] |
c561588858bd4d33f6c5554c841ab8d49117a0b7 | 5,607 | h | C | src/ios/Opentok.framework/Versions/A/Headers/OTPublisherKit.h | aullman/cordova-plugin-opentok | dd2672fa8110d2d82ee1cb3526be2f6690cc4284 | [
"MIT"
] | null | null | null | src/ios/Opentok.framework/Versions/A/Headers/OTPublisherKit.h | aullman/cordova-plugin-opentok | dd2672fa8110d2d82ee1cb3526be2f6690cc4284 | [
"MIT"
] | null | null | null | src/ios/Opentok.framework/Versions/A/Headers/OTPublisherKit.h | aullman/cordova-plugin-opentok | dd2672fa8110d2d82ee1cb3526be2f6690cc4284 | [
"MIT"
] | null | null | null | //
// OTPublisherKit.h
//
// Copyright (c) 2014 Tokbox, Inc. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <AVFoundation/AVFoundation.h>
@class OTPublisherKit, OTSession, OTError, OTStream;
@protocol OTVideoCapture;
@protocol OTVideoRender;
@protocol OTPublisherKitDelegate;
@protocol OTPublisherKitAudioLevelDelegate;
/**
* A publisher captures an audio-video stream from the sources you specify. You
* can then publish the audio-video stream to an OpenTok session by sending the
* <[OTSession publish:error:]> message.
*
* The OpenTok iOS SDK supports publishing on all multi-core iOS devices.
* See "Developer and client requirements" in the README file for the
* [OpenTok iOS SDK](http://tokbox.com/opentok/libraries/client/ios).
*/
@interface OTPublisherKit : NSObject
/** @name Initializing a publisher */
/**
* Initialize a publisher object and specify the delegate object.
*
* When running in the XCode iOS Simulator, this method returns `nil`.
*
* @param delegate The delegate (<OTPublisherKitDelegate>) object for the
* publisher.
*
* @return The pointer to the instance, or `nil` if initialization failed.
*/
- (id)initWithDelegate:(id<OTPublisherKitDelegate>)delegate;
/**
* Initialize a publisher object, and specify the delegate object and the
* stream's name.
*
* When running in the XCode iOS Simulator, this method returns `nil`.
*
* @param delegate The delegate (<OTPublisherKitDelegate>) object for the
* publisher.
*
* @param name The name for this stream. This string is displayed at the
* bottom of publisher
* videos and at the bottom of subscriber videos associated with the published
* stream.
*
* @return The pointer to the instance, or `nil` if initialization failed.
*/
- (id)initWithDelegate:(id<OTPublisherKitDelegate>)delegate
name:(NSString*)name;
/** @name Getting information about the publisher */
/**
* The <OTPublisherDelegate> object, which is the delegate for the OTPublisher
* object.
*/
@property(nonatomic, assign) id<OTPublisherKitDelegate> delegate;
/**
* Periodically receives reports of audio levels for this publisher.
*
* This is a separate delegate object from that set as the delegate property
* (the OTPublisherKitDelegate object).
*
* If you do not set this property, the audio sampling subsystem is disabled.
*/
@property (nonatomic, assign)
id<OTPublisherKitAudioLevelDelegate> audioLevelDelegate;
/**
* The session that owns this publisher.
*/
@property(readonly) OTSession* session;
/**
* The <OTStream> object associated with the publisher.
*/
@property(readonly) OTStream* stream;
/**
* A string that will be associated with this publisher's stream. This string is
* displayed at the bottom of subscriber videos associated with the published
* stream, if an overlay to display the name exists.
*
* Name must be set at initialization, when you when you send the
* <[OTPublisherKit initWithDelegate:name:]> message.
*
* This value defaults to an empty string.
*/
@property(readonly) NSString* name;
/** @name Controlling audio and video output for a publisher */
/**
* Whether to publish audio.
*
* The default value is TRUE.
*/
@property(nonatomic) BOOL publishAudio;
/**
* Whether to publish video.
*
* The default value is TRUE.
*/
@property(nonatomic) BOOL publishVideo;
/** @name Setting publisher device configuration */
/**
* The <OTVideoCapture> instance used to capture video to stream to the OpenTok
* session.
*/
@property(nonatomic, retain) id<OTVideoCapture> videoCapture;
/**
* The <OTVideoRender> instance used to render video to stream to the OpenTok
* session.
*/
@property(nonatomic, retain) id<OTVideoRender> videoRender;
@end
/**
* Used for sending messages for an OTPublisher instance. The OTPublisher class
* includes a `delegate` property. When you send the
* <[OTPublisherKit initWithDelegate:]> message or the
* <[OTPublisherKit initWithDelegate:name:]> message, you specify an
* OTSessionDelegate object.
*/
@protocol OTPublisherKitDelegate <NSObject>
/**
* Sent if the publisher encounters an error. After this message is sent,
* the publisher can be considered fully detached from a session and may
* be released.
* @param publisher The publisher that signalled this event.
* @param error The error (an <OTError> object). The `OTPublisherErrorCode`
* enum (defined in the OTError class)
* defines values for the `code` property of this object.
*/
- (void)publisher:(OTPublisherKit*)publisher didFailWithError:(OTError*)error;
@optional
/**
* Sent when the publisher starts streaming.
*
* @param publisher The publisher of the stream.
* @param stream The stream that was created.
*/
- (void)publisher:(OTPublisherKit*)publisher streamCreated:(OTStream*)stream;
/**
* Sent when the publisher stops streaming.
* @param publisher The publisher that stopped sending this stream.
* @param stream The stream that ended.
*/
- (void)publisher:(OTPublisherKit*)publisher streamDestroyed:(OTStream*)stream;
@end
/**
* Used for monitoring the audio levels of the publisher.
*/
@protocol OTPublisherKitAudioLevelDelegate <NSObject>
/**
* Sent on a regular interval with the recent representative audio level.
*
* @param publisher The publisher instance being represented.
* @param audioLevel A value between 0 and 1, representing the audio level.
* Adjust this value logarithmically for use in a user interface
* visualization of the volume (such as a volume meter).
*/
- (void)publisher:(OTPublisherKit*)publisher
audioLevelUpdated:(float)audioLevel;
@end
| 29.203125 | 80 | 0.742465 | [
"render",
"object"
] |
c56c1c6b448f11d9e7e395891cc669f84d80f6d7 | 2,439 | h | C | cpp/libs/src/opendnp3/app/parsing/Collections.h | Kisensum/dnp3 | 0b525927562eb052e9406075811b283d80975bf8 | [
"Apache-2.0"
] | 1 | 2021-06-25T07:22:24.000Z | 2021-06-25T07:22:24.000Z | cpp/libs/src/opendnp3/app/parsing/Collections.h | Kisensum/dnp3 | 0b525927562eb052e9406075811b283d80975bf8 | [
"Apache-2.0"
] | null | null | null | cpp/libs/src/opendnp3/app/parsing/Collections.h | Kisensum/dnp3 | 0b525927562eb052e9406075811b283d80975bf8 | [
"Apache-2.0"
] | 1 | 2021-07-21T03:15:18.000Z | 2021-07-21T03:15:18.000Z | /*
* Licensed to Green Energy Corp (www.greenenergycorp.com) under one or
* more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
* Green Energy Corp licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This project was forked on 01/01/2013 by Automatak, LLC and modifications
* may have been made to this file. Automatak, LLC licenses these modifications
* to you under the terms of the License.
*/
#ifndef OPENDNP3_COLLECTIONS_H
#define OPENDNP3_COLLECTIONS_H
#include "opendnp3/app/parsing/ICollection.h"
namespace opendnp3
{
/**
* A simple collection derived from an underlying array
*/
template <class T>
class ArrayCollection : public ICollection<T>
{
public:
ArrayCollection(const T* pArray_, size_t count) : pArray(pArray_), COUNT(count)
{}
virtual size_t Count() const override final
{
return COUNT;
}
virtual void Foreach(IVisitor<T>& visitor) const override final
{
for (uint32_t i = 0; i < COUNT; ++i)
{
visitor.OnValue(pArray[i]);
}
}
private:
const T* pArray;
const size_t COUNT;
};
template <class T, class U, class Transform>
class TransformedCollection : public ICollection < U >
{
public:
TransformedCollection(const ICollection<T>& input, Transform transform) :
input(&input),
transform(transform)
{}
virtual size_t Count() const override final
{
return input->Count();
}
virtual void Foreach(IVisitor<U>& visitor) const override final
{
auto process = [this, &visitor](const T & elem)
{
visitor.OnValue(transform(elem));
};
input->ForeachItem(process);
}
private:
const ICollection<T>* input;
Transform transform;
};
template <class T, class U, class Transform>
TransformedCollection<T, U, Transform> Map(const ICollection<T>& input, Transform transform)
{
return TransformedCollection<T, U, Transform>(input, transform);
}
}
#endif
| 23.911765 | 92 | 0.736777 | [
"transform"
] |
c56eb1bc61102cba9dab638f29c1f56343aadea1 | 766 | h | C | benchmark/askit_release/rkdtsrc/include/oldtree/distributeToLeaf_ot.h | maumueller/rehashing | 38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad | [
"MIT"
] | 20 | 2019-05-14T20:08:08.000Z | 2021-09-22T20:48:29.000Z | benchmark/askit_release/rkdtsrc/include/oldtree/distributeToLeaf_ot.h | maumueller/rehashing | 38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad | [
"MIT"
] | 2 | 2020-10-06T09:47:52.000Z | 2020-10-09T04:27:39.000Z | benchmark/askit_release/rkdtsrc/include/oldtree/distributeToLeaf_ot.h | maumueller/rehashing | 38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad | [
"MIT"
] | 2 | 2019-08-11T22:29:45.000Z | 2020-10-08T20:02:46.000Z | #ifndef _DISTRIBUTETOLEAFOT_H_
#define _DISTRIBUTETOLEAFOT_H_
#include <mpi.h>
#include <cassert>
#include <vector>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <map>
#include <utility>
#include <util.h>
#include "binTree.h"
#include "oldTree.h"
namespace oldtree {
void distributeToLeaves(pbinData inData, long rootNpoints,
double dupFactor, poldNode searchNode,
double range,
pbinData *outData, poldNode *leaf);
void distributeToLeaves(pbinData inData, long rootNpoints,
double dupFactor, poldNode searchNode,
pbinData *outData, poldNode *leaf);
void distributeToNearestLeaf( pbinData inData,
poldNode searchNode,
pbinData *outData,
poldNode *leaf);
}
#endif
| 18.238095 | 59 | 0.711488 | [
"vector"
] |
c573809c6d87d9da402a13ae48390b771d81fa63 | 8,386 | c | C | automatic_maintenance.c | wesinator/windows-c-examples | 7e6c797a71915533545828077d9d5e43e49a9427 | [
"CC-BY-4.0"
] | 1 | 2021-11-24T09:42:36.000Z | 2021-11-24T09:42:36.000Z | automatic_maintenance.c | wesinator/windows-c-examples | 7e6c797a71915533545828077d9d5e43e49a9427 | [
"CC-BY-4.0"
] | null | null | null | automatic_maintenance.c | wesinator/windows-c-examples | 7e6c797a71915533545828077d9d5e43e49a9427 | [
"CC-BY-4.0"
] | null | null | null | /********************************************************************
This sample creates a maintenance task to start cmd window during maintenance opportunities with periodicity of 2 days and deadline 0f 14 days.
https://docs.microsoft.com/en-us/windows/win32/w8cookbook/automatic-maintenance
********************************************************************/
#define _WIN32_DCOM
#include <windows.h>
#include <iostream>
#include <stdio.h>
#include <comdef.h>
#include <wincred.h>
// Include the task header file.
#include <taskschd.h>
//#pragma comment(lib, "taskschd.lib")
//#pragma comment(lib, "comsupp.lib")
int __cdecl
MainteanceTask( )
{
// ------------------------------------------------------
// Initialize COM.
HRESULT hr;
// ------------------------------------------------------
// Create a name for the task.
LPCWSTR wszTaskName = L"MaintenanceTask";
ITaskService *pService = NULL;
ITaskFolder *pRootFolder = NULL;
ITaskDefinition *pTask = NULL;
ITaskSettings *pSettings = NULL;
IRegistrationInfo *pRegInfo= NULL;
IPrincipal *pPrincipal = NULL;
ITaskSettings3 *pSettings3 = NULL;
IMaintenanceSettings* pMaintenanceSettings = NULL;
IActionCollection *pActionCollection = NULL;
IAction *pAction = NULL;
IExecAction *pExecAction = NULL;
IRegisteredTask *pRegisteredTask = NULL;
wprintf(L"\nCreate Maintenance Task %ws", wszTaskName );
hr = CoInitializeEx( NULL, COINIT_MULTITHREADED);
if( FAILED(hr) )
{
wprintf(L"\nCoInitializeEx failed: %x", hr );
return 1;
}
// Set general COM security levels.
hr = CoInitializeSecurity( NULL,
-1,
NULL,
NULL,
RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
RPC_C_IMP_LEVEL_IMPERSONATE,
NULL,
0,
NULL);
if( FAILED(hr) )
{
wprintf(L"\nCoInitializeSecurity failed: %x", hr );
goto CleanUp;
}
// ------------------------------------------------------
// Create an instance of the Task Service.
hr = CoCreateInstance( CLSID_TaskScheduler,
NULL,
CLSCTX_INPROC_SERVER,
IID_ITaskService,
(void**)&pService );
if (FAILED(hr))
{
wprintf(L"\nFailed to create an instance of ITaskService: %x", hr);
goto CleanUp;
}
// Connect to the task service.
hr = pService->Connect(_variant_t(), _variant_t(), _variant_t(), _variant_t());
if( FAILED(hr) )
{
wprintf(L"\nITaskService::Connect failed: %x", hr );
goto CleanUp;
}
// ------------------------------------------------------
// Get the pointer to the root task folder. This folder will hold the
// new task that is registered.
hr = pService->GetFolder( _bstr_t( L"\\") , &pRootFolder );
if( FAILED(hr) )
{
wprintf(L"\nCannot get Root folder pointer: %x", hr );
goto CleanUp;
}
// If the same task exists, remove it.
( void ) pRootFolder->DeleteTask( _bstr_t(wszTaskName), 0 );
// Create the task definition object to create the task.
hr = pService->NewTask( 0, &pTask );
if (FAILED(hr))
{
wprintf(L"\nFailed to CoCreate an instance of the TaskService class: %x", hr);
goto CleanUp;
}
// ------------------------------------------------------
// Get the registration info for setting the identification.
hr = pTask->get_RegistrationInfo( &pRegInfo );
if( FAILED(hr) )
{
wprintf(L"\nCannot get identification pointer: %x", hr );
goto CleanUp;
}
hr = pRegInfo->put_Author( _bstr_t(L"Author Name") );
if( FAILED(hr) )
{
wprintf(L"\nCannot put identification info: %x", hr );
goto CleanUp;
}
// The task needs to grant explicit FRFX to LOCAL SERVICE (A;;FRFX;;;LS)
hr = pRegInfo->put_SecurityDescriptor( _variant_t(L"D:P(A;;FA;;;BA)(A;;FA;;;SY)(A;;FRFX;;;LS)") );
if( FAILED(hr) )
{
wprintf(L"\nCannot put security descriptor: %x", hr );
goto CleanUp;
}
// ------------------------------------------------------
// Create the principal for the task - these credentials
// are overwritten with the credentials passed to RegisterTaskDefinition
hr = pTask->get_Principal( &pPrincipal );
if( FAILED(hr) )
{
wprintf(L"\nCannot get principal pointer: %x", hr );
goto CleanUp;
}
// Set up principal logon type to interactive logon
hr = pPrincipal->put_LogonType( TASK_LOGON_INTERACTIVE_TOKEN );
if( FAILED(hr) )
{
wprintf(L"\nCannot put principal info: %x", hr );
goto CleanUp;
}
// ------------------------------------------------------
// Create the settings for the task
hr = pTask->get_Settings( &pSettings );
if( FAILED(hr) )
{
wprintf(L"\nCannot get settings pointer: %x", hr );
goto CleanUp;
}
hr = pSettings->QueryInterface( __uuidof(ITaskSettings3), (void**) &pSettings3 );
if( FAILED(hr) )
{
wprintf(L"\nCannot query ITaskSettings3 interface: %x", hr );
goto CleanUp;
}
hr = pSettings3->put_UseUnifiedSchedulingEngine( VARIANT_TRUE );
if( FAILED(hr) )
{
wprintf(L"\nCannot put_UseUnifiedSchedulingEngine: %x", hr );
goto CleanUp;
}
hr = pSettings3->CreateMaintenanceSettings( &pMaintenanceSettings );
if( FAILED(hr) )
{
wprintf(L"\nCannot CreateMaintenanceSettings: %x", hr );
goto CleanUp;
}
hr = pMaintenanceSettings->put_Period ( _bstr_t(L"P2D") );
if( FAILED(hr) )
{
wprintf(L"\nCannot put_Period: %x", hr );
goto CleanUp;
}
hr = pMaintenanceSettings->put_Deadline ( _bstr_t(L"P14D") );
if( FAILED(hr) )
{
wprintf(L"\nCannot put_Period: %x", hr );
goto CleanUp;
}
// ------------------------------------------------------
// Add an action to the task. This task will execute cmd.exe.
// Get the task action collection pointer.
hr = pTask->get_Actions( &pActionCollection );
if( FAILED(hr) )
{
wprintf(L"\nCannot get Task collection pointer: %x", hr );
goto CleanUp;
}
// Create the action, specifying that it is an executable action.
hr = pActionCollection->Create( TASK_ACTION_EXEC, &pAction );
if( FAILED(hr) )
{
wprintf(L"\nCannot create the action: %x", hr );
goto CleanUp;
}
// QI for the executable task pointer.
hr = pAction->QueryInterface( IID_IExecAction, (void**) &pExecAction );
if( FAILED(hr) )
{
wprintf(L"\nQueryInterface call failed for IExecAction: %x", hr );
goto CleanUp;
}
// Set the path of the executable to cmd.exe.
hr = pExecAction->put_Path( _bstr_t(L"cmd") );
if( FAILED(hr) )
{
wprintf(L"\nCannot put action path: %x", hr );
goto CleanUp;
}
// ------------------------------------------------------
// Save the task in the root folder.
hr = pRootFolder->RegisterTaskDefinition(
_bstr_t(wszTaskName),
pTask,
TASK_CREATE_OR_UPDATE,
_variant_t(),
_variant_t(),
TASK_LOGON_INTERACTIVE_TOKEN,
_variant_t(L""),
&pRegisteredTask);
if( FAILED(hr) )
{
wprintf(L"\nError saving the Task : %x", hr );
goto CleanUp;
}
wprintf(L"\nSuccess!\n----------------------------------" );
CleanUp:
if ( pService != NULL ) pService->Release();
if ( pRootFolder != NULL ) pRootFolder->Release();
if ( pTask != NULL ) pTask->Release();
if ( pSettings != NULL ) pSettings->Release();
if ( pRegInfo != NULL ) pRegInfo->Release();
if ( pPrincipal != NULL ) pPrincipal->Release();
if ( pSettings3 != NULL ) pSettings3->Release();
if ( pMaintenanceSettings != NULL ) pMaintenanceSettings->Release();
if ( pActionCollection != NULL ) pActionCollection->Release();
if ( pAction != NULL ) pAction->Release();
if ( pExecAction != NULL ) pExecAction->Release();
if ( pRegisteredTask != NULL ) pRegisteredTask->Release();
CoUninitialize();
return SUCCEEDED ( hr ) ? 0 : 1;
}
| 31.40824 | 143 | 0.546983 | [
"object"
] |
c57879fc4d5e138d27cb6a25f72c0811a4a0a46c | 8,070 | h | C | ppapi/proxy/enter_proxy.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | ppapi/proxy/enter_proxy.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | ppapi/proxy/enter_proxy.h | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef PPAPI_PROXY_ENTER_PROXY_H_
#define PPAPI_PROXY_ENTER_PROXY_H_
#include <stdint.h>
#include "base/check.h"
#include "base/notreached.h"
#include "ppapi/cpp/completion_callback.h"
#include "ppapi/proxy/host_dispatcher.h"
#include "ppapi/proxy/plugin_dispatcher.h"
#include "ppapi/proxy/plugin_globals.h"
#include "ppapi/proxy/plugin_resource_tracker.h"
#include "ppapi/thunk/enter.h"
namespace ppapi {
namespace proxy {
// Wrapper around EnterResourceNoLock that takes a host resource. This is used
// when handling messages in the plugin from the host and we need to convert to
// an object in the plugin side corresponding to that.
//
// This never locks since we assume the host Resource is coming from IPC, and
// never logs errors since we assume the host is doing reasonable things.
template<typename ResourceT>
class EnterPluginFromHostResource
: public thunk::EnterResourceNoLock<ResourceT> {
public:
explicit EnterPluginFromHostResource(const HostResource& host_resource)
: thunk::EnterResourceNoLock<ResourceT>(
PluginGlobals::Get()->plugin_resource_tracker()->
PluginResourceForHostResource(host_resource),
false) {
// Validate that we're in the plugin rather than the host. Otherwise this
// object will do the wrong thing. In the plugin, the instance should have
// a corresponding plugin dispatcher (assuming the resource is valid).
DCHECK(this->failed() ||
PluginDispatcher::GetForInstance(host_resource.instance()));
}
};
template<typename ResourceT>
class EnterHostFromHostResource
: public thunk::EnterResourceNoLock<ResourceT> {
public:
explicit EnterHostFromHostResource(const HostResource& host_resource)
: thunk::EnterResourceNoLock<ResourceT>(host_resource.host_resource(),
false) {
// Validate that we're in the host rather than the plugin. Otherwise this
// object will do the wrong thing. In the host, the instance should have
// a corresponding host disptacher (assuming the resource is valid).
DCHECK(this->failed() ||
HostDispatcher::GetForInstance(host_resource.instance()));
}
EnterHostFromHostResource(const HostResource& host_resource,
const pp::CompletionCallback& callback)
: thunk::EnterResourceNoLock<ResourceT>(host_resource.host_resource(),
callback.pp_completion_callback(),
false) {
// Validate that we're in the host rather than the plugin. Otherwise this
// object will do the wrong thing. In the host, the instance should have
// a corresponding host disptacher (assuming the resource is valid).
DCHECK(this->failed() ||
HostDispatcher::GetForInstance(host_resource.instance()));
}
};
// Enters a resource and forces a completion callback to be issued.
//
// This is used when implementing the host (renderer) side of a resource
// function that issues a completion callback. In all cases, we need to issue
// the callback to avoid hanging the plugin.
//
// This class automatically constructs a callback with the given factory
// calling the given method. The method will generally be the one that sends
// the message to trigger the completion callback in the plugin process.
//
// It will automatically issue the callback with PP_ERROR_NOINTERFACE if the
// host resource is invalid (i.e. failed() is set). In all other cases you
// should call SetResult(), which will issue the callback immediately if the
// result value isn't PP_OK_COMPLETIONPENDING. In the "completion pending"
// case, it's assumed the function the proxy is calling will take responsibility
// of executing the callback (returned by callback()).
//
// Example:
// EnterHostFromHostResourceForceCallback<PPB_Foo_API> enter(
// resource, callback_factory_, &MyClass::SendResult, resource);
// if (enter.failed())
// return; // SendResult automatically called with PP_ERROR_BADRESOURCE.
// enter.SetResult(enter.object()->DoFoo(enter.callback()));
//
// Where DoFoo's signature looks like this:
// int32_t DoFoo(PP_CompletionCallback callback);
// And SendResult's implementation looks like this:
// void MyClass::SendResult(int32_t result, const HostResource& res) {
// Send(new FooMsg_FooComplete(..., result, res));
// }
template<typename ResourceT>
class EnterHostFromHostResourceForceCallback
: public EnterHostFromHostResource<ResourceT> {
public:
EnterHostFromHostResourceForceCallback(
const HostResource& host_resource,
const pp::CompletionCallback& callback)
: EnterHostFromHostResource<ResourceT>(host_resource, callback),
needs_running_(true) {
}
// For callbacks that take no parameters except the "int32_t result". Most
// implementations will use the 1-extra-argument constructor below.
template<class CallbackFactory, typename Method>
EnterHostFromHostResourceForceCallback(
const HostResource& host_resource,
CallbackFactory& factory,
Method method)
: EnterHostFromHostResource<ResourceT>(host_resource,
factory.NewOptionalCallback(method)),
needs_running_(true) {
if (this->failed())
RunCallback(PP_ERROR_BADRESOURCE);
}
// For callbacks that take an extra parameter as a closure.
template<class CallbackFactory, typename Method, typename A>
EnterHostFromHostResourceForceCallback(
const HostResource& host_resource,
CallbackFactory& factory,
Method method,
const A& a)
: EnterHostFromHostResource<ResourceT>(host_resource,
factory.NewOptionalCallback(method, a)),
needs_running_(true) {
if (this->failed())
RunCallback(PP_ERROR_BADRESOURCE);
}
// For callbacks that take two extra parameters as a closure.
template<class CallbackFactory, typename Method, typename A, typename B>
EnterHostFromHostResourceForceCallback(
const HostResource& host_resource,
CallbackFactory& factory,
Method method,
const A& a,
const B& b)
: EnterHostFromHostResource<ResourceT>(host_resource,
factory.NewOptionalCallback(method, a, b)),
needs_running_(true) {
if (this->failed())
RunCallback(PP_ERROR_BADRESOURCE);
}
// For callbacks that take three extra parameters as a closure.
template<class CallbackFactory, typename Method, typename A, typename B,
typename C>
EnterHostFromHostResourceForceCallback(
const HostResource& host_resource,
CallbackFactory& factory,
Method method,
const A& a,
const B& b,
const C& c)
: EnterHostFromHostResource<ResourceT>(host_resource,
factory.NewOptionalCallback(method, a, b, c)),
needs_running_(true) {
if (this->failed())
RunCallback(PP_ERROR_BADRESOURCE);
}
~EnterHostFromHostResourceForceCallback() {
if (needs_running_) {
NOTREACHED() << "Should always call SetResult except in the "
"initialization failed case.";
RunCallback(PP_ERROR_FAILED);
}
}
void SetResult(int32_t result) {
DCHECK(needs_running_) << "Don't call SetResult when there already is one.";
if (result != PP_OK_COMPLETIONPENDING)
RunCallback(result);
needs_running_ = false;
// Either we already ran the callback, or it will be run asynchronously. We
// clear the callback so it isn't accidentally run again (and because
// EnterBase checks that the callback has been cleared).
this->ClearCallback();
}
private:
void RunCallback(int32_t result) {
DCHECK(needs_running_);
needs_running_ = false;
this->callback()->Run(result);
this->ClearCallback();
}
bool needs_running_;
};
} // namespace proxy
} // namespace ppapi
#endif // PPAPI_PROXY_ENTER_PROXY_H_
| 38.798077 | 80 | 0.71202 | [
"object"
] |
c57efca8667d9e1da2e63e867eef80c028cb7fa2 | 5,663 | c | C | src/linear/LinearRegression/LinearRegression.c | georgikorchakov/c-cori-ml | b94e6597c7a2b976ddfd66cc24bb28fe57c1dcaa | [
"MIT"
] | 4 | 2018-12-26T13:08:18.000Z | 2019-09-04T14:21:17.000Z | src/linear/LinearRegression/LinearRegression.c | georgikorchakov/c-cori-ml | b94e6597c7a2b976ddfd66cc24bb28fe57c1dcaa | [
"MIT"
] | null | null | null | src/linear/LinearRegression/LinearRegression.c | georgikorchakov/c-cori-ml | b94e6597c7a2b976ddfd66cc24bb28fe57c1dcaa | [
"MIT"
] | null | null | null | /**
* LinearRegression.c
*
* Created: 5/12/2018
* Author: Georgi Korchakov
*/
#include <stdio.h>
#include <stdlib.h>
#include "../../math/cori-math.h"
#include "LinearRegression.h"
/** @brief Initialize linear regression
* @param float learning_rate, learning rate for gradient descent
* @param int number_of_features, number of features in dataset
* @return linear_regression_t*, Pointer to initialized linear_regression_t
*/
linear_regression_t*
linear_regression_init (float learning_rate, int number_of_features)
{
linear_regression_t *model = malloc(sizeof(*model));
model->learning_rate = learning_rate;
model->number_of_features = number_of_features;
// Initialize model->intercept to be random value between 0 and 1
model->intercept = cori_random();
model->coef = malloc(sizeof(double) * number_of_features);
for (int i = 0; i < number_of_features; i++)
{
// Initialize model->coef[i] to be random value between 0 and 1
model->coef[i] = cori_random();
}
model->verbose = 0;
// Initialize method functions
model->fit = &linear_regression_gradient_descent;
model->predict = &linear_regression_predict;
model->cost = &linear_regression_cost;
return model;
}
/** @brief Gives a prediction for specific data
* @param linear_regression_t *model, linear regression struct (pointer)
* @param double *x, data for prediction
* @return double, prediction
*/
double
linear_regression_predict (linear_regression_t *model, double *x)
{
double y = model->intercept;
for (int i = 0; i < model->number_of_features; i++)
{
y += model->coef[i] * x[i];
}
return y;
}
/** @brief Cost Function for linear regression
* @param linear_regression_t *model, linear regression struct (pointer)
* @param matrix_t *X, feature matrix (pointer)
* @param vector_t *y, label vector (pointer)
* @return double, cost (how bad are the predictions)
*/
double
linear_regression_cost (linear_regression_t *model, matrix_t *X, vector_t *y)
{
double score = 0;
double error = 0;
for (int i = 0; i < X->m; i++)
{
error = linear_regression_predict(model, X->data[i]) - y->data[i];
score += error * error;
}
return score / (2 * X->m);
}
/** @brief Calculate derivatives for gradient descent
* @param linear_regression_t *model, linear regression struct (pointer)
* @param matrix_t *X, feature matrix (pointer)
* @param vector_t *y, label vector (pointer)
* @return linear_regression_t*, new derivative calculations for each coef_
*/
linear_regression_t*
linear_regression_calc_derivatives (linear_regression_t *model,
matrix_t *X, vector_t *y)
{
// Initialize new linear_regression_t, used to store calculated parameters
linear_regression_t *calculation =
linear_regression_init(model->learning_rate, model->number_of_features);
// Calc derivative for intercept
for (int i = 0; i < X->m; i++)
{
calculation->intercept += linear_regression_predict(model, X->data[i]) -
y->data[i];
}
calculation->intercept = calculation->intercept / X->m;
// Calc derivatives for coefs
for (int j = 0; j < X->n; j++)
{
for (int i = 0; i < X->m; i++)
{
calculation->coef[j] +=
(linear_regression_predict(model, X->data[i]) - y->data[i]) *
X->data[i][j];
}
calculation->coef[j] = calculation->coef[j] / X->m;
}
return calculation;
}
/** @brief Gradient Descent for linear regression
* @param linear_regression_t *model, linear regression struct (pointer)
* @param matrix_t *X, feature matrix (pointer)
* @param vector_t *y, label vector (pointer)
* @return double, lowest cost
*/
double
linear_regression_gradient_descent (linear_regression_t *model,
matrix_t *X, vector_t *y)
{
long long int counter = 0;
// Get the first (worst) cost of the model
double first_best = linear_regression_cost(model, X, y);
double best = first_best * 2;
if (model->verbose == 1) fprintf(stdout, "First Best: %f\n", first_best);
// Initialize new linear_regression_t
// used to store new calculated derivatives
linear_regression_t *calculation =
linear_regression_init (model->learning_rate, model->number_of_features);
// Iterate while cost is better than previous
while (linear_regression_cost(model, X, y) < best)
{
++counter;
if (model->verbose == 1)
{
fputs("--------------------\n", stdout);
fprintf(stdout, "%lldth iteration\n", counter);
if (counter == 1)
{
fprintf(stdout, "Cost: %f\n", first_best);
}
else
{
fprintf(stdout, "Cost: %f\n", best);
}
}
best = linear_regression_cost(model, X, y);
// Get new derivatives
calculation = linear_regression_calc_derivatives(model, X, y);
// Apply new derivatives to our model
model->intercept = model->intercept -
calculation->intercept * model->learning_rate;
for (int i = 0; i < model->number_of_features; i++)
{
model->coef[i] = model->coef[i] -
calculation->coef[i] * model->learning_rate;
}
}
if (model->verbose == 1)
{
fputs("\n*******************************\n", stdout);
fprintf(stdout, "* Iterations: %15lld *\n", counter);
fprintf(stdout, "* First Cost: %15f *\n", first_best);
fprintf(stdout, "* Best Cost: %16f *\n", best);
fprintf(stdout, "*******************************\n");
}
return best;
}
| 29.962963 | 78 | 0.631291 | [
"vector",
"model"
] |
c580596a16d99264883b9ebda8c9a7a480987f03 | 3,916 | h | C | NS3-master/src/uan/model/uan-header-common.h | legendPerceptor/blockchain | 615ba331ae5ec53c683dfe6a16992a5181be0fea | [
"Apache-2.0"
] | 1 | 2021-09-20T07:05:25.000Z | 2021-09-20T07:05:25.000Z | NS3-master/src/uan/model/uan-header-common.h | legendPerceptor/blockchain | 615ba331ae5ec53c683dfe6a16992a5181be0fea | [
"Apache-2.0"
] | null | null | null | NS3-master/src/uan/model/uan-header-common.h | legendPerceptor/blockchain | 615ba331ae5ec53c683dfe6a16992a5181be0fea | [
"Apache-2.0"
] | 2 | 2021-09-02T08:25:16.000Z | 2022-01-03T08:48:38.000Z | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2009 University of Washington
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Leonard Tracy <lentracy@gmail.com>
*/
#ifndef UAN_HEADER_COMMON_H
#define UAN_HEADER_COMMON_H
#include "ns3/header.h"
#include "ns3/nstime.h"
#include "ns3/simulator.h"
#include "ns3/mac8-address.h"
namespace ns3 {
struct UanProtocolBits
{
uint8_t m_type : 4;
uint8_t m_protocolNumber : 4;
};
/**
* \ingroup uan
*
* Common packet header fields.
*
* 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | src addr | dst addr | prtcl | type |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*
*
* src addr: The MAC8 source address
*
* dst addr: The MAC8 destination address
*
* prtcl: The layer 3 protocol
* prtcl=1 (IPv4)
* prtcl=2 (ARP)
* prtcl=3 (IPv6)
*
* type: The type field is MAC protocol specific
*/
class UanHeaderCommon : public Header
{
public:
/** Default constructor */
UanHeaderCommon ();
/**
* Create UanHeaderCommon object with given source and destination
* address and header type
*
* \param src Source address defined in header.
* \param dest Destination address defined in header.
* \param type Header type.
* \param protocolNumber the layer 3 protocol number
*/
UanHeaderCommon (const Mac8Address src, const Mac8Address dest, uint8_t type, uint8_t protocolNumber);
/** Destructor */
virtual ~UanHeaderCommon ();
/**
* Register this type.
* \return The TypeId.
*/
static TypeId GetTypeId (void);
/**
* Set the destination address.
*
* \param dest Address of destination node.
*/
void SetDest (Mac8Address dest);
/**
* Set the source address.
*
* \param src Address of packet source node.
*/
void SetSrc (Mac8Address src);
/**
* Set the header type.
*
* Use of this value is protocol specific.
* \param type The type value.
*/
void SetType (uint8_t type);
/**
* Set the packet type.
*
* Used to indicate the layer 3 protocol
* \param protocolNumber The layer 3 protocol number value.
*/
void SetProtocolNumber (uint16_t protocolNumber);
/**
* Get the destination address.
*
* \return Mac8Address in destination field.
*/
Mac8Address GetDest (void) const;
/**
* Get the source address
*
* \return Mac8Address in source field.
*/
Mac8Address GetSrc (void) const;
/**
* Get the header type value.
*
* \return value of type field.
*/
uint8_t GetType (void) const;
/**
* Get the packet type value.
*
* \return value of protocolNumber field.
*/
uint16_t GetProtocolNumber (void) const;
// Inherited methods
virtual uint32_t GetSerializedSize (void) const;
virtual void Serialize (Buffer::Iterator start) const;
virtual uint32_t Deserialize (Buffer::Iterator start);
virtual void Print (std::ostream &os) const;
virtual TypeId GetInstanceTypeId (void) const;
private:
Mac8Address m_dest; //!< The destination address.
Mac8Address m_src; //!< The source address.
UanProtocolBits m_uanProtocolBits {0}; //!< The type and protocol bits
}; // class UanHeaderCommon
} // namespace ns3
#endif /* UAN_HEADER_COMMON_H */
| 25.933775 | 104 | 0.660878 | [
"object"
] |
c584e579c56693b22435007c11af9ae986a99b96 | 3,386 | h | C | sewer_graph/include/sewer_graph/sewer_graph.h | robotics-upo/localization_siar | 6b4ca6f2bb56f7071479839dcbb88a6384eca091 | [
"MIT"
] | 4 | 2018-08-15T16:00:32.000Z | 2021-05-17T12:38:42.000Z | sewer_graph/include/sewer_graph/sewer_graph.h | robotics-upo/localization_siar | 6b4ca6f2bb56f7071479839dcbb88a6384eca091 | [
"MIT"
] | null | null | null | sewer_graph/include/sewer_graph/sewer_graph.h | robotics-upo/localization_siar | 6b4ca6f2bb56f7071479839dcbb88a6384eca091 | [
"MIT"
] | 3 | 2019-01-13T03:15:46.000Z | 2021-09-20T06:54:42.000Z | #ifndef SEWER_GRAPH_H
#define SEWER_GRAPH_H
#include <string>
#include <kml/dom.h>
#include "functions/DegMinSec.h"
#include "functions/RealVector.h"
#include "simple_graph/SimpleGraph.h"
#include "sewer_graph/earthlocation.h"
#include <visualization_msgs/Marker.h>
#include <sensor_msgs/NavSatFix.h>
namespace sewer_graph {
enum SewerVertexType {
MANHOLE,
FORK,
NORMAL,
ALL = 255
};
// Types
struct SewerVertex {
EarthLocation e;
std::string comments;
double x, y; // Local coordinates
std::string toString() const;
SewerVertexType type;
};
struct SewerEdge {
double distance;
double route; // Angle relative to N (in the sense of waterflow)
long id;
std::string section; // Can be T181, D1400, T168, T133, NT120A, T164, T130...
std::string toString() const;
};
//! @brief This class is used to represent an Earth Location in terms of longitude and latitude.
//! Uses decimal degrees as internal representation of latitude and longitude.
//! The altitude is stored in meters above the sea level.
//! ToString method gives many representations.
class SewerGraph:public simple_graph::SimpleGraph<SewerVertex, SewerEdge>
{
public:
SewerGraph() {
}
//! @brief Constructor from file
SewerGraph(const std::string &filename);
//! @brief Loads graph from a file
bool loadGraph(const std::string &filename);
bool loadLocalGraph(const std::string &filename, double lat, double lon);
bool writeGraph(const std::string &filename);
virtual void addEdge(int i, int j);
virtual void addEdge(int i, int j, int type, int suffix = 0);
// std::string toString() const; Por ahora usamos la versión de SimpleGraph
double getDistanceToClosestManhole(double x, double y) const;
double getDistanceToClosestVertex(double x, double y, SewerVertexType type = ALL) const;
int getClosestVertex(double x, double y, SewerVertexType type = ALL) const;
double getDistanceToClosestEdge(double x, double y, int &id1, int &id2) const;
double getClosestEdgeAngle(double x, double y) const;
//! @brief Exports the trajectory information into KML format
//! @param filename Output filename
//! @retval true The information has been successfully saved
//! @retval false Errors while saving information
bool exportKMLFile(const string& filename, sewer_graph::SewerVertexType type = ALL) const;
//! Grief Exports the Graph in RViz format
std::vector<visualization_msgs::Marker> getMarkers(const std::string &ref_frame) const;
sensor_msgs::NavSatFix getReferencePosition() const;
void setCenter(const EarthLocation &c) {
center = c;
}
EarthLocation getCenter() const {
return center;
}
protected:
EarthLocation center;
// KML stuff -------------------------------------------------
kmldom::KmlFactory* factory;
void addKMLStyle(kmldom::DocumentPtr& doc) const;
// End of KML stuff -----------------------------------------------
//! @brief Parses the type: the thousand digit indicates: if 0 --> T. if 1 --> D, if 2 --> NT
//! @param type The number as readed from file
//! @param type The suffix ASCII code (65 = A, 66 = B, 67 = C) (if zero, none)
//! @return The string describing the section type
std::string parseSectionType(int type, char suffix = 0) const;
};
}
#endif // EARTHLOCATION_H
| 26.248062 | 96 | 0.685765 | [
"vector"
] |
c5854efca548d4e233be8e998014f00947646559 | 3,012 | h | C | src/Leddar/LdSensorM16.h | magm3333/LeddarSDK_OC | 55a545e1e7ea4d54ae7edc0ddee8f4ec6bd6f3e5 | [
"BSD-3-Clause"
] | null | null | null | src/Leddar/LdSensorM16.h | magm3333/LeddarSDK_OC | 55a545e1e7ea4d54ae7edc0ddee8f4ec6bd6f3e5 | [
"BSD-3-Clause"
] | null | null | null | src/Leddar/LdSensorM16.h | magm3333/LeddarSDK_OC | 55a545e1e7ea4d54ae7edc0ddee8f4ec6bd6f3e5 | [
"BSD-3-Clause"
] | 1 | 2020-06-01T17:40:08.000Z | 2020-06-01T17:40:08.000Z | ////////////////////////////////////////////////////////////////////////////////////////////////////
/// \file Leddar/LdSensorM16.h
///
/// \brief Declares the LdSensorM16 class
///
/// Copyright (c) 2018 LeddarTech. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "LtDefines.h"
#if defined(BUILD_M16) && defined(BUILD_USB)
#include "LdSensor.h"
#include "LdProtocolLeddartechUSB.h"
namespace LeddarDevice
{
class LdSensorM16 : public LdSensor
{
public:
explicit LdSensorM16( LeddarConnection::LdConnection *aConnection );
~LdSensorM16();
virtual void Connect( void ) override;
virtual void GetConstants( void ) override;
virtual void UpdateConstants( void ) override;
virtual void GetConfig( void ) override;
virtual void SetConfig( void ) override;
virtual void WriteConfig( void ) override;
virtual void RestoreConfig( void ) override;
virtual void GetCalib() override;
virtual void SetDataMask( uint32_t aDataMask ) override;
virtual bool GetData( void ) override;
virtual bool GetEchoes( void ) override { return false; }; //Dont use this function, use GetData
virtual void GetStates( void ) override {}; //Dont use this function, use GetData
virtual void Reset( LeddarDefines::eResetType aType, LeddarDefines::eResetOptions aOptions = LeddarDefines::RO_NO_OPTION ) override;
void RequestProperties( LeddarCore::LdPropertiesContainer *aProperties, std::vector<uint16_t> aDeviceIds );
void SetProperties( LeddarCore::LdPropertiesContainer *aProperties, std::vector<uint16_t> aDeviceIds, unsigned int aRetryNbr = 0 );
virtual void RemoveLicense( const std::string &aLicense ) override;
virtual void RemoveAllLicenses( void ) override;
virtual LeddarDefines::sLicense SendLicense( const std::string &aLicense ) override;
LeddarDefines::sLicense SendLicense( const std::string &aLicense, bool aVolatile );
LeddarDefines::sLicense SendLicense( const uint8_t *aLicense, bool aVolatile = false );
virtual std::vector<LeddarDefines::sLicense> GetLicenses( void ) override;
//For IS16
protected:
LeddarConnection::LdProtocolLeddartechUSB *mProtocolConfig;
LeddarConnection::LdProtocolLeddartechUSB *mProtocolData;
LeddarCore::LdPropertiesContainer *mResultStatePropeties;
virtual bool ProcessStates( void );
void ProcessEchoes( void );
private:
LdSensorM16( const LdSensorM16 &aSensor ); //Disable copy constructor
LdSensorM16 &operator=( const LdSensorM16 &aSensor );//Disable equal constructor
void InitProperties( void );
void GetListing( void );
void GetIntensityMappings( void );
};
}
#endif | 42.422535 | 150 | 0.62915 | [
"vector"
] |
c5875657333f4e041929273d25d8322223244af3 | 8,610 | h | C | MNE/fiff/fiff_ch_info.h | liminsun/mne-cpp | c5de865281164cf1867450c9705b21c9ac1b5cd7 | [
"BSD-3-Clause"
] | null | null | null | MNE/fiff/fiff_ch_info.h | liminsun/mne-cpp | c5de865281164cf1867450c9705b21c9ac1b5cd7 | [
"BSD-3-Clause"
] | null | null | null | MNE/fiff/fiff_ch_info.h | liminsun/mne-cpp | c5de865281164cf1867450c9705b21c9ac1b5cd7 | [
"BSD-3-Clause"
] | null | null | null | //=============================================================================================================
/**
* @file fiff_ch_info.h
* @author Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;
* Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version 1.0
* @date July, 2012
*
* @section LICENSE
*
* Copyright (C) 2012, Christoph Dinh and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of MNE-CPP authors nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief FiffChInfo class declaration.
*
*/
#ifndef FIFF_CH_INFO_H
#define FIFF_CH_INFO_H
//*************************************************************************************************************
//=============================================================================================================
// FIFF INCLUDES
//=============================================================================================================
#include "fiff_global.h"
#include "fiff_types.h"
//*************************************************************************************************************
//=============================================================================================================
// Qt INCLUDES
//=============================================================================================================
#include <QSharedPointer>
#include <QString>
//*************************************************************************************************************
//=============================================================================================================
// Eigen INCLUDES
//=============================================================================================================
#include <Eigen/Core>
//*************************************************************************************************************
//=============================================================================================================
// DEFINE NAMESPACE FIFFLIB
//=============================================================================================================
namespace FIFFLIB
{
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace Eigen;
//=============================================================================================================
/**
* Channel Info descriptor replaces _fiffChInfoRec struct.
*
* @brief Channel info descriptor.
*/
class FIFFSHARED_EXPORT FiffChInfo
{
public:
typedef QSharedPointer<FiffChInfo> SPtr; /**< Shared pointer type for FiffChInfo. */
typedef QSharedPointer<const FiffChInfo> ConstSPtr; /**< Const shared pointer type for FiffChInfo. */
//=========================================================================================================
/**
* Constructs the channel info descriptor.
*/
FiffChInfo();
//=========================================================================================================
/**
* Copy constructor.
*
* @param[in] p_FiffChInfo Channel Info descriptor which should be copied
*/
FiffChInfo(const FiffChInfo &p_FiffChInfo);
//=========================================================================================================
/**
* Destroys the channel info descriptor.
*/
~FiffChInfo();
//=========================================================================================================
/**
* Size of the old struct (fiffChInfoRec) 20*int + 16 = 20*4 + 16 = 96
*
* @return the size of the old struct fiffChInfoRec.
*/
inline static qint32 storageSize();
public:
fiff_int_t scanno; /**< Scanning order number 1*/
fiff_int_t logno; /**< Logical channel # 1*/
fiff_int_t kind; /**< Kind of channel 1*/
fiff_float_t range; /**< Voltmeter range (-1 = auto ranging) 1*/
fiff_float_t cal; /**< Calibration from volts to units used 1*/
fiff_int_t coil_type; /**< What kind of coil. */
Matrix<double,12,1, DontAlign> loc; /**< Channel (MEG) location:
* 3x Coil coordinate system origin;
* 3x Coil coordinate system x-axis unit vector;
* 3x Coil coordinate system y-axis unit vector;
* 3x Coil coordinate system z-axis unit vector*/
Matrix<double,4,4, DontAlign> coil_trans; /**< Coil coordinate system transformation */
Matrix<double,3,2, DontAlign> eeg_loc; /**< Channel location */
fiff_int_t coord_frame; /**< Coordinate Frame */
// /** Measurement channel position and coil type. */
// typedef struct _fiffChPosRec {
// fiff_int_t coil_type; /**< What kind of coil. */
// fiff_float_t r0[3]; /**< Coil coordinate system origin */
// fiff_float_t ex[3]; /**< Coil coordinate system x-axis unit vector */
// fiff_float_t ey[3]; /**< Coil coordinate system y-axis unit vector */
// fiff_float_t ez[3]; /**< Coil coordinate system z-axis unit vector */
// } fiffChPosRec,*fiffChPos; /**< Measurement channel position and coil type */
// typedef fiffChPosRec fiff_ch_pos_t;
// fiff_ch_pos_t chpos; /**< Channel location 15 -> ToDo: read in*/
fiff_int_t unit; /**< Unit of measurement 1*/
fiff_int_t unit_mul; /**< Unit multiplier exponent 1*/
QString ch_name; /**< Descriptive name for the channel 16*/
// ### OLD STRUCT ###
// typedef struct _fiffChInfoRec {
// fiff_int_t scanNo; /**< Scanning order number *
// fiff_int_t logNo; /**< Logical channel # *
// fiff_int_t kind; /**< Kind of channel *
// fiff_float_t range; /**< Voltmeter range (-1 = auto ranging) *
// fiff_float_t cal; /**< Calibration from volts to units used *
// fiff_ch_pos_t chpos; /**< Channel location *
// fiff_int_t unit; /**< Unit of measurement *
// fiff_int_t unit_mul; /**< Unit multiplier exponent *
// fiff_char_t ch_name[16]; /**< Descriptive name for the channel *
// } fiffChInfoRec,*fiffChInfo; /**< Description of one channel *
// /** Alias for fiffChInfoRec *
// typedef fiffChInfoRec fiff_ch_info_t;
};
//*************************************************************************************************************
//=============================================================================================================
// INLINE DEFINITIONS
//=============================================================================================================
inline qint32 FiffChInfo::storageSize()
{
return 96;
}
} // NAMESPACE
#endif // FIFF_CH_INFO_H
| 45.315789 | 116 | 0.445296 | [
"vector"
] |
c589f6c4667ed0245d745fa5517de68d8cc5d331 | 1,444 | h | C | Source/RollaBall/Game/RollaBallPlayer.h | UstymUkhman/RollaBall | 29cf407c88e0cde09b6adcdaa613e8cf00a5a8d2 | [
"MIT"
] | 1 | 2021-08-01T09:13:00.000Z | 2021-08-01T09:13:00.000Z | Source/RollaBall/Game/RollaBallPlayer.h | UstymUkhman/RollaBall | 29cf407c88e0cde09b6adcdaa613e8cf00a5a8d2 | [
"MIT"
] | null | null | null | Source/RollaBall/Game/RollaBallPlayer.h | UstymUkhman/RollaBall | 29cf407c88e0cde09b6adcdaa613e8cf00a5a8d2 | [
"MIT"
] | null | null | null | #pragma once
#include "CoreMinimal.h"
#include "GameFramework/Pawn.h"
#include "RollaBallPlayer.generated.h"
class UCameraComponent;
class USpringArmComponent;
UCLASS()
class ROLLABALL_API ARollaBallPlayer : public APawn
{
GENERATED_BODY()
public:
// Called to bind functionality to input
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
// Sets default values for this pawn's properties
ARollaBallPlayer();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
// Define Components:
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components")
UStaticMeshComponent* Mesh;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components")
USpringArmComponent* SpringArm;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Components")
UCameraComponent* Camera;
// Define Variables:
UPROPERTY(EditAnywhere, BlueprintReadWrite)
float MoveForce = 500.0f;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
float JumpImpulse = 500.0f;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
int32 MaxJumpCount = 1;
private:
// Define Functions:
void MoveForward(float Value);
void MoveRight(float Value);
void Jump();
UFUNCTION()
void OnHit(
UPrimitiveComponent* HitComponent,
AActor* OtherActor,
UPrimitiveComponent* OtherComp,
FVector NormalImpulse,
const FHitResult& Hit
);
int32 JumpCount = 0;
};
| 22.920635 | 94 | 0.780471 | [
"mesh"
] |
c591b5db532f761e2e6cf2e0db24214ab677d9a4 | 12,222 | c | C | apps/dsaparam.c | robstradling/openssl | 211a68b41a0dd3fed01ac9c93e495fdc03bd1e92 | [
"OpenSSL"
] | 1 | 2015-12-21T11:57:55.000Z | 2015-12-21T11:57:55.000Z | apps/dsaparam.c | robstradling/openssl | 211a68b41a0dd3fed01ac9c93e495fdc03bd1e92 | [
"OpenSSL"
] | 1 | 2018-11-09T09:47:44.000Z | 2018-11-09T09:51:50.000Z | apps/dsaparam.c | robstradling/openssl | 211a68b41a0dd3fed01ac9c93e495fdc03bd1e92 | [
"OpenSSL"
] | 1 | 2021-03-16T09:56:33.000Z | 2021-03-16T09:56:33.000Z | /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <openssl/opensslconf.h> /* for OPENSSL_NO_DSA */
#ifndef OPENSSL_NO_DSA
# include <stdio.h>
# include <stdlib.h>
# include <time.h>
# include <string.h>
# include "apps.h"
# include <openssl/bio.h>
# include <openssl/err.h>
# include <openssl/bn.h>
# include <openssl/dsa.h>
# include <openssl/x509.h>
# include <openssl/pem.h>
# ifdef GENCB_TEST
static int stop_keygen_flag = 0;
static void timebomb_sigalarm(int foo)
{
stop_keygen_flag = 1;
}
# endif
static int dsa_cb(int p, int n, BN_GENCB *cb);
typedef enum OPTION_choice {
OPT_ERR = -1, OPT_EOF = 0, OPT_HELP,
OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_TEXT, OPT_C,
OPT_NOOUT, OPT_GENKEY, OPT_RAND, OPT_NON_FIPS_ALLOW, OPT_ENGINE,
OPT_TIMEBOMB
} OPTION_CHOICE;
OPTIONS dsaparam_options[] = {
{"help", OPT_HELP, '-', "Display this summary"},
{"inform", OPT_INFORM, 'F', "Input format - DER or PEM"},
{"in", OPT_IN, '<', "Input file"},
{"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"},
{"out", OPT_OUT, '>', "Output file"},
{"text", OPT_TEXT, '-', "Print as text"},
{"C", OPT_C, '-', "Output C code"},
{"noout", OPT_NOOUT, '-', "No output"},
{"genkey", OPT_GENKEY, '-', "Generate a DSA key"},
{"rand", OPT_RAND, 's', "Files to use for random number input"},
{"non-fips-allow", OPT_NON_FIPS_ALLOW, '-'},
# ifdef GENCB_TEST
{"timebomb", OPT_TIMEBOMB, 'p', "Interrupt keygen after 'pnum' seconds"},
# endif
# ifndef OPENSSL_NO_ENGINE
{"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"},
# endif
{NULL}
};
int dsaparam_main(int argc, char **argv)
{
DSA *dsa = NULL;
BIO *in = NULL, *out = NULL;
BN_GENCB *cb = NULL;
int numbits = -1, num = 0, genkey = 0, need_rand = 0, non_fips_allow = 0;
int informat = FORMAT_PEM, outformat = FORMAT_PEM, noout = 0, C = 0;
int ret = 1, i, text = 0, private = 0;
# ifdef GENCB_TEST
int timebomb = 0;
# endif
char *infile = NULL, *outfile = NULL, *prog, *inrand = NULL;
OPTION_CHOICE o;
prog = opt_init(argc, argv, dsaparam_options);
while ((o = opt_next()) != OPT_EOF) {
switch (o) {
case OPT_EOF:
case OPT_ERR:
opthelp:
BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
goto end;
case OPT_HELP:
opt_help(dsaparam_options);
ret = 0;
goto end;
case OPT_INFORM:
if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
goto opthelp;
break;
case OPT_IN:
infile = opt_arg();
break;
case OPT_OUTFORM:
if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
goto opthelp;
break;
case OPT_OUT:
outfile = opt_arg();
break;
case OPT_ENGINE:
(void)setup_engine(opt_arg(), 0);
break;
case OPT_TIMEBOMB:
# ifdef GENCB_TEST
timebomb = atoi(opt_arg());
break;
# endif
case OPT_TEXT:
text = 1;
break;
case OPT_C:
C = 1;
break;
case OPT_GENKEY:
genkey = need_rand = 1;
break;
case OPT_RAND:
inrand = opt_arg();
need_rand = 1;
break;
case OPT_NOOUT:
noout = 1;
break;
case OPT_NON_FIPS_ALLOW:
non_fips_allow = 1;
break;
}
}
argc = opt_num_rest();
argv = opt_rest();
if (argc == 1) {
if (!opt_int(argv[0], &num))
goto end;
/* generate a key */
numbits = num;
need_rand = 1;
}
private = genkey ? 1 : 0;
in = bio_open_default(infile, 'r', informat);
if (in == NULL)
goto end;
out = bio_open_owner(outfile, outformat, private);
if (out == NULL)
goto end;
if (need_rand) {
app_RAND_load_file(NULL, (inrand != NULL));
if (inrand != NULL)
BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
app_RAND_load_files(inrand));
}
if (numbits > 0) {
cb = BN_GENCB_new();
if (cb == NULL) {
BIO_printf(bio_err, "Error allocating BN_GENCB object\n");
goto end;
}
BN_GENCB_set(cb, dsa_cb, bio_err);
assert(need_rand);
dsa = DSA_new();
if (dsa == NULL) {
BIO_printf(bio_err, "Error allocating DSA object\n");
goto end;
}
if (non_fips_allow)
dsa->flags |= DSA_FLAG_NON_FIPS_ALLOW;
BIO_printf(bio_err, "Generating DSA parameters, %d bit long prime\n",
num);
BIO_printf(bio_err, "This could take some time\n");
# ifdef GENCB_TEST
if (timebomb > 0) {
struct sigaction act;
act.sa_handler = timebomb_sigalarm;
act.sa_flags = 0;
BIO_printf(bio_err,
"(though I'll stop it if not done within %d secs)\n",
timebomb);
if (sigaction(SIGALRM, &act, NULL) != 0) {
BIO_printf(bio_err, "Error, couldn't set SIGALRM handler\n");
goto end;
}
alarm(timebomb);
}
# endif
if (!DSA_generate_parameters_ex(dsa, num, NULL, 0, NULL, NULL, cb)) {
# ifdef GENCB_TEST
if (stop_keygen_flag) {
BIO_printf(bio_err, "DSA key generation time-stopped\n");
/* This is an asked-for behaviour! */
ret = 0;
goto end;
}
# endif
ERR_print_errors(bio_err);
BIO_printf(bio_err, "Error, DSA key generation failed\n");
goto end;
}
} else if (informat == FORMAT_ASN1)
dsa = d2i_DSAparams_bio(in, NULL);
else
dsa = PEM_read_bio_DSAparams(in, NULL, NULL, NULL);
if (dsa == NULL) {
BIO_printf(bio_err, "unable to load DSA parameters\n");
ERR_print_errors(bio_err);
goto end;
}
if (text) {
DSAparams_print(out, dsa);
}
if (C) {
int len = BN_num_bytes(dsa->p);
int bits_p = BN_num_bits(dsa->p);
unsigned char *data = app_malloc(len + 20, "BN space");
BIO_printf(bio_out, "DSA *get_dsa%d()\n{\n", bits_p);
print_bignum_var(bio_out, dsa->p, "dsap", len, data);
print_bignum_var(bio_out, dsa->q, "dsaq", len, data);
print_bignum_var(bio_out, dsa->g, "dsag", len, data);
BIO_printf(bio_out, " DSA *dsa = DSA_new();\n"
"\n");
BIO_printf(bio_out, " if (dsa == NULL)\n"
" return NULL;\n");
BIO_printf(bio_out, " dsa->p = BN_bin2bn(dsap_%d, sizeof (dsap_%d), NULL);\n",
bits_p, bits_p);
BIO_printf(bio_out, " dsa->q = BN_bin2bn(dsaq_%d, sizeof (dsaq_%d), NULL);\n",
bits_p, bits_p);
BIO_printf(bio_out, " dsa->g = BN_bin2bn(dsag_%d, sizeof (dsag_%d), NULL);\n",
bits_p, bits_p);
BIO_printf(bio_out, " if (!dsa->p || !dsa->q || !dsa->g) {\n"
" DSA_free(dsa);\n"
" return NULL;\n"
" }\n"
" return(dsa);\n}\n");
}
if (!noout) {
if (outformat == FORMAT_ASN1)
i = i2d_DSAparams_bio(out, dsa);
else
i = PEM_write_bio_DSAparams(out, dsa);
if (!i) {
BIO_printf(bio_err, "unable to write DSA parameters\n");
ERR_print_errors(bio_err);
goto end;
}
}
if (genkey) {
DSA *dsakey;
assert(need_rand);
if ((dsakey = DSAparams_dup(dsa)) == NULL)
goto end;
if (non_fips_allow)
dsakey->flags |= DSA_FLAG_NON_FIPS_ALLOW;
if (!DSA_generate_key(dsakey)) {
ERR_print_errors(bio_err);
DSA_free(dsakey);
goto end;
}
assert(private);
if (outformat == FORMAT_ASN1)
i = i2d_DSAPrivateKey_bio(out, dsakey);
else
i = PEM_write_bio_DSAPrivateKey(out, dsakey, NULL, NULL, 0, NULL,
NULL);
DSA_free(dsakey);
}
if (need_rand)
app_RAND_write_file(NULL);
ret = 0;
end:
BN_GENCB_free(cb);
BIO_free(in);
BIO_free_all(out);
DSA_free(dsa);
return (ret);
}
static int dsa_cb(int p, int n, BN_GENCB *cb)
{
char c = '*';
if (p == 0)
c = '.';
if (p == 1)
c = '+';
if (p == 2)
c = '*';
if (p == 3)
c = '\n';
BIO_write(BN_GENCB_get_arg(cb), &c, 1);
(void)BIO_flush(BN_GENCB_get_arg(cb));
# ifdef GENCB_TEST
if (stop_keygen_flag)
return 0;
# endif
return 1;
}
#else /* !OPENSSL_NO_DSA */
# if PEDANTIC
static void *dummy = &dummy;
# endif
#endif
| 33.484932 | 89 | 0.58182 | [
"object"
] |
c59eb949416faa903ecff54ec19d1fac199e9b8a | 30,147 | c | C | invensense/6515/libsensors_iio/software/core/mllite/results_holder.c | OpenSource-Infinix/android_hardware | 9a8a025f7c9471444c9e271bbe7f48182741d710 | [
"Unlicense"
] | 1 | 2017-09-22T01:41:30.000Z | 2017-09-22T01:41:30.000Z | invensense/6515/libsensors_iio/software/core/mllite/results_holder.c | Keneral/ahardware | 9a8a025f7c9471444c9e271bbe7f48182741d710 | [
"Unlicense"
] | null | null | null | invensense/6515/libsensors_iio/software/core/mllite/results_holder.c | Keneral/ahardware | 9a8a025f7c9471444c9e271bbe7f48182741d710 | [
"Unlicense"
] | 1 | 2018-02-24T19:09:04.000Z | 2018-02-24T19:09:04.000Z | /*
$License:
Copyright (C) 2011-2012 InvenSense Corporation, All Rights Reserved.
See included License.txt for License information.
$
*/
/**
* @defgroup Results_Holder results_holder
* @brief Motion Library - Results Holder
* Holds the data for MPL
*
* @{
* @file results_holder.c
* @brief Results Holder for HAL.
*/
#include <string.h>
#include "results_holder.h"
#include "ml_math_func.h"
#include "mlmath.h"
#include "start_manager.h"
#include "data_builder.h"
#include "message_layer.h"
#include "log.h"
struct results_t {
float nav_quat[4];
float game_quat[4];
long gam_quat[4];
float geomag_quat[4];
long accel_quat[4];
inv_time_t nav_timestamp;
inv_time_t gam_timestamp;
inv_time_t geomag_timestamp;
long mag_scale[3]; /**< scale factor to apply to magnetic field reading */
long compass_correction[4]; /**< quaternion going from gyro,accel quaternion to 9 axis */
long geomag_compass_correction[4]; /**< quaternion going from accel quaternion to geomag sensor fusion */
int acc_state; /**< Describes accel state */
int got_accel_bias; /**< Flag describing if accel bias is known */
long compass_bias_error[3]; /**< Error Squared */
unsigned char motion_state;
unsigned int motion_state_counter; /**< Incremented for each no motion event in a row */
long compass_count; /**< compass state internal counter */
int got_compass_bias; /**< Flag describing if compass bias is known */
int large_mag_field; /**< Flag describing if there is a large magnetic field */
int compass_state; /**< Internal compass state */
long status;
struct inv_sensor_cal_t *sensor;
float quat_confidence_interval;
float geo_mag_confidence_interval;
struct local_field_t mag_local_field;
struct local_field_t mpl_compass_cal;
int quat_validity;
#ifdef WIN32
long last_quat[4];
#endif
};
static struct results_t rh;
/** @internal
* Store a quaternion more suitable for gaming. This quaternion is often determined
* using only gyro and accel.
* @param[in] quat Length 4, Quaternion scaled by 2^30
* @param[in] timestamp Timestamp of the 6-axis quaternion
*/
void inv_store_gaming_quaternion(const long *quat, inv_time_t timestamp)
{
rh.status |= INV_6_AXIS_QUAT_SET;
memcpy(&rh.gam_quat, quat, sizeof(rh.gam_quat));
rh.gam_timestamp = timestamp;
}
/** @internal
* Store a 9-axis quaternion.
* @param[in] quat Length 4 in floating-point numbers
* @param[in] timestamp Timestamp of the 9-axis quaternion
*/
void inv_store_nav_quaternion(const float *quat, inv_time_t timestamp)
{
memcpy(&rh.nav_quat, quat, sizeof(rh.nav_quat));
rh.nav_timestamp = timestamp;
}
/** @internal
* Store a 6-axis geomagnetic quaternion.
* @param[in] quat Length 4 in floating-point numbers
* @param[in] timestamp Timestamp of the geomag quaternion
*/
void inv_store_geomag_quaternion(const float *quat, inv_time_t timestamp)
{
memcpy(&rh.geomag_quat, quat, sizeof(rh.geomag_quat));
rh.geomag_timestamp = timestamp;
}
/** @internal
* Store a floating-point quaternion more suitable for gaming.
* @param[in] quat Length 4 in floating-point numbers
* @param[in] timestamp Timestamp of the 6-axis quaternion
*/
void inv_store_game_quaternion(const float *quat, inv_time_t timestamp)
{
rh.status |= INV_6_AXIS_QUAT_SET;
memcpy(&rh.game_quat, quat, sizeof(rh.game_quat));
rh.gam_timestamp = timestamp;
}
/** @internal
* Store a quaternion computed from accelerometer correction. This quaternion is
* determined * using only accel, and used for geomagnetic fusion.
* @param[in] quat Length 4, Quaternion scaled by 2^30
*/
void inv_store_accel_quaternion(const long *quat, inv_time_t timestamp)
{
// rh.status |= INV_6_AXIS_QUAT_SET;
memcpy(&rh.accel_quat, quat, sizeof(rh.accel_quat));
rh.geomag_timestamp = timestamp;
}
/** @internal
* Sets the quaternion adjustment from 6 axis (accel, gyro) to 9 axis quaternion.
* @param[in] data Quaternion Adjustment
* @param[in] timestamp Timestamp of when this is valid
*/
void inv_set_compass_correction(const long *data, inv_time_t timestamp)
{
rh.status |= INV_COMPASS_CORRECTION_SET;
memcpy(rh.compass_correction, data, sizeof(rh.compass_correction));
rh.nav_timestamp = timestamp;
}
/** @internal
* Sets the quaternion adjustment from 3 axis (accel) to 6 axis (with compass) quaternion.
* @param[in] data Quaternion Adjustment
* @param[in] timestamp Timestamp of when this is valid
*/
void inv_set_geomagnetic_compass_correction(const long *data, inv_time_t timestamp)
{
rh.status |= INV_GEOMAGNETIC_CORRECTION_SET;
memcpy(rh.geomag_compass_correction, data, sizeof(rh.geomag_compass_correction));
rh.geomag_timestamp = timestamp;
}
/** @internal
* Gets the quaternion adjustment from 6 axis (accel, gyro) to 9 axis quaternion.
* @param[out] data Quaternion Adjustment
* @param[out] timestamp Timestamp of when this is valid
*/
void inv_get_compass_correction(long *data, inv_time_t *timestamp)
{
memcpy(data, rh.compass_correction, sizeof(rh.compass_correction));
*timestamp = rh.nav_timestamp;
}
/** @internal
* Gets the quaternion adjustment from 3 axis (accel) to 6 axis (with compass) quaternion.
* @param[out] data Quaternion Adjustment
* @param[out] timestamp Timestamp of when this is valid
*/
void inv_get_geomagnetic_compass_correction(long *data, inv_time_t *timestamp)
{
memcpy(data, rh.geomag_compass_correction, sizeof(rh.geomag_compass_correction));
*timestamp = rh.geomag_timestamp;
}
/** Returns non-zero if there is a large magnetic field. See inv_set_large_mag_field() for setting this variable.
* @return Returns non-zero if there is a large magnetic field.
*/
int inv_get_large_mag_field()
{
return rh.large_mag_field;
}
/** Set to non-zero if there as a large magnetic field. See inv_get_large_mag_field() for getting this variable.
* @param[in] state value to set for magnetic field strength. Should be non-zero if it is large.
*/
void inv_set_large_mag_field(int state)
{
rh.large_mag_field = state;
}
/** Gets the accel state set by inv_set_acc_state()
* @return accel state.
*/
int inv_get_acc_state()
{
return rh.acc_state;
}
/** Sets the accel state. See inv_get_acc_state() to get the value.
* @param[in] state value to set accel state to.
*/
void inv_set_acc_state(int state)
{
rh.acc_state = state;
return;
}
/** Returns the motion state
* @param[out] cntr Number of previous times a no motion event has occured in a row.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
int inv_get_motion_state(unsigned int *cntr)
{
*cntr = rh.motion_state_counter;
return rh.motion_state;
}
/** Sets the motion state
* @param[in] state motion state where INV_NO_MOTION is not moving
* and INV_MOTION is moving.
*/
void inv_set_motion_state(unsigned char state)
{
long set;
if (state == rh.motion_state) {
if (state == INV_NO_MOTION) {
rh.motion_state_counter++;
} else {
rh.motion_state_counter = 0;
}
return;
}
rh.motion_state_counter = 0;
rh.motion_state = state;
/* Equivalent to set = state, but #define's may change. */
if (state == INV_MOTION)
set = INV_MSG_MOTION_EVENT;
else
set = INV_MSG_NO_MOTION_EVENT;
inv_set_message(set, (INV_MSG_MOTION_EVENT | INV_MSG_NO_MOTION_EVENT), 0);
}
/** Sets the compass sensitivity
* @param[in] data Length 3, sensitivity for each compass axis
* scaled such that 1.0 = 2^30.
*/
void inv_set_mag_scale(const long *data)
{
memcpy(rh.mag_scale, data, sizeof(rh.mag_scale));
}
/** Gets the compass sensitivity
* @param[out] data Length 3, sensitivity for each compass axis
* scaled such that 1.0 = 2^30.
*/
void inv_get_mag_scale(long *data)
{
memcpy(data, rh.mag_scale, sizeof(rh.mag_scale));
}
/** Gets gravity vector
* @param[out] data gravity vector in body frame scaled such that 1.0 = 2^30.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_get_gravity(long *data)
{
long ldata[4];
inv_error_t result = inv_get_quaternion(ldata);
data[0] =
inv_q29_mult(ldata[1], ldata[3]) - inv_q29_mult(ldata[2], ldata[0]);
data[1] =
inv_q29_mult(ldata[2], ldata[3]) + inv_q29_mult(ldata[1], ldata[0]);
data[2] =
(inv_q29_mult(ldata[3], ldata[3]) + inv_q29_mult(ldata[0], ldata[0])) -
1073741824L;
return result;
}
/** Returns a quaternion based only on accel.
* @param[out] data 3-axis accel quaternion scaled such that 1.0 = 2^30.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_get_accel_quaternion(long *data)
{
memcpy(data, rh.accel_quat, sizeof(rh.accel_quat));
return INV_SUCCESS;
}
inv_error_t inv_get_gravity_6x(long *data)
{
data[0] =
inv_q29_mult(rh.gam_quat[1], rh.gam_quat[3]) - inv_q29_mult(rh.gam_quat[2], rh.gam_quat[0]);
data[1] =
inv_q29_mult(rh.gam_quat[2], rh.gam_quat[3]) + inv_q29_mult(rh.gam_quat[1], rh.gam_quat[0]);
data[2] =
(inv_q29_mult(rh.gam_quat[3], rh.gam_quat[3]) + inv_q29_mult(rh.gam_quat[0], rh.gam_quat[0])) -
1073741824L;
return INV_SUCCESS;
}
/** Returns a quaternion based only on gyro and accel.
* @param[out] data 6-axis gyro and accel quaternion scaled such that 1.0 = 2^30.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_get_6axis_quaternion(long *data, inv_time_t *timestamp)
{
data[0] = (long)MIN(MAX(rh.game_quat[0] * ((float)(1L << 30)), -2147483648.), 2147483647.);
data[1] = (long)MIN(MAX(rh.game_quat[1] * ((float)(1L << 30)), -2147483648.), 2147483647.);
data[2] = (long)MIN(MAX(rh.game_quat[2] * ((float)(1L << 30)), -2147483648.), 2147483647.);
data[3] = (long)MIN(MAX(rh.game_quat[3] * ((float)(1L << 30)), -2147483648.), 2147483647.);
*timestamp = rh.gam_timestamp;
return INV_SUCCESS;
}
/** Returns a quaternion.
* @param[out] data 9-axis quaternion scaled such that 1.0 = 2^30.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_get_quaternion(long *data)
{
data[0] = (long)MIN(MAX(rh.nav_quat[0] * ((float)(1L << 30)), -2147483648.), 2147483647.);
data[1] = (long)MIN(MAX(rh.nav_quat[1] * ((float)(1L << 30)), -2147483648.), 2147483647.);
data[2] = (long)MIN(MAX(rh.nav_quat[2] * ((float)(1L << 30)), -2147483648.), 2147483647.);
data[3] = (long)MIN(MAX(rh.nav_quat[3] * ((float)(1L << 30)), -2147483648.), 2147483647.);
return INV_SUCCESS;
}
#ifdef WIN32
/** Returns the last 9-axis quaternion genearted by MPL, so that
* it can be written to the DMP.
* @param[out] data 9-axis quaternion scaled such that 1.0 = 2^30.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_get_last_quaternion(long *data)
{
memcpy(data, rh.last_quat, sizeof(rh.last_quat));
return INV_SUCCESS;
}
/** Saves the last 9-axis quaternion generated by MPL.
* @param[in] data 9-axis quaternion data.
*/
inv_error_t inv_set_last_quaternion(long *data)
{
memcpy(rh.last_quat, data, sizeof(rh.last_quat));
return INV_SUCCESS;
}
#endif
/** Returns the status of the result holder.
* @param[out] rh_status Result holder status.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_get_result_holder_status(long *rh_status)
{
*rh_status = rh.status;
return INV_SUCCESS;
}
/** Set the status of the result holder.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_set_result_holder_status(long rh_status)
{
rh.status = rh_status;
return INV_SUCCESS;
}
/** Returns the status of the authenticity of the quaternion data.
* @param[out] value Authenticity of the quaternion data.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_get_quaternion_validity(int *value)
{
*value = rh.quat_validity;
return INV_SUCCESS;
}
/** Set the status of the authenticity of the quaternion data.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_set_quaternion_validity(int value)
{
rh.quat_validity = value;
return INV_SUCCESS;
}
/** Returns a quaternion based only on compass and accel.
* @param[out] data 6-axis compass and accel quaternion scaled such that 1.0 = 2^30.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_get_geomagnetic_quaternion(long *data, inv_time_t *timestamp)
{
data[0] = (long)MIN(MAX(rh.geomag_quat[0] * ((float)(1L << 30)), -2147483648.), 2147483647.);
data[1] = (long)MIN(MAX(rh.geomag_quat[1] * ((float)(1L << 30)), -2147483648.), 2147483647.);
data[2] = (long)MIN(MAX(rh.geomag_quat[2] * ((float)(1L << 30)), -2147483648.), 2147483647.);
data[3] = (long)MIN(MAX(rh.geomag_quat[3] * ((float)(1L << 30)), -2147483648.), 2147483647.);
*timestamp = rh.geomag_timestamp;
return INV_SUCCESS;
}
/** Returns a quaternion.
* @param[out] data 9-axis quaternion.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_get_quaternion_float(float *data)
{
memcpy(data, rh.nav_quat, sizeof(rh.nav_quat));
return INV_SUCCESS;
}
/** Returns a quaternion based only on gyro and accel.
* @param[out] data 6-axis gyro and accel quaternion.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_get_6axis_quaternion_float(float *data, inv_time_t *timestamp)
{
memcpy(data, rh.game_quat, sizeof(rh.game_quat));
*timestamp = rh.gam_timestamp;
return INV_SUCCESS;
}
/** Returns a quaternion based only on compass and accel.
* @param[out] data 6-axis compass and accel quaternion.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_get_geomagnetic_quaternion_float(float *data, inv_time_t *timestamp)
{
memcpy(data, rh.geomag_quat, sizeof(rh.geomag_quat));
*timestamp = rh.geomag_timestamp;
return INV_SUCCESS;
}
/** Returns a quaternion with accuracy and timestamp.
* @param[out] data 9-axis quaternion scaled such that 1.0 = 2^30.
* @param[out] accuracy Accuracy of quaternion, 0-3, where 3 is most accurate.
* @param[out] timestamp Timestamp of this quaternion in nanoseconds
*/
void inv_get_quaternion_set(long *data, int *accuracy, inv_time_t *timestamp)
{
inv_get_quaternion(data);
*timestamp = inv_get_last_timestamp();
if (inv_get_compass_on()) {
*accuracy = inv_get_mag_accuracy();
} else if (inv_get_gyro_on()) {
*accuracy = inv_get_gyro_accuracy();
}else if (inv_get_accel_on()) {
*accuracy = inv_get_accel_accuracy();
} else {
*accuracy = 0;
}
}
/** Callback that gets called everytime there is new data. It is
* registered by inv_start_results_holder().
* @param[in] sensor_cal New sensor data to process.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_generate_results(struct inv_sensor_cal_t *sensor_cal)
{
rh.sensor = sensor_cal;
return INV_SUCCESS;
}
/** Function to turn on this module. This is automatically called by
* inv_enable_results_holder(). Typically not called by users.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_start_results_holder(void)
{
inv_register_data_cb(inv_generate_results, INV_PRIORITY_RESULTS_HOLDER,
INV_GYRO_NEW | INV_ACCEL_NEW | INV_MAG_NEW);
return INV_SUCCESS;
}
/** Initializes results holder. This is called automatically by the
* enable function inv_enable_results_holder(). It may be called any time the feature is enabled, but
* is typically not needed to be called by outside callers.
* @return Returns INV_SUCCESS if successful or an error code if not.
*/
inv_error_t inv_init_results_holder(void)
{
memset(&rh, 0, sizeof(rh));
rh.mag_scale[0] = 1L<<30;
rh.mag_scale[1] = 1L<<30;
rh.mag_scale[2] = 1L<<30;
rh.compass_correction[0] = 1L<<30;
rh.gam_quat[0] = 1L<<30;
rh.nav_quat[0] = 1.;
rh.geomag_quat[0] = 1.;
rh.game_quat[0] = 1.;
rh.accel_quat[0] = 1L<<30;
rh.geomag_compass_correction[0] = 1L<<30;
rh.quat_confidence_interval = (float)M_PI;
#ifdef WIN32
rh.last_quat[0] = 1L<<30;
#endif
#ifdef TEST
{
struct local_field_t local_field;
local_field.intensity = 48.0f; // uT
local_field.inclination = 60.0f; // degree
local_field.declination = 0.0f; // degree
inv_set_earth_magnetic_local_field_parameter(&local_field);
// inv_set_local_field_status(LOCAL_FILED_NOT_SET_BY_USER);
inv_set_local_field_status(LOCAL_FILED_SET_BY_USER);
inv_set_local_magnetic_field(48.0f, 59.0f, 0.0f);
// set default mpl calibration result for testing
local_field.intensity = 50.0f; // uT
local_field.inclination = 59.0f; // degree
local_field.declination = 0.0f; // degree
inv_set_mpl_magnetic_local_field_parameter(&local_field);
inv_set_mpl_mag_field_status(LOCAL_FIELD_SET_BUT_NOT_MATCH_WITH_MPL);
}
#endif
return INV_SUCCESS;
}
/** Turns on storage of results.
*/
inv_error_t inv_enable_results_holder()
{
inv_error_t result;
result = inv_init_results_holder();
if ( result ) {
return result;
}
result = inv_register_mpl_start_notification(inv_start_results_holder);
return result;
}
/** Sets state of if we know the accel bias.
* @return return 1 if we know the accel bias, 0 if not.
* it is set with inv_set_accel_bias_found()
*/
int inv_got_accel_bias()
{
return rh.got_accel_bias;
}
/** Sets whether we know the accel bias
* @param[in] state Set to 1 if we know the accel bias.
* Can be retrieved with inv_got_accel_bias()
*/
void inv_set_accel_bias_found(int state)
{
rh.got_accel_bias = state;
}
/** Sets state of if we know the compass bias.
* @return return 1 if we know the compass bias, 0 if not.
* it is set with inv_set_compass_bias_found()
*/
int inv_got_compass_bias()
{
return rh.got_compass_bias;
}
/** Sets whether we know the compass bias
* @param[in] state Set to 1 if we know the compass bias.
* Can be retrieved with inv_got_compass_bias()
*/
void inv_set_compass_bias_found(int state)
{
rh.got_compass_bias = state;
}
/** Sets the compass state.
* @param[in] state Compass state. It can be retrieved with inv_get_compass_state().
*/
void inv_set_compass_state(int state)
{
rh.compass_state = state;
}
/** Get's the compass state
* @return the compass state that was set with inv_set_compass_state()
*/
int inv_get_compass_state()
{
return rh.compass_state;
}
/** Set compass bias error. See inv_get_compass_bias_error()
* @param[in] bias_error Set's how accurate we know the compass bias. It is the
* error squared.
*/
void inv_set_compass_bias_error(const long *bias_error)
{
memcpy(rh.compass_bias_error, bias_error, sizeof(rh.compass_bias_error));
}
/** Get's compass bias error. See inv_set_compass_bias_error() for setting.
* @param[out] bias_error Accuracy as to how well the compass bias is known. It is the error squared.
*/
void inv_get_compass_bias_error(long *bias_error)
{
memcpy(bias_error, rh.compass_bias_error, sizeof(rh.compass_bias_error));
}
/**
* @brief Returns 3-element vector of accelerometer data in body frame
* with gravity removed
* @param[out] data 3-element vector of accelerometer data in body frame
* with gravity removed
* @return INV_SUCCESS if successful
* INV_ERROR_INVALID_PARAMETER if invalid input pointer
*/
inv_error_t inv_get_linear_accel(long *data)
{
long gravity[3];
if (data != NULL)
{
inv_get_accel_set(data, NULL, NULL);
inv_get_gravity(gravity);
data[0] -= gravity[0] >> 14;
data[1] -= gravity[1] >> 14;
data[2] -= gravity[2] >> 14;
return INV_SUCCESS;
}
else {
return INV_ERROR_INVALID_PARAMETER;
}
}
/**
* @brief Returns 3-element vector of accelerometer data in body frame
* @param[out] data 3-element vector of accelerometer data in body frame
* @return INV_SUCCESS if successful
* INV_ERROR_INVALID_PARAMETER if invalid input pointer
*/
inv_error_t inv_get_accel(long *data)
{
if (data != NULL) {
inv_get_accel_set(data, NULL, NULL);
return INV_SUCCESS;
}
else {
return INV_ERROR_INVALID_PARAMETER;
}
}
/**
* @brief Returns 3-element vector of accelerometer float data
* @param[out] data 3-element vector of accelerometer float data
* @return INV_SUCCESS if successful
* INV_ERROR_INVALID_PARAMETER if invalid input pointer
*/
inv_error_t inv_get_accel_float(float *data)
{
long tdata[3];
unsigned char i;
if (data != NULL && !inv_get_accel(tdata)) {
for (i = 0; i < 3; ++i) {
data[i] = ((float)tdata[i] / (1L << 16));
}
return INV_SUCCESS;
}
else {
return INV_ERROR_INVALID_PARAMETER;
}
}
/**
* @brief Returns 3-element vector of gyro float data
* @param[out] data 3-element vector of gyro float data
* @return INV_SUCCESS if successful
* INV_ERROR_INVALID_PARAMETER if invalid input pointer
*/
inv_error_t inv_get_gyro_float(float *data)
{
long tdata[3];
unsigned char i;
if (data != NULL) {
inv_get_gyro_set(tdata, NULL, NULL);
for (i = 0; i < 3; ++i) {
data[i] = ((float)tdata[i] / (1L << 16));
}
return INV_SUCCESS;
}
else {
return INV_ERROR_INVALID_PARAMETER;
}
}
/** Set 9 axis 95% heading confidence interval for quaternion
* @param[in] ci Confidence interval in radians.
*/
void inv_set_heading_confidence_interval(float ci)
{
rh.quat_confidence_interval = ci;
}
/** Get 9 axis 95% heading confidence interval for quaternion
* @return Confidence interval in radians.
*/
float inv_get_heading_confidence_interval(void)
{
return rh.quat_confidence_interval;
}
/** Set 6 axis (accel and compass) 95% heading confidence interval for quaternion
* @param[in] ci Confidence interval in radians.
*/
void inv_set_accel_compass_confidence_interval(float ci)
{
rh.geo_mag_confidence_interval = ci;
}
/** Get 6 axis (accel and compass) 95% heading confidence interval for quaternion
* @return Confidence interval in radians.
*/
float inv_get_accel_compass_confidence_interval(void)
{
return rh.geo_mag_confidence_interval;
}
/**
* @brief Returns 3-element vector of linear accel float data
* @param[out] data 3-element vector of linear aceel float data
* @return INV_SUCCESS if successful
* INV_ERROR_INVALID_PARAMETER if invalid input pointer
*/
inv_error_t inv_get_linear_accel_float(float *data)
{
long tdata[3];
unsigned char i;
if (data != NULL && !inv_get_linear_accel(tdata)) {
for (i = 0; i < 3; ++i) {
data[i] = ((float)tdata[i] / (1L << 16));
}
return INV_SUCCESS;
}
else {
return INV_ERROR_INVALID_PARAMETER;
}
}
/**
* @brief Returns the status of earth magnetic field local field parameters
* @param[out] N/A
* @return status of local field, defined in enum compass_local_field_e
*/
enum compass_local_field_e inv_get_local_field_status(void)
{
return rh.mag_local_field.mpl_match_status;
}
/** Set the status of earth magnetic field local field parameters
* @param[in] status of earth magnetic field local field parameters.
*/
void inv_set_local_field_status(enum compass_local_field_e status)
{
rh.mag_local_field.mpl_match_status = status;
}
/** Set the parameters of earth magnetic field local field
* @param[in] the earth magnetic field local field parameters.
*/
void inv_set_earth_magnetic_local_field_parameter(struct local_field_t *parameters)
{
rh.mag_local_field.intensity = parameters->intensity; // radius
rh.mag_local_field.inclination = parameters->inclination; // dip angle
rh.mag_local_field.declination = parameters->declination; // yaw deviation angle from true north
inv_set_local_field_status(LOCAL_FILED_SET_BY_USER);
}
/**
* @brief Returns the parameters of earth magnetic field local field
* @param[out] the parameters of earth magnetic field local field
* @return N/A
*/
void inv_get_earth_magnetic_local_field_parameter(struct local_field_t *parameters)
{
parameters->intensity = rh.mag_local_field.intensity; // radius
parameters->inclination = rh.mag_local_field.inclination; // dip angle
parameters->declination = rh.mag_local_field.declination; // yaw deviation angle from true north
parameters->mpl_match_status = rh.mag_local_field.mpl_match_status;
}
/**
* @brief Returns the status of mpl calibrated magnetic field local field parameters
* @param[out] N/A
* @return status of local field, defined in enum compass_local_field_e
*/
enum compass_local_field_e inv_get_mpl_mag_field_status(void)
{
return rh.mpl_compass_cal.mpl_match_status;
}
/** Set the status of mpl calibrated magnetic field local field parameters
* @param[in] status of earth magnetic field local field parameters.
*/
void inv_set_mpl_mag_field_status(enum compass_local_field_e status)
{
rh.mpl_compass_cal.mpl_match_status = status;
}
/** Set the magnetic field local field struct object
* @param[in] status of earth magnetic field local field parameters.
*/
inv_error_t inv_set_local_magnetic_field(float intensity, float inclination, float declination)
{
struct local_field_t local_field;
local_field.intensity = intensity; // radius
local_field.inclination = inclination; // dip angle angle degree
local_field.declination = declination; // yaw deviation angle from true north, eastward as positive
local_field.mpl_match_status = LOCAL_FILED_SET_BY_USER;
inv_set_earth_magnetic_local_field_parameter(&local_field);
return 0;
}
/** Set the parameters of mpl calibrated magnetic field local field
* This API is used by mpl only.
* @param[in] the earth magnetic field local field parameters.
* @return INV_SUCCESS if successful
* INV_ERROR_INVALID_PARAMETER if invalid input pointer
*/
inv_error_t inv_set_mpl_magnetic_local_field_parameter(struct local_field_t *parameters)
{
enum compass_local_field_e mpl_status;
struct local_field_t local_field;
inv_error_t status;
rh.mpl_compass_cal.intensity = parameters->intensity; // radius
rh.mpl_compass_cal.inclination = parameters->inclination; // dip angle
rh.mpl_compass_cal.declination = parameters->declination; // yaw deviation angle from true north
mpl_status = inv_get_mpl_mag_field_status();
inv_get_earth_magnetic_local_field_parameter(&local_field);
status = INV_SUCCESS;
switch (inv_get_local_field_status()) {
case LOCAL_FILED_NOT_SET_BY_USER:
if (mpl_status == LOCAL_FILED_NOT_SET_BY_USER) {
inv_set_mpl_mag_field_status(LOCAL_FILED_NOT_SET_BY_USER_BUT_SET_BY_MPL);
} else {
// illegal status
status = INV_ERROR_INVALID_PARAMETER;
}
break;
case LOCAL_FILED_SET_BY_USER:
switch (mpl_status) {
case LOCAL_FIELD_SET_BUT_NOT_MATCH_WITH_MPL:
case LOCAL_FIELD_SET_MATCH_WITH_MPL:
if ( (ABS(local_field.intensity - parameters->intensity) < 5.0f) &&
(ABS(local_field.intensity - parameters->intensity) < 5.0f) ) {
inv_set_mpl_mag_field_status(LOCAL_FIELD_SET_MATCH_WITH_MPL);
} else {
inv_set_mpl_mag_field_status(LOCAL_FIELD_SET_BUT_NOT_MATCH_WITH_MPL);
}
break;
case LOCAL_FILED_NOT_SET_BY_USER_BUT_SET_BY_MPL:
// no status update
break;
case LOCAL_FILED_NOT_SET_BY_USER:
case LOCAL_FILED_SET_BY_USER:
default:
// illegal status
status = INV_ERROR_INVALID_PARAMETER;
break;
}
break;
case LOCAL_FILED_NOT_SET_BY_USER_BUT_SET_BY_MPL:
case LOCAL_FIELD_SET_BUT_NOT_MATCH_WITH_MPL:
case LOCAL_FIELD_SET_MATCH_WITH_MPL:
default:
// illegal status
status = INV_ERROR_INVALID_PARAMETER;
break;
}
return status;
}
/**
* @brief Returns the parameters of mpl calibrated magnetic field local field
* @param[out] the parameters of earth magnetic field local field
* @return N/A
*/
void inv_get_mpl_magnetic_local_field_parameter(struct local_field_t *parameters)
{
parameters->intensity = rh.mpl_compass_cal.intensity; // radius
parameters->inclination = rh.mpl_compass_cal.inclination; // dip angle
parameters->declination = rh.mpl_compass_cal.declination; // yaw deviation angle from true north
parameters->mpl_match_status = rh.mpl_compass_cal.mpl_match_status;
}
/**
* @}
*/
| 33.721477 | 114 | 0.681361 | [
"object",
"vector"
] |
c5aaa364b16d08931c5d33a1a4f1108e2dba348e | 2,025 | h | C | Examples/Plugins/org.mitk.example.gui.imaging/src/internal/isosurface/QmitkIsoSurface.h | maleike/MITK | 83b0c35625dfaed99147f357dbd798b1dc19815b | [
"BSD-3-Clause"
] | 5 | 2015-02-05T10:58:41.000Z | 2019-04-17T15:04:07.000Z | Examples/Plugins/org.mitk.example.gui.imaging/src/internal/isosurface/QmitkIsoSurface.h | kometa-dev/MITK | 984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d | [
"BSD-3-Clause"
] | 141 | 2015-03-03T06:52:01.000Z | 2020-12-10T07:28:14.000Z | Examples/Plugins/org.mitk.example.gui.imaging/src/internal/isosurface/QmitkIsoSurface.h | kometa-dev/MITK | 984b5f7ac8ea614e80f303381ef1fc77d8ca4c3d | [
"BSD-3-Clause"
] | 4 | 2015-02-19T06:48:13.000Z | 2020-06-19T16:20:25.000Z | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#ifndef QMITK_ISOSURFACE_H__INCLUDED
#define QMITK_ISOSURFACE_H__INCLUDED
#include "QmitkAbstractView.h"
#include "mitkColorSequenceRainbow.h"
#include "mitkDataStorage.h"
#include "ui_QmitkIsoSurfaceControls.h"
/**
* \brief IsoSurface
*
* \sa QmitkAbstractView
*/
class QmitkIsoSurface : public QmitkAbstractView
{
Q_OBJECT
public:
QmitkIsoSurface(QObject *parent=nullptr, const char *name=nullptr);
virtual ~QmitkIsoSurface();
private:
/**
* \brief method for creating the widget containing the application controls, like sliders, buttons etc.
*/
virtual void CreateQtPartControl(QWidget *parent) override;
virtual void SetFocus() override;
/**
* \brief method for creating the connections of main and control widget
*/
virtual void CreateConnections();
private slots:
/*
* just an example slot for the example TreeNodeSelector widget
*/
void ImageSelected(const mitk::DataNode* item);
/**
* \brief method for creating a surface object
*/
void CreateSurface();
private:
/**
* controls containing sliders for scrolling through the slices
*/
Ui::QmitkIsoSurfaceControls * m_Controls;
/**
* image which is used to create the surface
*/
mitk::Image* m_MitkImage;
/**
* read thresholdvalue from GUI and convert it to float
*/
float getThreshold();
/**
* variable to count Surfaces and give it to name
*/
int m_SurfaceCounter;
mitk::ColorSequenceRainbow m_RainbowColor;
};
#endif // QMITK_ISOSURFACE_H__INCLUDED
| 21.774194 | 108 | 0.685926 | [
"object"
] |
c5b0096f27cc4a9be8e5d46808b81098ccebf33e | 9,005 | h | C | Engine/Source/Core/Renderer/PM/TSPPMRadianceEvaluator.h | jasonoscar88/Photon-v2 | 90649196c436261d28cc2300511b78ac88236448 | [
"MIT"
] | 88 | 2017-01-21T18:20:16.000Z | 2021-12-21T02:32:04.000Z | Engine/Source/Core/Renderer/PM/TSPPMRadianceEvaluator.h | jasonoscar88/Photon-v2 | 90649196c436261d28cc2300511b78ac88236448 | [
"MIT"
] | 72 | 2017-07-28T10:00:35.000Z | 2021-11-09T18:36:23.000Z | Engine/Source/Core/Renderer/PM/TSPPMRadianceEvaluator.h | jasonoscar88/Photon-v2 | 90649196c436261d28cc2300511b78ac88236448 | [
"MIT"
] | 8 | 2017-03-19T12:19:10.000Z | 2020-05-19T15:15:05.000Z | #pragma once
#include "Core/Renderer/PM/TViewPathHandler.h"
#include "Core/Renderer/PM/TViewpoint.h"
#include "Core/Renderer/PM/TPhoton.h"
#include "Common/assertion.h"
#include "Common/primitive_type.h"
#include "Core/SurfaceHit.h"
#include "Core/Intersectable/Primitive.h"
#include "Core/Intersectable/PrimitiveMetadata.h"
#include "Core/Emitter/Emitter.h"
#include "Core/SurfaceBehavior/SurfaceBehavior.h"
#include "Core/SurfaceBehavior/SurfaceOptics.h"
#include "Math/Random.h"
#include "World/Scene.h"
#include "Core/Filmic/HdrRgbFilm.h"
#include "Core/Renderer/PM/TPhotonMap.h"
#include "Math/math.h"
#include "Core/Renderer/Region/Region.h"
#include <vector>
#include <type_traits>
#include <utility>
namespace ph
{
template<typename Viewpoint, typename Photon>
class TSPPMRadianceEvaluator : public TViewPathHandler<TSPPMRadianceEvaluator<Viewpoint, Photon>>
{
static_assert(std::is_base_of_v<TViewpoint<Viewpoint>, Viewpoint>);
static_assert(std::is_base_of_v<TPhoton<Photon>, Photon>);
public:
TSPPMRadianceEvaluator(
Viewpoint* viewpoints,
std::size_t numViewpoints,
const TPhotonMap<Photon>* photonMap,
std::size_t numPhotonPaths,
const Scene* scene,
HdrRgbFilm* film,
const Region& filmRegion,
std::size_t numSamplesPerPixel,
std::size_t maxViewpointDepth);
bool impl_onCameraSampleStart(
const Vector2R& filmNdc,
const SpectralStrength& pathThroughput);
auto impl_onPathHitSurface(
std::size_t pathLength,
const SurfaceHit& surfaceHit,
const SpectralStrength& pathThroughput) -> ViewPathTracingPolicy;
void impl_onCameraSampleEnd();
void impl_onSampleBatchFinished();
private:
Viewpoint* m_viewpoints;
std::size_t m_numViewpoints;
const TPhotonMap<Photon>* m_photonMap;
std::size_t m_numPhotonPaths;
const Scene* m_scene;
HdrRgbFilm* m_film;
Region m_filmRegion;
std::size_t m_numSamplesPerPixel;
std::size_t m_maxViewpointDepth;
Viewpoint* m_viewpoint;
std::vector<Photon> m_photonCache;
Vector2S m_filmPosPx;
bool m_isViewpointFound;
void addViewRadiance(const SpectralStrength& radiance);
};
// In-header Implementations:
template<typename Viewpoint, typename Photon>
inline TSPPMRadianceEvaluator<Viewpoint, Photon>::TSPPMRadianceEvaluator(
Viewpoint* viewpoints,
std::size_t numViewpoints,
const TPhotonMap<Photon>* photonMap,
std::size_t numPhotonPaths,
const Scene* scene,
HdrRgbFilm* film,
const Region& filmRegion,
std::size_t numSamplesPerPixel,
std::size_t maxViewpointDepth) :
m_viewpoints(viewpoints),
m_numViewpoints(numViewpoints),
m_photonMap(photonMap),
m_numPhotonPaths(numPhotonPaths),
m_scene(scene),
m_film(film),
m_filmRegion(filmRegion),
m_numSamplesPerPixel(numSamplesPerPixel),
m_maxViewpointDepth(maxViewpointDepth)
{
PH_ASSERT(m_viewpoints);
PH_ASSERT(photonMap);
PH_ASSERT_GE(numPhotonPaths, 1);
PH_ASSERT(scene);
PH_ASSERT(film);
PH_ASSERT_GE(maxViewpointDepth, 1);
}
template<typename Viewpoint, typename Photon>
inline bool TSPPMRadianceEvaluator<Viewpoint, Photon>::impl_onCameraSampleStart(
const Vector2R& filmNdc,
const SpectralStrength& pathThroughput)
{
// FIXME: sample res
const real fFilmXPx = filmNdc.x * static_cast<real>(m_film->getActualResPx().x);
const real fFilmYPx = filmNdc.y * static_cast<real>(m_film->getActualResPx().y);
m_filmPosPx.x = math::clamp(static_cast<std::size_t>(fFilmXPx),
static_cast<std::size_t>(m_filmRegion.minVertex.x),
static_cast<std::size_t>(m_filmRegion.maxVertex.x - 1));
m_filmPosPx.y = math::clamp(static_cast<std::size_t>(fFilmYPx),
static_cast<std::size_t>(m_filmRegion.minVertex.y),
static_cast<std::size_t>(m_filmRegion.maxVertex.y - 1));
const std::size_t viewpointIdx = m_filmPosPx.y * static_cast<std::size_t>(m_film->getActualResPx().x) + m_filmPosPx.x;
PH_ASSERT_LT(viewpointIdx, m_numViewpoints);
m_viewpoint = &(m_viewpoints[viewpointIdx]);
m_isViewpointFound = false;
return true;
}
template<typename Viewpoint, typename Photon>
inline auto TSPPMRadianceEvaluator<Viewpoint, Photon>::impl_onPathHitSurface(
const std::size_t pathLength,
const SurfaceHit& surfaceHit,
const SpectralStrength& pathThroughput) -> ViewPathTracingPolicy
{
const PrimitiveMetadata* metadata = surfaceHit.getDetail().getPrimitive()->getMetadata();
const SurfaceOptics* optics = metadata->getSurface().getOptics();
// TODO: MIS
if constexpr(Viewpoint::template has<EViewpointData::VIEW_RADIANCE>())
{
if(metadata->getSurface().getEmitter())
{
SpectralStrength viewRadiance;
metadata->getSurface().getEmitter()->evalEmittedRadiance(surfaceHit, &viewRadiance);
addViewRadiance(pathThroughput * viewRadiance);
}
}
// TODO: better handling of glossy optics
if(optics->getAllPhenomena().hasAtLeastOne({ESurfacePhenomenon::DIFFUSE_REFLECTION}) ||
pathLength >= m_maxViewpointDepth)
{
if constexpr(Viewpoint::template has<EViewpointData::SURFACE_HIT>()) {
m_viewpoint->template set<EViewpointData::SURFACE_HIT>(surfaceHit);
}
if constexpr(Viewpoint::template has<EViewpointData::VIEW_THROUGHPUT>()) {
m_viewpoint->template set<EViewpointData::VIEW_THROUGHPUT>(pathThroughput);
}
if constexpr(Viewpoint::template has<EViewpointData::VIEW_DIR>()) {
m_viewpoint->template set<EViewpointData::VIEW_DIR>(surfaceHit.getIncidentRay().getDirection().mul(-1));
}
m_isViewpointFound = true;
return ViewPathTracingPolicy().kill();
}
else
{
return ViewPathTracingPolicy().
traceSinglePathFor(ALL_ELEMENTALS).
useRussianRoulette(true);
}
}
template<typename Viewpoint, typename Photon>
inline void TSPPMRadianceEvaluator<Viewpoint, Photon>::impl_onCameraSampleEnd()
{
if(!m_isViewpointFound)
{
return;
}
TSurfaceEventDispatcher<ESaPolicy::STRICT> surfaceEvent(m_scene);
const SurfaceHit& surfaceHit = m_viewpoint->template get<EViewpointData::SURFACE_HIT>();
const Vector3R L = m_viewpoint->template get<EViewpointData::VIEW_DIR>();
const Vector3R Ng = surfaceHit.getGeometryNormal();
const Vector3R Ns = surfaceHit.getShadingNormal();
const real R = m_viewpoint->template get<EViewpointData::RADIUS>();
m_photonCache.clear();
m_photonMap->findWithinRange(surfaceHit.getPosition(), R, m_photonCache);
// FIXME: as a parameter
const real alpha = 2.0_r / 3.0_r;
const real N = m_viewpoint->template get<EViewpointData::NUM_PHOTONS>();
const real M = static_cast<real>(m_photonCache.size());
const real newN = N + alpha * M;
const real newR = (N + M) != 0.0_r ? R * std::sqrt(newN / (N + M)) : R;
SpectralStrength tauM(0);
BsdfEvaluation bsdfEval;
for(const auto& photon : m_photonCache)
{
const Vector3R V = photon.template get<EPhotonData::FROM_DIR>();
bsdfEval.inputs.set(surfaceHit, L, V, ALL_ELEMENTALS, ETransport::IMPORTANCE);
if(!surfaceEvent.doBsdfEvaluation(surfaceHit, bsdfEval))
{
continue;
}
SpectralStrength tau = photon.template get<EPhotonData::THROUGHPUT_RADIANCE>();
tau.mulLocal(bsdfEval.outputs.bsdf);
tau.mulLocal(lta::importance_BSDF_Ns_corrector(Ns, Ng, L, V));
tauM.addLocal(tau);
}
tauM.mulLocal(m_viewpoint->template get<EViewpointData::VIEW_THROUGHPUT>());
const SpectralStrength tauN = m_viewpoint->template get<EViewpointData::TAU>();
const SpectralStrength newTau = (N + M) != 0.0_r ? (tauN + tauM) * (newN / (N + M)) : SpectralStrength(0);
m_viewpoint->template set<EViewpointData::RADIUS>(newR);
m_viewpoint->template set<EViewpointData::NUM_PHOTONS>(newN);
m_viewpoint->template set<EViewpointData::TAU>(newTau);
}
template<typename Viewpoint, typename Photon>
inline void TSPPMRadianceEvaluator<Viewpoint, Photon>::impl_onSampleBatchFinished()
{
// evaluate radiance using current iteration's data
for(int64 y = m_filmRegion.minVertex.y; y < m_filmRegion.maxVertex.y; ++y)
{
for(int64 x = m_filmRegion.minVertex.x; x < m_filmRegion.maxVertex.x; ++x)
{
const auto& viewpoint = m_viewpoints[y * m_film->getActualResPx().x + x];
const real radius = viewpoint.template get<EViewpointData::RADIUS>();
const real kernelArea = radius * radius * constant::pi<real>;
const real radianceMultiplier = 1.0_r / (kernelArea * static_cast<real>(m_numPhotonPaths));
SpectralStrength radiance(viewpoint.template get<EViewpointData::TAU>() * radianceMultiplier);
radiance.addLocal(viewpoint.template get<EViewpointData::VIEW_RADIANCE>() / static_cast<real>(m_numSamplesPerPixel));
m_film->setPixel(static_cast<float64>(x), static_cast<float64>(y), radiance);
}
}
}
template<typename Viewpoint, typename Photon>
inline void TSPPMRadianceEvaluator<Viewpoint, Photon>::addViewRadiance(const SpectralStrength& radiance)
{
if constexpr(Viewpoint::template has<EViewpointData::VIEW_RADIANCE>())
{
SpectralStrength viewRadiance = m_viewpoint->template get<EViewpointData::VIEW_RADIANCE>();
viewRadiance.addLocal(radiance);
m_viewpoint->template set<EViewpointData::VIEW_RADIANCE>(viewRadiance);
}
}
}// end namespace ph | 33.475836 | 120 | 0.759467 | [
"vector"
] |
c5b2e19b3e6c966ba959888e42002d531eef4d46 | 34,785 | c | C | mibench/office/ghostscript/src/gdevmrop.c | hyu-iot/gem5 | aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5 | [
"BSD-3-Clause"
] | 28 | 2017-01-20T15:25:54.000Z | 2020-03-17T00:28:31.000Z | mibench/office/ghostscript/src/gdevmrop.c | hyu-iot/gem5 | aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5 | [
"BSD-3-Clause"
] | 80 | 2019-08-27T14:43:46.000Z | 2020-12-16T11:56:19.000Z | mibench/office/ghostscript/src/gdevmrop.c | hyu-iot/gem5 | aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5 | [
"BSD-3-Clause"
] | 98 | 2019-08-30T14:29:16.000Z | 2020-11-21T18:22:13.000Z | /* Copyright (C) 1995, 1996 Aladdin Enterprises. All rights reserved.
This file is part of Aladdin Ghostscript.
Aladdin Ghostscript is distributed with NO WARRANTY OF ANY KIND. No author
or distributor accepts any responsibility for the consequences of using it,
or for whether it serves any particular purpose or works at all, unless he
or she says so in writing. Refer to the Aladdin Ghostscript Free Public
License (the "License") for full details.
Every copy of Aladdin Ghostscript must include a copy of the License,
normally in a plain ASCII text file named PUBLIC. The License grants you
the right to copy, modify and redistribute Aladdin Ghostscript, but only
under certain conditions described in the License. Among other things, the
License requires that the copyright notice and this notice be preserved on
all copies.
*/
/* gdevmrop.c */
/* RasterOp / transparency / render algorithm implementation for */
/* memory devices */
#include "memory_.h"
#include "gx.h"
#include "gsbittab.h"
#include "gserrors.h"
#include "gsropt.h"
#include "gxdcolor.h"
#include "gxdevice.h"
#include "gxdevmem.h"
#include "gxdevrop.h"
#include "gdevmrop.h"
/* Define whether we implement transparency correctly, or whether we */
/* implement it as documented in the H-P manuals. */
#define TRANSPARENCY_PER_H_P
/**************** NOTE: ****************
* The 2- and 4-bit cases don't handle transparency right.
* The 8- and 24-bit cases haven't been tested.
* The 16- and 32-bit cases aren't implemented.
***************** ****************/
#define mdev ((gx_device_memory *)dev)
/* Forward references */
private gs_rop3_t gs_transparent_rop(P1(gs_logical_operation_t lop));
#define chunk byte
/* Calculate the X offset for a given Y value, */
/* taking shift into account if necessary. */
#define x_offset(px, ty, textures)\
((textures)->shift == 0 ? (px) :\
(px) + (ty) / (textures)->rep_height * (textures)->rep_shift)
/* ---------------- Initialization ---------------- */
void
gs_roplib_init(gs_memory_t *mem)
{ /* Replace the default and forwarding copy_rop procedures. */
gx_default_copy_rop_proc = gx_real_default_copy_rop;
gx_forward_copy_rop_proc = gx_forward_copy_rop;
gx_default_strip_copy_rop_proc = gx_real_default_strip_copy_rop;
gx_forward_strip_copy_rop_proc = gx_forward_strip_copy_rop;
}
/* ---------------- Debugging aids ---------------- */
#ifdef DEBUG
private void
trace_copy_rop(const char *cname, gx_device *dev,
const byte *sdata, int sourcex, uint sraster, gx_bitmap_id id,
const gx_color_index *scolors,
const gx_strip_bitmap *textures, const gx_color_index *tcolors,
int x, int y, int width, int height,
int phase_x, int phase_y, gs_logical_operation_t lop)
{ dprintf4("%s: dev=0x%lx(%s) depth=%d\n",
cname, (ulong)dev, dev->dname, dev->color_info.depth);
dprintf4(" source data=0x%lx x=%d raster=%u id=%lu colors=",
(ulong)sdata, sourcex, sraster, (ulong)id);
if ( scolors )
dprintf2("(%lu,%lu);\n", scolors[0], scolors[1]);
else
dputs("none;\n");
if ( textures )
dprintf8(" textures=0x%lx size=%dx%d(%dx%d) raster=%u shift=%d(%d)",
(ulong)textures, textures->size.x, textures->size.y,
textures->rep_width, textures->rep_height, textures->raster,
textures->shift, textures->rep_shift);
else
dputs(" textures=none");
if ( tcolors )
dprintf2(" colors=(%lu,%lu)\n", tcolors[0], tcolors[1]);
else
dputs(" colors=none\n");
dprintf7(" rect=(%d,%d),(%d,%d) phase=(%d,%d) op=0x%x\n",
x, y, x + width, y + height, phase_x, phase_y,
(uint)lop);
if ( gs_debug_c('B') )
{ if ( sdata )
debug_dump_bitmap(sdata, sraster, height, "source bits");
if ( textures && textures->data )
debug_dump_bitmap(textures->data, textures->raster,
textures->size.y, "textures bits");
}
}
#endif
/* ---------------- Monobit RasterOp ---------------- */
int
mem_mono_strip_copy_rop(gx_device *dev,
const byte *sdata, int sourcex, uint sraster, gx_bitmap_id id,
const gx_color_index *scolors,
const gx_strip_bitmap *textures, const gx_color_index *tcolors,
int x, int y, int width, int height,
int phase_x, int phase_y, gs_logical_operation_t lop)
{ gs_rop3_t rop = gs_transparent_rop(lop); /* handle transparency */
gx_strip_bitmap no_texture;
bool invert;
uint draster = mdev->raster;
uint traster;
int line_count;
byte *drow;
const byte *srow;
int ty;
/* If map_rgb_color isn't the default one for monobit memory */
/* devices, palette might not be set; set it now if needed. */
if ( mdev->palette.data == 0 )
gdev_mem_mono_set_inverted(mdev,
(*dev_proc(dev, map_rgb_color))
(dev, (gx_color_value)0,
(gx_color_value)0, (gx_color_value)0)
!= 0);
invert = mdev->palette.data[0] != 0;
#ifdef DEBUG
if ( gs_debug_c('b') )
trace_copy_rop("mem_mono_strip_copy_rop",
dev, sdata, sourcex, sraster,
id, scolors, textures, tcolors,
x, y, width, height, phase_x, phase_y, lop);
if ( gs_debug_c('B') )
debug_dump_bitmap(scan_line_base(mdev, y), mdev->raster,
height, "initial dest bits");
#endif
/*
* RasterOp is defined as operating in RGB space; in the monobit
* case, this means black = 0, white = 1. However, most monobit
* devices use the opposite convention. To make this work,
* we must precondition the Boolean operation by swapping the
* order of bits end-for-end and then inverting.
*/
if ( invert )
rop = byte_reverse_bits[rop] ^ 0xff;
/*
* From this point on, rop works in terms of device pixel values,
* not RGB-space values.
*/
/* Modify the raster operation according to the source palette. */
if ( scolors != 0 )
{ /* Source with palette. */
switch ( (int)((scolors[1] << 1) + scolors[0]) )
{
case 0: rop = rop3_know_S_0(rop); break;
case 1: rop = rop3_invert_S(rop); break;
case 2: break;
case 3: rop = rop3_know_S_1(rop); break;
}
}
/* Modify the raster operation according to the texture palette. */
if ( tcolors != 0 )
{ /* Texture with palette. */
switch ( (int)((tcolors[1] << 1) + tcolors[0]) )
{
case 0: rop = rop3_know_T_0(rop); break;
case 1: rop = rop3_invert_T(rop); break;
case 2: break;
case 3: rop = rop3_know_T_1(rop); break;
}
}
/* Handle constant source and/or texture, and other special cases. */
{ gx_color_index color0, color1;
switch ( rop_usage_table[rop] )
{
case rop_usage_none:
/* We're just filling with a constant. */
return (*dev_proc(dev, fill_rectangle))
(dev, x, y, width, height, (gx_color_index)(rop & 1));
case rop_usage_D:
/* This is either D (no-op) or ~D. */
if ( rop == rop3_D )
return 0;
/* Code no_S inline, then finish with no_T. */
fit_fill(dev, x, y, width, height);
sdata = mdev->base;
sourcex = x;
sraster = 0;
goto no_T;
case rop_usage_S:
/* This is either S or ~S, which copy_mono can handle. */
if ( rop == rop3_S )
color0 = 0, color1 = 1;
else
color0 = 1, color1 = 0;
do_copy: return (*dev_proc(dev, copy_mono))
(dev, sdata, sourcex, sraster, id, x, y, width, height,
color0, color1);
case rop_usage_DS:
/* This might be a case that copy_mono can handle. */
#define copy_case(c0, c1) color0 = c0, color1 = c1; goto do_copy;
switch ( (uint)rop ) /* cast shuts up picky compilers */
{
case rop3_D & rop3_not(rop3_S): copy_case(gx_no_color_index, 0);
case rop3_D | rop3_S: copy_case(gx_no_color_index, 1);
case rop3_D & rop3_S: copy_case(0, gx_no_color_index);
case rop3_D | rop3_not(rop3_S): copy_case(1, gx_no_color_index);
default: ;
}
#undef copy_case
fit_copy(dev, sdata, sourcex, sraster, id, x, y, width, height);
no_T: /* Texture is not used; textures may be garbage. */
no_texture.data = mdev->base; /* arbitrary */
no_texture.raster = 0;
no_texture.size.x = width;
no_texture.size.y = height;
no_texture.rep_width = no_texture.rep_height = 1;
no_texture.rep_shift = no_texture.shift = 0;
textures = &no_texture;
break;
case rop_usage_T:
/* This is either T or ~T, which tile_rectangle can handle. */
if ( rop == rop3_T )
color0 = 0, color1 = 1;
else
color0 = 1, color1 = 0;
do_tile: return (*dev_proc(dev, strip_tile_rectangle))
(dev, textures, x, y, width, height, color0, color1,
phase_x, phase_y);
case rop_usage_DT:
/* This might be a case that tile_rectangle can handle. */
#define tile_case(c0, c1) color0 = c0, color1 = c1; goto do_tile;
switch ( (uint)rop ) /* cast shuts up picky compilers */
{
case rop3_D & rop3_not(rop3_T): tile_case(gx_no_color_index, 0);
case rop3_D | rop3_T: tile_case(gx_no_color_index, 1);
case rop3_D & rop3_T: tile_case(0, gx_no_color_index);
case rop3_D | rop3_not(rop3_T): tile_case(1, gx_no_color_index);
default: ;
}
#undef tile_case
fit_fill(dev, x, y, width, height);
/* Source is not used; sdata et al may be garbage. */
sdata = mdev->base; /* arbitrary, as long as all */
/* accesses are valid */
sourcex = x; /* guarantee no source skew */
sraster = 0;
break;
default: /* rop_usage_[D]ST */
fit_copy(dev, sdata, sourcex, sraster, id, x, y, width, height);
}
}
#ifdef DEBUG
if_debug1('b', "final rop=0x%x\n", rop);
#endif
/* Set up transfer parameters. */
line_count = height;
srow = sdata;
drow = scan_line_base(mdev, y);
traster = textures->raster;
ty = y + phase_y;
/* Loop over scan lines. */
for ( ; line_count-- > 0; drow += draster, srow += sraster, ++ty )
{ int sx = sourcex;
int dx = x;
int w = width;
const byte *trow =
textures->data + (ty % textures->rep_height) * traster;
int xoff = x_offset(phase_x, ty, textures);
int nw;
/* Loop over (norizontal) copies of the tile. */
for ( ; w > 0; sx += nw, dx += nw, w -= nw )
{ int dbit = dx & 7;
int sbit = sx & 7;
int sskew = sbit - dbit;
int tx = (dx + xoff) % textures->rep_width;
int tbit = tx & 7;
int tskew = tbit - dbit;
int left = nw = min(w, textures->size.x - tx);
byte lmask = 0xff >> dbit;
byte rmask = 0xff << (~(dbit + nw - 1) & 7);
byte mask = lmask;
int nx = 8 - dbit;
byte *dptr = drow + (dx >> 3);
const byte *sptr = srow + (sx >> 3);
const byte *tptr = trow + (tx >> 3);
if ( sskew < 0 )
--sptr, sskew += 8;
if ( tskew < 0 )
--tptr, tskew += 8;
for ( ; left > 0;
left -= nx, mask = 0xff, nx = 8,
++dptr, ++sptr, ++tptr
)
{ byte dbyte = *dptr;
#define fetch1(ptr, skew)\
(skew ? (ptr[0] << skew) + (ptr[1] >> (8 - skew)) : *ptr)
byte sbyte = fetch1(sptr, sskew);
byte tbyte = fetch1(tptr, tskew);
#undef fetch1
byte result =
(*rop_proc_table[rop])(dbyte, sbyte, tbyte);
if ( left <= nx )
mask &= rmask;
*dptr = (mask == 0xff ? result :
(result & mask) | (dbyte & ~mask));
}
}
}
#ifdef DEBUG
if ( gs_debug_c('B') )
debug_dump_bitmap(scan_line_base(mdev, y), mdev->raster,
height, "final dest bits");
#endif
return 0;
}
/* ---------------- Fake RasterOp for 2- and 4-bit devices ---------------- */
int
mem_gray_strip_copy_rop(gx_device *dev,
const byte *sdata, int sourcex, uint sraster, gx_bitmap_id id,
const gx_color_index *scolors,
const gx_strip_bitmap *textures, const gx_color_index *tcolors,
int x, int y, int width, int height,
int phase_x, int phase_y, gs_logical_operation_t lop)
{ gx_color_index scolors2[2];
const gx_color_index *real_scolors = scolors;
gx_color_index tcolors2[2];
const gx_color_index *real_tcolors = tcolors;
gx_strip_bitmap texture2;
const gx_strip_bitmap *real_texture = textures;
long tdata;
int depth = dev->color_info.depth;
int log2_depth = depth >> 1; /* works for 2, 4 */
gx_color_index max_pixel = (1 << depth) - 1;
int code;
#ifdef DEBUG
if ( gs_debug_c('b') )
trace_copy_rop("mem_gray_strip_copy_rop",
dev, sdata, sourcex, sraster,
id, scolors, textures, tcolors,
x, y, width, height, phase_x, phase_y, lop);
#endif
if ( scolors )
{ /* We can't handle "real" source colors. */
if ( (scolors[0] | scolors[1]) & ~max_pixel )
return_error(gs_error_rangecheck);
scolors2[0] = scolors[0] & 1;
scolors2[1] = scolors[1] & 1;
real_scolors = scolors2;
}
if ( textures )
{ texture2 = *textures;
texture2.size.x <<= log2_depth;
texture2.rep_width <<= log2_depth;
texture2.shift <<= log2_depth;
texture2.rep_shift <<= log2_depth;
real_texture = &texture2;
}
if ( tcolors )
{ /* We can't handle monobit textures. */
if ( tcolors[0] != tcolors[1] )
return_error(gs_error_rangecheck);
/* For polybit textures with colors other than */
/* all 0s or all 1s, fabricate the data. */
if ( tcolors[0] != 0 && tcolors[0] != max_pixel )
{ real_tcolors = 0;
*(byte *)&tdata = (byte)tcolors[0] << (8 - depth);
texture2.data = (byte *)&tdata;
texture2.raster = align_bitmap_mod;
texture2.size.x = texture2.rep_width = depth;
texture2.size.y = texture2.rep_height = 1;
texture2.id = gx_no_bitmap_id;
texture2.shift = texture2.rep_shift = 0;
real_texture = &texture2;
}
else
{ tcolors2[0] = tcolors2[1] = tcolors[0] & 1;
real_tcolors = tcolors2;
}
}
dev->width <<= log2_depth;
code = mem_mono_strip_copy_rop(dev, sdata,
(real_scolors == NULL ? sourcex << log2_depth : sourcex),
sraster, id, real_scolors, real_texture, real_tcolors,
x << log2_depth, y, width << log2_depth, height,
phase_x << log2_depth, phase_y, lop);
dev->width >>= log2_depth;
return code;
}
/* ---------------- RasterOp with 8-bit gray / 24-bit RGB ---------------- */
int
mem_gray8_rgb24_strip_copy_rop(gx_device *dev,
const byte *sdata, int sourcex, uint sraster, gx_bitmap_id id,
const gx_color_index *scolors,
const gx_strip_bitmap *textures, const gx_color_index *tcolors,
int x, int y, int width, int height,
int phase_x, int phase_y, gs_logical_operation_t lop)
{ gs_rop3_t rop = lop_rop(lop);
gx_color_index const_source = gx_no_color_index;
gx_color_index const_texture = gx_no_color_index;
uint draster = mdev->raster;
int line_count;
byte *drow;
int depth = dev->color_info.depth;
int bpp = depth >> 3; /* bytes per pixel, 1 or 3 */
gx_color_index all_ones = ((gx_color_index)1 << depth) - 1;
gx_color_index strans =
(lop & lop_S_transparent ? all_ones : gx_no_color_index);
gx_color_index ttrans =
(lop & lop_T_transparent ? all_ones : gx_no_color_index);
/* Check for constant source. */
if ( scolors != 0 && scolors[0] == scolors[1] )
{ /* Constant source */
const_source = scolors[0];
if ( const_source == 0 )
rop = rop3_know_S_0(rop);
else if ( const_source == all_ones )
rop = rop3_know_S_1(rop);
}
else if ( !rop3_uses_S(rop) )
const_source = 0; /* arbitrary */
/* Check for constant texture. */
if ( tcolors != 0 && tcolors[0] == tcolors[1] )
{ /* Constant texture */
const_texture = tcolors[0];
if ( const_texture == 0 )
rop = rop3_know_T_0(rop);
else if ( const_texture == all_ones )
rop = rop3_know_T_1(rop);
}
else if ( !rop3_uses_T(rop) )
const_texture = 0; /* arbitrary */
/* Adjust coordinates to be in bounds. */
if ( const_source == gx_no_color_index )
{ fit_copy(dev, sdata, sourcex, sraster, id,
x, y, width, height);
}
else
{ fit_fill(dev, x, y, width, height);
}
/* Set up transfer parameters. */
line_count = height;
drow = scan_line_base(mdev, y) + x * bpp;
/*
* There are 18 cases depending on whether each of the source and
* texture is constant, 1-bit, or multi-bit, and on whether the
* depth is 8 or 24 bits. We divide first according to constant
* vs. non-constant, and then according to 1- vs. multi-bit, and
* finally according to pixel depth. This minimizes source code,
* but not necessarily time, since we do some of the divisions
* within 1 or 2 levels of loop.
*/
#define dbit(base, i) ((base)[(i) >> 3] & (0x80 >> ((i) & 7)))
/* 8-bit */
#define cbit8(base, i, colors)\
(dbit(base, i) ? (byte)colors[1] : (byte)colors[0])
#define rop_body_8()\
if ( s_pixel == strans || /* So = 0, s_tr = 1 */\
t_pixel == ttrans /* Po = 0, p_tr = 1 */\
)\
continue;\
*dptr = (*rop_proc_table[rop])(*dptr, s_pixel, t_pixel)
/* 24-bit */
#define get24(ptr)\
(((gx_color_index)(ptr)[0] << 16) | ((gx_color_index)(ptr)[1] << 8) | (ptr)[2])
#define put24(ptr, pixel)\
(ptr)[0] = (byte)((pixel) >> 16),\
(ptr)[1] = (byte)((uint)(pixel) >> 8),\
(ptr)[2] = (byte)(pixel)
#define cbit24(base, i, colors)\
(dbit(base, i) ? colors[1] : colors[0])
#define rop_body_24()\
if ( s_pixel == strans || /* So = 0, s_tr = 1 */\
t_pixel == ttrans /* Po = 0, p_tr = 1 */\
)\
continue;\
{ gx_color_index d_pixel = get24(dptr);\
d_pixel = (*rop_proc_table[rop])(d_pixel, s_pixel, t_pixel);\
put24(dptr, d_pixel);\
}
if ( const_texture != gx_no_color_index ) /**** Constant texture ****/
{
if ( const_source != gx_no_color_index ) /**** Constant source & texture ****/
{
for ( ; line_count-- > 0; drow += draster )
{ byte *dptr = drow;
int left = width;
if ( bpp == 1 ) /**** 8-bit destination ****/
#define s_pixel (byte)const_source
#define t_pixel (byte)const_texture
for ( ; left > 0; ++dptr, --left )
{ rop_body_8();
}
#undef s_pixel
#undef t_pixel
else /**** 24-bit destination ****/
#define s_pixel const_source
#define t_pixel const_texture
for ( ; left > 0; dptr += 3, --left )
{ rop_body_24();
}
#undef s_pixel
#undef t_pixel
}
}
else /**** Data source, const texture ****/
{ const byte *srow = sdata;
for ( ; line_count-- > 0; drow += draster, srow += sraster )
{ byte *dptr = drow;
int left = width;
if ( scolors ) /**** 1-bit source ****/
{ int sx = sourcex;
if ( bpp == 1 ) /**** 8-bit destination ****/
#define t_pixel (byte)const_texture
for ( ; left > 0; ++dptr, ++sx, --left )
{ byte s_pixel = cbit8(srow, sx, scolors);
rop_body_8();
}
#undef t_pixel
else /**** 24-bit destination ****/
#define t_pixel const_texture
for ( ; left > 0; dptr += 3, ++sx, --left )
{ bits32 s_pixel = cbit24(srow, sx, scolors);
rop_body_24();
}
#undef t_pixel
}
else if ( bpp == 1) /**** 8-bit source & dest ****/
{ const byte *sptr = srow + sourcex;
#define t_pixel (byte)const_texture
for ( ; left > 0; ++dptr, ++sptr, --left )
{ byte s_pixel = *sptr;
rop_body_8();
}
#undef t_pixel
}
else /**** 24-bit source & dest ****/
{ const byte *sptr = srow + sourcex * 3;
#define t_pixel const_texture
for ( ; left > 0; dptr += 3, sptr += 3, --left )
{ bits32 s_pixel = get24(sptr);
rop_body_24();
}
#undef t_pixel
}
}
}
}
else if ( const_source != gx_no_color_index ) /**** Const source, data texture ****/
{ uint traster = textures->raster;
int ty = y + phase_y;
for ( ; line_count-- > 0; drow += draster, ++ty )
{ /* Loop over copies of the tile. */
int dx = x, w = width, nw;
byte *dptr = drow;
const byte *trow =
textures->data + (ty % textures->size.y) * traster;
int xoff = x_offset(phase_x, ty, textures);
for ( ; w > 0; dx += nw, w -= nw )
{ int tx = (dx + xoff) % textures->rep_width;
int left = nw = min(w, textures->size.x - tx);
const byte *tptr = trow;
if ( tcolors ) /**** 1-bit texture ****/
{ if ( bpp == 1 ) /**** 8-bit dest ****/
#define s_pixel (byte)const_source
for ( ; left > 0; ++dptr, ++tx, --left )
{ byte t_pixel = cbit8(tptr, tx, tcolors);
rop_body_8();
}
#undef s_pixel
else /**** 24-bit dest ****/
#define s_pixel const_source
for ( ; left > 0; dptr += 3, ++tx, --left )
{ bits32 t_pixel = cbit24(tptr, tx, tcolors);
rop_body_24();
}
#undef s_pixel
}
else if ( bpp == 1 ) /**** 8-bit T & D ****/
{ tptr += tx;
#define s_pixel (byte)const_source
for ( ; left > 0; ++dptr, ++tptr, --left )
{ byte t_pixel = *tptr;
rop_body_8();
}
#undef s_pixel
}
else /**** 24-bit T & D ****/
{ tptr += tx * 3;
#define s_pixel const_source
for ( ; left > 0; dptr += 3, tptr += 3, --left )
{ bits32 t_pixel = get24(tptr);
rop_body_24();
}
#undef s_pixel
}
}
}
}
else /**** Data source & texture ****/
{
uint traster = textures->raster;
int ty = y + phase_y;
const byte *srow = sdata;
/* Loop over scan lines. */
for ( ; line_count-- > 0; drow += draster, srow += sraster, ++ty )
{ /* Loop over copies of the tile. */
int sx = sourcex;
int dx = x;
int w = width;
int nw;
byte *dptr = drow;
const byte *trow =
textures->data + (ty % textures->size.y) * traster;
int xoff = x_offset(phase_x, ty, textures);
for ( ; w > 0; dx += nw, w -= nw )
{ /* Loop over individual pixels. */
int tx = (dx + xoff) % textures->rep_width;
int left = nw = min(w, textures->size.x - tx);
const byte *tptr = trow;
/*
* For maximum speed, we should split this loop
* into 7 cases depending on source & texture
* depth: (1,1), (1,8), (1,24), (8,1), (8,8),
* (24,1), (24,24). But since we expect these
* cases to be relatively uncommon, we just
* divide on the destination depth.
*/
if ( bpp == 1 ) /**** 8-bit destination ****/
{ const byte *sptr = srow + sx;
tptr += tx;
for ( ; left > 0; ++dptr, ++sptr, ++tptr, ++sx, ++tx, --left )
{ byte s_pixel =
(scolors ? cbit8(srow, sx, scolors) : *sptr);
byte t_pixel =
(tcolors ? cbit8(tptr, tx, tcolors) : *tptr);
rop_body_8();
}
}
else /**** 24-bit destination ****/
{ const byte *sptr = srow + sx * 3;
tptr += tx * 3;
for ( ; left > 0; dptr += 3, sptr += 3, tptr += 3, ++sx, ++tx, --left )
{ bits32 s_pixel =
(scolors ? cbit24(srow, sx, scolors) :
get24(sptr));
bits32 t_pixel =
(tcolors ? cbit24(tptr, tx, tcolors) :
get24(tptr));
rop_body_24();
}
}
}
}
}
#undef rop_body_8
#undef rop_body_24
#undef dbit
#undef cbit8
#undef cbit24
return 0;
}
/* ---------------- Default copy_rop implementations ---------------- */
#undef mdev
int
gx_real_default_copy_rop(gx_device *dev,
const byte *sdata, int sourcex, uint sraster, gx_bitmap_id id,
const gx_color_index *scolors,
const gx_tile_bitmap *texture, const gx_color_index *tcolors,
int x, int y, int width, int height,
int phase_x, int phase_y, gs_logical_operation_t lop)
{ const gx_strip_bitmap *textures;
gx_strip_bitmap tiles;
if ( texture == 0 )
textures = 0;
else
{ *(gx_tile_bitmap *)&tiles = *texture;
tiles.rep_shift = tiles.shift = 0;
textures = &tiles;
}
return (*dev_proc(dev, strip_copy_rop))
(dev, sdata, sourcex, sraster, id, scolors, textures, tcolors,
x, y, width, height, phase_x, phase_y, lop);
}
int
gx_real_default_strip_copy_rop(gx_device *dev,
const byte *sdata, int sourcex, uint sraster, gx_bitmap_id id,
const gx_color_index *scolors,
const gx_strip_bitmap *textures, const gx_color_index *tcolors,
int x, int y, int width, int height,
int phase_x, int phase_y, gs_logical_operation_t lop)
{ /*
* The default implementation uses get_bits to read out the
* pixels, the memory device implementation to do the operation,
* and copy_color to write the pixels back.
*/
int depth = dev->color_info.depth;
const gx_device_memory *mdproto = gdev_mem_device_for_bits(depth);
gx_device_memory mdev;
uint draster = gx_device_raster(dev, true);
bool uses_d = rop3_uses_D(gs_transparent_rop(lop));
byte *row;
int code;
int py;
#ifdef DEBUG
if ( gs_debug_c('b') )
trace_copy_rop("gx_default_strip_copy_rop",
dev, sdata, sourcex, sraster,
id, scolors, textures, tcolors,
x, y, width, height, phase_x, phase_y, lop);
#endif
if ( mdproto == 0 )
return_error(gs_error_rangecheck);
if ( sdata == 0 )
{ fit_fill(dev, x, y, width, height);
}
else
{ fit_copy(dev, sdata, sourcex, sraster, id, x, y, width, height);
}
gs_make_mem_device(&mdev, mdproto, 0, -1, dev);
mdev.width = width;
mdev.height = 1;
mdev.bitmap_memory = &gs_memory_default;
code = (*dev_proc(&mdev, open_device))((gx_device *)&mdev);
if ( code < 0 )
return code;
row = gs_malloc(1, draster, "copy_rop buffer");
if ( row == 0 )
{ (*dev_proc(&mdev, close_device))((gx_device *)&mdev);
return_error(gs_error_VMerror);
}
for ( py = y; py < y + height; ++py )
{ byte *data;
if ( uses_d )
{ code = (*dev_proc(dev, get_bits))(dev, py, row, &data);
if ( code < 0 )
break;
code = (*dev_proc(&mdev, copy_color))((gx_device *)&mdev,
data, x, draster, gx_no_bitmap_id,
0, 0, width, 1);
if ( code < 0 )
return code;
}
code = (*dev_proc(&mdev, strip_copy_rop))((gx_device *)&mdev,
sdata + (py - y) * sraster, sourcex, sraster,
gx_no_bitmap_id, scolors, textures, tcolors,
0, 0, width, 1, phase_x + x, phase_y + py,
lop);
if ( code < 0 )
break;
code = (*dev_proc(&mdev, get_bits))((gx_device *)&mdev, 0, row, &data);
if ( code < 0 )
break;
code = (*dev_proc(dev, copy_color))(dev,
data, 0, draster, gx_no_bitmap_id,
x, py, width, 1);
if ( code < 0 )
break;
}
gs_free(row, 1, draster, "copy_rop buffer");
(*dev_proc(&mdev, close_device))((gx_device *)&mdev);
return code;
}
int
gx_forward_copy_rop(gx_device *dev,
const byte *sdata, int sourcex, uint sraster, gx_bitmap_id id,
const gx_color_index *scolors,
const gx_tile_bitmap *texture, const gx_color_index *tcolors,
int x, int y, int width, int height,
int phase_x, int phase_y, gs_logical_operation_t lop)
{ gx_device *tdev = ((gx_device_forward *)dev)->target;
dev_proc_copy_rop((*proc));
if ( tdev == 0 )
tdev = dev, proc = gx_default_copy_rop;
else
proc = dev_proc(tdev, copy_rop);
return (*proc)(tdev, sdata, sourcex, sraster, id, scolors,
texture, tcolors, x, y, width, height,
phase_x, phase_y, lop);
}
int
gx_forward_strip_copy_rop(gx_device *dev,
const byte *sdata, int sourcex, uint sraster, gx_bitmap_id id,
const gx_color_index *scolors,
const gx_strip_bitmap *textures, const gx_color_index *tcolors,
int x, int y, int width, int height,
int phase_x, int phase_y, gs_logical_operation_t lop)
{ gx_device *tdev = ((gx_device_forward *)dev)->target;
dev_proc_strip_copy_rop((*proc));
if ( tdev == 0 )
tdev = dev, proc = gx_default_strip_copy_rop;
else
proc = dev_proc(tdev, strip_copy_rop);
return (*proc)(tdev, sdata, sourcex, sraster, id, scolors,
textures, tcolors, x, y, width, height,
phase_x, phase_y, lop);
}
int
gx_copy_rop_unaligned(gx_device *dev,
const byte *sdata, int sourcex, uint sraster, gx_bitmap_id id,
const gx_color_index *scolors,
const gx_tile_bitmap *texture, const gx_color_index *tcolors,
int x, int y, int width, int height,
int phase_x, int phase_y, gs_logical_operation_t lop)
{ const gx_strip_bitmap *textures;
gx_strip_bitmap tiles;
if ( texture == 0 )
textures = 0;
else
{ *(gx_tile_bitmap *)&tiles = *texture;
tiles.rep_shift = tiles.shift = 0;
textures = &tiles;
}
return gx_strip_copy_rop_unaligned
(dev, sdata, sourcex, sraster, id, scolors, textures, tcolors,
x, y, width, height, phase_x, phase_y, lop);
}
int
gx_strip_copy_rop_unaligned(gx_device *dev,
const byte *sdata, int sourcex, uint sraster, gx_bitmap_id id,
const gx_color_index *scolors,
const gx_strip_bitmap *textures, const gx_color_index *tcolors,
int x, int y, int width, int height,
int phase_x, int phase_y, gs_logical_operation_t lop)
{ dev_proc_strip_copy_rop((*copy_rop)) = dev_proc(dev, strip_copy_rop);
int depth = (scolors == 0 ? dev->color_info.depth : 1);
int step = sraster & (align_bitmap_mod - 1);
/* Adjust the origin. */
if ( sdata != 0 )
{ uint offset =
(uint)(sdata - (const byte *)0) & (align_bitmap_mod - 1);
/* See copy_color above re the following statement. */
if ( depth == 24 )
offset += (offset % 3) *
(align_bitmap_mod * (3 - (align_bitmap_mod % 3)));
sdata -= offset;
sourcex += (offset << 3) / depth;
}
/* Adjust the raster. */
if ( !step || sdata == 0 ||
(scolors != 0 && scolors[0] == scolors[1])
)
{ /* No adjustment needed. */
return (*copy_rop)(dev, sdata, sourcex, sraster, id, scolors,
textures, tcolors, x, y, width, height,
phase_x, phase_y, lop);
}
/* Do the transfer one scan line at a time. */
{ const byte *p = sdata;
int d = sourcex;
int dstep = (step << 3) / depth;
int code = 0;
int i;
for ( i = 0; i < height && code >= 0;
++i, p += sraster - step, d += dstep
)
code = (*copy_rop)(dev, p, d, sraster, gx_no_bitmap_id, scolors,
textures, tcolors, x, y + i, width, 1,
phase_x, phase_y, lop);
return code;
}
}
/* ---------------- RasterOp texture device ---------------- */
public_st_device_rop_texture();
/* Device for clipping with a region. */
private dev_proc_fill_rectangle(rop_texture_fill_rectangle);
private dev_proc_copy_mono(rop_texture_copy_mono);
private dev_proc_copy_color(rop_texture_copy_color);
/* The device descriptor. */
private const gx_device_rop_texture far_data gs_rop_texture_device =
{ std_device_std_body(gx_device_rop_texture, 0, "rop source",
0, 0, 1, 1),
{ NULL, /* open_device */
gx_forward_get_initial_matrix,
NULL, /* default_sync_output */
NULL, /* output_page */
NULL, /* close_device */
gx_forward_map_rgb_color,
gx_forward_map_color_rgb,
rop_texture_fill_rectangle,
NULL, /* tile_rectangle */
rop_texture_copy_mono,
rop_texture_copy_color,
NULL, /* draw_line */
NULL, /* get_bits */
gx_forward_get_params,
gx_forward_put_params,
gx_forward_map_cmyk_color,
gx_forward_get_xfont_procs,
gx_forward_get_xfont_device,
gx_forward_map_rgb_alpha_color,
gx_forward_get_page_device,
NULL, /* get_alpha_bits (no alpha) */
gx_no_copy_alpha, /* shouldn't be called */
gx_forward_get_band,
gx_no_copy_rop, /* shouldn't be called */
NULL, /* fill_path */
NULL, /* stroke_path */
NULL, /* fill_mask */
NULL, /* fill_trapezoid */
NULL, /* fill_parallelogram */
NULL, /* fill_triangle */
NULL, /* draw_thin_line */
NULL, /* begin_image */
NULL, /* image_data */
NULL, /* end_image */
NULL, /* strip_tile_rectangle */
NULL, /* strip_copy_rop */
gx_forward_get_clipping_box
},
0, /* target */
lop_default, /* log_op */
NULL /* texture */
};
#define rtdev ((gx_device_rop_texture *)dev)
/* Initialize a RasterOp source device. */
void
gx_make_rop_texture_device(gx_device_rop_texture *dev, gx_device *target,
gs_logical_operation_t log_op, const gx_device_color *texture)
{ *dev = gs_rop_texture_device;
/* Drawing operations are defaulted, non-drawing are forwarded. */
gx_device_fill_in_procs((gx_device *)dev);
dev->color_info = target->color_info;
dev->target = target;
dev->log_op = log_op;
dev->texture = texture;
}
/* Fill a rectangle */
private int
rop_texture_fill_rectangle(gx_device *dev, int x, int y, int w, int h,
gx_color_index color)
{ gx_rop_source_t source;
source.sdata = NULL;
source.sourcex = 0;
source.sraster = 0;
source.id = gx_no_bitmap_id;
source.scolors[0] = source.scolors[1] = color;
source.use_scolors = true;
return gx_device_color_fill_rectangle(rtdev->texture,
x, y, w, h, rtdev->target,
rtdev->log_op, &source);
}
/* Copy a monochrome rectangle */
private int
rop_texture_copy_mono(gx_device *dev,
const byte *data, int sourcex, int raster, gx_bitmap_id id,
int x, int y, int w, int h,
gx_color_index color0, gx_color_index color1)
{ gx_rop_source_t source;
gs_logical_operation_t lop = rtdev->log_op;
source.sdata = data;
source.sourcex = sourcex;
source.sraster = raster;
source.id = id;
source.scolors[0] = color0;
source.scolors[1] = color1;
source.use_scolors = true;
/* Adjust the logical operation per transparent colors. */
if ( color0 == gx_no_color_index )
lop = rop3_use_D_when_S_0(lop);
else if ( color1 == gx_no_color_index )
lop = rop3_use_D_when_S_1(lop);
return gx_device_color_fill_rectangle(rtdev->texture,
x, y, w, h, rtdev->target,
lop, &source);
}
/* Copy a color rectangle */
private int
rop_texture_copy_color(gx_device *dev,
const byte *data, int sourcex, int raster, gx_bitmap_id id,
int x, int y, int w, int h)
{ gx_rop_source_t source;
source.sdata = data;
source.sourcex = sourcex;
source.sraster = raster;
source.id = id;
source.scolors[0] = source.scolors[1] = gx_no_color_index;
source.use_scolors = true;
return gx_device_color_fill_rectangle(rtdev->texture,
x, y, w, h, rtdev->target,
rtdev->log_op, &source);
}
/* ---------------- Internal routines ---------------- */
/* Compute the effective RasterOp for the 1-bit case, */
/* taking transparency into account. */
private gs_rop3_t
gs_transparent_rop(gs_logical_operation_t lop)
{ gs_rop3_t rop = lop_rop(lop);
/*
* The algorithm for computing an effective RasterOp is presented,
* albeit obfuscated, in the H-P PCL5 technical documentation.
* Define So ("source opaque") and Po ("pattern opaque") as masks
* that have 1-bits precisely where the source or pattern
* respectively are not white (transparent).
* One applies the original RasterOp to compute an intermediate
* result R, and then computes the final result as
* (R & M) | (D & ~M) where M depends on transparencies as follows:
* s_tr p_tr M
* 0 0 1
* 0 1 ~So | Po (? Po ?)
* 1 0 So
* 1 1 So & Po
* The s_tr = 0, p_tr = 1 case seems wrong, but it's clearly
* specified that way in the "PCL 5 Color Technical Reference
* Manual."
*
* In the 1-bit case, So = ~S and Po = ~P, so we can apply the
* above table directly.
*/
#define So rop3_not(rop3_S)
#define Po rop3_not(rop3_T)
#ifdef TRANSPARENCY_PER_H_P
# define MPo (rop3_uses_S(rop) ? rop3_not(So) | Po : Po)
#else
# define MPo Po
#endif
/*
* If the operation doesn't use S or T, we must disregard the
* corresponding transparency flag.
*/
#define source_transparent ((lop & lop_S_transparent) && rop3_uses_S(rop))
#define pattern_transparent ((lop & lop_T_transparent) && rop3_uses_T(rop))
gs_rop3_t mask =
(source_transparent ?
(pattern_transparent ? So & Po : So) :
(pattern_transparent ? MPo : rop3_1));
#undef MPo
return (rop & mask) | (rop3_D & ~mask);
}
| 31.508152 | 85 | 0.636165 | [
"render"
] |
c5b2ebc2a76193e9edfcd8588fc13c0ad687ba35 | 12,154 | c | C | drivers/input/keyboard/stmpe-keypad.c | tuxafgmur/OLD_Dhollmen_Kernel | 90ed4e2e3e6321de246fa193705ae40ede4e2d8e | [
"BSD-Source-Code"
] | null | null | null | drivers/input/keyboard/stmpe-keypad.c | tuxafgmur/OLD_Dhollmen_Kernel | 90ed4e2e3e6321de246fa193705ae40ede4e2d8e | [
"BSD-Source-Code"
] | null | null | null | drivers/input/keyboard/stmpe-keypad.c | tuxafgmur/OLD_Dhollmen_Kernel | 90ed4e2e3e6321de246fa193705ae40ede4e2d8e | [
"BSD-Source-Code"
] | null | null | null | /*
* Copyright (C) ST-Ericsson SA 2010
*
* License Terms: GNU General Public License, version 2
* Author: Rabin Vincent <rabin.vincent@stericsson.com> for ST-Ericsson
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/input/matrix_keypad.h>
#include <linux/mfd/stmpe.h>
/* These are at the same addresses in all STMPE variants */
#define STMPE_KPC_COL 0x60
#define STMPE_KPC_ROW_MSB 0x61
#define STMPE_KPC_ROW_LSB 0x62
#define STMPE_KPC_CTRL_MSB 0x63
#define STMPE_KPC_CTRL_LSB 0x64
#define STMPE_KPC_COMBI_KEY_0 0x65
#define STMPE_KPC_COMBI_KEY_1 0x66
#define STMPE_KPC_COMBI_KEY_2 0x67
#define STMPE_KPC_DATA_BYTE0 0x68
#define STMPE_KPC_DATA_BYTE1 0x69
#define STMPE_KPC_DATA_BYTE2 0x6a
#define STMPE_KPC_DATA_BYTE3 0x6b
#define STMPE_KPC_DATA_BYTE4 0x6c
#define STMPE_KPC_CTRL_LSB_SCAN (0x1 << 0)
#define STMPE_KPC_CTRL_LSB_DEBOUNCE (0x7f << 1)
#define STMPE_KPC_CTRL_MSB_SCAN_COUNT (0xf << 4)
#define STMPE_KPC_COL_MSB_COLS 0xff
#define STMPE_KPC_ROW_MSB_ROWS 0xff
#define STMPE_KPC_DATA_UP (0x1 << 7)
#define STMPE_KPC_DATA_ROW (0xf << 3)
#define STMPE_KPC_DATA_COL (0x7 << 0)
#define STMPE_KPC_DATA_NOKEY_MASK 0x78
#define STMPE_KEYPAD_MAX_DEBOUNCE 127
#define STMPE_KEYPAD_MAX_SCAN_COUNT 15
#define STMPE_KEYPAD_MAX_ROWS 8
#define STMPE_KEYPAD_MAX_COLS 10
#define STMPE_KEYPAD_ROW_SHIFT 3
#define STMPE_KEYPAD_KEYMAP_SIZE \
(STMPE_KEYPAD_MAX_ROWS * STMPE_KEYPAD_MAX_COLS)
#define STMPE_KEYPAD_MAX_COMBI_KEY 3
#define STMPE_KEYPAD_MAX_DATA_BYTE 5
struct stmpe_keypad_reg {
unsigned int col_msb;
unsigned int col_lsb;
unsigned int row_msb;
unsigned int row_lsb;
unsigned int ctrl_msb;
unsigned int ctrl_lsb;
unsigned int combi_key[STMPE_KEYPAD_MAX_COMBI_KEY];
unsigned int data_byte[STMPE_KEYPAD_MAX_DATA_BYTE];
};
static struct stmpe_keypad_reg stmpe_kpc = {
.col_msb = STMPE_KPC_COL,
.col_lsb = STMPE_KPC_COL,
.row_msb = STMPE_KPC_ROW_MSB,
.row_lsb = STMPE_KPC_ROW_LSB,
.ctrl_msb = STMPE_KPC_CTRL_MSB,
.ctrl_lsb = STMPE_KPC_CTRL_LSB,
.combi_key = {
STMPE_KPC_COMBI_KEY_0,
STMPE_KPC_COMBI_KEY_1,
STMPE_KPC_COMBI_KEY_2,
},
.data_byte = {
STMPE_KPC_DATA_BYTE0,
STMPE_KPC_DATA_BYTE1,
STMPE_KPC_DATA_BYTE2,
STMPE_KPC_DATA_BYTE3,
STMPE_KPC_DATA_BYTE4,
},
};
/* These are at the different addresses in all STMPE1801 variants */
#define STMPE1801_KPC_COL_MSB 0x31
#define STMPE1801_KPC_COL_LSB 0x32
#define STMPE1801_KPC_ROW 0x30
#define STMPE1801_KPC_CTRL_MSB 0x33
#define STMPE1801_KPC_CTRL_LSB 0x35
#define STMPE1801_KPC_COMBI_KEY_0 0x37
#define STMPE1801_KPC_COMBI_KEY_1 0x38
#define STMPE1801_KPC_COMBI_KEY_2 0x39
#define STMPE1801_KPC_DATA_BYTE0 0x3a
#define STMPE1801_KPC_DATA_BYTE1 0x3b
#define STMPE1801_KPC_DATA_BYTE2 0x3c
#define STMPE1801_KPC_DATA_BYTE3 0x3d
#define STMPE1801_KPC_DATA_BYTE4 0x3e
static struct stmpe_keypad_reg stmpe1801_kpc = {
.col_msb = STMPE1801_KPC_COL_MSB,
.col_lsb = STMPE1801_KPC_COL_LSB,
.row_msb = STMPE1801_KPC_ROW,
.row_lsb = STMPE1801_KPC_ROW,
.ctrl_msb = STMPE1801_KPC_CTRL_MSB,
.ctrl_lsb = STMPE1801_KPC_CTRL_LSB,
.combi_key = {
STMPE1801_KPC_COMBI_KEY_0,
STMPE1801_KPC_COMBI_KEY_1,
STMPE1801_KPC_COMBI_KEY_2,
},
.data_byte = {
STMPE1801_KPC_DATA_BYTE0,
STMPE1801_KPC_DATA_BYTE1,
STMPE1801_KPC_DATA_BYTE2,
STMPE1801_KPC_DATA_BYTE3,
STMPE1801_KPC_DATA_BYTE4,
},
};
/**
* struct stmpe_keypad_variant - model-specific attributes
* @auto_increment: whether the KPC_DATA_BYTE register address
* auto-increments on multiple read
* @num_data: number of data bytes
* @num_normal_data: number of normal keys' data bytes
* @max_cols: maximum number of columns supported
* @max_rows: maximum number of rows supported
* @col_gpios: bitmask of gpios which can be used for columns
* @row_gpios: bitmask of gpios which can be used for rows
*/
struct stmpe_keypad_variant {
bool auto_increment;
int num_data;
int num_normal_data;
int max_cols;
int max_rows;
unsigned int col_gpios;
unsigned int row_gpios;
struct stmpe_keypad_reg *reg;
};
static const struct stmpe_keypad_variant stmpe_keypad_variants[] = {
[STMPE1601] = {
.auto_increment = true,
.num_data = 5,
.num_normal_data = 3,
.max_cols = 8,
.max_rows = 8,
.col_gpios = 0x000ff, /* GPIO 0 - 7 */
.row_gpios = 0x0ff00, /* GPIO 8 - 15 */
.reg = &stmpe_kpc,
},
[STMPE1801] = {
.auto_increment = true,
.num_data = 5,
.num_normal_data = 3,
.max_cols = 10,
.max_rows = 8,
.col_gpios = 0x000ff, /* GPIO 0 - 7 */
.row_gpios = 0x3ff00, /* GPIO 8 - 17 */
.reg = &stmpe1801_kpc,
},
[STMPE2401] = {
.auto_increment = false,
.num_data = 3,
.num_normal_data = 2,
.max_cols = 8,
.max_rows = 12,
.col_gpios = 0x0000ff, /* GPIO 0 - 7*/
.row_gpios = 0x1fef00, /* GPIO 8-14, 16-20 */
.reg = &stmpe_kpc,
},
[STMPE2403] = {
.auto_increment = true,
.num_data = 5,
.num_normal_data = 3,
.max_cols = 8,
.max_rows = 12,
.col_gpios = 0x0000ff, /* GPIO 0 - 7*/
.row_gpios = 0x1fef00, /* GPIO 8-14, 16-20 */
.reg = &stmpe_kpc,
},
};
struct stmpe_keypad {
struct stmpe *stmpe;
struct input_dev *input;
const struct stmpe_keypad_variant *variant;
const struct stmpe_keypad_platform_data *plat;
unsigned int rows;
unsigned int cols;
unsigned short keymap[STMPE_KEYPAD_KEYMAP_SIZE];
};
static int stmpe_keypad_read_data(struct stmpe_keypad *keypad, u8 *data)
{
const struct stmpe_keypad_variant *variant = keypad->variant;
struct stmpe *stmpe = keypad->stmpe;
int ret;
int i;
if (variant->auto_increment)
return stmpe_block_read(stmpe, variant->reg->data_byte[0],
variant->num_data, data);
for (i = 0; i < variant->num_data; i++) {
ret = stmpe_reg_read(stmpe, variant->reg->data_byte[i]);
if (ret < 0)
return ret;
data[i] = ret;
}
return 0;
}
static irqreturn_t stmpe_keypad_irq(int irq, void *dev)
{
struct stmpe_keypad *keypad = dev;
struct input_dev *input = keypad->input;
const struct stmpe_keypad_variant *variant = keypad->variant;
u8 fifo[variant->num_data];
int ret;
int i;
ret = stmpe_keypad_read_data(keypad, fifo);
if (ret < 0)
return IRQ_NONE;
for (i = 0; i < variant->num_normal_data; i++) {
u8 data = fifo[i];
int row = (data & STMPE_KPC_DATA_ROW) >> 3;
int col = data & STMPE_KPC_DATA_COL;
int code = MATRIX_SCAN_CODE(row, col, STMPE_KEYPAD_ROW_SHIFT);
bool up = data & STMPE_KPC_DATA_UP;
if ((data & STMPE_KPC_DATA_NOKEY_MASK)
== STMPE_KPC_DATA_NOKEY_MASK)
continue;
input_event(input, EV_MSC, MSC_SCAN, code);
input_report_key(input, keypad->keymap[code], !up);
input_sync(input);
}
return IRQ_HANDLED;
}
static int __devinit stmpe_keypad_altfunc_init(struct stmpe_keypad *keypad)
{
const struct stmpe_keypad_variant *variant = keypad->variant;
unsigned int col_gpios = variant->col_gpios;
unsigned int row_gpios = variant->row_gpios;
struct stmpe *stmpe = keypad->stmpe;
unsigned int pins = 0;
int i;
/*
* Figure out which pins need to be set to the keypad alternate
* function.
*
* {cols,rows}_gpios are bitmasks of which pins on the chip can be used
* for the keypad.
*
* keypad->{cols,rows} are a bitmask of which pins (of the ones useable
* for the keypad) are used on the board.
*/
for (i = 0; i < variant->max_cols; i++) {
int num = __ffs(col_gpios);
if (keypad->cols & (1 << i))
pins |= 1 << num;
col_gpios &= ~(1 << num);
}
for (i = 0; i < variant->max_rows; i++) {
int num = __ffs(row_gpios);
if (keypad->rows & (1 << i))
pins |= 1 << num;
row_gpios &= ~(1 << num);
}
return stmpe_set_altfunc(stmpe, pins, STMPE_BLOCK_KEYPAD);
}
static int __devinit stmpe_keypad_chip_init(struct stmpe_keypad *keypad)
{
const struct stmpe_keypad_platform_data *plat = keypad->plat;
const struct stmpe_keypad_variant *variant = keypad->variant;
struct stmpe *stmpe = keypad->stmpe;
int ret;
if (plat->debounce_ms > STMPE_KEYPAD_MAX_DEBOUNCE)
return -EINVAL;
if (plat->scan_count > STMPE_KEYPAD_MAX_SCAN_COUNT)
return -EINVAL;
ret = stmpe_enable(stmpe, STMPE_BLOCK_KEYPAD);
if (ret < 0)
return ret;
ret = stmpe_keypad_altfunc_init(keypad);
if (ret < 0)
return ret;
ret = stmpe_reg_write(stmpe, variant->reg->col_lsb, keypad->cols);
if (ret < 0)
return ret;
if (variant->max_cols > 8) {
ret = stmpe_set_bits(stmpe, variant->reg->col_msb,
STMPE_KPC_COL_MSB_COLS,
keypad->cols >> 8);
if (ret < 0)
return ret;
}
ret = stmpe_reg_write(stmpe, variant->reg->row_lsb, keypad->rows);
if (ret < 0)
return ret;
if (variant->max_rows > 8) {
ret = stmpe_set_bits(stmpe, variant->reg->row_msb,
STMPE_KPC_ROW_MSB_ROWS,
keypad->rows >> 8);
if (ret < 0)
return ret;
}
ret = stmpe_set_bits(stmpe, variant->reg->ctrl_msb,
STMPE_KPC_CTRL_MSB_SCAN_COUNT,
plat->scan_count << 4);
if (ret < 0)
return ret;
return stmpe_set_bits(stmpe, variant->reg->ctrl_lsb,
STMPE_KPC_CTRL_LSB_SCAN |
STMPE_KPC_CTRL_LSB_DEBOUNCE,
STMPE_KPC_CTRL_LSB_SCAN |
(plat->debounce_ms << 1));
}
static int __devinit stmpe_keypad_probe(struct platform_device *pdev)
{
struct stmpe *stmpe = dev_get_drvdata(pdev->dev.parent);
struct stmpe_keypad_platform_data *plat;
struct stmpe_keypad *keypad;
struct input_dev *input;
int ret;
int irq;
int i;
plat = stmpe->pdata->keypad;
if (!plat)
return -ENODEV;
irq = platform_get_irq(pdev, 0);
if (irq < 0)
return irq;
keypad = kzalloc(sizeof(struct stmpe_keypad), GFP_KERNEL);
if (!keypad)
return -ENOMEM;
input = input_allocate_device();
if (!input) {
ret = -ENOMEM;
goto out_freekeypad;
}
input->name = "STMPE keypad";
input->id.bustype = BUS_I2C;
input->dev.parent = &pdev->dev;
input_set_capability(input, EV_MSC, MSC_SCAN);
__set_bit(EV_KEY, input->evbit);
if (!plat->no_autorepeat)
__set_bit(EV_REP, input->evbit);
input->keycode = keypad->keymap;
input->keycodesize = sizeof(keypad->keymap[0]);
input->keycodemax = ARRAY_SIZE(keypad->keymap);
matrix_keypad_build_keymap(plat->keymap_data, STMPE_KEYPAD_ROW_SHIFT,
input->keycode, input->keybit);
for (i = 0; i < plat->keymap_data->keymap_size; i++) {
unsigned int key = plat->keymap_data->keymap[i];
keypad->cols |= 1 << KEY_COL(key);
keypad->rows |= 1 << KEY_ROW(key);
}
keypad->stmpe = stmpe;
keypad->plat = plat;
keypad->input = input;
keypad->variant = &stmpe_keypad_variants[stmpe->partnum];
ret = stmpe_keypad_chip_init(keypad);
if (ret < 0)
goto out_freeinput;
ret = input_register_device(input);
if (ret) {
dev_err(&pdev->dev,
"unable to register input device: %d\n", ret);
goto out_freeinput;
}
ret = request_threaded_irq(irq, NULL, stmpe_keypad_irq, IRQF_ONESHOT,
"stmpe-keypad", keypad);
if (ret) {
dev_err(&pdev->dev, "unable to get irq: %d\n", ret);
goto out_unregisterinput;
}
platform_set_drvdata(pdev, keypad);
return 0;
out_unregisterinput:
input_unregister_device(input);
input = NULL;
out_freeinput:
input_free_device(input);
out_freekeypad:
kfree(keypad);
return ret;
}
static int __devexit stmpe_keypad_remove(struct platform_device *pdev)
{
struct stmpe_keypad *keypad = platform_get_drvdata(pdev);
struct stmpe *stmpe = keypad->stmpe;
int irq = platform_get_irq(pdev, 0);
stmpe_disable(stmpe, STMPE_BLOCK_KEYPAD);
free_irq(irq, keypad);
input_unregister_device(keypad->input);
platform_set_drvdata(pdev, NULL);
kfree(keypad);
return 0;
}
static struct platform_driver stmpe_keypad_driver = {
.driver.name = "stmpe-keypad",
.driver.owner = THIS_MODULE,
.probe = stmpe_keypad_probe,
.remove = __devexit_p(stmpe_keypad_remove),
};
static int __init stmpe_keypad_init(void)
{
return platform_driver_register(&stmpe_keypad_driver);
}
module_init(stmpe_keypad_init);
static void __exit stmpe_keypad_exit(void)
{
platform_driver_unregister(&stmpe_keypad_driver);
}
module_exit(stmpe_keypad_exit);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("STMPExxxx keypad driver");
MODULE_AUTHOR("Rabin Vincent <rabin.vincent@stericsson.com>");
| 25.268191 | 75 | 0.726181 | [
"model"
] |
c5b389f9153c0248acbce526f8b64067ec1c27b9 | 6,002 | c | C | myInitializeMatrix.c | Kautenja/comp7300-lab3 | c003920391b88a8554f9c553e0c33338257234ba | [
"MIT"
] | 1 | 2020-11-13T18:30:29.000Z | 2020-11-13T18:30:29.000Z | myInitializeMatrix.c | Kautenja/comp7300-lab3 | c003920391b88a8554f9c553e0c33338257234ba | [
"MIT"
] | null | null | null | myInitializeMatrix.c | Kautenja/comp7300-lab3 | c003920391b88a8554f9c553e0c33338257234ba | [
"MIT"
] | 1 | 2020-08-05T22:59:38.000Z | 2020-08-05T22:59:38.000Z | /********************************************************************\
* Laboratory Exercise COMP 7300/06 *
* Author: Saad Biaz *
* Date : October 25, 2017 *
* File : myInitializeMatrix.c for Lab3 *
\*******************************************************************/
/********************************************************************\
* Global system headers *
\********************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/select.h>
#include <sys/time.h>
/******************************************************************\
* Global data types *
\******************************************************************/
typedef double Timestamp;
typedef double Period;
/**********************************************************************\
* Global definitions *
\**********************************************************************/
#define DIMENSION 40000
#define PRINTDIM 7 // Dimension of matrix to display
#define NUMBER_TESTS 7//12
#define ROWWISE 0
#define COLUMNWISE 1
/**********************************************************************\
* Global data *
\**********************************************************************/
Timestamp StartTime;
double Matrix[DIMENSION][DIMENSION];
Period Max[2],Min[2],Avg[2];
unsigned int MaxIndex[2],MinIndex[2];
/**********************************************************************\
* Function prototypes *
\**********************************************************************/
Timestamp Now();
void InitializeMatrixRowwise();
void InitializeMatrixColumnwise();
void DisplayUpperQuandrant(unsigned dimension);
int main(){
int choice;
Timestamp StartInitialize;
Period testTime;
unsigned int i,j,nbreTests;
// Global Initialization
StartTime = Now();
nbreTests = NUMBER_TESTS;
Max[ROWWISE] = 0.00;
Max[COLUMNWISE] = 0.00;
Min[ROWWISE] = 10000.00;
Min[COLUMNWISE] = 10000.00;
Avg[ROWWISE] = 0.00;
Avg[COLUMNWISE] = 0.00;
// Matrix Initialization
printf("Be patient! Initializing............\n\n");
for (j = 1; j <= nbreTests; j++){
for (i = ROWWISE; i <= COLUMNWISE; i++){
StartInitialize = Now();
if (i == ROWWISE)
InitializeMatrixRowwise();
else
InitializeMatrixColumnwise();
testTime = Now() - StartInitialize;
if (testTime > Max[i]){
Max[i] = testTime;
MaxIndex[i] = j;
}
if (testTime < Min[i]){
Min[i] = testTime;
MinIndex[i] = j;
}
Avg[i] += testTime;
}
printf("%3d: Rowwise Max[%2d]=%7.3f Min[%2d]=%7.3f Avg=%7.3f\n",
j,MaxIndex[ROWWISE],Max[ROWWISE],MinIndex[ROWWISE],
Min[ROWWISE],Avg[ROWWISE]/j);
printf(" Columnwise Max[%2d]=%7.3f Min[%2d]=%7.3f Avg=%7.3f\n\n",
MaxIndex[COLUMNWISE],Max[COLUMNWISE],MinIndex[COLUMNWISE],
Min[COLUMNWISE],Avg[COLUMNWISE]/j);
DisplayUpperQuandrant(PRINTDIM);
}
}
/*********************************************************************\
* Input : None *
* Output : Returns the current system time *
\*********************************************************************/
Timestamp Now(){
struct timeval tv_CurrentTime;
gettimeofday(&tv_CurrentTime,NULL);
return( (Timestamp) tv_CurrentTime.tv_sec + (Timestamp) tv_CurrentTime.tv_usec / 1000000.0-StartTime);
}
/*********************************************************************\
* Input : None *
* Output : None *
* Function : Initialize a matrix rowwise *
\*********************************************************************/
void InitializeMatrixRowwise(){
int i,j;
double x;
x = 0.0;
for (i = 0; i < DIMENSION; i++){
for (j = 0; j < DIMENSION; j++){
if (i >= j){
Matrix[i][j] = x;
x += 1.0;
} else
Matrix[i][j] = 1.0;
}
}
}
/*********************************************************************\
* Input : None *
* Output : None *
* Function : Initialize a matrix columnwise *
\*********************************************************************/
void InitializeMatrixColumnwise(){
int i,j;
double x;
x = 0.0;
for (j = 0; j < DIMENSION; j++){
for (i = 0; i < DIMENSION; i++){
if (i >= j){
Matrix[i][j] = x;
x += 1.0;
} else
Matrix[i][j] = 1.0;
}
}
}
/*********************************************************************\
* Input : dimension (first n lines/columns) *
* Output : None *
* Function : Initialize a matrix columnwise *
\*********************************************************************/
void DisplayUpperQuandrant(unsigned dimension){
int i,j;
printf("\n\n********************************************************\n");
for (i = 0; i < dimension; i++){
printf("[");
for (j = 0; j < dimension; j++){
printf("%8.1f ",Matrix[i][j]);
}
printf("]\n");
}
printf("***************************************************************\n\n");
}
| 35.099415 | 104 | 0.341053 | [
"3d"
] |
c5b789ea428d8dcf6a2fe8d01428bb313a2691e0 | 6,169 | h | C | PWGLF/NUCLEX/Hypernuclei/Hyp2Body/AliAnalysisTaskHypTritEventTree.h | BongHwi/AliPhysics | fd7a9537d2cb5fdd0d32c352a37cae8a09996e37 | [
"BSD-3-Clause"
] | 2 | 2017-08-01T11:53:34.000Z | 2018-12-19T13:20:54.000Z | PWGLF/NUCLEX/Hypernuclei/Hyp2Body/AliAnalysisTaskHypTritEventTree.h | BongHwi/AliPhysics | fd7a9537d2cb5fdd0d32c352a37cae8a09996e37 | [
"BSD-3-Clause"
] | null | null | null | PWGLF/NUCLEX/Hypernuclei/Hyp2Body/AliAnalysisTaskHypTritEventTree.h | BongHwi/AliPhysics | fd7a9537d2cb5fdd0d32c352a37cae8a09996e37 | [
"BSD-3-Clause"
] | null | null | null | /// \class AliAnalysisTaskHypTritEventTree
/// \brief Hypertriton Analysis in two particle decay channel
///
/// Hypertriton candidates are identified using the on-the-fly V0 finder.
/// Events with Hypertriton candidates are filled in a tree
/// using the AliReducedHypTritEvent class.
///
/// \author Lukas Kreis <lukas.kreis@cern.ch>, GSI
/// \date Sep 1, 2016
#ifndef ALIANALYSISTASKHYPTRITEVENTTREE_H
#define ALIANALYSISTASKHYPTRITEVENTTREE_H
class TH1F;
class TH2F;
class AliESDEvent;
class AliESDpid;
class AliESDtrackCuts;
class AliESDv0;
class AliESDVertex;
class AliESDInputHandler;
class AliESDtrack;
class AliReducedHypTritEvent;
#include "AliReducedHypTritEvent.h"
#include "AliAnalysisTaskSE.h"
#include "AliStack.h"
#include "AliEventCuts.h"
#include "AliTRDonlineTrackMatching.h"
#include "AliCDBManager.h"
#include "AliGeomManager.h"
class AliAnalysisTaskHypTritEventTree : public AliAnalysisTaskSE {
public:
AliAnalysisTaskHypTritEventTree();
AliAnalysisTaskHypTritEventTree(const char *name);
virtual ~AliAnalysisTaskHypTritEventTree();
virtual void UserCreateOutputObjects();
virtual void UserExec(Option_t *option);
virtual void Terminate(const Option_t*);
void SetPidQa(Bool_t pidQa = kTRUE) {fPidQa = pidQa;};
void SetUseAnalysisTrackSelection(Bool_t trkSel = kTRUE) {fUseAnalysisTrkSel = trkSel;};
void SelectPIDcheckOnly(Bool_t pidch = kFALSE) {fPIDCheckOnly = pidch;};
void SetPeriod(Int_t period = 2015) {fPeriod = period;};
void SetTriggerMask(UInt_t triggerMask = AliVEvent::kINT7) {fTriggerMask = triggerMask;};
void SetBetheSplines(Bool_t betheSplines = kTRUE ) {fBetheSplines = betheSplines;};
void SetParamsHe(Double_t params[6]) { for(Int_t i=0; i < 6; i++) fBetheParamsHe[i] = params[i];};
void SetParamsT(Double_t params[6]) { for(Int_t i=0; i < 6; i++) fBetheParamsT[i] = params[i];};
private:
AliESDInputHandler *fInputHandler; //!<! Input handler
AliESDpid *fPID; //!<! ESD pid
AliESDEvent *fESDevent; //!<! ESD event
AliReducedHypTritEvent *fReducedEvent; //< Reduced event containing he3 and pi
AliReducedHypTritEvent *fReducedEventMCGen; //< Reduced MC event containing he3 and pi
AliStack *fStack; //!<! MC stack
AliESDv0 *fV0; //!<! ESD v0
TClonesArray *fV0Array; //< Array of v0s in a event
TH2F *fHistdEdx; //< Histogram of Tpc dEdx for pid qa
TH2F *fHistdEdxV0; //< Histogram of Tpc dEdx for pid qa
TH1F *fHistNumEvents; //< Histogram of number of events
TH1F *fHistTrigger; //< Histogram of trigger for all events
TH1F *fHistV0; //< Histogram of trigger for all V0s
TH1F *fHistMcGen; //< Histogram of generated Hypertriton
TH1F *fHistMcRec; //< Histogram of reconstructed Hypertriton
TTree *fTree; //< Tree containing reduced events
TTree *fTreeMCGen; //< Tree containing reduced MC events
TObjArray *fMCGenRecArray; //< Array used for matching reconstructed MC with generated MC particles in one event
TList *fHistogramList; //< List of histograms
Int_t fMCGenRec[40]; //!<! Array containing MC labels of generated hypertriton 40 per event
TLorentzVector fMomPos; //!<! Momentum of positive decay product
TLorentzVector fMomNeg; //!<! Momentum of negative decay product
TVector3 fPrimaryVertex; //!<! Vector of primary vertex of collision
Double_t fMagneticField; //!<! Magnetic field
Int_t fNV0Cand; //!<! Number of V0 candidates in a event
Int_t fMcGenRecCounter; //!<! Number of matched particles in one MC event
Bool_t fPidQa; //< Flag for activating pid qa histogram
Bool_t fUseAnalysisTrkSel; //< Flag to select track for analysis (true) or for good plot (false)
Bool_t fPIDCheckOnly; //< Flag to reduce the task only to PID check for Hypertriton daughters
Bool_t fMCtrue; //< Flag for activating MC analysis (set automatically)
AliEventCuts fEventCuts; //< 2015 event cuts as advised by PDG (AliEventCuts)
UInt_t fTriggerMask; //< Triggermask for event cuts
Int_t fPeriod; //< Data period for centrality selector
Bool_t fBetheSplines; //< Switch between built in BetheSplines and personal Fit
Double_t fBetheParamsHe[6]; //< Bethe Aleph He3 Parameter + TPC sigma: [0][i] he3 [2][i] t
Double_t fBetheParamsT[6]; //< Bethe Aleph He3 Parameter + TPC sigma: [0][i] he3 [2][i] t
Int_t fYear;
void MCStackLoop(AliMCEvent* mcEvent);
void SetMomentum(Int_t charge, Bool_t v0Charge);
void CalculateV0(const AliESDtrack& trackN, const AliESDtrack& trackP, AliPID::EParticleType typeNeg, AliPID::EParticleType typePos, AliMCEvent* mcEvent);
Bool_t TriggerSelection(AliMCEvent* mcEvent);
Double_t GetInvPtDevFromBC(Int_t b, Int_t c);
void SetMultiplicity();
Double_t Bethe(const AliESDtrack& track, Double_t mass, Int_t charge, Double_t* params);
Bool_t McCuts(const AliReducedHypTritV0& v0, const AliReducedHypTritTrack& he, const AliReducedHypTritTrack& pi);
Double_t GeoLength(const AliESDtrack& track);
void SetBetheBlochParams(Int_t runNumber);
Double_t TRDtrack(AliESDtrack* esdTrack ,AliReducedHypTritTrack* reducedHe);
Double_t SetTRDtrack(const AliESDtrack* esdTrack, AliReducedHypTritTrack* reducedTrack);
AliAnalysisTaskHypTritEventTree(const AliAnalysisTaskHypTritEventTree&);
AliAnalysisTaskHypTritEventTree &operator=(const AliAnalysisTaskHypTritEventTree&);
/// \cond CLASSIMP
ClassDef(AliAnalysisTaskHypTritEventTree, 7);
/// \endcond
};
#endif
| 56.59633 | 156 | 0.66283 | [
"vector"
] |
c5b8185f77c0d628e19ea927106f96e9a4f3d881 | 3,072 | h | C | Modules/Filtering/Statistics/include/otbPeriodicSampler.h | xcorail/OTB | 092a93654c3b5d009e420f450fe9b675f737cdca | [
"Apache-2.0"
] | null | null | null | Modules/Filtering/Statistics/include/otbPeriodicSampler.h | xcorail/OTB | 092a93654c3b5d009e420f450fe9b675f737cdca | [
"Apache-2.0"
] | null | null | null | Modules/Filtering/Statistics/include/otbPeriodicSampler.h | xcorail/OTB | 092a93654c3b5d009e420f450fe9b675f737cdca | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef otbPeriodicSampler_h
#define otbPeriodicSampler_h
#include "otbSamplerBase.h"
namespace otb
{
/**
* \class PeriodicSampler
*
* \brief Periodic sampler for iteration loops
*
* This class allows doing periodic sampling during an iteration loop.
*
* \ingroup OTBStatistics
*/
class ITK_EXPORT PeriodicSampler : public SamplerBase
{
public:
typedef PeriodicSampler Self;
typedef SamplerBase Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Internal parameters, only contains an offset to shift the periodic
* sampling
*/
typedef struct Parameter
{
/** Offset that shifts the whole periodic sampling
* (disabled if jitter is used) */
unsigned long Offset;
/** Maximum jitter to introduce (0 means no jitter) */
unsigned long MaxJitter;
/** Maximum buffer size for internal jitter values */
unsigned long MaxBufferSize;
bool operator!=(const struct Parameter & param) const;
} ParameterType;
/** Method for creation through the object factory. */
itkNewMacro(Self);
/** Runtime information support. */
itkTypeMacro(PeriodicSampler,SamplerBase);
/** Setter for internal parameters */
void SetParameters(const ParameterType ¶m)
{
if (m_Parameters != param)
{
this->Modified();
m_Parameters = param;
}
}
/** Getter for internal parameters */
ParameterType GetParameters()
{
return m_Parameters;
}
/**
* Method that resets the internal state of the sampler
*/
void Reset(void) override;
/**
* Method to call during iteration, returns true if the sample is selected,
* and false otherwise.
*/
bool TakeSample(void);
protected:
/** Constructor */
PeriodicSampler();
/** Destructor */
~PeriodicSampler() override {}
private:
// Not implemented
PeriodicSampler(const Self&);
void operator=(const Self&);
/** Internal parameters for the sampler */
ParameterType m_Parameters;
/** Internal width for jitter */
double m_JitterSize;
/** Internal current offset value
* (either fixed, or reset each time a sample is taken)*/
double m_OffsetValue;
/** jitter offsets computed up to MaxBufferSize */
std::vector<double> m_JitterValues;
};
} // namespace otb
#endif
| 24.576 | 77 | 0.693034 | [
"object",
"vector"
] |
c5b94f8979a17e61b436489f1e8578d439461e95 | 6,311 | h | C | System/Library/PrivateFrameworks/ContactsFoundation.framework/CNObservable.h | lechium/tvOS142Headers | c7696f6d760e4822f61b9f2c2adcd18749700fda | [
"MIT"
] | 1 | 2020-11-11T06:05:23.000Z | 2020-11-11T06:05:23.000Z | System/Library/PrivateFrameworks/ContactsFoundation.framework/CNObservable.h | lechium/tvOS142Headers | c7696f6d760e4822f61b9f2c2adcd18749700fda | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/ContactsFoundation.framework/CNObservable.h | lechium/tvOS142Headers | c7696f6d760e4822f61b9f2c2adcd18749700fda | [
"MIT"
] | null | null | null | /*
* This header is generated by classdump-dyld 1.5
* on Tuesday, November 10, 2020 at 10:11:45 PM Mountain Standard Time
* Operating System: Version 14.2 (Build 18K57)
* Image Source: /System/Library/PrivateFrameworks/ContactsFoundation.framework/ContactsFoundation
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
#import <ContactsFoundation/ContactsFoundation-Structs.h>
#import <libobjc.A.dylib/CNObservable.h>
@protocol CNObservable <NSObject>
@required
-(id)subscribe:(id)arg1;
@end
@class NSString;
@interface CNObservable : NSObject <CNObservable> {
NSString* _pipelineDescription;
}
@property (nonatomic,readonly) NSString * debugPipelineDescription;
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
@property (copy,readonly) NSString * description;
@property (copy,readonly) NSString * debugDescription;
+(id)os_log_protocol;
+(id)observableWithBlock:(/*^block*/id)arg1 ;
+(id)os_log;
+(id)observableWithInitialState:(id)arg1 condition:(/*^block*/id)arg2 nextState:(/*^block*/id)arg3 resultSelector:(/*^block*/id)arg4 scheduler:(id)arg5 ;
+(id)observableWithInitialState:(id)arg1 condition:(/*^block*/id)arg2 nextState:(/*^block*/id)arg3 resultSelector:(/*^block*/id)arg4 delay:(/*^block*/id)arg5 scheduler:(id)arg6 ;
+(id)observableWithInitialState:(id)arg1 condition:(/*^block*/id)arg2 nextState:(/*^block*/id)arg3 resultSelector:(/*^block*/id)arg4 ;
+(id)observableWithScannerResultsOfType:(unsigned long long)arg1 inString:(id)arg2 ;
+(id)observableWithFuture:(id)arg1 schedulerProvider:(id)arg2 ;
+(id)observableWithFutures:(id)arg1 schedulerProvider:(id)arg2 ;
+(id)merge:(id)arg1 schedulerProvider:(id)arg2 ;
+(id)observableWithRange:(NSRange)arg1 scheduler:(id)arg2 ;
+(id)observableWithResults:(id)arg1 scheduler:(id)arg2 ;
+(id)timerWithDelay:(double)arg1 scheduler:(id)arg2 ;
+(id)combineLatest:(id)arg1 schedulerProvider:(id)arg2 ;
+(id)combineLatest:(id)arg1 resultScheduler:(id)arg2 schedulerProvider:(id)arg3 ;
+(id)emptyObservable;
+(id)observableWithResults:(id)arg1 ;
+(id)amb:(id)arg1 ;
+(id)observableWithResult:(id)arg1 ;
+(id)observableWithTimeInterval:(double)arg1 scheduler:(id)arg2 ;
+(id)concatenate:(id)arg1 ;
+(id)observableWithFuture:(id)arg1 ;
+(id)observableWithFutures:(id)arg1 ;
+(id)observableWithRange:(NSRange)arg1 ;
+(id)observableWithRange:(NSRange)arg1 interval:(double)arg2 scheduler:(id)arg3 ;
+(id)observableWithResults:(id)arg1 interval:(double)arg2 scheduler:(id)arg3 ;
+(id)observableWithError:(id)arg1 ;
+(id)neverObservable;
+(id)timerWithDelay:(double)arg1 ;
+(id)combineLatest:(id)arg1 ;
+(id)forkJoin:(id)arg1 scheduler:(id)arg2 ;
+(id)merge:(id)arg1 ;
+(id)progressiveForkJoin:(id)arg1 scheduler:(id)arg2 ;
+(id)observableWithRelativeTimestamps:(id)arg1 schedulerProvider:(id)arg2 ;
+(void)sendNextTimestampFromQueue:(id)arg1 toObserver:(id)arg2 untilCanceled:(id)arg3 scheduler:(id)arg4 ;
+(id)observableWithAbsoluteTimestamps:(id)arg1 schedulerProvider:(id)arg2 ;
+(id)observableWithScannerResultsInString:(id)arg1 ;
+(id)binderTypeForResultType:(unsigned long long)arg1 ;
+(id)scannerResultsInString:(id)arg1 ;
+(id)asyncScannerResultsInString:(id)arg1 ;
+(id)observableWithEmailAddressesInString:(id)arg1 ;
+(id)observableOnNotificationCenter:(id)arg1 withName:(id)arg2 object:(id)arg3 ;
+(id)observableOnDefaultNotificationCenterWithName:(id)arg1 object:(id)arg2 ;
+(id)observableOnDarwinNotificationCenterWithName:(id)arg1 ;
+(id)observableForKeyPath:(id)arg1 ofObject:(id)arg2 withOptions:(unsigned long long)arg3 ;
-(id)timeInterval;
-(void)enumerateObjectsUsingBlock:(/*^block*/id)arg1 ;
-(id)publish;
-(id)toArray;
-(id)flatMap:(/*^block*/id)arg1 ;
-(id)subscribe:(id)arg1 ;
-(id)doOnTerminate:(/*^block*/id)arg1 ;
-(id)map:(/*^block*/id)arg1 ;
-(id)pipelineDescription:(/*^block*/id)arg1 ;
-(id)observeOn:(id)arg1 ;
-(id)flatMap:(/*^block*/id)arg1 schedulerProvider:(id)arg2 ;
-(id)pipelineDescriptionWithOperation:(/*^block*/id)arg1 onObservable:(id)arg2 ;
-(id)filter:(/*^block*/id)arg1 ;
-(id)take:(unsigned long long)arg1 ;
-(id)onEmpty:(id)arg1 ;
-(id)buffer:(unsigned long long)arg1 interval:(double)arg2 scheduler:(id)arg3 ;
-(id)bufferWithInterval:(double)arg1 scheduler:(id)arg2 ;
-(id)concatMap:(/*^block*/id)arg1 schedulerProvider:(id)arg2 ;
-(id)subscribeOn:(id)arg1 ;
-(id)doOnCompletion:(/*^block*/id)arg1 ;
-(id)doOnError:(/*^block*/id)arg1 ;
-(NSString *)debugPipelineDescription;
-(id)onErrorHandler:(/*^block*/id)arg1 ;
-(id)sample:(double)arg1 scheduler:(id)arg2 ;
-(id)sampleWithObservable:(id)arg1 ;
-(id)scan:(/*^block*/id)arg1 seed:(id)arg2 ;
-(id)startWith:(id)arg1 scheduler:(id)arg2 ;
-(id)switchWithSchedulerProvider:(id)arg1 ;
-(id)switchMap:(/*^block*/id)arg1 schedulerProvider:(id)arg2 ;
-(id)throttle:(double)arg1 options:(unsigned long long)arg2 schedulerProvider:(id)arg3 ;
-(id)timeIntervalWithScheduler:(id)arg1 ;
-(id)allObjects:(id*)arg1 ;
-(id)ambWith:(id)arg1 ;
-(id)any:(/*^block*/id)arg1 ;
-(id)buffer:(unsigned long long)arg1 ;
-(id)buffer:(unsigned long long)arg1 interval:(double)arg2 ;
-(id)bufferWithInterval:(double)arg1 ;
-(id)concatMap:(/*^block*/id)arg1 ;
-(id)delay:(double)arg1 scheduler:(id)arg2 ;
-(id)delaySubscription:(double)arg1 scheduler:(id)arg2 ;
-(id)dematerialize;
-(id)distinct;
-(id)distinctUntilChanged;
-(id)doOnCancel:(/*^block*/id)arg1 ;
-(id)doOnNext:(/*^block*/id)arg1 ;
-(id)doOnSubscribe:(/*^block*/id)arg1 ;
-(id)ignoreElements;
-(id)materialize;
-(id)onError:(id)arg1 ;
-(id)sample:(double)arg1 ;
-(id)scan:(/*^block*/id)arg1 ;
-(id)skip:(unsigned long long)arg1 ;
-(id)skipLast:(unsigned long long)arg1 ;
-(id)skipUntil:(id)arg1 ;
-(id)startWith:(id)arg1 ;
-(id)switch;
-(id)switchMap:(/*^block*/id)arg1 ;
-(id)takeLast:(unsigned long long)arg1 ;
-(id)takeUntil:(id)arg1 ;
-(id)throttle:(double)arg1 schedulerProvider:(id)arg2 ;
-(id)throttleFirst:(double)arg1 scheduler:(id)arg2 ;
-(id)throttleFirstAndLast:(double)arg1 schedulerProvider:(id)arg2 ;
-(id)timeoutAfterDelay:(double)arg1 alternateObservable:(id)arg2 schedule:(id)arg3 ;
-(id)timestampWithScheduler:(id)arg1 ;
-(id)using:(/*^block*/id)arg1 ;
@end
| 43.826389 | 178 | 0.729995 | [
"object"
] |
c5bb7152b8eda073ef9dd8d5684c1e0e8ff18b94 | 1,381 | h | C | ADCL/include/ADCL_papi.h | open-mpi/otpo | 0fb56525fe62bba376041652d8c4319c56af1300 | [
"BSD-3-Clause-Open-MPI"
] | 4 | 2015-09-22T09:25:22.000Z | 2017-11-25T10:27:04.000Z | ADCL/include/ADCL_papi.h | open-mpi/otpo | 0fb56525fe62bba376041652d8c4319c56af1300 | [
"BSD-3-Clause-Open-MPI"
] | 5 | 2015-08-21T09:23:23.000Z | 2021-06-03T14:13:06.000Z | ADCL/include/ADCL_papi.h | open-mpi/otpo | 0fb56525fe62bba376041652d8c4319c56af1300 | [
"BSD-3-Clause-Open-MPI"
] | 2 | 2015-04-02T10:08:34.000Z | 2015-08-25T22:17:38.000Z | /*
* Copyright (c) 2006-2007 University of Houston. All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
#ifndef __ADCL_PAPI_H__
#define __ADCL_PAPI_H__
#include <stdio.h>
#include <stdlib.h>
#include "papi.h"
struct ADCL_papi_s{
int p_id; /* id of the object */
int p_findex; /* index of this object in the fortran array */
int p_num_events; /* number of events in the event set */
long_long p_time_stamp; /* starting stamp */
long_long p_exec_time; /* total execution time */
unsigned int *p_events; /* the Event set */
long_long *p_values; /* values of each event in the event set */
const PAPI_hw_info_t *p_hwinfo; /* Hardware Information */
};
typedef struct ADCL_papi_s ADCL_papi_t;
extern ADCL_array_t *ADCL_papi_farray;
int ADCL_papi_init ( void );
int ADCL_papi_create ( ADCL_papi_t **papi );
int ADCL_papi_free ( ADCL_papi_t **papi );
int ADCL_papi_enter ( ADCL_papi_t *papi );
int ADCL_papi_leave ( ADCL_papi_t *papi );
int ADCL_papi_print ( ADCL_papi_t *papi );
static int ADCL_handle_error (int code , char *code_name) {
char message[PAPI_MAX_STR_LEN];
printf("ERROR IN PAPI FUNCTION %s\n" , code_name);
PAPI_perror(code, message , PAPI_MAX_STR_LEN);
printf("PAPI ERROR %i: %s\n", code , message);
exit(1);
}
#endif
| 30.688889 | 76 | 0.679942 | [
"object"
] |
c5bc005b885094b7bffd3274c4e35de5238e5974 | 5,905 | h | C | Base/QTGUI/qSlicerApplication.h | TheInterventionCentre/NorMIT-Plan-App | 765ed9a5dccc1cc134b65ccabe93fc132baeb2ea | [
"MIT"
] | null | null | null | Base/QTGUI/qSlicerApplication.h | TheInterventionCentre/NorMIT-Plan-App | 765ed9a5dccc1cc134b65ccabe93fc132baeb2ea | [
"MIT"
] | null | null | null | Base/QTGUI/qSlicerApplication.h | TheInterventionCentre/NorMIT-Plan-App | 765ed9a5dccc1cc134b65ccabe93fc132baeb2ea | [
"MIT"
] | null | null | null | /*==============================================================================
Program: 3D Slicer
Copyright (c) Kitware Inc.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
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.
This file was originally developed by Jean-Christophe Fillion-Robin, Kitware Inc.
and was partially funded by NIH grant 3P41RR013218-12S1
==============================================================================*/
#ifndef __qSlicerApplication_h
#define __qSlicerApplication_h
// Qt includes
#include <QPalette>
// CTK includes
#include <ctkPimpl.h>
#include <ctkSettingsDialog.h>
// QTCORE includes
#include "qSlicerCoreApplication.h"
// QTGUI includes
#include "qSlicerBaseQTGUIExport.h"
class QMainWindow;
class qSlicerApplicationPrivate;
class qSlicerCommandOptions;
class qSlicerIOManager;
#ifdef Slicer_USE_PYTHONQT
class qSlicerPythonManager;
#endif
class qSlicerLayoutManager;
class qSlicerWidget;
class ctkErrorLogModel;
#ifdef Slicer_USE_QtTesting
class ctkQtTestingUtility;
#endif
// MRML includes
class vtkMRMLNode;
class Q_SLICER_BASE_QTGUI_EXPORT qSlicerApplication : public qSlicerCoreApplication
{
Q_OBJECT
public:
typedef qSlicerCoreApplication Superclass;
qSlicerApplication(int &argc, char **argv);
virtual ~qSlicerApplication();
/// Return a reference to the application singleton
static qSlicerApplication* application();
/// Avoid some crashes due to execeptions thrown during inside event handlers
/// (such as slots). When exceptions are thown from slots, Qt generates this message:
///
/// > Qt has caught an exception thrown from an event handler. Throwing
/// > exceptions from an event handler is not supported in Qt. You must
/// > reimplement QApplication::notify() and catch all exceptions there.
///
/// so we follow the pattern suggested here:
///
/// http://stackoverflow.com/questions/13878373/where-am-i-supposed-to-reimplement-qapplicationnotify-function
///
virtual bool notify(QObject * receiver, QEvent * event);
/// Get errorLogModel
Q_INVOKABLE ctkErrorLogModel* errorLogModel()const;
/// Get commandOptions
Q_INVOKABLE qSlicerCommandOptions* commandOptions()const;
/// Get IO Manager
Q_INVOKABLE qSlicerIOManager* ioManager();
#ifdef Slicer_USE_PYTHONQT
/// Get Python Manager
Q_INVOKABLE qSlicerPythonManager * pythonManager();
Q_INVOKABLE ctkPythonConsole * pythonConsole();
#endif
#ifdef Slicer_USE_QtTesting
/// Get test utility
Q_INVOKABLE ctkQtTestingUtility* testingUtility();
#endif
/// Set/Get layout manager
Q_INVOKABLE qSlicerLayoutManager* layoutManager()const;
Q_INVOKABLE void setLayoutManager(qSlicerLayoutManager* layoutManager);
/// Return a pointer on the main window of the application if any.
QMainWindow* mainWindow()const;
/// TODO
/// See http://doc.trolltech.com/4.6/qapplication.html#commitData
/// and http://doc.trolltech.com/4.6/qsessionmanager.html#allowsInteraction
//virtual void commitData(QSessionManager & manager);
/// Enable/Disable tooltips
void setToolTipsEnabled(bool enable);
/// Return the module name that is most suitable for editing the specified node.
QString nodeModule(vtkMRMLNode* node)const;
Q_INVOKABLE ctkSettingsDialog* settingsDialog()const;
/// Log application information.
///
/// This function will log the following
/// details:
/// - Session start time
/// - Slicer version
/// - Operating system
/// - Memory
/// - CPU
/// - Developer mode enabled
/// - Prefer executable CLI
/// - Additional module paths
///
/// \note Starting the application with `--application-information` will
/// also print the information to standard output.
///
/// \sa qSlicerCoreCommandOptions::displayApplicationInformation()
Q_INVOKABLE virtual void logApplicationInformation() const;
public slots:
/// Utility function that retrieve the best module for a node and trigger
/// its associated QAction which eventually opens the module.
/// \note qSlicerApplication is a temporary host for the function as it should be
/// moved into a DataManager where module can register new node
/// types/modules
void openNodeModule(vtkMRMLNode* node);
/// Popup a dialog asking the user if the application should be restarted.
/// If no \a reason is given, the text will default to ""Are you sure you want to restart?"
void confirmRestart(QString reason = QString());
#ifdef Slicer_BUILD_EXTENSIONMANAGER_SUPPORT
void openExtensionsManagerDialog();
#endif
/// Number of recent log files to keep. Older log files are deleted automatically.
int numberOfRecentLogFilesToKeep();
/// Paths of recent log files
QStringList recentLogFiles();
/// Path of the current log file
/// \sa recentLogFiles(), setupFileLogging()
QString currentLogFile()const;
protected:
/// Reimplemented from qSlicerCoreApplication
virtual void handlePreApplicationCommandLineArguments();
virtual void handleCommandLineArguments();
virtual void onSlicerApplicationLogicModified();
/// Set up file logging. Creates and sets new log file and deletes the oldest
/// one from the stored queue
void setupFileLogging();
private:
Q_DECLARE_PRIVATE(qSlicerApplication);
Q_DISABLE_COPY(qSlicerApplication);
};
/// Apply the Slicer palette to the \c palette
/// Note also that the palette parameter is passed by reference and will be
/// updated using the native paletter and applying Slicer specific properties.
void Q_SLICER_BASE_QTGUI_EXPORT qSlicerApplyPalette(QPalette& palette);
#endif
| 31.57754 | 112 | 0.737341 | [
"3d"
] |
c5c15d2d0d770ae4c12965ef90678919eea90850 | 30,814 | c | C | src/tools/clut/main.c | hanatos/vkdt | 12ea015ac05d388f5d7c5f33582723bc76654f30 | [
"BSD-2-Clause"
] | 76 | 2019-07-12T16:00:44.000Z | 2022-03-23T20:15:48.000Z | src/tools/clut/main.c | hanatos/vkdt | 12ea015ac05d388f5d7c5f33582723bc76654f30 | [
"BSD-2-Clause"
] | 28 | 2019-07-17T19:28:30.000Z | 2022-03-25T19:07:56.000Z | src/tools/clut/main.c | hanatos/vkdt | 12ea015ac05d388f5d7c5f33582723bc76654f30 | [
"BSD-2-Clause"
] | 15 | 2019-09-10T06:34:31.000Z | 2022-03-07T11:24:48.000Z | // this creates an input device transform (idt) lookup table for a given camera
// based on spectral sensitivity functions (ssf). works best with a high-res
// high-quality spectral upsampling table, create via
// `mkspectra 1024 /dev/null XYZ`. (note the lack of `-b`)
// #define USE_LEVMAR
#include "core/inpaint.h"
#include "core/half.h"
#include "core/clip.h"
#include "core/solve.h"
#include "q2t.h"
#include <strings.h>
#include "../../pipe/modules/i-raw/adobe_coeff.h"
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <math.h>
#include <string.h>
#include <assert.h>
#include <alloca.h>
#ifdef USE_LEVMAR
#include "levmar-2.6/levmar.h"
#endif
#define MIN(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a < _b ? _a : _b; })
#define MAX(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a > _b ? _a : _b; })
#define CLAMP(a,m,M) (MIN(MAX((a), (m)), (M)))
#define CIE_SAMPLES 95
#define CIE_LAMBDA_MIN 360.0
#define CIE_LAMBDA_MAX 830.0
#define CIE_FINE_SAMPLES 95
typedef struct header_t
{ // header of .lut files
uint32_t magic;
uint16_t version;
uint8_t channels;
uint8_t datatype;
uint32_t wd;
uint32_t ht;
}
header_t;
static int num_coeff = 6;
static uint32_t seed = 1337;
static const double srgb_to_xyz[] = {
0.412453, 0.357580, 0.180423,
0.212671, 0.715160, 0.072169,
0.019334, 0.119193, 0.950227
};
static const double xyz_to_rec2020[] = {
1.7166511880, -0.3556707838, -0.2533662814,
-0.6666843518, 1.6164812366, 0.0157685458,
0.0176398574, -0.0427706133, 0.9421031212
};
static const double rec2020_to_xyz[] = {
0.6369580483, 0.1446169036, 0.1688809752,
0.2627002120, 0.6779980715, 0.0593017165,
0.0000000000, 0.0280726930, 1.0609850577,
};
static inline double
xrand()
{ // Algorithm "xor" from p. 4 of Marsaglia, "Xorshift RNGs"
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
return seed / 4294967296.0;
}
// bilinear lookup
static inline void
fetch_coeff(
const double *xy, // cie xy chromaticities
const float *spectra, // loaded spectral coeffs, 4-strided
const int wd, // width of texture
const int ht, // height of texture
double *out) // bilinear lookup will end up here
{
out[0] = out[1] = out[2] = 0.0;
if(xy[0] < 0 || xy[1] < 0 || xy[0] > 1.0 || xy[1] > 1.0) return;
double tc[] = {xy[0], xy[1]};
tri2quad(tc+0, tc+1);
double xf = tc[0]*wd, yf = tc[1]*ht;
int x0 = (int)CLAMP(xf, 0, wd-1), y0 = (int)CLAMP(yf, 0, ht-1);
int x1 = (int)CLAMP(x0+1, 0, wd-1), y1 = (int)CLAMP(y0+1, 0, ht-1);
int dx = x1 - x0, dy = y1 - y0;
double u = xf - x0, v = yf - y0;
const float *c = spectra + 4*(y0*wd + x0);
out[0] = out[1] = out[2] = 0.0;
for(int k=0;k<3;k++) out[k] += (1.0-u)*(1.0-v)*c[k];
for(int k=0;k<3;k++) out[k] += ( u)*(1.0-v)*c[k + 4*dx];
for(int k=0;k<3;k++) out[k] += (1.0-u)*( v)*c[k + 4*wd*dy];
for(int k=0;k<3;k++) out[k] += ( u)*( v)*c[k + 4*(wd*dy+dx)];
}
// nearest neighbour lookup
static inline void
fetch_coeffi(
const double *xy,
const float *spectra,
const int wd,
const int ht,
double *out)
{
out[0] = out[1] = out[2] = 0.0;
if(xy[0] < 0 || xy[1] < 0 || xy[0] > 1.0 || xy[1] > 1.0) return;
double tc[] = {xy[0], xy[1]};
tri2quad(tc+0, tc+1);
int xi = (int)CLAMP(tc[0]*wd+0.5, 0, wd-1), yi = (int)CLAMP(tc[1]*ht+0.5, 0, ht-1);
const float *c = spectra + 4*(yi*wd + xi);
out[0] = c[0]; out[1] = c[1]; out[2] = c[2];
}
// sample a cubic b-spline around (0.5, 0.5, 0.5)
static inline void
sample_rgb(double *rgb, double delta, int clamp)
{
for(int k=0;k<3;k++)
{
rgb[k] = 0.5;
for(int i=0;i<3;i++)
rgb[k] += delta*(2.0*xrand()-1.0);
if(clamp) rgb[k] = CLAMP(rgb[k], 0.0, 1.0);
}
}
static inline double
normalise1(double *col)
{
const double b = col[0] + col[1] + col[2];
for(int k=0;k<3;k++) col[k] /= b;
return b;
}
static inline double
poly(const double *c, double lambda, int num)
{
double r = 0.0;
for(int i=0;i<num;i++)
r = r * lambda + c[i];
return r;
}
static inline double
sigmoid(double x)
{
return 0.5 * x / sqrt(1.0 + x * x) + 0.5;
}
static inline double
ddx_sigmoid(double x)
{
return 0.5 * pow(x*x+1.0, -3.0/2.0);
}
static inline double
eval_ref(
const double (*cfa_spec)[4],
const int channel,
const int cnt,
const double *cf)
{
double out = 0.0;
for(int i=0;i<cnt;i++)
{
double lambda = cfa_spec[i][0];
double s = sigmoid(poly(cf, lambda, 3));
double t = cfa_spec[i][1+channel];
out += s*t;
}
return out * (cfa_spec[cnt-1][0] - cfa_spec[0][0]) / (double) cnt;
}
static inline double
eval(
const double *cp, // spectrum with np coeffs, use normalised lambda (for optimiser)
const double *cf, // spectrum with nf coeffs, use lambda in nanometers
int np,
int nf)
{
double out = 0.0;
for (int i = 0; i < CIE_FINE_SAMPLES; ++i)
{
double lambda0 = (i+.5)/(double)CIE_FINE_SAMPLES;
double lambda1 = lambda0 * (CIE_LAMBDA_MAX - CIE_LAMBDA_MIN) + CIE_LAMBDA_MIN;
double s = sigmoid(poly(cf, lambda1, nf)); // from map, use real lambda
double t = sigmoid(poly(cp, lambda0, np)); // optimising this, use normalised for smaller values (assumption of hessian approx)
out += s * t;
}
return out * (CIE_LAMBDA_MAX - CIE_LAMBDA_MIN) / (double)CIE_FINE_SAMPLES;
}
static inline double
ddp_eval(
const double *cp, // parameters, cfa spectrum
const double *cf, // coefficients of data point
int np, // number of parameter coeffs
int nf, // number of data point coeffs
double *jac) // output: gradient dx/dp{0..np-1} (i.e. np elements)
{
double out = 0.0;
double ddp_poly[20];
double ddp_t[20];
for(int j=0;j<np;j++) jac[j] = 0.0;
for (int i = 0; i < CIE_FINE_SAMPLES; ++i)
{
double lambda0 = (i+.5)/(double)CIE_FINE_SAMPLES;
double lambda1 = lambda0 * (CIE_LAMBDA_MAX - CIE_LAMBDA_MIN) + CIE_LAMBDA_MIN;
double x = poly(cf, lambda1, nf); // from map, use real lambda
double y = poly(cp, lambda0, np); // optimising this, use normalised for smaller values (assumption of hessian approx)
double s = sigmoid(x);
double t = sigmoid(y);
double ddx_sig = ddx_sigmoid(y);
// ddp t = ddx_sigmoid(poly(cp, lambda0, np)) * { ddp_poly(cp, lambda0, np) }
// where ddp_poly = (lambda0^{num_coeff-1}, lambda0^{num_coeff-2}, .., lambda0, 1)
ddp_poly[0] = 1.0;
ddp_poly[1] = lambda0;
ddp_poly[2] = lambda0 * lambda0;
for(int j=3;j<np;j++) ddp_poly[j] = (j&1? ddp_poly[j/2] * ddp_poly[j/2+1] : ddp_poly[j/2]*ddp_poly[j/2]);
for(int j=0;j<np;j++) ddp_t[j] = ddx_sig * ddp_poly[np-j-1];
// now out = sum(s * t)
// ddp out = sum ddp s*t = sum s * ddp t
out += s * t;
for(int j=0;j<np;j++) jac[j] += s * ddp_t[j];
}
// apply final scale:
for(int j=0;j<np;j++) jac[j] *= (CIE_LAMBDA_MAX - CIE_LAMBDA_MIN) / (double)CIE_FINE_SAMPLES;
// also return regular value, we need it for the chain rule
return out * (CIE_LAMBDA_MAX - CIE_LAMBDA_MIN) / (double)CIE_FINE_SAMPLES;
}
static inline double
mat3_det(const double *const restrict a)
{
#define A(y, x) a[(y - 1) * 3 + (x - 1)]
return
A(1, 1) * (A(3, 3) * A(2, 2) - A(3, 2) * A(2, 3)) -
A(2, 1) * (A(3, 3) * A(1, 2) - A(3, 2) * A(1, 3)) +
A(3, 1) * (A(2, 3) * A(1, 2) - A(2, 2) * A(1, 3));
}
static inline double
mat3_inv(const double *const restrict a, double *const restrict inv)
{
const double det = mat3_det(a);
if(!(det != 0.0)) return 0.0;
const double invdet = 1.0 / det;
inv[3*0+0] = invdet * (A(3, 3) * A(2, 2) - A(3, 2) * A(2, 3));
inv[3*0+1] = -invdet * (A(3, 3) * A(1, 2) - A(3, 2) * A(1, 3));
inv[3*0+2] = invdet * (A(2, 3) * A(1, 2) - A(2, 2) * A(1, 3));
inv[3*1+0] = -invdet * (A(3, 3) * A(2, 1) - A(3, 1) * A(2, 3));
inv[3*1+1] = invdet * (A(3, 3) * A(1, 1) - A(3, 1) * A(1, 3));
inv[3*1+2] = -invdet * (A(2, 3) * A(1, 1) - A(2, 1) * A(1, 3));
inv[3*2+0] = invdet * (A(3, 2) * A(2, 1) - A(3, 1) * A(2, 2));
inv[3*2+1] = -invdet * (A(3, 2) * A(1, 1) - A(3, 1) * A(1, 2));
inv[3*2+2] = invdet * (A(2, 2) * A(1, 1) - A(2, 1) * A(1, 2));
return det;
#undef A
}
static inline void
mat3_mulv(
const double *const restrict a,
const double *const restrict v,
double *const restrict res)
{
res[0] = res[1] = res[2] = 0.0f;
for(int j=0;j<3;j++)
for(int i=0;i<3;i++)
res[j] += a[3*j+i] * v[i];
}
// jacobian for levmar:
void lm_jacobian(
double *p, // parameters: num_coeff * 3 for camera cfa spectra
double *jac, // output: derivative dx / dp (n x m entries, n-major, i.e. (dx[0]/dp[0], dx[0]/dp[1], ..)
int m, // number of parameters (=num_coeff*3)
int n, // number of data points
void *data)
{
double *cf = data;
memset(jac, 0, sizeof(jac[0])*m*n);
double *Je = alloca(3*m*sizeof(double)); // dxdp
int num = n/2;
for(int i=0;i<num;i++) // for all rgb data points
{
memset(Je, 0, sizeof(double)*3*m);
// get derivative dx[3*i+{0,1,2}] / dp[3 * num_coeff]
double rgb[3];
rgb[0] = ddp_eval(p+0*num_coeff, cf + 3*i, num_coeff, 3, Je + 0*m);
rgb[1] = ddp_eval(p+1*num_coeff, cf + 3*i, num_coeff, 3, Je + 1*m+1*num_coeff);
rgb[2] = ddp_eval(p+2*num_coeff, cf + 3*i, num_coeff, 3, Je + 2*m+2*num_coeff);
double b = rgb[0]+rgb[1]+rgb[2];
double ib = 1.0/(b*b);
// account for normalise1:
// we got n = rgb/sum(rgb), so
// ddr r/(r+g+b) => ddx x/(x+c) = c / (x+c)^2
// ddr g/(r+g+b) => ddx a/(x+b) = - a / (x+b)^2
// / ddr r, ddg r, ddb r \
// Jn = | ddr g, ddg g, ddb g |
// \ ddr b, ddg b, ddb b /
double Jn[] = {
(rgb[1]+rgb[2])*ib, -rgb[0]*ib, -rgb[0]*ib,
-rgb[1]*ib, (rgb[0]+rgb[2])*ib, -rgb[1]*ib,
-rgb[2]*ib, -rgb[2]*ib, (rgb[0]+rgb[1])*ib,
};
// ddp n(rgb) = ddx n(rgb) * ddp rgb
// Jn `-----' =Je see above
// 3x3 (3*num_coeff)x3
for(int j=0;j<m;j++) // parameter number
for(int k=0;k<2;k++) // rgb colour channel
for(int l=0;l<3;l++)
jac[(2*i + k)*m + j] += Jn[3*k+l] * Je[m*l + j];
}
}
// callback for levmar:
void lm_callback(
double *p, // parameers: num_coeff * 3 for camera cfa spectra
double *x, // output data, write here
int m, // number of parameters
int n, // number of data points, i.e. colour spots
void *data)
{
double *cf = data;
int num = n/2;
for(int i=0;i<num;i++)
{
double rgb[3] = {
eval(p+0*num_coeff, cf + 3*i, num_coeff, 3),
eval(p+1*num_coeff, cf + 3*i, num_coeff, 3),
eval(p+2*num_coeff, cf + 3*i, num_coeff, 3)};
normalise1(rgb);
x[2*i+0] = rgb[0];
x[2*i+1] = rgb[1];
}
}
void lm_jacobian_dif(
double *p, // parameters: num_coeff * 3 for camera cfa spectra
double *jac, // output: derivative dx / dp (n x m entries, n-major, i.e. (dx[0]/dp[0], dx[0]/dp[1], ..)
int m, // number of parameters (=num_coeff*3)
int n, // number of data points
void *data)
{
for(int j=0;j<m;j++)
{
double X1[n];
double X2[n];
double cfa2[m];
const double h = 1e-10;
memcpy(cfa2, p, sizeof(cfa2));
cfa2[j] += h;
lm_callback(cfa2, X1, m, n, data);
memcpy(cfa2, p, sizeof(cfa2));
cfa2[j] -= h;
lm_callback(cfa2, X2, m, n, data);
for(int k=0;k<n;k++)
jac[m*k + j] = (X1[k] - X2[k]) / (2.0*h);
}
}
static inline int
load_reference_cfa_spectra(
const char *model,
double cfa_spec[100][4])
{
char filename[256];
snprintf(filename, sizeof(filename), "%s.txt", model);
int len = strlen(filename), cfa_spec_cnt = 0;
for(int i=0;i<len;i++) if(filename[i]==' ') filename[i] = '_';
FILE *fr = fopen(filename, "rb");
if(fr)
{
while(!feof(fr))
{
if(4 != fscanf(fr, "%lg %lg %lg %lg",
cfa_spec[cfa_spec_cnt] + 0, cfa_spec[cfa_spec_cnt] + 1,
cfa_spec[cfa_spec_cnt] + 2, cfa_spec[cfa_spec_cnt] + 3))
cfa_spec_cnt--; // do nothing, we'll ignore comments and stuff gone wrong
fscanf(fr, "*[^\n]"); fgetc(fr);
cfa_spec_cnt++;
}
fclose(fr);
}
else fprintf(stderr, "[vkdt-mkidt] can't open reference response curves! `%s'\n", filename);
return cfa_spec_cnt;
}
// print xyz and rgb pairs for vector plots:
static inline void
write_sample_points(
const char *basename,
const double *cfa,
const float *spectra,
const header_t *sh,
const double (*cfa_spec)[4],
const int cfa_spec_cnt,
const double *xyz_to_cam,
const double *cam_to_xyz,
float *chroma,
const int cwd,
const int cht)
{
char filename[256] = {0};
snprintf(filename, sizeof(filename), "%s_points.dat", basename);
FILE *f0 = fopen(filename, "wb");
if(!f0) return;
for(int i=0;i<2000;i++)
{ // pick a random srgb colour inside gamut
double rgb[3] = {0.0}, xyz[3] = {0.0}, xyz2[3], xyz3[3], cf[3], cam_rgb[3], cam_rgb_spec[3], cam_rgb_rspec[3];
sample_rgb(rgb, 0.9, 0);
mat3_mulv(srgb_to_xyz, rgb, xyz);
mat3_mulv(xyz_to_cam, xyz, cam_rgb); // convert to camera by matrix
normalise1(xyz); // convert to chromaticity
fetch_coeff(xyz, spectra, sh->wd, sh->ht, cf);
if(cf[0] == 0.0) continue; // discard out of spectral locus
for(int k=0;k<3;k++) // camera rgb by processing spectrum * cfa spectrum
cam_rgb_spec[k] = eval(cfa+num_coeff*k, cf, num_coeff, 3);
mat3_mulv(cam_to_xyz, cam_rgb_spec, xyz2); // spectral camera to xyz via matrix
for(int k=0;k<3;k++) // also compute a reference
cam_rgb_rspec[k] = eval_ref(cfa_spec, k, cfa_spec_cnt, cf);
mat3_mulv(cam_to_xyz, cam_rgb_rspec, xyz3);
double rec2020_from_mat[3] = {0.0};
mat3_mulv(xyz_to_rec2020, xyz2, rec2020_from_mat);
normalise1(cam_rgb);
normalise1(cam_rgb_spec);
normalise1(cam_rgb_rspec);
normalise1(xyz2);
normalise1(xyz3);
// also write exactly the thing we'll do runtime: camera rgb -> matrix and camera rgb -> lut
double tc[2] = {cam_rgb_spec[0], cam_rgb_spec[2]}; // normalised already
double rec2020[4] = {0.0}, xyz_spec[3] = {0.0};
fetch_coeff(tc, chroma, cwd, cht, rec2020); // fetch rb
rec2020[2] = rec2020[1]; // convert to rgb
rec2020[1] = 1.0-rec2020[0]-rec2020[2];
mat3_mulv(rec2020_to_xyz, rec2020, xyz_spec);
normalise1(rec2020_from_mat);
normalise1(rec2020);
normalise1(xyz_spec);
fprintf(f0, "%g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g %g\n",
xyz[0], xyz[1], xyz2[0], xyz2[1], xyz3[0], xyz3[1],
cam_rgb[0], cam_rgb[1], cam_rgb[2],
cam_rgb_spec[0], cam_rgb_spec[1], cam_rgb_spec[2],
cam_rgb_rspec[0], cam_rgb_rspec[1], cam_rgb_rspec[2],
xyz_spec[0], xyz_spec[1], xyz2[0], xyz2[1]);
}
fclose(f0);
}
#if 0
static inline void
write_identity_lut(
int wd,
int ht)
{
header_t hout = {
.magic = 1234,
.version = 2,
.channels = 2,
.datatype = 0,
.wd = wd,
.ht = ht,
};
FILE *f = fopen("id.lut", "wb");
fwrite(&hout, sizeof(hout), 1, f);
uint16_t *b16 = calloc(sizeof(uint16_t), wd*ht*2);
for(int j=0;j<ht;j++)
for(int i=0;i<wd;i++)
{
const int k=j*wd+i;
double rb[2] = {(i+0.5)/wd, (j+0.5)/ht};
quad2tri(rb, rb+1);
b16[2*k+0] = float_to_half(rb[0]);
b16[2*k+1] = float_to_half(rb[1]);
}
fwrite(b16, sizeof(uint16_t), wd*ht*2, f);
fclose(f);
free(b16);
}
#endif
// create 2.5D chroma lut
static inline float*
create_chroma_lut(
int *wd_out,
int *ht_out,
const float *spectra,
const header_t *sh,
const double *cfa,
const double (*cfa_spec)[4],
const int cfa_spec_cnt,
const double *xyz_to_cam,
const double *cam_to_xyz)
{
const int ssf = 0; // DEBUG output lut based on measured curve
// to avoid interpolation artifacts we only want to place straight pixel
// center values of our spectra.lut in the output:
int swd = sh->wd, sht = sh->ht; // sampling dimensions
int wd = swd, ht = sht; // output dimensions
float *buf = calloc(sizeof(float)*4, wd*ht+1);
// do two passes over the data
// get illum E white point (lowest saturation) in camera rgb and quad param:
const double white_xyz[3] = {1.0f/3.0f, 1.0f/3.0f, 1.0f/3.0f};
double white_cam_rgb[3];
mat3_mulv(xyz_to_cam, white_xyz, white_cam_rgb);
normalise1(white_cam_rgb); // should not be needed
tri2quad(white_cam_rgb, white_cam_rgb+2);
// first pass: get rough idea about max deviation from white and the saturation we got there
double *angular_ds = calloc(sizeof(double), 360*2);
int sample_wd = swd, sample_ht = sht;
for(int j=0;j<sample_ht;j++) for(int i=0;i<sample_wd;i++)
{
double xy[2] = {(i+0.5)/sample_wd, (j+0.5)/sample_ht};
quad2tri(xy+0, xy+1);
double cf[3]; // look up the coeffs for the sampled colour spectrum
fetch_coeffi(xy, spectra, sh->wd, sh->ht, cf); // nearest
if(cf[0] == 0) continue; // discard out of spectral locus
double cam_rgb_spec[3] = {0.0}; // camera rgb by processing spectrum * cfa spectrum
for(int k=0;k<3;k++)
if(ssf) cam_rgb_spec[k] = eval_ref(cfa_spec, k, cfa_spec_cnt, cf);
else cam_rgb_spec[k] = eval(cfa+num_coeff*k, cf, num_coeff, 3);
normalise1(cam_rgb_spec);
double u0 = cam_rgb_spec[0], u1 = cam_rgb_spec[2];
tri2quad(&u0, &u1);
float fxy[] = {xy[0], xy[1]}, white[] = {1.0f/3.0f, 1.0f/3.0f};
float sat = dt_spectrum_saturation(fxy, white);
// find angular max dist + sat
int bin = CLAMP(180.0/M_PI * (M_PI + atan2(u1-white_cam_rgb[2], u0-white_cam_rgb[0])), 0, 359);
double dist2 =
(u1-white_cam_rgb[2])*(u1-white_cam_rgb[2])+
(u0-white_cam_rgb[0])*(u0-white_cam_rgb[0]);
if(dist2 > angular_ds[2*bin])
{
angular_ds[2*bin+0] = dist2;
angular_ds[2*bin+1] = sat;
}
}
double white_norm = 1.0;
{
double coeff[3] = {0.0};
coeff[2] = 100000.0;
double white_cam_rgb[3] = {0.0};
white_cam_rgb[0] = eval(cfa+num_coeff*0, coeff, num_coeff, 3);
white_cam_rgb[1] = eval(cfa+num_coeff*1, coeff, num_coeff, 3);
white_cam_rgb[2] = eval(cfa+num_coeff*2, coeff, num_coeff, 3);
white_norm = normalise1(white_cam_rgb);
}
// 2nd pass:
// #pragma omp parallel for schedule(dynamic) collapse(2) default(shared)
for(int j=0;j<sht;j++) for(int i=0;i<swd;i++)
{
double xy[2] = {(i+0.5)/swd, (j+0.5)/sht};
quad2tri(xy+0, xy+1);
const double xyz[3] = {xy[0], xy[1], 1.0-xy[0]-xy[1]};
double cf[3]; // look up the coeffs for the sampled colour spectrum
fetch_coeff(xy, spectra, sh->wd, sh->ht, cf); // interpolate
// fetch_coeffi(xy, spectra, sh->wd, sh->ht, cf); // nearest
if(cf[0] == 0) continue; // discard out of spectral locus
double cam_rgb_spec[3] = {0.0}; // camera rgb by processing spectrum * cfa spectrum
for(int k=0;k<3;k++)
if(ssf) cam_rgb_spec[k] = eval_ref(cfa_spec, k, cfa_spec_cnt, cf);
else cam_rgb_spec[k] = eval(cfa+num_coeff*k, cf, num_coeff, 3);
double norm = normalise1(cam_rgb_spec);
float fxy[] = {xy[0], xy[1]}, white[2] = {1.0f/3.0f, 1.0f/3.0f};
float sat = dt_spectrum_saturation(fxy, white);
// convert tri t to quad u:
double u0 = cam_rgb_spec[0], u1 = cam_rgb_spec[2];
tri2quad(&u0, &u1);
int bin = CLAMP(180.0/M_PI * (M_PI + atan2(u1-white_cam_rgb[2], u0-white_cam_rgb[0])), 0, 359);
double dist2 =
(u1-white_cam_rgb[2])*(u1-white_cam_rgb[2])+
(u0-white_cam_rgb[0])*(u0-white_cam_rgb[0]);
if(dist2 < angular_ds[2*bin] && sat > angular_ds[2*bin+1])
continue; // discard higher xy sat for lower rgb sat
if(dist2 < 0.8*0.8*angular_ds[2*bin] && sat > 0.95*angular_ds[2*bin+1])
continue; // be harsh to values straddling our bounds
// sort this into rb/sum(rgb) map in camera rgb
int ii = CLAMP(u0 * wd + 0.5, 0, wd-1);
int jj = CLAMP(u1 * ht + 0.5, 0, ht-1);
double rec2020[3];
mat3_mulv(xyz_to_rec2020, xyz, rec2020);
normalise1(rec2020);
buf[4*(jj*wd + ii)+0] = rec2020[0];
buf[4*(jj*wd + ii)+1] = rec2020[2];
buf[4*(jj*wd + ii)+2] = norm/white_norm; // store relative norm too!
}
free(angular_ds);
*wd_out = wd;
*ht_out = ht;
return buf;
}
// write look up table based on hue and chroma:
static inline void
write_chroma_lut(
const char *basename,
const float *buf,
const int wd,
const int ht)
{
char filename[256] = {0};
snprintf(filename, sizeof(filename), "%s.pfm", basename);
FILE *f = fopen(filename, "wb");
fprintf(f, "PF\n%d %d\n-1.0\n", wd, ht);
for(int k=0;k<wd*ht;k++)
{
float col[3] = {buf[4*k], buf[4*k+1], 1.0-buf[4*k]-buf[4*k+1]};
fwrite(col, sizeof(float), 3, f);
}
fclose(f);
header_t hout = {
.magic = 1234,
.version = 2,
.channels = 2,
.datatype = 0,
.wd = wd,
.ht = ht,
};
snprintf(filename, sizeof(filename), "%s.lut", basename);
f = fopen(filename, "wb");
fwrite(&hout, sizeof(hout), 1, f);
uint16_t *b16 = calloc(sizeof(uint16_t), wd*ht*2);
for(int k=0;k<wd*ht;k++)
{
b16[2*k+0] = float_to_half(buf[4*k+0]);
b16[2*k+1] = float_to_half(buf[4*k+1]);
}
fwrite(b16, sizeof(uint16_t), wd*ht*2, f);
fclose(f);
free(b16);
}
static inline void
print_cfa_coeffs(double *cfa)
{
fprintf(stderr, "[vkdt-mkidt] red cfa coeffs ");
for(int k=0;k<num_coeff;k++) fprintf(stderr, "%2.8g ", cfa[k]);
fprintf(stderr, "\n[vkdt-mkidt] green cfa coeffs ");
for(int k=0;k<num_coeff;k++) fprintf(stderr, "%2.8g ", cfa[num_coeff+k]);
fprintf(stderr, "\n[vkdt-mkidt] blue cfa coeffs ");
for(int k=0;k<num_coeff;k++) fprintf(stderr, "%2.8g ", cfa[2*num_coeff+k]);
fprintf(stderr, "\n");
}
static inline void
write_camera_curves(
const char *basename,
const double *cfa)
{ // plot 'dat' u 1:2 w l lw 4, '' u 1:3 w l lw 4, '' u 1:4 w l lw 4
char filename[256] = {0};
snprintf(filename, sizeof(filename), "%s_curves.dat", basename);
FILE *f = fopen(filename, "wb");
if(!f) return;
for(int i=0;i<CIE_SAMPLES;i++)
{ // plot the camera curves:
double lambda0 = (i+.5)/(double)CIE_FINE_SAMPLES;
double lambda1 = lambda0 * (CIE_LAMBDA_MAX - CIE_LAMBDA_MIN) + CIE_LAMBDA_MIN;
double s0 = sigmoid(poly(cfa+0*num_coeff, lambda0, num_coeff));
double s1 = sigmoid(poly(cfa+1*num_coeff, lambda0, num_coeff));
double s2 = sigmoid(poly(cfa+2*num_coeff, lambda0, num_coeff));
fprintf(f, "%g %g %g %g\n", lambda1, s0, s1, s2);
}
fclose(f);
}
int main(int argc, char *argv[])
{
// warm up random number generator
for(int k=0;k<10;k++) xrand();
// load spectra.lut:
header_t header;
float *spectra = 0;
{
FILE *f = fopen("spectra.lut", "rb");
if(!f) goto error;
if(fread(&header, sizeof(header_t), 1, f) != 1) goto error;
if(header.channels != 4) goto error;
if(header.version != 2) goto error;
spectra = calloc(4*sizeof(float), header.wd * header.ht);
fread(spectra, header.wd*header.ht, 4*sizeof(float), f);
fclose(f);
if(0)
{
error:
if(f) fclose(f);
fprintf(stderr, "[vkdt-mkidt] could not read spectra.lut!\n");
exit(2);
}
}
// these influence the problem size and the mode of operation of the fitter:
// low quality mode:
num_coeff = 6; // number of coefficients in the sigmoid/polynomial cfa spectra
int num_it = 500; // iterations per batch
int num = 10; // number of data points (spectrum/xy) per batch
int batch_cnt = 50; // number of batches
// initial thoughts: using 100 batches and 1000 iterations (num=50)
// improves the fit a bit, only not in the reds. probably not
// converged yet, but indeed it seems more data serves the process.
int der = 0, hq = 0;
const char *model = "Canon EOS 5D Mark II";
for(int k=1;k<argc;k++)
{
if (!strcmp(argv[k], "--hq" )) hq = 1; // high quality mode
else if(!strcmp(argv[k], "--der")) der = 1; // use analytic jacobian
else model = argv[k];
}
if(hq && !der)
{
fprintf(stderr, "[vkdt-mkidt] setting high quality mode, this can be slow..\n");
num_coeff = 6;
num_it = 1000; // 100k unfortunately it does improve from 10k, not by much but notably. this is 10x the cost :(
batch_cnt = 100;
num = 70;
}
else if(hq && der)
{ // these need way more iterations because they often bail out early
fprintf(stderr, "[vkdt-mkidt] setting high quality mode and analytic jacobian. this can be slow..\n");
num_coeff = 6;
num_it = 1000;
batch_cnt = 100;
num = 70;
}
double xyz_to_cam[9];
float adobe_mat[12] = {1, 0, 0, 0, 1, 0, 0, 0, 1};
fprintf(stderr, "[vkdt-mkidt] using matrix for `%s'\n", model);
if(strcmp(model, "identity") && dt_dcraw_adobe_coeff(model, &adobe_mat))
{
fprintf(stderr, "[vkdt-mkidt] could not find this camera model (%s)! check your spelling?\n", model);
exit(3);
}
for(int i=0;i<9;i++) xyz_to_cam[i] = adobe_mat[i];
double cam_to_xyz[9] = {0.0};
mat3_inv(xyz_to_cam, cam_to_xyz);
// xyz -> camera rgb matrix. does it contain white balancing stuff?
fprintf(stderr, "[vkdt-mkidt] M = %g %g %g\n"
" %g %g %g\n"
" %g %g %g\n",
xyz_to_cam[0], xyz_to_cam[1], xyz_to_cam[2],
xyz_to_cam[3], xyz_to_cam[4], xyz_to_cam[5],
xyz_to_cam[6], xyz_to_cam[7], xyz_to_cam[8]);
// in particular, xyz white 1 1 1 maps to this camera rgb:
double white[3] = {0.0}, one[3] = {1.0, 1.0, 1.0};
mat3_mulv(xyz_to_cam, one, white);
double wbcoeff[3] = {1.0/white[0], 1.0/white[1], 1.0/white[2]};
fprintf(stderr, "[vkdt-mkidt] white = %g %g %g\n", white[0], white[1], white[2]);
fprintf(stderr, "[vkdt-mkidt] wb coeff = %g %g %g\n", wbcoeff[0], wbcoeff[1], wbcoeff[2]);
// init initial cfa params and lower/upper bounds:
double cfa[30] = {0.0};
double lb[30] = {0.0};
double ub[30] = {0.0};
// these bounds are important for regularisation. else we'll fit to box spectra to be
// able to match the matrix better. +-50 seem to work really well in most cases.
// fuji/nikon sometimes asks for extended range, but i think it would be better to increase
// the number of coefficients/degree of the polynomial instead.
for(int k=0;k<3*num_coeff;k++) lb[k] = -50;
for(int k=0;k<3*num_coeff;k++) ub[k] = 50;
// for(int k=0;k<3*num_coeff;k++) lb[k] = -(ub[k] = 500); // for kodak need more complex blue
int e = num_coeff-3; // quadratic term
cfa[e+0] = cfa[e+num_coeff] = cfa[e+2*num_coeff] = -3.0;
// construct data point arrays for levmar, 3x for each tristimulus/camera rgb channel:
double *data = calloc(num, sizeof(double) * 3); // data point: spectral coeff for input
double *target = calloc(num, sizeof(double) * 2); // target chroma
fprintf(stderr, "[vkdt-mkidt] starting optimiser..");
double resid = 1.0;
// run optimisation in mini-batches
for (int batch=0;batch<batch_cnt;batch++)
{
for(int i=0;i<num;i++)
{
// pick a random srgb colour inside gamut
double rgb[3] = {0.0}, xyz[3] = {0.0};
sample_rgb(rgb, 0.17, 1); // chosen to reach all of srgb at least potentially
// sample_rgb(rgb, 0.3, 1); // relaxed for kodak
mat3_mulv(srgb_to_xyz, rgb, xyz);
normalise1(xyz);
double cf[3]; // look up the coeffs for the sampled colour spectrum
fetch_coeff(xyz, spectra, header.wd, header.ht, cf);
// apply xyz to camera rgb matrix:
double cam_rgb[3] = {0.0};
mat3_mulv(xyz_to_cam, xyz, cam_rgb);
normalise1(cam_rgb);
memcpy(target+2*i, cam_rgb, sizeof(double)*2);
memcpy(data+3*i, cf, sizeof(double)*3);
}
#ifdef USE_LEVMAR
double info[LM_INFO_SZ] = {0};
double opts[LM_OPTS_SZ] = {
// init-mu eps Jte eps Dp eps err eps diff
0.2, 1E-15, 1E-40, 1E-15, 1e-5};//LM_DIFF_DELTA};
if(der)
{
dlevmar_bc_der(
lm_callback, lm_jacobian, cfa, target, 3*num_coeff, 2*num,
lb, ub, NULL, // dscl, // diagonal scaling constants (?)
num_it, opts, info, NULL, NULL, data);
}
else
{
dlevmar_bc_dif(
lm_callback, cfa, target, 3*num_coeff, 2*num,
lb, ub, NULL, // dscl, // diagonal scaling constants (?)
num_it, opts, info, NULL, NULL, data);
}
// fprintf(stderr, " ||e||_2, ||J^T e||_inf, ||Dp||_2, mu/max[J^T J]_ii\n");
// fprintf(stderr, "info %g %g %g %g\n", info[1], info[2], info[3], info[4]);
fprintf(stderr, "\r[vkdt-mkidt] batch %d/%d it %04d/%d reason %g resid %g -> %g ",
batch+1, batch_cnt, (int)info[5], num_it, info[6], info[0], info[1]);
fprintf(stdout, "%g %g\n", info[0], info[1]);
#else
fprintf(stdout, "%g ", resid);
resid = dt_gauss_newton_cg(
lm_callback,
// lm_jacobian, // does not like our analytic jacobian
lm_jacobian_dif,
cfa, target, 3*num_coeff, 2*num,
lb, ub, num_it, data);
fprintf(stderr, "\r[vkdt-mkidt] batch %d/%d resid %g ",
batch+1, batch_cnt, resid);
// fprintf(stdout, "%g\n", resid); // write convergence history
#endif
} // end mini batches
fprintf(stderr, "\n");
// now we're done, prepare the data for some useful output:
// load reference spectra from txt, if we can
double cfa_spec[100][4] = {{0.0}};
const int cfa_spec_cnt = load_reference_cfa_spectra(model, cfa_spec);
// create the actual 2D chroma lut
int wd, ht;
float *buf = create_chroma_lut(&wd, &ht, spectra, &header, cfa, cfa_spec, cfa_spec_cnt, xyz_to_cam, cam_to_xyz);
#if 1 // then hole fill it
dt_inpaint_buf_t inpaint_buf = {
.dat = buf,
.wd = wd,
.ht = ht,
.cpp = 4,
};
dt_inpaint(&inpaint_buf);
#endif
char basename[256] = {0}; // get sanitised basename
snprintf(basename, sizeof(basename), "%s", model);
int len = strnlen(basename, sizeof(basename));
if(!strcasecmp(".txt", basename + len - 4))
basename[len-4] = 0;
for(int i=0;i<len;i++) if(basename[i] == ' ') basename[i] = '_';
// write the chroma lut to half float .lut as well as .pfm for debugging:
write_chroma_lut(basename, buf, wd, ht);
// write a couple of sample points for debug vector plots
write_sample_points(basename, cfa, spectra, &header, cfa_spec, cfa_spec_cnt, xyz_to_cam, cam_to_xyz, buf, wd, ht);
// output the coefficients to console
print_cfa_coeffs(cfa);
// write the cfa curves to a file for plotting
write_camera_curves(basename, cfa);
// write a camera rgb == rec2020 identity lut for debugging
// write_identity_lut(wd, ht);
free(buf);
exit(0);
}
| 33.566449 | 131 | 0.596515 | [
"vector",
"model",
"transform"
] |
c5c748e091e739076c6114d077753f1b4c8c4bfa | 1,591 | h | C | src/Model/Drawing/Drawing.h | ttfractal44/MechSandbox | 75ac111b094ba1a93e77908048704a98afb72deb | [
"MIT"
] | null | null | null | src/Model/Drawing/Drawing.h | ttfractal44/MechSandbox | 75ac111b094ba1a93e77908048704a98afb72deb | [
"MIT"
] | null | null | null | src/Model/Drawing/Drawing.h | ttfractal44/MechSandbox | 75ac111b094ba1a93e77908048704a98afb72deb | [
"MIT"
] | null | null | null | /*
* Drawing.h
*
* Created on: Apr 11, 2015
* Author: theron
*/
#ifndef DRAWING_H_
#define DRAWING_H_
#include <deque>
#include <osg/Node>
#include <osg/Group>
#include <typeinfo>
namespace Model {
namespace Drawing {
class Drawing;
}
}
#include "Element.h"
namespace Model {
namespace Drawing {
const int UPDATE_DESCEND = 0;
const int UPDATE_ASCEND = 1;
const int UPDATE_BIDIREC = 2;
class Drawing {
public:
Drawing(std::string _name);
virtual ~Drawing();
osg::Group* osggroup;
Element* addElement(Element* element); // Adds element to drawing, returns pointer to element
void deleteElement(Element* element);
void setUpdateProperties(uint depth, uint resolution);
void updateAll(uint depth, uint resolution); // setUpdateProperties and updateAll combined
void updateAll();
void updateAllNoArgs();
void updateElement(Element* element); // Update a specific element, handling recursion where needed
void debugPrintStructure();
std::string name;
uint updatedepth;
uint updateresolution;
std::deque<Element*> elements;
std::string getNewElementName();
private:
uint namecounter=0;
void fixNodeMembership(Element* element);
void resetUpdates(); // Set all elements to updated=false
//void updateElementInternal(Element* element, uint depth, bool bidirec);
void updateElementInternal(Element* element, uint depth, int direction);
};
/*template <typename Type>
Type* addElementReturnSame(Drawing* drawing, Type* element);*/
//#define DRAWING_ADD_ELEMENT_PRESERVE_TYPE(element)
} /* namespace Drawing */
} /* namespace Model */
#endif /* DRAWING_H_ */
| 23.397059 | 100 | 0.747957 | [
"model"
] |
c5caf8fdf0f9d27d9be513db60663c58eae459a3 | 4,814 | h | C | third_party/unzip/crypt.h | appotry/cosmopolitan | af4687cc3f2331a23dc336183ab58fe001cda082 | [
"ISC"
] | null | null | null | third_party/unzip/crypt.h | appotry/cosmopolitan | af4687cc3f2331a23dc336183ab58fe001cda082 | [
"ISC"
] | null | null | null | third_party/unzip/crypt.h | appotry/cosmopolitan | af4687cc3f2331a23dc336183ab58fe001cda082 | [
"ISC"
] | null | null | null | // clang-format off
/*
Copyright (c) 1990-2007 Info-ZIP. All rights reserved.
See the accompanying file LICENSE, version 2005-Feb-10 or later
(the contents of which are also included in (un)zip.h) for terms of use.
If, for some reason, all these files are missing, the Info-ZIP license
also may be found at: ftp://ftp.info-zip.org/pub/infozip/license.html
*/
/*
crypt.h (full version) by Info-ZIP. Last revised: [see CR_VERSION_DATE]
The main encryption/decryption source code for Info-Zip software was
originally written in Europe. To the best of our knowledge, it can
be freely distributed in both source and object forms from any country,
including the USA under License Exception TSU of the U.S. Export
Administration Regulations (section 740.13(e)) of 6 June 2002.
NOTE on copyright history:
Previous versions of this source package (up to version 2.8) were
not copyrighted and put in the public domain. If you cannot comply
with the Info-Zip LICENSE, you may want to look for one of those
public domain versions.
*/
#ifndef __crypt_h /* don't include more than once */
#define __crypt_h
#include "third_party/unzip/crc32.h"
#ifdef CRYPT
# undef CRYPT
#endif
/*
Logic of selecting "full crypt" code:
a) default behaviour:
- dummy crypt code when compiling UnZipSFX stub, to minimize size
- full crypt code when used to compile Zip, UnZip and fUnZip
b) USE_CRYPT defined:
- always full crypt code
c) NO_CRYPT defined:
- never full crypt code
NO_CRYPT takes precedence over USE_CRYPT
*/
#if defined(NO_CRYPT)
# define CRYPT 0 /* dummy version */
#else
#if defined(USE_CRYPT)
# define CRYPT 1 /* full version */
#else
#if !defined(SFX)
# define CRYPT 1 /* full version for zip and main unzip */
#else
# define CRYPT 0 /* dummy version for unzip sfx */
#endif
#endif /* ?USE_CRYPT */
#endif /* ?NO_CRYPT */
#if CRYPT
/* full version */
#ifdef CR_BETA
# undef CR_BETA /* this is not a beta release */
#endif
#define CR_MAJORVER 2
#define CR_MINORVER 11
#ifdef CR_BETA
# define CR_BETA_VER "c BETA"
# define CR_VERSION_DATE "05 Jan 2007" /* last real code change */
#else
# define CR_BETA_VER ""
# define CR_VERSION_DATE "05 Jan 2007" /* last public release date */
# define CR_RELEASE
#endif
#ifndef __G /* UnZip only, for now (DLL stuff) */
# define __G
# define __G__
# define __GDEF
# define __GPRO void
# define __GPRO__
#endif
#if defined(MSDOS) || defined(OS2) || defined(WIN32)
# ifndef DOS_OS2_W32
# define DOS_OS2_W32
# endif
#endif
#if defined(DOS_OS2_W32) || defined(__human68k__)
# ifndef DOS_H68_OS2_W32
# define DOS_H68_OS2_W32
# endif
#endif
#if defined(VM_CMS) || defined(MVS)
# ifndef CMS_MVS
# define CMS_MVS
# endif
#endif
/* To allow combining of Zip and UnZip static libraries in a single binary,
* the Zip and UnZip versions of the crypt core functions have to be named
* differently.
*/
#ifdef ZIP
# ifdef REALLY_SHORT_SYMS
# define decrypt_byte zdcrby
# else
# define decrypt_byte zp_decrypt_byte
# endif
# define update_keys zp_update_keys
# define init_keys zp_init_keys
#else /* !ZIP */
# ifdef REALLY_SHORT_SYMS
# define decrypt_byte dcrbyt
# endif
#endif /* ?ZIP */
#define IZ_PWLEN 80 /* input buffer size for reading encryption key */
#ifndef PWLEN /* for compatibility with previous zcrypt release... */
# define PWLEN IZ_PWLEN
#endif
#define RAND_HEAD_LEN 12 /* length of encryption random header */
/* the crc_32_tab array has to be provided externally for the crypt calculus */
/* encode byte c, using temp t. Warning: c must not have side effects. */
#define zencode(c,t) (t=decrypt_byte(__G), update_keys(c), t^(c))
/* decode byte c in place */
#define zdecode(c) update_keys(__G__ c ^= decrypt_byte(__G))
int decrypt_byte OF((__GPRO));
int update_keys OF((__GPRO__ int c));
void init_keys OF((__GPRO__ ZCONST char *passwd));
#ifdef ZIP
void crypthead OF((ZCONST char *, ulg, FILE *));
# ifdef UTIL
int zipcloak OF((struct zlist far *, FILE *, FILE *, ZCONST char *));
int zipbare OF((struct zlist far *, FILE *, FILE *, ZCONST char *));
# else
unsigned zfwrite OF((zvoid *, extent, extent, FILE *));
extern char *key;
# endif
#endif /* ZIP */
#if (defined(UNZIP) && !defined(FUNZIP))
int decrypt OF((__GPRO__ ZCONST char *passwrd));
#endif
#ifdef FUNZIP
extern int encrypted;
# ifdef NEXTBYTE
# undef NEXTBYTE
# endif
# define NEXTBYTE \
(encrypted? update_keys(__G__ getc(G.in)^decrypt_byte(__G)) : getc(G.in))
#endif /* FUNZIP */
#else /* !CRYPT */
/* dummy version */
#define zencode
#define zdecode
#define zfwrite fwrite
#endif /* ?CRYPT */
#endif /* !__crypt_h */
| 27.988372 | 79 | 0.690278 | [
"object"
] |
c5ce0c94b090784a555d35bf429dbbbc7f143fd1 | 7,139 | h | C | src/util/input/keyboard.h | marstau/shinsango | d9468787ae8e18fa478f936770d88e9bf93c11c0 | [
"BSD-3-Clause"
] | 1 | 2021-06-16T15:25:47.000Z | 2021-06-16T15:25:47.000Z | src/util/input/keyboard.h | marstau/shinsango | d9468787ae8e18fa478f936770d88e9bf93c11c0 | [
"BSD-3-Clause"
] | null | null | null | src/util/input/keyboard.h | marstau/shinsango | d9468787ae8e18fa478f936770d88e9bf93c11c0 | [
"BSD-3-Clause"
] | null | null | null | #ifndef _paintown_keyboard_h
#define _paintown_keyboard_h
#include <map>
#include <vector>
#include <stdint.h>
/* handles allegro key[] array better than keypressed()
* and readkey()
*/
class Keyboard{
private:
Keyboard();
public:
friend class InputManager;
typedef const int KeyType;
typedef uint32_t unicode_t;
struct KeyData{
KeyData():
key(-1),
unicode(-1),
enabled(false){
}
KeyData(int key, unicode_t unicode, bool enabled):
key(key),
unicode(unicode),
enabled(enabled){
}
int key;
/* Converted to a unicode character in UTF-32 */
unicode_t unicode;
/* whether the key is being pressed */
bool enabled;
};
/*
typedef void (*ObserverCallback)(const KeyData & data, void * extra);
struct Observer{
Observer():
callback(NULL),
extra(NULL){
}
Observer(ObserverCallback callback, void * extra):
callback(callback),
extra(extra){
}
ObserverCallback callback;
void * extra;
};
*/
/* poll:
* Put the keys in Allegro's key[] array into our map of int -> bool
*/
void poll();
/* wait for all keys to be released */
void wait();
/* []:
* Extract a boolean value given a key number
*/
#if 0
inline bool operator[] ( const int i ){
/* if the key has been pressed for the first time return true */
if ( my_keys[ i ] < 0 ){
my_keys[ i ] = 1;
return true;
}
bool b = my_keys[ i ] > key_delay[ i ];
if ( b ){
my_keys[ i ] = 1;
}
return b;
}
#endif
/* keypressed:
* Returns true if a key is pressed
*/
bool keypressed();
/* readKeys:
* Store all pressed keys in a user supplied vector
*/
void readKeys(std::vector< int > & all_keys);
void readBufferedKeys(std::vector<int> & keys);
std::vector<KeyData> readData();
std::vector<unicode_t> readText();
// int readKey();
void clear();
/* sets the latest repeat state. popping the state restores the previous state */
static void pushRepeatState(bool enabled);
static void popRepeatState();
/* true on systems that probably have a keyboard, like pc.
* false on ps3, wii, etc.
*/
static bool haveKeyboard();
void setDelay( const int key, const int delay );
void setAllDelay( const int delay );
inline const std::vector<KeyData> & getBufferedKeys() const {
return buffer;
}
static const char * keyToName( int key );
static bool isNumber( int key );
static bool isChar( int key );
static bool isAlpha( int key );
static KeyType Key_A;
static KeyType Key_B;
static KeyType Key_C;
static KeyType Key_D;
static KeyType Key_E;
static KeyType Key_F;
static KeyType Key_G;
static KeyType Key_H;
static KeyType Key_I;
static KeyType Key_J;
static KeyType Key_K;
static KeyType Key_L;
static KeyType Key_M;
static KeyType Key_N;
static KeyType Key_O;
static KeyType Key_P;
static KeyType Key_Q;
static KeyType Key_R;
static KeyType Key_S;
static KeyType Key_T;
static KeyType Key_U;
static KeyType Key_V;
static KeyType Key_W;
static KeyType Key_X;
static KeyType Key_Y;
static KeyType Key_Z;
static KeyType Key_0;
static KeyType Key_1;
static KeyType Key_2;
static KeyType Key_3;
static KeyType Key_4;
static KeyType Key_5;
static KeyType Key_6;
static KeyType Key_7;
static KeyType Key_8;
static KeyType Key_9;
static KeyType Key_0_PAD;
static KeyType Key_1_PAD;
static KeyType Key_2_PAD;
static KeyType Key_3_PAD;
static KeyType Key_4_PAD;
static KeyType Key_5_PAD;
static KeyType Key_6_PAD;
static KeyType Key_7_PAD;
static KeyType Key_8_PAD;
static KeyType Key_9_PAD;
static KeyType Key_F1;
static KeyType Key_F2;
static KeyType Key_F3;
static KeyType Key_F4;
static KeyType Key_F5;
static KeyType Key_F6;
static KeyType Key_F7;
static KeyType Key_F8;
static KeyType Key_F9;
static KeyType Key_F10;
static KeyType Key_F11;
static KeyType Key_F12;
static KeyType Key_ESC;
static KeyType Key_TILDE;
static KeyType Key_MINUS;
static KeyType Key_EQUALS;
static KeyType Key_BACKSPACE;
static KeyType Key_TAB;
static KeyType Key_OPENBRACE;
static KeyType Key_CLOSEBRACE;
static KeyType Key_ENTER;
static KeyType Key_COLON;
static KeyType Key_QUOTE;
static KeyType Key_BACKSLASH;
static KeyType Key_BACKSLASH2;
static KeyType Key_COMMA;
static KeyType Key_STOP;
static KeyType Key_SLASH;
static KeyType Key_SPACE;
static KeyType Key_INSERT;
static KeyType Key_DEL;
static KeyType Key_HOME;
static KeyType Key_END;
static KeyType Key_PGUP;
static KeyType Key_PGDN;
static KeyType Key_LEFT;
static KeyType Key_RIGHT;
static KeyType Key_UP;
static KeyType Key_DOWN;
static KeyType Key_SLASH_PAD;
static KeyType Key_ASTERISK;
static KeyType Key_MINUS_PAD;
static KeyType Key_PLUS_PAD;
static KeyType Key_DEL_PAD;
static KeyType Key_ENTER_PAD;
static KeyType Key_PRTSCR;
static KeyType Key_PAUSE;
static KeyType Key_ABNT_C1;
static KeyType Key_YEN;
static KeyType Key_KANA;
static KeyType Key_CONVERT;
static KeyType Key_NOCONVERT;
static KeyType Key_AT;
static KeyType Key_CIRCUMFLEX;
static KeyType Key_COLON2;
static KeyType Key_KANJI;
static KeyType Key_EQUALS_PAD;
static KeyType Key_BACKQUOTE;
static KeyType Key_SEMICOLON;
static KeyType Key_COMMAND;
/*
static KeyType Key_UNKNOWN1;
static KeyType Key_UNKNOWN2;
static KeyType Key_UNKNOWN3;
static KeyType Key_UNKNOWN4;
static KeyType Key_UNKNOWN5;
static KeyType Key_UNKNOWN6;
static KeyType Key_UNKNOWN7;
static KeyType Key_UNKNOWN8;
*/
static KeyType Key_MODIFIERS;
static KeyType Key_LSHIFT;
static KeyType Key_RSHIFT;
static KeyType Key_LCONTROL;
static KeyType Key_RCONTROL;
static KeyType Key_ALT;
static KeyType Key_ALTGR;
static KeyType Key_LWIN;
static KeyType Key_RWIN;
static KeyType Key_MENU;
static KeyType Key_SCRLOCK;
static KeyType Key_NUMLOCK;
static KeyType Key_CAPSLOCK;
void press(KeyType key, unicode_t unicode);
void release(KeyType key);
/*
virtual void addObserver(ObserverCallback observer, void * extra);
virtual void removeObserver(ObserverCallback observer, void * extra);
*/
protected:
static void disableKeyRepeat();
static void enableKeyRepeat();
// std::map<int,int> my_keys;
std::map<int,int> key_delay;
// std::vector<Observer> observers;
std::map<KeyType, KeyData> keyState;
std::vector<KeyData> buffer;
bool enableBuffer;
static std::vector<bool> repeatState;
};
#endif
| 25.96 | 85 | 0.658075 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.