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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
02cc80f5a98f5fb94d666def2f43a4a50c5081c4 | 1,877 | h | C | code/src/apps/celldetection-regr/CellDetectorRegr.h | pkainz/MICCAI2015 | 933e9e52d244ad1179713fe2f1dbb749d9e1f8d5 | [
"Apache-2.0"
] | 23 | 2015-12-14T06:06:45.000Z | 2022-03-25T10:51:42.000Z | code/src/apps/celldetection-regr/CellDetectorRegr.h | pkainz/MICCAI2015 | 933e9e52d244ad1179713fe2f1dbb749d9e1f8d5 | [
"Apache-2.0"
] | 3 | 2016-08-18T13:16:30.000Z | 2017-04-01T15:04:00.000Z | code/src/apps/celldetection-regr/CellDetectorRegr.h | pkainz/MICCAI2015 | 933e9e52d244ad1179713fe2f1dbb749d9e1f8d5 | [
"Apache-2.0"
] | 8 | 2015-08-18T10:31:06.000Z | 2020-12-30T13:55:01.000Z | /*
* CellDetectorRegr.h
*
* Author: Philipp Kainz, Martin Urschler, Samuel Schulter, Paul Wohlhart, Vincent Lepetit
* Institution: Medical University of Graz and Graz University of Technology, Austria
*
*/
#ifndef CELLDETECTORREGR_H
#define CELLDETECTORREGR_H
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <vector>
#include "AppContextCellDetRegr.h"
#include "SampleImgPatch.h"
#include "LabelMLRegr.h"
#include "SplitFunctionImgPatch.h"
#include "SplitEvaluatorMLRegr.h"
#include "LeafNodeStatisticsMLRegr.h"
#include "DataLoaderCellDetRegr.h"
#include "icgrf.h"
// typedefs for easier use later
typedef SplitFunctionImgPatch<uchar, float, AppContextCellDetRegr> TSplitFunctionImgPatch;
typedef RandomForest<SampleImgPatch, LabelMLRegr, TSplitFunctionImgPatch, SplitEvaluatorMLRegr<SampleImgPatch, AppContextCellDetRegr>, LeafNodeStatisticsMLRegr<SampleImgPatch, AppContextCellDetRegr>, AppContextCellDetRegr> TRegressionForest;
typedef Node<SampleImgPatch, LabelMLRegr, TSplitFunctionImgPatch, LeafNodeStatisticsMLRegr<SampleImgPatch, AppContextCellDetRegr>, AppContextCellDetRegr> TNode;
class CellDetectorRegr {
public:
// Constructor
CellDetectorRegr(TRegressionForest* rfin, AppContextCellDetRegr* apphpin);
// detect cells from test images (uses test path from appcontext)
void PredictTestImages();
// predict a single image
cv::Mat PredictSingleImage(const boost::filesystem::path file);
protected:
// predict the distance transform image using sliding window
// and store the prediction image to a specified folder
void PredictImage(const cv::Mat& src_img, cv::Mat& pred_dt_img);
private:
TRegressionForest* m_rf; // the forest
AppContextCellDetRegr* m_apphp; // the app context
int m_pwidth; // patch width
int m_pheight; // patch height
};
#endif // CELLDETECTORREGR_H
| 32.929825 | 241 | 0.787427 | [
"vector",
"transform"
] |
02dff723d62ea6983a43f8363a7f298ec63d8b7d | 1,280 | c | C | d/standard/orc_valley/shaman.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-07-19T05:24:44.000Z | 2021-11-18T04:08:19.000Z | d/standard/orc_valley/shaman.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 4 | 2021-03-15T18:56:39.000Z | 2021-08-17T17:08:22.000Z | d/standard/orc_valley/shaman.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-09-12T06:22:38.000Z | 2022-01-31T01:15:12.000Z | #include <std.h>
inherit ROOM;
void create() {
::create();
set_property("light", 1);
set_property("indoors", 1);
set_property("no castle", 1);
set("short", "The chamber of the orc shaman");
set("long",
"This secret room is the chamber of the orc shaman. "
"It is most certain that you should not be here.");
set_items(
(["chamber" : "It is a roundish room and dimly lit."]) );
set_exits(
(["south" : "/d/standard/orc_valley/open",
"north" : "/d/standard/orc_valley/treasure"]) );
set_pre_exit_functions( ({ "north"}), ({ "go_north" }) );
}
void reset() {
object mon, ob;
::reset();
if(!present("shaman")) {
mon = new("d/standard/obj/mon/orc_shaman");
mon->move(this_object());
ob = new(OBJECT);
ob->set_name("key");
ob->set_id( ({ "key", "stone key", "a stone key", "orc_treasure" }) );
ob->set("short", "A stone key");
ob->set("long", "There is nothing special about it.");
ob->set_weight(190);
ob->set_value(30);
ob->move(mon);
}
}
int go_north() {
if(!present("shaman")) return 1;
write("The shaman smashes you as you try to go north!");
this_player()->add_hp(-(random(10)));
return 0;
}
| 27.234043 | 78 | 0.557031 | [
"object"
] |
02ee92677e3eaf84a15f7097d94c607dc091fa86 | 5,181 | c | C | nitan/adm/daemons/story/master.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | 1 | 2019-03-27T07:25:16.000Z | 2019-03-27T07:25:16.000Z | nitan/adm/daemons/story/master.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | nitan/adm/daemons/story/master.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | // story:master 宗師聚會
#include <ansi.h>
nosave string *char_id;
nosave string *char_name;
nosave string winner_name;
nosave string winner_id;
nosave string ann_name;
nosave string ann_id;
int get_winner();
mixed give_gift();
int rob_gift();
int select_characters();
nosave mixed *story = ({
"$1[$I1]:好,今日我們五人齊聚華山,不必寒暄,可快入正題。",
"$2[$I2]:嗯,來龍去脈也不必多説了,此次乃是為了江湖上近日出現的"
HIM "玄黃紫清丹" NOR WHT "一事。",
"$3[$I3]:聽説此丹千年一遇,服用以後妙用無窮,平增十年功力。",
"$4[$I4]:嘿嘿,只是每次出現弄得江湖腥風血雨,不得安寧。",
"$5[$I5]:所以在下召集諸位,以武會友,定下這神丹名分。",
"$2[$I2]:也是,這等神物,若是給江湖宵小拿去,真可謂明珠暗投!",
"$5[$I5]:近來江湖你爭我奪,在下實在是看不過去,這才親自出手取了來。",
"$1[$I1]:甚好甚好,理當如此。",
"$5[$I5]:只是此神物我也不敢貿然自居,故請得諸位來華山論劍,以決此物歸屬。",
"$3[$I3]:廢話不必多説,如何比法?",
"$4[$I4]:我們各顯絕藝,誰能壓倒對方,便是得主,如何?",
"$2[$I2]:好吧,$4所言極是。",
"...",
"天黑了...",
"天又亮了...",
"天又黑了...",
"天又亮了...",
"...",
(: get_winner :),
"$a歎服道:三天以來,看來還是$w武功高強,更勝一籌啊!",
"$w謙道:哪里哪里,各位身手不凡,在下亦是眼界大開,方知天外有天。",
"$a[$Ia]:不必謙讓,此物理應歸$w所有,此乃天意啊。",
(: give_gift :),
"$w[$Iw]:休走!接招!",
"那黑影驀然回身,和$w對了一掌,只震得$w眼花繚亂,氣血翻湧。",
"黑影哈哈長笑,飄然下山而去。",
"$w調息良久,緩緩的吐出一口氣,道:此人內力當真深厚,我看好像是$6。",
(: rob_gift :),
});
void create()
{
seteuid(getuid());
if (uptime() < 86400)
{
destruct(this_object());
return;
}
ann_id = 0;
ann_name = 0;
winner_id = 0;
winner_name = 0;
if (! select_characters())
{
STORY_D->remove_story("master");
destruct(this_object());
return;
}
}
string prompt() { return HIG "【華山論劍】" NOR; }
int select_characters()
{
object *obs;
object ob;
int i;
obs = filter_array(all_interactive(),
(: ! wizardp($1) && ultrap($1) && living($1):));
if (sizeof(obs) < 6)
return 0;
char_id = allocate(6);
char_name = allocate(6);
for (i = 0; i < 6; i++)
{
ob = obs[random(sizeof(obs))];
char_id[i]=query("id", ob);
char_name[i] = ob->name(1);
obs -= ({ ob });
}
return 1;
}
mixed query_story_message(int step)
{
mixed msg;
if (step >= sizeof(story))
return 0;
msg = story[step];
if (functionp(msg)) msg = evaluate(msg);
if (stringp(msg))
{
msg = replace_string(msg, "$1", char_name[0]);
msg = replace_string(msg, "$I1", char_id[0]);
msg = replace_string(msg, "$2", char_name[1]);
msg = replace_string(msg, "$I2", char_id[1]);
msg = replace_string(msg, "$3", char_name[2]);
msg = replace_string(msg, "$I3", char_id[2]);
msg = replace_string(msg, "$4", char_name[3]);
msg = replace_string(msg, "$I4", char_id[3]);
msg = replace_string(msg, "$5", char_name[4]);
msg = replace_string(msg, "$I5", char_id[4]);
msg = replace_string(msg, "$6", char_name[5]);
msg = replace_string(msg, "$I6", char_id[5]);
if (ann_name && ann_id)
{
msg = replace_string(msg, "$a", ann_name);
msg = replace_string(msg, "$Ia", ann_id);
}
if (winner_name && winner_id)
{
msg = replace_string(msg, "$w", winner_name);
msg = replace_string(msg, "$Iw", winner_id);
}
}
return msg;
}
int get_winner()
{
int i;
i = random(5);
winner_name = char_name[i];
winner_id = char_id[i];
do
{
i = random(5);
ann_id = char_id[i];
ann_name = char_name[i];
} while (ann_id == winner_id);
return 1;
}
mixed give_gift()
{
object gob;
object gift;
gob = find_player(winner_id);
if (random(2))
{
CHANNEL_D->do_channel(this_object(), "rumor",
"聽説五大宗師在華山聚會,將" +
"玄黃紫清丹交給" + winner_name + "。");
STORY_D->remove_story("master");
if (gob)
{
gift = new("/clone/ultra/xuanhuang");
if (gift) gift->move(gob, 1);
}
return 0;
}
return "一道黑影掠過,一掌重重的擊在$a的背心,$a大叫一聲,吐出一口鮮血。";
}
int rob_gift()
{
object rob;
object gift;
rob = find_player(char_id[5]);
CHANNEL_D->do_channel(this_object(), "rumor",
"聽説" + char_name[5] + "從五大宗師手中奪走了"
"玄黃紫清丹。");
STORY_D->remove_story("master");
if (rob)
{
gift = new("/clone/ultra/xuanhuang");
if (gift) gift->move(rob, 1);
}
return 0;
}
| 27.125654 | 75 | 0.44779 | [
"object"
] |
02f0bed6c4a3019a2e530b12c39505f4357fdca8 | 2,742 | h | C | src/Parser.h | saintleva/libboolfunccompiler | a881a0ee8a71c6abb3508d670499ae4a526159e5 | [
"MIT"
] | null | null | null | src/Parser.h | saintleva/libboolfunccompiler | a881a0ee8a71c6abb3508d670499ae4a526159e5 | [
"MIT"
] | null | null | null | src/Parser.h | saintleva/libboolfunccompiler | a881a0ee8a71c6abb3508d670499ae4a526159e5 | [
"MIT"
] | null | null | null |
#if !defined(COCO_PARSER_H__)
#define COCO_PARSER_H__
#include "predefined-operations.h"
#include "semantic-data.h"
#include "exceptions.h"
#include <string>
#include <vector>
#include <iostream>
#include <boost/format.hpp>
#include <polishboolfunctions/Operand.h>
#include <polishboolfunctions/Constant.h>
#include <polishboolfunctions/Variable.h>
#include <polishboolfunctions/AbstractOperation.h>
#include <polishboolfunctions/NotOperation.h>
#include <polishboolfunctions/BinaryOperation.h>
#include <polishboolfunctions/RpnFunctionOperation.h>
namespace PBF = PolishBoolFunctions;
#include "Scanner.h"
class Errors {
public:
int count; // number of errors detected
Errors();
void SynErr(int line, int col, int n);
void Error(int line, int col, const wchar_t *s);
void Warning(int line, int col, const wchar_t *s);
void Warning(const wchar_t *s);
void Exception(const wchar_t *s);
}; // Errors
class Parser {
private:
enum {
_EOF=0,
_functionName=1,
_parameterName=2,
_numericalLiteral=3
};
int maxT;
Token *dummyToken;
int errDist;
int minErrDist;
void SynErr(int n);
void Get();
void Expect(int n);
bool StartOf(int s);
void ExpectWeak(int n, int follow);
bool WeakSeparator(int n, int syFol, int repFol);
public:
Scanner *scanner;
Errors *errors;
Token *t; // last recognized token
Token *la; // lookahead token
Sem::FunctionContainer functions;
Parser(Scanner *scanner);
~Parser();
void SemErr(const wchar_t* msg);
void BooleanFunctions();
void FunctionDefinition();
void PostfixFuncDefinition();
void InfixFuncDefinition();
void FunctionHeader(Sem::FunctionHeader& header);
void PostfixExpression(PBF::Rpn& rpn, const Sem::FunctionHeader& header);
void InfixExpression(PBF::Rpn& rpn, const Sem::FunctionHeader& header);
void ParamList(Sem::FunctionHeader::ParamMap& params);
void Operand(PBF::Operand*& operand, const Sem::FunctionHeader& header);
void FunctionNameUsing(PBF::AbstractOperation*& operation);
void AdditiveTerm(PBF::Rpn& rpn, const Sem::FunctionHeader& header);
void PrefixedByOperatorInfixExpression(PBF::Rpn& rpn, const Sem::FunctionHeader& header);
void MultiplicativeTerm(PBF::Rpn& rpn, const Sem::FunctionHeader& header);
void PrefixedByOperatorAdditiveTerm(PBF::Rpn& rpn, const Sem::FunctionHeader& header);
void NegativeTerm(PBF::Rpn& rpn, const Sem::FunctionHeader& header);
void PrefixedByOperatorMultiplicativeTerm(PBF::Rpn& rpn, const Sem::FunctionHeader& header);
void SingleExpression(PBF::Rpn& rpn, const Sem::FunctionHeader& header);
void InfixExpressionList(PBF::Rpn& rpn, const Sem::FunctionHeader& header);
void Literal(PBF::Constant*& value);
void Parse();
}; // end Parser
#endif // !defined(COCO_PARSER_H__)
| 25.867925 | 93 | 0.753465 | [
"vector"
] |
f3154a5b60a1ef34a1cd7f4cffff3b0016629ad7 | 34,680 | h | C | src/crypto/uint256.h | metabasenet/metabasenet | e9bc89b22c11981bcf1d71b63b9b66df3a4e54e1 | [
"MIT"
] | null | null | null | src/crypto/uint256.h | metabasenet/metabasenet | e9bc89b22c11981bcf1d71b63b9b66df3a4e54e1 | [
"MIT"
] | null | null | null | src/crypto/uint256.h | metabasenet/metabasenet | e9bc89b22c11981bcf1d71b63b9b66df3a4e54e1 | [
"MIT"
] | null | null | null | // Copyright (c) 2021-2022 The MetabaseNet developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef CRYPTO_UINT256_H
#define CRYPTO_UINT256_H
#include <boost/multiprecision/cpp_int.hpp>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <string>
#include <vector>
#include "stream/stream.h"
/** Base class without constructors for uint256 and uint160.
* This makes the compiler let u use it in a union.
*/
template <unsigned int BITS>
class base_uint
{
friend class hcode::CStream;
protected:
enum
{
WIDTH = BITS / 32
};
unsigned int pn[WIDTH];
public:
bool operator!() const
{
for (int i = 0; i < WIDTH; i++)
if (pn[i] != 0)
return false;
return true;
}
const base_uint operator~() const
{
base_uint ret;
for (int i = 0; i < WIDTH; i++)
ret.pn[i] = ~pn[i];
return ret;
}
const base_uint operator-() const
{
base_uint ret;
for (int i = 0; i < WIDTH; i++)
ret.pn[i] = ~pn[i];
++ret;
return ret;
}
base_uint& operator=(int8 b)
{
pn[0] = b;
for (int i = 1; i < WIDTH; i++)
pn[i] = 0;
return *this;
}
base_uint& operator=(uint8 b)
{
pn[0] = b;
for (int i = 1; i < WIDTH; i++)
pn[i] = 0;
return *this;
}
base_uint& operator=(int16 b)
{
pn[0] = b;
for (int i = 1; i < WIDTH; i++)
pn[i] = 0;
return *this;
}
base_uint& operator=(uint16 b)
{
pn[0] = b;
for (int i = 1; i < WIDTH; i++)
pn[i] = 0;
return *this;
}
base_uint& operator=(int32 b)
{
pn[0] = b;
for (int i = 1; i < WIDTH; i++)
pn[i] = 0;
return *this;
}
base_uint& operator=(uint32 b)
{
pn[0] = b;
for (int i = 1; i < WIDTH; i++)
pn[i] = 0;
return *this;
}
base_uint& operator=(int64 b)
{
pn[0] = (unsigned int)b;
pn[1] = (int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
return *this;
}
base_uint& operator=(uint64 b)
{
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
return *this;
}
base_uint& operator^=(const base_uint& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] ^= b.pn[i];
return *this;
}
base_uint& operator&=(const base_uint& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] &= b.pn[i];
return *this;
}
base_uint& operator|=(const base_uint& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] |= b.pn[i];
return *this;
}
base_uint& operator^=(uint64 b)
{
pn[0] ^= (unsigned int)b;
pn[1] ^= (unsigned int)(b >> 32);
return *this;
}
base_uint& operator|=(uint64 b)
{
pn[0] |= (unsigned int)b;
pn[1] |= (unsigned int)(b >> 32);
return *this;
}
base_uint& operator<<=(unsigned int shift)
{
base_uint a(*this);
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
int k = shift / 32;
shift = shift % 32;
for (int i = 0; i < WIDTH; i++)
{
if (i + k + 1 < WIDTH && shift != 0)
pn[i + k + 1] |= (a.pn[i] >> (32 - shift));
if (i + k < WIDTH)
pn[i + k] |= (a.pn[i] << shift);
}
return *this;
}
base_uint& operator>>=(unsigned int shift)
{
base_uint a(*this);
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
int k = shift / 32;
shift = shift % 32;
for (int i = 0; i < WIDTH; i++)
{
if (i - k - 1 >= 0 && shift != 0)
pn[i - k - 1] |= (a.pn[i] << (32 - shift));
if (i - k >= 0)
pn[i - k] |= (a.pn[i] >> shift);
}
return *this;
}
base_uint& operator+=(const base_uint& b)
{
uint64 carry = 0;
for (int i = 0; i < WIDTH; i++)
{
uint64 n = carry + pn[i] + b.pn[i];
pn[i] = n & 0xffffffff;
carry = n >> 32;
}
return *this;
}
base_uint& operator-=(const base_uint& b)
{
*this += -b;
return *this;
}
base_uint& operator+=(uint64 b64)
{
base_uint b;
b = b64;
*this += b;
return *this;
}
base_uint& operator-=(uint64 b64)
{
base_uint b;
b = b64;
*this += -b;
return *this;
}
base_uint& operator++()
{
// prefix operator
int i = 0;
while (++pn[i] == 0 && i < WIDTH - 1)
i++;
return *this;
}
const base_uint operator++(int)
{
// postfix operator
const base_uint ret = *this;
++(*this);
return ret;
}
base_uint& operator--()
{
// prefix operator
int i = 0;
while (--pn[i] == -1 && i < WIDTH - 1)
i++;
return *this;
}
const base_uint operator--(int)
{
// postfix operator
const base_uint ret = *this;
--(*this);
return ret;
}
unsigned int& operator[](size_t pos)
{
return pn[pos];
}
const unsigned int& operator[](size_t pos) const
{
return pn[pos];
}
friend inline bool operator<(const base_uint& a, const base_uint& b)
{
for (int i = base_uint::WIDTH - 1; i >= 0; i--)
{
if (a.pn[i] < b.pn[i])
return true;
else if (a.pn[i] > b.pn[i])
return false;
}
return false;
}
friend inline bool operator<=(const base_uint& a, const base_uint& b)
{
for (int i = base_uint::WIDTH - 1; i >= 0; i--)
{
if (a.pn[i] < b.pn[i])
return true;
else if (a.pn[i] > b.pn[i])
return false;
}
return true;
}
friend inline bool operator>(const base_uint& a, const base_uint& b)
{
for (int i = base_uint::WIDTH - 1; i >= 0; i--)
{
if (a.pn[i] > b.pn[i])
return true;
else if (a.pn[i] < b.pn[i])
return false;
}
return false;
}
friend inline bool operator>=(const base_uint& a, const base_uint& b)
{
for (int i = base_uint::WIDTH - 1; i >= 0; i--)
{
if (a.pn[i] > b.pn[i])
return true;
else if (a.pn[i] < b.pn[i])
return false;
}
return true;
}
friend inline bool operator==(const base_uint& a, const base_uint& b)
{
for (int i = 0; i < base_uint::WIDTH; i++)
if (a.pn[i] != b.pn[i])
return false;
return true;
}
friend inline bool operator==(const base_uint& a, uint64 b)
{
if (a.pn[0] != (unsigned int)b)
return false;
if (a.pn[1] != (unsigned int)(b >> 32))
return false;
for (int i = 2; i < base_uint::WIDTH; i++)
if (a.pn[i] != 0)
return false;
return true;
}
friend inline bool operator!=(const base_uint& a, const base_uint& b)
{
return (!(a == b));
}
friend inline bool operator!=(const base_uint& a, uint64 b)
{
return (!(a == b));
}
std::string GetHex() const
{
char psz[sizeof(pn) * 2 + 1];
for (unsigned int i = 0; i < sizeof(pn); i++)
sprintf(psz + i * 2, "%02x", ((unsigned char*)pn)[sizeof(pn) - i - 1]);
return std::string(psz, psz + sizeof(pn) * 2);
}
size_t SetHex(const char* psz)
{
size_t len = 0;
const char* in = psz;
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
// skip leading spaces
while (isspace(*psz))
psz++;
// skip 0x
if (psz[0] == '0' && tolower(psz[1]) == 'x')
psz += 2;
// hex string to uint
static unsigned char phexdigit[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
const char* pbegin = psz;
while (phexdigit[(unsigned char)*psz] || *psz == '0')
psz++;
len = psz - in;
psz--;
unsigned char* p1 = (unsigned char*)pn;
unsigned char* pend = p1 + WIDTH * 4;
while (psz >= pbegin && p1 < pend)
{
*p1 = phexdigit[(unsigned char)*psz--];
if (psz >= pbegin)
{
*p1 |= (phexdigit[(unsigned char)*psz--] << 4);
p1++;
}
}
return len;
}
size_t SetHex(const std::string& str)
{
return SetHex(str.c_str());
}
std::string ToString() const
{
return (GetHex());
}
unsigned char* begin()
{
return (unsigned char*)&pn[0];
}
unsigned char* end()
{
return (unsigned char*)&pn[WIDTH];
}
const unsigned char* begin() const
{
return (unsigned char*)&pn[0];
}
const unsigned char* end() const
{
return (unsigned char*)&pn[WIDTH];
}
static unsigned int size()
{
return sizeof(pn);
}
uint64 Get64(int n = 0) const
{
return pn[2 * n] | (uint64)pn[2 * n + 1] << 32;
}
uint32 Get32(int n = 0) const
{
return pn[n];
}
const base_uint& reverse()
{
unsigned char* front = (unsigned char*)pn;
unsigned char* after = front + sizeof(pn) - 1;
while (front < after)
{
unsigned char temp = *front;
*front = *after;
*after = temp;
front++;
after--;
}
return *this;
}
protected:
void Serialize(hcode::CStream& s, hcode::SaveType&) const
{
//s.Write((char*)pn, sizeof(pn));
unsigned char us[sizeof(pn)];
for (unsigned int i = 0; i < sizeof(pn); i++)
us[i] = ((unsigned char*)pn)[sizeof(pn) - i - 1];
s.Write((char*)us, sizeof(pn));
}
void Serialize(hcode::CStream& s, hcode::LoadType&)
{
//s.Read((char*)pn, sizeof(pn));
unsigned char us[sizeof(pn)];
s.Read((char*)us, sizeof(pn));
for (unsigned int i = 0; i < sizeof(pn); i++)
((unsigned char*)pn)[sizeof(pn) - i - 1] = us[i];
}
void Serialize(hcode::CStream& s, std::size_t& serSize) const
{
(void)s;
serSize += sizeof(pn);
}
friend class uint160;
friend class uint256;
friend class uint224;
friend class uint2048;
friend inline int Testuint256AdHoc(std::vector<std::string> vArg);
};
typedef base_uint<160> base_uint160;
typedef base_uint<256> base_uint256;
typedef base_uint<224> base_uint224;
typedef base_uint<2048> base_uint2048;
//
// uint160 and uint256 could be implemented as templates, but to keep
// compile errors and debugging cleaner, they're copy and pasted.
//
//////////////////////////////////////////////////////////////////////////////
//
// uint160
//
/** 160-bit unsigned integer */
class uint160 : public base_uint160
{
public:
typedef base_uint160 basetype;
uint160()
{
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
}
uint160(const basetype& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = b.pn[i];
}
uint160& operator=(const basetype& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = b.pn[i];
return *this;
}
uint160(uint64 b)
{
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
}
uint160& operator=(uint64 b)
{
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
return *this;
}
explicit uint160(const std::string& str)
{
SetHex(str);
}
explicit uint160(const std::vector<unsigned char>& vch)
{
if (vch.size() == sizeof(pn))
memcpy(pn, &vch[0], sizeof(pn));
else
*this = 0;
}
};
inline bool operator==(const uint160& a, uint64 b)
{
return (base_uint160)a == b;
}
inline bool operator!=(const uint160& a, uint64 b)
{
return (base_uint160)a != b;
}
inline const uint160 operator<<(const base_uint160& a, unsigned int shift)
{
return uint160(a) <<= shift;
}
inline const uint160 operator>>(const base_uint160& a, unsigned int shift)
{
return uint160(a) >>= shift;
}
inline const uint160 operator<<(const uint160& a, unsigned int shift)
{
return uint160(a) <<= shift;
}
inline const uint160 operator>>(const uint160& a, unsigned int shift)
{
return uint160(a) >>= shift;
}
inline const uint160 operator^(const base_uint160& a, const base_uint160& b)
{
return uint160(a) ^= b;
}
inline const uint160 operator&(const base_uint160& a, const base_uint160& b)
{
return uint160(a) &= b;
}
inline const uint160 operator|(const base_uint160& a, const base_uint160& b)
{
return uint160(a) |= b;
}
inline const uint160 operator+(const base_uint160& a, const base_uint160& b)
{
return uint160(a) += b;
}
inline const uint160 operator-(const base_uint160& a, const base_uint160& b)
{
return uint160(a) -= b;
}
inline bool operator<(const base_uint160& a, const uint160& b)
{
return (base_uint160)a < (base_uint160)b;
}
inline bool operator<=(const base_uint160& a, const uint160& b)
{
return (base_uint160)a <= (base_uint160)b;
}
inline bool operator>(const base_uint160& a, const uint160& b)
{
return (base_uint160)a > (base_uint160)b;
}
inline bool operator>=(const base_uint160& a, const uint160& b)
{
return (base_uint160)a >= (base_uint160)b;
}
inline bool operator==(const base_uint160& a, const uint160& b)
{
return (base_uint160)a == (base_uint160)b;
}
inline bool operator!=(const base_uint160& a, const uint160& b)
{
return (base_uint160)a != (base_uint160)b;
}
inline const uint160 operator^(const base_uint160& a, const uint160& b)
{
return (base_uint160)a ^ (base_uint160)b;
}
inline const uint160 operator&(const base_uint160& a, const uint160& b)
{
return (base_uint160)a & (base_uint160)b;
}
inline const uint160 operator|(const base_uint160& a, const uint160& b)
{
return (base_uint160)a | (base_uint160)b;
}
inline const uint160 operator+(const base_uint160& a, const uint160& b)
{
return (base_uint160)a + (base_uint160)b;
}
inline const uint160 operator-(const base_uint160& a, const uint160& b)
{
return (base_uint160)a - (base_uint160)b;
}
inline bool operator<(const uint160& a, const base_uint160& b)
{
return (base_uint160)a < (base_uint160)b;
}
inline bool operator<=(const uint160& a, const base_uint160& b)
{
return (base_uint160)a <= (base_uint160)b;
}
inline bool operator>(const uint160& a, const base_uint160& b)
{
return (base_uint160)a > (base_uint160)b;
}
inline bool operator>=(const uint160& a, const base_uint160& b)
{
return (base_uint160)a >= (base_uint160)b;
}
inline bool operator==(const uint160& a, const base_uint160& b)
{
return (base_uint160)a == (base_uint160)b;
}
inline bool operator!=(const uint160& a, const base_uint160& b)
{
return (base_uint160)a != (base_uint160)b;
}
inline const uint160 operator^(const uint160& a, const base_uint160& b)
{
return (base_uint160)a ^ (base_uint160)b;
}
inline const uint160 operator&(const uint160& a, const base_uint160& b)
{
return (base_uint160)a & (base_uint160)b;
}
inline const uint160 operator|(const uint160& a, const base_uint160& b)
{
return (base_uint160)a | (base_uint160)b;
}
inline const uint160 operator+(const uint160& a, const base_uint160& b)
{
return (base_uint160)a + (base_uint160)b;
}
inline const uint160 operator-(const uint160& a, const base_uint160& b)
{
return (base_uint160)a - (base_uint160)b;
}
inline bool operator<(const uint160& a, const uint160& b)
{
return (base_uint160)a < (base_uint160)b;
}
inline bool operator<=(const uint160& a, const uint160& b)
{
return (base_uint160)a <= (base_uint160)b;
}
inline bool operator>(const uint160& a, const uint160& b)
{
return (base_uint160)a > (base_uint160)b;
}
inline bool operator>=(const uint160& a, const uint160& b)
{
return (base_uint160)a >= (base_uint160)b;
}
inline bool operator==(const uint160& a, const uint160& b)
{
return (base_uint160)a == (base_uint160)b;
}
inline bool operator!=(const uint160& a, const uint160& b)
{
return (base_uint160)a != (base_uint160)b;
}
inline const uint160 operator^(const uint160& a, const uint160& b)
{
return (base_uint160)a ^ (base_uint160)b;
}
inline const uint160 operator&(const uint160& a, const uint160& b)
{
return (base_uint160)a & (base_uint160)b;
}
inline const uint160 operator|(const uint160& a, const uint160& b)
{
return (base_uint160)a | (base_uint160)b;
}
inline const uint160 operator+(const uint160& a, const uint160& b)
{
return (base_uint160)a + (base_uint160)b;
}
inline const uint160 operator-(const uint160& a, const uint160& b)
{
return (base_uint160)a - (base_uint160)b;
}
//////////////////////////////////////////////////////////////////////////////
//
// uint256
//
/** 256-bit unsigned integer */
class uint256 : public base_uint256
{
public:
typedef base_uint256 basetype;
uint256()
{
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
}
uint256(const basetype& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = b.pn[i];
}
uint256(const uint32 h, const base_uint224& l)
{
for (int i = 0; i < WIDTH - 1; i++)
pn[i] = l.pn[i];
pn[WIDTH - 1] = h;
}
uint256(const int8 b)
{
pn[0] = b;
for (int i = 1; i < WIDTH; i++)
pn[i] = 0;
}
uint256(const uint8 b)
{
pn[0] = b;
for (int i = 1; i < WIDTH; i++)
pn[i] = 0;
}
uint256(const int16 b)
{
pn[0] = b;
for (int i = 1; i < WIDTH; i++)
pn[i] = 0;
}
uint256(const uint16 b)
{
pn[0] = b;
for (int i = 1; i < WIDTH; i++)
pn[i] = 0;
}
uint256(const int32 b)
{
pn[0] = b;
for (int i = 1; i < WIDTH; i++)
pn[i] = 0;
}
uint256(const uint32 b)
{
pn[0] = b;
for (int i = 1; i < WIDTH; i++)
pn[i] = 0;
}
uint256(const int64 b)
{
pn[0] = (unsigned int)b;
pn[1] = (int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
}
uint256(const uint64 b)
{
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
}
uint256(const uint64 b[4])
{
for (int i = 0; i < 4; i++)
{
pn[2 * i] = (unsigned int)b[i];
pn[2 * i + 1] = (unsigned int)(b[i] >> 32);
}
}
uint256(const uint32 nBase, const uint32 nPower)
{
uint64 b = (uint64)std::pow(nBase, nPower);
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
}
uint256(const uint16 a, const uint32 b, const uint256& n)
{
for (int i = 0; i < WIDTH - 1; i++)
pn[i] = n.pn[i];
pn[WIDTH - 1] = (((uint32)a << 16) | (b >> 16));
pn[WIDTH - 2] = ((b << 16) | (pn[WIDTH - 2] >> 16));
}
explicit uint256(const std::string& str)
{
SetHex(str);
}
explicit uint256(const std::vector<unsigned char>& vch)
{
if (vch.size() == sizeof(pn))
memcpy(pn, &vch[0], sizeof(pn));
else
*this = 0;
}
explicit uint256(const unsigned char* data, const std::size_t len)
{
if (data && len == sizeof(pn))
memcpy(pn, data, len);
else
*this = 0;
}
uint256& operator=(const basetype& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = b.pn[i];
return *this;
}
uint256& operator=(uint64 b)
{
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
return *this;
}
boost::multiprecision::uint256_t GetMuint256() const
{
boost::multiprecision::uint256_t m;
for (int i = WIDTH - 1; i >= 0; i--)
{
m += Get32(i);
if (i > 0)
{
m <<= 32;
}
}
return m;
}
void SetMuint256(const boost::multiprecision::uint256_t& m)
{
boost::multiprecision::uint256_t t(m);
for (int i = 0; i < WIDTH; i++)
{
pn[i] = (uint32_t)(t & std::numeric_limits<uint32_t>::max());
t >>= 32;
}
}
};
inline bool operator==(const uint256& a, uint64 b)
{
return (base_uint256)a == b;
}
inline bool operator!=(const uint256& a, uint64 b)
{
return (base_uint256)a != b;
}
inline const uint256 operator<<(const base_uint256& a, unsigned int shift)
{
return uint256(a) <<= shift;
}
inline const uint256 operator>>(const base_uint256& a, unsigned int shift)
{
return uint256(a) >>= shift;
}
inline const uint256 operator<<(const uint256& a, unsigned int shift)
{
return uint256(a) <<= shift;
}
inline const uint256 operator>>(const uint256& a, unsigned int shift)
{
return uint256(a) >>= shift;
}
inline const uint256 operator^(const base_uint256& a, const base_uint256& b)
{
return uint256(a) ^= b;
}
inline const uint256 operator&(const base_uint256& a, const base_uint256& b)
{
return uint256(a) &= b;
}
inline const uint256 operator|(const base_uint256& a, const base_uint256& b)
{
return uint256(a) |= b;
}
inline const uint256 operator+(const base_uint256& a, const base_uint256& b)
{
return uint256(a) += b;
}
inline const uint256 operator-(const base_uint256& a, const base_uint256& b)
{
return uint256(a) -= b;
}
inline bool operator<(const base_uint256& a, const uint256& b)
{
return (base_uint256)a < (base_uint256)b;
}
inline bool operator<=(const base_uint256& a, const uint256& b)
{
return (base_uint256)a <= (base_uint256)b;
}
inline bool operator>(const base_uint256& a, const uint256& b)
{
return (base_uint256)a > (base_uint256)b;
}
inline bool operator>=(const base_uint256& a, const uint256& b)
{
return (base_uint256)a >= (base_uint256)b;
}
inline bool operator==(const base_uint256& a, const uint256& b)
{
return (base_uint256)a == (base_uint256)b;
}
inline bool operator!=(const base_uint256& a, const uint256& b)
{
return (base_uint256)a != (base_uint256)b;
}
inline const uint256 operator^(const base_uint256& a, const uint256& b)
{
return (base_uint256)a ^ (base_uint256)b;
}
inline const uint256 operator&(const base_uint256& a, const uint256& b)
{
return (base_uint256)a & (base_uint256)b;
}
inline const uint256 operator|(const base_uint256& a, const uint256& b)
{
return (base_uint256)a | (base_uint256)b;
}
inline const uint256 operator+(const base_uint256& a, const uint256& b)
{
return (base_uint256)a + (base_uint256)b;
}
inline const uint256 operator-(const base_uint256& a, const uint256& b)
{
return (base_uint256)a - (base_uint256)b;
}
inline bool operator<(const uint256& a, const base_uint256& b)
{
return (base_uint256)a < (base_uint256)b;
}
inline bool operator<=(const uint256& a, const base_uint256& b)
{
return (base_uint256)a <= (base_uint256)b;
}
inline bool operator>(const uint256& a, const base_uint256& b)
{
return (base_uint256)a > (base_uint256)b;
}
inline bool operator>=(const uint256& a, const base_uint256& b)
{
return (base_uint256)a >= (base_uint256)b;
}
inline bool operator==(const uint256& a, const base_uint256& b)
{
return (base_uint256)a == (base_uint256)b;
}
inline bool operator!=(const uint256& a, const base_uint256& b)
{
return (base_uint256)a != (base_uint256)b;
}
inline const uint256 operator^(const uint256& a, const base_uint256& b)
{
return (base_uint256)a ^ (base_uint256)b;
}
inline const uint256 operator&(const uint256& a, const base_uint256& b)
{
return (base_uint256)a & (base_uint256)b;
}
inline const uint256 operator|(const uint256& a, const base_uint256& b)
{
return (base_uint256)a | (base_uint256)b;
}
inline const uint256 operator+(const uint256& a, const base_uint256& b)
{
return (base_uint256)a + (base_uint256)b;
}
inline const uint256 operator-(const uint256& a, const base_uint256& b)
{
return (base_uint256)a - (base_uint256)b;
}
inline bool operator<(const uint256& a, const uint256& b)
{
return (base_uint256)a < (base_uint256)b;
}
inline bool operator<=(const uint256& a, const uint256& b)
{
return (base_uint256)a <= (base_uint256)b;
}
inline bool operator>(const uint256& a, const uint256& b)
{
return (base_uint256)a > (base_uint256)b;
}
inline bool operator>=(const uint256& a, const uint256& b)
{
return (base_uint256)a >= (base_uint256)b;
}
inline bool operator==(const uint256& a, const uint256& b)
{
return (base_uint256)a == (base_uint256)b;
}
inline bool operator!=(const uint256& a, const uint256& b)
{
return (base_uint256)a != (base_uint256)b;
}
inline const uint256 operator^(const uint256& a, const uint256& b)
{
return (base_uint256)a ^ (base_uint256)b;
}
inline const uint256 operator&(const uint256& a, const uint256& b)
{
return (base_uint256)a & (base_uint256)b;
}
inline const uint256 operator|(const uint256& a, const uint256& b)
{
return (base_uint256)a | (base_uint256)b;
}
inline const uint256 operator+(const uint256& a, const uint256& b)
{
return (base_uint256)a + (base_uint256)b;
}
inline const uint256 operator-(const uint256& a, const uint256& b)
{
return (base_uint256)a - (base_uint256)b;
}
inline const uint256 operator*(const uint256& a, const uint256& b)
{
boost::multiprecision::uint256_t ma;
for (int i = 7; i >= 0; i--)
{
ma += a.Get32(i);
if (i > 0)
{
ma <<= 32;
}
}
boost::multiprecision::uint256_t mb;
for (int i = 7; i >= 0; i--)
{
mb += b.Get32(i);
if (i > 0)
{
mb <<= 32;
}
}
ma *= mb;
uint256 c;
for (int i = 0; i < 8; i++)
{
c[i] = (uint32_t)(ma & std::numeric_limits<uint32_t>::max());
ma >>= 32;
}
return c;
}
inline const uint256 operator/(const uint256& a, const uint256& b)
{
boost::multiprecision::uint256_t ma;
for (int i = 7; i >= 0; i--)
{
ma += a.Get32(i);
if (i > 0)
{
ma <<= 32;
}
}
boost::multiprecision::uint256_t mb;
for (int i = 7; i >= 0; i--)
{
mb += b.Get32(i);
if (i > 0)
{
mb <<= 32;
}
}
ma /= mb;
uint256 c;
for (int i = 0; i < 8; i++)
{
c[i] = (uint32_t)(ma & std::numeric_limits<uint32_t>::max());
ma >>= 32;
}
return c;
}
//////////////////////////////////////////////////////////////////////////////
//
// uint224
//
/** 224-bit unsigned integer */
class uint224 : public base_uint224
{
public:
typedef base_uint224 basetype;
uint224()
{
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
}
uint224(const basetype& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = b.pn[i];
}
uint224(const uint256& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = b.pn[i];
}
uint224& operator=(const basetype& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = b.pn[i];
return *this;
}
uint224(const uint64 b)
{
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
}
uint224& operator=(uint64 b)
{
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
return *this;
}
explicit uint224(const std::string& str)
{
SetHex(str);
}
explicit uint224(const std::vector<unsigned char>& vch)
{
if (vch.size() == sizeof(pn))
memcpy(pn, &vch[0], sizeof(pn));
else
*this = 0;
}
};
inline bool operator<(const base_uint224& a, const uint224& b)
{
return (base_uint224)a < (base_uint224)b;
}
inline bool operator<=(const base_uint224& a, const uint224& b)
{
return (base_uint224)a <= (base_uint224)b;
}
inline bool operator>(const base_uint224& a, const uint224& b)
{
return (base_uint224)a > (base_uint224)b;
}
inline bool operator>=(const base_uint224& a, const uint224& b)
{
return (base_uint224)a >= (base_uint224)b;
}
inline bool operator==(const base_uint224& a, const uint224& b)
{
return (base_uint224)a == (base_uint224)b;
}
inline bool operator!=(const base_uint224& a, const uint224& b)
{
return (base_uint224)a != (base_uint224)b;
}
inline bool operator<(const uint224& a, const base_uint224& b)
{
return (base_uint224)a < (base_uint224)b;
}
inline bool operator<=(const uint224& a, const base_uint224& b)
{
return (base_uint224)a <= (base_uint224)b;
}
inline bool operator>(const uint224& a, const base_uint224& b)
{
return (base_uint224)a > (base_uint224)b;
}
inline bool operator>=(const uint224& a, const base_uint224& b)
{
return (base_uint224)a >= (base_uint224)b;
}
inline bool operator==(const uint224& a, const base_uint224& b)
{
return (base_uint224)a == (base_uint224)b;
}
inline bool operator!=(const uint224& a, const base_uint224& b)
{
return (base_uint224)a != (base_uint224)b;
}
inline bool operator<(const uint224& a, const uint224& b)
{
return (base_uint224)a < (base_uint224)b;
}
inline bool operator<=(const uint224& a, const uint224& b)
{
return (base_uint224)a <= (base_uint224)b;
}
inline bool operator>(const uint224& a, const uint224& b)
{
return (base_uint224)a > (base_uint224)b;
}
inline bool operator>=(const uint224& a, const uint224& b)
{
return (base_uint224)a >= (base_uint224)b;
}
inline bool operator==(const uint224& a, const uint224& b)
{
return (base_uint224)a == (base_uint224)b;
}
inline bool operator!=(const uint224& a, const uint224& b)
{
return (base_uint224)a != (base_uint224)b;
}
//////////////////////////////////////////////////////////////////////////////
//
// uint2048
//
/** 2048-bit unsigned integer */
class uint2048 : public base_uint2048
{
public:
typedef base_uint2048 basetype;
uint2048()
{
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
}
uint2048(const basetype& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = b.pn[i];
}
uint2048(const uint256& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = b.pn[i];
}
uint2048& operator=(const basetype& b)
{
for (int i = 0; i < WIDTH; i++)
pn[i] = b.pn[i];
return *this;
}
uint2048(const uint64 b)
{
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
}
uint2048& operator=(uint64 b)
{
pn[0] = (unsigned int)b;
pn[1] = (unsigned int)(b >> 32);
for (int i = 2; i < WIDTH; i++)
pn[i] = 0;
return *this;
}
explicit uint2048(const std::string& str)
{
SetHex(str);
}
explicit uint2048(const std::vector<unsigned char>& vch)
{
if (vch.size() == sizeof(pn))
memcpy(pn, &vch[0], sizeof(pn));
else
*this = 0;
}
};
inline bool operator<(const base_uint2048& a, const uint2048& b)
{
return (base_uint2048)a < (base_uint2048)b;
}
inline bool operator<=(const base_uint2048& a, const uint2048& b)
{
return (base_uint2048)a <= (base_uint2048)b;
}
inline bool operator>(const base_uint2048& a, const uint2048& b)
{
return (base_uint2048)a > (base_uint2048)b;
}
inline bool operator>=(const base_uint2048& a, const uint2048& b)
{
return (base_uint2048)a >= (base_uint2048)b;
}
inline bool operator==(const base_uint2048& a, const uint2048& b)
{
return (base_uint2048)a == (base_uint2048)b;
}
inline bool operator!=(const base_uint2048& a, const uint2048& b)
{
return (base_uint2048)a != (base_uint2048)b;
}
inline bool operator<(const uint2048& a, const base_uint2048& b)
{
return (base_uint2048)a < (base_uint2048)b;
}
inline bool operator<=(const uint2048& a, const base_uint2048& b)
{
return (base_uint2048)a <= (base_uint2048)b;
}
inline bool operator>(const uint2048& a, const base_uint2048& b)
{
return (base_uint2048)a > (base_uint2048)b;
}
inline bool operator>=(const uint2048& a, const base_uint2048& b)
{
return (base_uint2048)a >= (base_uint2048)b;
}
inline bool operator==(const uint2048& a, const base_uint2048& b)
{
return (base_uint2048)a == (base_uint2048)b;
}
inline bool operator!=(const uint2048& a, const base_uint2048& b)
{
return (base_uint2048)a != (base_uint2048)b;
}
inline bool operator<(const uint2048& a, const uint2048& b)
{
return (base_uint2048)a < (base_uint2048)b;
}
inline bool operator<=(const uint2048& a, const uint2048& b)
{
return (base_uint2048)a <= (base_uint2048)b;
}
inline bool operator>(const uint2048& a, const uint2048& b)
{
return (base_uint2048)a > (base_uint2048)b;
}
inline bool operator>=(const uint2048& a, const uint2048& b)
{
return (base_uint2048)a >= (base_uint2048)b;
}
inline bool operator==(const uint2048& a, const uint2048& b)
{
return (base_uint2048)a == (base_uint2048)b;
}
inline bool operator!=(const uint2048& a, const uint2048& b)
{
return (base_uint2048)a != (base_uint2048)b;
}
#endif // CRYPTO_UINT256_H
| 24.1841 | 409 | 0.54778 | [
"vector"
] |
f3183fd5c8a3291f3f358a7acede565e08a11a28 | 6,729 | c | C | firmware/imu2_filtered/main.c | suraj-testing2/Shoes_Fence | 2566ab61ec27cd988c159a183eb576e535964b5c | [
"Apache-2.0"
] | 4 | 2015-02-27T09:41:30.000Z | 2020-03-15T04:18:04.000Z | firmware/imu2_filtered/main.c | suraj-testing2/Shoes_Fence | 2566ab61ec27cd988c159a183eb576e535964b5c | [
"Apache-2.0"
] | null | null | null | firmware/imu2_filtered/main.c | suraj-testing2/Shoes_Fence | 2566ab61ec27cd988c159a183eb576e535964b5c | [
"Apache-2.0"
] | 8 | 2015-03-16T07:52:24.000Z | 2021-07-12T11:54:01.000Z | /*
Copyright 2013 Google Inc. 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.
*/
// IMU main (main.c)
#include "IMU.h"
extern void initAdc();
extern void initSerial();
extern void initSpi();
extern void initI2C();
void resetMag();
extern void initiateTx();
// Required variables to allow booting from flash
extern unsigned int hwi_vec_loadstart;
extern unsigned int hwi_vec_loadend;
extern unsigned int hwi_vec_runstart;
extern unsigned int trcdata_loadstart;
extern unsigned int trcdata_loadend;
extern unsigned int trcdata_runstart;
extern unsigned int ramfuncs_loadstart;
extern unsigned int ramfuncs_loadend;
extern unsigned int ramfuncs_runstart;
extern unsigned int econst_loadstart;
extern unsigned int econst_loadend;
extern unsigned int econst_runstart;
extern void DSP28x_usDelay(unsigned long Count);
IMURawData rawData;
IMUConvData convData;
IMUFilterData filterData;
IMUFilterData filterInputData; // used for debug
// Debug mode can be set by sending 'db' plus the mode number:
// db0: autotransmit raw data
// db1: autotransmit converted data
// db2: autotransmit filtered data
char debug_mode = -1;
Uint32 led_state;
Uint32 led1_pattern;
// Pre-main function
void UserInit(void) {
memcpy(&trcdata_runstart, &trcdata_loadstart,
&trcdata_loadend - &trcdata_loadstart);
}
// Main function contains initialization routines then passes control
// to DSP/Bios scheduler
int main(void) {
// Initialize the hwi vector
EALLOW;
memcpy(&hwi_vec_runstart, &hwi_vec_loadstart,
&hwi_vec_loadend - &hwi_vec_loadstart);
EDIS;
// Copy the ram functions
memcpy(&ramfuncs_runstart, &ramfuncs_loadstart,
&ramfuncs_loadend - &ramfuncs_loadstart);
// Copy the constant table
memcpy(&econst_runstart, &econst_loadstart,
&econst_loadend - &econst_loadstart);
// Some initializations first
DINT;
EALLOW;
// Enable the peripherals
DevEmuRegs.PROTSTART = 0x0100;
DevEmuRegs.PROTRANGE = 0x00FF;
// Configure the clocks
// High speed peripheral clock prescaler = 1
SysCtrlRegs.HISPCP.all = 0x0000;
// Low speed peripheral clock prescaler = 4
SysCtrlRegs.LOSPCP.all = 0x0002;
// Enable the ADC and send clock signals there
SysCtrlRegs.PCLKCR0.bit.ADCENCLK = 1;
// Initialize PIE
PieCtrlRegs.PIECTRL.bit.ENPIE = 0;
// Disable and clear all PIE
PieCtrlRegs.PIEIER1.all = 0x0000;
PieCtrlRegs.PIEIER2.all = 0x0000;
PieCtrlRegs.PIEIER3.all = 0x0000;
PieCtrlRegs.PIEIER4.all = 0x0000;
PieCtrlRegs.PIEIER5.all = 0x0000;
PieCtrlRegs.PIEIER6.all = 0x0000;
PieCtrlRegs.PIEIER7.all = 0x0000;
PieCtrlRegs.PIEIER8.all = 0x0000;
PieCtrlRegs.PIEIER9.all = 0x0000;
PieCtrlRegs.PIEIER10.all = 0x0000;
PieCtrlRegs.PIEIER11.all = 0x0000;
PieCtrlRegs.PIEIER12.all = 0x0000;
PieCtrlRegs.PIEIFR1.all = 0x0000;
PieCtrlRegs.PIEIFR2.all = 0x0000;
PieCtrlRegs.PIEIFR3.all = 0x0000;
PieCtrlRegs.PIEIFR4.all = 0x0000;
PieCtrlRegs.PIEIFR5.all = 0x0000;
PieCtrlRegs.PIEIFR6.all = 0x0000;
PieCtrlRegs.PIEIFR7.all = 0x0000;
PieCtrlRegs.PIEIFR8.all = 0x0000;
PieCtrlRegs.PIEIFR9.all = 0x0000;
PieCtrlRegs.PIEIFR10.all = 0x0000;
PieCtrlRegs.PIEIFR11.all = 0x0000;
PieCtrlRegs.PIEIFR12.all = 0x0000;
// Acknowlege all PIE interrupt groups
PieCtrlRegs.PIEACK.all = 0xFFFF;
// Enable PIE
PieCtrlRegs.PIECTRL.bit.ENPIE = 1;
// Setup GPIOs
GpioCtrlRegs.GPAMUX1.all = 0x0000; // GPIO functionality GPIO0-GPIO15
GpioCtrlRegs.GPAMUX2.all = 0x0000; // GPIO functionality GPIO16-GPIO31
GpioCtrlRegs.GPCMUX1.all = 0x0000; // GPIO functionality GPIO64-GPIO79
GpioCtrlRegs.GPCMUX2.all = 0x0000; // GPIO functionality GPIO80-GPIO95
GpioCtrlRegs.GPADIR.all = 0x0000; // GPIO0-GPIO31 are inputs
GpioCtrlRegs.GPBDIR.all = 0x0000; // GPIO32-GPIO63 are inputs
GpioCtrlRegs.GPCDIR.all = 0x0000; // GPIO65-GPIO95 are inputs
// Setup LED outputs
GpioCtrlRegs.GPCDIR.bit.nLED0 = 1;
GpioCtrlRegs.GPCDIR.bit.nLED1 = 1;
GpioDataRegs.GPCSET.bit.nLED0 = 1;
GpioDataRegs.GPCCLEAR.bit.nLED1 = 1;
led_state = 1; // initialized state variable
// Setup mag reset pin
GpioCtrlRegs.GPAPUD.bit.MAG_RESET = 1; // disable pullup
GpioCtrlRegs.GPADIR.bit.MAG_RESET = 1; // set as output
EDIS;
// Initialize magnetometers
resetMag();
// Initialize ADC
initAdc();
// Initialize Serial
initSerial();
// Initialize SPI for 3-axis accel.
initSpi();
// Initialize I2C for serial number and copy into the data structure
initI2C();
EINT;
ERTM;
// Return control to DSP/BIOS
}
// Resets the magetometers using the built-in set/reset straps.
void resetMag() {
GpioDataRegs.GPASET.bit.MAG_RESET = 1;
DELAY_US(10000);
GpioDataRegs.GPACLEAR.bit.MAG_RESET = 1;
DELAY_US(1000);
GpioDataRegs.GPASET.bit.MAG_RESET = 1;
}
#pragma CODE_SECTION(SensorUpdate,"ramfuncs");
void SensorUpdate(void) {
static Uint16 sample;
// Initiate adc conversion
AdcRegs.ADCTRL2.bit.SOC_SEQ1 = 1;
// Autotransmit during debug mode
// Send raw and converted data at the normal ouput rate.
// Send filter debug data at the full internal rate.
if (debug_mode == -1); // normal mode - do nothing
else if (debug_mode == 0 || debug_mode == 1) {
if (sample >= OVERSAMPLE_RATE-1) {
sample = 0;
initiateTx(debug_mode);
} else {
sample++;
}
} else if (debug_mode == 2) {
initiateTx(2);
} else {
debug_mode = -1; // reset to normal mode
}
}
// The led blink pattern is defined over 32 states where each bit in the
// pattern variable determines whether the led is on of off during the current
// state. (1 = on, 0 = off). The state variable is a one-hot encoded Uint32.
#pragma CODE_SECTION(LedBlink,"ramfuncs");
void LedBlink(void) {
if (led_state & LED1_PATTERN)
GpioDataRegs.GPCCLEAR.bit.nLED1 = 1;
else
GpioDataRegs.GPCSET.bit.nLED1 = 1;
// increment state
if (led_state == 0x80000000)
led_state = 1;
else
led_state = led_state << 1;
}
| 29.384279 | 79 | 0.702779 | [
"vector"
] |
f321e5809c97ce382f35f7b4d6f03fec74bd9a0c | 1,349 | h | C | Nuclear Engine/include/Base/BuildConfig.h | Redeaux-Games/REDx-Game-Engine | 7cbc837ed65a3b9728e92942e973dced5e07a40a | [
"Apache-2.0"
] | 65 | 2017-10-26T23:57:13.000Z | 2022-03-28T10:34:15.000Z | Nuclear Engine/include/Base/BuildConfig.h | Redeaux-Games/REDx-Game-Engine | 7cbc837ed65a3b9728e92942e973dced5e07a40a | [
"Apache-2.0"
] | 9 | 2018-01-01T20:31:46.000Z | 2019-08-10T14:14:51.000Z | Nuclear Engine/include/Base/BuildConfig.h | Redeaux-Games/REDx-Game-Engine | 7cbc837ed65a3b9728e92942e973dced5e07a40a | [
"Apache-2.0"
] | 9 | 2018-01-01T20:31:14.000Z | 2021-04-29T22:49:09.000Z | #pragma once
#ifdef _WIN32
#ifdef _WIN64
#define NUCLEAR_PLATFORM_WINDOWS_PC_64BIT
#else
#define NUCLEAR_PLATFORM_WINDOWS_PC_32BIT
#endif
#define NUCLEAR_PLATFORM_WINDOWS_PC
#endif
#ifdef _DEBUG
#define NUCLEAR_CONFIG_DEBUG
#else
#define NUCLEAR_CONFIG_RELEASE
#endif
/*
Building Configs for the whole engine goes here.
Building options:
-NE_USE_CORE_OPENGL
-Builds whole engine in OpenGL Render API (Defines NE_COMPILE_CORE_OPENGL)
-Also uses XShaderCompiler to cross-compile HLSL to GLSL (Defines NE_COMPILE_XSHADERCOMPILER)
-NE_USE_DIRECTX11
-Builds whole engine in DirectX Render API (Defines NE_COMPILE_DIRECTX11)
-Also uses DirectX HLSL Compiler to compile HLSL to DXBC (Defines NE_COMPILE_D3DCOMPILER)
-NE_USE_RUNTIME_RENDER_API
-Builds the engine to use both DirectX11 and OpenGL 3 render APIs, (May have impact on performance so not recommended for release)
-NE_USE_RENDER_API_DEBUG_LAYER
-Enable the Render-API debug layer to trace and detect errors
-NE_USE_PHYSICS3DENGINE
-Enabled Nvidia PhysX Engine integration (not suitable for 2D).
*/
//#include <PhysX\PhysXincluder.h>
//#if !defined(PHYSX_NOT_INCLUDED)
//#define NE_USE_PHYSICS3DENGINE
//#endif
#if defined (NE_USE_PHYSICS3DENGINE) && defined(PHYSX_NOT_INCLUDED)
#error PhysX isnot available
#endif
#define NE_COMPILE_D3DCOMPILER
#define NE_COMPILE_XSHADERCOMPILER
| 27.530612 | 131 | 0.825056 | [
"render"
] |
f327b2bb25f51f29957a83607370574e4e194d39 | 2,351 | h | C | ImageProcessing/Execution/Headers/ImageProcessingManager.h | Eng-RSMY/PorousMediaAnalysis | 922327ad1c8d9729a44abe1dfcf35752589b3429 | [
"MIT"
] | 19 | 2015-03-13T13:21:56.000Z | 2021-09-10T13:17:09.000Z | ImageProcessing/Execution/Headers/ImageProcessingManager.h | Eng-RSMY/PorousMediaAnalysis | 922327ad1c8d9729a44abe1dfcf35752589b3429 | [
"MIT"
] | 2 | 2020-01-13T17:12:24.000Z | 2021-06-15T19:10:11.000Z | ImageProcessing/Execution/Headers/ImageProcessingManager.h | MINATILO/PorousMediaAnalysis | 922327ad1c8d9729a44abe1dfcf35752589b3429 | [
"MIT"
] | 6 | 2017-09-29T18:50:25.000Z | 2021-09-10T13:17:11.000Z | // Copyright (c) 2013 Vasili Baranau
// Distributed under the MIT software license
// See the accompanying file License.txt or http://opensource.org/licenses/MIT
#ifndef Execution_ImageProcessingManager_h
#define Execution_ImageProcessingManager_h
#include "Core/Headers/Macros.h"
#include "ImageProcessing/Model/Headers/Types.h"
#include "ImageProcessing/Model/Headers/Config.h"
namespace Services { class Serializer; }
namespace Services { class ImageResampler; }
namespace Services { class EuclideanDistanceComputer; }
namespace Services { class ContainingBallsAssigner; }
namespace Services { class PoreAndThroatComputer; }
namespace Services { class EmptyPoresRemover; }
namespace Services { class WatershedComputer; }
namespace Services { class ShortestPathComputer; }
namespace Execution
{
class ImageProcessingManager
{
private:
Services::Serializer* serializer;
Services::ImageResampler* imageResampler;
Services::EuclideanDistanceComputer* euclideanDistanceComputer;
Services::ContainingBallsAssigner* containingBallsAssigner;
Services::PoreAndThroatComputer* poreAndThroatComputer;
Services::EmptyPoresRemover* emptyPoresRemover;
Services::WatershedComputer* watershedComputer;
Services::ShortestPathComputer* shortestPathComputer;
Model::Config config;
public:
ImageProcessingManager(Services::Serializer* serializer,
Services::ImageResampler* imageResampler,
Services::EuclideanDistanceComputer* euclideanDistanceComputer,
Services::ContainingBallsAssigner* containingBallsAssigner,
Services::PoreAndThroatComputer* poreAndThroatComputer,
Services::EmptyPoresRemover* emptyPoresRemover,
Services::WatershedComputer* watershedComputer,
Services::ShortestPathComputer* shortestPathComputer);
void SetUserConfig(const Model::Config& userConfig);
void DoAll();
void CalculateEuclideanDistanceTransform();
void RemoveInnerBalls();
void AssignPoresAndThroats();
void CalculateShortestPathDistances();
virtual ~ImageProcessingManager();
private:
DISALLOW_COPY_AND_ASSIGN(ImageProcessingManager);
};
}
#endif /* Execution_ImageProcessingManager_h */
| 34.573529 | 79 | 0.739685 | [
"model"
] |
f33085dca9c4fb5e57081a7ef71c51e55727e0f5 | 4,290 | h | C | WSEExternal/include/Physics/Collide/Filter/hkpCollisionFilter.h | Swyter/wse | 3ad901f1a463139b320c30ea08bdc343358ea6b6 | [
"WTFPL"
] | null | null | null | WSEExternal/include/Physics/Collide/Filter/hkpCollisionFilter.h | Swyter/wse | 3ad901f1a463139b320c30ea08bdc343358ea6b6 | [
"WTFPL"
] | null | null | null | WSEExternal/include/Physics/Collide/Filter/hkpCollisionFilter.h | Swyter/wse | 3ad901f1a463139b320c30ea08bdc343358ea6b6 | [
"WTFPL"
] | null | null | null | /*
*
* Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's
* prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok.
* Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement.
*
*/
#ifndef HK_COLLIDE2_COLLISION_FILTER_H
#define HK_COLLIDE2_COLLISION_FILTER_H
#include <Common/Base/Object/hkReferencedObject.h>
#include <Physics/Collide/Filter/hkpCollidableCollidableFilter.h>
#include <Physics/Collide/Filter/hkpRayCollidableFilter.h>
#include <Physics/Collide/Filter/hkpShapeCollectionFilter.h>
#include <Physics/Collide/Shape/Query/hkpRayShapeCollectionFilter.h>
extern const hkClass hkpCollisionFilterClass;
class hkpBvTreeShape;
/// This class inherits from all four collision filters. These are all the filters used by the system.
/// Typically you inherit from this, to provide an adaptor to a collision filter with some unified behavior.
/// See hkpGroupFilter for an example of this.
class hkpCollisionFilter : public hkReferencedObject,
public hkpCollidableCollidableFilter,
public hkpShapeCollectionFilter,
public hkpRayShapeCollectionFilter,
public hkpRayCollidableFilter
{
public:
HK_DECLARE_REFLECTION();
HK_DECLARE_CLASS_ALLOCATOR( HK_MEMORY_CLASS_CDINFO );
// note that only filters of type HK_FILTER_GROUP will be executed on spu currently
enum hkpFilterType
{
HK_FILTER_UNKNOWN = 0,
HK_FILTER_NULL = 1,
HK_FILTER_GROUP = 2,
HK_FILTER_LIST = 3,
HK_FILTER_CUSTOM = 4,
HK_FILTER_PAIR = 5,
HK_FILTER_CONSTRAINT = 6,
};
public:
hkpCollisionFilter();
/// Checks two collidables
virtual hkBool isCollisionEnabled( const hkpCollidable& a, const hkpCollidable& b ) const = 0;
/// hkpShapeCollectionFilter interface forwarding
virtual hkBool isCollisionEnabled( const hkpCollisionInput& input, const hkpCdBody& a, const hkpCdBody& b, const HK_SHAPE_CONTAINER& bContainer, hkpShapeKey bKey ) const = 0;
/// hkpShapeCollectionFilter interface forwarding
virtual hkBool isCollisionEnabled( const hkpCollisionInput& input, const hkpCdBody& collectionBodyA, const hkpCdBody& collectionBodyB, const HK_SHAPE_CONTAINER& containerShapeA, const HK_SHAPE_CONTAINER& containerShapeB, hkpShapeKey keyA, hkpShapeKey keyB ) const = 0;
/// Default hkpShapeCollectionFilter interface implementation
virtual int numShapeKeyHitsLimitBreached( const hkpCollisionInput& input,
const hkpCdBody& bodyA, const hkpCdBody& bodyB,
const hkpBvTreeShape* bvTreeShapeB, hkAabb& aabb,
hkpShapeKey* shapeKeysInOut,
int shapeKeysCapacity) const;
/// hkpRayShapeCollectionFilter interface forwarding
virtual hkBool isCollisionEnabled( const hkpShapeRayCastInput& aInput, const hkpShape& bShape, const HK_SHAPE_CONTAINER& bContainer, hkpShapeKey bKey ) const = 0;
/// hkpRayCollidableFilter interface forwarding
virtual hkBool isCollisionEnabled( const hkpWorldRayCastInput& a, const hkpCollidable& collidableB ) const = 0;
public:
hkUint32 m_prepad[2];
hkEnum<hkpFilterType,hkUint32> m_type;
hkUint32 m_postpad[3];
public:
hkpCollisionFilter(hkFinishLoadedObjectFlag flag) : hkReferencedObject(flag) {}
};
#endif // HK_COLLIDE2_COLLISION_FILTER_H
/*
* Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20090704)
*
* Confidential Information of Havok. (C) Copyright 1999-2009
* Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
* Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership
* rights, and intellectual property rights in the Havok software remain in
* Havok and/or its suppliers.
*
* Use of this software for evaluation purposes is subject to and indicates
* acceptance of the End User licence Agreement for this product. A copy of
* the license is included with this software and is also available at www.havok.com/tryhavok.
*
*/
| 41.650485 | 271 | 0.756643 | [
"object",
"shape"
] |
f343cf548c1cf1d861a223d057d30438e9c4d7b4 | 4,649 | h | C | math3d.h | BenShallcroft/computerScienceProject | a56eb7f72c30e2f93d8686ce0c5d362104f194c2 | [
"MIT"
] | null | null | null | math3d.h | BenShallcroft/computerScienceProject | a56eb7f72c30e2f93d8686ce0c5d362104f194c2 | [
"MIT"
] | null | null | null | math3d.h | BenShallcroft/computerScienceProject | a56eb7f72c30e2f93d8686ce0c5d362104f194c2 | [
"MIT"
] | null | null | null | /*
Original version by Alastair Channon: a.d.channon@keele.ac.uk
Amended version by Ben Shallcroft: b@shallcroft.com
Amended version adds a matrix function create a skew symmetric matrix. Found in the matrix class.
*/
#ifndef math3d_h
#define math3d_h
#include <iostream>
#include "types.h"
#undef extern_inline
#undef inline
#ifndef DONOTINLINE_math3d
#define extern_inline extern inline
#else // DONOTINLINE_math3d
#define extern_inline // no inlining
#define inline // no inlining
#endif // DONOTINLINE_math3d
class Vector {
public: real x,y,z;
inline Vector operator%(const Vector& v) const; // cross product (nb. % preferred to ^ so that operation takes precedence over + and -)
inline Vector operator+(const Vector& v) const;
inline void operator+=(const Vector& v);
inline Vector operator-(const Vector& v) const;
inline void operator-=(const Vector& v);
inline Vector operator-() const;
inline Vector operator*(const real& d) const; // using "const real&" arguments helps by improving timings with -pg (so making code profiling more accurate / simpler), although may not help once "-O3"/etc. used
inline void operator*=(const real& d);
inline Vector operator/(const real& d) const;
inline void operator/=(const real& d);
inline void zero();
inline void normalize(); // make unit length
// not implemented: == != [] () ...
};
extern_inline std::ostream& operator<< (std::ostream& out, const Vector& v);
extern_inline Vector operator*(const real& d, const Vector& v);
extern_inline Vector multiplyElements(const Vector& v1, const Vector& v2);
extern_inline real dotProduct(const Vector& v1, const Vector& v2);
extern_inline Vector vectorTripleProduct(const Vector& a, const Vector& b, const Vector& c);
class Matrix {
public: real m00,m01,m02, m10,m11,m12, m20,m21,m22;
inline Vector operator*(const Vector& v) const;
inline Matrix operator*(const Matrix& M) const;
inline Matrix operator*(const real& d) const;
inline void operator*=(const real& d);
inline Matrix operator/(const real& d) const;
inline void operator/=(const real& d);
inline Matrix operator+(const Matrix& M) const;
inline void operator+=(const Matrix& M);
inline Matrix operator-(const Matrix& M) const;
inline void operator-=(const Matrix& M);
inline Matrix operator-() const;
inline void zero();
inline void reorthogonalize(int& reorthogonalizeRotor);
inline void reorthogonalize();
inline bool isZero(); //Added by Ben Shallcroft
};
extern_inline std::ostream& operator<< (std::ostream& out, const Matrix& M);
extern_inline Matrix operator*(const real& d, const Matrix& M);
extern_inline Matrix transpose(const Matrix& M);
extern_inline Matrix inverse(const Matrix& M);
extern_inline Matrix multiply(const Vector& v0, const Vector& v1); // returns v0 * transpose(v1), which is a Matrix (3x1 * 1x3 => 3x3)
extern_inline Vector multiply(const Vector& v, const Matrix& M); // returns transpose(transpose(v) * M), which is a Vector (transpose[1x3 * 3x3 => 1x3])
extern_inline Matrix tildaMultiply(const Vector& v, const Matrix& M); // returns tilda(v) * M = v % each column of M
extern_inline void tildaMultiply(const Vector& v, const Matrix& M, Matrix& rM); // sets rM = tilda(v) * M = v % each column of M
extern_inline Matrix tildaMultiply(const Matrix& M, const Vector& v); // returns M * tilda(v) // = -transpose(tilda(v)*transpose(M))
extern_inline void tildaMultiply(const Matrix& M, const Vector& v, Matrix& rM); // sets rM = M * tilda(v) // = -transpose(tilda(v)*transpose(M))
extern_inline Vector transposeMultiply(const Matrix& M, const Vector& v); // returns transpose(M) * v
extern_inline Matrix rotationMatrix(const real& angle, const Vector& axis, bool axisIsUnitLength=false); // return the matrix that rotates angle radians about axis
//Added by Ben Shallcroft
extern_inline Matrix skewSymmetric(const Vector& v);
// convenience functions to output to std::cout
extern_inline void o(const Vector& v);
extern_inline void o(const Matrix& M);
// convenience function(s) that return(s) 0 if and only if none of the values within their arguments are bad (eg. nan, infinite or "subnormal" floating point values). this is easy to extend into classes using these types/classes
extern_inline int bad(const real& d);
extern_inline int bad(const Vector& v);
extern_inline int bad(const Matrix& M);
#ifndef DONOTINLINE_math3d
#include "math3d.cc"
#endif // DONOTINLINE_math3d
#endif // math3d_h
| 46.959596 | 229 | 0.7094 | [
"vector"
] |
f3471483f184c720a22eab91ad25dbd516895f32 | 14,941 | h | C | desktop/core/ext-py/cx_Oracle-6.4.1/src/cxoModule.h | yetsun/hue | 2e48f0cc70e233ee0e1b40733d4b2a18d8836c66 | [
"Apache-2.0"
] | 5,079 | 2015-01-01T03:39:46.000Z | 2022-03-31T07:38:22.000Z | desktop/core/ext-py/cx_Oracle-6.4.1/src/cxoModule.h | yetsun/hue | 2e48f0cc70e233ee0e1b40733d4b2a18d8836c66 | [
"Apache-2.0"
] | 1,623 | 2015-01-01T08:06:24.000Z | 2022-03-30T19:48:52.000Z | desktop/core/ext-py/cx_Oracle-6.4.1/src/cxoModule.h | yetsun/hue | 2e48f0cc70e233ee0e1b40733d4b2a18d8836c66 | [
"Apache-2.0"
] | 2,033 | 2015-01-04T07:18:02.000Z | 2022-03-28T19:55:47.000Z | //-----------------------------------------------------------------------------
// Copyright 2018, Oracle and/or its affiliates. All rights reserved.
//
// Licensed under BSD license (see LICENSE.txt).
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// cxoModule.h
// Include file for all cx_Oracle source files.
//-----------------------------------------------------------------------------
#include <Python.h>
#include <structmember.h>
#include <time.h>
#include <dpi.h>
// define integer macros/methods for Python 3.x
#ifndef PyInt_Check
#define PyInt_Check PyLong_Check
#define PyInt_FromLong PyLong_FromLong
#define PyInt_AsLong PyLong_AsLong
#endif
// use the bytes methods in cx_Oracle and define them as the equivalent string
// type methods as is done in Python 2.6
#ifndef PyBytes_Check
#define PyBytes_Type PyString_Type
#define PyBytes_AS_STRING PyString_AS_STRING
#define PyBytes_GET_SIZE PyString_GET_SIZE
#define PyBytes_Check PyString_Check
#define PyBytes_FromStringAndSize PyString_FromStringAndSize
#endif
// define string/binary types and methods
#if PY_MAJOR_VERSION >= 3
#define CXO_BASE_EXCEPTION NULL
#define cxoPyTypeBinary PyBytes_Type
#define cxoPyTypeString PyUnicode_Type
#define cxoPyString_fromAscii(str) \
PyUnicode_DecodeASCII(str, strlen(str), NULL)
#define cxoPyString_fromEncodedString(buffer, numBytes, encoding, errors) \
PyUnicode_Decode(buffer, numBytes, encoding, errors)
#else
#define CXO_BASE_EXCEPTION PyExc_StandardError
#define cxoPyTypeBinary PyBuffer_Type
#define cxoPyTypeString PyString_Type
#define cxoPyString_fromAscii(str) \
PyBytes_FromString(str)
#define cxoPyString_fromEncodedString(buffer, numBytes, encoding, errors) \
PyBytes_FromStringAndSize(buffer, numBytes)
#endif
// define macros to get the build version as a string and the driver name
#define xstr(s) str(s)
#define str(s) #s
#define CXO_BUILD_VERSION_STRING xstr(CXO_BUILD_VERSION)
#define CXO_DRIVER_NAME "cx_Oracle : "CXO_BUILD_VERSION_STRING
// define macro for clearing buffers
#define cxoBuffer_clear(buf) Py_CLEAR((buf)->obj)
//-----------------------------------------------------------------------------
// Forward Declarations
//-----------------------------------------------------------------------------
typedef struct cxoBuffer cxoBuffer;
typedef struct cxoError cxoError;
typedef struct cxoConnection cxoConnection;
typedef struct cxoCursor cxoCursor;
typedef struct cxoDeqOptions cxoDeqOptions;
typedef struct cxoEnqOptions cxoEnqOptions;
typedef struct cxoFuture cxoFuture;
typedef struct cxoLob cxoLob;
typedef struct cxoMessage cxoMessage;
typedef struct cxoMessageQuery cxoMessageQuery;
typedef struct cxoMessageRow cxoMessageRow;
typedef struct cxoMessageTable cxoMessageTable;
typedef struct cxoMsgProps cxoMsgProps;
typedef struct cxoObject cxoObject;
typedef struct cxoObjectAttr cxoObjectAttr;
typedef struct cxoObjectType cxoObjectType;
typedef struct cxoSessionPool cxoSessionPool;
typedef struct cxoSubscr cxoSubscr;
typedef struct cxoVar cxoVar;
typedef struct cxoVarType cxoVarType;
//-----------------------------------------------------------------------------
// Globals
//-----------------------------------------------------------------------------
// exception objects
extern PyObject *cxoWarningException;
extern PyObject *cxoErrorException;
extern PyObject *cxoInterfaceErrorException;
extern PyObject *cxoDatabaseErrorException;
extern PyObject *cxoDataErrorException;
extern PyObject *cxoOperationalErrorException;
extern PyObject *cxoIntegrityErrorException;
extern PyObject *cxoInternalErrorException;
extern PyObject *cxoProgrammingErrorException;
extern PyObject *cxoNotSupportedErrorException;
// type objects
extern PyTypeObject cxoPyTypeBfileVar;
extern PyTypeObject cxoPyTypeBinaryVar;
extern PyTypeObject cxoPyTypeBlobVar;
extern PyTypeObject cxoPyTypeBooleanVar;
extern PyTypeObject cxoPyTypeClobVar;
extern PyTypeObject cxoPyTypeConnection;
extern PyTypeObject cxoPyTypeCursor;
extern PyTypeObject cxoPyTypeCursorVar;
extern PyTypeObject cxoPyTypeDateTimeVar;
extern PyTypeObject cxoPyTypeDeqOptions;
extern PyTypeObject cxoPyTypeEnqOptions;
extern PyTypeObject cxoPyTypeError;
extern PyTypeObject cxoPyTypeFixedCharVar;
extern PyTypeObject cxoPyTypeFixedNcharVar;
extern PyTypeObject cxoPyTypeFuture;
extern PyTypeObject cxoPyTypeIntervalVar;
extern PyTypeObject cxoPyTypeLob;
extern PyTypeObject cxoPyTypeLongBinaryVar;
extern PyTypeObject cxoPyTypeLongStringVar;
extern PyTypeObject cxoPyTypeMsgProps;
extern PyTypeObject cxoPyTypeMessage;
extern PyTypeObject cxoPyTypeMessageQuery;
extern PyTypeObject cxoPyTypeMessageRow;
extern PyTypeObject cxoPyTypeMessageTable;
extern PyTypeObject cxoPyTypeNativeFloatVar;
extern PyTypeObject cxoPyTypeNativeIntVar;
extern PyTypeObject cxoPyTypeNcharVar;
extern PyTypeObject cxoPyTypeNclobVar;
extern PyTypeObject cxoPyTypeNumberVar;
extern PyTypeObject cxoPyTypeObject;
extern PyTypeObject cxoPyTypeObjectAttr;
extern PyTypeObject cxoPyTypeObjectType;
extern PyTypeObject cxoPyTypeObjectVar;
extern PyTypeObject cxoPyTypeRowidVar;
extern PyTypeObject cxoPyTypeSessionPool;
extern PyTypeObject cxoPyTypeStringVar;
extern PyTypeObject cxoPyTypeSubscr;
extern PyTypeObject cxoPyTypeTimestampVar;
// datetime types
extern PyTypeObject *cxoPyTypeDate;
extern PyTypeObject *cxoPyTypeDateTime;
// ODPI-C context and version information
extern dpiContext *cxoDpiContext;
extern dpiVersionInfo cxoClientVersionInfo;
// future object
extern cxoFuture *cxoFutureObj;
//-----------------------------------------------------------------------------
// Transforms
//-----------------------------------------------------------------------------
typedef enum {
CXO_TRANSFORM_NONE = 0,
CXO_TRANSFORM_BINARY,
CXO_TRANSFORM_BFILE,
CXO_TRANSFORM_BLOB,
CXO_TRANSFORM_BOOLEAN,
CXO_TRANSFORM_CLOB,
CXO_TRANSFORM_CURSOR,
CXO_TRANSFORM_DATE,
CXO_TRANSFORM_DATETIME,
CXO_TRANSFORM_DECIMAL,
CXO_TRANSFORM_FIXED_CHAR,
CXO_TRANSFORM_FIXED_NCHAR,
CXO_TRANSFORM_FLOAT,
CXO_TRANSFORM_INT,
CXO_TRANSFORM_LONG_BINARY,
CXO_TRANSFORM_LONG_INT,
CXO_TRANSFORM_LONG_STRING,
CXO_TRANSFORM_NATIVE_DOUBLE,
CXO_TRANSFORM_NATIVE_FLOAT,
CXO_TRANSFORM_NATIVE_INT,
CXO_TRANSFORM_NCLOB,
CXO_TRANSFORM_NSTRING,
CXO_TRANSFORM_OBJECT,
CXO_TRANSFORM_ROWID,
CXO_TRANSFORM_STRING,
CXO_TRANSFORM_TIMEDELTA,
CXO_TRANSFORM_TIMESTAMP,
CXO_TRANSFORM_TIMESTAMP_LTZ,
CXO_TRANSFORM_UNSUPPORTED
} cxoTransformNum;
//-----------------------------------------------------------------------------
// Structures
//-----------------------------------------------------------------------------
struct cxoBuffer {
const char *ptr;
uint32_t numCharacters;
uint32_t size;
PyObject *obj;
};
struct cxoError {
PyObject_HEAD
long code;
unsigned offset;
PyObject *message;
PyObject *context;
char isRecoverable;
};
struct cxoConnection {
PyObject_HEAD
dpiConn *handle;
cxoSessionPool *sessionPool;
PyObject *inputTypeHandler;
PyObject *outputTypeHandler;
PyObject *username;
PyObject *dsn;
PyObject *version;
dpiEncodingInfo encodingInfo;
int autocommit;
};
struct cxoCursor {
PyObject_HEAD
dpiStmt *handle;
dpiStmtInfo stmtInfo;
cxoConnection *connection;
PyObject *statement;
PyObject *statementTag;
PyObject *bindVariables;
PyObject *fetchVariables;
PyObject *rowFactory;
PyObject *inputTypeHandler;
PyObject *outputTypeHandler;
uint32_t arraySize;
uint32_t bindArraySize;
uint32_t fetchArraySize;
int setInputSizes;
uint64_t rowCount;
uint32_t fetchBufferRowIndex;
uint32_t numRowsInFetchBuffer;
int moreRowsToFetch;
int isScrollable;
int fixupRefCursor;
int isOpen;
};
struct cxoDeqOptions {
PyObject_HEAD
dpiDeqOptions *handle;
const char *encoding;
};
struct cxoEnqOptions {
PyObject_HEAD
dpiEnqOptions *handle;
const char *encoding;
};
struct cxoFuture {
PyObject_HEAD
int contextManagerClose;
int dmlReturningArray;
};
struct cxoLob {
PyObject_HEAD
cxoConnection *connection;
dpiOracleTypeNum oracleTypeNum;
dpiLob *handle;
};
struct cxoMessage {
PyObject_HEAD
cxoSubscr *subscription;
dpiEventType type;
PyObject *dbname;
PyObject *txId;
PyObject *tables;
PyObject *queries;
PyObject *queueName;
PyObject *consumerName;
int registered;
};
struct cxoMessageQuery {
PyObject_HEAD
uint64_t id;
dpiOpCode operation;
PyObject *tables;
};
struct cxoMessageRow {
PyObject_HEAD
PyObject *rowid;
dpiOpCode operation;
};
struct cxoMessageTable {
PyObject_HEAD
PyObject *name;
PyObject *rows;
dpiOpCode operation;
};
struct cxoMsgProps {
PyObject_HEAD
dpiMsgProps *handle;
const char *encoding;
};
struct cxoObject {
PyObject_HEAD
cxoObjectType *objectType;
dpiObject *handle;
};
struct cxoObjectAttr {
PyObject_HEAD
PyObject *name;
dpiObjectAttr *handle;
dpiOracleTypeNum oracleTypeNum;
cxoTransformNum transformNum;
cxoObjectType *type;
};
struct cxoObjectType {
PyObject_HEAD
dpiObjectType *handle;
PyObject *schema;
PyObject *name;
PyObject *attributes;
PyObject *attributesByName;
cxoConnection *connection;
dpiOracleTypeNum elementOracleTypeNum;
cxoTransformNum elementTransformNum;
PyObject *elementType;
char isCollection;
};
struct cxoSessionPool {
PyObject_HEAD
dpiPool *handle;
uint32_t minSessions;
uint32_t maxSessions;
uint32_t sessionIncrement;
uint32_t cacheSize;
dpiEncodingInfo encodingInfo;
int homogeneous;
int externalAuth;
PyObject *username;
PyObject *dsn;
PyObject *name;
PyTypeObject *connectionType;
};
struct cxoSubscr {
PyObject_HEAD
dpiSubscr *handle;
cxoConnection *connection;
PyObject *callback;
uint32_t namespace;
PyObject *name;
uint32_t protocol;
PyObject *ipAddress;
uint32_t port;
uint32_t timeout;
uint32_t operations;
uint32_t qos;
uint8_t groupingClass;
uint32_t groupingValue;
uint8_t groupingType;
uint64_t id;
};
struct cxoVar {
PyObject_HEAD
dpiVar *handle;
dpiData *data;
cxoConnection *connection;
PyObject *inConverter;
PyObject *outConverter;
cxoObjectType *objectType;
const char *encodingErrors;
uint32_t allocatedElements;
uint32_t size;
uint32_t bufferSize;
int isArray;
int isValueSet;
int getReturnedData;
cxoVarType *type;
};
struct cxoVarType {
cxoTransformNum transformNum;
PyTypeObject *pythonType;
uint32_t size;
};
//-----------------------------------------------------------------------------
// Functions
//-----------------------------------------------------------------------------
int cxoBuffer_fromObject(cxoBuffer *buf, PyObject *obj, const char *encoding);
int cxoBuffer_init(cxoBuffer *buf);
int cxoConnection_isConnected(cxoConnection *conn);
int cxoCursor_performBind(cxoCursor *cursor);
int cxoCursor_setBindVariables(cxoCursor *cursor, PyObject *parameters,
unsigned numElements, unsigned arrayPos, int deferTypeAssignment);
cxoDeqOptions *cxoDeqOptions_new(cxoConnection *connection);
cxoEnqOptions *cxoEnqOptions_new(cxoConnection *connection);
cxoError *cxoError_newFromInfo(dpiErrorInfo *errorInfo);
int cxoError_raiseAndReturnInt(void);
PyObject *cxoError_raiseAndReturnNull(void);
int cxoError_raiseFromInfo(dpiErrorInfo *errorInfo);
PyObject *cxoError_raiseFromString(PyObject *exceptionType,
const char *message);
PyObject *cxoLob_new(cxoConnection *connection, dpiOracleTypeNum oracleTypeNum,
dpiLob *handle);
cxoMsgProps *cxoMsgProps_new(cxoConnection*);
int cxoObject_internalExtend(cxoObject *obj, PyObject *sequence);
PyObject *cxoObject_new(cxoObjectType *objectType, dpiObject *handle);
cxoObjectAttr *cxoObjectAttr_new(cxoConnection *connection,
dpiObjectAttr *handle);
cxoObjectType *cxoObjectType_new(cxoConnection *connection,
dpiObjectType *handle);
cxoObjectType *cxoObjectType_newByName(cxoConnection *connection,
PyObject *name);
void cxoSubscr_callback(cxoSubscr *subscr, dpiSubscrMessage *message);
PyObject *cxoTransform_dateFromTicks(PyObject *args);
int cxoTransform_fromPython(cxoTransformNum transformNum, PyObject *pyValue,
dpiDataBuffer *dbValue, cxoBuffer *buffer, const char *encoding,
const char *nencoding, cxoVar *var, uint32_t arrayPos);
cxoTransformNum cxoTransform_getNumFromDataTypeInfo(dpiDataTypeInfo *info);
cxoTransformNum cxoTransform_getNumFromType(PyTypeObject *type);
cxoTransformNum cxoTransform_getNumFromValue(PyObject *value, int plsql);
void cxoTransform_getTypeInfo(cxoTransformNum transformNum,
dpiOracleTypeNum *oracleTypeNum, dpiNativeTypeNum *nativeTypeNum);
int cxoTransform_init(void);
PyObject *cxoTransform_timestampFromTicks(PyObject *args);
PyObject *cxoTransform_toPython(cxoTransformNum transformNum,
cxoConnection *connection, cxoObjectType *objType,
dpiDataBuffer *dbValue, const char *encodingErrors);
PyObject *cxoUtils_formatString(const char *format, PyObject *args);
const char *cxoUtils_getAdjustedEncoding(const char *encoding);
int cxoUtils_getBooleanValue(PyObject *obj, int defaultValue, int *value);
int cxoUtils_getModuleAndName(PyTypeObject *type, PyObject **module,
PyObject **name);
int cxoUtils_initializeDPI(void);
cxoVarType *cxoVarType_fromDataTypeInfo(dpiDataTypeInfo *info);
cxoVarType *cxoVarType_fromPythonType(PyTypeObject *type);
cxoVarType *cxoVarType_fromPythonValue(PyObject *value, int *isArray,
Py_ssize_t *size, Py_ssize_t *numElements, int plsql);
int cxoVar_bind(cxoVar *var, cxoCursor *cursor, PyObject *name, uint32_t pos);
int cxoVar_check(PyObject *object);
PyObject *cxoVar_getSingleValue(cxoVar *var, dpiData *data, uint32_t arrayPos);
PyObject *cxoVar_getValue(cxoVar *var, uint32_t arrayPos);
cxoVar *cxoVar_new(cxoCursor *cursor, Py_ssize_t numElements, cxoVarType *type,
Py_ssize_t size, int isArray, cxoObjectType *objType);
cxoVar *cxoVar_newByType(cxoCursor *cursor, PyObject *value,
uint32_t numElements);
cxoVar *cxoVar_newByValue(cxoCursor *cursor, PyObject *value,
Py_ssize_t numElements);
int cxoVar_setValue(cxoVar *var, uint32_t arrayPos, PyObject *value);
| 30.997925 | 79 | 0.713004 | [
"object"
] |
f34948b3af536570874bf1fe64bdbd21e2a6c10a | 21,709 | c | C | mpich-3.3/src/mpi/datatype/type_struct.c | ucd-plse/mpi-error-prop | 4367df88bcdc4d82c9a65b181d0e639d04962503 | [
"BSD-3-Clause"
] | 3 | 2020-05-22T04:17:23.000Z | 2020-07-17T04:14:25.000Z | mpich-3.3/src/mpi/datatype/type_struct.c | ucd-plse/mpi-error-prop | 4367df88bcdc4d82c9a65b181d0e639d04962503 | [
"BSD-3-Clause"
] | null | null | null | mpich-3.3/src/mpi/datatype/type_struct.c | ucd-plse/mpi-error-prop | 4367df88bcdc4d82c9a65b181d0e639d04962503 | [
"BSD-3-Clause"
] | null | null | null | /* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil ; -*- */
/*
*
* (C) 2001 by Argonne National Laboratory.
* See COPYRIGHT in top-level directory.
*/
#include "mpiimpl.h"
#include "datatype.h"
/* -- Begin Profiling Symbol Block for routine MPI_Type_struct */
#if defined(HAVE_PRAGMA_WEAK)
#pragma weak MPI_Type_struct = PMPI_Type_struct
#elif defined(HAVE_PRAGMA_HP_SEC_DEF)
#pragma _HP_SECONDARY_DEF PMPI_Type_struct MPI_Type_struct
#elif defined(HAVE_PRAGMA_CRI_DUP)
#pragma _CRI duplicate MPI_Type_struct as PMPI_Type_struct
#elif defined(HAVE_WEAK_ATTRIBUTE)
int MPI_Type_struct(int count, int *array_of_blocklengths,
MPI_Aint * array_of_displacements,
MPI_Datatype * array_of_types, MPI_Datatype * newtype)
__attribute__ ((weak, alias("PMPI_Type_struct")));
#endif
/* -- End Profiling Symbol Block */
/* Define MPICH_MPI_FROM_PMPI if weak symbols are not supported to build
the MPI routines */
#ifndef MPICH_MPI_FROM_PMPI
#undef MPI_Type_struct
#define MPI_Type_struct PMPI_Type_struct
static MPI_Aint MPII_Type_struct_alignsize(int count,
const MPI_Datatype * oldtype_array,
const MPI_Aint * displacement_array);
/* MPII_Type_struct_alignsize
*
* This function guesses at how the C compiler would align a structure
* with the given components.
*
* It uses these configure-time defines to do its magic:
* - HAVE_MAX_INTEGER_ALIGNMENT - maximum byte alignment of integers
* - HAVE_MAX_FP_ALIGNMENT - maximum byte alignment of floating points
* - HAVE_MAX_LONG_DOUBLE_FP_ALIGNMENT - maximum byte alignment with long
* doubles (if different from FP_ALIGNMENT)
* - HAVE_MAX_DOUBLE_FP_ALIGNMENT - maximum byte alignment with doubles (if
* long double is different from FP_ALIGNMENT)
* - HAVE_DOUBLE_POS_ALIGNMENT - indicates that structures with doubles
* are aligned differently if double isn't
* at displacement 0 (e.g. PPC32/64).
* - HAVE_LLINT_POS_ALIGNMENT - same as above, for MPI_LONG_LONG_INT
*
* The different FP, DOUBLE, LONG_DOUBLE alignment case are necessary for
* Cygwin on X86 (because long_double is 12 bytes, so double and long double
* have different natural alignments). Linux on X86, however, does not have
* different rules for this case.
*/
static MPI_Aint MPII_Type_struct_alignsize(int count,
const MPI_Datatype * oldtype_array,
const MPI_Aint * displacement_array)
{
int i;
MPI_Aint max_alignsize = 0, tmp_alignsize, derived_alignsize = 0;
for (i = 0; i < count; i++) {
/* shouldn't be called with an LB or UB, but we'll handle it nicely */
if (oldtype_array[i] == MPI_LB || oldtype_array[i] == MPI_UB)
continue;
else if (HANDLE_GET_KIND(oldtype_array[i]) == HANDLE_KIND_BUILTIN) {
tmp_alignsize = MPIR_Datatype_get_basic_size(oldtype_array[i]);
#ifdef HAVE_DOUBLE_ALIGNMENT_EXCEPTION
if (oldtype_array[i] == MPI_DOUBLE) {
tmp_alignsize = HAVE_DOUBLE_ALIGNMENT_EXCEPTION;
}
#endif
switch (oldtype_array[i]) {
case MPI_FLOAT:
case MPI_DOUBLE:
case MPI_LONG_DOUBLE:
#if defined(HAVE_MAX_LONG_DOUBLE_FP_ALIGNMENT) && \
defined(HAVE_MAX_DOUBLE_FP_ALIGNMENT)
if (oldtype_array[i] == MPI_LONG_DOUBLE) {
if (tmp_alignsize > HAVE_MAX_LONG_DOUBLE_FP_ALIGNMENT)
tmp_alignsize = HAVE_MAX_LONG_DOUBLE_FP_ALIGNMENT;
} else if (oldtype_array[i] == MPI_DOUBLE) {
if (tmp_alignsize > HAVE_MAX_DOUBLE_FP_ALIGNMENT)
tmp_alignsize = HAVE_MAX_DOUBLE_FP_ALIGNMENT;
} else {
/* HAVE_MAX_FP_ALIGNMENT may not be defined, hence commented */
/*
* if (tmp_alignsize > HAVE_MAX_FP_ALIGNMENT)
* tmp_alignsize = HAVE_MAX_FP_ALIGNMENT;
*/
}
#elif defined(HAVE_MAX_FP_ALIGNMENT)
if (tmp_alignsize > HAVE_MAX_FP_ALIGNMENT)
tmp_alignsize = HAVE_MAX_FP_ALIGNMENT;
#endif
#ifdef HAVE_DOUBLE_POS_ALIGNMENT
/* sort of a hack, but so is this rule */
if (oldtype_array[i] == MPI_DOUBLE && displacement_array[i] != (MPI_Aint) 0) {
tmp_alignsize = 4;
}
#endif
break;
default:
#ifdef HAVE_MAX_INTEGER_ALIGNMENT
if (tmp_alignsize > HAVE_MAX_INTEGER_ALIGNMENT)
tmp_alignsize = HAVE_MAX_INTEGER_ALIGNMENT;
#endif
break;
#ifdef HAVE_LLINT_POS_ALIGNMENT
if (oldtype_array[i] == MPI_LONG_LONG_INT &&
displacement_array[i] != (MPI_Aint) 0) {
tmp_alignsize = 4;
}
#endif
}
} else {
MPIR_Datatype *dtp;
MPIR_Datatype_get_ptr(oldtype_array[i], dtp);
tmp_alignsize = dtp->alignsize;
if (derived_alignsize < tmp_alignsize)
derived_alignsize = tmp_alignsize;
}
if (max_alignsize < tmp_alignsize)
max_alignsize = tmp_alignsize;
}
return max_alignsize;
}
/*@
MPIR_Type_struct - create a struct datatype
Input Parameters:
+ count - number of blocks in vector
. blocklength_array - number of elements in each block
. displacement_array - offsets of blocks from start of type in bytes
- oldtype_array - types (using handle) of datatypes on which vector is based
Output Parameters:
. newtype - handle of new struct datatype
Return Value:
MPI_SUCCESS on success, MPI errno on failure.
@*/
#undef FUNCNAME
#define FUNCNAME MPIR_Type_struct
#undef FCNAME
#define FCNAME MPL_QUOTE(FUNCNAME)
int MPIR_Type_struct(int count,
const int *blocklength_array,
const MPI_Aint * displacement_array,
const MPI_Datatype * oldtype_array, MPI_Datatype * newtype)
{
int mpi_errno = MPI_SUCCESS;
int i, old_are_contig = 1, definitely_not_contig = 0;
int found_sticky_lb = 0, found_sticky_ub = 0, found_true_lb = 0,
found_true_ub = 0, found_el_type = 0, found_lb = 0, found_ub = 0;
MPI_Aint el_sz = 0;
MPI_Aint size = 0;
MPI_Datatype el_type = MPI_DATATYPE_NULL;
MPI_Aint true_lb_disp = 0, true_ub_disp = 0, sticky_lb_disp = 0,
sticky_ub_disp = 0, lb_disp = 0, ub_disp = 0;
MPIR_Datatype *new_dtp;
if (count == 0)
return MPII_Type_zerolen(newtype);
#ifdef MPID_STRUCT_DEBUG
MPII_Datatype_printf(oldtype_array[0], 1, displacement_array[0], blocklength_array[0], 1);
for (i = 1; i < count; i++) {
MPII_Datatype_printf(oldtype_array[i], 1, displacement_array[i], blocklength_array[i], 0);
}
#endif
/* allocate new datatype object and handle */
new_dtp = (MPIR_Datatype *) MPIR_Handle_obj_alloc(&MPIR_Datatype_mem);
/* --BEGIN ERROR HANDLING-- */
if (!new_dtp) {
mpi_errno = MPIR_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE,
"MPIR_Type_struct", __LINE__, MPI_ERR_OTHER, "**nomem", 0);
return mpi_errno;
}
/* --END ERROR HANDLING-- */
/* handle is filled in by MPIR_Handle_obj_alloc() */
MPIR_Object_set_ref(new_dtp, 1);
new_dtp->is_permanent = 0;
new_dtp->is_committed = 0;
new_dtp->attributes = NULL;
new_dtp->cache_id = 0;
new_dtp->name[0] = 0;
new_dtp->contents = NULL;
new_dtp->dataloop = NULL;
new_dtp->dataloop_size = -1;
new_dtp->dataloop_depth = -1;
/* check for junk struct with all zero blocks */
for (i = 0; i < count; i++)
if (blocklength_array[i] != 0)
break;
if (i == count) {
MPIR_Handle_obj_free(&MPIR_Datatype_mem, new_dtp);
return MPII_Type_zerolen(newtype);
}
new_dtp->max_contig_blocks = 0;
for (i = 0; i < count; i++) {
int is_builtin = (HANDLE_GET_KIND(oldtype_array[i]) == HANDLE_KIND_BUILTIN);
MPI_Aint tmp_lb, tmp_ub, tmp_true_lb, tmp_true_ub;
MPI_Aint tmp_el_sz;
MPI_Datatype tmp_el_type;
MPIR_Datatype *old_dtp = NULL;
int old_is_contig;
/* Interpreting typemap to not include 0 blklen things, including
* MPI_LB and MPI_UB. -- Rob Ross, 10/31/2005
*/
if (blocklength_array[i] == 0)
continue;
if (is_builtin) {
tmp_el_sz = MPIR_Datatype_get_basic_size(oldtype_array[i]);
tmp_el_type = oldtype_array[i];
MPII_DATATYPE_BLOCK_LB_UB((MPI_Aint) (blocklength_array[i]),
displacement_array[i],
0, tmp_el_sz, tmp_el_sz, tmp_lb, tmp_ub);
tmp_true_lb = tmp_lb;
tmp_true_ub = tmp_ub;
size += tmp_el_sz * blocklength_array[i];
new_dtp->max_contig_blocks++;
} else {
MPIR_Datatype_get_ptr(oldtype_array[i], old_dtp);
/* Ensure that "builtin_element_size" fits into an int datatype. */
MPIR_Ensure_Aint_fits_in_int(old_dtp->builtin_element_size);
tmp_el_sz = old_dtp->builtin_element_size;
tmp_el_type = old_dtp->basic_type;
MPII_DATATYPE_BLOCK_LB_UB((MPI_Aint) blocklength_array[i],
displacement_array[i],
old_dtp->lb, old_dtp->ub, old_dtp->extent, tmp_lb, tmp_ub);
tmp_true_lb = tmp_lb + (old_dtp->true_lb - old_dtp->lb);
tmp_true_ub = tmp_ub + (old_dtp->true_ub - old_dtp->ub);
size += old_dtp->size * blocklength_array[i];
new_dtp->max_contig_blocks += old_dtp->max_contig_blocks;
}
/* element size and type */
if (oldtype_array[i] != MPI_LB && oldtype_array[i] != MPI_UB) {
if (found_el_type == 0) {
el_sz = tmp_el_sz;
el_type = tmp_el_type;
found_el_type = 1;
} else if (el_sz != tmp_el_sz) {
el_sz = -1;
el_type = MPI_DATATYPE_NULL;
} else if (el_type != tmp_el_type) {
/* Q: should we set el_sz = -1 even though the same? */
el_type = MPI_DATATYPE_NULL;
}
}
/* keep lowest sticky lb */
if ((oldtype_array[i] == MPI_LB) || (!is_builtin && old_dtp->has_sticky_lb)) {
if (!found_sticky_lb) {
found_sticky_lb = 1;
sticky_lb_disp = tmp_lb;
} else if (sticky_lb_disp > tmp_lb) {
sticky_lb_disp = tmp_lb;
}
}
/* keep highest sticky ub */
if ((oldtype_array[i] == MPI_UB) || (!is_builtin && old_dtp->has_sticky_ub)) {
if (!found_sticky_ub) {
found_sticky_ub = 1;
sticky_ub_disp = tmp_ub;
} else if (sticky_ub_disp < tmp_ub) {
sticky_ub_disp = tmp_ub;
}
}
/* keep lowest lb/true_lb and highest ub/true_ub
*
* note: checking for contiguity at the same time, to avoid
* yet another pass over the arrays
*/
if (oldtype_array[i] != MPI_UB && oldtype_array[i] != MPI_LB) {
if (!found_true_lb) {
found_true_lb = 1;
true_lb_disp = tmp_true_lb;
} else if (true_lb_disp > tmp_true_lb) {
/* element starts before previous */
true_lb_disp = tmp_true_lb;
definitely_not_contig = 1;
}
if (!found_lb) {
found_lb = 1;
lb_disp = tmp_lb;
} else if (lb_disp > tmp_lb) {
/* lb before previous */
lb_disp = tmp_lb;
definitely_not_contig = 1;
}
if (!found_true_ub) {
found_true_ub = 1;
true_ub_disp = tmp_true_ub;
} else if (true_ub_disp < tmp_true_ub) {
true_ub_disp = tmp_true_ub;
} else {
/* element ends before previous ended */
definitely_not_contig = 1;
}
if (!found_ub) {
found_ub = 1;
ub_disp = tmp_ub;
} else if (ub_disp < tmp_ub) {
ub_disp = tmp_ub;
} else {
/* ub before previous */
definitely_not_contig = 1;
}
}
MPIR_Datatype_is_contig(oldtype_array[i], &old_is_contig);
if (!old_is_contig)
old_are_contig = 0;
}
new_dtp->n_builtin_elements = -1; /* TODO */
new_dtp->builtin_element_size = el_sz;
new_dtp->basic_type = el_type;
new_dtp->has_sticky_lb = found_sticky_lb;
new_dtp->true_lb = true_lb_disp;
new_dtp->lb = (found_sticky_lb) ? sticky_lb_disp : lb_disp;
new_dtp->has_sticky_ub = found_sticky_ub;
new_dtp->true_ub = true_ub_disp;
new_dtp->ub = (found_sticky_ub) ? sticky_ub_disp : ub_disp;
new_dtp->alignsize = MPII_Type_struct_alignsize(count, oldtype_array, displacement_array);
new_dtp->extent = new_dtp->ub - new_dtp->lb;
if ((!found_sticky_lb) && (!found_sticky_ub)) {
/* account for padding */
MPI_Aint epsilon = (new_dtp->alignsize > 0) ?
new_dtp->extent % ((MPI_Aint) (new_dtp->alignsize)) : 0;
if (epsilon) {
new_dtp->ub += ((MPI_Aint) (new_dtp->alignsize) - epsilon);
new_dtp->extent = new_dtp->ub - new_dtp->lb;
}
}
new_dtp->size = size;
/* new type is contig for N types if its size and extent are the
* same, and the old type was also contiguous, and we didn't see
* something noncontiguous based on true ub/ub.
*/
if (((MPI_Aint) (new_dtp->size) == new_dtp->extent) &&
old_are_contig && (!definitely_not_contig)) {
new_dtp->is_contig = 1;
} else {
new_dtp->is_contig = 0;
}
*newtype = new_dtp->handle;
return mpi_errno;
}
#undef FUNCNAME
#define FUNCNAME MPIR_Type_struct_impl
#undef FCNAME
#define FCNAME MPL_QUOTE(FUNCNAME)
int MPIR_Type_struct_impl(int count, const int *array_of_blocklengths,
const MPI_Aint * array_of_displacements,
const MPI_Datatype * array_of_types, MPI_Datatype * newtype)
{
int mpi_errno = MPI_SUCCESS;
MPI_Datatype new_handle;
int i, *ints;
MPIR_Datatype *new_dtp;
MPIR_CHKLMEM_DECL(1);
mpi_errno = MPIR_Type_struct(count,
array_of_blocklengths,
array_of_displacements, array_of_types, &new_handle);
if (mpi_errno)
MPIR_ERR_POP(mpi_errno);
MPIR_CHKLMEM_MALLOC(ints, int *, (count + 1) * sizeof(int), mpi_errno, "contents integer array",
MPL_MEM_BUFFER);
ints[0] = count;
for (i = 0; i < count; i++) {
ints[i + 1] = array_of_blocklengths[i];
}
MPIR_Datatype_get_ptr(new_handle, new_dtp);
mpi_errno = MPIR_Datatype_set_contents(new_dtp, MPI_COMBINER_STRUCT, count + 1, /* ints (count, blocklengths) */
count, /* aints (displacements) */
count, /* types */
ints, array_of_displacements, array_of_types);
if (mpi_errno)
MPIR_ERR_POP(mpi_errno);
MPIR_OBJ_PUBLISH_HANDLE(*newtype, new_handle);
fn_exit:
MPIR_CHKLMEM_FREEALL();
return mpi_errno;
fn_fail:
goto fn_exit;
}
#endif
#undef FUNCNAME
#define FUNCNAME MPI_Type_struct
#undef FCNAME
#define FCNAME MPL_QUOTE(FUNCNAME)
/*@
MPI_Type_struct - Creates a struct datatype
Input Parameters:
+ count - number of blocks (integer) -- also number of
entries in arrays array_of_types ,
array_of_displacements and array_of_blocklengths
. array_of_blocklengths - number of elements in each block (array)
. array_of_displacements - byte displacement of each block (array)
- array_of_types - type of elements in each block (array
of handles to datatype objects)
Output Parameters:
. newtype - new datatype (handle)
.N Deprecated
The replacement for this routine is 'MPI_Type_create_struct'
Notes:
If an upperbound is set explicitly by using the MPI datatype 'MPI_UB', the
corresponding index must be positive.
The MPI standard originally made vague statements about padding and alignment;
this was intended to allow the simple definition of structures that could
be sent with a count greater than one. For example,
.vb
struct { int a; char b; } foo;
.ve
may have 'sizeof(foo) > sizeof(int) + sizeof(char)'; for example,
'sizeof(foo) == 2*sizeof(int)'. The initial version of the MPI standard
defined the extent of a datatype as including an `epsilon` that would have
allowed an implementation to make the extent an MPI datatype
for this structure equal to '2*sizeof(int)'.
However, since different systems might define different paddings, there was
much discussion by the MPI Forum about what was the correct value of
epsilon, and one suggestion was to define epsilon as zero.
This would have been the best thing to do in MPI 1.0, particularly since
the 'MPI_UB' type allows the user to easily set the end of the structure.
Unfortunately, this change did not make it into the final document.
Currently, this routine does not add any padding, since the amount of
padding needed is determined by the compiler that the user is using to
build their code, not the compiler used to construct the MPI library.
A later version of MPICH may provide for some natural choices of padding
(e.g., multiple of the size of the largest basic member), but users are
advised to never depend on this, even with vendor MPI implementations.
Instead, if you define a structure datatype and wish to send or receive
multiple items, you should explicitly include an 'MPI_UB' entry as the
last member of the structure. For example, the following code can be used
for the structure foo
.vb
blen[0] = 1; array_of_displacements[0] = 0; oldtypes[0] = MPI_INT;
blen[1] = 1; array_of_displacements[1] = &foo.b - &foo; oldtypes[1] = MPI_CHAR;
blen[2] = 1; array_of_displacements[2] = sizeof(foo); oldtypes[2] = MPI_UB;
MPI_Type_struct(3, blen, array_of_displacements, oldtypes, &newtype);
.ve
.N ThreadSafe
.N Fortran
.N Errors
.N MPI_SUCCESS
.N MPI_ERR_TYPE
.N MPI_ERR_COUNT
.N MPI_ERR_EXHAUSTED
@*/
int MPI_Type_struct(int count,
int *array_of_blocklengths,
MPI_Aint * array_of_displacements,
MPI_Datatype * array_of_types, MPI_Datatype * newtype)
{
int mpi_errno = MPI_SUCCESS;
MPIR_FUNC_TERSE_STATE_DECL(MPID_STATE_MPI_TYPE_STRUCT);
MPIR_ERRTEST_INITIALIZED_ORDIE();
MPID_THREAD_CS_ENTER(GLOBAL, MPIR_THREAD_GLOBAL_ALLFUNC_MUTEX);
MPIR_FUNC_TERSE_ENTER(MPID_STATE_MPI_TYPE_STRUCT);
/* Validate parameters, especially handles needing to be converted */
#ifdef HAVE_ERROR_CHECKING
{
MPID_BEGIN_ERROR_CHECKS;
{
int i;
MPIR_Datatype *datatype_ptr;
MPIR_ERRTEST_COUNT(count, mpi_errno);
if (count > 0) {
MPIR_ERRTEST_ARGNULL(array_of_blocklengths, "array_of_blocklengths", mpi_errno);
MPIR_ERRTEST_ARGNULL(array_of_displacements, "array_of_displacements", mpi_errno);
MPIR_ERRTEST_ARGNULL(array_of_types, "array_of_types", mpi_errno);
}
for (i = 0; i < count; i++) {
MPIR_ERRTEST_ARGNEG(array_of_blocklengths[i], "blocklength", mpi_errno);
MPIR_ERRTEST_DATATYPE(array_of_types[i], "datatype[i]", mpi_errno);
if (array_of_types[i] != MPI_DATATYPE_NULL &&
HANDLE_GET_KIND(array_of_types[i]) != HANDLE_KIND_BUILTIN) {
MPIR_Datatype_get_ptr(array_of_types[i], datatype_ptr);
MPIR_Datatype_valid_ptr(datatype_ptr, mpi_errno);
}
}
if (mpi_errno != MPI_SUCCESS)
goto fn_fail;
}
MPID_END_ERROR_CHECKS;
}
#endif /* HAVE_ERROR_CHECKING */
/* ... body of routine ... */
mpi_errno =
MPIR_Type_struct_impl(count, array_of_blocklengths, array_of_displacements, array_of_types,
newtype);
if (mpi_errno)
goto fn_fail;
/* ... end of body of routine ... */
fn_exit:
MPIR_FUNC_TERSE_EXIT(MPID_STATE_MPI_TYPE_STRUCT);
MPID_THREAD_CS_EXIT(GLOBAL, MPIR_THREAD_GLOBAL_ALLFUNC_MUTEX);
return mpi_errno;
fn_fail:
/* --BEGIN ERROR HANDLING-- */
#ifdef HAVE_ERROR_CHECKING
{
mpi_errno =
MPIR_Err_create_code(mpi_errno, MPIR_ERR_RECOVERABLE, FCNAME, __LINE__, MPI_ERR_OTHER,
"**mpi_type_struct", "**mpi_type_struct %d %p %p %p %p", count,
array_of_blocklengths, array_of_displacements, array_of_types,
newtype);
}
#endif
mpi_errno = MPIR_Err_return_comm(NULL, FCNAME, mpi_errno);
goto fn_exit;
/* --END ERROR HANDLING-- */
}
| 36.982964 | 120 | 0.614077 | [
"object",
"vector"
] |
f358ec110a5a80153fd931768c65431b814bc23e | 2,633 | c | C | src/comet2.c | j8takagi/YACASL2 | 12c73be7ca883738a4faa16737751f1531e5d9ac | [
"MIT"
] | 11 | 2015-01-15T03:51:20.000Z | 2021-12-29T09:38:39.000Z | src/comet2.c | j8takagi/YACASL2 | 12c73be7ca883738a4faa16737751f1531e5d9ac | [
"MIT"
] | null | null | null | src/comet2.c | j8takagi/YACASL2 | 12c73be7ca883738a4faa16737751f1531e5d9ac | [
"MIT"
] | 1 | 2018-04-18T01:02:53.000Z | 2018-04-18T01:02:53.000Z | #include "package.h"
#include "exec.h"
#include "load.h"
/**
* comet2コマンドのオプション
*/
static struct option longopts[] = {
{"trace", no_argument, NULL, 't'},
{"tracearithmetic", no_argument, NULL, 't'},
{"tracelogical", no_argument, NULL, 'T'},
{"dump", no_argument, NULL, 'd'},
{"monitor", no_argument, NULL, 'm'},
{"memorysize", required_argument, NULL, 'M'},
{"clocks", required_argument, NULL, 'C'},
{"version", no_argument, NULL, 'v' },
{"help", no_argument, NULL, 'h'},
{0, 0, 0, 0},
};
/**
* @brief comet2コマンドのメイン
*
* @return 正常終了時は0、異常終了時は1
*
* @param argc コマンドライン引数の数
* @param *argv[] コマンドライン引数の配列
*/
int main(int argc, char *argv[])
{
int memsize = DEFAULT_MEMSIZE;
int clocks = DEFAULT_CLOCKS;
int opt = 0;
int stat = 0;
const char *version = PACKAGE_VERSION;
const char *cmdversion = "comet2 of YACASL2 version %s\n";
const char *usage = "Usage: %s [-tTdmvh] [-M <MEMORYSIZE>] [-C <CLOCKS>] FILE\n";
/* エラーの定義 */
cerr_init();
addcerrlist_load();
addcerrlist_exec();
/* オプションの処理 */
while((opt = getopt_long(argc, argv, "tTdmM:C:vh", longopts, NULL)) != -1) {
switch(opt) {
case 't':
execmode.trace = true;
break;
case 'T':
execmode.trace = true;
execmode.logical = true;
break;
case 'd':
execmode.dump = true;
break;
case 'm':
execmode.monitor = true;
break;
case 'M':
memsize = atoi(optarg);
break;
case 'C':
clocks = atoi(optarg);
break;
case 'v':
fprintf(stdout, cmdversion, version);
goto comet2fin;
case 'h':
fprintf(stdout, usage, argv[0]);
goto comet2fin;
case '?':
fprintf(stderr, usage, argv[0]);
setcerr(212, ""); /* invalid option */
goto comet2fin;
}
}
if(argv[optind] == NULL) {
setcerr(211, ""); /* object file not specified */
fprintf(stderr, "comet2 error - %d: %s\n", cerr->num, cerr->msg);
goto comet2fin;
}
reset(memsize, clocks); /* COMET II仮想マシンのリセット */
execptr->start = 0;
execptr->end = loadassemble(argv[optind], execptr->start);
if(execptr->end > 0 && cerr->num == 0) {
exec(); /* プログラム実行 */
}
shutdown(); /* COMET II仮想マシンのシャットダウン */
comet2fin:
if(cerr->num > 0) {
stat = 1;
}
freecerr(); /* エラーの解放 */
return stat;
}
| 26.867347 | 85 | 0.511204 | [
"object"
] |
f36a3daab207324385379a62e06b35b87509f91d | 265 | h | C | header/includes.h | milovangudelj/hash-code-template-cxx | 3321c9003f323e587311afe2e0cf730888e2b8b9 | [
"Apache-2.0"
] | null | null | null | header/includes.h | milovangudelj/hash-code-template-cxx | 3321c9003f323e587311afe2e0cf730888e2b8b9 | [
"Apache-2.0"
] | null | null | null | header/includes.h | milovangudelj/hash-code-template-cxx | 3321c9003f323e587311afe2e0cf730888e2b8b9 | [
"Apache-2.0"
] | null | null | null | #ifndef includes_h
#define includes_h
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <cmath>
#include <map>
#include <utility>
#include <algorithm>
#include "../fmt/core.h"
#include "../fmt/colors.h"
#endif | 15.588235 | 26 | 0.716981 | [
"vector"
] |
b3e04abf47d7eb909a361371e083e1034b4dfc9b | 5,905 | h | C | include/sketch/ssi.h | spapadias/sketch | ebf601024ec6fa389153a2186a761761c14cc575 | [
"MIT"
] | 1 | 2021-04-29T18:13:46.000Z | 2021-04-29T18:13:46.000Z | include/sketch/ssi.h | spapadias/sketch | ebf601024ec6fa389153a2186a761761c14cc575 | [
"MIT"
] | null | null | null | include/sketch/ssi.h | spapadias/sketch | ebf601024ec6fa389153a2186a761761c14cc575 | [
"MIT"
] | null | null | null | #ifndef SKETCH_SETSKETCH_INDEX_H__
#define SKETCH_SETSKETCH_INDEX_H__
#include <cstdint>
#include <map>
#include <vector>
#include <cstdio>
#include <iostream>
#include "xxHash/xxh3.h"
#include "flat_hash_map/flat_hash_map.hpp"
#include "sketch/div.h"
#include "sketch/integral.h"
namespace sketch {
using std::uint64_t;
using std::uint32_t;
namespace lsh {
static inline constexpr uint64_t _wymum(uint64_t x, uint64_t y) {
__uint128_t l = x;
l *= y;
return l ^ (l >> 64);
}
// call wyhash64_seed before calling wyhash64
static inline constexpr uint64_t wyhash64_stateless(uint64_t *seed) {
*seed += UINT64_C(0x60bee2bee120fc15);
return _wymum(*seed ^ 0xe7037ed1a0b428dbull, *seed);
}
template<typename KeyT=uint64_t, typename IdT=uint32_t>
struct SetSketchIndex {
/*
* Maintains an LSH index over a set of sketches
*
*/
private:
size_t m_;
using HashMap = ska::flat_hash_map<KeyT, std::vector<IdT>>;
using HashV = std::vector<HashMap>;
std::vector<HashV> packed_maps_;
std::vector<uint64_t> regs_per_reg_;
size_t total_ids_ = 0;
public:
using key_type = KeyT;
using id_type = IdT;
size_t m() const {return m_;}
size_t size() const {return total_ids_;}
size_t ntables() const {return packed_maps_.size();}
template<typename IT, typename Alloc, typename OIT, typename OAlloc>
SetSketchIndex(size_t m, const std::vector<IT, Alloc> &nperhashes, const std::vector<OIT, OAlloc> &nperrows): m_(m) {
if(nperhashes.size() != nperrows.size()) throw std::invalid_argument("SetSketchIndex requires nperrows and nperhashes have the same size");
for(size_t i = 0, e = nperhashes.size(); i < e; ++i) {
const IT v = nperhashes[i];
regs_per_reg_.push_back(v);
OIT v2 = nperrows[i];
OIT v1 = m_ / v;
if(v2 <= 0) v2 = v1;
packed_maps_.emplace_back(v2);
}
}
template<typename IT, typename Alloc>
SetSketchIndex(size_t m, const std::vector<IT, Alloc> &nperhashes): m_(m) {
for(const auto v: nperhashes) {
if(size_t(v) > m) throw std::invalid_argument("Cannot create LSH keys with v > m");
regs_per_reg_.push_back(v);
packed_maps_.emplace_back(HashV(m_ / v));
}
}
SetSketchIndex(size_t m, bool densified=false): m_(m) {
uint64_t rpr = 1;
const size_t nrpr = densified ? m: size_t(ilog2(sketch::integral::roundup(m)));
regs_per_reg_.reserve(nrpr);
packed_maps_.reserve(nrpr);
for(;rpr <= m_;) {
regs_per_reg_.push_back(rpr);
packed_maps_.emplace_back(HashV(m_ / rpr));
if(densified) {
++rpr;
} else {
rpr <<= 1;
}
}
}
template<typename Sketch>
void update(const Sketch &item) {
if(item.size() != m_) throw std::invalid_argument(std::string("Item has wrong size: ") + std::to_string(item.size()) + ", expected" + std::to_string(m_));
const auto my_id = total_ids_++;
const size_t n_subtable_lists = regs_per_reg_.size();
for(size_t i = 0; i < n_subtable_lists; ++i) {
auto &subtab = packed_maps_[i];
const size_t nsubs = subtab.size();
for(size_t j = 0; j < nsubs; ++j) {
KeyT myhash = hash_index(item, i, j);
subtab[j][myhash].push_back(my_id);
}
}
}
template<typename Sketch>
KeyT hash_index(const Sketch &item, size_t i, size_t j) const {
const size_t nreg = regs_per_reg_.at(i);
static constexpr size_t ITEMSIZE = sizeof(std::decay_t<decltype(item[0])>);
if(nreg * packed_maps_[i].size() == m_)
return XXH3_64bits(&item[nreg * j], nreg * ITEMSIZE);
uint64_t seed = (i << 32) | j;
XXH64_state_t state;
XXH64_reset(&state, seed);
const schism::Schismatic<uint32_t> div(m_);
for(size_t ri = 0; ri < nreg; ++ri) {
XXH64_update(&state, &item[div.mod(wyhash64_stateless(&seed))], ITEMSIZE);
}
return XXH64_digest(&state);
}
template<typename Sketch>
std::pair<std::vector<IdT>, std::vector<uint32_t>>
query_candidates(const Sketch &item, size_t maxcand, size_t starting_idx = size_t(-1)) const {
if(starting_idx == size_t(-1)) starting_idx = regs_per_reg_.size();
/*
* Returns ids matching input minhash sketches, in order from most specific/least sensitive
* to least specific/most sensitive
* Can be then used, along with sketches, to select nearest neighbors
* */
ska::flat_hash_map<IdT, uint32_t> rset;
std::vector<IdT> passing_ids;
std::vector<uint32_t> items_per_row;
rset.reserve(maxcand); passing_ids.reserve(maxcand); items_per_row.reserve(starting_idx);
for(std::ptrdiff_t i = starting_idx;--i >= 0;) {
auto &m = packed_maps_[i];
const size_t nsubs = m.size();
const size_t items_before = passing_ids.size();
for(size_t j = 0; j < nsubs; ++j) {
KeyT myhash = hash_index(item, i, j);
auto it = m[j].find(myhash);
if(it == m[j].end()) continue;
for(const auto id: it->second) {
auto rit2 = rset.find(id);
if(rit2 == rset.end()) {
rset.emplace(id, 1);
passing_ids.push_back(id);
} else ++rit2->second;
}
}
items_per_row.push_back(passing_ids.size() - items_before);
if(rset.size() >= maxcand) break;
}
return std::make_pair(passing_ids, items_per_row);
}
};
} // lsh
using lsh::SetSketchIndex;
} // namespace sketch
#endif /* #ifndef SKETCH_SETSKETCH_INDEX_H__ */
| 36.90625 | 162 | 0.596613 | [
"vector"
] |
b3e2e1775d0f6218d31ab859a4eea43e9f20b929 | 1,563 | h | C | include/DB.h | amrtechguy/My-Clinic | 440cdb1a534391b6f2b79c3002d3b36f686a0bea | [
"MIT"
] | null | null | null | include/DB.h | amrtechguy/My-Clinic | 440cdb1a534391b6f2b79c3002d3b36f686a0bea | [
"MIT"
] | null | null | null | include/DB.h | amrtechguy/My-Clinic | 440cdb1a534391b6f2b79c3002d3b36f686a0bea | [
"MIT"
] | null | null | null | #ifndef DB_H
#define DB_H
#include <string>
#include <vector>
#include <sqlite3.h>
class DB
{
private:
std::string db_file;
sqlite3 *db_handle;
std::string sql_query;
void *data;
int last_insert_rowid;
private:
bool connect();
std::string get_query_key();
friend int store_selected_data(void* data, int argc, char** argv, char** azColName);
public:
DB();
void query(std::string sql);
auto get_data()
{
return (static_cast<std::vector<std::vector<std::string>>*>(data));
}
int get_last_insert_rowid();
void reset();
~DB();
};
static int store_selected_data(void* data, int argc, char** argv, char** azColName)
{
std::vector<std::string> single_row;
// store the column names
if ((static_cast<std::vector<std::vector<std::string>>*>(data))->size() == 0)
{
// store column names
for (int i {0}; i < argc; i++)
{
single_row.push_back(azColName[i]);
}
(static_cast<std::vector<std::vector<std::string>>*>(data))->push_back(single_row);
single_row.erase(single_row.begin(), single_row.end());
// store the first row
for (int i{ 0 }; i < argc; i++)
{
single_row.push_back(argv[i]);
}
(static_cast<std::vector<std::vector<std::string>>*>(data))->push_back(single_row);
single_row.erase(single_row.begin(), single_row.end());
}
else
{
// store the rest of rows
for (int i {0}; i < argc; i++)
{
single_row.push_back(argv[i]);
}
(static_cast<std::vector<std::vector<std::string>>*>(data))->push_back(single_row);
single_row.erase(single_row.begin(), single_row.end());
}
return 0;
}
#endif
| 20.84 | 85 | 0.664107 | [
"vector"
] |
b3f10d19d8be7f1e884c539ac8913a9bcee32232 | 1,089 | h | C | Gems/Maestro/Code/Source/Cinematics/SelectTrack.h | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-09-13T00:01:12.000Z | 2021-09-13T00:01:12.000Z | Gems/Maestro/Code/Source/Cinematics/SelectTrack.h | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/Maestro/Code/Source/Cinematics/SelectTrack.h | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T11:07:25.000Z | 2021-07-20T11:07:25.000Z | /*
* 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
*
*/
#ifndef CRYINCLUDE_CRYMOVIE_SELECTTRACK_H
#define CRYINCLUDE_CRYMOVIE_SELECTTRACK_H
#pragma once
#include "IMovieSystem.h"
#include "AnimTrack.h"
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/** Select track. Used to select Cameras on a Director's Camera Track
*/
class CSelectTrack
: public TAnimTrack<ISelectKey>
{
public:
AZ_CLASS_ALLOCATOR(CSelectTrack, AZ::SystemAllocator, 0);
AZ_RTTI(CSelectTrack, "{D05D53BF-86D1-4D38-A3C6-4EFC09C16431}", IAnimTrack);
AnimValueType GetValueType();
void GetKeyInfo(int key, const char*& description, float& duration);
void SerializeKey(ISelectKey& key, XmlNodeRef& keyNode, bool bLoading);
static void Reflect(AZ::ReflectContext* context);
};
#endif // CRYINCLUDE_CRYMOVIE_SELECTTRACK_H
| 29.432432 | 158 | 0.652893 | [
"3d"
] |
b3f1732ea698bc02ce32a5c4d0ba6a73638ead88 | 96,793 | c | C | montage-tech/src/kware/demux_mp/mplayer/libmpdemux/demux_real.c | kuikuitage/NewCool-UC-3.1.0-priv | 16198d4eae1dd1a1bf4f4ba4b54652688078c018 | [
"Apache-2.0"
] | null | null | null | montage-tech/src/kware/demux_mp/mplayer/libmpdemux/demux_real.c | kuikuitage/NewCool-UC-3.1.0-priv | 16198d4eae1dd1a1bf4f4ba4b54652688078c018 | [
"Apache-2.0"
] | null | null | null | montage-tech/src/kware/demux_mp/mplayer/libmpdemux/demux_real.c | kuikuitage/NewCool-UC-3.1.0-priv | 16198d4eae1dd1a1bf4f4ba4b54652688078c018 | [
"Apache-2.0"
] | 3 | 2016-05-03T05:57:19.000Z | 2021-11-10T21:34:00.000Z | /*
* Real parser & demuxer
* copyright (C) 2001 Alex Beregszaszi
* copyright (C) 2005, 2006 Roberto Togni
* based on FFmpeg's libav/rm.c
*
* audio codecs: (supported by RealPlayer8 for Linux)
* DNET - RealAudio 3.0, really it's AC3 in swapped-byteorder
* SIPR - SiproLab's audio codec, ACELP decoder working with MPlayer,
* needs fine-tuning too :)
* ATRC - RealAudio 8 (ATRAC3) - www.minidisc.org/atrac3_article.pdf,
* ACM decoder uploaded, needs some fine-tuning to work
* -> RealAudio 8
* COOK/COKR - Real Cooker -> RealAudio G2
*
* video codecs: (supported by RealPlayer8 for Linux)
* RV10 - H.263 based, working with libavcodec's decoder
* RV20-RV40 - using RealPlayer's codec plugins
*
* This file is part of MPlayer.
*
* MPlayer is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* MPlayer 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 MPlayer; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifdef __LINUX__
#include <stdio.h>
#include <stdlib.h>
#else
#include "mp_func_trans.h"
#endif
#include <unistd.h>
#include <inttypes.h>
#include "config.h"
#include "mp_msg.h"
#include "help_mp.h"
#include "mpbswap.h"
#include "libavutil/common.h"
#include "libavutil/intreadwrite.h"
#include "stream/stream.h"
#include "aviprint.h"
#include "demuxer.h"
#include "stheader.h"
#include "demux_real.h"
#define BUFFER_HEADER_EXTEND_FOR_WRITE 64
typedef struct sh_real_opaque_data
{
unsigned int opauqe_data_size;
unsigned int media_object_format;
unsigned short bit_count;
unsigned short pad_width;
unsigned short pad_height;
unsigned char *p_opaque_data;
}sh_real_opaque_data_t;
//#define mp_dbg(mod,lev, args... ) mp_msg_c((mod<<8)|lev, ## args )
typedef struct packet_hdr_s {
unsigned int slice_header_len;
unsigned int offset;
unsigned short TR;
unsigned short width;
unsigned short height;
unsigned short MBA;
unsigned char ECC;
unsigned char PicCodType;
unsigned char SQUANT;
unsigned char BitStreamVersion;
unsigned char OSV_QUANT;
unsigned char Deblock_Pass_Thru;
unsigned char pixel_aspect_ratio;
unsigned char broken_up_by_us;
unsigned char MBA_bits;
unsigned char start_mb_data;///because reade slice header is not align ,so we read more one byte ,including mb data,this is the valid mb data in this byte
unsigned char start_mb_data_bitnum;///valid data in first mb data to make data align
} packet_hdr_t;
#define MAX_STREAMS 32
#define MAX_MLTIIDX 16
static unsigned char sipr_swaps[38][2]={
{0,63},{1,22},{2,44},{3,90},{5,81},{7,31},{8,86},{9,58},{10,36},{12,68},
{13,39},{14,73},{15,53},{16,69},{17,57},{19,88},{20,34},{21,71},{24,46},
{25,94},{26,54},{28,75},{29,50},{32,70},{33,92},{35,74},{38,85},{40,56},
{42,87},{43,65},{45,59},{48,79},{49,93},{51,89},{55,95},{61,76},{67,83},
{77,80} };
typedef struct {
unsigned int timestamp;
int offset;
// int packetno;
// int len; /* only filled by our index generator */
// int flags; /* only filled by our index generator */
} real_index_table_t;
typedef struct {
/* for seeking */
int index_chunk_offset;
real_index_table_t *index_table[MAX_STREAMS];
// int *index_table[MAX_STREAMS];
int index_table_size[MAX_STREAMS];
int index_malloc_size[MAX_STREAMS];
int data_chunk_offset;
int num_of_packets;
int current_packet;
int streams_in_file;
// need for seek
int audio_need_keyframe;
int video_after_seek;
int current_apacket;
int current_vpacket;
// timestamp correction:
int64_t kf_base;// timestamp of the prev. video keyframe
unsigned int kf_pts; // timestamp of next video keyframe
unsigned int a_pts; // previous audio timestamp
double v_pts; // previous video timestamp
unsigned long duration;
/* stream id table */
// int last_a_stream;
// int a_streams[MAX_STREAMS];
// int last_v_stream;
// int v_streams[MAX_STREAMS];
/**
* Used to demux multirate files
*/
int is_multirate; ///< != 0 for multirate files
int str_data_offset[MAX_STREAMS]; ///< Data chunk offset for every audio/video stream
int audio_curpos; ///< Current file position for audio demuxing
int video_curpos; ///< Current file position for video demuxing
int a_num_of_packets; ///< Number of audio packets
int v_num_of_packets; ///< Number of video packets
int a_bitrate; ///< Audio bitrate
int v_bitrate; ///< Video bitrate
int stream_switch; ///< Flag used to switch audio/video demuxing
/**
* Used to demux MLTI files
*/
int is_mlti; ///< != 0 for MLTI files
unsigned int mp2rm_streamid[MAX_STREAMS]; ///< Convert Mplayer stream_id to rm stream id
unsigned int rm2mp[MAX_STREAMS][MAX_MLTIIDX]; ///< Convert rm stream id and mlti index to Mplayer stream_id
/**
* Used to reorder audio data
*/
unsigned int intl_id[MAX_STREAMS]; ///< interleaver id, per stream
int sub_packet_size[MAX_STREAMS]; ///< sub packet size, per stream
int sub_packet_h[MAX_STREAMS]; ///< number of coded frames per block
int coded_framesize[MAX_STREAMS]; ///< coded frame size, per stream
int audiopk_size[MAX_STREAMS]; ///< audio packet size
unsigned char *audio_buf; ///< place to store reordered audio data
double *audio_timestamp; ///< timestamp for each audio packet
int sub_packet_cnt; ///< number of subpacket already received
int audio_filepos; ///< file position of first audio packet in block
unsigned int slice_size_addr;
unsigned int slice_size;
sh_real_opaque_data_t real_video_opaque;
unsigned short prev_width;
unsigned short prev_height;
char video_file_start;
unsigned char slice_size_bit_offset;
} real_priv_t;
//! use at most 200 MB of memory for index, corresponds to around 25 million entries
#define MAX_INDEX_ENTRIES (200*1024*1024 / sizeof(real_index_table_t))
static unsigned int enc_vlc_code(unsigned short info, unsigned char info_len)
{
unsigned int v = 1;
unsigned int shift = 1;
unsigned char i;
for(i=0; i<info_len; i++)
{
v += ((info&1)<<shift);
shift += 2;
info = info>>1;
}
return v;
}
/* originally from FFmpeg */
static void get_str(int isbyte, demuxer_t *demuxer, char *buf, int buf_size)
{
int len;
if (isbyte)
len = stream_read_char(demuxer->stream);
else
len = stream_read_word(demuxer->stream);
stream_read(demuxer->stream, buf, (len > buf_size) ? buf_size : len);
if (len > buf_size)
stream_skip(demuxer->stream, len-buf_size);
mp_msg(MSGT_DEMUX, MSGL_V, "read_str: %d bytes read\n", len);
}
static void dump_index(demuxer_t *demuxer, int stream_id)
{
real_priv_t *priv = demuxer->priv;
real_index_table_t *index;
int i, entries;
if (!mp_msg_test(MSGT_DEMUX,MSGL_V))
return;
if ((unsigned)stream_id >= MAX_STREAMS)
return;
index = priv->index_table[stream_id];
entries = priv->index_table_size[stream_id];
mp_msg(MSGT_DEMUX, MSGL_V, "Index table for stream %d\n", stream_id);
for (i = 0; i < entries; i++)
{
#if 1
mp_msg(MSGT_DEMUX, MSGL_V,"i: %d, pos: %d, timestamp: %u\n", i, index[i].offset, index[i].timestamp);
#else
mp_msg(MSGT_DEMUX, MSGL_V,"packetno: %x pos: %x len: %x timestamp: %x flags: %x\n",
index[i].packetno, index[i].offset, index[i].len, index[i].timestamp,
index[i].flags);
#endif
}
}
static int parse_index_chunk(demuxer_t *demuxer)
{
real_priv_t *priv = demuxer->priv;
int origpos = stream_tell(demuxer->stream);
int next_header_pos = priv->index_chunk_offset;
int i, entries, stream_id;
read_index:
stream_seek(demuxer->stream, next_header_pos);
i = stream_read_dword_le(demuxer->stream);
if ((i == -256) || (i != MKTAG('I', 'N', 'D', 'X')))
{
mp_msg(MSGT_DEMUX, MSGL_WARN,"Something went wrong, no index chunk found on given address (%d)\n",
next_header_pos);
index_mode = -1;
if (i == -256)
stream_reset(demuxer->stream);
stream_seek(demuxer->stream, origpos);
return 0;
//goto end;
}
mp_msg(MSGT_DEMUX, MSGL_V,"Reading index table from index chunk (%d)\n",
next_header_pos);
i = stream_read_dword(demuxer->stream);
mp_msg(MSGT_DEMUX, MSGL_V,"size: %d bytes\n", i);
i = stream_read_word(demuxer->stream);
if (i != 0)
mp_msg(MSGT_DEMUX, MSGL_WARN,"Hmm, index table with unknown version (%d), please report it to MPlayer developers!\n", i);
entries = stream_read_dword(demuxer->stream);
mp_msg(MSGT_DEMUX, MSGL_V,"entries: %d\n", entries);
stream_id = stream_read_word(demuxer->stream);
mp_msg(MSGT_DEMUX, MSGL_V,"stream_id: %d\n", stream_id);
next_header_pos = stream_read_dword(demuxer->stream);
mp_msg(MSGT_DEMUX, MSGL_V,"next_header_pos: %d\n", next_header_pos);
if (entries <= 0 || entries > MAX_INDEX_ENTRIES)
{
if (next_header_pos)
goto read_index;
i = entries;
goto end;
}
priv->index_table_size[stream_id] = entries;
priv->index_table[stream_id] = calloc(priv->index_table_size[stream_id], sizeof(real_index_table_t));
for (i = 0; i < entries; i++)
{
stream_skip(demuxer->stream, 2); /* version */
priv->index_table[stream_id][i].timestamp = stream_read_dword(demuxer->stream);
priv->index_table[stream_id][i].offset = stream_read_dword(demuxer->stream);
stream_skip(demuxer->stream, 4); /* packetno */
// priv->index_table[stream_id][i].packetno = stream_read_dword(demuxer->stream);
// printf("Index table: Stream#%d: entry: %d: pos: %d\n",
// stream_id, i, priv->index_table[stream_id][i].offset);
}
dump_index(demuxer, stream_id);
if (next_header_pos > 0)
goto read_index;
end:
if (i == -256)
stream_reset(demuxer->stream);
stream_seek(demuxer->stream, origpos);
if (i == -256)
return 0;
else
return 1;
}
#if 1
static void add_index_item(demuxer_t *demuxer, int stream_id, unsigned int timestamp, int offset)
{
if ((unsigned)stream_id < MAX_STREAMS)
{
real_priv_t *priv = demuxer->priv;
real_index_table_t *index;
if (priv->index_table_size[stream_id] >= MAX_INDEX_ENTRIES) {
mp_msg(MSGT_DEMUXER, MSGL_WARN, "Index too large during building\n");
return;
}
if (priv->index_table_size[stream_id] >= priv->index_malloc_size[stream_id])
{
if (priv->index_malloc_size[stream_id] == 0)
priv->index_malloc_size[stream_id] = 2048;
else
priv->index_malloc_size[stream_id] += priv->index_malloc_size[stream_id] / 2;
// in case we have a really large chunk...
if (priv->index_table_size[stream_id] >=
priv->index_malloc_size[stream_id])
priv->index_malloc_size[stream_id] =
priv->index_table_size[stream_id] + 1;
priv->index_table[stream_id] = realloc(priv->index_table[stream_id], priv->index_malloc_size[stream_id]*sizeof(priv->index_table[0][0]));
}
if (priv->index_table_size[stream_id] > 0)
{
index = &priv->index_table[stream_id][priv->index_table_size[stream_id] - 1];
if (index->timestamp >= timestamp || index->offset >= offset)
return;
}
index = &priv->index_table[stream_id][priv->index_table_size[stream_id]++];
index->timestamp = timestamp;
index->offset = offset;
}
}
static void add_index_segment(demuxer_t *demuxer, int seek_stream_id, int64_t seek_timestamp)
{
int tag, len, stream_id, flags;
unsigned int timestamp;
if (seek_timestamp != -1 && (unsigned)seek_stream_id >= MAX_STREAMS)
return;
while (1)
{
demuxer->filepos = stream_tell(demuxer->stream);
tag = stream_read_dword(demuxer->stream);
if (tag == MKTAG('A', 'T', 'A', 'D'))
{
stream_skip(demuxer->stream, 14);
continue; /* skip to next loop */
}
len = tag & 0xffff;
if (tag == -256 || len < 12)
break;
stream_id = stream_read_word(demuxer->stream);
timestamp = stream_read_dword(demuxer->stream);
stream_skip(demuxer->stream, 1); /* reserved */
flags = stream_read_char(demuxer->stream);
if (flags == -256)
break;
if (flags & 2)
{
add_index_item(demuxer, stream_id, timestamp, demuxer->filepos);
if (stream_id == seek_stream_id && timestamp >= seek_timestamp)
{
stream_seek(demuxer->stream, demuxer->filepos);
return;
}
}
// printf("Index: stream=%d packet=%d timestamp=%u len=%d flags=0x%x datapos=0x%x\n", stream_id, entries, timestamp, len, flags, index->offset);
/* skip data */
stream_skip(demuxer->stream, len-12);
}
}
static int generate_index(demuxer_t *demuxer)
{
real_priv_t *priv = demuxer->priv;
int origpos = stream_tell(demuxer->stream);
int data_pos = priv->data_chunk_offset-10;
int i;
int tag;
stream_seek(demuxer->stream, data_pos);
tag = stream_read_dword(demuxer->stream);
if (tag != MKTAG('A', 'T', 'A', 'D'))
{
mp_msg(MSGT_DEMUX, MSGL_WARN,"Something went wrong, no data chunk found on given address (%d)\n", data_pos);
}
else
{
stream_skip(demuxer->stream, 14);
add_index_segment(demuxer, -1, -1);
}
for (i = 0; i < MAX_STREAMS; i++)
{
if (priv->index_table_size[i] > 0)
{
dump_index(demuxer, i);
}
}
stream_reset(demuxer->stream);
stream_seek(demuxer->stream, origpos);
return 0;
}
#else
static int generate_index(demuxer_t *demuxer)
{
real_priv_t *priv = demuxer->priv;
int origpos = stream_tell(demuxer->stream);
int data_pos = priv->data_chunk_offset-10;
int num_of_packets = 0;
int i, entries = 0;
int len, stream_id = 0, flags;
unsigned int timestamp;
int tab_pos = 0;
read_index:
stream_seek(demuxer->stream, data_pos);
i = stream_read_dword_le(demuxer->stream);
if ((i == -256) || (i != MKTAG('D', 'A', 'T', 'A')))
{
mp_msg(MSGT_DEMUX, MSGL_WARN,"Something went wrong, no data chunk found on given address (%d)\n",
data_pos);
goto end;
}
stream_skip(demuxer->stream, 4); /* chunk size */
stream_skip(demuxer->stream, 2); /* version */
num_of_packets = stream_read_dword(demuxer->stream);
mp_msg(MSGT_DEMUX, MSGL_V,"Generating index table from raw data (pos: 0x%x) for %d packets\n",
data_pos, num_of_packets);
data_pos = stream_read_dword_le(demuxer->stream)-10; /* next data chunk */
for (i = 0; i < MAX_STREAMS; i++)
{
priv->index_table_size[i] = num_of_packets;
priv->index_table[i] = calloc(priv->index_table_size[i], sizeof(real_index_table_t));
// priv->index_table[stream_id] = realloc(priv->index_table[stream_id],
// priv->index_table_size[stream_id] * sizeof(real_index_table_t));
}
tab_pos = 0;
// memset(priv->index_table_size, 0, sizeof(int)*MAX_STREAMS);
// memset(priv->index_table, 0, sizeof(real_index_table_t)*MAX_STREAMS);
while (tab_pos < num_of_packets)
{
i = stream_read_char(demuxer->stream);
if (i == -256)
goto end;
stream_skip(demuxer->stream, 1);
// stream_skip(demuxer->stream, 2); /* version */
len = stream_read_word(demuxer->stream);
stream_id = stream_read_word(demuxer->stream);
timestamp = stream_read_dword(demuxer->stream);
stream_skip(demuxer->stream, 1); /* reserved */
flags = stream_read_char(demuxer->stream);
i = tab_pos;
// priv->index_table_size[stream_id] = i;
// if (priv->index_table[stream_id] == NULL)
// priv->index_table[stream_id] = malloc(priv->index_table_size[stream_id] * sizeof(real_index_table_t));
// else
// priv->index_table[stream_id] = realloc(priv->index_table[stream_id],
// priv->index_table_size[stream_id] * sizeof(real_index_table_t));
priv->index_table[stream_id][i].timestamp = timestamp;
priv->index_table[stream_id][i].offset = stream_tell(demuxer->stream)-12;
priv->index_table[stream_id][i].len = len;
priv->index_table[stream_id][i].packetno = entries;
priv->index_table[stream_id][i].flags = flags;
tab_pos++;
/* skip data */
stream_skip(demuxer->stream, len-12);
}
dump_index(demuxer, stream_id);
if (data_pos)
goto read_index;
end:
if (i == -256)
stream_reset(demuxer->stream);
stream_seek(demuxer->stream, origpos);
if (i == -256)
return 0;
else
return 1;
}
#endif
static int real_check_file(demuxer_t* demuxer)
{
real_priv_t *priv;
int c;
mp_msg(MSGT_DEMUX,MSGL_V,"Checking for REAL\n");
c = stream_read_dword_le(demuxer->stream);
if (c == -256)
return 0; /* EOF */
if (c != MKTAG('.', 'R', 'M', 'F'))
return 0; /* bad magic */
priv = calloc(1, sizeof(real_priv_t));
demuxer->priv = priv;
return DEMUXER_TYPE_REAL;
}
static double real_fix_timestamp_static(packet_hdr_t *pkt_hdr, unsigned int timestamp, unsigned int format, int64_t *kf_base, int *kf_pts, double *pts){
double v_pts;
unsigned int kf=timestamp;
int pict_type;
unsigned int orig_kf;
if(format==mmioFOURCC('R','V','3','0') || format==mmioFOURCC('R','V','4','0')){
pict_type = pkt_hdr->PicCodType;
orig_kf=kf= pkt_hdr->TR; // kf= 2*SHOW_BITS(12);
// if(pict_type==0)
if(pict_type<=1){
// I frame, sync timestamps:
*kf_base=(int64_t)timestamp-kf;
mp_msg(MSGT_DEMUX, MSGL_DBG2,"\nTS: base=%08"PRIX64"\n",*kf_base);
kf=timestamp;
} else {
// P/B frame, merge timestamps:
int64_t tmp=(int64_t)timestamp-*kf_base;
kf|=tmp&(~0x1fff); // combine with packet timestamp
if(kf<tmp-4096) kf+=8192; else // workaround wrap-around problems
if(kf>tmp+4096) kf-=8192;
kf+=*kf_base;
}
if(pict_type != 3){ // P || I frame -> swap timestamps
unsigned int tmp=kf;
kf=*kf_pts;
*kf_pts=tmp;
// if(kf<=tmp) kf=0;
}
}
v_pts=kf*0.001f;
// if(pts && (v_pts<*pts || !kf)) v_pts=*pts+frametime;
if(pts) *pts=v_pts;
return v_pts;
}
#define SKIP_BITS(n) buffer<<=n
#define SHOW_BITS(n) ((buffer)>>(32-(n)))
double real_fix_timestamp(unsigned char *buf, unsigned int timestamp, unsigned int format, int64_t *kf_base, int *kf_pts, double *pts){
double v_pts;
unsigned char *s = buf + 1 + (*buf+1)*8;
uint32_t buffer= (s[0]<<24) + (s[1]<<16) + (s[2]<<8) + s[3];
unsigned int kf=timestamp;
int pict_type;
unsigned int orig_kf;
if(format==mmioFOURCC('R','V','3','0') || format==mmioFOURCC('R','V','4','0')){
if(format==mmioFOURCC('R','V','3','0')){
SKIP_BITS(3);
pict_type= SHOW_BITS(2);
SKIP_BITS(2 + 7);
}else{
SKIP_BITS(1);
pict_type= SHOW_BITS(2);
SKIP_BITS(2 + 7 + 3);
}
orig_kf=
kf= SHOW_BITS(13); // kf= 2*SHOW_BITS(12);
// if(pict_type==0)
if(pict_type<=1){
// I frame, sync timestamps:
*kf_base=(int64_t)timestamp-kf;
mp_msg(MSGT_DEMUX, MSGL_DBG2,"\nTS: base=%08"PRIX64"\n",*kf_base);
kf=timestamp;
} else {
// P/B frame, merge timestamps:
int64_t tmp=(int64_t)timestamp-*kf_base;
kf|=tmp&(~0x1fff); // combine with packet timestamp
if(kf<tmp-4096) kf+=8192; else // workaround wrap-around problems
if(kf>tmp+4096) kf-=8192;
kf+=*kf_base;
}
if(pict_type != 3){ // P || I frame -> swap timestamps
unsigned int tmp=kf;
kf=*kf_pts;
*kf_pts=tmp;
// if(kf<=tmp) kf=0;
}
mp_msg(MSGT_DEMUX, MSGL_DBG2,"\nTS: %08X -> %08X (%04X) %d %02X %02X %02X %02X %5u\n",timestamp,kf,orig_kf,pict_type,s[0],s[1],s[2],s[3],pts?kf-(unsigned int)(*pts*1000.0):0);
}
v_pts=kf*0.001f;
// if(pts && (v_pts<*pts || !kf)) v_pts=*pts+frametime;
if(pts) *pts=v_pts;
return v_pts;
}
#define RV_INTRAPIC 0
#define RV_FORCED_INTRAPIC 1
#define RV_INTERPIC 2
#define RV_TRUEBPIC 3
typedef struct dp_hdr_s {
uint32_t chunks; // number of chunks
uint32_t timestamp; // timestamp from packet header
uint32_t len; // length of actual data
uint32_t header_buffer_len; // offset to data offset array
} dp_hdr_t;
typedef struct getbits_context
{
unsigned char value;
unsigned char *buffer;
unsigned int bufferlen;
unsigned int bitcnt;
unsigned int index;
}mtg_getbits_context_t;
static unsigned int mtg_get_bits(mtg_getbits_context_t *s,int n){
unsigned int x=0;
while(n-->0){
if(!s->bitcnt){
if(s->index >= s->bufferlen)
return -1;
s->value=s->buffer[s->index++];
s->bitcnt=8;
}
//x=(x<<1)|(buf&1);buf>>=1;
x=(x<<1)|(s->value>>7);s->value<<=1;
--s->bitcnt;
}
return x;
}
static int mtg_write_bits(mtg_getbits_context_t *s,int v,int n){
while(n-->0)
{
s->value<<=1;
s->value += ((v>>n)&1);
++s->bitcnt;
if(s->bitcnt == 8)
{
if(s->index >= s->bufferlen)
return -1;
s->buffer[s->index++] = s->value;
s->bitcnt=0;
s->value=0;
}
}
return 0;
}
unsigned int mtg_init_op_bits8(mtg_getbits_context_t *s, const uint8_t *buffer,
int byte_size)
{
if(!buffer || byte_size <= 0)
{
return -1;
}
s->buffer = buffer;
s->bufferlen = byte_size;
s->bitcnt = 0;
s->index = 0;
s->value = 0;
}
static const unsigned short rv34_mb_max_sizes[6] = { 0x2F, 0x62, 0x18B, 0x62F, 0x18BF, 0x23FF };
static const unsigned char rv34_mb_bits_sizes[6] = { 6, 7, 9, 11, 13, 14 };
static const int rv40_standard_widths[] = { 160, 172, 240, 320, 352, 640, 704, 0};
static const int rv40_standard_heights[] = { 120, 132, 144, 240, 288, 480, -8, -10, 180, 360, 576, 0};
static int ff_rv34_get_start_offset(int mb_size)
{
int i;
for(i = 0; i < 5; i++)
if(rv34_mb_max_sizes[i] >= mb_size - 1)
break;
return rv34_mb_bits_sizes[i];
}
static int get_dimension(mtg_getbits_context_t *gb, const int *dim)
{
int t = mtg_get_bits(gb, 3);
int val = dim[t];
if(val < 0)
{
val = dim[mtg_get_bits(gb,1) - val];
}
if(!val){
do{
t = mtg_get_bits(gb, 8);
val += t << 2;
}while(t == 0xFF);
}
return val;
}
static void rv40_parse_picture_size(mtg_getbits_context_t *gb, int *w, int *h)
{
*w = get_dimension(gb, rv40_standard_widths);
*h = get_dimension(gb, rv40_standard_heights);
}
static void update_slice_size(real_priv_t *priv, unsigned int slice_bit_len)
{
mtg_getbits_context_t bitctx;
unsigned int slice_size = priv->slice_size;
unsigned int addr = priv->slice_size_addr;
unsigned char bitoffset = priv->slice_size_bit_offset;
unsigned char *buffer = (unsigned char *)addr;
unsigned char tmp = (buffer[0]>>(8-bitoffset));
mtg_init_op_bits8(&bitctx,buffer,6);
mtg_write_bits(&bitctx,tmp,bitoffset);
slice_size += slice_bit_len;
mtg_write_bits(&bitctx,slice_size>>24,8);
mtg_write_bits(&bitctx,3,2);
mtg_write_bits(&bitctx,slice_size>>16,8);
mtg_write_bits(&bitctx,3,2);
mtg_write_bits(&bitctx,slice_size>>8,8);
mtg_write_bits(&bitctx,3,2);
mtg_write_bits(&bitctx,slice_size,8);
mtg_write_bits(&bitctx,3,2);
if(bitctx.bitcnt)
{
tmp = buffer[bitctx.index];
tmp =(((unsigned char)(tmp<<(8-bitctx.bitcnt)))>>(8-bitctx.bitcnt));
tmp |= (bitctx.value<<(8-bitctx.bitcnt));
buffer[bitctx.index] = tmp;
}
priv->slice_size = slice_size;
}
static void write_slice_size(real_priv_t *priv, packet_hdr_t *pkt_hdr, mtg_getbits_context_t *bitctx, unsigned char *buffer, unsigned int slice_bit_len)
{
priv->slice_size = slice_bit_len;
if(pkt_hdr->broken_up_by_us)
{
priv->slice_size_addr = (unsigned int)(buffer+bitctx->index);
priv->slice_size_bit_offset = bitctx->bitcnt;
}
mtg_write_bits(bitctx,slice_bit_len>>24,8);
mtg_write_bits(bitctx,3,2);
mtg_write_bits(bitctx,slice_bit_len>>16,8);
mtg_write_bits(bitctx,3,2);
mtg_write_bits(bitctx,slice_bit_len>>8,8);
mtg_write_bits(bitctx,3,2);
mtg_write_bits(bitctx,slice_bit_len,8);
mtg_write_bits(bitctx,3,2);
}
static void write_ecc_tr_db_struffing(packet_hdr_t *pkt_hdr, mtg_getbits_context_t *bitctx)
{
char stuffing_bits;
mtg_write_bits(bitctx,pkt_hdr->ECC,1);
mtg_write_bits(bitctx,pkt_hdr->TR>>8,5);
mtg_write_bits(bitctx,pkt_hdr->Deblock_Pass_Thru,1);
mtg_write_bits(bitctx,1,1);
stuffing_bits = 8-bitctx->bitcnt - pkt_hdr->start_mb_data_bitnum;
stuffing_bits = (stuffing_bits <= 0)?(stuffing_bits+8):stuffing_bits;
mtg_write_bits(bitctx,stuffing_bits,8);
mtg_write_bits(bitctx,0,stuffing_bits);
if(pkt_hdr->start_mb_data_bitnum)
mtg_write_bits(bitctx,pkt_hdr->start_mb_data,pkt_hdr->start_mb_data_bitnum);
}
static int realvideo_write_file_header(sh_video_t *sh_video, real_priv_t *priv, unsigned char *buffer)
{
int index = 0;
unsigned int i;
uint32_t SubMOFTag;
if(sh_video->format == mmioFOURCC('R', 'V', '3', '0')) ///rv8
{
mp_msg(MSGT_DEMUX,MSGL_INFO,"realvideo_write_file_header rv8\n");
AV_WB32(buffer+index,0x00000100);
index += 4;
SubMOFTag = mmioFOURCC('R', 'V', '3', '0');
}
else if(sh_video->format == mmioFOURCC('R', 'V', '4', '0'))///rv9-rv10
{
mp_msg(MSGT_DEMUX,MSGL_INFO,"realvideo_write_file_header rv9\n");
AV_WB32(buffer+index,0x55555555);
index += 4;
SubMOFTag = mmioFOURCC('R', 'V', '4', '0');
}
else
{
mp_msg(MSGT_DEMUX,MSGL_ERR,"[%s] format[0x%x] is not rv30 or rv40, we can't support!\n",__func__,sh_video->format);
return -1;
}
AV_WB32(buffer+index,0x5649444F);///tag = VIDO
index += 4;
AV_WB32(buffer+index,priv->real_video_opaque.opauqe_data_size+26);///length
index += 4;
AV_WB32(buffer+index,0x5649444F);///MOFTag = VIDO
index += 4;
AV_WL32(buffer+index,SubMOFTag);///SubMOFTag
index += 4;
AV_WB16(buffer+index,sh_video->disp_w);///width
index += 2;
AV_WB16(buffer+index,sh_video->disp_h);///height
index += 2;
AV_WB16(buffer+index,priv->real_video_opaque.bit_count);///bitcount
index += 2;
AV_WB16(buffer+index,priv->real_video_opaque.pad_width);///pad_width
index += 2;
AV_WB16(buffer+index,priv->real_video_opaque.pad_height);///pad_height
index += 2;
AV_WB32(buffer+index,(uint32_t)sh_video->fps);///fps
index += 4;
AV_WB32(buffer+index,priv->real_video_opaque.opauqe_data_size);///opaque data size
index += 4;
for(i=0;i<priv->real_video_opaque.opauqe_data_size;i++)
{
buffer[index+i] = priv->real_video_opaque.p_opaque_data[i];
}
index += priv->real_video_opaque.opauqe_data_size;
return index;
}
static int realvideo_write_pic_header(real_priv_t *priv, sh_video_t *sh_video, packet_hdr_t *pkt_hdr, unsigned char *buffer, unsigned int len, unsigned int slice_raw_bs_len)
{
int index = 0;
char is_rv8 = (sh_video->format == mmioFOURCC('R', 'V', '3', '0'));
char is_rv9 = (sh_video->format == mmioFOURCC('R', 'V', '4', '0'));
if(is_rv8 || is_rv9)
{
unsigned int slice_payload_len;
unsigned int picture_layer_info;///31bits
unsigned short tmp;
unsigned short CSFMT_FWI;///9bits
unsigned short CSFMT_FHI;///9bits
unsigned char sequence_end_code;///1bit
unsigned char is_QCIF;///1bit
unsigned char PQUANT;///5bits
unsigned char TR_low;///8bits
unsigned char pixel_aspect_ratio;
mtg_getbits_context_t bitctx;
mtg_init_op_bits8(&bitctx,buffer+index,len-index);
if(is_rv9)
mtg_write_bits(&bitctx,0x55555555,32);
else
mtg_write_bits(&bitctx,1,24);
/**********************picture_layer_info*****************/
sequence_end_code = 0;
is_QCIF = (pkt_hdr->width == 176 && pkt_hdr->height == 144);
PQUANT = pkt_hdr->SQUANT;
TR_low = pkt_hdr->TR&0xff;
tmp = TR_low;
tmp = (tmp<<5)+PQUANT;
tmp = (tmp<<1)+(1-is_QCIF);
tmp = (tmp<<1)+sequence_end_code;
picture_layer_info = enc_vlc_code(tmp,15);
mtg_write_bits(&bitctx,picture_layer_info,31);
if(pkt_hdr->PicCodType == RV_INTRAPIC || pkt_hdr->PicCodType == RV_FORCED_INTRAPIC)
{
mtg_write_bits(&bitctx,3,3);///3bits
}
else if(pkt_hdr->PicCodType == RV_INTERPIC)
{
mtg_write_bits(&bitctx,1,1);///1bit
}
else///RV_TRUEBPIC
{
mtg_write_bits(&bitctx,1,5);///5bits
}
if(!is_QCIF)
{
pixel_aspect_ratio = 1;
mtg_write_bits(&bitctx,pixel_aspect_ratio,4);///4bits
CSFMT_FWI = (pkt_hdr->width>>2)-1;
mtg_write_bits(&bitctx,CSFMT_FWI,9);
mtg_write_bits(&bitctx,1,1);
CSFMT_FHI = (pkt_hdr->height>>2);
mtg_write_bits(&bitctx,CSFMT_FHI,9);
}
if(is_rv9)
mtg_write_bits(&bitctx,pkt_hdr->OSV_QUANT,2);
slice_payload_len = (slice_raw_bs_len - pkt_hdr->slice_header_len)*8 + pkt_hdr->start_mb_data_bitnum;
write_slice_size(priv,pkt_hdr,&bitctx,buffer,slice_payload_len);
write_ecc_tr_db_struffing(pkt_hdr,&bitctx);
index += bitctx.index;
}
return index;
}
static int realvideo_write_slice_header(real_priv_t *priv, sh_video_t *sh_video, packet_hdr_t *pkt_hdr, unsigned char *buffer, unsigned int len, unsigned int slice_raw_bs_len)
{
int index = 0;
char is_rv8 = (sh_video->format == mmioFOURCC('R', 'V', '3', '0'));
char is_rv9 = (sh_video->format == mmioFOURCC('R', 'V', '4', '0'));
if(is_rv8 || is_rv9)
{
unsigned int slice_payload_len;
unsigned char Slice_GOB_frame_ID;
mtg_getbits_context_t bitctx;
mtg_init_op_bits8(&bitctx,buffer+index,len-index);
if(is_rv9)
mtg_write_bits(&bitctx,0x1d1c10,24);
else
mtg_write_bits(&bitctx,1,17);
mtg_write_bits(&bitctx,1,1);
mtg_write_bits(&bitctx,pkt_hdr->MBA,pkt_hdr->MBA_bits);
if(pkt_hdr->MBA_bits > 11)
mtg_write_bits(&bitctx,1,1);
mtg_write_bits(&bitctx,pkt_hdr->SQUANT,5);
if(is_rv9)
mtg_write_bits(&bitctx,pkt_hdr->OSV_QUANT,2);
mtg_write_bits(&bitctx,1,1);
Slice_GOB_frame_ID = 0;
mtg_write_bits(&bitctx,Slice_GOB_frame_ID,2);
slice_payload_len = (slice_raw_bs_len - pkt_hdr->slice_header_len)*8 + pkt_hdr->start_mb_data_bitnum;
write_slice_size(priv,pkt_hdr,&bitctx,buffer,slice_payload_len);
write_ecc_tr_db_struffing(pkt_hdr,&bitctx);
index += bitctx.index;
}
return index;
}
static int rv8_parse_slice_header(demuxer_t *demuxer, packet_hdr_t *hdr, unsigned char *buf, unsigned int buflen)
{
real_priv_t *priv = demuxer->priv;
unsigned int max_rpr;
unsigned int rpr;
unsigned int mb_size;
unsigned int mb_bits= 0;
int w = priv->prev_width;
int h = priv->prev_height;
unsigned int extradata_size = priv->real_video_opaque.opauqe_data_size;
unsigned char *extradata = priv->real_video_opaque.p_opaque_data;
mtg_getbits_context_t bit_context;
mtg_init_op_bits8(&bit_context,buf,buflen);
////see rv_codec_opaque_data in RealVideo_Opaque_Data_Specification.doc
if(!extradata && extradata_size < 8)
{
mp_msg(MSGT_DEMUX,MSGL_ERR,"[%s] rv8 need opaque data as spoflag,but no data found!\n",__func__);
return -1;
}
mtg_get_bits(&bit_context,3);
hdr->PicCodType = mtg_get_bits(&bit_context,2);
hdr->ECC = mtg_get_bits(&bit_context,1);
hdr->SQUANT = mtg_get_bits(&bit_context,5);
hdr->Deblock_Pass_Thru = mtg_get_bits(&bit_context,1);
hdr->TR = mtg_get_bits(&bit_context,13);
max_rpr = extradata[1]&7;
rpr = mtg_get_bits(&bit_context, av_log2(max_rpr) + 1);
if (extradata_size < rpr * 2 + 8)
{
mp_msg(MSGT_DEMUX,MSGL_ERR,"demux_real: rv8_get_slice_header :Insufficient extradata - need at least %d bytes, got %d\n",
8 + rpr * 2, extradata_size);
return -1;
}
if(rpr)
{
w = extradata[6 + rpr*2] << 2;
h = extradata[7 + rpr*2] << 2;
}
hdr->width = w;
hdr->height = h;
mb_size = ((w + 15) >> 4) * ((h + 15) >> 4);
mb_bits = ff_rv34_get_start_offset(mb_size);
hdr->MBA = mtg_get_bits(&bit_context,mb_bits);
hdr->MBA_bits = mb_bits;
///RTYPE
mtg_get_bits(&bit_context,1);
hdr->slice_header_len = bit_context.index;
if(bit_context.bitcnt)
{
hdr->start_mb_data_bitnum = bit_context.bitcnt;
hdr->start_mb_data = mtg_get_bits(&bit_context,hdr->start_mb_data_bitnum);
}
else
hdr->start_mb_data_bitnum = 0;
return 0;
}
static int rv9_parse_slice_header(demuxer_t *demuxer,packet_hdr_t *hdr, unsigned char *buf, unsigned int buflen)
{
real_priv_t *priv = demuxer->priv;
mtg_getbits_context_t bit_context;
int w = priv->prev_width;
int h = priv->prev_height;
unsigned int mb_size;
unsigned int mb_bits= 0;
mtg_init_op_bits8(&bit_context,buf,buflen);
hdr->pixel_aspect_ratio = 1;//dont know the value ,so set 1
hdr->ECC = mtg_get_bits(&bit_context,1);
hdr->PicCodType = mtg_get_bits(&bit_context,2);
hdr->SQUANT = mtg_get_bits(&bit_context,5);
///1bit bitstream version
hdr->BitStreamVersion = mtg_get_bits(&bit_context,1);
///reserved
mtg_get_bits(&bit_context,1);
hdr->OSV_QUANT = mtg_get_bits(&bit_context,2);
hdr->Deblock_Pass_Thru = mtg_get_bits(&bit_context,1);
hdr->TR = mtg_get_bits(&bit_context,13);
if(hdr->PicCodType == RV_INTERPIC || hdr->PicCodType == RV_TRUEBPIC)
{
if(mtg_get_bits(&bit_context,1) == 0)
{
rv40_parse_picture_size(&bit_context,&w,&h);
}
}
else
rv40_parse_picture_size(&bit_context,&w,&h);
hdr->width = w;
hdr->height = h;
priv->prev_width = w;
priv->prev_height = h;
mb_size = ((w + 15) >> 4) * ((h + 15) >> 4);
mb_bits = ff_rv34_get_start_offset(mb_size);
hdr->MBA = mtg_get_bits(&bit_context,mb_bits);
hdr->MBA_bits = mb_bits;
hdr->slice_header_len = bit_context.index;
if(bit_context.bitcnt)
{
hdr->start_mb_data_bitnum = bit_context.bitcnt;
hdr->start_mb_data = mtg_get_bits(&bit_context,hdr->start_mb_data_bitnum);
}
else
hdr->start_mb_data_bitnum = 0;
return 0;
}
static int parse_slice_header(sh_video_t *sh_video, demuxer_t *demuxer, packet_hdr_t *pkt_hdr, unsigned char *buffer, int len)
{
if(sh_video->format == mmioFOURCC('R', 'V', '3', '0'))
{
return rv8_parse_slice_header(demuxer,pkt_hdr,buffer,len);
}
else if(sh_video->format == mmioFOURCC('R', 'V', '4', '0'))
{
return rv9_parse_slice_header(demuxer,pkt_hdr,buffer,len);
}
else
{
mp_msg(MSGT_DEMUX,MSGL_ERR,"[%s] format[0x%x] is not rv30 or rv40, we can't support!\n",__func__,sh_video->format);
return -1;
}
}
static void queue_video_packet(real_priv_t *priv, demux_stream_t *ds, demux_packet_t *dp)
{
dp_hdr_t hdr = *(dp_hdr_t*)dp->buffer;
packet_hdr_t *pkt_hdr = (packet_hdr_t*)(dp->buffer+sizeof(dp_hdr_t));
sh_video_t *sh_video = ds->sh;
uint32_t i;
int index = 0;
unsigned int slice_raw_bs_len;
unsigned char *tmp = malloc(sizeof(packet_hdr_t)*(1+hdr.chunks));
unsigned char last_broken_flag = 0;
memcpy(tmp, dp->buffer+sizeof(dp_hdr_t), sizeof(packet_hdr_t)*(1+hdr.chunks));
if(priv->video_file_start == 1)///file header
{
priv->video_file_start = 0;
index += realvideo_write_file_header(sh_video,priv,dp->buffer);
}
pkt_hdr = (packet_hdr_t*)tmp;
for(i=0;i<=hdr.chunks;i++,pkt_hdr++)
{
if(i < hdr.chunks)
{
slice_raw_bs_len = (pkt_hdr+1)->offset - pkt_hdr->offset;
}
else
{
slice_raw_bs_len = hdr.len - pkt_hdr->offset;
}
if(i == 0)//first slice
{
last_broken_flag = pkt_hdr->broken_up_by_us;
index += realvideo_write_pic_header(priv,sh_video,pkt_hdr,dp->buffer+index, dp->len-index, slice_raw_bs_len);
memmove(dp->buffer+index,dp->buffer+hdr.header_buffer_len+pkt_hdr->offset+pkt_hdr->slice_header_len,slice_raw_bs_len-pkt_hdr->slice_header_len);
index += (slice_raw_bs_len-pkt_hdr->slice_header_len);
}
else
{
if(last_broken_flag && pkt_hdr->broken_up_by_us)
{
update_slice_size(priv,slice_raw_bs_len<<3);
memmove(dp->buffer+index,dp->buffer+hdr.header_buffer_len+pkt_hdr->offset,slice_raw_bs_len);
index += slice_raw_bs_len;
}
else
{
index += realvideo_write_slice_header(priv,sh_video,pkt_hdr,dp->buffer+index, dp->len-index, slice_raw_bs_len);
memmove(dp->buffer+index,dp->buffer+hdr.header_buffer_len+pkt_hdr->offset+pkt_hdr->slice_header_len,slice_raw_bs_len-pkt_hdr->slice_header_len);
index += (slice_raw_bs_len-pkt_hdr->slice_header_len);
}
}
}
dp->len = index;
if(priv->video_after_seek){
priv->kf_base = 0;
priv->kf_pts = hdr.timestamp;
priv->video_after_seek = 0;
}
if(hdr.len >= 3) /* this check may be useless */
{
pkt_hdr = (packet_hdr_t*)tmp;
dp->pts = real_fix_timestamp_static(pkt_hdr,hdr.timestamp,
((sh_video_t *)ds->sh)->format,
&priv->kf_base, &priv->kf_pts,
&priv->v_pts);
}
free(tmp);
ds_add_packet(ds, dp);
}
// return value:
// 0 = EOF or no stream found
// 1 = successfully read a packet
static int demux_real_fill_buffer(demuxer_t *demuxer, demux_stream_t *dsds)
{
real_priv_t *priv = demuxer->priv;
demux_stream_t *ds = NULL;
int len;
unsigned int timestamp;
int rm_stream_id, mp_stream_id;
#ifdef CRACK_MATRIX
int i;
#endif
int flags;
int version;
int pk_group;
demux_packet_t *dp;
int x, sps, cfs, sph, spc, w;
int audioreorder_getnextpk = 0;
packet_hdr_t *pkt_hdr = NULL;
char broken_up_by_us = 0;
// Don't demux video if video codec init failed
if (demuxer->video->id >= 0 && !demuxer->video->sh)
demuxer->video->id = -2;
while(!stream_eof(demuxer->stream)){
/* Handle audio/video demxing switch for multirate files (non-interleaved) */
if (priv->is_multirate && priv->stream_switch) {
demuxer->audio->eof = priv->current_apacket >= priv->index_table_size[demuxer->audio->id];
demuxer->video->eof = priv->current_vpacket >= priv->index_table_size[demuxer->video->id];
if (demuxer->audio->eof && demuxer->video->eof)
return 0;
else if (!demuxer->audio->eof && demuxer->video->eof)
stream_seek(demuxer->stream, priv->audio_curpos); // Get audio
else if (demuxer->audio->eof && !demuxer->video->eof)
stream_seek(demuxer->stream, priv->video_curpos); // Get video
else if (priv->index_table[demuxer->audio->id][priv->current_apacket].timestamp <
priv->index_table[demuxer->video->id][priv->current_vpacket].timestamp)
stream_seek(demuxer->stream, priv->audio_curpos); // Get audio
else
stream_seek(demuxer->stream, priv->video_curpos); // Get video
priv->stream_switch = 0;
}
demuxer->filepos = stream_tell(demuxer->stream);
version = stream_read_word(demuxer->stream); /* version */
len = stream_read_word(demuxer->stream);
if ((version==0x4441) && (len==0x5441)) { // new data chunk
mp_msg(MSGT_DEMUX,MSGL_INFO,"demux_real: New data chunk is coming!!!\n");
if (priv->is_multirate)
return 0; // EOF
stream_skip(demuxer->stream,14);
demuxer->filepos = stream_tell(demuxer->stream);
version = stream_read_word(demuxer->stream); /* version */
len = stream_read_word(demuxer->stream);
} else if ((version == 0x494e) && (len == 0x4458)) {
mp_msg(MSGT_DEMUX,MSGL_V,"demux_real: Found INDX chunk. EOF.\n");
demuxer->stream->eof=1;
return 0;
}
if (len == -256){ /* EOF */
// printf("len==-256!\n");
return 0;
}
if (len < 12){
unsigned int idx_streamid;
mp_msg(MSGT_DEMUX, MSGL_V,"%08X: packet v%d len=%d \n",(int)demuxer->filepos,(int)version,(int)len);
mp_msg(MSGT_DEMUX, MSGL_WARN,"bad packet len (%d)\n", len);
if ((unsigned)demuxer->video->id < MAX_STREAMS) {
idx_streamid = priv->is_mlti ? priv->mp2rm_streamid[demuxer->video->id] : demuxer->video->id;
if (priv->current_vpacket + 1 < priv->index_table_size[idx_streamid]) {
stream_seek(demuxer->stream, priv->index_table[idx_streamid][++priv->current_vpacket].offset);
}
} else if ((unsigned)demuxer->audio->id < MAX_STREAMS) {
idx_streamid = priv->is_mlti ? priv->mp2rm_streamid[demuxer->audio->id] : demuxer->audio->id;
if (priv->current_apacket + 1 < priv->index_table_size[idx_streamid]) {
stream_seek(demuxer->stream, priv->index_table[idx_streamid][++priv->current_apacket].offset);
}
}
continue; //goto loop;
}
rm_stream_id = stream_read_word(demuxer->stream);
timestamp = stream_read_dword(demuxer->stream);
pk_group = stream_read_char(demuxer->stream);
flags = stream_read_char(demuxer->stream);
/* flags: */
/* 0x1 - reliable */
/* 0x2 - keyframe */
if (version == 1) {
int tmp;
tmp = stream_read_char(demuxer->stream);
mp_msg(MSGT_DEMUX, MSGL_DBG2,"Version: %d, skipped byte is %d\n", version, tmp);
len--;
if (priv->is_mlti)
mp_msg(MSGT_DEMUX, MSGL_WARN,"MLTI file with v1 DATA, expect problems! Please contact Mplayer developers.\n");
}
if (flags & 2)
add_index_item(demuxer, rm_stream_id, timestamp, demuxer->filepos);
// printf("%08X: packet v%d len=%4d id=%d pts=%6d rvd=%d flags=%d \n",
// (int)demuxer->filepos,(int)version,(int)len, stream_id,
// (int) timestamp, reserved, flags);
mp_dbg(MSGT_DEMUX,MSGL_DBG2, "\npacket#%d: pos: 0x%0x, len: %d, rm_id: %d, pts: %u, flags: %x grp:%d\n",
priv->current_packet, (int)demuxer->filepos, len, rm_stream_id, timestamp, flags, pk_group);
priv->current_packet++;
len -= 12;
// printf("s_id=%d aid=%d vid=%d \n",stream_id,demuxer->audio->id,demuxer->video->id);
// Map rm stream id and packet group to MPlayer stream aid or vid if file is MLTI
if (priv->is_mlti && rm_stream_id < MAX_STREAMS && (pk_group>>1) < MAX_MLTIIDX)
mp_stream_id = priv->rm2mp[rm_stream_id][(pk_group>>1)-1];
else
mp_stream_id = rm_stream_id;
/* check stream_id: */
if(demuxer->audio->id==mp_stream_id){
if (priv->audio_need_keyframe == 1&& flags != 0x2)
goto discard;
got_audio:
ds=demuxer->audio;
mp_dbg(MSGT_DEMUX,MSGL_DBG2, "packet is audio (mp_id: %d)\n", mp_stream_id);
if (flags & 2) {
priv->sub_packet_cnt = 0;
audioreorder_getnextpk = 0;
}
// parse audio chunk:
{
#ifdef CRACK_MATRIX
int spos=stream_tell(demuxer->stream);
static int cnt=0;
static int cnt2=CRACK_MATRIX;
#endif
if (((sh_audio_t *)ds->sh)->format == mmioFOURCC('M', 'P', '4', 'A')) {
uint16_t sub_packet_lengths[16], sub_packets, i;
int totlen = 0;
/* AAC in Real: several AAC frames in one Real packet. */
/* Second byte, upper four bits: number of AAC frames */
/* next n * 2 bytes: length of the AAC frames in bytes, BE */
if (len < 2)
goto discard;
sub_packets = (stream_read_word(demuxer->stream) & 0xf0) >> 4;
if (len < 2 * sub_packets)
goto discard;
for (i = 0; i < sub_packets; i++)
totlen += sub_packet_lengths[i] = stream_read_word(demuxer->stream);
if (len < totlen )
goto discard;
for (i = 0; i < sub_packets; i++) {
demux_packet_t *dp = new_demux_packet(sub_packet_lengths[i]);
stream_read(demuxer->stream, dp->buffer, sub_packet_lengths[i]);
if (priv->a_pts != timestamp)
dp->pts = timestamp / 1000.0;
priv->a_pts = timestamp;
dp->pos = demuxer->filepos;
ds_add_packet(ds, dp);
}
return 1;
}
if ((priv->intl_id[demuxer->audio->id] == mmioFOURCC('I', 'n', 't', '4')) ||
(priv->intl_id[demuxer->audio->id] == mmioFOURCC('g', 'e', 'n', 'r')) ||
(priv->intl_id[demuxer->audio->id] == mmioFOURCC('s', 'i', 'p', 'r'))) {
if (!priv->audio_buf) {
priv->audio_buf = calloc(priv->sub_packet_h[demuxer->audio->id], priv->audiopk_size[demuxer->audio->id]);
priv->audio_timestamp = calloc(priv->sub_packet_h[demuxer->audio->id], sizeof(double));
}
sps = priv->sub_packet_size[demuxer->audio->id];
sph = priv->sub_packet_h[demuxer->audio->id];
cfs = priv->coded_framesize[demuxer->audio->id];
w = priv->audiopk_size[demuxer->audio->id];
spc = priv->sub_packet_cnt;
switch (priv->intl_id[demuxer->audio->id]) {
case mmioFOURCC('I', 'n', 't', '4'):
if (len < cfs * sph/2)
goto discard;
for (x = 0; x < sph / 2; x++)
stream_read(demuxer->stream, priv->audio_buf + x * 2 * w + spc * cfs, cfs);
break;
case mmioFOURCC('g', 'e', 'n', 'r'):
if (len < w)
goto discard;
for (x = 0; x < w / sps; x++)
stream_read(demuxer->stream, priv->audio_buf + sps * (sph * x + ((sph + 1) / 2) * (spc & 1) +
(spc >> 1)), sps);
break;
case mmioFOURCC('s', 'i', 'p', 'r'):
if (len < w)
goto discard;
stream_read(demuxer->stream, priv->audio_buf + spc * w, w);
if (spc == sph - 1) {
int n;
int bs = sph * w * 2 / 96; // nibbles per subpacket
// Perform reordering
for(n=0; n < 38; n++) {
int j;
int i = bs * sipr_swaps[n][0];
int o = bs * sipr_swaps[n][1];
// swap nibbles of block 'i' with 'o' TODO: optimize
for(j = 0;j < bs; j++) {
int x = (i & 1) ? (priv->audio_buf[i >> 1] >> 4) : (priv->audio_buf[i >> 1] & 0x0F);
int y = (o & 1) ? (priv->audio_buf[o >> 1] >> 4) : (priv->audio_buf[o >> 1] & 0x0F);
if(o & 1)
priv->audio_buf[o >> 1] = (priv->audio_buf[o >> 1] & 0x0F) | (x << 4);
else
priv->audio_buf[o >> 1] = (priv->audio_buf[o >> 1] & 0xF0) | x;
if(i & 1)
priv->audio_buf[i >> 1] = (priv->audio_buf[i >> 1] & 0x0F) | (y << 4);
else
priv->audio_buf[i >> 1] = (priv->audio_buf[i >> 1] & 0xF0) | y;
++i; ++o;
}
}
}
break;
}
priv->audio_need_keyframe = 0;
priv->audio_timestamp[priv->sub_packet_cnt] = (priv->a_pts==timestamp) ? MP_NOPTS_VALUE : (timestamp/1000.0);
priv->a_pts = timestamp;
if (priv->sub_packet_cnt == 0)
priv->audio_filepos = demuxer->filepos;
if (++(priv->sub_packet_cnt) < sph)
audioreorder_getnextpk = 1;
else {
int apk_usize = ((sh_audio_t*)ds->sh)->wf->nBlockAlign;
audioreorder_getnextpk = 0;
priv->sub_packet_cnt = 0;
// Release all the audio packets
for (x = 0; x < sph*w/apk_usize; x++) {
dp = new_demux_packet(apk_usize);
memcpy(dp->buffer, priv->audio_buf + x * apk_usize, apk_usize);
/* Put timestamp only on packets that correspond to original audio packets in file */
if (x * apk_usize % w == 0)
dp->pts = priv->audio_timestamp[x * apk_usize / w];
dp->pos = priv->audio_filepos; // all equal
dp->flags = x ? 0 : 0x10; // Mark first packet as keyframe
ds_add_packet(ds, dp);
}
}
} else { // No interleaving
dp = new_demux_packet(len);
stream_read(demuxer->stream, dp->buffer, len);
#ifdef CRACK_MATRIX
mp_msg(MSGT_DEMUX, MSGL_V,"*** audio block len=%d\n",len);
{ // HACK - used for reverse engineering the descrambling matrix
FILE* f=fopen("test.rm","r+");
fseek(f,spos,SEEK_SET);
++cnt;
// for(i=0;i<len;i++) dp->buffer[i]=i/0x12;
// for(i=0;i<len;i++) dp->buffer[i]=i;
// for(i=0;i<len;i++) dp->buffer[i]=cnt;
// for(i=0;i<len;i++) dp->buffer[i]=cnt<<4;
for(i=0;i<len;i++) dp->buffer[i]=(i==cnt2) ? (cnt+16*(8+cnt)) : 0;
if(cnt==6){ cnt=0; ++cnt2; }
fwrite(dp->buffer, len, 1, f);
fclose(f);
if(cnt2>0x150) *((int*)NULL)=1; // sig11 :)
}
#endif
#if 0
if( ((sh_audio_t *)ds->sh)->format == 0x2000) {
// if DNET, swap bytes, as DNET is byte-swapped AC3:
char *ptr = dp->buffer;
int i;
for (i = 0; i < len; i += 2)
{
const char tmp = ptr[0];
ptr[0] = ptr[1];
ptr[1] = tmp;
ptr += 2;
}
}
#endif
if (priv->audio_need_keyframe == 1) {
priv->audio_need_keyframe = 0;
} else if(priv->a_pts != timestamp)
dp->pts = timestamp/1000.0;
priv->a_pts=timestamp;
dp->pos = demuxer->filepos;
dp->flags = (flags & 0x2) ? 0x10 : 0;
ds_add_packet(ds, dp);
} // codec_id check, codec default case
}
// we will not use audio index if we use -idx and have a video
if(((!demuxer->video->sh && index_mode == 2) || priv->is_multirate) && (unsigned)demuxer->audio->id < MAX_STREAMS) {
while (priv->current_apacket + 1 < priv->index_table_size[rm_stream_id] &&
timestamp > priv->index_table[rm_stream_id][priv->current_apacket].timestamp) {
priv->current_apacket += 1;
priv->stream_switch = 1;
}
if (priv->stream_switch)
priv->audio_curpos = stream_tell(demuxer->stream);
}
// If we're reordering audio packets and we need more data get it
if (audioreorder_getnextpk)
continue;
return 1;
}
if(demuxer->video->id==mp_stream_id){
got_video:
ds=demuxer->video;
mp_dbg(MSGT_DEMUX,MSGL_DBG2, "packet is video (mp_id: %d)\n", mp_stream_id);
// parse video chunk:
{
// we need a more complicated, 2nd level demuxing, as the video
// frames are stored fragmented in the video chunks :(
sh_video_t *sh_video = ds->sh;
demux_packet_t *dp;
unsigned vpkg_header, vpkg_length, vpkg_offset;
int vpkg_seqnum=-1;
int vpkg_subseq=0;
while(len>2){
dp_hdr_t* dp_hdr;
unsigned char* dp_data;
uint8_t* extra;
// printf("xxx len=%d \n",len);
// read packet header
// bit 7: 1=last block in block chain
// bit 6: 1=short header (only one block?)
vpkg_header=stream_read_char(demuxer->stream); --len;
mp_dbg(MSGT_DEMUX,MSGL_DBG2, "hdr: %02X (len=%d) ",vpkg_header,len);
if (0x40==(vpkg_header&0xc0)) {//whole frame
// seems to be a very short header
// 2 bytes, purpose of the second byte yet unknown
int bummer;
bummer=stream_read_char(demuxer->stream); --len;
mp_dbg(MSGT_DEMUX,MSGL_DBG2, "%02X",bummer);
vpkg_offset=0;
vpkg_length=len;
} else {
if (0==(vpkg_header&0x40)) {//partial frame or last partial frame
// sub-seqnum (bits 0-6: number of fragment. bit 7: ???)
vpkg_subseq=stream_read_char(demuxer->stream);
--len;
mp_dbg(MSGT_DEMUX,MSGL_DBG2, "subseq: %02X ",vpkg_subseq);
vpkg_subseq&=0x7f;
}
// size of the complete packet
// bit 14 is always one (same applies to the offset)
vpkg_length=stream_read_word(demuxer->stream);
broken_up_by_us = vpkg_length>>15;
len-=2;
mp_dbg(MSGT_DEMUX,MSGL_DBG2, "l: %02X %02X ",vpkg_length>>8,vpkg_length&0xff);
if (!(vpkg_length&0xC000)) {
vpkg_length<<=16;
vpkg_length|=(uint16_t)stream_read_word(demuxer->stream);
mp_dbg(MSGT_DEMUX,MSGL_DBG2, "l+: %02X %02X ",(vpkg_length>>8)&0xff,vpkg_length&0xff);
len-=2;
} else
vpkg_length&=0x3fff;
// offset of the following data inside the complete packet
// Note: if (hdr&0xC0)==0x80 then offset is relative to the
// _end_ of the packet, so it's equal to fragment size!!!
vpkg_offset=stream_read_word(demuxer->stream);
len-=2;
mp_dbg(MSGT_DEMUX,MSGL_DBG2, "o: %02X %02X ",vpkg_offset>>8,vpkg_offset&0xff);
if (!(vpkg_offset&0xC000)) {
vpkg_offset<<=16;
vpkg_offset|=(uint16_t)stream_read_word(demuxer->stream);
mp_dbg(MSGT_DEMUX,MSGL_DBG2, "o+: %02X %02X ",(vpkg_offset>>8)&0xff,vpkg_offset&0xff);
len-=2;
} else
vpkg_offset&=0x3fff;
vpkg_seqnum=stream_read_char(demuxer->stream); --len;
mp_dbg(MSGT_DEMUX,MSGL_DBG2, "seq: %02X ",vpkg_seqnum);
}
mp_dbg(MSGT_DEMUX,MSGL_DBG2, "\n");
mp_dbg(MSGT_DEMUX,MSGL_DBG2, "blklen=%d\n", len);
mp_msg(MSGT_DEMUX,MSGL_DBG2, "block: hdr=0x%0x, len=%d, offset=%d, seqnum=%d\n",
vpkg_header, vpkg_length, vpkg_offset, vpkg_seqnum);
if(ds->asf_packet){
dp=ds->asf_packet;
dp_hdr=(dp_hdr_t*)dp->buffer;
dp_data=dp->buffer+dp_hdr->header_buffer_len;
pkt_hdr=(packet_hdr_t *)(dp->buffer+sizeof(dp_hdr_t));
mp_dbg(MSGT_DEMUX,MSGL_DBG2, "we have an incomplete packet (oldseq=%d new=%d)\n",ds->asf_seq,vpkg_seqnum);
// we have an incomplete packet:
if(ds->asf_seq!=vpkg_seqnum){
// this fragment is for new packet, close the old one
mp_msg(MSGT_DEMUX,MSGL_DBG2, "closing probably incomplete packet, len: %d \n",dp->len);
queue_video_packet(priv, ds, dp);
ds->asf_packet=NULL;
} else {
// append data to it!
++dp_hdr->chunks;
mp_msg(MSGT_DEMUX,MSGL_DBG2,"[chunks=%d subseq=%d]\n",dp_hdr->chunks,vpkg_subseq);
pkt_hdr += dp_hdr->chunks;
pkt_hdr->offset = dp_hdr->len;
pkt_hdr->broken_up_by_us = broken_up_by_us;
if(0x80==(vpkg_header&0xc0)){
// last fragment!
if(dp_hdr->len!=vpkg_length-vpkg_offset)
mp_msg(MSGT_DEMUX,MSGL_V,"warning! assembled.len=%d frag.len=%d total.len=%d \n",dp->len,vpkg_offset,vpkg_length-vpkg_offset);
if (vpkg_offset > dp->len - dp_hdr->header_buffer_len - dp_hdr->len) vpkg_offset = dp->len - dp_hdr->header_buffer_len - dp_hdr->len;
stream_read(demuxer->stream, dp_data+dp_hdr->len, vpkg_offset);
parse_slice_header(sh_video,demuxer,pkt_hdr,dp_data+dp_hdr->len, vpkg_offset);
if((dp_data[dp_hdr->len]&0x20) && (sh_video->format==0x30335652)) --dp_hdr->chunks; else
dp_hdr->len+=vpkg_offset;
len-=vpkg_offset;
mp_dbg(MSGT_DEMUX,MSGL_DBG2, "fragment (%d bytes) appended, %d bytes left\n",vpkg_offset,len);
// we know that this is the last fragment -> we can close the packet!
queue_video_packet(priv, ds, dp);
ds->asf_packet=NULL;
// continue parsing
continue;
}
// non-last fragment:
if(dp_hdr->len!=vpkg_offset)
mp_msg(MSGT_DEMUX,MSGL_V,"warning! assembled.len=%d offset=%d frag.len=%d total.len=%d \n",dp->len,vpkg_offset,len,vpkg_length);
if (len > dp->len - dp_hdr->header_buffer_len - dp_hdr->len) len = dp->len - dp_hdr->header_buffer_len - dp_hdr->len;
stream_read(demuxer->stream, dp_data+dp_hdr->len, len);
parse_slice_header(sh_video,demuxer,pkt_hdr,dp_data+dp_hdr->len, len);
if((dp_data[dp_hdr->len]&0x20) && (sh_video->format==0x30335652)) --dp_hdr->chunks; else
dp_hdr->len+=len;
len=0;
break; // no more fragments in this chunk!
}
}
// create new packet!
dp = new_demux_packet(sizeof(dp_hdr_t)+vpkg_length+sizeof(packet_hdr_t)*(1+2*(vpkg_header&0x3F))+BUFFER_HEADER_EXTEND_FOR_WRITE);
// the timestamp seems to be in milliseconds
dp->pos = demuxer->filepos;
dp->flags = (flags & 0x2) ? 0x10 : 0;
ds->asf_seq = vpkg_seqnum;
dp_hdr=(dp_hdr_t*)dp->buffer;
dp_hdr->chunks=0;
dp_hdr->timestamp=timestamp;
dp_hdr->header_buffer_len=sizeof(dp_hdr_t)+sizeof(packet_hdr_t)*(1+2*(vpkg_header&0x3F))+BUFFER_HEADER_EXTEND_FOR_WRITE;
dp_data=dp->buffer+dp_hdr->header_buffer_len;
pkt_hdr=(packet_hdr_t *)(dp->buffer+sizeof(dp_hdr_t));
pkt_hdr->offset = 0;
pkt_hdr->broken_up_by_us = broken_up_by_us;
if(0x00==(vpkg_header&0xc0)){
// first fragment:
if (len > dp->len - dp_hdr->header_buffer_len) len = dp->len - dp_hdr->header_buffer_len;
dp_hdr->len=len;
stream_read(demuxer->stream, dp_data, len);
parse_slice_header(sh_video,demuxer,pkt_hdr,dp_data, len);
ds->asf_packet=dp;
len=0;
break;
}
// whole packet (not fragmented):
if (vpkg_length > len) {
mp_msg(MSGT_DEMUX, MSGL_WARN,"\n******** WARNING: vpkg_length=%i > len=%i ********\n", vpkg_length, len);
/*
* To keep the video stream rolling, we need to break
* here. We shouldn't touch len to make sure rest of the
* broken packet is skipped.
*/
break;
}
dp_hdr->len=vpkg_length; len-=vpkg_length;
stream_read(demuxer->stream, dp_data, vpkg_length);
parse_slice_header(sh_video,demuxer,pkt_hdr,dp_data, vpkg_length);
queue_video_packet(priv, ds, dp);
} // while(len>0)
if(len){
mp_msg(MSGT_DEMUX, MSGL_WARN,"\n******** !!!!!!!! BUG!! len=%d !!!!!!!!!!! ********\n",len);
if(len>0) stream_skip(demuxer->stream, len);
}
}
if ((unsigned)demuxer->video->id < MAX_STREAMS) {
while (priv->current_vpacket + 1 < priv->index_table_size[rm_stream_id] &&
timestamp > priv->index_table[rm_stream_id][priv->current_vpacket + 1].timestamp) {
priv->current_vpacket += 1;
priv->stream_switch = 1;
}
if (priv->stream_switch)
priv->video_curpos = stream_tell(demuxer->stream);
}
return 1;
}
if((unsigned)rm_stream_id<MAX_STREAMS){
if(demuxer->audio->id==-1 && demuxer->a_streams[mp_stream_id]){
sh_audio_t *sh = demuxer->a_streams[mp_stream_id];
demuxer->audio->id=mp_stream_id;
demuxer->audio->sh=sh;
mp_msg(MSGT_DEMUX,MSGL_V,"Auto-selected RM audio ID = %d (rm id %d)\n",mp_stream_id, rm_stream_id);
goto got_audio;
}
if(demuxer->video->id==-1 && demuxer->v_streams[mp_stream_id]){
sh_video_t *sh = demuxer->v_streams[mp_stream_id];
demuxer->video->id=mp_stream_id;
demuxer->video->sh=sh;
mp_msg(MSGT_DEMUX,MSGL_V,"Auto-selected RM video ID = %d (rm id %d)\n",mp_stream_id, rm_stream_id);
goto got_video;
}
}
mp_msg(MSGT_DEMUX,MSGL_DBG2, "unknown stream id (%d)\n", rm_stream_id);
discard:
stream_skip(demuxer->stream, len);
}// goto loop;
return 0;
}
static demuxer_t* demux_open_real(demuxer_t* demuxer)
{
real_priv_t* priv = demuxer->priv;
int num_of_headers;
int a_streams=0;
int v_streams=0;
int i;
int header_size;
priv->video_file_start = 1;
header_size = stream_read_dword(demuxer->stream); /* header size */
mp_msg(MSGT_DEMUX,MSGL_V, "real: Header size: %d\n", header_size);
i = stream_read_word(demuxer->stream); /* version */
mp_msg(MSGT_DEMUX,MSGL_V, "real: Header object version: %d\n", i);
if (header_size == 0x10)
i = stream_read_word(demuxer->stream);
else /* we should test header_size here too. */
i = stream_read_dword(demuxer->stream);
mp_msg(MSGT_DEMUX,MSGL_V, "real: File version: %d\n", i);
num_of_headers = stream_read_dword(demuxer->stream);
/* parse chunks */
for (i = 1; i <= num_of_headers; i++)
// for (i = 1; ; i++)
{
int chunk_id, chunk_pos, chunk_size;
chunk_pos = stream_tell(demuxer->stream);
chunk_id = stream_read_dword_le(demuxer->stream);
chunk_size = stream_read_dword(demuxer->stream);
stream_skip(demuxer->stream, 2); /* version */
mp_msg(MSGT_DEMUX,MSGL_V, "Chunk: %.4s (%x) (size: 0x%x, offset: 0x%x)\n",
(char *)&chunk_id, chunk_id, chunk_size, chunk_pos);
if (chunk_id != MKTAG('D', 'A', 'T', 'A') && chunk_size < 10){
mp_msg(MSGT_DEMUX,MSGL_ERR,"demux_real: invalid chunksize! (%d)\n",chunk_size);
break; //return;
}
switch(chunk_id)
{
case MKTAG('P', 'R', 'O', 'P'):
/* Properties header */
stream_skip(demuxer->stream, 4); /* max bitrate */
stream_skip(demuxer->stream, 4); /* avg bitrate */
stream_skip(demuxer->stream, 4); /* max packet size */
stream_skip(demuxer->stream, 4); /* avg packet size */
stream_skip(demuxer->stream, 4); /* nb packets */
priv->duration = stream_read_dword(demuxer->stream)/1000; /* duration */
stream_skip(demuxer->stream, 4); /* preroll */
priv->index_chunk_offset = stream_read_dword(demuxer->stream);
mp_msg(MSGT_DEMUX,MSGL_V,"First index chunk offset: 0x%x\n", priv->index_chunk_offset);
priv->data_chunk_offset = stream_read_dword(demuxer->stream)+10;
mp_msg(MSGT_DEMUX,MSGL_V,"First data chunk offset: 0x%x\n", priv->data_chunk_offset);
priv->streams_in_file = stream_read_word(demuxer->stream);
mp_msg(MSGT_DEMUX,MSGL_V,"Number of streams in file: %d\n", priv->streams_in_file);
#if 0
stream_skip(demuxer->stream, 2); /* flags */
#else
{
int flags = stream_read_word(demuxer->stream);
if (flags)
{
mp_msg(MSGT_DEMUX,MSGL_V,"Flags (%x): ", flags);
if (flags & 0x1)
mp_msg(MSGT_DEMUX,MSGL_V,"[save allowed] ");
if (flags & 0x2)
mp_msg(MSGT_DEMUX,MSGL_V,"[perfect play (more buffers)] ");
if (flags & 0x4)
mp_msg(MSGT_DEMUX,MSGL_V,"[live broadcast] ");
mp_msg(MSGT_DEMUX,MSGL_V,"\n");
}
}
#endif
break;
case MKTAG('C', 'O', 'N', 'T'):
{
/* Content description header */
char *buf;
int len;
len = stream_read_word(demuxer->stream);
if (len > 0)
{
buf = malloc(len+1);
stream_read(demuxer->stream, buf, len);
buf[len] = 0;
demux_info_add(demuxer, "title", buf);
free(buf);
}
len = stream_read_word(demuxer->stream);
if (len > 0)
{
buf = malloc(len+1);
stream_read(demuxer->stream, buf, len);
buf[len] = 0;
demux_info_add(demuxer, "author", buf);
free(buf);
}
len = stream_read_word(demuxer->stream);
if (len > 0)
{
buf = malloc(len+1);
stream_read(demuxer->stream, buf, len);
buf[len] = 0;
demux_info_add(demuxer, "copyright", buf);
free(buf);
}
len = stream_read_word(demuxer->stream);
if (len > 0)
{
buf = malloc(len+1);
stream_read(demuxer->stream, buf, len);
buf[len] = 0;
demux_info_add(demuxer, "comment", buf);
free(buf);
}
break;
}
case MKTAG('M', 'D', 'P', 'R'):
{
/* Media properties header */
int stream_id;
int bitrate;
int codec_data_size;
int codec_pos;
int tmp;
int len;
char *descr, *mimet = NULL;
stream_id = stream_read_word(demuxer->stream);
mp_msg(MSGT_DEMUX,MSGL_V,"Found new stream (id: %d)\n", stream_id);
stream_skip(demuxer->stream, 4); /* max bitrate */
bitrate = stream_read_dword(demuxer->stream); /* avg bitrate */
stream_skip(demuxer->stream, 4); /* max packet size */
stream_skip(demuxer->stream, 4); /* avg packet size */
stream_skip(demuxer->stream, 4); /* start time */
stream_skip(demuxer->stream, 4); /* preroll */
stream_skip(demuxer->stream, 4); /* duration */
if ((len = stream_read_char(demuxer->stream)) > 0) {
descr = malloc(len+1);
stream_read(demuxer->stream, descr, len);
descr[len] = 0;
mp_msg(MSGT_DEMUX, MSGL_INFO,"Stream description: %s\n", descr);
free(descr);
}
if ((len = stream_read_char(demuxer->stream)) > 0) {
mimet = malloc(len+1);
stream_read(demuxer->stream, mimet, len);
mimet[len] = 0;
mp_msg(MSGT_DEMUX, MSGL_INFO,"Stream mimetype: %s\n", mimet);
}
/* Type specific header */
codec_data_size = stream_read_dword(demuxer->stream);
codec_pos = stream_tell(demuxer->stream);
#ifdef MP_DEBUG
#define stream_skip(st,siz) { int i; for(i=0;i<siz;i++) mp_msg(MSGT_DEMUX,MSGL_V," %02X",stream_read_char(st)); mp_msg(MSGT_DEMUX,MSGL_V,"\n");}
#endif
if (!strncmp(mimet,"audio/",6)) {
if (strstr(mimet,"x-pn-realaudio") || strstr(mimet,"x-pn-multirate-realaudio")) {
int num_mlti, mlti_cnt, ra_size;
tmp = stream_read_dword(demuxer->stream);
if (tmp == MKTAG('I', 'T', 'L', 'M')) // MLTI chunk in audio
{
int num_streams, stream_cnt;
mp_msg(MSGT_DEMUX,MSGL_V,"MLTI chunk in audio.\n");
num_streams = stream_read_word(demuxer->stream);
for (stream_cnt = 0; stream_cnt < num_streams; stream_cnt++)
stream_skip(demuxer->stream, 2); // MDPR index, one per stream
num_mlti = stream_read_word(demuxer->stream);
if (num_mlti != 1) {
mp_msg(MSGT_DEMUX,MSGL_V,"Found MLTI in audio with %d substreams.\n", num_mlti);
priv->is_mlti = 1;
} else
mp_msg(MSGT_DEMUX,MSGL_V,"Found MLTI in audio with 1 substream. Ignoring\n");
if (num_mlti > MAX_MLTIIDX) {
mp_msg(MSGT_DEMUX,MSGL_ERR,"Too many (%d) MLTI audio, truncating; expect problems. Please report to Mplayer developers.\n", num_mlti);
num_mlti = MAX_MLTIIDX - 1; // Limit to max MLTI
}
ra_size = stream_read_dword(demuxer->stream); // Size of the following .ra chunk
tmp = stream_read_dword(demuxer->stream);
} else {
num_mlti = 1;
ra_size = codec_data_size;
}
for (mlti_cnt = 0; mlti_cnt < num_mlti; mlti_cnt++) {
if (mlti_cnt) {
ra_size = stream_read_dword(demuxer->stream); // Size of the following .ra chunk
tmp = stream_read_dword(demuxer->stream);
}
if (tmp != MKTAG(0xfd, 'a', 'r', '.'))
{
mp_msg(MSGT_DEMUX,MSGL_V,"Audio: can't find .ra in codec data\n");
stream_skip(demuxer->stream, ra_size - 4);
} else {
/* audio header */
int aid = priv->is_mlti ? priv->streams_in_file + a_streams + v_streams : stream_id;
sh_audio_t *sh = new_sh_audio(demuxer, aid, NULL);
char buf[128]; /* for codec name */
int frame_size;
int sub_packet_size = 0;
int sub_packet_h = 0;
int version;
int coded_frame_size = 0;
int codecdata_length;
int i;
char *buft;
int hdr_size;
mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_AudioID, "real", aid);
priv->mp2rm_streamid[aid] = stream_id;
priv->rm2mp[stream_id][mlti_cnt] = aid;
mp_msg(MSGT_DEMUX,MSGL_V,"Mplayer aid %d is rm stream %d with MDPR index %d\n", aid, stream_id, mlti_cnt);
mp_msg(MSGT_DEMUX,MSGL_V,"Found audio stream!\n");
version = stream_read_word(demuxer->stream);
mp_msg(MSGT_DEMUX,MSGL_V,"version: %d\n", version);
if (version == 3) {
stream_skip(demuxer->stream, 2);
stream_skip(demuxer->stream, 10);
stream_skip(demuxer->stream, 4);
// Name, author, (c) are also in CONT tag
if ((i = stream_read_char(demuxer->stream)) != 0) {
buft = malloc(i+1);
stream_read(demuxer->stream, buft, i);
buft[i] = 0;
demux_info_add(demuxer, "Name", buft);
free(buft);
}
if ((i = stream_read_char(demuxer->stream)) != 0) {
buft = malloc(i+1);
stream_read(demuxer->stream, buft, i);
buft[i] = 0;
demux_info_add(demuxer, "Author", buft);
free(buft);
}
if ((i = stream_read_char(demuxer->stream)) != 0) {
buft = malloc(i+1);
stream_read(demuxer->stream, buft, i);
buft[i] = 0;
demux_info_add(demuxer, "Copyright", buft);
free(buft);
}
if ((i = stream_read_char(demuxer->stream)) != 0)
mp_msg(MSGT_DEMUX,MSGL_WARN,"Last header byte is not zero!\n");
stream_skip(demuxer->stream, 1);
i = stream_read_char(demuxer->stream);
sh->format = stream_read_dword_le(demuxer->stream);
if (i != 4) {
mp_msg(MSGT_DEMUX,MSGL_WARN,"Audio FourCC size is not 4 (%d), please report to "
"MPlayer developers\n", i);
stream_skip(demuxer->stream, i - 4);
}
if (sh->format != mmioFOURCC('l','p','c','J')) {
mp_msg(MSGT_DEMUX,MSGL_WARN,"Version 3 audio with FourCC %8x, please report to "
"MPlayer developers\n", sh->format);
}
sh->channels = 1;
sh->samplesize = 16;
sh->samplerate = 8000;
frame_size = 240;
strcpy(buf, "14_4");
} else {
stream_skip(demuxer->stream, 2); // 00 00
stream_skip(demuxer->stream, 4); /* .ra4 or .ra5 */
stream_skip(demuxer->stream, 4); // ???
stream_skip(demuxer->stream, 2); /* version (4 or 5) */
hdr_size = stream_read_dword(demuxer->stream); // header size
mp_msg(MSGT_DEMUX,MSGL_V,"header size: %d\n", hdr_size);
stream_skip(demuxer->stream, 2);/* codec flavor id */
coded_frame_size = stream_read_dword(demuxer->stream);/* needed by codec */
mp_msg(MSGT_DEMUX,MSGL_V,"coded_frame_size: %d\n", coded_frame_size);
stream_skip(demuxer->stream, 4); // big number
stream_skip(demuxer->stream, 4); // bigger number
stream_skip(demuxer->stream, 4); // 2 || -''-
sub_packet_h = stream_read_word(demuxer->stream);
mp_msg(MSGT_DEMUX,MSGL_V,"sub_packet_h: %d\n", sub_packet_h);
frame_size = stream_read_word(demuxer->stream);
mp_msg(MSGT_DEMUX,MSGL_V,"frame_size: %d\n", frame_size);
sub_packet_size = stream_read_word(demuxer->stream);
mp_msg(MSGT_DEMUX,MSGL_V,"sub_packet_size: %d\n", sub_packet_size);
stream_skip(demuxer->stream, 2); // 0
if (version == 5)
stream_skip(demuxer->stream, 6); //0,srate,0
sh->samplerate = stream_read_word(demuxer->stream);
stream_skip(demuxer->stream, 2); // 0
sh->samplesize = stream_read_word(demuxer->stream)/8;
sh->channels = stream_read_word(demuxer->stream);
mp_msg(MSGT_DEMUX,MSGL_V,"samplerate: %d, channels: %d\n",
sh->samplerate, sh->channels);
if (version == 5)
{
stream_read(demuxer->stream, buf, 4); // interleaver id
priv->intl_id[aid] = MKTAG(buf[0], buf[1], buf[2], buf[3]);
stream_read(demuxer->stream, buf, 4); // fourcc
buf[4] = 0;
}
else
{
/* Interleaver id */
get_str(1, demuxer, buf, sizeof(buf));
priv->intl_id[aid] = MKTAG(buf[0], buf[1], buf[2], buf[3]);
/* Codec FourCC */
get_str(1, demuxer, buf, sizeof(buf));
}
}
/* Emulate WAVEFORMATEX struct: */
sh->wf = calloc(1, sizeof(*sh->wf));
sh->wf->nChannels = sh->channels;
sh->wf->wBitsPerSample = sh->samplesize*8;
sh->wf->nSamplesPerSec = sh->samplerate;
sh->wf->nAvgBytesPerSec = bitrate/8;
sh->wf->nBlockAlign = frame_size;
sh->wf->cbSize = 0;
sh->format = MKTAG(buf[0], buf[1], buf[2], buf[3]);
switch (sh->format)
{
case MKTAG('d', 'n', 'e', 't'):
mp_msg(MSGT_DEMUX,MSGL_V,"Audio: DNET -> AC3\n");
// sh->format = 0x2000;
break;
case MKTAG('1', '4', '_', '4'):
sh->wf->nBlockAlign = 0x14;
break;
case MKTAG('2', '8', '_', '8'):
sh->wf->nBlockAlign = coded_frame_size;
break;
case MKTAG('s', 'i', 'p', 'r'):
case MKTAG('a', 't', 'r', 'c'):
case MKTAG('c', 'o', 'o', 'k'):
// realaudio codec plugins - common:
stream_skip(demuxer->stream,3); // Skip 3 unknown bytes
if (version==5)
stream_skip(demuxer->stream,1); // Skip 1 additional unknown byte
codecdata_length=stream_read_dword(demuxer->stream);
// Check extradata len, we can't store bigger values in cbSize anyway
if ((unsigned)codecdata_length > 0xffff) {
mp_msg(MSGT_DEMUX,MSGL_ERR,"Extradata too big (%d)\n", codecdata_length);
goto skip_this_chunk;
}
sh->wf->cbSize = codecdata_length;
sh->wf = realloc(sh->wf, sizeof(*sh->wf)+sh->wf->cbSize);
stream_read(demuxer->stream, ((char*)(sh->wf+1)), codecdata_length); // extras
if (priv->intl_id[aid] == MKTAG('g', 'e', 'n', 'r'))
sh->wf->nBlockAlign = sub_packet_size;
else
sh->wf->nBlockAlign = coded_frame_size;
break;
case MKTAG('r', 'a', 'a', 'c'):
case MKTAG('r', 'a', 'c', 'p'):
/* This is just AAC. The two or five bytes of */
/* config data needed for libfaad are stored */
/* after the audio headers. */
stream_skip(demuxer->stream,3); // Skip 3 unknown bytes
if (version==5)
stream_skip(demuxer->stream,1); // Skip 1 additional unknown byte
codecdata_length=stream_read_dword(demuxer->stream);
if (codecdata_length>=1) {
sh->codecdata_len = codecdata_length - 1;
sh->codecdata = calloc(sh->codecdata_len, 1);
stream_skip(demuxer->stream, 1);
stream_read(demuxer->stream, sh->codecdata, sh->codecdata_len);
}
sh->format = mmioFOURCC('M', 'P', '4', 'A');
break;
default:
mp_msg(MSGT_DEMUX,MSGL_V,"Audio: Unknown (%s)\n", buf);
}
// Interleaver setup
priv->sub_packet_size[aid] = sub_packet_size;
priv->sub_packet_h[aid] = sub_packet_h;
priv->coded_framesize[aid] = coded_frame_size;
priv->audiopk_size[aid] = frame_size;
sh->wf->wFormatTag = sh->format;
mp_msg(MSGT_DEMUX,MSGL_V,"audio fourcc: %.4s (%x)\n", (char *)&sh->format, sh->format);
if ( mp_msg_test(MSGT_DEMUX,MSGL_V) )
print_wave_header(sh->wf, MSGL_V);
/* Select audio stream with highest bitrate if multirate file*/
if (priv->is_multirate && ((demuxer->audio->id == -1) ||
((demuxer->audio->id >= 0) && priv->a_bitrate && (bitrate > priv->a_bitrate)))) {
demuxer->audio->id = stream_id;
demuxer->audio->sh = sh;
priv->a_bitrate = bitrate;
mp_msg(MSGT_DEMUX,MSGL_DBG2,"Multirate autoselected audio id %d with bitrate %d\n", stream_id, bitrate);
}
++a_streams;
#ifdef stream_skip
#undef stream_skip
#endif
} // .ra
} // MLTI
} else if (strstr(mimet,"X-MP3-draft-00")) {
sh_audio_t *sh = new_sh_audio(demuxer, stream_id, NULL);
mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_AudioID, "real", stream_id);
/* Emulate WAVEFORMATEX struct: */
sh->wf = calloc(1, sizeof(*sh->wf));
sh->wf->nChannels = 0;//sh->channels;
sh->wf->wBitsPerSample = 16;
sh->wf->nSamplesPerSec = 0;//sh->samplerate;
sh->wf->nAvgBytesPerSec = 0;//bitrate;
sh->wf->nBlockAlign = 0;//frame_size;
sh->wf->cbSize = 0;
sh->wf->wFormatTag = sh->format = mmioFOURCC('a','d','u',0x55);
++a_streams;
} else if (strstr(mimet,"x-ralf-mpeg4")) {
sh_audio_t *sh = new_sh_audio(demuxer, stream_id, NULL);
mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_AudioID, "real", stream_id);
// Check extradata len, we can't store bigger values in cbSize anyway
if ((unsigned)codec_data_size > 0xffff) {
mp_msg(MSGT_DEMUX,MSGL_ERR,"Extradata too big (%d)\n", codec_data_size);
goto skip_this_chunk;
}
/* Emulate WAVEFORMATEX struct: */
sh->wf = calloc(1, sizeof(*sh->wf)+codec_data_size);
sh->wf->nChannels = 0;
sh->wf->wBitsPerSample = 16;
sh->wf->nSamplesPerSec = 0;
sh->wf->nAvgBytesPerSec = 0;
sh->wf->nBlockAlign = 0;
sh->wf->wFormatTag = sh->format = mmioFOURCC('L','S','D',':');
sh->wf->cbSize = codec_data_size;
stream_read(demuxer->stream, (char*)(sh->wf+1), codec_data_size);
++a_streams;
} else if (strstr(mimet,"x-pn-encrypted-ra")) {
mp_msg(MSGT_DEMUX,MSGL_ERR,"Encrypted audio is not supported\n");
} else {
mp_msg(MSGT_DEMUX,MSGL_V,"Unknown audio stream format\n");
}
} else if (!strncmp(mimet,"video/",6)) {
if (strstr(mimet,"x-pn-realvideo") || strstr(mimet,"x-pn-multirate-realvideo")) {
int num_mlti, mlti_cnt, vido_size, vido_pos;
tmp = stream_read_dword(demuxer->stream);
if (tmp == MKTAG('I', 'T', 'L', 'M')) // MLTI chunk in video
{
int num_streams, stream_cnt;
mp_msg(MSGT_DEMUX,MSGL_V,"MLTI chunk in video.\n");
num_streams = stream_read_word(demuxer->stream);
for (stream_cnt = 0; stream_cnt < num_streams; stream_cnt++)
stream_skip(demuxer->stream, 2); // MDPR index, one per stream
num_mlti = stream_read_word(demuxer->stream);
if (num_mlti != 1) {
mp_msg(MSGT_DEMUX,MSGL_V,"Found MLTI in video with %d substreams.\n", num_mlti);
priv->is_mlti = 1;
} else
mp_msg(MSGT_DEMUX,MSGL_V,"Found MLTI in audio with 1 substream. Ignoring\n");
if (num_mlti > MAX_MLTIIDX) {
mp_msg(MSGT_DEMUX,MSGL_ERR,"Too many (%d) MLTI video, truncating; expect problems. Please report to Mplayer developers.\n", num_mlti);
num_mlti = MAX_MLTIIDX - 1; // Limit to max MLTI
}
vido_size = stream_read_dword(demuxer->stream); // Size of the following .vido chunk
vido_pos = stream_tell(demuxer->stream);;
stream_skip(demuxer->stream, 4);
tmp = stream_read_dword(demuxer->stream);
priv->is_mlti = 1;
} else {
num_mlti = 1;
vido_size = codec_data_size;
vido_pos = codec_pos;
tmp = stream_read_dword(demuxer->stream);
}
for (mlti_cnt = 0; mlti_cnt < num_mlti; mlti_cnt++) {
if (mlti_cnt) {
vido_size = stream_read_dword(demuxer->stream); // Size of the following vido chunk
mp_msg(MSGT_DEMUX,MSGL_V,"VIDO size: %x\n", vido_size);
vido_pos = stream_tell(demuxer->stream);;
stream_skip(demuxer->stream, 4);
tmp = stream_read_dword(demuxer->stream);
}
if(tmp != MKTAG('O', 'D', 'I', 'V'))
{
mp_msg(MSGT_DEMUX,MSGL_V,"Video: can't find VIDO in codec data\n");
stream_skip(demuxer->stream, vido_size - 4);
} else {
/* video header */
int vid = priv->is_mlti ? priv->streams_in_file + a_streams + v_streams : stream_id;
sh_video_t *sh = new_sh_video(demuxer, vid);
sh_real_opaque_data_t *opaque = &priv->real_video_opaque;
opaque->media_object_format = tmp;
opaque->opauqe_data_size = 0;
mp_msg(MSGT_DEMUX, MSGL_INFO, MSGTR_VideoID, "real", vid);
priv->mp2rm_streamid[vid] = stream_id;
priv->rm2mp[stream_id][mlti_cnt] = vid;
mp_msg(MSGT_DEMUX,MSGL_V,"Mplayer vid %d is rm stream %d with MDPR index %d\n", vid, stream_id, mlti_cnt);
sh->format = stream_read_dword_le(demuxer->stream); /* fourcc */
mp_msg(MSGT_DEMUX,MSGL_V,"video fourcc: %.4s (%x)\n", (char *)&sh->format, sh->format);
/* emulate BITMAPINFOHEADER */
sh->bih = calloc(1, sizeof(*sh->bih));
sh->bih->biSize = sizeof(*sh->bih);
priv->prev_width = sh->disp_w = sh->bih->biWidth = stream_read_word(demuxer->stream);
priv->prev_height = sh->disp_h = sh->bih->biHeight = stream_read_word(demuxer->stream);
if (sh->disp_w > 0 && sh->disp_h > 0)
sh->original_aspect = (float)sh->disp_w / sh->disp_h;
sh->bih->biPlanes = 1;
sh->bih->biBitCount = 24;
sh->bih->biCompression = sh->format;
sh->bih->biSizeImage= sh->bih->biWidth*sh->bih->biHeight*3;
sh->fps = (float) stream_read_word(demuxer->stream);
//add by libin ------this 16 bits is bit_count in protocol ,but mplayer set it as fps ,dont know why??
opaque->bit_count = (unsigned short)sh->fps;
if (sh->fps<=0) sh->fps=24; // we probably won't even care about fps
sh->frametime = 1.0f/sh->fps;
#if 1
//stream_skip(demuxer->stream, 4);
opaque->pad_width = stream_read_word(demuxer->stream);
opaque->pad_height = stream_read_word(demuxer->stream);
#else
mp_msg(MSGT_DEMUX, MSGL_V,"unknown1: 0x%X \n",stream_read_dword(demuxer->stream));
mp_msg(MSGT_DEMUX, MSGL_V,"unknown2: 0x%X \n",stream_read_word(demuxer->stream));
mp_msg(MSGT_DEMUX, MSGL_V,"unknown3: 0x%X \n",stream_read_word(demuxer->stream));
#endif
// if(sh->format==0x30335652 || sh->format==0x30325652 )
if(1)
{
int tmp=stream_read_word(demuxer->stream);
if(tmp>0){
sh->fps=tmp; sh->frametime = 1.0f/sh->fps;
}
} else {
int fps=stream_read_word(demuxer->stream);
mp_msg(MSGT_DEMUX, MSGL_WARN,"realvid: ignoring FPS = %d\n",fps);
}
stream_skip(demuxer->stream, 2);
{
// read and store codec extradata
unsigned int cnt = vido_size - (stream_tell(demuxer->stream) - vido_pos);
if (cnt > 0x7fffffff - sizeof(*sh->bih)) {
mp_msg(MSGT_DEMUX, MSGL_ERR,"Extradata too big (%u)\n", cnt);
} else {
sh->bih = realloc(sh->bih, sizeof(*sh->bih) + cnt);
sh->bih->biSize += cnt;
stream_read(demuxer->stream, ((unsigned char*)(sh->bih+1)), cnt);
opaque->p_opaque_data = ((unsigned char*)(sh->bih+1));
opaque->opauqe_data_size = cnt;
}
}
if(sh->format == 0x30315652 && ((unsigned char*)(sh->bih+1))[6] == 0x30)
sh->bih->biCompression = sh->format = mmioFOURCC('R', 'V', '1', '3');
/* Select video stream with highest bitrate if multirate file*/
if (priv->is_multirate && ((demuxer->video->id == -1) ||
((demuxer->video->id >= 0) && priv->v_bitrate && (bitrate > priv->v_bitrate)))) {
demuxer->video->id = stream_id;
demuxer->video->sh = sh;
priv->v_bitrate = bitrate;
mp_msg(MSGT_DEMUX,MSGL_DBG2,"Multirate autoselected video id %d with bitrate %d\n", stream_id, bitrate);
}
++v_streams;
} // VIDO
} // MLTI
} else {
mp_msg(MSGT_DEMUX,MSGL_V,"Unknown video stream format\n");
}
} else if (strstr(mimet,"logical-")) {
if (strstr(mimet,"fileinfo")) {
mp_msg(MSGT_DEMUX,MSGL_V,"Got a logical-fileinfo chunk\n");
} else if (strstr(mimet,"-audio") || strstr(mimet,"-video")) {
int i, stream_cnt;
int stream_list[MAX_STREAMS];
priv->is_multirate = 1;
stream_skip(demuxer->stream, 4); // Length of codec data (repeated)
stream_cnt = stream_read_dword(demuxer->stream); // Get number of audio or video streams
if ((unsigned)stream_cnt >= MAX_STREAMS) {
mp_msg(MSGT_DEMUX,MSGL_ERR,"Too many streams in %s. Big troubles ahead.\n", mimet);
goto skip_this_chunk;
}
for (i = 0; i < stream_cnt; i++)
stream_list[i] = stream_read_word(demuxer->stream);
for (i = 0; i < stream_cnt; i++)
if ((unsigned)stream_list[i] >= MAX_STREAMS) {
mp_msg(MSGT_DEMUX,MSGL_ERR,"Stream id out of range: %d. Ignored.\n", stream_list[i]);
stream_skip(demuxer->stream, 4); // Skip DATA offset for broken stream
} else {
priv->str_data_offset[stream_list[i]] = stream_read_dword(demuxer->stream);
mp_msg(MSGT_DEMUX,MSGL_V,"Stream %d with DATA offset 0x%08x\n", stream_list[i], priv->str_data_offset[stream_list[i]]);
}
// Skip the rest of this chunk
} else
mp_msg(MSGT_DEMUX,MSGL_V,"Unknown logical stream\n");
}
else {
mp_msg(MSGT_DEMUX, MSGL_ERR, "Not audio/video stream or unsupported!\n");
}
// break;
// default:
skip_this_chunk:
/* skip codec info */
tmp = stream_tell(demuxer->stream) - codec_pos;
mp_msg(MSGT_DEMUX,MSGL_V,"### skipping %d bytes of codec info\n", codec_data_size - tmp);
#if 0
{ int i;
for(i=0;i<codec_data_size - tmp;i++)
mp_msg(MSGT_DEMUX, MSGL_V," %02X",stream_read_char(demuxer->stream));
mp_msg(MSGT_DEMUX, MSGL_V,"\n");
}
#else
stream_skip(demuxer->stream, codec_data_size - tmp);
#endif
free (mimet);
break;
// }
}
case MKTAG('D', 'A', 'T', 'A'):
goto header_end;
case MKTAG('I', 'N', 'D', 'X'):
default:
mp_msg(MSGT_DEMUX,MSGL_V,"Unknown chunk: %x\n", chunk_id);
stream_skip(demuxer->stream, chunk_size - 10);
break;
}
}
header_end:
if(priv->is_multirate && priv->is_mlti)
mp_msg(MSGT_DEMUX,MSGL_ERR,"Multirate and MLTI in the same file is bad. Please contact Mplayer developers.\n");
if(priv->is_multirate) {
mp_msg(MSGT_DEMUX,MSGL_V,"Selected video id %d audio id %d\n", demuxer->video->id, demuxer->audio->id);
/* Perform some sanity checks to avoid checking streams id all over the code*/
if (demuxer->audio->id >= MAX_STREAMS) {
mp_msg(MSGT_DEMUX,MSGL_ERR,"Invalid audio stream %d. No sound will be played.\n", demuxer->audio->id);
demuxer->audio->id = -2;
} else if ((demuxer->audio->id >= 0) && (priv->str_data_offset[demuxer->audio->id] == 0)) {
mp_msg(MSGT_DEMUX,MSGL_ERR,"Audio stream %d not found. No sound will be played.\n", demuxer->audio->id);
demuxer->audio->id = -2;
}
if (demuxer->video->id >= MAX_STREAMS) {
mp_msg(MSGT_DEMUX,MSGL_ERR,"Invalid video stream %d. No video will be played.\n", demuxer->video->id);
demuxer->video->id = -2;
} else if ((demuxer->video->id >= 0) && (priv->str_data_offset[demuxer->video->id] == 0)) {
mp_msg(MSGT_DEMUX,MSGL_ERR,"Video stream %d not found. No video will be played.\n", demuxer->video->id);
demuxer->video->id = -2;
}
}
if(priv->is_multirate && ((demuxer->video->id >= 0) || (demuxer->audio->id >=0))) {
/* If audio or video only, seek to right place and behave like standard file */
if (demuxer->video->id < 0) {
// Stream is audio only, or -novideo
stream_seek(demuxer->stream, priv->data_chunk_offset = priv->str_data_offset[demuxer->audio->id]+10);
priv->is_multirate = 0;
}
if (demuxer->audio->id < 0) {
// Stream is video only, or -nosound
stream_seek(demuxer->stream, priv->data_chunk_offset = priv->str_data_offset[demuxer->video->id]+10);
priv->is_multirate = 0;
}
}
if(!priv->is_multirate) {
// printf("i=%d num_of_headers=%d \n",i,num_of_headers);
priv->num_of_packets = stream_read_dword(demuxer->stream);
stream_skip(demuxer->stream, 4); /* next data header */
mp_msg(MSGT_DEMUX,MSGL_V,"Packets in file: %d\n", priv->num_of_packets);
if (priv->num_of_packets == 0)
priv->num_of_packets = -10;
} else {
priv->audio_curpos = priv->str_data_offset[demuxer->audio->id] + 18;
stream_seek(demuxer->stream, priv->str_data_offset[demuxer->audio->id]+10);
priv->a_num_of_packets = stream_read_dword(demuxer->stream);
priv->video_curpos = priv->str_data_offset[demuxer->video->id] + 18;
stream_seek(demuxer->stream, priv->str_data_offset[demuxer->video->id]+10);
priv->v_num_of_packets = stream_read_dword(demuxer->stream);
priv->stream_switch = 1;
/* Index required for multirate playback, force building if it's not there */
/* but respect user request to force index regeneration */
if (index_mode == -1)
index_mode = 1;
}
priv->audio_need_keyframe = 0;
priv->video_after_seek = 0;
switch (index_mode){
case -1: // untouched
if ((demuxer->stream->flags & MP_STREAM_SEEK) == MP_STREAM_SEEK &&
priv->index_chunk_offset && parse_index_chunk(demuxer))
{
demuxer->seekable = 1;
}
break;
case 1: // use (generate index)
if (priv->index_chunk_offset && parse_index_chunk(demuxer))
{
demuxer->seekable = 1;
} else {
generate_index(demuxer);
demuxer->seekable = 1;
}
break;
case 2: // force generating index
generate_index(demuxer);
demuxer->seekable = 1;
break;
default: // do nothing
break;
}
// detect streams:
if(demuxer->video->id==-1 && v_streams>0){
// find the valid video stream:
ds_fill_buffer(demuxer->video);
}
if(demuxer->audio->id==-1 && a_streams>0){
// find the valid audio stream:
if(!ds_fill_buffer(demuxer->audio)){
mp_msg(MSGT_DEMUXER,MSGL_INFO,"RM: " MSGTR_MissingAudioStream);
}
}
if(demuxer->video->id==-1 && v_streams>0){
// try video once more in case there were too many audio packets first.
demuxer->video->eof = 0;
demuxer->video->fill_count = 0;
if(!ds_fill_buffer(demuxer->video)){
mp_msg(MSGT_DEMUXER,MSGL_INFO,"RM: " MSGTR_MissingVideoStream);
}
}
if(demuxer->video->id==-1 && v_streams>0){
// worst case just select the first
int i;
for (i = 0; i < MAX_V_STREAMS; i++)
if (demuxer->v_streams[i]) {
demuxer->video->id = i;
demuxer->video->sh = demuxer->v_streams[i];
}
}
if(demuxer->audio->id==-1 && a_streams>0){
// worst case just select the first
int i;
for (i = 0; i < MAX_A_STREAMS; i++)
if (demuxer->a_streams[i]) {
demuxer->audio->id = i;
demuxer->audio->sh = demuxer->a_streams[i];
}
}
if(demuxer->video->sh){
sh_video_t *sh=demuxer->video->sh;
mp_msg(MSGT_DEMUX,MSGL_V,"VIDEO: %.4s [%08X,%08X] %dx%d (aspect %4.2f) %4.2f fps\n",
(char *)&sh->format,((unsigned int*)(sh->bih+1))[1],((unsigned int*)(sh->bih+1))[0],
sh->disp_w,sh->disp_h,sh->aspect,sh->fps);
}
if(demuxer->audio->sh){
sh_audio_t *sh=demuxer->audio->sh;
mp_msg(MSGT_DEMUX,MSGL_V,"AUDIO: %.4s [%08X]\n",
(char *)&sh->format,sh->format);
}
return demuxer;
}
static void demux_close_real(demuxer_t *demuxer)
{
int i;
real_priv_t* priv = demuxer->priv;
if (priv){
for(i=0; i<MAX_STREAMS; i++)
free(priv->index_table[i]);
free(priv->audio_buf);
free(priv->audio_timestamp);
free(priv);
}
return;
}
/* please upload RV10 samples WITH INDEX CHUNK */
static void demux_seek_real(demuxer_t *demuxer, float rel_seek_secs, float audio_delay, int flags)
{
real_priv_t *priv = demuxer->priv;
demux_stream_t *d_audio = demuxer->audio;
demux_stream_t *d_video = demuxer->video;
sh_audio_t *sh_audio = d_audio->sh;
sh_video_t *sh_video = d_video->sh;
int vid = d_video->id, aid = d_audio->id;
int next_offset = 0;
int64_t target_timestamp = 0;
int streams = 0;
int retried = 0;
if (priv->is_mlti && (unsigned)vid < MAX_STREAMS)
vid = priv->mp2rm_streamid[d_video->id];
if (priv->is_mlti && (unsigned)aid < MAX_STREAMS)
aid = priv->mp2rm_streamid[d_audio->id];
if (sh_video && (unsigned)vid < MAX_STREAMS && priv->index_table_size[vid])
streams |= 1;
if (sh_audio && (unsigned)aid < MAX_STREAMS && priv->index_table_size[aid])
streams |= 2;
// printf("streams: %d\n", streams);
if (!streams)
return;
if (flags & SEEK_ABSOLUTE)
priv->current_apacket = priv->current_vpacket = 0;
if (flags & SEEK_FACTOR)
rel_seek_secs *= priv->duration;
if ((streams & 1) && priv->current_vpacket >= priv->index_table_size[vid])
priv->current_vpacket = priv->index_table_size[vid] - 1;
if ((streams & 2) && priv->current_apacket >= priv->index_table_size[aid])
priv->current_apacket = priv->index_table_size[aid] - 1;
// if (index_mode == 1 || index_mode == 2) {
if (streams & 1) {// use the video index if we have one
target_timestamp = priv->index_table[vid][priv->current_vpacket].timestamp;
target_timestamp += rel_seek_secs * 1000;
if (rel_seek_secs > 0)
while (priv->index_table[vid][priv->current_vpacket].timestamp < target_timestamp){
priv->current_vpacket += 1;
if (priv->current_vpacket >= priv->index_table_size[vid]) {
priv->current_vpacket = priv->index_table_size[vid] - 1;
if (!retried) {
stream_seek(demuxer->stream, priv->index_table[vid][priv->current_vpacket].offset);
add_index_segment(demuxer, vid, target_timestamp);
retried = 1;
}
else
break;
}
}
else if (rel_seek_secs < 0) {
while (priv->index_table[vid][priv->current_vpacket].timestamp > target_timestamp){
priv->current_vpacket -= 1;
if (priv->current_vpacket < 0) {
priv->current_vpacket = 0;
break;
}
}
}
priv->video_curpos = priv->index_table[vid][priv->current_vpacket].offset;
priv->audio_need_keyframe = !priv->is_multirate;
priv->video_after_seek = 1;
} else {
target_timestamp = priv->index_table[aid][priv->current_apacket].timestamp;
target_timestamp += rel_seek_secs * 1000;
}
if (streams & 2) {
if (rel_seek_secs > 0)
while (priv->index_table[aid][priv->current_apacket].timestamp < target_timestamp){
priv->current_apacket += 1;
if (priv->current_apacket >= priv->index_table_size[aid]) {
priv->current_apacket = priv->index_table_size[aid] - 1;
break;
}
}
else if (rel_seek_secs < 0)
while (priv->index_table[aid][priv->current_apacket].timestamp > target_timestamp){
priv->current_apacket -= 1;
if (priv->current_apacket < 0) {
priv->current_apacket = 0;
break;
}
}
priv->audio_curpos = priv->index_table[aid][priv->current_apacket].offset;
}
// }
next_offset = streams & 1 ? priv->video_curpos : priv->audio_curpos;
// printf("seek: pos: %d, current packets: a: %d, v: %d\n",
// next_offset, priv->current_apacket, priv->current_vpacket);
if (next_offset)
stream_seek(demuxer->stream, next_offset);
demux_real_fill_buffer(demuxer, NULL);
}
static int demux_real_control(demuxer_t *demuxer, int cmd, void *arg)
{
real_priv_t *priv = demuxer->priv;
unsigned int lastpts = priv->v_pts ? priv->v_pts : priv->a_pts;
switch (cmd) {
case DEMUXER_CTRL_GET_TIME_LENGTH:
if (priv->duration == 0)
return DEMUXER_CTRL_DONTKNOW;
*((double *)arg) = (double)priv->duration;
return DEMUXER_CTRL_OK;
case DEMUXER_CTRL_GET_PERCENT_POS:
if (priv->duration == 0)
return DEMUXER_CTRL_DONTKNOW;
*((int *)arg) = (int)(100 * lastpts / priv->duration);
return DEMUXER_CTRL_OK;
default:
return DEMUXER_CTRL_NOTIMPL;
}
}
const demuxer_desc_t demuxer_desc_real = {
"Realmedia demuxer",
"real",
"REAL",
"Alex Beregszasi, Florian Schneider, A'rpi, Roberto Togni",
"handles new .RMF files",
DEMUXER_TYPE_REAL,
1, // safe autodetect
real_check_file,
demux_real_fill_buffer,
demux_open_real,
demux_close_real,
demux_seek_real,
demux_real_control
};
| 35.559515 | 179 | 0.614931 | [
"object"
] |
b3f9e8b32e53e6d4c928be9482f4107e3e7538ad | 1,989 | h | C | KDDockWidgets/src/MDIArea.h | fritzone/geodraw | c29b86c6068992d284b581b55c0e10ef95c9ba8a | [
"MIT"
] | null | null | null | KDDockWidgets/src/MDIArea.h | fritzone/geodraw | c29b86c6068992d284b581b55c0e10ef95c9ba8a | [
"MIT"
] | null | null | null | KDDockWidgets/src/MDIArea.h | fritzone/geodraw | c29b86c6068992d284b581b55c0e10ef95c9ba8a | [
"MIT"
] | null | null | null | /*
This file is part of KDDockWidgets.
SPDX-FileCopyrightText: 2020-2021 Klarälvdalens Datakonsult AB, a KDAB Group company <info@kdab.com>
Author: Sérgio Martins <sergio.martins@kdab.com>
SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only
Contact KDAB at <info@kdab.com> for commercial licensing options.
*/
#ifndef KDDOCKWIDGETS_MDI_AREA_H
#define KDDOCKWIDGETS_MDI_AREA_H
#include "kddockwidgets/docks_export.h"
#include "KDDockWidgets.h"
#include "QWidgetAdapter.h"
#include <QWidget>
namespace KDDockWidgets {
class MDILayoutWidget;
class DockWidgetBase;
class Frame;
/**
* @brief MDIArea allows to host dock widget in MDI mode.
* This is an alternative to using a full blown MainWindowMDI.
* The use case is when you already have a MainWindow (doing normal docking) and you
* want to add an area where you want to use MDI dock widgets. Instead of docking a MainWindowMDI,
* you'd just use an MDIArea, and avoid having nested main windows.
*
* See examples/mdi_with_docking/.
*/
class DOCKS_EXPORT MDIArea : public QWidgetAdapter
{
Q_OBJECT
public:
explicit MDIArea(QWidgetOrQuick *parent = nullptr);
~MDIArea();
/// @brief docks the dock widgets into this MDI area, at the specified position
void addDockWidget(DockWidgetBase *dw, QPoint localPt, InitialOption addingOption = {});
/// @brief Moves a dock widget @p dw to point @p pos
void moveDockWidget(DockWidgetBase *dw, QPoint pos);
/// @brief Sets the size of dock widget @p dw to @p size
void resizeDockWidget(DockWidgetBase *dw, QSize size);
/// @brief Returns the list of frames in this MDI Area
/// Each Frame object represents a 'window' emebedded in the MDI Area
QList<Frame *> frames() const;
/// @brief Forwards the close event to the MDI dock widgets, aborts closing if at least one
/// dock widget doesn't allow it
void onCloseEvent(QCloseEvent *) override;
private:
class Private;
Private *const d;
};
}
#endif
| 29.25 | 102 | 0.732026 | [
"object"
] |
b60e63fc799d92a0aef1ae29cef9584aab52d0a6 | 1,701 | h | C | inc/cryengine/CryCommon/CountedValue.h | samneirinck/awesomium-ce3 | c23810b616e97708b77798d019ac34e5d3892dd5 | [
"MIT"
] | 4 | 2017-12-18T20:10:16.000Z | 2021-02-07T21:21:24.000Z | src/native/inc/cryengine/CryCommon/CountedValue.h | samneirinck/cemono | fc4624b55852f7cc1efdc9771685581c32d34b2c | [
"MIT"
] | null | null | null | src/native/inc/cryengine/CryCommon/CountedValue.h | samneirinck/cemono | fc4624b55852f7cc1efdc9771685581c32d34b2c | [
"MIT"
] | 3 | 2019-03-11T21:36:15.000Z | 2021-02-07T21:21:26.000Z | /*************************************************************************
Crytek Source File.
Copyright (C), Crytek Studios, 2001-2009.
-------------------------------------------------------------------------
$Id$
$DateTime$
Description: A wrapper that counts the number of times the wrapped object
has been set. This is useful for netserializing an object
that might be given a "new value" that's the same as the old value.
-------------------------------------------------------------------------
History:
- 16/06/2009 : Created by Alex McCarthy
*************************************************************************/
#ifndef __COUNTED_VALUE_H__
#define __COUNTED_VALUE_H__
template <typename T>
struct CountedValue
{
public:
CountedValue() : m_lastProducedId(0), m_lastConsumedId(0) {}
typedef uint32 TCountedID;
void SetAndDirty(const T& value)
{
m_value = value;
++m_lastProducedId;
CRY_ASSERT(m_lastProducedId > 0);
}
const T* GetLatestValue()
{
bool bHasNewValue = IsDirty(); // check for dirtiness before updating ids
m_lastConsumedId = m_lastProducedId;
return bHasNewValue ? &m_value : NULL;
}
inline bool IsDirty() const
{
return m_lastProducedId != m_lastConsumedId;
}
const T& Peek() const
{
return m_value;
}
TCountedID GetLatestID() const
{
return m_lastProducedId;
}
// This method should only be used to update the object during serialization!
void UpdateDuringSerializationOnly(const T& value, TCountedID lastProducedId)
{
m_value = value;
m_lastProducedId = lastProducedId;
}
private:
TCountedID m_lastProducedId;
TCountedID m_lastConsumedId;
T m_value;
};
#endif //__COUNTED_VALUE_H__
| 24.3 | 78 | 0.604938 | [
"object"
] |
b6132e19466ddb723a9620adaba84e52f20ddccc | 4,244 | h | C | _studio/enctools/include/mfx_enctools_brc.h | VickyZengg/MediaSDK | 924da6d0664e77cef46eeef7821694dad140b8df | [
"MIT"
] | 2 | 2020-12-10T09:57:40.000Z | 2021-02-26T08:28:12.000Z | _studio/enctools/include/mfx_enctools_brc.h | VickyZengg/MediaSDK | 924da6d0664e77cef46eeef7821694dad140b8df | [
"MIT"
] | null | null | null | _studio/enctools/include/mfx_enctools_brc.h | VickyZengg/MediaSDK | 924da6d0664e77cef46eeef7821694dad140b8df | [
"MIT"
] | 1 | 2021-07-20T01:17:31.000Z | 2021-07-20T01:17:31.000Z | // Copyright (c) 2009-2020 Intel Corporation
//
// 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 __MFX_ENCTOOLS_BRC_H__
#define __MFX_ENCTOOLS_BRC_H__
#include "mfx_enctools_brc_defs.h"
#include "mfxdefs.h"
#include <vector>
#include <memory>
#include <algorithm>
#include "mfx_enctools_utils.h"
#include <climits>
namespace EncToolsBRC
{
/*
NalHrdConformance | VuiNalHrdParameters | Result
--------------------------------------------------------------
off any => MFX_BRC_NO_HRD
default off => MFX_BRC_NO_HRD
on off => MFX_BRC_HRD_WEAK
on (or default) on (or default) => MFX_BRC_HRD_STRONG
--------------------------------------------------------------
*/
struct BRC_FrameStruct
{
BRC_FrameStruct() :
frameType(0),
pyrLayer(0),
encOrder(0),
dispOrder(0),
qp(0),
frameSize(0),
numRecode(0),
sceneChange(0),
longTerm(0),
frameCmplx(0),
OptimalFrameSizeInBytes(0),
optimalBufferFullness(0),
qpDelta(MFX_QP_UNDEFINED),
qpModulation(MFX_QP_MODULATION_NOT_DEFINED)
{}
mfxU16 frameType;
mfxU16 pyrLayer;
mfxU32 encOrder;
mfxU32 dispOrder;
mfxI32 qp;
mfxI32 frameSize;
mfxI32 numRecode;
mfxU16 sceneChange;
mfxU16 longTerm;
mfxU32 frameCmplx;
mfxU32 OptimalFrameSizeInBytes;
mfxU32 optimalBufferFullness;
mfxI16 qpDelta;
mfxU16 qpModulation;
};
class BRC_EncTool
{
public:
BRC_EncTool() :
m_bInit(false),
m_par(),
m_hrdSpec(),
m_bDynamicInit(false),
m_ctx(),
m_SkipCount(0),
m_ReEncodeCount(0)
{}
~BRC_EncTool() { Close(); }
mfxStatus Init(mfxEncToolsCtrl const & ctrl);
mfxStatus Reset(mfxEncToolsCtrl const & ctrl);
void Close()
{
m_bInit = false;
}
mfxStatus ReportEncResult(mfxU32 dispOrder, mfxEncToolsBRCEncodeResult const & pEncRes);
mfxStatus SetFrameStruct(mfxU32 dispOrder, mfxEncToolsBRCFrameParams const & pFrameStruct);
mfxStatus ReportBufferHints(mfxU32 dispOrder, mfxEncToolsBRCBufferHint const & pBufHints);
mfxStatus ReportGopHints(mfxU32 dispOrder, mfxEncToolsHintPreEncodeGOP const & pGopHints);
mfxStatus ProcessFrame(mfxU32 dispOrder, mfxEncToolsBRCQuantControl *pFrameQp);
mfxStatus UpdateFrame(mfxU32 dispOrder, mfxEncToolsBRCStatus *pFrameSts);
protected:
bool m_bInit;
cBRCParams m_par;
std::unique_ptr < HRDCodecSpec> m_hrdSpec;
bool m_bDynamicInit;
BRC_Ctx m_ctx;
std::unique_ptr<AVGBitrate> m_avg;
mfxU32 m_SkipCount;
mfxU32 m_ReEncodeCount;
std::vector<BRC_FrameStruct> m_FrameStruct;
mfxI32 GetCurQP(mfxU32 type, mfxI32 layer, mfxU16 isRef, mfxU16 qpMod) const;
mfxI32 GetSeqQP(mfxI32 qp, mfxU32 type, mfxI32 layer, mfxU16 isRef, mfxU16 qpMod) const;
mfxI32 GetPicQP(mfxI32 qp, mfxU32 type, mfxI32 layer, mfxU16 isRef, mfxU16 qpMod) const;
mfxF64 ResetQuantAb(mfxI32 qp, mfxU32 type, mfxI32 layer, mfxU16 isRef, mfxF64 fAbLong, mfxU32 eo, bool bIdr, mfxU16 qpMod) const;
};
};
#endif
| 31.437037 | 134 | 0.674364 | [
"vector"
] |
b61364763c35bf321db10a31e1945efc55d1dcbc | 563 | h | C | LZTabBarCnotroller/LZTabBarCnotroller/Classes/Controllers/MyPreference/Views/LZMyPreferenceCell.h | do-my-best/LZTabBarCnotroller | a6e230540213d4c76c66f85d56c88ad33b505666 | [
"MIT"
] | 1 | 2015-11-23T03:51:04.000Z | 2015-11-23T03:51:04.000Z | LZTabBarCnotroller/LZTabBarCnotroller/Classes/Controllers/MyPreference/Views/LZMyPreferenceCell.h | do-my-best/LZTabBarCnotroller | a6e230540213d4c76c66f85d56c88ad33b505666 | [
"MIT"
] | 1 | 2020-11-04T05:44:22.000Z | 2020-11-04T05:44:22.000Z | LZTabBarCnotroller/LZTabBarCnotroller/Classes/Controllers/MyPreference/Views/LZMyPreferenceCell.h | do-my-best/LZTabBarCnotroller | a6e230540213d4c76c66f85d56c88ad33b505666 | [
"MIT"
] | null | null | null | //
// LZMyPreferenceCell.h
// LZTabBarCnotroller
//
// Created by liuzhu on 15/11/23.
// Copyright © 2015年 liuzhu. All rights reserved.
//
#import <UIKit/UIKit.h>
@class LZMyPreferenceModel;
@class LZMyPreferenceCell;
@protocol LZMyPreferenceCellDelegate <NSObject>
- (void)MyPreferenceCellAskToRefreshTableView:(LZMyPreferenceCell *)cell;
@end
@interface LZMyPreferenceCell : UITableViewCell
/// 拥有一个模型
@property ( nonatomic,strong ) LZMyPreferenceModel *model;
/// 让主控制器刷新表格等
@property (nonatomic,weak)id <LZMyPreferenceCellDelegate> delegate;
@end
| 20.107143 | 73 | 0.77087 | [
"model"
] |
b61b078a3d659be75b0e9ff0ab066b0c1cf84dbd | 200 | h | C | Allmund/src/Allmund/Scene.h | taz40/Allmund | 69a4bdd831d209848cb30fe99bd86b947ce55418 | [
"Apache-2.0"
] | null | null | null | Allmund/src/Allmund/Scene.h | taz40/Allmund | 69a4bdd831d209848cb30fe99bd86b947ce55418 | [
"Apache-2.0"
] | null | null | null | Allmund/src/Allmund/Scene.h | taz40/Allmund | 69a4bdd831d209848cb30fe99bd86b947ce55418 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <vector>
#include "Actor.h"
namespace Allmund {
class ALLMUND_API Scene
{
public:
std::vector<Actor*> actors;
Scene();
~Scene();
void addActor(Actor* actor);
};
} | 11.764706 | 30 | 0.655 | [
"vector"
] |
b62291c1f3a75204a28cecc86d7597c16e5854e7 | 7,189 | h | C | UniEngine/include/Entity.h | edisonlee0212/UniEngine-deprecated | 4b899980c280ac501c3b5fa2746cf1e71cfedd28 | [
"MIT"
] | null | null | null | UniEngine/include/Entity.h | edisonlee0212/UniEngine-deprecated | 4b899980c280ac501c3b5fa2746cf1e71cfedd28 | [
"MIT"
] | null | null | null | UniEngine/include/Entity.h | edisonlee0212/UniEngine-deprecated | 4b899980c280ac501c3b5fa2746cf1e71cfedd28 | [
"MIT"
] | 1 | 2021-09-06T08:07:37.000Z | 2021-09-06T08:07:37.000Z | #pragma once
#include "UniEngineAPI.h"
#include "Serializable.h"
namespace UniEngine {
#pragma region EntityManager
#pragma region Entity
struct UNIENGINE_API ComponentDataType final {
std::string m_name;
size_t m_typeId = 0;
size_t m_size = 0;
size_t m_offset = 0;
ComponentDataType() = default;
ComponentDataType(const std::string& name, const size_t& id, const size_t& size);
bool operator ==(const ComponentDataType& other) const;
bool operator !=(const ComponentDataType& other) const;
};
struct UNIENGINE_API ComponentDataBase {
};
class PrivateComponentBase;
struct UNIENGINE_API Entity final {
unsigned m_index = 0;
unsigned m_version = 0;
Entity();
bool operator ==(const Entity& other) const;
bool operator !=(const Entity& other) const;
size_t operator()(Entity const& key) const;
[[nodiscard]] bool IsEnabled() const;
void SetStatic(const bool& value) const;
void SetEnabled(const bool& value) const;
void SetEnabledSingle(const bool& value) const;
[[nodiscard]] bool IsNull() const;
[[nodiscard]] bool IsStatic() const;
[[nodiscard]] bool IsDeleted() const;
[[nodiscard]] bool IsValid() const;
template<typename T = ComponentDataBase>
void SetComponentData(const T& value) const;
template<typename T = ComponentDataBase>
T GetComponentData() const;
template<typename T = ComponentDataBase>
[[nodiscard]] bool HasComponentData() const;
template <typename T = PrivateComponentBase>
std::unique_ptr<T>& GetPrivateComponent() const;
template <typename T = PrivateComponentBase>
void SetPrivateComponent(std::unique_ptr<T> value) const;
template <typename T = PrivateComponentBase>
void RemovePrivateComponent() const;
template <typename T = PrivateComponentBase>
[[nodiscard]] bool HasPrivateComponent() const;
[[nodiscard]] inline std::string GetName() const;
inline void SetName(const std::string& name) const;
};
#pragma region Storage
class UNIENGINE_API PrivateComponentBase : public Serializable {
friend class EntityManager;
friend class EditorManager;
friend struct PrivateComponentElement;
friend class SerializationManager;
bool m_enabled = false;
Entity m_owner;
public:
[[nodiscard]] Entity GetOwner() const;
void SetEnabled(const bool& value);
[[nodiscard]] bool IsEnabled() const;
virtual void Init();
virtual void OnEnable();
virtual void OnDisable();
virtual void OnEntityEnable();
virtual void OnEntityDisable();
virtual void OnGui();
void Serialize(YAML::Emitter& out) override;
void Deserialize(const YAML::Node& in) override;
~PrivateComponentBase() override;
};
template<typename T>
ComponentDataType Typeof() {
ComponentDataType type;
type.m_name = std::string(typeid(T).name());
type.m_size = sizeof(T);
type.m_offset = 0;
type.m_typeId = typeid(T).hash_code();
return type;
}
const size_t ARCHETYPECHUNK_SIZE = 16384;
struct ComponentDataChunk {
void* m_data;
template<typename T>
T GetData(const size_t& offset);
[[nodiscard]] ComponentDataBase* GetDataPointer(const size_t& offset) const;
template<typename T>
void SetData(const size_t& offset, const T& data);
void SetData(const size_t& offset, const size_t& size, ComponentDataBase* data) const;
void ClearData(const size_t& offset, const size_t& size) const;
};
struct ComponentDataChunkArray {
std::vector<Entity> Entities;
std::vector<ComponentDataChunk> Chunks;
};
struct UNIENGINE_API EntityArchetype final {
size_t m_index;
[[nodiscard]] bool IsNull() const;
[[nodiscard]] bool IsValid() const;
[[nodiscard]] std::string GetName() const;
};
struct UNIENGINE_API PrivateComponentElement
{
std::string m_name;
size_t m_typeId;
std::unique_ptr<PrivateComponentBase> m_privateComponentData;
PrivateComponentElement(const std::string& name, const size_t& id, std::unique_ptr<PrivateComponentBase> data, const Entity& owner);
void ResetOwner(const Entity& newOwner) const;
};
struct EntityInfo {
friend class PrivateComponentStorage;
std::string m_name;
unsigned m_version = 1;
bool m_static = false;
bool m_enabled = true;
Entity m_parent = Entity();
std::vector<PrivateComponentElement> m_privateComponentElements;
std::vector<Entity> m_children;
size_t m_archetypeInfoIndex;
size_t m_chunkArrayIndex;
};
struct UNIENGINE_API EntityArchetypeInfo {
std::string m_name;
size_t m_index = 0;
std::vector<ComponentDataType> m_componentTypes;
size_t m_entitySize = 0;
size_t m_chunkCapacity = 0;
size_t m_entityCount = 0;
size_t m_entityAliveCount = 0;
template<typename T>
bool HasType();
bool HasType(const size_t& typeID);
};
struct UNIENGINE_API EntityQuery final {
size_t m_index = 0;
bool operator ==(const EntityQuery& other) const;
bool operator !=(const EntityQuery& other) const;
size_t operator()(const EntityQuery& key) const;
[[nodiscard]] bool IsNull() const;
template<typename T = ComponentDataBase, typename... Ts>
void SetAllFilters(T arg, Ts... args);
template<typename T = ComponentDataBase, typename... Ts>
void SetAnyFilters(T arg, Ts... args);
template<typename T = ComponentDataBase, typename... Ts>
void SetNoneFilters(T arg, Ts... args);
template<typename T1 = ComponentDataBase>
void ToComponentDataArray(std::vector<T1>& container);
template<typename T1 = ComponentDataBase, typename T2 = ComponentDataBase>
void ToComponentDataArray(std::vector<T1>& container, const std::function<bool(const T2&)>& filterFunc);
template<typename T1 = ComponentDataBase, typename T2 = ComponentDataBase, typename T3 = ComponentDataBase>
void ToComponentDataArray(std::vector<T1>& container, const std::function<bool(const T2&, const T3&)>& filterFunc);
template<typename T1 = ComponentDataBase, typename T2 = ComponentDataBase>
void ToComponentDataArray(const T1& filter, std::vector<T2>& container);
void ToEntityArray(std::vector<Entity>& container) const;
template<typename T1 = ComponentDataBase>
void ToEntityArray(const T1& filter, std::vector<Entity>& container);
template<typename T1 = ComponentDataBase>
void ToEntityArray(std::vector<Entity>& container, const std::function<bool(const Entity&, const T1&)>& filterFunc);
template<typename T1 = ComponentDataBase, typename T2 = ComponentDataBase>
void ToEntityArray(std::vector<Entity>& container, const std::function<bool(const Entity&, const T1&, const T2&)>& filterFunc);
[[nodiscard]] size_t GetEntityAmount() const;
};
struct UNIENGINE_API EntityComponentDataStorage {
EntityArchetypeInfo* m_archetypeInfo;
ComponentDataChunkArray* m_chunkArray;
EntityComponentDataStorage(EntityArchetypeInfo* info, ComponentDataChunkArray* array);
};
struct EntityQueryInfo {
std::vector<ComponentDataType> m_allComponentTypes;
std::vector<ComponentDataType> m_anyComponentTypes;
std::vector<ComponentDataType> m_noneComponentTypes;
std::vector<EntityComponentDataStorage> m_queriedStorage;
};
#pragma endregion
#pragma endregion
#pragma endregion
template<typename T>
bool EntityArchetypeInfo::HasType()
{
for (const auto& i : m_componentTypes) {
if (i.m_typeId == typeid(T).hash_code()) return true;
}
return false;
}
} | 36.492386 | 134 | 0.751426 | [
"vector"
] |
b34185096ba4244adb41f92ea393380006526447 | 2,498 | h | C | src/prng.h | xann16/isai-genalg-poly-interpolation | 83cdae89b55fc3e605e4dede5769937e232c1615 | [
"MIT"
] | null | null | null | src/prng.h | xann16/isai-genalg-poly-interpolation | 83cdae89b55fc3e605e4dede5769937e232c1615 | [
"MIT"
] | null | null | null | src/prng.h | xann16/isai-genalg-poly-interpolation | 83cdae89b55fc3e605e4dede5769937e232c1615 | [
"MIT"
] | null | null | null | #pragma once
#ifndef ISAI_GENEPI_PRNG_H_INCLUDED
#define ISAI_GENEPI_PRNG_H_INCLUDED
#include <algorithm>
#include <array>
#include <cassert>
#include <random>
#include <vector>
namespace isai
{
// alias for single byte
using byte_t = unsigned char;
// random number generation utils
class prng_t
{
private:
prng_t() noexcept = default;
public:
// initializes prng device
static void initialize() noexcept
{
s_eng = std::default_random_engine{ s_dev() };
}
// gets array of random doubles from given range
static std::vector< double >
get_uniform_doubles( std::size_t count, double lo, double hi ) noexcept
{
auto dist = std::uniform_real_distribution< double >{ lo, hi };
auto res = std::vector< double >{};
res.reserve( count );
for ( auto i = std::size_t{ 0 }; i < count; i++ )
{
res.emplace_back( dist( s_eng ) );
}
return res;
}
// fills given byte array with random bits
template < std::size_t N >
static void fill_with_random_bits( std::array< byte_t, N > &bit_array )
{
auto dist = std::uniform_int_distribution< byte_t >{};
for ( auto &b : bit_array )
{
b = dist( s_eng );
}
}
// probability [0,1] to binary success/failure
static bool perc_check( double perc ) noexcept
{
assert( perc >= 0.0 );
assert( perc <= 1.0 );
return perc >= std::generate_canonical< double, 64 >( s_eng );
}
// random index for chromosome crossover point
template < std::size_t N >
static std::size_t get_crossover_point()
{
auto dist = std::uniform_int_distribution< std::size_t >{ 1, N };
return dist( s_eng );
}
// picks random index from array of increasing probabilities (cdf)
static std::size_t pick_by_prob( std::vector< double > const &table )
{
auto val = std::generate_canonical< double, 64 >( s_eng );
for ( auto i = std::size_t{ 0 }; i < table.size(); i++ )
{
if ( val <= table[ i ] )
{
return i;
}
}
return table.size() - 1;
}
// shuffles elements of given vector
template < typename T >
static void shuffle( std::vector< T > &v )
{
std::random_shuffle( std::begin( v ), std::end( v ) );
}
private:
static std::random_device s_dev;
static std::default_random_engine s_eng;
};
} // namespace isai
#endif // !ISAI_GENEPI_POLY_H_INCLUDED
| 24.252427 | 75 | 0.602882 | [
"vector"
] |
b34393c3eb6c0127262fdca0457312fc8ebaa066 | 3,013 | h | C | source/game/physics/Physics_Actor.h | JasonHutton/QWTA | 7f42dc70eb230cf69a8048fc98d647a486e752f1 | [
"MIT"
] | 2 | 2021-05-02T18:37:48.000Z | 2021-07-18T16:18:14.000Z | source/game/physics/Physics_Actor.h | JasonHutton/QWTA | 7f42dc70eb230cf69a8048fc98d647a486e752f1 | [
"MIT"
] | null | null | null | source/game/physics/Physics_Actor.h | JasonHutton/QWTA | 7f42dc70eb230cf69a8048fc98d647a486e752f1 | [
"MIT"
] | null | null | null | // Copyright (C) 2007 Id Software, Inc.
//
#ifndef __PHYSICS_ACTOR_H__
#define __PHYSICS_ACTOR_H__
#include "Physics_Base.h"
/*
===================================================================================
Actor physics base class
An actor typically uses one collision model which is aligned with the gravity
direction. The collision model is usually a simple box with the origin at the
bottom center.
===================================================================================
*/
class idPhysics_Actor : public idPhysics_Base {
public:
CLASS_PROTOTYPE( idPhysics_Actor );
idPhysics_Actor( void );
~idPhysics_Actor( void );
// get delta yaw of master
float GetMasterDeltaYaw( void ) const;
// returns the ground entity
idEntity * GetGroundEntity( void ) const;
// align the clip model with the gravity direction
void SetClipModelAxis( void );
public: // common physics interface
void SetClipModel( idClipModel *model, float density, int id = 0, bool freeOld = true );
idClipModel * GetClipModel( int id = 0 ) const;
int GetNumClipModels( void ) const;
void SetMass( float mass, int id = -1 );
float GetMass( int id = -1 ) const;
void SetContents( int contents, int id = -1 );
int GetContents( int id = -1 ) const;
const idBounds & GetBounds( int id = -1 ) const;
const idBounds & GetAbsBounds( int id = -1 ) const;
bool IsPushable( void ) const;
const idVec3 & GetOrigin( int id = 0 ) const;
const idMat3 & GetAxis( int id = 0 ) const;
void SetGravity( const idVec3 &newGravity );
const idMat3 & GetGravityAxis( void ) const;
void ClipTranslation( trace_t &results, const idVec3 &translation, const idClipModel *model ) const;
void ClipRotation( trace_t &results, const idRotation &rotation, const idClipModel *model ) const;
int ClipContents( const idClipModel *model ) const;
void UnlinkClip( void );
void LinkClip( void );
void DisableClip( bool activateContacting = true );
void EnableClip( void );
bool EvaluateContacts( CLIP_DEBUG_PARMS_DECLARATION_ONLY );
// vehicle pushing stuff - Actors tend to have physics that
// doesn't play nice with rigid body physics, so it needs to
// be "pushed"
enum vehiclePushResult_t {
VPUSH_OK = 0,
VPUSH_BLOCKED
};
virtual int VehiclePush( bool stuck, float timeDelta, idVec3& move, idClipModel* pusher, int pushCount ) { return VPUSH_BLOCKED; }
protected:
idClipModel * clipModel; // clip model used for collision detection
idMat3 clipModelAxis; // axis of clip model aligned with gravity direction
// derived properties
float mass;
float invMass;
// master
idEntity * masterEntity;
float masterYaw;
float masterDeltaYaw;
// results of last evaluate
idEntityPtr<idEntity> groundEntityPtr;
};
#endif /* !__PHYSICS_ACTOR_H__ */
| 31.061856 | 135 | 0.635579 | [
"model"
] |
b374eb53e2fe1ecfb73e2d385dd123980c98fdc3 | 10,260 | c | C | openeuler-kernel/drivers/infiniband/sw/rxe/rxe_pool.c | Ddnirvana/test-CI | dd7a0a71281075e8ab300bddbab4a9fa039958f0 | [
"MulanPSL-1.0"
] | 31 | 2021-04-27T08:50:40.000Z | 2022-03-01T02:26:21.000Z | openeuler-kernel/drivers/infiniband/sw/rxe/rxe_pool.c | Ddnirvana/test-CI | dd7a0a71281075e8ab300bddbab4a9fa039958f0 | [
"MulanPSL-1.0"
] | 13 | 2021-07-10T04:36:17.000Z | 2022-03-03T10:50:05.000Z | openeuler-kernel/drivers/infiniband/sw/rxe/rxe_pool.c | Ddnirvana/test-CI | dd7a0a71281075e8ab300bddbab4a9fa039958f0 | [
"MulanPSL-1.0"
] | 12 | 2021-04-06T02:23:10.000Z | 2022-02-28T11:43:19.000Z | // SPDX-License-Identifier: GPL-2.0 OR Linux-OpenIB
/*
* Copyright (c) 2016 Mellanox Technologies Ltd. All rights reserved.
* Copyright (c) 2015 System Fabric Works, Inc. All rights reserved.
*/
#include "rxe.h"
#include "rxe_loc.h"
/* info about object pools
* note that mr and mw share a single index space
* so that one can map an lkey to the correct type of object
*/
struct rxe_type_info rxe_type_info[RXE_NUM_TYPES] = {
[RXE_TYPE_UC] = {
.name = "rxe-uc",
.size = sizeof(struct rxe_ucontext),
.flags = RXE_POOL_NO_ALLOC,
},
[RXE_TYPE_PD] = {
.name = "rxe-pd",
.size = sizeof(struct rxe_pd),
.flags = RXE_POOL_NO_ALLOC,
},
[RXE_TYPE_AH] = {
.name = "rxe-ah",
.size = sizeof(struct rxe_ah),
.flags = RXE_POOL_ATOMIC | RXE_POOL_NO_ALLOC,
},
[RXE_TYPE_SRQ] = {
.name = "rxe-srq",
.size = sizeof(struct rxe_srq),
.flags = RXE_POOL_INDEX | RXE_POOL_NO_ALLOC,
.min_index = RXE_MIN_SRQ_INDEX,
.max_index = RXE_MAX_SRQ_INDEX,
},
[RXE_TYPE_QP] = {
.name = "rxe-qp",
.size = sizeof(struct rxe_qp),
.cleanup = rxe_qp_cleanup,
.flags = RXE_POOL_INDEX,
.min_index = RXE_MIN_QP_INDEX,
.max_index = RXE_MAX_QP_INDEX,
},
[RXE_TYPE_CQ] = {
.name = "rxe-cq",
.size = sizeof(struct rxe_cq),
.flags = RXE_POOL_NO_ALLOC,
.cleanup = rxe_cq_cleanup,
},
[RXE_TYPE_MR] = {
.name = "rxe-mr",
.size = sizeof(struct rxe_mem),
.cleanup = rxe_mem_cleanup,
.flags = RXE_POOL_INDEX,
.max_index = RXE_MAX_MR_INDEX,
.min_index = RXE_MIN_MR_INDEX,
},
[RXE_TYPE_MW] = {
.name = "rxe-mw",
.size = sizeof(struct rxe_mem),
.flags = RXE_POOL_INDEX,
.max_index = RXE_MAX_MW_INDEX,
.min_index = RXE_MIN_MW_INDEX,
},
[RXE_TYPE_MC_GRP] = {
.name = "rxe-mc_grp",
.size = sizeof(struct rxe_mc_grp),
.cleanup = rxe_mc_cleanup,
.flags = RXE_POOL_KEY,
.key_offset = offsetof(struct rxe_mc_grp, mgid),
.key_size = sizeof(union ib_gid),
},
[RXE_TYPE_MC_ELEM] = {
.name = "rxe-mc_elem",
.size = sizeof(struct rxe_mc_elem),
.flags = RXE_POOL_ATOMIC,
},
};
static inline const char *pool_name(struct rxe_pool *pool)
{
return rxe_type_info[pool->type].name;
}
static int rxe_pool_init_index(struct rxe_pool *pool, u32 max, u32 min)
{
int err = 0;
size_t size;
if ((max - min + 1) < pool->max_elem) {
pr_warn("not enough indices for max_elem\n");
err = -EINVAL;
goto out;
}
pool->max_index = max;
pool->min_index = min;
size = BITS_TO_LONGS(max - min + 1) * sizeof(long);
pool->table = kmalloc(size, GFP_KERNEL);
if (!pool->table) {
err = -ENOMEM;
goto out;
}
pool->table_size = size;
bitmap_zero(pool->table, max - min + 1);
out:
return err;
}
int rxe_pool_init(
struct rxe_dev *rxe,
struct rxe_pool *pool,
enum rxe_elem_type type,
unsigned int max_elem)
{
int err = 0;
size_t size = rxe_type_info[type].size;
memset(pool, 0, sizeof(*pool));
pool->rxe = rxe;
pool->type = type;
pool->max_elem = max_elem;
pool->elem_size = ALIGN(size, RXE_POOL_ALIGN);
pool->flags = rxe_type_info[type].flags;
pool->tree = RB_ROOT;
pool->cleanup = rxe_type_info[type].cleanup;
atomic_set(&pool->num_elem, 0);
kref_init(&pool->ref_cnt);
rwlock_init(&pool->pool_lock);
if (rxe_type_info[type].flags & RXE_POOL_INDEX) {
err = rxe_pool_init_index(pool,
rxe_type_info[type].max_index,
rxe_type_info[type].min_index);
if (err)
goto out;
}
if (rxe_type_info[type].flags & RXE_POOL_KEY) {
pool->key_offset = rxe_type_info[type].key_offset;
pool->key_size = rxe_type_info[type].key_size;
}
pool->state = RXE_POOL_STATE_VALID;
out:
return err;
}
static void rxe_pool_release(struct kref *kref)
{
struct rxe_pool *pool = container_of(kref, struct rxe_pool, ref_cnt);
pool->state = RXE_POOL_STATE_INVALID;
kfree(pool->table);
}
static void rxe_pool_put(struct rxe_pool *pool)
{
kref_put(&pool->ref_cnt, rxe_pool_release);
}
void rxe_pool_cleanup(struct rxe_pool *pool)
{
unsigned long flags;
write_lock_irqsave(&pool->pool_lock, flags);
pool->state = RXE_POOL_STATE_INVALID;
if (atomic_read(&pool->num_elem) > 0)
pr_warn("%s pool destroyed with unfree'd elem\n",
pool_name(pool));
write_unlock_irqrestore(&pool->pool_lock, flags);
rxe_pool_put(pool);
}
static u32 alloc_index(struct rxe_pool *pool)
{
u32 index;
u32 range = pool->max_index - pool->min_index + 1;
index = find_next_zero_bit(pool->table, range, pool->last);
if (index >= range)
index = find_first_zero_bit(pool->table, range);
WARN_ON_ONCE(index >= range);
set_bit(index, pool->table);
pool->last = index;
return index + pool->min_index;
}
static void insert_index(struct rxe_pool *pool, struct rxe_pool_entry *new)
{
struct rb_node **link = &pool->tree.rb_node;
struct rb_node *parent = NULL;
struct rxe_pool_entry *elem;
while (*link) {
parent = *link;
elem = rb_entry(parent, struct rxe_pool_entry, node);
if (elem->index == new->index) {
pr_warn("element already exists!\n");
goto out;
}
if (elem->index > new->index)
link = &(*link)->rb_left;
else
link = &(*link)->rb_right;
}
rb_link_node(&new->node, parent, link);
rb_insert_color(&new->node, &pool->tree);
out:
return;
}
static void insert_key(struct rxe_pool *pool, struct rxe_pool_entry *new)
{
struct rb_node **link = &pool->tree.rb_node;
struct rb_node *parent = NULL;
struct rxe_pool_entry *elem;
int cmp;
while (*link) {
parent = *link;
elem = rb_entry(parent, struct rxe_pool_entry, node);
cmp = memcmp((u8 *)elem + pool->key_offset,
(u8 *)new + pool->key_offset, pool->key_size);
if (cmp == 0) {
pr_warn("key already exists!\n");
goto out;
}
if (cmp > 0)
link = &(*link)->rb_left;
else
link = &(*link)->rb_right;
}
rb_link_node(&new->node, parent, link);
rb_insert_color(&new->node, &pool->tree);
out:
return;
}
void rxe_add_key(void *arg, void *key)
{
struct rxe_pool_entry *elem = arg;
struct rxe_pool *pool = elem->pool;
unsigned long flags;
write_lock_irqsave(&pool->pool_lock, flags);
memcpy((u8 *)elem + pool->key_offset, key, pool->key_size);
insert_key(pool, elem);
write_unlock_irqrestore(&pool->pool_lock, flags);
}
void rxe_drop_key(void *arg)
{
struct rxe_pool_entry *elem = arg;
struct rxe_pool *pool = elem->pool;
unsigned long flags;
write_lock_irqsave(&pool->pool_lock, flags);
rb_erase(&elem->node, &pool->tree);
write_unlock_irqrestore(&pool->pool_lock, flags);
}
void rxe_add_index(void *arg)
{
struct rxe_pool_entry *elem = arg;
struct rxe_pool *pool = elem->pool;
unsigned long flags;
write_lock_irqsave(&pool->pool_lock, flags);
elem->index = alloc_index(pool);
insert_index(pool, elem);
write_unlock_irqrestore(&pool->pool_lock, flags);
}
void rxe_drop_index(void *arg)
{
struct rxe_pool_entry *elem = arg;
struct rxe_pool *pool = elem->pool;
unsigned long flags;
write_lock_irqsave(&pool->pool_lock, flags);
clear_bit(elem->index - pool->min_index, pool->table);
rb_erase(&elem->node, &pool->tree);
write_unlock_irqrestore(&pool->pool_lock, flags);
}
void *rxe_alloc(struct rxe_pool *pool)
{
struct rxe_pool_entry *elem;
unsigned long flags;
might_sleep_if(!(pool->flags & RXE_POOL_ATOMIC));
read_lock_irqsave(&pool->pool_lock, flags);
if (pool->state != RXE_POOL_STATE_VALID) {
read_unlock_irqrestore(&pool->pool_lock, flags);
return NULL;
}
kref_get(&pool->ref_cnt);
read_unlock_irqrestore(&pool->pool_lock, flags);
if (!ib_device_try_get(&pool->rxe->ib_dev))
goto out_put_pool;
if (atomic_inc_return(&pool->num_elem) > pool->max_elem)
goto out_cnt;
elem = kzalloc(rxe_type_info[pool->type].size,
(pool->flags & RXE_POOL_ATOMIC) ?
GFP_ATOMIC : GFP_KERNEL);
if (!elem)
goto out_cnt;
elem->pool = pool;
kref_init(&elem->ref_cnt);
return elem;
out_cnt:
atomic_dec(&pool->num_elem);
ib_device_put(&pool->rxe->ib_dev);
out_put_pool:
rxe_pool_put(pool);
return NULL;
}
int rxe_add_to_pool(struct rxe_pool *pool, struct rxe_pool_entry *elem)
{
unsigned long flags;
might_sleep_if(!(pool->flags & RXE_POOL_ATOMIC));
read_lock_irqsave(&pool->pool_lock, flags);
if (pool->state != RXE_POOL_STATE_VALID) {
read_unlock_irqrestore(&pool->pool_lock, flags);
return -EINVAL;
}
kref_get(&pool->ref_cnt);
read_unlock_irqrestore(&pool->pool_lock, flags);
if (!ib_device_try_get(&pool->rxe->ib_dev))
goto out_put_pool;
if (atomic_inc_return(&pool->num_elem) > pool->max_elem)
goto out_cnt;
elem->pool = pool;
kref_init(&elem->ref_cnt);
return 0;
out_cnt:
atomic_dec(&pool->num_elem);
ib_device_put(&pool->rxe->ib_dev);
out_put_pool:
rxe_pool_put(pool);
return -EINVAL;
}
void rxe_elem_release(struct kref *kref)
{
struct rxe_pool_entry *elem =
container_of(kref, struct rxe_pool_entry, ref_cnt);
struct rxe_pool *pool = elem->pool;
if (pool->cleanup)
pool->cleanup(elem);
if (!(pool->flags & RXE_POOL_NO_ALLOC))
kfree(elem);
atomic_dec(&pool->num_elem);
ib_device_put(&pool->rxe->ib_dev);
rxe_pool_put(pool);
}
void *rxe_pool_get_index(struct rxe_pool *pool, u32 index)
{
struct rb_node *node = NULL;
struct rxe_pool_entry *elem = NULL;
unsigned long flags;
read_lock_irqsave(&pool->pool_lock, flags);
if (pool->state != RXE_POOL_STATE_VALID)
goto out;
node = pool->tree.rb_node;
while (node) {
elem = rb_entry(node, struct rxe_pool_entry, node);
if (elem->index > index)
node = node->rb_left;
else if (elem->index < index)
node = node->rb_right;
else {
kref_get(&elem->ref_cnt);
break;
}
}
out:
read_unlock_irqrestore(&pool->pool_lock, flags);
return node ? elem : NULL;
}
void *rxe_pool_get_key(struct rxe_pool *pool, void *key)
{
struct rb_node *node = NULL;
struct rxe_pool_entry *elem = NULL;
int cmp;
unsigned long flags;
read_lock_irqsave(&pool->pool_lock, flags);
if (pool->state != RXE_POOL_STATE_VALID)
goto out;
node = pool->tree.rb_node;
while (node) {
elem = rb_entry(node, struct rxe_pool_entry, node);
cmp = memcmp((u8 *)elem + pool->key_offset,
key, pool->key_size);
if (cmp > 0)
node = node->rb_left;
else if (cmp < 0)
node = node->rb_right;
else
break;
}
if (node)
kref_get(&elem->ref_cnt);
out:
read_unlock_irqrestore(&pool->pool_lock, flags);
return node ? elem : NULL;
}
| 22.304348 | 75 | 0.689864 | [
"object"
] |
b378f7b0f896f3b19e3a4f3ed591190cd9011242 | 8,907 | c | C | tests/arbpoly2d.c | EMinsight/Silo | a1e27d34e8b52196be2de3d4aae2d0cae21b3f36 | [
"Apache-2.0"
] | 8 | 2021-10-08T00:22:19.000Z | 2022-03-21T02:17:31.000Z | tests/arbpoly2d.c | EMinsight/Silo | a1e27d34e8b52196be2de3d4aae2d0cae21b3f36 | [
"Apache-2.0"
] | 184 | 2019-03-20T03:02:33.000Z | 2019-03-24T18:08:08.000Z | tests/arbpoly2d.c | EMinsight/Silo | a1e27d34e8b52196be2de3d4aae2d0cae21b3f36 | [
"Apache-2.0"
] | 4 | 2021-12-28T11:40:36.000Z | 2022-03-30T08:51:51.000Z | /*
Copyright (C) 1994-2016 Lawrence Livermore National Security, LLC.
LLNL-CODE-425250.
All rights reserved.
This file is part of Silo. For details, see silo.llnl.gov.
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 disclaimer below.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the disclaimer (as noted
below) in the documentation and/or other materials provided with
the distribution.
* Neither the name of the LLNS/LLNL 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 LAWRENCE
LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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.
This work was produced at Lawrence Livermore National Laboratory under
Contract No. DE-AC52-07NA27344 with the DOE. Neither the United
States Government nor Lawrence Livermore National Security, LLC nor
any of their employees, makes any warranty, express or implied, or
assumes any liability or responsibility for the accuracy,
completeness, or usefulness of any information, apparatus, product, or
process disclosed, or represents that its use would not infringe
privately-owned rights. Any reference herein to any specific
commercial products, process, or services by trade name, trademark,
manufacturer or otherwise does not necessarily constitute or imply its
endorsement, recommendation, or favoring by the United States
Government or Lawrence Livermore National Security, LLC. The views and
opinions of authors expressed herein do not necessarily state or
reflect those of the United States Government or Lawrence Livermore
National Security, LLC, and shall not be used for advertising or
product endorsement purposes.
*/
#include <silo.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <std.c>
#define LEN(A) (sizeof(A)/sizeof(A[0]))
int
main(int argc, char *argv[])
{
int i;
DBfile *dbfile = NULL;
char *coordnames[3];
float *coords[3];
float x[8] = {0, 1, 2, 3, 4, 3, 2, 1};
float y[8] = {.5,0, 0, 0,.5, 1, 1, 1};
float z[8] = {0, 0, 0, 0, 0, 0, 0, 0};
int nl[12] = { 0,1,7, 1,2,6,7, 2,3,4,5,6};
int nl2[13] = { 0,1,7, 1,2,6,7, 5,2,3,4,5,6};
int nl3[15] = {3,0,1,7, 4,1,2,6,7, 5,2,3,4,5,6};
int shapetype[8];
int shapesize[8];
int shapecnt[8] = {1,1,1,1,1,1,1,1};
DBfacelist *facelist = NULL;
float angle;
float var[8] = {4, 3, 2, 1, 0, 1, 2, 3};
int driver=DB_PDB;
char *filename = "arbpoly2d.silo";
for (i=1; i<argc; i++) {
if (!strncmp(argv[i], "DB_PDB",6)) {
driver = StringToDriver(argv[i]);
} else if (!strncmp(argv[i], "DB_HDF5", 7)) {
driver = StringToDriver(argv[i]);
} else if (argv[i][0] != '\0') {
fprintf(stderr, "%s: ignored argument `%s'\n", argv[0], argv[i]);
}
}
DBShowErrors(DB_ABORT, NULL);
printf("Creating test file \"%s\".\n", filename);
dbfile = DBCreate(filename, DB_CLOBBER, DB_LOCAL, "2D arbitrary polyon tests", driver);
coordnames[0] = "xcoords";
coordnames[1] = "ycoords";
coordnames[2] = "zcoords";
coords[0] = x;
coords[1] = y;
coords[2] = z;
/* typical 2D mesh with normal zonelist */
shapesize[0] = 3;
shapesize[1] = 4;
shapesize[2] = 5;
DBPutUcdmesh(dbfile, "mesh_zl", 2, (DBCAS_t) coordnames,
coords, 8, 1, "zl", NULL, DB_FLOAT, NULL);
DBSetDeprecateWarnings(0);
DBPutZonelist(dbfile, "zl", 3, 2, nl, LEN(nl), 0, shapesize,
shapecnt, 3);
DBSetDeprecateWarnings(3);
DBPutUcdvar1(dbfile, "v_zl", "mesh_zl", var, 8, NULL, 0, DB_FLOAT,
DB_NODECENT, NULL);
/* same as above except using convention where shapesize is zero and
vertex count is encoded as first entry in each shape */
shapesize[0] = 3;
shapesize[1] = 4;
shapesize[2] = 0;
DBPutUcdmesh(dbfile, "mesh_zl0", 2, (DBCAS_t) coordnames,
coords, 8, 1, "zl0", NULL, DB_FLOAT, NULL);
DBSetDeprecateWarnings(0);
DBPutZonelist(dbfile, "zl0", 3, 2, nl2, LEN(nl2), 0, shapesize,
shapecnt, 3);
DBSetDeprecateWarnings(3);
DBPutUcdvar1(dbfile, "v_zl0", "mesh_zl0", var, 8, NULL, 0, DB_FLOAT,
DB_NODECENT, NULL);
/* same using PutZonelist2 */
shapesize[0] = 3;
shapesize[1] = 4;
shapesize[2] = 5;
shapetype[0] = DB_ZONETYPE_TRIANGLE;
shapetype[1] = DB_ZONETYPE_QUAD;
shapetype[2] = DB_ZONETYPE_POLYGON;
DBPutUcdmesh(dbfile, "mesh_zl2", 2, (DBCAS_t) coordnames,
coords, 8, 1, "zl2", NULL, DB_FLOAT, NULL);
DBPutZonelist2(dbfile, "zl2", 3, 2, nl, LEN(nl), 0, 0, 0, shapetype,
shapesize, shapecnt, 3, NULL);
DBPutUcdvar1(dbfile, "v_zl2", "mesh_zl2", var, 8, NULL, 0, DB_FLOAT,
DB_NODECENT, NULL);
/* same using PutZonelist2 */
shapesize[0] = 3;
shapesize[1] = 4;
shapesize[2] = 0;
shapetype[0] = DB_ZONETYPE_TRIANGLE;
shapetype[1] = DB_ZONETYPE_QUAD;
shapetype[2] = DB_ZONETYPE_POLYGON;
DBPutUcdmesh(dbfile, "mesh_zl20", 2, (DBCAS_t) coordnames,
coords, 8, 1, "zl20", NULL, DB_FLOAT, NULL);
DBPutZonelist2(dbfile, "zl20", 3, 2, nl2, LEN(nl2), 0, 0, 0, shapetype,
shapesize, shapecnt, 3, NULL);
DBPutUcdvar1(dbfile, "v_zl20", "mesh_zl20", var, 8, NULL, 0, DB_FLOAT,
DB_NODECENT, NULL);
/* same using PutZonelist2 with every zone set to type polygon */
shapesize[0] = 3;
shapesize[1] = 4;
shapesize[2] = 5;
shapetype[0] = DB_ZONETYPE_POLYGON;
shapetype[1] = DB_ZONETYPE_POLYGON;
shapetype[2] = DB_ZONETYPE_POLYGON;
DBPutUcdmesh(dbfile, "mesh_zl2p", 2, (DBCAS_t) coordnames,
coords, 8, 1, "zl2p", NULL, DB_FLOAT, NULL);
DBPutZonelist2(dbfile, "zl2p", 3, 2, nl, LEN(nl), 0, 0, 0, shapetype,
shapesize, shapecnt, 3, NULL);
DBPutUcdvar1(dbfile, "v_zl2p", "mesh_zl2p", var, 8, NULL, 0, DB_FLOAT,
DB_NODECENT, NULL);
/* same using PutZonelist2 with every zone set to type polygon and sizes zero */
shapesize[0] = 0;
shapesize[1] = 0;
shapesize[2] = 0;
shapetype[0] = DB_ZONETYPE_POLYGON;
shapetype[1] = DB_ZONETYPE_POLYGON;
shapetype[2] = DB_ZONETYPE_POLYGON;
DBPutUcdmesh(dbfile, "mesh_zl2p0", 2, (DBCAS_t) coordnames,
coords, 8, 1, "zl2p0", NULL, DB_FLOAT, NULL);
DBPutZonelist2(dbfile, "zl2p0", 3, 2, nl3, LEN(nl3), 0, 0, 0, shapetype,
shapesize, shapecnt, 3, NULL);
DBPutUcdvar1(dbfile, "v_zl2p0", "mesh_zl2p0", var, 8, NULL, 0, DB_FLOAT,
DB_NODECENT, NULL);
/* same using facelist */
shapetype[0] = DB_ZONETYPE_TRIANGLE;
shapetype[1] = DB_ZONETYPE_QUAD;
shapetype[2] = DB_ZONETYPE_POLYGON;
DBPutUcdmesh(dbfile, "mesh_fl", 2, (DBCAS_t) coordnames,
coords, 8, 1, "fl", NULL, DB_FLOAT, NULL);
/* note that we need to say ndims==3 to get this call to write shapesize/shapecnt */
DBPutFacelist(dbfile, "fl", 3, 3, nl, LEN(nl), 0, NULL,
shapesize, shapecnt, 3, shapetype, NULL, 3);
DBPutUcdvar1(dbfile, "v_fl", "mesh_fl", var, 8, NULL, 0, DB_FLOAT,
DB_NODECENT, NULL);
/* same using ph-zonelist */
shapesize[0] = 3;
shapesize[1] = 4;
shapesize[2] = 5;
DBPutUcdmesh(dbfile, "mesh_phzl", 2, (DBCAS_t) coordnames,
coords, 8, 1, "phzl", NULL, DB_FLOAT, NULL);
DBPutPHZonelist(dbfile, "phzl", 3, shapesize, LEN(nl), nl, 0,0,0,0,0,0,0,0,0);
DBPutUcdvar1(dbfile, "v_phzl", "mesh_phzl", var, 8, NULL, 0, DB_FLOAT,
DB_NODECENT, NULL);
DBClose(dbfile);
CleanupDriverStuff();
return (0);
}
| 41.427907 | 91 | 0.638936 | [
"mesh",
"shape"
] |
b38420dd093b17f8ec37cfbae29e7167ecdc92d9 | 2,326 | h | C | src/error.h | jyvet/mapreduce | 0f11314e7774a62324463511e985a20c7c552453 | [
"MIT"
] | 1 | 2017-08-21T01:49:21.000Z | 2017-08-21T01:49:21.000Z | src/error.h | jyvet/mapreduce | 0f11314e7774a62324463511e985a20c7c552453 | [
"MIT"
] | null | null | null | src/error.h | jyvet/mapreduce | 0f11314e7774a62324463511e985a20c7c552453 | [
"MIT"
] | null | null | null | /*******************************************************************************
* Copyright (C) 2015, Jean-Yves VET, contact [at] jean-yves [dot] vet *
* *
* This software is licensed as described in the file LICENCE, which you should *
* have received as part of this distribution. You may opt to use, copy, *
* modify, merge, publish, distribute and/or sell copies of the Software, and *
* permit persons to whom the Software is furnished to do so, under the terms *
* of the LICENCE file. *
* *
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY *
* KIND, either express or implied. *
*******************************************************************************/
#ifndef HEADER_MAPREDUCE_ERROR_H
#define HEADER_MAPREDUCE_ERROR_H
#include "common.h"
typedef enum {
ERR_SUCCESS, /* No error. */
ERR_MINTHREADS, /* Not enough threads */
ERR_MAXTHREADS, /* Too many threads */
ERR_FILEACCESS, /* File cannot be accessed */
ERR_MEMALLOC, /* Allocation error. */
ERR_LAST /* Number of errors. */
} err_code;
static const char *t[] = {
"Success",
"You should start the program with more threads",
"You should start the program with fewer threads (maximum reached)",
"File does not exist or cannot be accessed in read mode",
"Allocation error",
};
/**
* Transform an error code into a string and exit with error code.
*
* @param error[in] Error code
*/
static inline void *mr_error(err_code error) {
#if MAPREDUCE_DEFAULT_USECOLORS
fprintf(stderr, "\e[1;91mError: \e[2;91m%s\e[0m\n",
error<ERR_LAST ? (char *)t[error] : NULL);
#else
fprintf(stderr, "Error: %s\n",
error<ERR_LAST ? (char *)t[error] : NULL);
#endif
exit(error);
}
#endif
| 42.290909 | 80 | 0.463887 | [
"transform"
] |
b3902cd42a8c92666cfffffbe657a8074ba1d145 | 25,953 | h | C | third_party/wvr_client/include/wvr/wvr_device.h | pingxingyun/larkxr_native_android_app | 464fc5eecb011325b553adf82ef83c1659b05c20 | [
"Apache-2.0"
] | 4 | 2021-08-25T05:51:58.000Z | 2022-02-09T06:34:12.000Z | third_party/wvr_client/include/wvr/wvr_device.h | pingxingyun/larkxr_native_android_app | 464fc5eecb011325b553adf82ef83c1659b05c20 | [
"Apache-2.0"
] | 1 | 2021-09-03T01:18:45.000Z | 2021-09-03T01:18:45.000Z | third_party/wvr_client/include/wvr/wvr_device.h | pingxingyun/larkxr_native_android_app | 464fc5eecb011325b553adf82ef83c1659b05c20 | [
"Apache-2.0"
] | null | null | null | // "WaveVR SDK
// © 2017 HTC Corporation. All Rights Reserved.
//
// Unless otherwise required by copyright law and practice,
// upon the execution of HTC SDK license agreement,
// HTC grants you access to and use of the WaveVR SDK(s).
// You shall fully comply with all of HTC’s SDK license agreement terms and
// conditions signed by you and all SDK and API requirements,
// specifications, and documentation provided by HTC to You."
#ifndef wvr_device_h_
#define wvr_device_h_
#include "wvr_stdinc.h"
#include "wvr_types.h"
#include "begin_code.h"
#ifdef __cplusplus
extern "C" {
#endif
static const uint32_t WVR_DEVICE_COUNT_LEVEL_0 = 1; /**< Get HMD */
static const uint32_t WVR_DEVICE_COUNT_LEVEL_1 = 3; /**< Get HMD and 2 controllers */
static const uint32_t WVR_DEVICE_COUNT_LEVEL_2 = 16; /**< Get HMD, 2 controllers, and other miscellaneous tracking devices */
static const uint32_t WVR_DEVICE_HMD = 0; /**< Specify device HMD */
/**
* @brief input type for input id
*/
typedef enum {
WVR_InputType_Button = 1<<0, /**< Button input type */
WVR_InputType_Touch = 1<<1, /**< Touch input type */
WVR_InputType_Analog = 1<<2, /**< Analog input type */
} WVR_InputType;
/**
* @brief analog type
*/
typedef enum {
WVR_AnalogType_None = 0,
WVR_AnalogType_2D = 1, /**< Provide analog data with x and y coordinate, @ref WVR_Axis value is -1 ~ 1*/
WVR_AnalogType_1D = 2, /**< Provide analog data with x coordinate, @ref WVR_Axis value is 0 ~ 1*/
} WVR_AnalogType;
/**
* @brief intensity of vibrator
*/
typedef enum {
WVR_Intensity_Weak = 1, /**< The Intensity of vibrate is Weak. */
WVR_Intensity_Light = 2, /**< The Intensity of vibrate is Light. */
WVR_Intensity_Normal = 3, /**< The Intensity of vibrate is Normal. */
WVR_Intensity_Strong = 4, /**< The Intensity of vibrate is Strong. */
WVR_Intensity_Severe = 5, /**< The Intensity of vibrate is Severe. */
} WVR_Intensity;
/**
* @brief analog data
*/
typedef struct WVR_Axis {
float x; /**< -1<=x<=1 for @ref WVR_AnalogType_2D; 0<=x<=1 for @ref WVR_AnalogType_1D. */
float y; /**< -1<=y<=1 for @ref WVR_AnalogType_2D; 0 for @ref WVR_AnalogType_1D. */
} WVR_Axis_t;
/**
* @brief analog state structure
*/
typedef struct WVR_AnalogState {
WVR_InputId id; /**< indicate the analog state belongs to which WVR_InputId */
WVR_AnalogType type; /**< indicate the analog data's type */
WVR_Axis_t axis; /**< @ref WVR_Axis, include analog data */
} WVR_AnalogState_t;
/**
* @brief input attribute for designated input id
*/
typedef struct WVR_InputAttribute {
WVR_InputId id; /**< The input id of device. */
int32_t capability; /**< bitmask of @ref WVR_InputType, value must be 1 ~ 7 */
WVR_AnalogType axis_type; /**< @ref WVR_AnalogType_2D or @ref WVR_AnalogType_1D if analog bit of capability is 1; otherwise WVR_AnalogType_None */
} WVR_InputAttribute_t;
/**
* @brief input mapping pair from device to app
*/
typedef struct WVR_InputMappingPair {
WVR_InputAttribute destination; /**< destination key to app */
WVR_InputAttribute source; /**< source key from device */
} WVR_InputMappingPair_t;
/**
* @brief The status of battery capacity.
*/
typedef enum {
WVR_BatteryStatus_Unknown = 0, /**< an error code if device service cannot get the status of the battery. */
WVR_BatteryStatus_Normal = 1, /**< battery capacity is normal. */
WVR_BatteryStatus_Low = 2, /**< warning, batter capacity is low. */
WVR_BatteryStatus_UltraLow = 3, /**< battery capacity is too low. */
} WVR_BatteryStatus;
/**
* @brief The status of battery temperature.
*/
typedef enum {
WVR_BatteryTemperatureStatus_Unknown = 0, /**< an error code if device service cannot get the temperature status of the battery. */
WVR_BatteryTemperatureStatus_Normal = 1, /**< battery temperature is normal. */
WVR_BatteryTemperatureStatus_Overheat = 2, /**< warning, battery temperature is high. */
WVR_BatteryTemperatureStatus_UltraOverheat = 3, /**< battery temperature is too high. */
} WVR_BatteryTemperatureStatus;
/**
* @brief The charging status.
*/
typedef enum {
WVR_ChargeStatus_Unknown = 0, /**< an error code if device service cannot get the charging status of battery in use. */
WVR_ChargeStatus_Discharging = 1, /**< device doesn't charge currently. */
WVR_ChargeStatus_Charging = 2, /**< device is charging. */
WVR_ChargeStatus_Full = 3, /**< battery capacity of device is full. */
} WVR_ChargeStatus;
/**
* @brief Recenter effect of WVR_InAppRecenter
*/
typedef enum {
WVR_RecenterType_Disabled = 0, /**< Make everything back to system coordinate instantly */
WVR_RecenterType_YawOnly = 1, /**< Only adjust the Yaw angle */
WVR_RecenterType_YawAndPosition = 2, /**< Adjust the Yaw angle, and also reset user's position to Virtual World's center */
WVR_RecenterType_RotationAndPosition = 3, /**< Affect all the XYZ and Pitch Yaw Roll. It is sensitive to user's head gesture at recentering. */
} WVR_RecenterType;
/**
* @brief Arm/Neck Model options of WVR_SetArmModel/WVR_SetNeckModel
*/
typedef enum {
WVR_SimulationType_Auto = 0, /**< Simulates device position while device tracking is only 3DoF. */
WVR_SimulationType_ForceOn = 1, /**< Always simulates and replaces devices' positions. */
WVR_SimulationType_ForceOff = 2, /**< Do NOT activate Position Simulation. */
} WVR_SimulationType;
/**
* @brief Developer can know if WVR_DeviceType is connected
*
* @param type which indicate @ref WVR_DeviceType.
* @return false if is disconnected, true is connected.
* @version API Level 1
*/
extern WVR_EXPORT bool WVR_IsDeviceConnected(WVR_DeviceType type);
/**
* @brief Developer can know if WVR_DeviceType is suspend, note only for HMD
*
* @param type which indicate @ref WVR_DeviceType.
* @return true if in suspend status, otherwise return false.
* @version API Level 1
*/
extern WVR_EXPORT bool WVR_IsDeviceSuspend(WVR_DeviceType type);
/**
* @brief Function to get Input Device Capability for WVR_InputType
*
* @param type which indicate what device to get the capability. (refer to @ref WVR_DeviceType)
* @param inputType , one of @ref WVR_InputType.
* @return int32_t, bitmask for WVR_InputType, -1 for error occurs
* @version API Level 1
*/
extern WVR_EXPORT int32_t WVR_GetInputDeviceCapability(WVR_DeviceType type, WVR_InputType inputType);
/**
* @brief Function to get Input Device Analog Type for @ref WVR_InputId
*
* @param type which indicate what device to get the capability. (refer to @ref WVR_DeviceType)
* @param id one of @ref WVR_InputId.
* @return analog type for @ref WVR_InputId. (refer to @ref WVR_AnalogType)
* @version API Level 3
* @note Effective with Runtime version 3 or higher
*/
extern WVR_EXPORT WVR_AnalogType WVR_GetInputDeviceAnalogType(WVR_DeviceType type, WVR_InputId id);
/**
* @brief Function to get count for WVR_InputType. This is caluate WVR_InputType count
* base on WVR_SetInputRequest paried result.
*
* @param type which indicates what device to get the count. (refer to @ref WVR_DeviceType)
* @param inputType, one of @ref WVR_InputType
* @return int32_t, count for each WVR_InputType, -1 for error occurs
* @version API Level 1
*/
extern WVR_EXPORT int32_t WVR_GetInputTypeCount(WVR_DeviceType type, WVR_InputType inputType);
/**
* @brief Function to get WVR_InputType data, inputType is a bitmask to represent the combination input type for WVR_InputType.
*
* @param type which indicates what device to get the InputDeviceState. (refer to @ref WVR_DeviceType)
* @param inputType, a bitmask to represent the combination input type for @ref WVR_InputType, developer can get singleton
* or combination input status.
* @param buttons, a bitmask to represent the button state, each bit is corresponding to WVR_InputId.
* @param touches, a bitmast to represent the touches state, each bit is corresponding to WVR_InputId.
* @param analogArray, an array of WVR_AnalogState_t to represent all analog data. (refer to @ref WVR_AnalogState)
* @param analoyAarrayCount, Developer should the the array count from the WVR_GetInputTypeCount API.
* @return false when anyone of parameter @ref WVR_InputType get data failed. For example, if inputType is a combination of
* WVR_InputType_Button and WVR_InputType_Analog, but the WVR_InputType_Button data get failed, the API return false.
* @version API Level 1
*/
extern WVR_EXPORT bool WVR_GetInputDeviceState(WVR_DeviceType type, uint32_t inputType, uint32_t* buttons, uint32_t* touches,
WVR_AnalogState_t* analogArray, uint32_t analogArrayCount);
/**
* @brief Function to get button state of specific input id
*
* @param type which indicates what device type. (refer to @ref WVR_DeviceType)
* @param id, one of @ref WVR_InputId, indicate which button
* @return bool, true for pressed and false is unpressed
* @version API Level 1
*/
extern WVR_EXPORT bool WVR_GetInputButtonState(WVR_DeviceType type, WVR_InputId id);
/**
* @brief Function to get touch state of specific input id
*
* @param type which indicates what device type. (refer to @ref WVR_DeviceType)
* @param id, one of @ref WVR_InputId, indicate which touch
* @return bool, true for touched and false is untouched
* @version API Level 1
*/
extern WVR_EXPORT bool WVR_GetInputTouchState(WVR_DeviceType type, WVR_InputId id);
/**
* @brief Function to get analog data of specific input id
*
* @param type which indicates what device type. (refer to @ref WVR_DeviceType)
* @param id, one of @ref WVR_InputId, indicate which touch
* @return analog data for @ref WVR_InputId. (refer to @ref WVR_Axis)
* @version API Level 1
*/
extern WVR_EXPORT WVR_Axis_t WVR_GetInputAnalogAxis(WVR_DeviceType type, WVR_InputId id);
/**
* @brief Function to get VR device pose w/wo prediction
*
* The pose that the tracker thinks that the HMD will be in at the specified number of seconds into the
* future. Pass 0 to get the state at the instant the method is called. Most of the time the application should
* calculate the time until the photons will be emitted from the display and pass that time into the method.
*
* For devices where isValidPose is true the application can use the pose to position the device
* in question.
*
* Seated experiences should call this method with **WVR_PoseOriginModel_OriginOnHead** and receive poses relative
* to the seated zero pose. Standing experiences should call this method with **WVR_PoseOriginModel_OriginOnGround**
* and receive poses relative to the Arena Play Area. **WVR_PoseOriginModel_OriginOnTrackingObserver** should
* probably not be used unless the application is the Arena calibration tool itself, but will provide
* poses relative to the hardware-specific coordinate system in the driver.
*
* You will need to explicitly indicate the correct pose with the parameter 'pose' when calling @ref WVR_SubmitFrame.
*
* @param type Type of the device to get the InputDeviceState. (refer to @ref WVR_DeviceType)
* @param originModel Tracking universe that returned poses should be relative to. (refer to @ref WVR_PoseOriginModel)
* @param predictedMilliSec Number of milliseconds from now to predict poses for. Positive numbers are in the future.
* Pass 0 to get the state at the instant the function is called.
* @param poseState to obtain pose data (refer to @ref WVR_PoseState) of tracked device by @ref WVR_DeviceType.
* @version API Level 1
*/
extern WVR_EXPORT void WVR_GetPoseState(WVR_DeviceType type, WVR_PoseOriginModel originModel, uint32_t predictedMilliSec, WVR_PoseState_t *poseState);
/**
* @brief Returns poses to usage for rendering scene.
*
* This function gets the poses from runtime for the usage of rendering scene at the specific moment based on the pose origin model.
* The one-time configuring the tracking universe assumes one kind of origin pose models unless the model setting is not changed.
* The description of tracking universe can refer to the argument originModel of @ref WVR_GetPoseState.
*
* The poses and device type are aggregated together as struct WVR_DevicePosePair_t.
* The struct pointers of all tracked devices compose a specific size array to keep track of the locomotions of the devices.
* The specific array size can be substituted with three levels of device count.
* **WVR_DEVICE_COUNT_LEVEL_0** is only assumed to get HMD device.
* **WVR_DEVICE_COUNT_LEVEL_1** is assumed that the HMD and two controllers are tracked.
* **WVR_DEVICE_COUNT_LEVEL_2** should track the number of devices up to 16, including HMD, 2 controllers, and other miscellaneous tracking devices.
*
* You will need to explicitly indicate the correct pose with the parameter 'pose' when calling @ref WVR_SubmitFrame.
*
* To reduce the judder, the moment of getting poses should approximate the moment update the new scene on display.
* WVR_GetSyncPose also make short time prediction of poses according to different render methods such as ATW and direct mode.
*
* @param originModel enum @ref WVR_PoseOriginModel, specify the tracking universe of origin pose model.
* @param pairArray struct pointer WVR_DevicePosePair_t (refer to @ref WVR_DevicePosePair), aggregation array to keep pose information and tracked device type.
* @param pairArrayCount uint32_t, specify the size of WVR_DevicePosePair_t array. The three levels of device count are optional.
* @version API Level 1
*/
extern WVR_EXPORT void WVR_GetSyncPose(WVR_PoseOriginModel originModel, WVR_DevicePosePair_t * pairArray, uint32_t pairArrayCount);
/**
* @brief Function to trigger vibration.
*
* @param type which indicate what device type (refer to @ref WVR_DeviceType)
* @param id indicates the @ref WVR_InputId to trigger a vibration on.
* @param durationMicroSec The duration when vibrator works.
* @param frequency The vibrator times during durationMicroSec.
* @param intensity The intensity when vibrator works, default value is WVR_Intensity_Normal
* @version API Level 4
* @note Effective with Runtime version 4 or higher
*/
extern WVR_EXPORT void WVR_TriggerVibration(WVR_DeviceType type, WVR_InputId id = WVR_InputId_Max, uint32_t durationMicroSec = 65535,
uint32_t frequency = 1, WVR_Intensity intensity = WVR_Intensity_Normal);
/**
* @brief Function to recenter tracker coordinate system to the current rotation and/or position of the App "Virtual World".
*
* Sets the zero pose for current tracker coordinate system to the current position and rotation of the Virtual World. After
* @ref WVR_InAppRecenter all @ref WVR_GetSyncPose and @ref WVR_GetPoseState calls that pass @ref WVR_PoseOriginModel
zType indicates type of recenter in @ref WVR_RecenterType
* @version API Level 2
*/
extern WVR_EXPORT void WVR_InAppRecenter(WVR_RecenterType recenterType);
/**
* @brief Function to transform between rotation Matrix and Quaternion
*
* Convenience utility to apply the specified transform between rotation Matrix and Quaternion.
*
* @param mat input rotation matrix. (refer to @ref WVR_Matrix4f)
* @param quat input Quaternion. (refer to @ref WVR_Quatf)
* @param m2q true to convert matrix to Quaternion, false to do opposite.
* @version API Level 1
*/
extern WVR_EXPORT void WVR_ConvertMatrixQuaternion(WVR_Matrix4f_t *mat, WVR_Quatf_t *quat, bool m2q);
/**
* @brief Function to set a parameter string to device service.
*
* @param type which indicate @ref WVR_DeviceType.
* @param pchValue set string to let AP communicate to device service.
* @version API Level 1
*/
extern WVR_EXPORT void WVR_SetParameters(WVR_DeviceType type, const char *pchValue);
/**
* @brief Function to get a parameter string from device service.
*
* @param type which indicate @ref WVR_DeviceType.
* @param pchValue send string to let AP communicate to device service.
* @param retValue The buffer to store parameter get from device service. unBufferSize should be the size of this buffer.
* @param unBufferSize The size of the buffer pointed to by pchValue.
* @return The number of bytes necessary to hold the string, including the trailing null. Returns 0 (and 0-length string) on failure.
* @version API Level 1
*/
extern WVR_EXPORT uint32_t WVR_GetParameters(WVR_DeviceType type, const char *pchValue, char *retValue, uint32_t unBufferSize);
/**
* @brief Function to get the Degree of Freedom (DoF) of device's pose.
*
* @param type which indicate @ref WVR_DeviceType.
* @return WVR_NumDoF_3DoF means the device provides 3 DoF pose (only rotation), WVR_NumDoF_6DoF means the device provides 6 DoF pose (rotation and position). (refer to @ref WVR_NumDoF)
* @version API Level 1
*/
extern WVR_EXPORT WVR_NumDoF WVR_GetDegreeOfFreedom(WVR_DeviceType type);
/**
* @brief Function to get the default controller role which will determine the role while the first controller connects.
* While the controller role is changed, server will send an event of WVR_EventType_DeviceRoleChanged to notify all of applications.
* At this moment, applications have to check the controller roles again with this API(WVR_GetDefaultControllerRole).
*
* @return The type of controller role, it will be WVRDeviceType_Controller_Right or WVRDeviceType_Controller_Left. (refer to @ref WVR_DeviceType)
* @version API Level 1
*/
extern WVR_EXPORT WVR_DeviceType WVR_GetDefaultControllerRole();
/**
* @brief Get current battery capacity of specified device with percentage.
* @param type Type of the device to get the InputDeviceState. (refer to @ref WVR_DeviceType)
* @return The percentage of battery of specified device.
* @version API Level 1
*/
extern WVR_EXPORT float WVR_GetDeviceBatteryPercentage( WVR_DeviceType type );
/**
* @brief Get the current status of battery capacity.
* @param type Type of the device to get the InputDeviceState. (refer to @ref WVR_DeviceType)
* @return The status of battery capacity. Return WVR_BatteryStatus_Unknown if device service cannot get the battery status. (refer to @ref WVR_BatteryStatus)
* @version API Level 1
*/
extern WVR_EXPORT WVR_BatteryStatus WVR_GetBatteryStatus( WVR_DeviceType type );
/**
* @brief Get the current charging status.
* @param type Type of the device to get the InputDeviceState. (refer to @ref WVR_DeviceType)
* @return The charging status. Return WVR_ChargeStatus_Unknown if device service cannot get the charging status. (refer to @ref WVR_ChargeStatus)
* @version API Level 1
*/
extern WVR_EXPORT WVR_ChargeStatus WVR_GetChargeStatus( WVR_DeviceType type );
/**
* @brief Get the current status of temperature of battery.
* @param type : Type of the device to get the InputDeviceState. (refer to @ref WVR_DeviceType)
* @return The Status of temperature of battery. Return WVR_BatteryTemperatureStatus_Unknown if device service cannot get the temperature status of battery in use. (refer to @ref WVR_BatteryTemperatureStatus)
* @version API Level 1
*/
extern WVR_EXPORT WVR_BatteryTemperatureStatus WVR_GetBatteryTemperatureStatus( WVR_DeviceType type );
/**
* @brief Get the current temperature of battery.
* @param type Type of the device to get the InputDeviceState. (refer to @ref WVR_DeviceType)
* @return The temperature of battery.
* -1 means not support or failure.
* @version API Level 1
*/
extern WVR_EXPORT float WVR_GetBatteryTemperature( WVR_DeviceType type );
/**
* @brief Function to set the interaction mode of application.
*
* @param mode which indicates @ref WVR_InteractionMode, @ref WVR_InteractionMode_SystemDefault means to reset @ref WVR_InteractionMode and @ref WVR_GazeTriggerType to system default values.
* @return bool, true for setting successfully.
* @version API Level 2
* @note Effective with Runtime version 2 or higher
*/
extern WVR_EXPORT bool WVR_SetInteractionMode(WVR_InteractionMode mode);
/**
* @brief Function to get the interaction mode of application.
*
* @return @ref WVR_InteractionMode, the interaction mode of application.
* @version API Level 2
* @note Effective with Runtime version 2 or higher
*/
extern WVR_EXPORT WVR_InteractionMode WVR_GetInteractionMode();
/**
* @brief Function to set the trigger type of gaze of application.
*
* @param type which indicate @ref WVR_GazeTriggerType.
* @return bool, true for setting successfully.
* @version API Level 2
* @note Effective with Runtime version 2 or higher
*/
extern WVR_EXPORT bool WVR_SetGazeTriggerType(WVR_GazeTriggerType type);
/**
* @brief Function to get the trigger type of gaze of application.
*
* @return @ref WVR_GazeTriggerType, the trigger type of gaze of application.
* @version API Level 2
* @note Effective with Runtime version 2 or higher
*/
extern WVR_EXPORT WVR_GazeTriggerType WVR_GetGazeTriggerType();
/**
* @brief Function to get the current states of device errors from the specific device.
*
* @param type Type of the device to get the InputDeviceState.
* @return WVR_DeviceErrorState, the bitmask records all of current states of device errors which has occurred on the specific device.
* @version API Level 3
* @note Effective with Runtime version 3 or higher
*/
extern WVR_EXPORT bool WVR_GetDeviceErrorState( WVR_DeviceType dev_type, WVR_DeviceErrorStatus error_type );
/**
* @brief Function to enables or disables use of the neck model for 3-DOF head tracking.
*
* @param true to enable neck model for 3-DOF head tracking, false to disable.
* @version API Level 2
* @note Effective with Runtime version 2 or higher
*/
extern WVR_EXPORT void WVR_SetNeckModelEnabled(bool enabled);
/**
* @brief Function to replace HMD position with Neck Model simulation or not.
* If one pose was simulated by Neck Model, its is6DoFPose will be always false.
*
* @param type which indicates @ref WVR_SimulationType.
* @version API Level 3
*/
extern WVR_EXPORT void WVR_SetNeckModel(WVR_SimulationType type);
/**
* @brief Function to replace Controllers' positions with Arm Model simulation or not.
* If one pose was simulated by Arm Model, its is6DoFPose will be always false.
*
* @param type which indicates @ref WVR_SimulationType.
* @version API Level 3
*/
extern WVR_EXPORT void WVR_SetArmModel(WVR_SimulationType type);
/**
* @brief Function to set the behavior of Arm Model simulation. Default NOT follows head/HMD if a controller is steady (stickyArm=false).
*
* @param stickyArm force the simulated controllers' positions always follow HMD constantly, even a controller is steady.
* @version API Level 3
*/
extern WVR_EXPORT void WVR_SetArmSticky(bool stickyArm);
/**
* @brief To set what input keys are requested by app.
* MUST be invoked after WVR_Init otherwise @ref WVR_InputEvent, @ref WVR_GetInputDeviceState, @ref WVR_GetInputButtonState, @ref WVR_GetInputTouchState, and @ref WVR_GetInputAnalogAxis all cannot get input event in app.
*
* @param type which indicates what device type. (refer to @ref WVR_DeviceType).
* @param request what keys used by app (refer to @ref WVR_InputAttribute).
* @param size the size of the request buffer pointed to.
* @return true means request valid, false means request invalid.
* @version API Level 3
* @note Key mapping policy excludes 2 cases from setting input request:
* -# @ref WVR_InputId_Alias1_System is reserved for system use. The app cannot receive system key event even you set input request for it.
* -# @ref WVR_InputId_Alias1_Volume_Up and @ref WVR_InputId_Alias1_Volume_Down are specially used for volume control by system. Key mapping policy will not get other keys mapping to volume keys. The app can receive volume key events even you don’t set input request for them.
*/
extern WVR_EXPORT bool WVR_SetInputRequest(WVR_DeviceType type, const WVR_InputAttribute* request, uint32_t size);
/**
* @brief To get input mapping pair for the designated destination key.
* @param type which indicates what device type. (refer to @ref WVR_DeviceType).
* @param destination indicates the input id which app asks (refer to @ref WVR_InputId).
* @param pair outputs the input mapping pair for destination input id.
* @return true means pair valid, false means pair invalid(cannot find a right source mapping to destination from device).
* @version API Level 3
*/
extern WVR_EXPORT bool WVR_GetInputMappingPair(WVR_DeviceType type, WVR_InputId destination, WVR_InputMappingPair* pair);
/**
* @brief To get the entire input mapping table.
* @param type which indicates what device type. (refer to @ref WVR_DeviceType).
* @param table outputs the entire input mapping table.
* @param size the buffer size of allocated for table.
* @return the valid size filled in output table which means exactly getting the right input mapping from device to app.
* @version API Level 3
*/
extern WVR_EXPORT uint32_t WVR_GetInputMappingTable(WVR_DeviceType type, WVR_InputMappingPair* table, uint32_t size);
/**
* @brief Function to enable or disable position and rotation prediction of pose.
* @param type which indicates what device type. (refer to @ref WVR_DeviceType).
* @param enabled_position_predict enable or disable position prediction of pose.
* @param enabled_rotation_predict enable or disable rotation prediction of pose.
* @version API Level 4
* @note HMD always supports rotation prediction and cannot be disabled.
* You can pick either left or right controller to enable/disable both controllers pose prediction.
* HMD position prediction and controller pose prediction are default disabled.
* This feature will depend on device's capability of supporting pose prediction.
*/
extern WVR_EXPORT void WVR_SetPosePredictEnabled(WVR_DeviceType type, bool enabled_position_predict, bool enabled_rotation_predict);
#ifdef __cplusplus
}
#endif
#include "close_code.h"
#endif /* wvr_device_h_ */
| 47.79558 | 276 | 0.757716 | [
"render",
"model",
"transform"
] |
b393905d7413d9a394da1f6a8c2059a0950ce99c | 1,255 | h | C | actor-apps/core-async-cocoa/src/im/actor/model/api/UserOutPeer.h | DragonStuff/actor-platform | d262e6bb3c18b20eb35551313bce16c471cd2928 | [
"MIT"
] | null | null | null | actor-apps/core-async-cocoa/src/im/actor/model/api/UserOutPeer.h | DragonStuff/actor-platform | d262e6bb3c18b20eb35551313bce16c471cd2928 | [
"MIT"
] | null | null | null | actor-apps/core-async-cocoa/src/im/actor/model/api/UserOutPeer.h | DragonStuff/actor-platform | d262e6bb3c18b20eb35551313bce16c471cd2928 | [
"MIT"
] | null | null | null | //
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: /Users/ex3ndr/Develop/actor-platform/actor-apps/core/src/main/java/im/actor/model/api/UserOutPeer.java
//
#ifndef _APUserOutPeer_H_
#define _APUserOutPeer_H_
#include "J2ObjC_header.h"
#include "im/actor/model/droidkit/bser/BserObject.h"
@class BSBserValues;
@class BSBserWriter;
@interface APUserOutPeer : BSBserObject
#pragma mark Public
- (instancetype)init;
- (instancetype)initWithInt:(jint)uid
withLong:(jlong)accessHash;
- (jlong)getAccessHash;
- (jint)getUid;
- (void)parseWithBSBserValues:(BSBserValues *)values;
- (void)serializeWithBSBserWriter:(BSBserWriter *)writer;
- (NSString *)description;
@end
J2OBJC_EMPTY_STATIC_INIT(APUserOutPeer)
FOUNDATION_EXPORT void APUserOutPeer_initWithInt_withLong_(APUserOutPeer *self, jint uid, jlong accessHash);
FOUNDATION_EXPORT APUserOutPeer *new_APUserOutPeer_initWithInt_withLong_(jint uid, jlong accessHash) NS_RETURNS_RETAINED;
FOUNDATION_EXPORT void APUserOutPeer_init(APUserOutPeer *self);
FOUNDATION_EXPORT APUserOutPeer *new_APUserOutPeer_init() NS_RETURNS_RETAINED;
J2OBJC_TYPE_LITERAL_HEADER(APUserOutPeer)
typedef APUserOutPeer ImActorModelApiUserOutPeer;
#endif // _APUserOutPeer_H_
| 24.607843 | 121 | 0.803187 | [
"model"
] |
b39403132f0863892c933966f8cc19d878c9854f | 12,207 | c | C | src/lib/encrypt.c | alvinchchen/tpm2-pkcs11 | 5ce4e01a52fcbb3b3073daa2c16ee943f71496c6 | [
"BSD-2-Clause"
] | null | null | null | src/lib/encrypt.c | alvinchchen/tpm2-pkcs11 | 5ce4e01a52fcbb3b3073daa2c16ee943f71496c6 | [
"BSD-2-Clause"
] | null | null | null | src/lib/encrypt.c | alvinchchen/tpm2-pkcs11 | 5ce4e01a52fcbb3b3073daa2c16ee943f71496c6 | [
"BSD-2-Clause"
] | null | null | null | /* SPDX-License-Identifier: BSD-2-Clause */
#include <openssl/bn.h>
#include <openssl/err.h>
#include <openssl/rsa.h>
#include "checks.h"
#include "encrypt.h"
#include "mech.h"
#include "openssl_compat.h"
#include "session.h"
#include "session_ctx.h"
#include "token.h"
#include "tpm.h"
struct sw_encrypt_data {
int padding;
RSA *key;
};
typedef CK_RV (*crypto_op)(crypto_op_data *enc_data, CK_OBJECT_CLASS, CK_BYTE_PTR in, CK_ULONG inlen, CK_BYTE_PTR out, CK_ULONG_PTR outlen);
static sw_encrypt_data *sw_encrypt_data_new(void) {
return (sw_encrypt_data *)calloc(1, sizeof(sw_encrypt_data));
}
static void sw_encrypt_data_free(sw_encrypt_data **enc_data) {
if (!enc_data) {
return;
}
if ((*enc_data)->key) {
RSA_free((*enc_data)->key);
}
free(*enc_data);
*enc_data = NULL;
}
encrypt_op_data *encrypt_op_data_new(tobject *tobj) {
CK_ATTRIBUTE_PTR a = attr_get_attribute_by_type(tobj->attrs, CKA_CLASS);
if (!a) {
LOGE("Expected tobjects to have attribute CKA_CLASS");
return NULL;
}
CK_OBJECT_CLASS clazz;
CK_RV rv = attr_CK_OBJECT_CLASS(a, &clazz);
if (rv != CKR_OK) {
LOGE("Could not convert CKA_CLASS");
return NULL;
}
encrypt_op_data *d = (encrypt_op_data *)calloc(1, sizeof(encrypt_op_data));
if (!d) {
return NULL;
}
d->clazz = clazz;
return d;
}
void encrypt_op_data_free(encrypt_op_data **opdata) {
if (opdata) {
(*opdata)->use_sw ?
sw_encrypt_data_free(&(*opdata)->cryptopdata.sw_enc_data) :
tpm_opdata_free(&(*opdata)->cryptopdata.tpm_opdata);
free(*opdata);
*opdata = NULL;
}
}
static CK_RV sw_encrypt_data_init(CK_MECHANISM *mechanism, tobject *tobj, sw_encrypt_data **enc_data) {
BIGNUM *e = NULL;
BIGNUM *n = NULL;
RSA *r = NULL;
CK_RV rv = CKR_GENERAL_ERROR;
/* we only support one mechanism via this path right now */
if (mechanism->mechanism != CKM_RSA_PKCS) {
LOGE("Cannot synthesize mechanism for key");
return CKR_MECHANISM_INVALID;
}
/*
* We know this in RSA key since we checked the mechanism,
* create the OSSL key
*/
r = RSA_new();
if (!r) {
LOGE("oom");
rv = CKR_HOST_MEMORY;
goto error;
}
CK_ATTRIBUTE_PTR a = attr_get_attribute_by_type(tobj->attrs, CKA_MODULUS);
if (!a) {
LOGE("Expected RSA key to have modulus");
goto error;
}
n = BN_bin2bn(a->pValue, a->ulValueLen, NULL);
if (!n) {
LOGE("Could not create BN from modulus");
goto error;
}
a = attr_get_attribute_by_type(tobj->attrs, CKA_PUBLIC_EXPONENT);
if (!a) {
LOGE("Expected RSA key to have exponent");
goto error;
}
e = BN_bin2bn(a->pValue, a->ulValueLen, NULL);
if (!e) {
LOGE("Could not create BN from exponent");
goto error;
}
int rc = RSA_set0_key(r, n, e, NULL);
if (!rc) {
LOGE("Could not set RSA public key from parts");
goto error;
}
/* ownership of memory transferred */
n = NULL;
e = NULL;
sw_encrypt_data *d = sw_encrypt_data_new();
if (!d) {
LOGE("oom");
rv = CKR_HOST_MEMORY;
goto error;
}
d->key = r;
d->padding = RSA_PKCS1_PADDING;
*enc_data = d;
return CKR_OK;
error:
if (n) {
BN_free(n);
}
if (e) {
BN_free(e);
}
return rv;
}
CK_RV sw_encrypt(crypto_op_data *opdata, CK_OBJECT_CLASS clazz,
CK_BYTE_PTR ptext, CK_ULONG ptextlen,
CK_BYTE_PTR ctext, CK_ULONG_PTR ctextlen) {
UNUSED(clazz);
assert(opdata);
sw_encrypt_data *sw_enc_data = opdata->sw_enc_data;
assert(sw_enc_data);
assert(sw_enc_data->key);
RSA *r = sw_enc_data->key;
int padding = sw_enc_data->padding;
/* make sure destination is big enough */
int to_len = RSA_size(r);
if (to_len < 0) {
LOGE("RSA_Size cannot be 0");
return CKR_GENERAL_ERROR;
}
if ((CK_ULONG)to_len > *ctextlen) {
*ctextlen = to_len;
return CKR_BUFFER_TOO_SMALL;
}
int rc = RSA_public_encrypt(ptextlen, ptext,
ctext, r, padding);
if (!rc) {
LOGE("Could not perform RSA public encrypt");
return CKR_GENERAL_ERROR;
}
assert(rc > 0);
*ctextlen = rc;
return CKR_OK;
}
CK_RV sw_decrypt(crypto_op_data *opdata, CK_OBJECT_CLASS clazz,
CK_BYTE_PTR ctext, CK_ULONG ctextlen,
CK_BYTE_PTR ptext, CK_ULONG_PTR ptextlen) {
UNUSED(clazz);
assert(opdata);
CK_RV rv = CKR_GENERAL_ERROR;
sw_encrypt_data *sw_enc_data = opdata->sw_enc_data;
assert(sw_enc_data);
assert(sw_enc_data->key);
RSA *r = sw_enc_data->key;
int padding = sw_enc_data->padding;
int to_len = RSA_size(r);
if (to_len <= 0) {
LOGE("Expected buffer size to be > 0, got: %d", to_len);
return CKR_GENERAL_ERROR;
}
unsigned char *buffer = calloc(1, to_len);
if (!buffer) {
LOGE("oom");
return CKR_HOST_MEMORY;
}
int rc = RSA_public_decrypt(ctextlen, ctext, buffer, r, padding);
if (rc <= 0) {
LOGE("Could not perform RSA public decrypt: %s",
ERR_error_string(ERR_get_error(), NULL));
goto out;
}
assert(rc > 0);
if (*ptextlen > (CK_ULONG)rc) {
*ptextlen = rc;
free(buffer);
return CKR_BUFFER_TOO_SMALL;
}
memcpy(ptext, buffer, rc);
*ptextlen = rc;
rv = CKR_OK;
out:
free(buffer);
return rv;
}
static CK_RV common_init_op (session_ctx *ctx, encrypt_op_data *supplied_opdata, operation op, CK_MECHANISM_PTR mechanism, CK_OBJECT_HANDLE key) {
check_pointer(mechanism);
LOGV("mechanism->mechanism: %lu\n"
"mechanism->ulParameterLen: %lu\n"
"mechanism->pParameter: %s",
mechanism->mechanism,
mechanism->ulParameterLen,
mechanism->pParameter ? "set" : "(null)");
token *tok = session_ctx_get_token(ctx);
assert(tok);
if (!supplied_opdata) {
bool is_active = session_ctx_opdata_is_active(ctx);
if (is_active) {
return CKR_OPERATION_ACTIVE;
}
}
tobject *tobj;
CK_RV rv = token_load_object(tok, key, &tobj);
if (rv != CKR_OK) {
return rv;
}
rv = object_mech_is_supported(tobj, mechanism);
if (rv != CKR_OK) {
tobject_user_decrement(tobj);
return rv;
}
encrypt_op_data *opdata;
if (!supplied_opdata) {
opdata = encrypt_op_data_new(tobj);
if (!opdata) {
tobject_user_decrement(tobj);
return CKR_HOST_MEMORY;
}
} else {
opdata = supplied_opdata;
}
/*
* Objects that don't have a tpm pub pointer blob are things like public key
* only object and don't go to the TPM.
*/
if (tobj->pub) {
rv = mech_get_tpm_opdata(tok->tctx, mechanism, tobj,
&opdata->cryptopdata.tpm_opdata);
} else {
opdata->use_sw = true;
rv = sw_encrypt_data_init(mechanism, tobj, &opdata->cryptopdata.sw_enc_data);
}
if (rv != CKR_OK) {
tobject_user_decrement(tobj);
if (!supplied_opdata) {
encrypt_op_data_free(&opdata);
}
return rv;
}
if (!supplied_opdata) {
session_ctx_opdata_set(ctx, op, tobj, opdata, (opdata_free_fn)encrypt_op_data_free);
}
return CKR_OK;
}
static CK_RV common_update_op (session_ctx *ctx, encrypt_op_data *supplied_opdata, operation op,
CK_BYTE_PTR part, CK_ULONG part_len,
CK_BYTE_PTR encrypted_part, CK_ULONG_PTR encrypted_part_len) {
check_pointer(part);
check_pointer(encrypted_part_len);
CK_RV rv = CKR_GENERAL_ERROR;
twist input = twistbin_new(part, part_len);
if (!input) {
return CKR_HOST_MEMORY;
}
twist output = NULL;
encrypt_op_data *opdata = NULL;
if (!supplied_opdata) {
rv = session_ctx_opdata_get(ctx, op, &opdata);
if (rv != CKR_OK) {
goto out;
}
rv = session_ctx_tobject_authenticated(ctx);
if (rv != CKR_OK) {
goto out;
}
} else {
opdata = supplied_opdata;
}
crypto_op fop;
switch(op) {
case operation_encrypt:
fop = opdata->use_sw ? sw_encrypt : tpm_encrypt;
break;
case operation_decrypt:
fop = opdata->use_sw ? sw_decrypt : tpm_decrypt;
break;
default:
return CKR_GENERAL_ERROR;
}
rv = fop(&opdata->cryptopdata, opdata->clazz, part, part_len,
encrypted_part, encrypted_part_len);
if (rv != CKR_OK) {
goto out;
}
rv = CKR_OK;
out:
twist_free(input);
twist_free(output);
return rv;
}
static CK_RV common_final_op(session_ctx *ctx, encrypt_op_data *supplied_opdata, operation op,
CK_BYTE_PTR last_part, CK_ULONG_PTR last_part_len) {
/*
* We have no use for these.
*/
UNUSED(last_part);
UNUSED(last_part_len);
CK_RV rv = CKR_GENERAL_ERROR;
/* nothing to do if opdata is supplied externally */
if (supplied_opdata) {
/* do not goto out, no opdata to clear */
return CKR_OK;
}
encrypt_op_data *opdata = NULL;
rv = session_ctx_opdata_get(ctx, op, &opdata);
if (rv != CKR_OK) {
return rv;
}
rv = session_ctx_tobject_authenticated(ctx);
if (rv != CKR_OK) {
return rv;
}
tobject *tobj = session_ctx_opdata_get_tobject(ctx);
assert(tobj);
tobj->is_authenticated = false;
rv = tobject_user_decrement(tobj);
if (rv != CKR_OK) {
return rv;
}
session_ctx_opdata_clear(ctx);
return CKR_OK;
}
CK_RV encrypt_init_op (session_ctx *ctx, encrypt_op_data *supplied_opdata, CK_MECHANISM *mechanism, CK_OBJECT_HANDLE key) {
return common_init_op(ctx, supplied_opdata, operation_encrypt, mechanism, key);
}
CK_RV decrypt_init_op (session_ctx *ctx, encrypt_op_data *supplied_opdata, CK_MECHANISM *mechanism, CK_OBJECT_HANDLE key) {
return common_init_op(ctx, supplied_opdata, operation_decrypt, mechanism, key);
}
CK_RV encrypt_update_op (session_ctx *ctx, encrypt_op_data *supplied_opdata, CK_BYTE_PTR part, CK_ULONG part_len, CK_BYTE_PTR encrypted_part, CK_ULONG_PTR encrypted_part_len) {
return common_update_op(ctx, supplied_opdata, operation_encrypt, part, part_len, encrypted_part, encrypted_part_len);
}
CK_RV decrypt_update_op (session_ctx *ctx, encrypt_op_data *supplied_opdata, CK_BYTE_PTR part, CK_ULONG part_len, CK_BYTE_PTR encrypted_part, CK_ULONG_PTR encrypted_part_len) {
return common_update_op(ctx, supplied_opdata, operation_decrypt, part, part_len, encrypted_part, encrypted_part_len);
}
CK_RV encrypt_final_op (session_ctx *ctx, encrypt_op_data *supplied_opdata, CK_BYTE_PTR last_encrypted_part, CK_ULONG_PTR last_encrypted_part_len) {
return common_final_op(ctx, supplied_opdata, operation_encrypt, last_encrypted_part, last_encrypted_part_len);
}
CK_RV decrypt_final_op (session_ctx *ctx, encrypt_op_data *supplied_opdata, CK_BYTE_PTR last_part, CK_ULONG_PTR last_part_len) {
return common_final_op(ctx, supplied_opdata, operation_decrypt, last_part, last_part_len);
}
CK_RV decrypt_oneshot_op (session_ctx *ctx, encrypt_op_data *supplied_opdata, CK_BYTE_PTR encrypted_data, CK_ULONG encrypted_data_len, CK_BYTE_PTR data, CK_ULONG_PTR data_len) {
CK_RV rv = decrypt_update_op(ctx, supplied_opdata, encrypted_data, encrypted_data_len,
data, data_len);
if (rv != CKR_OK || !data) {
return rv;
}
return decrypt_final_op(ctx, supplied_opdata, NULL, NULL);
}
CK_RV encrypt_oneshot_op (session_ctx *ctx, encrypt_op_data *supplied_opdata, CK_BYTE_PTR data, CK_ULONG data_len, CK_BYTE_PTR encrypted_data, CK_ULONG_PTR encrypted_data_len) {
CK_RV rv = encrypt_update_op (ctx, supplied_opdata, data, data_len, encrypted_data, encrypted_data_len);
if (rv != CKR_OK || !encrypted_data) {
return rv;
}
return encrypt_final_op(ctx, supplied_opdata, NULL, NULL);
}
| 25.97234 | 177 | 0.643074 | [
"object"
] |
b3964dbe7318dae20d0374f6fb4f92bdfabb0854 | 1,838 | h | C | dependencies/libdansdl2/herramientas/templates/gestor_vector_static.h | TheMarlboroMan/winter-fgj5 | 28cd4bd4ae37230e51c1a9963bcd293e674cdc3c | [
"Beerware"
] | null | null | null | dependencies/libdansdl2/herramientas/templates/gestor_vector_static.h | TheMarlboroMan/winter-fgj5 | 28cd4bd4ae37230e51c1a9963bcd293e674cdc3c | [
"Beerware"
] | null | null | null | dependencies/libdansdl2/herramientas/templates/gestor_vector_static.h | TheMarlboroMan/winter-fgj5 | 28cd4bd4ae37230e51c1a9963bcd293e674cdc3c | [
"Beerware"
] | null | null | null | #ifndef GESTOR_VECTOR_STATIC_H
#define GESTOR_VECTOR_STATIC_H
#include <vector>
#include <iostream> //Para NULL...
/*
Unas palabras... Aquí hay estar un poco atento: el tipo es class T y siempre
se enuncia de ese modo. Si la intención del vector es recibir punteros lo
declarareos como Gestor_vector_static<clase_de_turno *>.
*/
namespace DLibH
{
template<class T>
class Gestor_vector_static
{
protected:
static std::vector<T> elementos;
Gestor_vector_static(){}
~Gestor_vector_static(){}
public:
static const std::vector<T>& acc_elementos() {return Gestor_vector_static::elementos;}
unsigned int cantidad() const {return Gestor_vector_static::elementos.size();}
static T registrar(T p_elem)
{
int l=Gestor_vector_static::elementos.size(), i=0;
bool encontrado=false;
for(; i<l && !encontrado; i++)
encontrado=p_elem==Gestor_vector_static::elementos[i];
if(!encontrado)
Gestor_vector_static::elementos.push_back(p_elem);
return p_elem;
}
static T obtener(unsigned int p_indice)
{
int l=Gestor_vector_static::elementos.size();
T resultado=NULL;
if(p_indice >= 0 && p_indice<l)
{
resultado=Gestor_vector_static::elementos[p_indice];
}
return resultado;
}
static bool liberar(unsigned int p_indice)
{
bool resultado=false;
int l=Gestor_vector_static::elementos.size(), i=0;
if(p_indice >= 0 && p_indice<l)
{
Gestor_vector_static::elementos.erase(Gestor_vector_static::elementos.begin()+p_indice);
resultado=true;
}
return resultado;
}
static void vaciar()
{
while(!Gestor_vector_static::elementos.empty())
{
T elemento=Gestor_vector_static::elementos.back();
delete elemento;
Gestor_vector_static::elementos.pop_back();
}
}
};
template <class T> std::vector<T> Gestor_vector_static<T>::elementos;
} //Fin namespace DLibH
#endif
| 20.886364 | 91 | 0.729053 | [
"vector"
] |
b39a4764ace64f72414ed24e2037b16c8c1d36b3 | 10,836 | h | C | src/njli/physics/constraint/PhysicsConstraintGeneric6Dof.h | njligames/Engine | 899c7b79cea33a72fc34f159134f721b56715d3d | [
"MIT"
] | 1 | 2019-02-13T05:41:54.000Z | 2019-02-13T05:41:54.000Z | src/njli/physics/constraint/PhysicsConstraintGeneric6Dof.h | njligames/Engine | 899c7b79cea33a72fc34f159134f721b56715d3d | [
"MIT"
] | null | null | null | src/njli/physics/constraint/PhysicsConstraintGeneric6Dof.h | njligames/Engine | 899c7b79cea33a72fc34f159134f721b56715d3d | [
"MIT"
] | null | null | null | //
// PhysicsConstraintGeneric6Dof.h
// JLIGameEngineTest
//
// Created by James Folk on 6/19/15.
// Copyright (c) 2015 James Folk. All rights reserved.
//
#ifndef __JLIGameEngineTest__PhysicsConstraintGeneric6Dof__
#define __JLIGameEngineTest__PhysicsConstraintGeneric6Dof__
#pragma mark Header
#include "AbstractFactoryObject.h"
#include "AbstractBuilder.h"
#include "lua.hpp"
#include "Log.h"
#include "PhysicsConstraint.h"
class btGeneric6DofConstraint;
class btRotationalLimitMotor;
class btTranslationalLimitMotor;
namespace njli
{
class PhysicsConstraintGeneric6DofBuilder;
/**
* <#Description#>
*/
ATTRIBUTE_ALIGNED16(class) PhysicsConstraintGeneric6Dof:
public PhysicsConstraint
{
friend class WorldFactory;
protected:
PhysicsConstraintGeneric6Dof();
PhysicsConstraintGeneric6Dof(const AbstractBuilder&);
PhysicsConstraintGeneric6Dof(const PhysicsConstraintGeneric6Dof &);
BT_DECLARE_ALIGNED_ALLOCATOR();
virtual ~PhysicsConstraintGeneric6Dof();
PhysicsConstraintGeneric6Dof &operator=(const PhysicsConstraintGeneric6Dof &);
public:
/**
* <#Description#>
*
* @return <#return value description#>
*/
virtual s32 calculateSerializeBufferSize() const;
/**
* @author James Folk, 16-02-11 15:02:41
*
* @brief <#Description#>
*
* @param dataBuffer <#dataBuffer description#>
* @param btSerializer <#btSerializer description#>
*/
virtual void serialize(void*dataBuffer, btSerializer*) const;
/**
* <#Description#>
*
* @return <#return value description#>
*/
virtual const char *getClassName()const;
/**
* <#Description#>
*
* @return <#return value description#>
*/
virtual s32 getType()const;
/**
* <#Description#>
*
* @return <#return value description#>
*/
operator std::string() const;
/**
* <#Description#>
*
* @param size <#size description#>
*
* @return <#return value description#>
*/
static PhysicsConstraintGeneric6Dof **createArray(const u32 size);
/**
* <#Description#>
*
* @param array <#array description#>
*/
static void destroyArray(PhysicsConstraintGeneric6Dof **array, const u32 size = 0);
/**
* <#Description#>
*
* @return <#return value description#>
*/
static PhysicsConstraintGeneric6Dof *create();
/**
* <#Description#>
*
* @param builder <#builder description#>
*
* @return <#return value description#>
*/
static PhysicsConstraintGeneric6Dof *create(const PhysicsConstraintGeneric6DofBuilder &builder);
/**
* <#Description#>
*
* @param object <#object description#>
*
* @return <#return value description#>
*/
static PhysicsConstraintGeneric6Dof *clone(const PhysicsConstraintGeneric6Dof &object);
/**
* <#Description#>
*
* @param object <#object description#>
*
* @return <#return value description#>
*/
static PhysicsConstraintGeneric6Dof *copy(const PhysicsConstraintGeneric6Dof &object);
/**
* <#Description#>
*
* @param object <#object description#>
*/
static void destroy(PhysicsConstraintGeneric6Dof *object);
/**
* <#Description#>
*
* @param object <#object description#>
* @param L <#L description#>
* @param stack_index <#stack_index description#>
*/
static void load(PhysicsConstraintGeneric6Dof &object, lua_State *L, int stack_index);
/**
* <#Description#>
*
* @return <#return value description#>
*/
static u32 type();
public:
//TODO: fill in specific methods for PhysicsConstraintGeneric6Dof
/**
* <#Description#>
*
* @param nodeA <#nodeA description#>
* @param nodeB <#nodeB description#>
* @param frameInA <#frameInA description#>
* @param frameInB <#frameInB description#>
* @param useLinearReferenceFrameA <#useLinearReferenceFrameA description#>
*/
void setNodes(Node *nodeA, Node *nodeB, const btTransform& frameInA = btTransform::getIdentity(), const btTransform& frameInB = btTransform::getIdentity() ,bool useLinearReferenceFrameA = true);
/**
* <#Description#>
*
* @param nodeB <#nodeB description#>
* @param frameInB <#frameInB description#>
* @param useLinearReferenceFrameB <#useLinearReferenceFrameB description#>
*/
void setNodes(Node *nodeB, const btTransform& frameInB = btTransform::getIdentity(), bool useLinearReferenceFrameB = true);
/**
* <#Description#>
*/
void calculateTransforms();
/**
* <#Description#>
*
* @return <#return value description#>
*/
const btTransform & getCalculatedTransformA() const;
/**
* <#Description#>
*
* @return <#return value description#>
*/
const btTransform & getCalculatedTransformB() const;
/**
* <#Description#>
*
* @return <#return value description#>
*/
const btTransform & getFrameOffsetA() const;
/**
* <#Description#>
*
* @return <#return value description#>
*/
const btTransform & getFrameOffsetB() const;
/**
* <#Description#>
*
* @return <#return value description#>
*/
btTransform & getFrameOffsetA();
/**
* <#Description#>
*
* @return <#return value description#>
*/
btTransform & getFrameOffsetB();
/**
* <#Description#>
*
* @param axis_index <#axis_index description#>
*
* @return <#return value description#>
*/
btVector3 getAxis(int axis_index) const;
/**
* <#Description#>
*
* @param axis_index <#axis_index description#>
*
* @return <#return value description#>
*/
f32 getAngle(int axis_index) const;
/**
* <#Description#>
*
* @param axis_index <#axis_index description#>
*
* @return <#return value description#>
*/
f32 getRelativePivotPosition(int axis_index) const;
/**
* <#Description#>
*
* @param frameA <#frameA description#>
* @param frameB <#frameB description#>
*/
void setFrames(const btTransform & frameA, const btTransform & frameB);
/**
* <#Description#>
*
* @param axis_index <#axis_index description#>
*
* @return <#return value description#>
*/
bool testAngularLimitMotor(int axis_index);
/**
* <#Description#>
*
* @param linearLower <#linearLower description#>
*/
void setLinearLowerLimit(const btVector3& linearLower);
/**
* <#Description#>
*
* @param linearLower <#linearLower description#>
*/
void getLinearLowerLimit(btVector3& linearLower);
/**
* <#Description#>
*
* @param linearUpper <#linearUpper description#>
*/
void setLinearUpperLimit(const btVector3& linearUpper);
/**
* <#Description#>
*
* @param linearUpper <#linearUpper description#>
*/
void getLinearUpperLimit(btVector3& linearUpper);
/**
* <#Description#>
*
* @param angularLower <#angularLower description#>
*/
void setAngularLowerLimit(const btVector3& angularLower);
/**
* <#Description#>
*
* @param angularLower <#angularLower description#>
*/
void getAngularLowerLimit(btVector3& angularLower);
/**
* <#Description#>
*
* @param angularUpper <#angularUpper description#>
*/
void setAngularUpperLimit(const btVector3& angularUpper);
/**
* <#Description#>
*
* @param angularUpper <#angularUpper description#>
*/
void getAngularUpperLimit(btVector3& angularUpper);
/**
* <#Description#>
*
* @param index <#index description#>
*
* @return <#return value description#>
*/
btRotationalLimitMotor * getRotationalLimitMotor(int index);
/**
* <#Description#>
*
* @return <#return value description#>
*/
btTranslationalLimitMotor * getTranslationalLimitMotor();
/**
* <#Description#>
*
* @param axis <#axis description#>
* @param lo <#lo description#>
* @param hi <#hi description#>
*/
void setLimit(int axis, f32 lo, f32 hi);
/**
* <#Description#>
*
* @param limitIndex <#limitIndex description#>
*
* @return <#return value description#>
*/
bool isLimited(int limitIndex);
/**
* <#Description#>
*
* @return <#return value description#>
*/
bool getUseFrameOffset();
/**
* <#Description#>
*
* @param frameOffsetOnOff <#frameOffsetOnOff description#>
*/
void setUseFrameOffset(bool frameOffsetOnOff);
/**
* <#Description#>
*
* @param axis1 <#axis1 description#>
* @param axis2 <#axis2 description#>
*/
void setAxis( const btVector3& axis1, const btVector3& axis2);
protected:
virtual btTypedConstraint *getConstraint();
virtual const btTypedConstraint *getConstraint()const;
virtual void removeConstraint();
private:
btGeneric6DofConstraint *m_btGeneric6DofConstraint;
};
}
#endif /* defined(__JLIGameEngineTest__PhysicsConstraintGeneric6Dof__) */
| 30.610169 | 202 | 0.531654 | [
"object"
] |
b39f15e5db845229c490c32dbf0874a4df39bcc6 | 2,852 | h | C | extra/news/src/xk/external/udpipe/udpipe/parsito/parser/parser_nn.h | scignscape/PGVM | e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0 | [
"BSL-1.0"
] | null | null | null | extra/news/src/xk/external/udpipe/udpipe/parsito/parser/parser_nn.h | scignscape/PGVM | e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0 | [
"BSL-1.0"
] | null | null | null | extra/news/src/xk/external/udpipe/udpipe/parsito/parser/parser_nn.h | scignscape/PGVM | e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0 | [
"BSL-1.0"
] | null | null | null | // This file is part of Parsito <http://github.com/ufal/parsito/>.
//
// Copyright 2015 Institute of Formal and Applied Linguistics, Faculty of
// Mathematics and Physics, Charles University in Prague, Czech Republic.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#pragma once
#include <list>
#include "common.h"
#include "parsito/configuration/node_extractor.h"
#include "parsito/configuration/value_extractor.h"
#include "parsito/embedding/embedding.h"
#include "parsito/network/neural_network.h"
#include "parser.h"
#include "parsito/transition/transition_system.h"
#include "utils/threadsafe_stack.h"
namespace ufal {
namespace udpipe {
namespace parsito {
class parser_nn : public parser {
public:
parser_nn(bool versioned);
virtual void parse(tree& t, unsigned beam_size = 0, double* cost = nullptr) const override;
protected:
virtual void load(binary_decoder& data, unsigned cache) override;
private:
friend class parser_nn_trainer;
void parse_greedy(tree& t, double* cost) const;
void parse_beam_search(tree& t, unsigned beam_size, double* cost) const;
bool versioned;
unsigned version;
bool single_root;
enum { VERSION_LATEST = 2 };
vector<string> labels;
unique_ptr<transition_system> system;
node_extractor nodes;
vector<value_extractor> values;
vector<embedding> embeddings;
neural_network network;
neural_network::embeddings_cache embeddings_cache;
struct workspace {
workspace(bool single_root) : conf(single_root) {}
configuration conf;
string word, word_buffer;
vector<vector<int>> embeddings;
vector<vector<string>> embeddings_values;
vector<int> extracted_nodes;
vector<const vector<int>*> extracted_embeddings;
vector<float> outcomes, network_buffer;
// Beam-size structures
struct beam_size_configuration {
beam_size_configuration(bool single_root) : conf(single_root) {}
configuration conf;
vector<int> heads;
vector<string> deprels;
double cost;
void refresh_tree();
void save_tree();
};
struct beam_size_alternative {
const beam_size_configuration* bs_conf;
int transition;
double cost;
bool operator<(const beam_size_alternative& other) const { return cost > other.cost; }
beam_size_alternative(const beam_size_configuration* bs_conf, int transition, double cost)
: bs_conf(bs_conf), transition(transition), cost(cost) {}
};
vector<beam_size_configuration> bs_confs[2]; size_t bs_confs_size[2];
vector<beam_size_alternative> bs_alternatives;
};
mutable threadsafe_stack<workspace> workspaces;
};
} // namespace parsito
} // namespace udpipe
} // namespace ufal
| 28.237624 | 96 | 0.73352 | [
"vector"
] |
b3a5a3d318ef8d698cf2dd03643c935ccfea0e24 | 1,493 | h | C | bin/ledger/storage/public/commit.h | Acidburn0zzz/peridot | 9a3b1fb8e834d0315092478d83d0176ef28cb765 | [
"BSD-3-Clause"
] | 1 | 2018-02-05T23:33:32.000Z | 2018-02-05T23:33:32.000Z | bin/ledger/storage/public/commit.h | Acidburn0zzz/peridot | 9a3b1fb8e834d0315092478d83d0176ef28cb765 | [
"BSD-3-Clause"
] | null | null | null | bin/ledger/storage/public/commit.h | Acidburn0zzz/peridot | 9a3b1fb8e834d0315092478d83d0176ef28cb765 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef PERIDOT_BIN_LEDGER_STORAGE_PUBLIC_COMMIT_H_
#define PERIDOT_BIN_LEDGER_STORAGE_PUBLIC_COMMIT_H_
#include <memory>
#include <string>
#include <vector>
#include "lib/fxl/macros.h"
#include "peridot/bin/ledger/storage/public/types.h"
namespace storage {
class Commit {
public:
Commit() {}
virtual ~Commit() {}
// Returns a copy of the commit.
virtual std::unique_ptr<Commit> Clone() const = 0;
// Returns the id of this commit.
virtual const CommitId& GetId() const = 0;
// Returns the ids of this commit's parents.
virtual std::vector<CommitIdView> GetParentIds() const = 0;
// Returns the creation timestamp of this commit in nanoseconds since epoch.
// TODO(nellyv): Replace return value with a time/clock type.
virtual int64_t GetTimestamp() const = 0;
// Returns the generation of this commit (ie. the number of commits to the
// root).
virtual uint64_t GetGeneration() const = 0;
// Returns the id of the root node of this commit.
virtual ObjectIdentifier GetRootIdentifier() const = 0;
// Returns the byte representation of this |Commit| as they will be synced to
// the cloud.
virtual fxl::StringView GetStorageBytes() const = 0;
private:
FXL_DISALLOW_COPY_AND_ASSIGN(Commit);
};
} // namespace storage
#endif // PERIDOT_BIN_LEDGER_STORAGE_PUBLIC_COMMIT_H_
| 28.169811 | 79 | 0.737441 | [
"vector"
] |
b3d220d4d2a98133d2b9c97268ecd39e35f9b218 | 8,599 | h | C | Linux/Sources/PP_Sources/Tables/UNX_LTableView.h | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2015-04-21T16:10:43.000Z | 2021-11-05T13:41:46.000Z | Linux/Sources/PP_Sources/Tables/UNX_LTableView.h | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2015-11-02T13:32:11.000Z | 2019-07-10T21:11:21.000Z | Linux/Sources/PP_Sources/Tables/UNX_LTableView.h | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2015-01-12T08:49:12.000Z | 2021-03-27T09:11:10.000Z | /*
Copyright (c) 2007 Cyrus Daboo. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef _H_UNX_LTableView
#define _H_UNX_LTableView
#include <UNX_LScrollable.h>
#include <UNX_UTables.h>
class LTableGeometry;
class LTableSelector;
class LTableStorage;
class JPainter;
// ---------------------------------------------------------------------------
class LTableView : public LScrollable {
public:
// Constructors & Destructor
LTableView(JXScrollbarSet* scrollbarSet,
JXContainer* enclosure,
const HSizingOption hSizing,
const VSizingOption vSizing,
const JCoordinate x, const JCoordinate y,
const JCoordinate w, const JCoordinate h);
virtual ~LTableView();
// Setters/Getters
void GetTableSize(
TableIndexT& outRows,
TableIndexT& outCols) const;
void SetUseDragSelect( bool inUseIt )
{
mUseDragSelect = inUseIt;
}
void SetDeferAdjustment( bool inDefer );
bool GetDeferAdjustment() { return mDeferAdjustment; }
// Row, Col, and Cell Verification
bool IsValidRow( TableIndexT inRow ) const;
bool IsValidCol( TableIndexT inCol ) const;
bool IsValidCell( const STableCell & inCell ) const;
// Row & Col Management
virtual void InsertRows(
UInt32 inHowMany,
TableIndexT inAfterRow,
const void* inDataPtr = nil,
UInt32 inDataSize = 0,
bool inRefresh = false);
virtual void InsertCols(
UInt32 inHowMany,
TableIndexT inAfterCol,
const void* inDataPtr = nil,
UInt32 inDataSize = 0,
bool inRefresh = false);
virtual void RemoveRows(
UInt32 inHowMany,
TableIndexT inFromRow,
bool inRefresh);
virtual void RemoveAllRows( bool inRefresh );
virtual void RemoveCols(
UInt32 inHowMany,
TableIndexT inFromCol,
bool inRefresh);
virtual void RemoveAllCols( bool inRefresh );
virtual void AdjustImageSize( bool inRefresh );
// Accessing Cells
virtual void CellToIndex(
const STableCell& inCell,
TableIndexT& outIndex) const;
virtual void IndexToCell(
TableIndexT inIndex,
STableCell& outCell) const;
virtual bool GetNextCell( STableCell& ioCell ) const;
virtual STableCell GetFirstSelectedCell() const;
virtual bool GetNextSelectedCell( STableCell& ioCell ) const;
virtual bool GetPreviousCell( STableCell& ioCell ) const;
virtual bool GetPreviousSelectedCell( STableCell& ioCell ) const;
virtual void ScrollCellIntoFrame( const STableCell& inCell );
virtual STableCell GetFirstFullyVisibleCell() const;
virtual STableCell GetLastFullyVisibleCell() const;
virtual STableCell GetSelectionAnchor() const;
virtual STableCell GetSelectionBoat() const;
// Cell Geometry
virtual void SetTableGeometry( LTableGeometry* inTableGeometry );
LTableGeometry* GetTableGeometry() { return mTableGeometry; }
virtual void GetImageCellBounds(
const STableCell& inCell,
JRect& outRect) const;
virtual void GetImageCellBounds(
const STableCell& inCell,
SInt32& outLeft,
SInt32& outTop,
SInt32& outRight,
SInt32& outBottom) const;
virtual bool GetLocalCellRect(
const STableCell& inCell,
JRect& outCellFrame) const;
virtual bool GetCellHitBy(
const JPoint& inImagePt,
STableCell& outCell) const;
virtual UInt16 GetRowHeight( TableIndexT inRow ) const;
virtual void SetRowHeight(
UInt16 inHeight,
TableIndexT inFromRow,
TableIndexT inToRow);
virtual UInt16 GetColWidth( TableIndexT inCol ) const;
virtual void SetColWidth(
UInt16 inWidth,
TableIndexT inFromCol,
TableIndexT inToCol);
virtual void FetchIntersectingCells(
const JRect& inLocalRect,
STableCell& outTopLeft,
STableCell& outBotRight) const;
UInt16 GetVisibleRows() const;
// Selecting Cells
virtual void SetTableSelector( LTableSelector* inTableSelector );
LTableSelector* GetTableSelector() { return mTableSelector; }
virtual bool CellIsSelected( const STableCell& inCell ) const;
virtual void SelectCell( const STableCell& inCell );
virtual void SelectAllCells();
virtual void UnselectCell( const STableCell& inCell );
virtual void UnselectAllCells();
virtual bool ClickSelect(
const STableCell& inCell,
const JXKeyModifiers& modifiers);
virtual void HiliteSelection(
bool inActively,
bool inHilite);
virtual void HiliteCell(
const STableCell& inCell,
bool inHilite);
virtual void SelectionChanged();
// Storing Data
virtual void SetTableStorage( LTableStorage* inTableStorage );
LTableStorage* GetTableStorage() { return mTableStorage; }
virtual void SetCellData(
const STableCell& inCell,
const void* inDataPtr,
UInt32 inDataSize);
virtual void GetCellData(
const STableCell& inCell,
void* outDataPtr,
UInt32& ioDataSize) const;
virtual bool FindCellData(
STableCell& outCell,
const void* inDataPtr,
UInt32 inDataSize) const;
// Refreshing
virtual void RefreshCell( const STableCell& inCell );
virtual void RefreshCellRange(
const STableCell& inTopLeft,
const STableCell& inBotRight);
protected:
enum DragType
{
kInvalidDrag,
kWaitForDNDDrag,
kSelectDrag
};
TableIndexT mRows;
TableIndexT mCols;
LTableGeometry *mTableGeometry;
LTableSelector *mTableSelector;
LTableStorage *mTableStorage;
bool mUseDragSelect;
bool mDeferAdjustment;
JPoint mDragStartPoint;
DragType mDragType;
// Hiliting
virtual void HiliteCellActively(
const STableCell& inCell,
bool inHilite);
virtual void HiliteCellInactively(
const STableCell& inCell,
bool inHilite);
// Clicking
virtual void HandleMouseDown(const JPoint& pt,
const JXMouseButton button,
const JSize clickCount,
const JXButtonStates& buttonStates,
const JXKeyModifiers& modifiers);
virtual void HandleMouseDrag(const JPoint& pt,
const JXButtonStates& buttonStates,
const JXKeyModifiers& modifiers);
virtual void HandleMouseUp(const JPoint& pt,
const JXMouseButton button,
const JXButtonStates& buttonStates,
const JXKeyModifiers& modifiers);
virtual void LClickCell(const STableCell& inCell,
const JXKeyModifiers& modifiers);
virtual void LDblClickCell(const STableCell& inCell,
const JXKeyModifiers& modifiers);
virtual void RClickCell(const STableCell& inCell,
const JXKeyModifiers& modifiers);
// Key board
virtual void HandleKeyPress(const int key, const JXKeyModifiers& modifiers);
virtual bool HandleChar(const int key, const JXKeyModifiers& modifiers);
// Drawing
virtual void Draw(JXWindowPainter& p, const JRect& rect);
virtual void DrawCellRange(JPainter* pDC,
const STableCell& inTopLeftCell,
const STableCell& inBottomRightCell);
virtual void DrawCell(JPainter* pDC,
const STableCell& inCell,
const JRect& inLocalRect);
virtual bool DrawCellSelection(JPainter* pDC,
const STableCell& inCell);
virtual void DrawBackground(JXWindowPainter& pDC, const JRect& inLocalRect);
private:
void InitTable();
};
// ---------------------------------------------------------------------------
class StDeferTableAdjustment {
public:
StDeferTableAdjustment( LTableView* inTable );
~StDeferTableAdjustment();
private:
LTableView* mTable;
bool mSaveDefer;
};
#endif
| 26.458462 | 78 | 0.659379 | [
"geometry"
] |
278fc43f92b7e4956266be73be9ed48da6672bde | 5,117 | h | C | include/xspf/XspfDateTime.h | ezdev128/libxspf | ba71431e24293510c44d6581e2c05b901a372880 | [
"BSD-3-Clause"
] | null | null | null | include/xspf/XspfDateTime.h | ezdev128/libxspf | ba71431e24293510c44d6581e2c05b901a372880 | [
"BSD-3-Clause"
] | null | null | null | include/xspf/XspfDateTime.h | ezdev128/libxspf | ba71431e24293510c44d6581e2c05b901a372880 | [
"BSD-3-Clause"
] | null | null | null | /*
* libxspf - XSPF playlist handling library
*
* Copyright (C) 2006-2008, Sebastian Pipping / Xiph.Org Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* * Neither the name of the Xiph.Org Foundation 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.
*
* Sebastian Pipping, sping@xiph.org
*/
/**
* @file XspfDateTime.h
* Interface of XspfDateTime.
*/
#ifndef XSPF_DATE_TIME_H
#define XSPF_DATE_TIME_H
#include "XspfDefines.h"
namespace Xspf {
class XspfDateTimePrivate;
/**
* Represents a "dateTime" timestamp
* without fractional second component.
*/
class XspfDateTime {
private:
/// @cond DOXYGEN_NON_API
XspfDateTimePrivate * const d; ///< D pointer
/// @endcond
public:
/**
* Creates a new dateTime timestamp.
* The given parameters must be valid and are not
* checked for validity inside.
*
* @param year Year [-9999..+9999] but not zero
* @param month Month [1..12]
* @param day Day [1..31]
* @param hour Hour [0..23]
* @param minutes Minutes [0..59]
* @param seconds Seconds [0..59]
* @param distHours Time shift hours [-14..+14]
* @param distMinutes Time shift minutes [-59..+59]
*/
XspfDateTime(int year, int month, int day, int hour, int minutes,
int seconds, int distHours, int distMinutes);
/**
* Creates a new dateTime timestamp.
*/
XspfDateTime();
/**
* Copy constructor.
*
* @param source Source to copy from
*/
XspfDateTime(XspfDateTime const & source);
/**
* Assignment operator.
*
* @param source Source to copy from
*/
XspfDateTime & operator=(XspfDateTime const & source);
/**
* Destroys this dateTime timestamp.
*/
~XspfDateTime();
/**
* Clones this dateTime object.
*
*`@return Cloned object
*/
XspfDateTime * clone() const;
/**
* Returns the year.
*
* @return Year
*/
int getYear() const;
/**
* Returns the month.
*
* @return Month
*/
int getMonth() const;
/**
* Returns the day.
*
* @return Day
*/
int getDay() const;
/**
* Returns the hour.
*
* @return Hour
*/
int getHour() const;
/**
* Returns the minutes.
*
* @return Minutes
*/
int getMinutes() const;
/**
* Returns the seconds.
*
* @return Seconds
*/
int getSeconds() const;
/**
* Returns the time shift hours.
*
* @return Time shift hours
*/
int getDistHours() const;
/**
* Returns the time shift minutes.
*
* @return Time shift minutes
*/
int getDistMinutes() const;
/**
* Sets the year.
*
* @param year Year to set
*/
void setYear(int year);
/**
* Sets the month.
*
* @param month Month to set
*/
void setMonth(int month);
/**
* Sets the day.
*
* @param day Day to set
*/
void setDay(int day);
/**
* Sets the hour.
*
* @param hour Hour to set
*/
void setHour(int hour);
/**
* Sets the minutes.
*
* @param minutes Minutes to set
*/
void setMinutes(int minutes);
/**
* Sets the seconds.
*
* @param seconds Seconds to set
*/
void setSeconds(int seconds);
/**
* Sets the time shift hours.
*
* @param distHours Time shift hours
*/
void setDistHours(int distHours);
/**
* Sets the time shift minutes.
*
* @param distMinutes Time shift minutes
*/
void setDistMinutes(int distMinutes);
/**
* Extracts a dateTime from <c>text</c>.
*
* @param text Text
* @param output dateTime storage destination
* @return Valid dateTime flag
* @since 1.0.0rc1
*/
static bool extractDateTime(XML_Char const * text,
XspfDateTime * output);
};
} // namespace Xspf
#endif // XSPF_DATE_TIME_H
| 20.716599 | 70 | 0.650967 | [
"object"
] |
27a1b89206c54fb91367c23774a105c0e805f8c7 | 2,081 | h | C | dependencies/panda/Panda3D-1.10.0-x64/include/cppSimpleType.h | CrankySupertoon01/Toontown-2 | 60893d104528a8e7eb4aced5d0015f22e203466d | [
"MIT"
] | 3 | 2018-03-09T12:07:29.000Z | 2021-02-25T06:50:25.000Z | dtool/src/cppparser/cppSimpleType.h | Sinkay/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | 1 | 2018-07-28T20:07:04.000Z | 2018-07-30T18:28:34.000Z | dtool/src/cppparser/cppSimpleType.h | Sinkay/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | 2 | 2019-12-02T01:39:10.000Z | 2021-02-13T22:41:00.000Z | // Filename: cppSimpleType.h
// Created by: drose (19Oct99)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#ifndef CPPSIMPLETYPE_H
#define CPPSIMPLETYPE_H
#include "dtoolbase.h"
#include "cppType.h"
///////////////////////////////////////////////////////////////////
// Class : CPPSimpleType
// Description :
////////////////////////////////////////////////////////////////////
class CPPSimpleType : public CPPType {
public:
enum Type {
T_unknown,
T_bool,
T_char,
T_wchar_t,
T_char16_t,
T_char32_t,
T_int,
T_float,
T_double,
T_void,
// T_parameter is a special type which is assigned to expressions
// that are discovered where a formal parameter was expected.
// This is a special case for handling cases like this:
//
// int foo(0);
//
// which really means the same thing as:
//
// int foo = 0;
//
// but it initially looks like a function prototype.
//
T_parameter,
};
enum Flags {
F_long = 0x001,
F_longlong = 0x002,
F_short = 0x004,
F_unsigned = 0x008,
F_signed = 0x010,
};
CPPSimpleType(Type type, int flags = 0);
Type _type;
int _flags;
virtual bool is_tbd() const;
virtual bool is_trivial() const;
virtual bool is_parameter_expr() const;
virtual string get_preferred_name() const;
virtual void output(ostream &out, int indent_level, CPPScope *scope,
bool complete) const;
virtual SubType get_subtype() const;
virtual CPPSimpleType *as_simple_type();
protected:
virtual bool is_equal(const CPPDeclaration *other) const;
virtual bool is_less(const CPPDeclaration *other) const;
};
#endif
| 24.197674 | 70 | 0.576646 | [
"3d"
] |
27a962ec9608845690098e2acc88c6443524a8a7 | 1,402 | h | C | EventAnalyzer/interface/EventVariableMatrixWeights2D.h | peterthomassen/RutgersIAF | 50fd20b79b8bce30478d49e1ce7c763424e094f1 | [
"MIT"
] | null | null | null | EventAnalyzer/interface/EventVariableMatrixWeights2D.h | peterthomassen/RutgersIAF | 50fd20b79b8bce30478d49e1ce7c763424e094f1 | [
"MIT"
] | null | null | null | EventAnalyzer/interface/EventVariableMatrixWeights2D.h | peterthomassen/RutgersIAF | 50fd20b79b8bce30478d49e1ce7c763424e094f1 | [
"MIT"
] | null | null | null | #ifndef EventVariableMatrixWeights2D_h
#define EventVariableMatrixWeights2D_h
#include <vector>
#include "TLorentzVector.h"
#include "RutgersIAF/EventAnalyzer/interface/EventVariable.h"
class EventVariableMatrixWeights2D : public EventVariable{
public:
EventVariableMatrixWeights2D(TString name, TString productname, TString suffix, TString loosename, TString tightname) : EventVariable(name), m_suffix(suffix), m_loosename(loosename), m_tightname(tightname) {m_productnames.push_back(productname);}
void addProduct(TString);
bool calculate(BaseHandler*);
void ResetFakePromptRates();
void ResetLooseTight();
void SetFakePromptRates(TLorentzVector, TLorentzVector, int array[2], TString);
void setVariablesToZero(BaseHandler*);
float mP( float, float, float, TString );
float mF( float, float, float, TString );
float eP( float, float, float, TString );
float eF( float, float, float, TString );
float tP( float, float, float, TString );
float tF( float, float, float, TString );
float p1, p2;
float f1, f2;
float nLL;
float nLT;
float nTL;
float nTT;
//double fake
float Wff();
//single fake
float Wfp();
float Wpf();
//zero fake
float Wpp();
float WfakeBckg();
ClassDef(EventVariableMatrixWeights2D,1);
private:
TString m_suffix;
TString m_loosename;
TString m_tightname;
std::vector<TString> m_productnames;
};
#endif
| 23.762712 | 247 | 0.741797 | [
"vector"
] |
27aeac334b70785eff3b15457b07333fc9103251 | 3,098 | h | C | ArduinoPartsLed.h | scls19fr/ArduinoPartsPushButton | a4f8de17e5cf471aabbb07261f0abf0232e79c67 | [
"MIT"
] | null | null | null | ArduinoPartsLed.h | scls19fr/ArduinoPartsPushButton | a4f8de17e5cf471aabbb07261f0abf0232e79c67 | [
"MIT"
] | 1 | 2019-01-23T17:35:58.000Z | 2019-01-23T17:35:58.000Z | ArduinoPartsLed.h | scls19fr/ArduinoPartsPushButton | a4f8de17e5cf471aabbb07261f0abf0232e79c67 | [
"MIT"
] | null | null | null | /*!\file ArduinoPartsLed.h
** \author Sébastien Celles
** \date 2019/01/23
** \copyright MIT License (c) 2019, Sébastien Celles
** \brief Led handling library.
** \details Led handling library.
** This library was designed for Arduino boards
**/
#ifndef ARDUINO_PARTS_LED
#define ARDUINO_PARTS_LED
#include <Arduino.h>
/*! \brief Default lit state (true)
**/
#define LED_LIT_STATE_DEFAULT true
/*! \brief Light emitting diode
**/
class Led {
public:
/*! \brief Led constructor
** \param [in] pin - The Arduino pin the led is connected to
** \param [in] lit_state - false to turn on led by bringing cathode to low state. (default true)
** \return nothing
**/
Led(uint8_t pin, uint8_t lit_state=LED_LIT_STATE_DEFAULT)
: m_pin(pin), m_lit_state(lit_state) {}
/*! \brief Initialize a PushButton object
** \warning The pin it's connected to is also initialized
**/
void begin(uint32_t ms);
/*! \brief Switch on led
**/
void on();
/*! \brief Switch off led
**/
void off();
/*! \brief Toggle led
**/
void toggle();
/*! \brief Switch on or off led according state
** \param [in] state - state=false (off) state=true (on)
**/
void lit(bool state);
/*! \brief Get led state (on or off)
** \retval true if the led is on
** \retval false if the led is off
**/
bool isLit();
/*! \brief Set physically Led state according internal state
**/
void update(uint32_t ms);
private:
uint8_t m_pin; //!< arduino pin number connected to led
bool m_lit_state; //!< if true, interpret logic low as pressed, else interpret logic high as pressed
bool m_state; //!< current led state, true=led on false=led off
};
/*! \brief Blink task
**/
class BlinkTask {
public:
/*! \brief BlinkTask constructor
**/
BlinkTask(const Led &led)
: m_led(led), m_initial_lit_state(false),
m_active(false), m_stop_request(false),
m_times(0), m_times_remaining(0), m_forever(false),
m_on_delay(0), m_off_delay(0),
m_ms(0), m_next_ms(0) {}
/*! \brief Initialize a BlinkTask object
**/
void begin(uint32_t ms);
/*! \brief Start blinking a given number of times
**/
void start(uint8_t times, uint32_t on_delay, uint32_t off_delay);
/*! \brief Start blinking forever
**/
void start(uint32_t on_delay, uint32_t off_delay);
/*! \brief Stop blinking
**/
void stop();
/*! \return true if task is active
**/
bool isActive();
/*! \brief Update BlinkTask
**/
void update(uint32_t ms);
private:
Led m_led;
bool m_initial_lit_state;
bool m_active; //!< active state
bool m_stop_request; //!< stop request
uint8_t m_times; //!< number of times it should blink
uint8_t m_times_remaining; //!< number of times it should blink
bool m_forever; //!< blinking state
uint32_t m_on_delay;
uint32_t m_off_delay;
uint32_t m_ms;
uint32_t m_next_ms;
void schedule(uint32_t ms);
};
#endif
| 24.393701 | 106 | 0.630407 | [
"object"
] |
27b083adac858acc349d7e399a793c0c295e27d4 | 1,285 | h | C | Engine/Common/CommonMath.h | hhyyrylainen/Leviathan | 0a0d2ea004a153f9b17c6230da029e8160716f71 | [
"BSL-1.0"
] | 16 | 2018-12-22T02:09:05.000Z | 2022-03-09T20:38:59.000Z | Engine/Common/CommonMath.h | hhyyrylainen/Leviathan | 0a0d2ea004a153f9b17c6230da029e8160716f71 | [
"BSL-1.0"
] | 46 | 2018-04-02T11:06:01.000Z | 2019-12-14T11:16:04.000Z | Engine/Common/CommonMath.h | hhyyrylainen/Leviathan | 0a0d2ea004a153f9b17c6230da029e8160716f71 | [
"BSL-1.0"
] | 14 | 2018-04-09T02:26:15.000Z | 2021-09-11T03:12:15.000Z | // Leviathan Game Engine
// Copyright (c) 2012-2018 Henri Hyyryläinen
#pragma once
// ------------------------------------ //
#include "Types.h"
#include <cmath>
#include <vector>
namespace Leviathan { namespace MMath {
DLLEXPORT float CoordinateDistance(float x1, float x2, float y1, float y2);
DLLEXPORT double AngleBetweenPoints(float x1, float x2, float y1, float y2);
DLLEXPORT bool IsPointInsidePolygon(const std::vector<Float3>& polygon, const Float3& point);
//! greatest common divisor, courtesy of Wikipedia
DLLEXPORT int GreatestCommonDivisor(int a, int b);
//! calculates a normal for triangle and returns in normalized //
DLLEXPORT Float3 CalculateNormal(const Float3& p1, const Float3& p2, const Float3& p3);
/*--------------------------------------
Original Function written by Philip J. Erdelsky October 25, 2001 (revised August 22, 2002)
Code Edited by Henri Hyyryläinen
This function uses Fermat's Theorem 100 times to test the primeness of a
(large) positive integer.
----------------------------------------------------------------------------*/
// DLLEXPORT bool IsPrime(const mpuint &p);
// float and double comparison (with EPSILON)
DLLEXPORT bool IsEqual(double x, double y);
DLLEXPORT bool IsEqual(float x, float y);
}} // namespace Leviathan::MMath
| 34.72973 | 93 | 0.673152 | [
"vector"
] |
27b56385f1a10c5cfc611a13e9079855ae6966bf | 2,049 | h | C | src/lib/file/stringutil.h | stutiredboy/obproxy | b5f98a6e1c45e6a878376df49b9c10b4249d3626 | [
"Apache-2.0"
] | 74 | 2021-05-31T15:23:49.000Z | 2022-03-12T04:46:39.000Z | src/lib/file/stringutil.h | stutiredboy/obproxy | b5f98a6e1c45e6a878376df49b9c10b4249d3626 | [
"Apache-2.0"
] | 16 | 2021-05-31T15:26:38.000Z | 2022-03-30T06:02:43.000Z | src/lib/file/stringutil.h | stutiredboy/obproxy | b5f98a6e1c45e6a878376df49b9c10b4249d3626 | [
"Apache-2.0"
] | 64 | 2021-05-31T15:25:36.000Z | 2022-02-23T08:43:58.000Z | /**
* Copyright (c) 2021 OceanBase
* OceanBase Database Proxy(ODP) is licensed under Mulan PubL v2.
* You can use this software according to the terms and conditions of the Mulan PubL v2.
* You may obtain a copy of Mulan PubL v2 at:
* http://license.coscl.org.cn/MulanPubL-2.0
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PubL v2 for more details.
*/
#ifndef TBSYS_STRINGUTIL_H
#define TBSYS_STRINGUTIL_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <time.h>
#include <vector>
//using namespace std;
namespace obsys {
/**
* @brief String manipulation, and the encapsulation of conversion
*/
class CStringUtil {
public:
// Convert string to int
static int strToInt(const char *str, int d);
// Is an integer
static int isInt(const char *str);
// Convert to lowercase
static char *strToLower(char *str);
// Convert to uppercase
static char *strToUpper(char *str);
// trim
static char *trim(char *str, const char *what = " ", int mode = 3);
// hash_value
static int hashCode(const char *str);
// Get the prime number of the hash value of a str
static int getPrimeHash(const char *str);
// Separate the string with delim and put it in the list
static void split(char *str, const char *delim, std::vector<char*> &list);
// urldecode
static char *urlDecode(const char *src, char *dest);
// http://murmurhash.googlepages.com/
static unsigned int murMurHash(const void *key, int len);
// Convert bytes into readable, such as 10K 12M, etc.
static std::string formatByteSize(double bytes);
};
}
#endif
///////////////////END
| 34.728814 | 88 | 0.620791 | [
"vector"
] |
27bb7071b53671d699f400a3cbe3feecd3cff33f | 2,214 | h | C | net/ias/iasjet/setup/stdafx.h | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | net/ias/iasjet/setup/stdafx.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | net/ias/iasjet/setup/stdafx.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /////////////////////////////////////////////////////////////////////////////
//
// Copyright(C) 2000 Microsoft Corporation all rights reserved.
//
// Module: stdafx.h
//
// Project: Windows 2000 IAS
//
// Description:
// include file for standard system include files,
// or project specific include files that are used frequently,
// but are changed infrequently
//
// Author: tperraut
//
// Revision 02/24/2000 created
//
/////////////////////////////////////////////////////////////////////////////
#ifndef _STDAFX_H_64176C8B_CC9E_4A96_8997_47FA8A21C843
#define _STDAFX_H_64176C8B_CC9E_4A96_8997_47FA8A21C843
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#define STRICT
#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0500
#endif
#define _ATL_APARTMENT_THREADED
#ifndef _UNICODE
#define _UNICODE
#endif
#ifndef UNICODE
#define UNICODE
#endif
#pragma warning( push )
#pragma warning( disable : 4700 ) // variable not initialized
#include <atlbase.h>
extern CComModule _Module;
#include <atlcom.h>
#include "atldb.h"
#pragma warning( pop )
#include <comutil.h>
#include <comdef.h>
#include <crtdbg.h>
#include <wchar.h>
#include <new>
#include <memory>
// next line for the constants like IAS_SYNTAX_OCTETSTRING, IAS_LOGGING_DAILY
#include "sdoias.h"
#include "nocopy.h"
#include "utils.h"
// to improve building times:
#include <map>
#include <vector>
#include "Attributes.h"
#include "basetable.h"
#include "basecommand.h"
#include "Clients.h"
#include "datastore2.h"
#include "DefaultProvider.h"
#include "doupgrade.h"
#include "GlobalData.h"
#include "Objects.h"
#include "migratemdb.h"
#include "migrateregistry.h"
#include "nocopy.h"
#include "Properties.h"
#include "profileattributelist.h"
#include "Profiles.h"
#include "Providers.h"
#include "proxyservergroupcollection.h"
#include "proxyserversgrouphelper.h"
#include "ProxyServerHelper.h"
#include "RadiusAttributeValues.h"
#include "Realms.h"
#include "RemoteRadiusServers.h"
#include "ServiceConfiguration.h"
#include "Version.h"
#endif // _STDAFX_H_64176C8B_CC9E_4A96_8997_47FA8A21C843
| 22.591837 | 78 | 0.663053 | [
"vector"
] |
27d2b4d4a248587b19f24258bf4aa8742292d2ed | 1,219 | h | C | src/genetic_algorithm_operators.h | jfrfonseca/kcmc_heuristic | 92b45a3570f26efe2e1813e5c0683b5555be4785 | [
"MIT"
] | null | null | null | src/genetic_algorithm_operators.h | jfrfonseca/kcmc_heuristic | 92b45a3570f26efe2e1813e5c0683b5555be4785 | [
"MIT"
] | null | null | null | src/genetic_algorithm_operators.h | jfrfonseca/kcmc_heuristic | 92b45a3570f26efe2e1813e5c0683b5555be4785 | [
"MIT"
] | null | null | null | /*
* Genetic algorithm operators
* Set of Genetic Algorithm operators that can be used in many configurations of the algorithm
* Many are used in our implementation of Gupta's Genetic Algorithm for the KCMC Problem
*/
#include <cstdlib> // rand
#include <numeric> // accumulate
#include <algorithm> // copy, fill
// Dependencies from this package
#include "kcmc_instance.h"
#ifndef GENETIC_ALGORITHM_OPERATORS_H
#define GENETIC_ALGORITHM_OPERATORS_H
void exit_signal_handler(int signal);
int get_best_individual(int interval, std::unordered_set<int> *unused_sensors, int chromo_size, int pop_size,
int **population, double *fitness, int num_generation, int previous_best);
int individual_creation(float one_bias, int size, int chromo[]);
bool inspect_individual(int size, int *individual);
bool inspect_population(int pop_size, int size, int **population);
int selection_roulette(int sel_size, std::vector<int> *selection, int pop_size, double *fitness);
int selection_get_one(int sel_size, std::vector<int> selection, int avoid);
int crossover_single_point(int size, int *chromo_a, int *chromo_b, int output[]);
int mutation_random_bit_flip(int size, int chromo[]);
#endif
| 35.852941 | 109 | 0.765381 | [
"vector"
] |
27dd7981ae09a26e9a4d6635048ae97c3eb80c1a | 2,785 | h | C | RXVerifyExample/RXVerifyExample/RXPersonal/RXAFNetworking/Serialization/RXAFURLResponseSerialization.h | Explorer1092/RXVerifyExample | 344f954c155457c34d52db6831f928b5ac400bbc | [
"MIT"
] | null | null | null | RXVerifyExample/RXVerifyExample/RXPersonal/RXAFNetworking/Serialization/RXAFURLResponseSerialization.h | Explorer1092/RXVerifyExample | 344f954c155457c34d52db6831f928b5ac400bbc | [
"MIT"
] | null | null | null | RXVerifyExample/RXVerifyExample/RXPersonal/RXAFNetworking/Serialization/RXAFURLResponseSerialization.h | Explorer1092/RXVerifyExample | 344f954c155457c34d52db6831f928b5ac400bbc | [
"MIT"
] | null | null | null | //
// RXAFURLResponseSerialization.h
// RXVerifyExample
//
// Created by Rush.D.Xzj on 2018/12/14.
// Copyright © 2018 Rush.D.Xzj. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
///----------------
/// @name Constants
///----------------
/**
## Error Domains
The following error domain is predefined.
- `NSString * const AFURLResponseSerializationErrorDomain`
### Constants
`AFURLResponseSerializationErrorDomain`
AFURLResponseSerializer errors. Error codes for `AFURLResponseSerializationErrorDomain` correspond to codes in `NSURLErrorDomain`.
*/
FOUNDATION_EXPORT NSString * const RXAFURLResponseSerializationErrorDomain;
/**
## User info dictionary keys
These keys may exist in the user info dictionary, in addition to those defined for NSError.
- `NSString * const AFNetworkingOperationFailingURLResponseErrorKey`
- `NSString * const AFNetworkingOperationFailingURLResponseDataErrorKey`
### Constants
`AFNetworkingOperationFailingURLResponseErrorKey`
The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`.
`AFNetworkingOperationFailingURLResponseDataErrorKey`
The corresponding value is an `NSData` containing the original data of the operation associated with an error. This key is only present in the `AFURLResponseSerializationErrorDomain`.
*/
FOUNDATION_EXPORT NSString * const RXAFNetworkingOperationFailingURLResponseErrorKey;
FOUNDATION_EXPORT NSString * const RXAFNetworkingOperationFailingURLResponseDataErrorKey;
/**
The `AFURLResponseSerialization` protocol is adopted by an object that decodes data into a more useful object representation, according to details in the server response. Response serializers may additionally perform validation on the incoming response and data.
For example, a JSON response serializer may check for an acceptable status code (`2XX` range) and content type (`application/json`), decoding a valid JSON response into an object.
*/
@protocol RXAFURLResponseSerialization <NSObject, NSSecureCoding, NSCopying>
/**
The response object decoded from the data associated with a specified response.
@param response The response to be processed.
@param data The response data to be decoded.
@param error The error that occurred while attempting to decode the response data.
@return The object decoded from the specified response data.
*/
- (nullable id)responseObjectForResponse:(nullable NSURLResponse *)response
data:(nullable NSData *)data
error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW;
@end
NS_ASSUME_NONNULL_END
| 34.382716 | 263 | 0.771993 | [
"object"
] |
27ded2a5ec049136cab334c71448d5fbd6b9b92b | 18,681 | h | C | lib/tx/include/monsoon/tx/detail/wal.h | nahratzah/monsoon_plus_plus | 789082078f1d474d38056518f66613ed1319181b | [
"BSD-2-Clause"
] | 1 | 2018-03-06T11:15:40.000Z | 2018-03-06T11:15:40.000Z | lib/tx/include/monsoon/tx/detail/wal.h | nahratzah/monsoon_plus_plus | 789082078f1d474d38056518f66613ed1319181b | [
"BSD-2-Clause"
] | null | null | null | lib/tx/include/monsoon/tx/detail/wal.h | nahratzah/monsoon_plus_plus | 789082078f1d474d38056518f66613ed1319181b | [
"BSD-2-Clause"
] | null | null | null | #ifndef MONSOON_TX_DETAIL_WAL_H
#define MONSOON_TX_DETAIL_WAL_H
#include <monsoon/tx/detail/export_.h>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <queue>
#include <shared_mutex>
#include <stdexcept>
#include <string>
#include <vector>
#include <monsoon/io/fd.h>
#include <monsoon/io/stream.h>
#include <monsoon/xdr/xdr.h>
#include <monsoon/tx/detail/replacement_map.h>
#include <instrumentation/counter.h>
namespace monsoon::tx::detail {
/**
* \brief Exception for Write-Ahead-Log.
* \details
* This error indicates that the WAL encountered an unrecoverable error.
* When encountered, the WAL becomes unusable.
*/
class monsoon_tx_export_ wal_error
: public std::runtime_error
{
public:
using std::runtime_error::runtime_error;
~wal_error();
};
/**
* \brief Exception for Write-Ahead-Log being filled.
* \details
* This error indicates a write to the WAL failed, due to the WAL having
* no more space to write log entries.
*/
class monsoon_tx_export_ wal_bad_alloc
: public wal_error
{
public:
using wal_error::wal_error;
~wal_bad_alloc();
};
class wal_region;
///\brief Types of WAL entries.
enum class wal_entry : std::uint8_t {
end = 0, ///<\brief End of WAL segment.
commit = 1, ///<\brief Transaction commit.
write = 10, ///<\brief Write operation that is part of a transaction.
resize = 11 ///<\brief File resize operation that is part of a transaction.
};
/**
* \brief Entry in the WAL.
* \details
* WAL records describe a single operation.
*/
class monsoon_tx_export_ wal_record {
public:
///\brief Type of transaction IDs.
using tx_id_type = std::uint32_t;
///\brief Mask for transaction IDs.
///\details Transactions are encoded as part of the WAL record type, using the high 24 bit.
static constexpr tx_id_type tx_id_mask = 0xffffffu;
wal_record() = delete;
///\brief Construct a WAL record with the given transaction ID.
wal_record(tx_id_type tx_id);
///\brief Destructor.
virtual ~wal_record() noexcept;
///\brief Return the WAL entry type.
virtual auto get_wal_entry() const noexcept -> wal_entry = 0;
private:
///\brief Write this record to an XDR stream.
virtual auto do_write(monsoon::xdr::xdr_ostream& out) const -> void = 0;
///\brief Apply the operation described in this WAL record.
virtual auto do_apply(wal_region& wal) const -> void = 0;
public:
///\brief Read a WAL record from an XDR stream.
static auto read(monsoon::xdr::xdr_istream& in) -> std::unique_ptr<wal_record>;
///\brief Write this recod to an XDR stream.
void write(monsoon::xdr::xdr_ostream& out) const;
///\brief Raw operation that writes a header for an entry.
static void to_stream(monsoon::xdr::xdr_ostream& out, wal_entry e, tx_id_type tx_id);
///\brief Apply the operation described in this WAL record.
void apply(wal_region& wal) const;
///\brief Test if this WAL record denotes the end of a WAL segment.
auto is_end() const noexcept -> bool;
///\brief Test if this WAL record indicates a transaction commit.
auto is_commit() const noexcept -> bool;
///\brief Test if this WAL record is a control record.
auto is_control_record() const noexcept -> bool;
///\brief Retrieve the transaction ID of this WAL record.
auto tx_id() const noexcept -> std::uint32_t { return tx_id_; }
///\brief Create a record describing the end of a WAL segment.
static auto make_end() -> std::unique_ptr<wal_record>;
///\brief Create a record describing a transaction commit.
///\params[in] tx_id The transaction ID.
static auto make_commit(tx_id_type tx_id) -> std::unique_ptr<wal_record>;
///\brief Create a record that describes a write operation.
///\params[in] tx_id The transaction ID.
///\params[in] offset The position at which the write happens.
///\params[in] data The data that is to be written.
static auto make_write(tx_id_type tx_id, std::uint64_t offset, std::vector<std::uint8_t>&& data) -> std::unique_ptr<wal_record>;
///\brief Create a record that describes a write operation.
///\params[in] tx_id The transaction ID.
///\params[in] offset The position at which the write happens.
///\params[in] data The data that is to be written.
static auto make_write(tx_id_type tx_id, std::uint64_t offset, const std::vector<std::uint8_t>& data) -> std::unique_ptr<wal_record>;
///\brief Create a record indicating the file is being resized.
///\params[in] tx_id The transaction ID.
///\params[in] new_size The new size of the file.
static auto make_resize(tx_id_type tx_id, std::uint64_t new_size) -> std::unique_ptr<wal_record>;
private:
///\brief The transaction ID of the record.
tx_id_type tx_id_;
};
class wal_record_end;
class wal_record_commit;
class wal_record_write;
class wal_record_resize;
/**
* \brief A WAL region in a file.
* \details
* The WAL region handles the logistics of making a file appear transactional.
*/
class monsoon_tx_export_ wal_region {
friend wal_record_write;
friend wal_record_resize;
private:
struct wal_header;
public:
///\brief Constructor tag signaling a newly created file.
struct create {};
class tx;
private:
///\brief WAL segment sequence number type.
using wal_seqno_type = std::uint32_t;
///\brief A WAL segment.
///\details This type holds information during transaction replay.
struct wal_vector {
///\brief Slot index.
std::size_t slot;
///\brief WAL segment sequence number.
wal_seqno_type seq;
///\brief Size of the file at the start of the segment.
monsoon::io::fd::size_type file_size;
///\brief Records in the WAL segment.
std::vector<std::unique_ptr<wal_record>> data;
};
public:
wal_region() = delete;
///\brief Create a WAL region from an existing file.
///\param[in] name A name used for instrumentation.
///\param[in] fd The file in which to open the region.
///\param[in] off The offset in the file at which the WAL was created.
///\param[in] len The size of the WAL.
wal_region(std::string name, monsoon::io::fd&& fd, monsoon::io::fd::offset_type off, monsoon::io::fd::size_type len);
///\brief Create a WAL region from a newly initialized file.
///\param[in] name A name used for instrumentation.
///\param[in] c A tag type to distinguish between the constructors.
///\param[in] fd The file in which to open the region.
///\param[in] off The offset in the file at which to create the WAL.
///\param[in] len The size of the WAL.
wal_region(std::string name, create c, monsoon::io::fd&& fd, monsoon::io::fd::offset_type off, monsoon::io::fd::size_type len);
wal_region(wal_region&&) noexcept = delete;
wal_region(const wal_region&) = delete;
wal_region& operator=(wal_region&&) noexcept = delete;
wal_region& operator=(const wal_region&) = delete;
~wal_region() = default;
///\brief Retrieve the end of the WAL region.
auto wal_end_offset() const noexcept -> monsoon::io::fd::offset_type {
return off_ + len_;
}
private:
///\brief Allocate a transaction ID.
[[nodiscard]]
auto allocate_tx_id() -> wal_record::tx_id_type;
///\brief Number of segments that the WAL is divided in.
static constexpr std::size_t num_segments_ = 2;
///\brief Length of the segments inside the WAL.
auto segment_len_() const noexcept -> monsoon::io::fd::size_type {
return segment_len_(len_);
}
///\brief Length of the segments inside the WAL.
static constexpr auto segment_len_(monsoon::io::fd::size_type len) noexcept -> monsoon::io::fd::size_type {
return len / num_segments_;
}
///\brief Retrieve the begin offset of a given segment.
///\param[in] slot The index of the slot for which to deduce the offset.
///\return The offset of the first byte of this slot.
auto slot_begin_off(std::size_t slot) const noexcept -> monsoon::io::fd::offset_type {
return off_ + slot * segment_len_();
}
///\brief Retrieve the end offset of a given segment.
///\param[in] slot The index of the slot for which to deduce the offset.
///\return The offset of the first past-the-end byte of this slot.
auto slot_end_off(std::size_t slot) const noexcept -> monsoon::io::fd::offset_type {
return slot_begin_off(slot) + segment_len_();
}
///\brief Read a WAL segment header.
///\param[in] fd The file descriptor.
///\param[in] idx The slot index of the segment to read.
auto read_segment_header_(std::size_t idx) const -> wal_header;
///\brief Read a WAL segment.
///\param[in] fd The file descriptor.
///\param[in] idx The slot index of the segment to read.
auto read_segment_(std::size_t idx) const -> wal_vector;
public:
auto fd() const & noexcept -> const monsoon::io::fd& {
return fd_;
}
auto fd() & noexcept -> monsoon::io::fd& {
return fd_;
}
auto fd() && -> monsoon::io::fd&& {
return std::move(fd_);
}
auto read_at(monsoon::io::fd::offset_type off, void* buf, std::size_t len) const -> std::size_t;
void compact();
auto size() const noexcept -> monsoon::io::fd::size_type;
private:
///\brief Read from the WAL log.
///\details Must be called with mtx_ held for share.
///\param[in] off File offset at which the read happens.
///\param[in] buf Buffer into which to read.
///\param[in] len The length of the read.
///\return The number of bytes read.
auto read_at_(monsoon::io::fd::offset_type off, void* buf, std::size_t len) const -> std::size_t;
///\brief Write a WAL record to the log.
///\param[in] r The record to write.
///This should only be set when copying into a new log, until the log is activated.
void log_write_(const wal_record& r);
///\brief Write a WAL record to the log, that is encoded in the given byte sequence.
///\param[in] xdr The raw bytes of zero or more WAL records, with a wal_record_end following it.
///This should only be set when copying into a new log, until the log is activated.
void log_write_raw_(const monsoon::xdr::xdr_bytevector_ostream<>& xdr);
/**
* \brief Compact the log.
* \details
* Reads the log, filters out all transactions that have completed,
* and writes it out again. This action compresses the log, making
* space available for writes.
*
* During compaction, all pending writes will be flushed out as well.
*/
void compact_();
///\brief Write a WAL record for a write to the log.
///\details This is equivalent to calling
///`log_write(wal_record_write(...))`.
///This method elides a copy operation of the buffer, making it a bit faster
///to execute.
///\param[in] tx_id The transaction ID of the write operation.
///\param[in] off The offset at which the write takes place.
///\param[in] buf The buffer holding the data that is to be written.
///\param[in] len The length of the buffer.
void tx_write_(wal_record::tx_id_type tx_id, monsoon::io::fd::offset_type off, const void* buf, std::size_t len);
///\brief Write a WAL record for a resize operation to the log.
///\param[in] tx_id The transaction ID of the write operation.
///\param[in] new_size The new file size.
void tx_resize_(wal_record::tx_id_type tx_id, monsoon::io::fd::size_type new_size);
///\brief Write a commit message to the log.
///\param[in] tx_id The transaction ID of the commit operation.
///\param[in] writes The writes done as part of this transaction.
///\param[in] new_file_size If present, a file size modification operation.
///\return A replacement_map recording for all replaced data in the file, what the before-commit contents was.
void tx_commit_(wal_record::tx_id_type tx_id, replacement_map&& writes, std::optional<monsoon::io::fd::size_type> new_file_size, std::function<void(replacement_map)> undo_op_fn);
///\brief Mark a transaction as canceled.
void tx_rollback_(wal_record::tx_id_type tx_id) noexcept;
///\brief Offset of the WAL.
const monsoon::io::fd::offset_type off_;
///\brief Length of the WAL.
const monsoon::io::fd::size_type len_;
///\brief WAL segment sequence number.
wal_seqno_type current_seq_;
///\brief Current WAL segment slot to which records are appended.
std::size_t current_slot_;
///\brief Append offset in the slot.
monsoon::io::fd::offset_type slot_off_;
///\brief Vector where tx_id is the index and bool indicates wether the transaction is in progress.
///\details A transaction that is in progress has been started, but has neither been committed, nor been rolled back.
std::vector<bool> tx_id_states_;
///\brief List of transaction IDs that are available for allocation.
///\details
///These IDs are all marked as inactive.
std::priority_queue<wal_record::tx_id_type, std::vector<wal_record::tx_id_type>, std::greater<wal_record::tx_id_type>> tx_id_avail_;
///\brief Number of completed transactions in tx_id_states_.
///\details
///This holds the value `std::count(tx_id_states_.cbegin(), tx_id_states_.cend(), false)`.
std::vector<bool>::size_type tx_id_completed_count_ = 0;
///\brief Mutex providing read/write access to the file, excluding the WAL.
///\details
///Parts of the file covered by repl_ are not protected with this mutex (but repl_ itself is).
///Instead, the log_mtx_ covers those sections.
///
///This mutex may not be locked with alloc_mtx_ held.
mutable std::shared_mutex mtx_;
///\brief Mutex providing access to the WAL.
///\details
///This mutex may not be locked with mtx_ or alloc_mtx_ held.
mutable std::mutex log_mtx_;
///\brief Mutex providing access to the allocator data.
///\details
///Protects tx_id_states_ and tx_id_avail_.
mutable std::mutex alloc_mtx_;
///\brief File descriptor.
monsoon::io::fd fd_;
///\brief Current size of the file.
monsoon::io::fd::size_type fd_size_;
///\brief Pending writes.
replacement_map repl_;
///\brief Instrumentation.
instrumentation::counter commit_count_, write_ops_, compactions_, file_flush_;
};
/**
* \brief Transaction for WAL region.
* \details
* A WAL transaction runs at read-committed isolation.
*/
class monsoon_tx_export_ wal_region::tx {
public:
tx() = default;
tx(const tx&) = delete;
tx(tx&&) noexcept = default;
tx& operator=(const tx&) = delete;
tx& operator=(tx&&) noexcept = default;
///\brief Start a new transaction.
tx(const std::shared_ptr<wal_region>& wal) noexcept;
///\brief Destructor.
~tx() noexcept;
///\brief Test if this transaction is active.
explicit operator bool() const noexcept;
///\brief Test if this transaction is invalid.
auto operator!() const noexcept -> bool {
return !this->operator bool();
}
///\brief Transactional write.
///\param[in] off The offset at which to write.
///\param[in] buf Buffer with data.
///\param[in] len The size of the buffer.
///\throws std::bad_weak_ptr if the transaction is invalid.
void write_at(monsoon::io::fd::offset_type off, const void* buf, std::size_t len);
///\brief Transactional resize operation.
///\details Allows for the file to grow or shrink.
///\param[in] new_size The new file size.
///\throws std::bad_weak_ptr if the transaction is invalid.
void resize(monsoon::io::fd::size_type new_size);
///\brief Commit this transaction.
///\param[in] undo_op_fn A callback that will accept the replacement_map with recorded overwritten data.
///\throws std::bad_weak_ptr if the transaction is invalid.
void commit(std::function<void(replacement_map)> undo_op_fn);
///\brief Commit this transaction.
///\throws std::bad_weak_ptr if the transaction is invalid.
void commit();
///\brief Rollback this transaction.
void rollback() noexcept;
///\brief Read operation.
///\details Performs a read.
///The data visible to the read operation is the set of committed transactions.
///
///The \p fn callback is invoked between reading the transaction-local information
///and the WAL-committed information.
///\param[in] off The file offset to read from.
///\param[out] buf The buffer to read data into.
///\param[in] len The size of the buffer.
///\param[in] fn An invokable that is to participate in the read_at operation.
///\return The number of bytes read.
///\throws std::bad_weak_ptr if the transaction is invalid.
template<typename IntermediateFn>
auto read_at(monsoon::io::fd::offset_type off, void* buf, std::size_t len, IntermediateFn&& fn) const -> std::size_t {
const auto wal = std::shared_ptr<wal_region>(wal_);
// If the transaction has an altered file size, apply it.
if (new_file_size_.has_value()) {
if (off >= *new_file_size_) return 0;
if (len > *new_file_size_ - off) len = *new_file_size_ - off;
}
// First, evaluate local writes.
{
const auto local_rlen = writes_.read_at(off, buf, len); // May update len.
if (local_rlen != 0u) return local_rlen;
}
// The callback and the WAL both are protected using the mtx_.
std::shared_lock<std::shared_mutex> lck{ wal->mtx_ };
// Second, evaluate callback read operation.
{
const auto fn_rlen = std::invoke(std::forward<IntermediateFn>(fn), off, buf, len); // May update len.
if (fn_rlen != 0u) return fn_rlen;
}
// Third, read directly from the WAL.
{
const auto wal_rlen = wal->read_at_(off, buf, len);
if (wal_rlen != 0u) return wal_rlen;
}
// If nothing can provide data, pretend the file is zero-filled.
if (new_file_size_.has_value()) {
std::fill_n(reinterpret_cast<std::uint8_t*>(buf), len, std::uint8_t(0u));
return len;
}
return 0;
}
///\brief Read operation.
///\details Performs a read.
///The data visible to the read operation is the set of committed transactions.
///\param[in] off The file offset to read from.
///\param[out] buf The buffer to read data into.
///\param[in] len The size of the buffer.
///\return The number of bytes read.
///\throws std::bad_weak_ptr if the transaction is invalid.
auto read_at(monsoon::io::fd::offset_type off, void* buf, std::size_t len) const -> std::size_t;
///\brief Get the size of the file.
///\return The size of the file.
///\throws std::bad_weak_ptr if the transaction is invalid.
auto size() const -> monsoon::io::fd::size_type;
private:
///\brief Reference to the WAL.
std::weak_ptr<wal_region> wal_;
///\brief Writes performed in this transaction.
replacement_map writes_;
///\brief Recorded change in file size.
std::optional<monsoon::io::fd::size_type> new_file_size_;
///\brief Internal transaction ID.
wal_record::tx_id_type tx_id_;
};
} /* namespace monsoon::tx::detail */
#endif /* MONSOON_TX_DETAIL_WAL_H */
| 37.892495 | 180 | 0.704566 | [
"vector"
] |
27df33a11db69ce721f6bed4398b303230a10d0e | 8,432 | h | C | OrbitCore/Pdb.h | robbiesri/orbitprofiler | fff73e9cafc4e7928feb900f07b1dddb4af0ecee | [
"BSD-2-Clause"
] | null | null | null | OrbitCore/Pdb.h | robbiesri/orbitprofiler | fff73e9cafc4e7928feb900f07b1dddb4af0ecee | [
"BSD-2-Clause"
] | null | null | null | OrbitCore/Pdb.h | robbiesri/orbitprofiler | fff73e9cafc4e7928feb900f07b1dddb4af0ecee | [
"BSD-2-Clause"
] | null | null | null | //-----------------------------------
// Copyright Pierric Gimmig 2013-2017
//-----------------------------------
#pragma once
#include "OrbitDbgHelp.h"
#include "OrbitType.h"
#include "Variable.h"
#include <vector>
#include <functional>
#include <thread>
#include <atomic>
struct IDiaSymbol;
struct IDiaSession;
struct IDiaDataSource;
#ifdef _WIN32
class Pdb
{
public:
Pdb( const wchar_t* a_PdbName );
~Pdb();
void Init();
virtual bool LoadPdb( const wchar_t* a_PdbName );
virtual void LoadPdbAsync( const wchar_t* a_PdbName, std::function<void()> a_CompletionCallback );
bool LoadDataFromPdb();
bool LoadPdbDia();
void Update();
void AddFunction( Function & a_Function );
void CheckOrbitFunction( Function & a_Function );
void AddType( const Type & a_Type );
void AddGlobal( const Variable & a_Global );
void PrintFunction( Function & a_Func );
void OnReceiveMessage( const Message & a_Msg );
void AddArgumentRegister( const std::string & a_Reg, const std::string & a_Function );
const std::wstring & GetName() const { return m_Name; }
const std::wstring & GetFileName() const { return m_FileName; }
std::vector<Function>& GetFunctions() { return m_Functions; }
std::vector<Type>& GetTypes() { return m_Types; }
std::vector<Variable>& GetGlobals() { return m_Globals; }
HMODULE GetHModule() { return m_MainModule; }
Type & GetTypeFromId( ULONG a_Id ) { return m_TypeMap[a_Id]; }
Type* GetTypePtrFromId( ULONG a_ID );
GUID GetGuid();
void SetMainModule( HMODULE a_Module ){ m_MainModule = a_Module; }
void Print() const;
void PrintGlobals() const;
void PopulateFunctionMap();
void PopulateStringFunctionMap();
void Clear();
void Reserve();
void ApplyPresets();
Function* GetFunctionFromExactAddress( DWORD64 a_Address );
Function* GetFunctionFromProgramCounter( DWORD64 a_Address );
std::shared_ptr<OrbitDiaSymbol> SymbolFromAddress( DWORD64 a_Address );
bool LineInfoFromAddress( DWORD64 a_Address, struct LineInfo & o_LineInfo );
void SetLoadTime( float a_LoadTime ) { m_LastLoadTime = a_LoadTime; }
float GetLoadTime() { return m_LastLoadTime; }
std::wstring GetCachedName();
std::wstring GetCachedKey();
bool Load( const std::string & a_CachedPdb );
void Save();
bool IsLoading() const { return m_IsLoading; }
template <class Archive>
void serialize( Archive & ar, std::uint32_t const version )
{
/*ar( CEREAL_NVP(m_Name)
, CEREAL_NVP(m_FileName)
, CEREAL_NVP(m_FileNameW)
, CEREAL_NVP(m_Functions)
, CEREAL_NVP(m_Types)
, CEREAL_NVP(m_Globals)
, CEREAL_NVP(m_ModuleInfo)
, CEREAL_NVP(m_TypeMap) );*/
}
std::shared_ptr<OrbitDiaSymbol> GetDiaSymbolFromId(ULONG a_Id);
void ProcessData();
protected:
void SendStatusToUi();
protected:
// State
std::unique_ptr<std::thread> m_LoadingThread;
std::atomic<bool> m_FinishedLoading;
std::atomic<bool> m_IsLoading;
std::atomic<bool> m_IsPopulatingFunctionMap;
std::atomic<bool> m_IsPopulatingFunctionStringMap;
std::function<void()> m_LoadingCompleteCallback;
HMODULE m_MainModule;
float m_LastLoadTime;
bool m_LoadedFromCache;
std::vector< Variable > m_WatchedVariables;
std::set<std::string> m_ArgumentRegisters;
std::map<std::string, std::vector< std::string > > m_RegFunctionsMap;
// Data
std::wstring m_Name;
std::wstring m_FileName;
std::vector<Function> m_Functions;
std::vector<Type> m_Types;
std::vector<Variable> m_Globals;
IMAGEHLP_MODULE64 m_ModuleInfo;
std::unordered_map<ULONG, Type> m_TypeMap;
std::map<DWORD64, Function*> m_FunctionMap;
std::unordered_map<unsigned long long, Function*> m_StringFunctionMap;
Timer* m_LoadTimer;
// DIA
IDiaSession* m_DiaSession;
IDiaSymbol* m_DiaGlobalSymbol;
IDiaDataSource* m_DiaDataSource;
};
#else
class Pdb
{
public:
Pdb( const wchar_t* a_PdbName ){}
~Pdb(){}
void Init(){}
virtual bool LoadPdb( const wchar_t* a_PdbName ){ return false; }
virtual void LoadPdbAsync( const wchar_t* a_PdbName, std::function<void()> a_CompletionCallback );
bool LoadDataFromPdb(){return false;}
bool LoadPdbDia(){return false;}
void Update(){}
void AddFunction( Function & a_Function ){ m_Functions.push_back( a_Function ); }
void CheckOrbitFunction( Function & a_Function ){}
void AddType( const Type & a_Type ){}
void AddGlobal( const Variable & a_Global ){}
void PrintFunction( Function & a_Func ){}
void OnReceiveMessage( const Message & a_Msg ){}
void AddArgumentRegister( const std::string & a_Reg, const std::string & a_Function ){}
const std::wstring & GetName() const { return m_Name; }
const std::wstring & GetFileName() const { return m_FileName; }
std::vector<Function>& GetFunctions() { return m_Functions; }
std::vector<Type>& GetTypes() { return m_Types; }
std::vector<Variable>& GetGlobals() { return m_Globals; }
HMODULE GetHModule() { return m_MainModule; }
Type & GetTypeFromId( ULONG a_Id ) { return m_TypeMap[a_Id]; }
Type* GetTypePtrFromId( ULONG a_ID );
GUID GetGuid();
void SetMainModule( HMODULE a_Module ){ m_MainModule = a_Module; }
void Print() const;
void PrintGlobals() const;
void PopulateFunctionMap();
void PopulateStringFunctionMap();
void Clear();
void Reserve();
void ApplyPresets();
Function* GetFunctionFromExactAddress( DWORD64 a_Address );
Function* GetFunctionFromProgramCounter( DWORD64 a_Address );
IDiaSymbol* SymbolFromAddress( DWORD64 a_Address );
bool LineInfoFromAddress( DWORD64 a_Address, struct LineInfo & o_LineInfo );
Function* FunctionFromName( const std::wstring& a_Name );
void SetLoadTime( float a_LoadTime ) { m_LastLoadTime = a_LoadTime; }
float GetLoadTime() { return m_LastLoadTime; }
std::wstring GetCachedName();
std::wstring GetCachedKey();
bool Load( const std::string & a_CachedPdb );
void Save();
bool IsLoading() const { return m_IsLoading; }
template <class Archive>
void serialize( Archive & ar, std::uint32_t const version )
{
}
IDiaSymbol* GetDiaSymbolFromId( ULONG a_Id );
void ProcessData();
protected:
void SendStatusToUi();
protected:
// State
std::unique_ptr<std::thread> m_LoadingThread;
std::atomic<bool> m_FinishedLoading;
std::atomic<bool> m_IsLoading;
std::atomic<bool> m_IsPopulatingFunctionMap;
std::atomic<bool> m_IsPopulatingFunctionStringMap;
std::function<void()> m_LoadingCompleteCallback;
HMODULE m_MainModule = 0;
float m_LastLoadTime = 0;
std::vector< Variable > m_WatchedVariables;
std::set<std::string> m_ArgumentRegisters;
std::map<std::string, std::vector< std::string > > m_RegFunctionsMap;
// Data
std::wstring m_Name;
std::wstring m_FileName;
std::vector<Function> m_Functions;
std::vector<Type> m_Types;
std::vector<Variable> m_Globals;
std::unordered_map<ULONG, Type> m_TypeMap;
std::map<DWORD64, Function*> m_FunctionMap;
std::unordered_map<unsigned long long, Function*> m_StringFunctionMap;
Timer* m_LoadTimer = nullptr;
};
#endif
extern std::shared_ptr<Pdb> GPdbDbg;
| 36.502165 | 102 | 0.600451 | [
"vector"
] |
27e51905ecbdc303653e2efcafef7f4a49982c11 | 5,463 | h | C | Source/AST/ASTFunction.h | IanNorris/Shadr | eb6a67f96624cd41b78740c4a047ff6319493d4f | [
"MIT"
] | null | null | null | Source/AST/ASTFunction.h | IanNorris/Shadr | eb6a67f96624cd41b78740c4a047ff6319493d4f | [
"MIT"
] | null | null | null | Source/AST/ASTFunction.h | IanNorris/Shadr | eb6a67f96624cd41b78740c4a047ff6319493d4f | [
"MIT"
] | null | null | null | #if !defined( SHADR_AST_FUNCTION_H )
#define SHADR_AST_FUNCTION_H
class CASTPrototype : public CASTBase, public CASTScope, public CASTAnnotationSupport
{
public:
CASTPrototype( const SParsePosition& rtParsePosition, const char* pszName, unsigned int uNameLength, const CType& rtReturnType, CScope* pParentScope, bool bIntrinsic, bool bInline )
: CASTBase( rtParsePosition )
, CASTScope( pParentScope )
, m_tReturnType( rtReturnType )
, m_pReturnType( &m_tReturnType )
, m_tName( pszName, uNameLength )
, m_bIntrinsic( bIntrinsic )
, m_bInline( bInline )
{
AddReflection( "ReturnType", EASTReflectionType_Type, &m_pReturnType );
AddReflection( "Name", EASTReflectionType_SString, &m_tName );
AddReflection( "Parameters", EASTReflectionType_ASTNodeArray, &m_apParameters );
AddCondition( "HasParameters", [&](){ return !m_apParameters.empty(); } );
AddCondition( "IsIntrinsic", [&](){ return m_bIntrinsic; } );
AddCondition( "IsInline", [&](){ return m_bInline; } );
}
const char* GetElementName() const { return "Prototype"; }
void AddParameter( CASTVariableDefinition* pParameter )
{
m_apParameters.push_back( pParameter );
}
const CType& GetReturnType() { return m_tReturnType; }
const std::vector< CASTVariableDefinition* >& GetParameters() const { return m_apParameters; }
std::vector< CASTBase* > GetChildren( void )
{
std::vector< CASTBase* > tChildren;
for( auto& child : m_apParameters )
{
tChildren.push_back( child );
}
return tChildren;
}
const std::string& GetFunctionName() const { return m_tName; }
bool CanFitParameterCount( unsigned int uParameterCount )
{
//TODO: Implement default parameters here.
if( m_apParameters.size() == uParameterCount )
{
return true;
}
return false;
}
bool IsIntrinsic()
{
return m_bIntrinsic;
}
bool IsInline()
{
return m_bInline;
}
private:
CType* m_pReturnType; //Workaround for the type expecting CType** in AddReflection
CType m_tReturnType;
std::string m_tName;
std::vector< CASTVariableDefinition* > m_apParameters;
bool m_bIntrinsic;
bool m_bInline;
};
class CASTFunction : public CASTBase, public CASTAnnotationSupport
{
public:
CASTFunction( const SParsePosition& rtParsePosition, CASTPrototype* pPrototype, CASTBlockStatement* pBody )
: CASTBase( rtParsePosition )
, m_pPrototype( pPrototype )
, m_pBody( pBody )
, m_bInline( false )
{
AddReflection( "Prototype", EASTReflectionType_ASTNode, &m_pPrototype );
AddReflection( "Body", EASTReflectionType_ASTNode, &m_pBody );
AddReflection( "Inline", EASTReflectionType_Bool, &m_bInline );
}
const char* GetElementName() const { return "Function"; }
std::vector< CASTBase* > GetChildren( void )
{
std::vector< CASTBase* > tChildren;
tChildren.push_back( m_pPrototype );
tChildren.push_back( m_pBody );
return tChildren;
}
bool IsInline( void )
{
return m_bInline;
}
CASTPrototype* GetPrototype() { return m_pPrototype; }
private:
CASTPrototype* m_pPrototype;
CASTBlockStatement* m_pBody;
bool m_bInline;
};
class CASTExpressionFunctionCall : public CASTExpression
{
public:
CASTExpressionFunctionCall( const SParsePosition& rtParsePosition, const std::string& rtName )
: CASTExpression( rtParsePosition, CType::GetVoidType(), false )
, m_tName( rtName )
, m_pPrototype( nullptr )
, m_pFunctionBody( nullptr )
, m_bIntrinsic( false )
{
AddReflection( "Name", EASTReflectionType_SString, &m_tName );
AddReflection( "Parameters", EASTReflectionType_ASTNodeArray, &m_apParameters );
AddCondition( "HasParameters", [&](){ return !m_apParameters.empty(); } );
}
const std::string& GetFunctionName() const { return m_tName; }
const char* GetElementName() const { return "FunctionCall"; }
void AddParameter( CASTExpression* pParameter )
{
m_apParameters.push_back( pParameter );
}
const std::vector< CASTExpression* >& GetParameters() const { return m_apParameters; }
std::vector< CASTBase* > GetChildren( void )
{
std::vector< CASTBase* > tChildren;
for( auto& child : m_apParameters )
{
tChildren.push_back( child );
}
return tChildren;
}
bool FindMatchingFunction( CScope* pScope );
bool FindMatchingFunctionBody( CScope* pScope );
void EvaluateType() override
{
//TODO
if( m_pPrototype )
{
m_tType = m_pPrototype->GetReturnType();
}
else
{
m_tType = CType::GetConstIntType();
}
}
bool IsIntrinsic()
{
return m_bIntrinsic;
}
bool IsInline()
{
if( m_pPrototype )
{
return m_pPrototype->IsInline();
}
else
{
return false;
}
}
CASTPrototype* GetPrototype()
{
return m_pPrototype;
}
CASTFunction* GetFunctionBody()
{
return m_pFunctionBody;
}
virtual CASTExpression* ReplaceAndClone( std::vector< std::pair< CASTExpression*, CASTExpression* > >& expressionsToReplace, unsigned int uDepthToRecurse ) override
{
auto pFC = new CASTExpressionFunctionCall( GetParserPosition(), m_tName );
for( auto pParam : m_apParameters )
{
pFC->AddParameter( ReplaceAndCloneSingle( pParam, expressionsToReplace, uDepthToRecurse - 1 ) );
}
//Functions themselves should not be cloned
pFC->m_pPrototype = m_pPrototype;
pFC->m_pFunctionBody = m_pFunctionBody;
pFC->m_bIntrinsic = m_bIntrinsic;
return pFC;
}
private:
std::string m_tName;
std::vector< CASTExpression* > m_apParameters;
CASTPrototype* m_pPrototype;
CASTFunction* m_pFunctionBody;
bool m_bIntrinsic;
};
#endif //SHADR_AST_FUNCTION_H | 23.855895 | 182 | 0.727622 | [
"vector"
] |
27edf31b4824e8f7d6db5f3d83d5b727a68d3fbd | 2,931 | h | C | src/simulationModels/RenderDemoSimulation.h | hschwane/CIRCULATION | a53a99af4b0104101c18c8c5672ffd71b4ecb6c2 | [
"MIT"
] | null | null | null | src/simulationModels/RenderDemoSimulation.h | hschwane/CIRCULATION | a53a99af4b0104101c18c8c5672ffd71b4ecb6c2 | [
"MIT"
] | null | null | null | src/simulationModels/RenderDemoSimulation.h | hschwane/CIRCULATION | a53a99af4b0104101c18c8c5672ffd71b4ecb6c2 | [
"MIT"
] | null | null | null | /*
* CIRCULATION
* RenderDemoSimulation.h
*
* @author: Hendrik Schwanekamp
* @mail: hendrik.schwanekamp@gmx.net
*
* Implements the RenderDemoSimulation class
*
* Copyright (c) 2020 Hendrik Schwanekamp
*
*/
#ifndef CIRCULATION_RENDERDEMOSIMULATION_H
#define CIRCULATION_RENDERDEMOSIMULATION_H
// includes
//--------------------
#include "Simulation.h"
//--------------------
//-------------------------------------------------------------------
/**
* class RenderDemoSimulation
*
* usage:
*
*/
class RenderDemoSimulation : public Simulation
{
public:
void showCreationOptions() override
{
ImGui::Checkbox("Random Vectors", &m_randomVectors);
if(!m_randomVectors)
ImGui::DragFloat2("Vector", &m_vectorValue.x);
}
std::shared_ptr<GridBase> recreate(std::shared_ptr<CoordinateSystem> cs) override
{
m_cs = cs;
m_grid = std::make_shared<RenderDemoGrid>(m_cs->getNumGridCells());
// call reset() to initialize data
reset();
return m_grid;
}
std::unique_ptr<Simulation> clone() const override
{
return std::make_unique<RenderDemoSimulation>(*this);
}
void showBoundaryOptions(const CoordinateSystem& cs) override
{
ImGui::Text("This is a rendering demo, it does not include any special boundary handling.");
}
void reset() override
{
// generate some data
std::default_random_engine rng(mpu::getRanndomSeed());
std::normal_distribution<float> dist(10,4);
std::normal_distribution<float> vdist(0,4);
for(int i : mpu::Range<int>(m_grid->size()))
{
float density = fmax(0,dist(rng));
float velX = vdist(rng);
float velY = vdist(rng);
m_grid->write<AT::density>(i,density);
if(m_randomVectors)
{
m_grid->write<AT::velocityX>(i, velX);
m_grid->write<AT::velocityY>(i, velY);
}
else {
m_grid->write<AT::velocityX>(i, m_vectorValue.x);
m_grid->write<AT::velocityY>(i, m_vectorValue.y);
}
}
// swap buffers and ready for rendering
m_grid->swapAndRender();
}
private:
void simulateOnce() override
{
// this is the rendering demo, so we do nothing
}
GridBase& getGrid() override
{
return *m_grid;
}
void showSimulationOptions() override
{
ImGui::Text("This is a rendering demo, so the simulation does nothing. There are also no settings.");
}
std::string getDisplayName() override
{
return "Render Demo";
}
// creation options
bool m_randomVectors{true};
float2 m_vectorValue;
// sim data
std::shared_ptr<CoordinateSystem> m_cs;
std::shared_ptr<RenderDemoGrid> m_grid;
};
#endif //CIRCULATION_RENDERDEMOSIMULATION_H
| 23.829268 | 109 | 0.588536 | [
"render",
"vector"
] |
27f50bbccc6414ca02bb4ffc67aa84702a1c6c76 | 11,373 | c | C | src/gt2/gt2main.c | TheAssemblyArmada/GamespySDK | a75313bdf608806569896aa039763d82f9b7d0eb | [
"BSD-3-Clause"
] | null | null | null | src/gt2/gt2main.c | TheAssemblyArmada/GamespySDK | a75313bdf608806569896aa039763d82f9b7d0eb | [
"BSD-3-Clause"
] | null | null | null | src/gt2/gt2main.c | TheAssemblyArmada/GamespySDK | a75313bdf608806569896aa039763d82f9b7d0eb | [
"BSD-3-Clause"
] | null | null | null | /*
GameSpy GT2 SDK
Dan "Mr. Pants" Schoenblum
dan@gamespy.com
Copyright 2002 GameSpy Industries, Inc
devsupport@gamespy.com
*/
#include "gt2main.h"
#include "gt2socket.h"
#include "gt2connection.h"
#include "gt2message.h"
#include "gt2callback.h"
#include "gt2filter.h"
#include "gt2utility.h"
#define GTI2_INVALID_IP_MASK 0xE0000000
/*********************
** SOCKET FUNCTIONS **
*********************/
// Xbox VDP socket function(s).
#ifdef _XBOX
GT2Result gt2CreateVDPSocket(GT2Socket* socket,
const char* localAddress,
int outgoingBufferSize,
int incomingBufferSize,
gt2SocketErrorCallback callback)
{
return gti2CreateSocket(socket, localAddress, outgoingBufferSize, incomingBufferSize, callback, GTI2VdpProtocol);
}
#endif
GT2Result gt2CreateSocket(GT2Socket* socket,
const char* localAddress,
int outgoingBufferSize,
int incomingBufferSize,
gt2SocketErrorCallback callback)
{
return gti2CreateSocket(socket, localAddress, outgoingBufferSize, incomingBufferSize, callback, GTI2UdpProtocol);
}
GT2Result gt2CreateAdHocSocket(GT2Socket* socket,
const char* localAddress,
int outgoingBufferSize,
int incomingBufferSize,
gt2SocketErrorCallback callback)
{
return gti2CreateSocket(socket, localAddress, outgoingBufferSize, incomingBufferSize, callback, GTI2AdHocProtocol);
}
void gt2CloseSocket(GT2Socket socket)
{
// hard close the connections
gt2CloseAllConnectionsHard(socket);
// close the socket
gti2CloseSocket(socket);
}
void gt2Think(GT2Socket socket)
{
// check for incoming messages
if (!gti2ReceiveMessages(socket))
return;
// let the connections think
if (!gti2SocketConnectionsThink(socket))
return;
// free closed connections
gti2FreeClosedConnections(socket);
}
GT2Result gt2SendRawUDP(GT2Socket socket, const char* remoteAddress, const GT2Byte* message, int len)
{
unsigned int ip;
unsigned short port;
// get the ip and port
if (!gt2StringToAddress(remoteAddress, &ip, &port) || !port)
return GT2AddressError;
// check for invalid IP ranges
// class D (224-239.*, multicast) and class E (240-255.*, experimental)
if ((ntohl(ip) & GTI2_INVALID_IP_MASK) == GTI2_INVALID_IP_MASK)
return GT2AddressError;
// check if this is for broadcast
if (!ip) {
// check if broadcast is enable
if (!socket->broadcastEnabled) {
if (!SetSockBroadcast(socket->socket))
return GT2NetworkError;
socket->broadcastEnabled = GT2True;
}
// set the broadcast ip
ip = gsiGetBroadcastIP();
}
// send the datagram
gti2SocketSend(socket, ip, port, message, len);
return GT2Success;
}
/*********************
** LISTEN FUNCTIONS **
*********************/
void gt2Listen(GT2Socket socket, gt2ConnectAttemptCallback callback)
{
gti2Listen(socket, callback);
}
GT2Bool gt2Accept(GT2Connection connection, GT2ConnectionCallbacks* callbacks)
{
return gti2AcceptConnection(connection, callbacks);
}
void gt2Reject(GT2Connection connection, const GT2Byte* message, int len)
{
gti2RejectConnection(connection, message, len);
}
/*************************
** CONNECTION FUNCTIONS **
*************************/
GT2Result gt2Connect(GT2Socket socket,
GT2Connection* connection,
const char* remoteAddress,
const GT2Byte* message,
int len,
int timeout,
GT2ConnectionCallbacks* callbacks,
GT2Bool blocking)
{
GT2Connection connectionTemp;
GT2Result result;
GT2Bool done;
unsigned int ip;
unsigned short port;
{
// get the ip and port
if (!gt2StringToAddress(remoteAddress, &ip, &port) || !ip || !port)
return GT2AddressError;
}
// check for invalid IP ranges
// class D (224-239.*, multicast) and class E (240-255.*, experimental)
if ((ntohl(ip) & GTI2_INVALID_IP_MASK) == GTI2_INVALID_IP_MASK)
return GT2AddressError;
// create the connection object
result = gti2NewOutgoingConnection(socket, &connectionTemp, ip, port);
if (result)
return result;
// save the timeout value
connectionTemp->timeout = (unsigned int)timeout;
// initiate the connection attempt
result = gti2StartConnectionAttempt(connectionTemp, message, len, callbacks);
if (result) {
gti2FreeSocketConnection(connectionTemp);
return result;
}
// if not blocking, return now
if (!blocking) {
if (connection)
*connection = connectionTemp;
return GT2Success;
}
// we're not really in a callback, but this will prevent the connection
// from being freed before the loop finishes.
connectionTemp->callbackLevel++;
// if blocking, loop until the connect attempt is done
do {
// think
gt2Think(socket);
// check if we're done
done = (connectionTemp->state >= GTI2Connected);
// if we're not done, take a rest
if (!done)
msleep(1);
} while (!done);
// bring the callback level back down
connectionTemp->callbackLevel--;
// is it success?
if (connectionTemp->state == GTI2Connected)
*connection = connectionTemp;
return connectionTemp->connectionResult;
}
GT2Result gt2Send(GT2Connection connection, const GT2Byte* message, int len, GT2Bool reliable)
{
// used to check for voice data in reliable messages
unsigned short vdpDataLength;
// can't send a message if not connected
if (connection->state != GTI2Connected)
return GT2InvalidConnection;
// check the message and len
gti2MessageCheck(&message, &len);
if (reliable && connection->socket->protocolType == GTI2VdpProtocol) {
memcpy(&vdpDataLength, message, sizeof(unsigned short));
assert(vdpDataLength + connection->socket->protocolOffset == len);
if (vdpDataLength + connection->socket->protocolOffset != len)
return GT2InvalidMessage;
}
// do we need to filter it?
if (ArrayLength(connection->sendFilters)) {
gti2SendFilterCallback(connection, 0, message, len, reliable);
return GT2Success;
}
if (gti2Send(connection, message, len, reliable))
return GT2Success;
return GT2SendFailed;
}
void gt2Ping(GT2Connection connection)
{
gti2SendPing(connection);
}
void gt2CloseConnection(GT2Connection connection)
{
gti2CloseConnection(connection, GT2False);
}
void gt2CloseConnectionHard(GT2Connection connection)
{
gti2CloseConnection(connection, GT2True);
}
static void gti2CloseAllConnectionsMap(void* elem, void* clientData)
{
gt2CloseConnection(*(GT2Connection*)elem);
GSI_UNUSED(clientData);
}
void gt2CloseAllConnections(GT2Socket socket)
{
TableMapSafe(socket->connections, gti2CloseAllConnectionsMap, NULL);
}
static void gti2CloseAllConnectionsHardMap(void* elem, void* clientData)
{
gt2CloseConnectionHard(*(GT2Connection*)elem);
GSI_UNUSED(clientData);
}
void gt2CloseAllConnectionsHard(GT2Socket socket)
{
TableMapSafe(socket->connections, gti2CloseAllConnectionsHardMap, NULL);
}
/*************************
** MESSAGE CONFIRMATION **
*************************/
GT2MessageID gt2GetLastSentMessageID(GT2Connection connection)
{
return (GT2MessageID)(connection->serialNumber - 1);
}
GT2Bool gt2WasMessageIDConfirmed(GT2Connection connection, GT2MessageID messageID)
{
return gti2WasMessageIDConfirmed(connection, messageID);
}
/*********************
** FILTER FUNCTIONS **
*********************/
GT2Bool gt2AddSendFilter(GT2Connection connection, gt2SendFilterCallback callback)
{
return gti2AddSendFilter(connection, callback);
}
void gt2RemoveSendFilter(GT2Connection connection, gt2SendFilterCallback callback)
{
gti2RemoveSendFilter(connection, callback);
}
void gt2FilteredSend(GT2Connection connection, int filterID, const GT2Byte* message, int len, GT2Bool reliable)
{
gti2FilteredSend(connection, filterID, message, len, reliable);
}
GT2Bool gt2AddReceiveFilter(GT2Connection connection, gt2ReceiveFilterCallback callback)
{
return gti2AddReceiveFilter(connection, callback);
}
void gt2RemoveReceiveFilter(GT2Connection connection, gt2ReceiveFilterCallback callback)
{
gti2RemoveReceiveFilter(connection, callback);
}
void gt2FilteredReceive(GT2Connection connection, int filterID, GT2Byte* message, int len, GT2Bool reliable)
{
gti2FilteredReceive(connection, filterID, message, len, reliable);
}
/*******************
** INFO FUNCTIONS **
*******************/
GT2Socket gt2GetConnectionSocket(GT2Connection connection)
{
return connection->socket;
}
GT2ConnectionState gt2GetConnectionState(GT2Connection connection)
{
if (connection->state < GTI2Connected)
return GT2Connecting;
if (connection->state == GTI2Connected)
return GT2Connected;
if (connection->state == GTI2Closing)
return GT2Closing;
return GT2Closed;
}
unsigned int gt2GetRemoteIP(GT2Connection connection)
{
return connection->ip;
}
unsigned short gt2GetRemotePort(GT2Connection connection)
{
return connection->port;
}
unsigned int gt2GetLocalIP(GT2Socket socket)
{
return socket->ip;
}
unsigned short gt2GetLocalPort(GT2Socket socket)
{
return socket->port;
}
int gt2GetIncomingBufferSize(GT2Connection connection)
{
return connection->incomingBuffer.size;
}
int gt2GetIncomingBufferFreeSpace(GT2Connection connection)
{
return (connection->incomingBuffer.size - connection->incomingBuffer.len);
}
int gt2GetOutgoingBufferSize(GT2Connection connection)
{
return connection->outgoingBuffer.size;
}
int gt2GetOutgoingBufferFreeSpace(GT2Connection connection)
{
return (connection->outgoingBuffer.size - connection->outgoingBuffer.len);
}
/*****************************
** SOCKET SHARING FUNCTIONS **
*****************************/
SOCKET gt2GetSocketSOCKET(GT2Socket socket)
{
return socket->socket;
}
void gt2SetUnrecognizedMessageCallback(GT2Socket socket, gt2UnrecognizedMessageCallback callback)
{
socket->unrecognizedMessageCallback = callback;
}
/************************
** USER DATA FUNCTIONS **
************************/
void gt2SetSocketData(GT2Socket socket, void* data)
{
assert(socket);
socket->data = data;
}
void* gt2GetSocketData(GT2Socket socket)
{
assert(socket);
return socket->data;
}
void gt2SetConnectionData(GT2Connection connection, void* data)
{
assert(connection);
connection->data = data;
}
void* gt2GetConnectionData(GT2Connection connection)
{
assert(connection);
return connection->data;
}
/*******************
** DUMP FUNCTIONS **
*******************/
void gt2SetSendDump(GT2Socket socket, gt2DumpCallback callback)
{
socket->sendDumpCallback = callback;
}
void gt2SetReceiveDump(GT2Socket socket, gt2DumpCallback callback)
{
socket->receiveDumpCallback = callback;
}
| 25.557303 | 119 | 0.670184 | [
"object"
] |
7e081c611b817923dec8eb7613ce4e6082632916 | 8,841 | h | C | aws-cpp-sdk-translate/include/aws/translate/model/GetParallelDataResult.h | Eliyahu-Machluf/aws-sdk-cpp | 97b8d6cdc16df298b80941b94327a5026efa7f8c | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-translate/include/aws/translate/model/GetParallelDataResult.h | Eliyahu-Machluf/aws-sdk-cpp | 97b8d6cdc16df298b80941b94327a5026efa7f8c | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-translate/include/aws/translate/model/GetParallelDataResult.h | Eliyahu-Machluf/aws-sdk-cpp | 97b8d6cdc16df298b80941b94327a5026efa7f8c | [
"Apache-2.0"
] | 1 | 2022-03-23T15:17:18.000Z | 2022-03-23T15:17:18.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/translate/Translate_EXPORTS.h>
#include <aws/translate/model/ParallelDataProperties.h>
#include <aws/translate/model/ParallelDataDataLocation.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace Translate
{
namespace Model
{
class AWS_TRANSLATE_API GetParallelDataResult
{
public:
GetParallelDataResult();
GetParallelDataResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
GetParallelDataResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The properties of the parallel data resource that is being retrieved.</p>
*/
inline const ParallelDataProperties& GetParallelDataProperties() const{ return m_parallelDataProperties; }
/**
* <p>The properties of the parallel data resource that is being retrieved.</p>
*/
inline void SetParallelDataProperties(const ParallelDataProperties& value) { m_parallelDataProperties = value; }
/**
* <p>The properties of the parallel data resource that is being retrieved.</p>
*/
inline void SetParallelDataProperties(ParallelDataProperties&& value) { m_parallelDataProperties = std::move(value); }
/**
* <p>The properties of the parallel data resource that is being retrieved.</p>
*/
inline GetParallelDataResult& WithParallelDataProperties(const ParallelDataProperties& value) { SetParallelDataProperties(value); return *this;}
/**
* <p>The properties of the parallel data resource that is being retrieved.</p>
*/
inline GetParallelDataResult& WithParallelDataProperties(ParallelDataProperties&& value) { SetParallelDataProperties(std::move(value)); return *this;}
/**
* <p>The location of the most recent parallel data input file that was
* successfully imported into Amazon Translate. The location is returned as a
* presigned URL that has a 30 minute expiration.</p>
*/
inline const ParallelDataDataLocation& GetDataLocation() const{ return m_dataLocation; }
/**
* <p>The location of the most recent parallel data input file that was
* successfully imported into Amazon Translate. The location is returned as a
* presigned URL that has a 30 minute expiration.</p>
*/
inline void SetDataLocation(const ParallelDataDataLocation& value) { m_dataLocation = value; }
/**
* <p>The location of the most recent parallel data input file that was
* successfully imported into Amazon Translate. The location is returned as a
* presigned URL that has a 30 minute expiration.</p>
*/
inline void SetDataLocation(ParallelDataDataLocation&& value) { m_dataLocation = std::move(value); }
/**
* <p>The location of the most recent parallel data input file that was
* successfully imported into Amazon Translate. The location is returned as a
* presigned URL that has a 30 minute expiration.</p>
*/
inline GetParallelDataResult& WithDataLocation(const ParallelDataDataLocation& value) { SetDataLocation(value); return *this;}
/**
* <p>The location of the most recent parallel data input file that was
* successfully imported into Amazon Translate. The location is returned as a
* presigned URL that has a 30 minute expiration.</p>
*/
inline GetParallelDataResult& WithDataLocation(ParallelDataDataLocation&& value) { SetDataLocation(std::move(value)); return *this;}
/**
* <p>The Amazon S3 location of a file that provides any errors or warnings that
* were produced by your input file. This file was created when Amazon Translate
* attempted to create a parallel data resource. The location is returned as a
* presigned URL to that has a 30 minute expiration.</p>
*/
inline const ParallelDataDataLocation& GetAuxiliaryDataLocation() const{ return m_auxiliaryDataLocation; }
/**
* <p>The Amazon S3 location of a file that provides any errors or warnings that
* were produced by your input file. This file was created when Amazon Translate
* attempted to create a parallel data resource. The location is returned as a
* presigned URL to that has a 30 minute expiration.</p>
*/
inline void SetAuxiliaryDataLocation(const ParallelDataDataLocation& value) { m_auxiliaryDataLocation = value; }
/**
* <p>The Amazon S3 location of a file that provides any errors or warnings that
* were produced by your input file. This file was created when Amazon Translate
* attempted to create a parallel data resource. The location is returned as a
* presigned URL to that has a 30 minute expiration.</p>
*/
inline void SetAuxiliaryDataLocation(ParallelDataDataLocation&& value) { m_auxiliaryDataLocation = std::move(value); }
/**
* <p>The Amazon S3 location of a file that provides any errors or warnings that
* were produced by your input file. This file was created when Amazon Translate
* attempted to create a parallel data resource. The location is returned as a
* presigned URL to that has a 30 minute expiration.</p>
*/
inline GetParallelDataResult& WithAuxiliaryDataLocation(const ParallelDataDataLocation& value) { SetAuxiliaryDataLocation(value); return *this;}
/**
* <p>The Amazon S3 location of a file that provides any errors or warnings that
* were produced by your input file. This file was created when Amazon Translate
* attempted to create a parallel data resource. The location is returned as a
* presigned URL to that has a 30 minute expiration.</p>
*/
inline GetParallelDataResult& WithAuxiliaryDataLocation(ParallelDataDataLocation&& value) { SetAuxiliaryDataLocation(std::move(value)); return *this;}
/**
* <p>The Amazon S3 location of a file that provides any errors or warnings that
* were produced by your input file. This file was created when Amazon Translate
* attempted to update a parallel data resource. The location is returned as a
* presigned URL to that has a 30 minute expiration.</p>
*/
inline const ParallelDataDataLocation& GetLatestUpdateAttemptAuxiliaryDataLocation() const{ return m_latestUpdateAttemptAuxiliaryDataLocation; }
/**
* <p>The Amazon S3 location of a file that provides any errors or warnings that
* were produced by your input file. This file was created when Amazon Translate
* attempted to update a parallel data resource. The location is returned as a
* presigned URL to that has a 30 minute expiration.</p>
*/
inline void SetLatestUpdateAttemptAuxiliaryDataLocation(const ParallelDataDataLocation& value) { m_latestUpdateAttemptAuxiliaryDataLocation = value; }
/**
* <p>The Amazon S3 location of a file that provides any errors or warnings that
* were produced by your input file. This file was created when Amazon Translate
* attempted to update a parallel data resource. The location is returned as a
* presigned URL to that has a 30 minute expiration.</p>
*/
inline void SetLatestUpdateAttemptAuxiliaryDataLocation(ParallelDataDataLocation&& value) { m_latestUpdateAttemptAuxiliaryDataLocation = std::move(value); }
/**
* <p>The Amazon S3 location of a file that provides any errors or warnings that
* were produced by your input file. This file was created when Amazon Translate
* attempted to update a parallel data resource. The location is returned as a
* presigned URL to that has a 30 minute expiration.</p>
*/
inline GetParallelDataResult& WithLatestUpdateAttemptAuxiliaryDataLocation(const ParallelDataDataLocation& value) { SetLatestUpdateAttemptAuxiliaryDataLocation(value); return *this;}
/**
* <p>The Amazon S3 location of a file that provides any errors or warnings that
* were produced by your input file. This file was created when Amazon Translate
* attempted to update a parallel data resource. The location is returned as a
* presigned URL to that has a 30 minute expiration.</p>
*/
inline GetParallelDataResult& WithLatestUpdateAttemptAuxiliaryDataLocation(ParallelDataDataLocation&& value) { SetLatestUpdateAttemptAuxiliaryDataLocation(std::move(value)); return *this;}
private:
ParallelDataProperties m_parallelDataProperties;
ParallelDataDataLocation m_dataLocation;
ParallelDataDataLocation m_auxiliaryDataLocation;
ParallelDataDataLocation m_latestUpdateAttemptAuxiliaryDataLocation;
};
} // namespace Model
} // namespace Translate
} // namespace Aws
| 45.80829 | 192 | 0.737247 | [
"model"
] |
7e0c87974a765a45f5cd96423e2c07592035da3b | 7,792 | h | C | src/math/Types.h | alecnunn/mud | 9e204e2dc65f4a8ab52da3d11e6a261ff279d353 | [
"Zlib"
] | 1 | 2019-03-28T20:45:32.000Z | 2019-03-28T20:45:32.000Z | src/math/Types.h | alecnunn/mud | 9e204e2dc65f4a8ab52da3d11e6a261ff279d353 | [
"Zlib"
] | null | null | null | src/math/Types.h | alecnunn/mud | 9e204e2dc65f4a8ab52da3d11e6a261ff279d353 | [
"Zlib"
] | null | null | null | #pragma once
#include <math/Forward.h>
#if !defined MUD_MODULES || defined MUD_TYPE_LIB
#include <type/Type.h>
#include <type/Vector.h>
#endif
#ifndef MUD_MODULES
#include <infra/Types.h>
#include <type/Types.h>
#endif
#ifndef MUD_CPP_20
#include <string>
#include <cstdint>
#include <vector>
#endif
#include <math/Structs.h>
namespace mud
{
// Exported types
export_ template <> MUD_MATH_EXPORT Type& type<mud::Axes>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::Axis>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::Clockwise>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::Side>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::SignedAxis>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::Spectrum>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::TrackMode>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::AutoStat<float>>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::AutoStat<int>>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::Colour>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::Gauge>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::Image>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::Image256>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::ImageAtlas>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::Palette>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::Range<float>>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::Range<mud::Colour>>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::Range<mud::quat>>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::Range<mud::vec3>>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::Range<uint32_t>>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::Ratio>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::Time>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::TimeSpan>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::Transform>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::ValueCurve<float>>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::ValueCurve<mud::Colour>>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::ValueCurve<mud::quat>>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::ValueCurve<mud::vec3>>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::ValueCurve<uint32_t>>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::ValueTrack<float>>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::ValueTrack<mud::Colour>>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::ValueTrack<mud::quat>>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::ValueTrack<mud::vec3>>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::ValueTrack<uint32_t>>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::bvec3>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::bvec4>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::half2>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::half3>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::ivec2>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::ivec3>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::ivec4>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::mat4>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::quat>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::uvec2>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::uvec3>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::uvec4>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::vec2>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::vec3>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::vec4>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::Sprite>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::SpriteAtlas>();
export_ template <> MUD_MATH_EXPORT Type& type<mud::TextureAtlas>();
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::AutoStat<float>*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::AutoStat<int>*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::Colour*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::Gauge*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::Image*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::Image256*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::ImageAtlas*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::Palette*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::Range<float>*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::Range<mud::Colour>*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::Range<mud::quat>*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::Range<mud::vec3>*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::Range<uint32_t>*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::Ratio*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::Time*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::TimeSpan*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::Transform*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::ValueCurve<float>*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::ValueCurve<mud::Colour>*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::ValueCurve<mud::quat>*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::ValueCurve<mud::vec3>*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::ValueCurve<uint32_t>*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::ValueTrack<float>*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::ValueTrack<mud::Colour>*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::ValueTrack<mud::quat>*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::ValueTrack<mud::vec3>*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::ValueTrack<uint32_t>*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::bvec3*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::bvec4*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::half2*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::half3*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::ivec2*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::ivec3*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::ivec4*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::mat4*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::quat*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::uvec2*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::uvec3*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::uvec4*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::vec2*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::vec3*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::vec4*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::Sprite*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::SpriteAtlas*>>;
export_ template struct MUD_MATH_EXPORT Typed<std::vector<mud::TextureAtlas*>>;
}
| 61.84127 | 94 | 0.728953 | [
"vector",
"transform"
] |
7e153280a741647cf371762245abc3557fddb118 | 499 | h | C | include/SatOps/SatOps.h | srenevey/satops | 7051d7734d5761c49ae23e446b6b2dfc893daf04 | [
"Apache-2.0"
] | 3 | 2021-02-16T07:37:45.000Z | 2022-03-29T07:07:09.000Z | include/SatOps/SatOps.h | srenevey/satops | 7051d7734d5761c49ae23e446b6b2dfc893daf04 | [
"Apache-2.0"
] | null | null | null | include/SatOps/SatOps.h | srenevey/satops | 7051d7734d5761c49ae23e446b6b2dfc893daf04 | [
"Apache-2.0"
] | null | null | null | //
// Created by Sylvain on 5/12/20.
//
#ifndef SATOPS_SATOPS_H
#define SATOPS_SATOPS_H
#include "Atmosphere.h"
#include "Body.h"
#include "dimensions.h"
#include "EnvironmentModel.h"
#include "GravitationalField.h"
#include "Gyroscope.h"
#include "Magnetometer.h"
#include "MagneticField.h"
#include "Matrix.h"
#include "Quaternion.h"
#include "ReferenceFrame.h"
#include "Sensor.h"
#include "Sim.h"
#include "Spacecraft.h"
#include "StateVector.h"
#include "Vector.h"
#endif //SATOPS_SATOPS_H
| 19.192308 | 34 | 0.743487 | [
"vector"
] |
5f261395a9cd462ea8e24e62212e849f2227bcd7 | 5,479 | h | C | Morty/Morty/Core/Renderer/Vulkan/MVulkanDevice.h | FrostyLeaves/Morty | 64a47a5edcaf4ca62ff16ec4c20062f24fafe0ee | [
"MIT"
] | null | null | null | Morty/Morty/Core/Renderer/Vulkan/MVulkanDevice.h | FrostyLeaves/Morty | 64a47a5edcaf4ca62ff16ec4c20062f24fafe0ee | [
"MIT"
] | null | null | null | Morty/Morty/Core/Renderer/Vulkan/MVulkanDevice.h | FrostyLeaves/Morty | 64a47a5edcaf4ca62ff16ec4c20062f24fafe0ee | [
"MIT"
] | null | null | null | /**
* @File MVulkanDevice
*
* @Created 2020-06-17 20:01:48
*
* @Author DoubleYe
**/
#ifndef _M_MVULKANDEVICE_H_
#define _M_MVULKANDEVICE_H_
#include "MGlobal.h"
#if RENDER_GRAPHICS == MORTY_VULKAN
#include "MIDevice.h"
#include <vector>
#include "MVulkanWrapper.h"
#ifdef MORTY_WIN
#include "vulkan/vulkan_core.h"
#endif
#include "MVulkanObjectDestructor.h"
#include "MVulkanShaderCompiler.h"
#include "MVulkanPipelineManager.h"
#include "MVulkanBufferPool.h"
#include "MTexture.h"
class MORTY_API MVulkanDevice : public MIDevice
{
public:
MVulkanDevice();
virtual ~MVulkanDevice();
public:
virtual bool Initialize() override;
virtual void Release() override;
public:
virtual void GenerateBuffer(MVertexBuffer** ppVertexBuffer, MIMesh* pMesh, const bool& bModifiable = false) override;
virtual void DestroyBuffer(MVertexBuffer** ppVertexBuffer) override;
virtual void UploadBuffer(MVertexBuffer** ppVertexBuffer, MIMesh* pMesh) override;
virtual void GenerateTexture(MTextureBuffer** ppTextureBuffer, MTexture* pTexture) override;
virtual void GenerateTextureCube(MTextureBuffer** ppTextureBuffer, MTexture* vTexture[6], const bool& bGenerateMipmap) override;
virtual void DestroyTexture(MTextureBuffer** ppTextureBuffer) override;
virtual bool GenerateRenderTextureBuffer(MRenderTextureBuffer* ppTextureBuffer, MIRenderTexture* pTexture) override;
virtual void DestroyRenderTextureBuffer(MRenderTextureBuffer* ppTextureBuffer) override;
virtual bool CompileShader(MShaderBuffer** ppShaderBuffer, const MString& strShaderPath, const MEShaderType& eShaderType, const MShaderMacro& macro) override;
virtual void CleanShader(MShaderBuffer** ppShaderBuffer) override;
virtual bool GenerateShaderParamSet(MShaderParamSet* pParamSet) override;
virtual void DestroyShaderParamSet(MShaderParamSet* pParamSet) override;
virtual bool GenerateRenderTarget(MRenderPass* pRenderPass, MIRenderTarget* pRenderTarget) override;
virtual void DestroyRenderTarget(MIRenderTarget* pRenderTarget) override;
virtual bool GenerateShaderParamBuffer(MShaderConstantParam* pParam) override;
virtual void DestroyShaderParamBuffer(MShaderConstantParam* pParam) override;
virtual bool GenerateRenderPass(MRenderPass* pRenderPass) override;
virtual void DestroyRenderPass(MRenderPass* pRenderPass) override;
virtual bool GenerateFrameBuffer(MRenderPass* pRenderPass) override;
virtual void DestroyFrameBuffer(MRenderPass* pRenderPass) override;
virtual bool GenerateRenderTargetView(MRenderTextureBuffer* pTextureBuffer) override;
virtual void DestroyRenderTargetView(MRenderTextureBuffer* pTextureBuffer) override;
virtual bool RegisterMaterial(MMaterial* pMaterial) override;
virtual bool UnRegisterMaterial(MMaterial* pMaterial) override;
virtual MRenderCommand* CreateRenderCommand() override;
virtual void RecoveryRenderCommand(MRenderCommand* pCommand) override;
VkPhysicalDevice GetPhysicalDevice() { return m_VkPhysicalDevice; }
void CopyBuffer(VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size);
void CopyImageBuffer(VkBuffer srcBuffer, VkImage image, const uint32_t& width, const uint32_t& height, const uint32_t& unCount);
void CopyImageBuffer(MTextureBuffer* pSource, MTextureBuffer* pDestination, VkCommandBuffer buffer = VK_NULL_HANDLE);
void GenerateMipmaps(MTextureBuffer* pBuffer, const uint32_t& unMipLevels, VkCommandBuffer buffer = VK_NULL_HANDLE);
void TransitionImageLayout(VkImage image, VkImageLayout oldLayout, VkImageLayout newLayout, VkImageSubresourceRange subresourceRange, VkCommandBuffer buffer = VK_NULL_HANDLE);
VkImageView CreateImageView(VkImage image, VkFormat format, VkImageAspectFlags aspectFlags, const uint32_t& unMipmap);
void CreateImage(const uint32_t& unWidth, const uint32_t& unHeight, const uint32_t& unMipmap, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties, VkImage& image, VkDeviceMemory& imageMemory);
void CreateImageCube(const uint32_t& unWidth, const uint32_t& unHeight, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties, VkImage& image, VkDeviceMemory& imageMemory);
VkCommandBuffer BeginCommands();
void EndCommands(VkCommandBuffer commandBuffer);
int FindQueueGraphicsFamilies(VkPhysicalDevice device);
int FindQueuePresentFamilies(VkPhysicalDevice device, VkSurfaceKHR surface);
int FindMemoryType(uint32_t typeFilter, VkMemoryPropertyFlags properties);
int FindSupportedFormat(const std::vector<VkFormat>& candidates, VkImageTiling tiling, VkFormatFeatureFlags features);
VkBool32 FormatIsFilterable(VkFormat format, VkImageTiling tiling);
VkFormat GetFormat(const METextureLayout& layout);
protected:
bool InitVulkanInstance();
bool InitPhysicalDevice();
bool InitLogicalDevice();
bool InitCommandPool();
bool InitDefaultTexture();
bool InitDepthFormat();
bool IsDeviceSuitable(VkPhysicalDevice device);
bool CheckDeviceExtensionSupport(VkPhysicalDevice device);
public:
VkInstance m_VkInstance;
VkPhysicalDevice m_VkPhysicalDevice;
VkPhysicalDeviceProperties m_VkPhysicalDeviceProperties;
VkDevice m_VkDevice;
VkQueue m_VkGraphicsQueue;
VkCommandPool m_VkCommandPool;
MVulkanShaderCompiler m_ShaderCompiler;
MVulkanPipelineManager m_PipelineManager;
MVulkanObjectDestructor m_ObjectDestructor;
MVulkanBufferPool m_BufferPool;
VkFormat m_VkDepthTextureFormat;
MTexture m_WhiteTexture;
};
#endif
#endif | 37.786207 | 238 | 0.828983 | [
"vector"
] |
5f2f1e96c37ff9b348b8833d8ef4ccde959dfdd7 | 242 | h | C | common.h | rivergillis/chip-8 | ce49024cb97752fd8ab66ad041e86585d3a7a4ad | [
"MIT"
] | 9 | 2020-12-08T08:10:26.000Z | 2022-03-06T16:58:06.000Z | common.h | rivergillis/chip-8 | ce49024cb97752fd8ab66ad041e86585d3a7a4ad | [
"MIT"
] | null | null | null | common.h | rivergillis/chip-8 | ce49024cb97752fd8ab66ad041e86585d3a7a4ad | [
"MIT"
] | 2 | 2021-01-04T11:16:39.000Z | 2021-07-13T18:36:50.000Z | #ifndef C8_COMMON_H_
#define C8_COMMON_H_
#include <cstdint>
#include <memory>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <exception>
#include <stdexcept>
#include <cstring>
#include <iostream>
#include <vector>
#endif | 15.125 | 20 | 0.752066 | [
"vector"
] |
5f3230ef9431c8ab5eb0cec863209fade230e8a6 | 2,454 | h | C | src/samples/ParticleSystem/UpdaterLife.h | int-Frank/DgLib-deprecated | 2683c48d84b995b00c6fb13f9e02257d3c93e80c | [
"MIT"
] | null | null | null | src/samples/ParticleSystem/UpdaterLife.h | int-Frank/DgLib-deprecated | 2683c48d84b995b00c6fb13f9e02257d3c93e80c | [
"MIT"
] | null | null | null | src/samples/ParticleSystem/UpdaterLife.h | int-Frank/DgLib-deprecated | 2683c48d84b995b00c6fb13f9e02257d3c93e80c | [
"MIT"
] | null | null | null | #ifndef UPDATERLIFE_H
#define UPDATERLIFE_H
#include "particle_system/DgParticleData.h"
#include "particle_system/DgParticleUpdater.h"
//! Updates particle life, kills particles.
template<typename Real>
class UpdaterLife : public Dg::ParticleUpdater<Real>
{
public:
UpdaterLife() : Dg::ParticleUpdater<Real>() {}
~UpdaterLife() {}
UpdaterLife(UpdaterLife<Real> const & a_other) :Dg::ParticleUpdater<Real>(a_other) {}
UpdaterLife<Real> & operator=(UpdaterLife<Real> const & a_other)
{
Dg::ParticleUpdater<Real>::operator=(a_other);
return *this;
}
void UpdateNew(Dg::ParticleData<Real> &, int, Real);
void Update(Dg::ParticleData<Real> &, int, Real);
UpdaterLife<Real> * Clone() const { return new UpdaterLife<Real>(*this); }
};
template<typename Real>
void UpdaterLife<Real>::UpdateNew(Dg::ParticleData<Real> & a_data
, int a_start
, Real a_dt)
{
Dg::R3::Vector<Real> * pAccels = a_data.GetAcceleration();
Real * pLifes = a_data.GetLife();
Real * pLifeMaxes = a_data.GetLifeMax();
Real * pDLifes = a_data.GetDLife();
Real * ptimeSinceBirth = a_data.GetTimeSinceBirth();
if (ptimeSinceBirth == nullptr)
{
return;
}
int maxParCount = a_data.GetCountAlive();
if (pLifes && pLifeMaxes)
{
for (int i = maxParCount - 1; i >= a_start; --i)
{
pLifes[i] += ptimeSinceBirth[i];
if (pLifes[i] >= pLifeMaxes[i])
{
a_data.Kill(i);
}
}
maxParCount = a_data.GetCountAlive();
if (pDLifes)
{
for (int i = a_start; i < maxParCount; ++i)
{
pDLifes[i] = pLifes[i] / pLifeMaxes[i];
}
}
}
}
template<typename Real>
void UpdaterLife<Real>::Update(Dg::ParticleData<Real> & a_data
, int a_start
, Real a_dt)
{
Dg::R3::Vector<Real> * pAccels = a_data.GetAcceleration();
Real * pLifes = a_data.GetLife();
Real * pLifeMaxes = a_data.GetLifeMax();
Real * pDLifes = a_data.GetDLife();
int maxParCount = a_data.GetCountAlive();
if (pLifes && pLifeMaxes)
{
for (int i = maxParCount - 1; i >= a_start; --i)
{
pLifes[i] += a_dt;
if (pLifes[i] >= pLifeMaxes[i])
{
maxParCount = a_data.Kill(i);
}
}
if (pDLifes)
{
for (int i = a_start; i < maxParCount; ++i)
{
pDLifes[i] = pLifes[i] / pLifeMaxes[i];
}
}
}
}
#endif | 24.058824 | 87 | 0.595355 | [
"vector"
] |
5f580eade6bca46c10ec0008007f681d72cc4bc3 | 5,581 | h | C | Project/Temp/StagingArea/Data/il2cppOutput/mscorlib_System_Text_UTF32Encoding549530865MethodDeclarations.h | Yuunagi-Yu/NumberDisk | f1cf414dbfe8d0094d3ef11b37839f6caf58ae9f | [
"MIT"
] | null | null | null | Project/Temp/StagingArea/Data/il2cppOutput/mscorlib_System_Text_UTF32Encoding549530865MethodDeclarations.h | Yuunagi-Yu/NumberDisk | f1cf414dbfe8d0094d3ef11b37839f6caf58ae9f | [
"MIT"
] | null | null | null | Project/Temp/StagingArea/Data/il2cppOutput/mscorlib_System_Text_UTF32Encoding549530865MethodDeclarations.h | Yuunagi-Yu/NumberDisk | f1cf414dbfe8d0094d3ef11b37839f6caf58ae9f | [
"MIT"
] | null | null | null | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include <assert.h>
#include <exception>
// System.Text.UTF32Encoding
struct UTF32Encoding_t549530865;
// System.Char[]
struct CharU5BU5D_t1328083999;
// System.Byte[]
struct ByteU5BU5D_t3397334013;
// System.Text.Decoder
struct Decoder_t3792697818;
// System.Object
struct Il2CppObject;
// System.String
struct String_t;
#include "codegen/il2cpp-codegen.h"
#include "mscorlib_System_Object2689449295.h"
#include "mscorlib_System_String2029220233.h"
// System.Void System.Text.UTF32Encoding::.ctor()
extern "C" void UTF32Encoding__ctor_m422266633 (UTF32Encoding_t549530865 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void System.Text.UTF32Encoding::.ctor(System.Boolean,System.Boolean)
extern "C" void UTF32Encoding__ctor_m2711820969 (UTF32Encoding_t549530865 * __this, bool ___bigEndian0, bool ___byteOrderMark1, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void System.Text.UTF32Encoding::.ctor(System.Boolean,System.Boolean,System.Boolean)
extern "C" void UTF32Encoding__ctor_m3199945978 (UTF32Encoding_t549530865 * __this, bool ___bigEndian0, bool ___byteOrderMark1, bool ___throwOnInvalidCharacters2, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Int32 System.Text.UTF32Encoding::GetByteCount(System.Char[],System.Int32,System.Int32)
extern "C" int32_t UTF32Encoding_GetByteCount_m3183615393 (UTF32Encoding_t549530865 * __this, CharU5BU5D_t1328083999* ___chars0, int32_t ___index1, int32_t ___count2, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Int32 System.Text.UTF32Encoding::GetBytes(System.Char[],System.Int32,System.Int32,System.Byte[],System.Int32)
extern "C" int32_t UTF32Encoding_GetBytes_m2290150495 (UTF32Encoding_t549530865 * __this, CharU5BU5D_t1328083999* ___chars0, int32_t ___charIndex1, int32_t ___charCount2, ByteU5BU5D_t3397334013* ___bytes3, int32_t ___byteIndex4, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Int32 System.Text.UTF32Encoding::GetCharCount(System.Byte[],System.Int32,System.Int32)
extern "C" int32_t UTF32Encoding_GetCharCount_m3319809517 (UTF32Encoding_t549530865 * __this, ByteU5BU5D_t3397334013* ___bytes0, int32_t ___index1, int32_t ___count2, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Int32 System.Text.UTF32Encoding::GetChars(System.Byte[],System.Int32,System.Int32,System.Char[],System.Int32)
extern "C" int32_t UTF32Encoding_GetChars_m2511673789 (UTF32Encoding_t549530865 * __this, ByteU5BU5D_t3397334013* ___bytes0, int32_t ___byteIndex1, int32_t ___byteCount2, CharU5BU5D_t1328083999* ___chars3, int32_t ___charIndex4, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Int32 System.Text.UTF32Encoding::GetMaxByteCount(System.Int32)
extern "C" int32_t UTF32Encoding_GetMaxByteCount_m3742308917 (UTF32Encoding_t549530865 * __this, int32_t ___charCount0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Int32 System.Text.UTF32Encoding::GetMaxCharCount(System.Int32)
extern "C" int32_t UTF32Encoding_GetMaxCharCount_m677194067 (UTF32Encoding_t549530865 * __this, int32_t ___byteCount0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Text.Decoder System.Text.UTF32Encoding::GetDecoder()
extern "C" Decoder_t3792697818 * UTF32Encoding_GetDecoder_m2714144074 (UTF32Encoding_t549530865 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Byte[] System.Text.UTF32Encoding::GetPreamble()
extern "C" ByteU5BU5D_t3397334013* UTF32Encoding_GetPreamble_m767706727 (UTF32Encoding_t549530865 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Boolean System.Text.UTF32Encoding::Equals(System.Object)
extern "C" bool UTF32Encoding_Equals_m2227431860 (UTF32Encoding_t549530865 * __this, Il2CppObject * ___value0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Int32 System.Text.UTF32Encoding::GetHashCode()
extern "C" int32_t UTF32Encoding_GetHashCode_m4205784236 (UTF32Encoding_t549530865 * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Int32 System.Text.UTF32Encoding::GetByteCount(System.Char*,System.Int32)
extern "C" int32_t UTF32Encoding_GetByteCount_m77034086 (UTF32Encoding_t549530865 * __this, Il2CppChar* ___chars0, int32_t ___count1, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Int32 System.Text.UTF32Encoding::GetByteCount(System.String)
extern "C" int32_t UTF32Encoding_GetByteCount_m3218538734 (UTF32Encoding_t549530865 * __this, String_t* ___s0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Int32 System.Text.UTF32Encoding::GetBytes(System.Char*,System.Int32,System.Byte*,System.Int32)
extern "C" int32_t UTF32Encoding_GetBytes_m2093416998 (UTF32Encoding_t549530865 * __this, Il2CppChar* ___chars0, int32_t ___charCount1, uint8_t* ___bytes2, int32_t ___byteCount3, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Int32 System.Text.UTF32Encoding::GetBytes(System.String,System.Int32,System.Int32,System.Byte[],System.Int32)
extern "C" int32_t UTF32Encoding_GetBytes_m2073800022 (UTF32Encoding_t549530865 * __this, String_t* ___s0, int32_t ___charIndex1, int32_t ___charCount2, ByteU5BU5D_t3397334013* ___bytes3, int32_t ___byteIndex4, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.String System.Text.UTF32Encoding::GetString(System.Byte[],System.Int32,System.Int32)
extern "C" String_t* UTF32Encoding_GetString_m1168793734 (UTF32Encoding_t549530865 * __this, ByteU5BU5D_t3397334013* ___bytes0, int32_t ___index1, int32_t ___count2, const MethodInfo* method) IL2CPP_METHOD_ATTR;
| 82.073529 | 275 | 0.833363 | [
"object"
] |
5f6228ebd047695d5cd8a53c67dc5ea1ce7377aa | 3,491 | h | C | src/centerclustermapper.h | LaoZZZZZ/bartender-1.1 | ddfb2e52bdf92258dd837ab8ee34306e9fb45b81 | [
"MIT"
] | 22 | 2016-08-11T06:16:25.000Z | 2022-02-22T00:06:59.000Z | src/centerclustermapper.h | LaoZZZZZ/bartender-1.1 | ddfb2e52bdf92258dd837ab8ee34306e9fb45b81 | [
"MIT"
] | 9 | 2016-12-08T12:42:38.000Z | 2021-12-28T20:12:15.000Z | src/centerclustermapper.h | LaoZZZZZ/bartender-1.1 | ddfb2e52bdf92258dd837ab8ee34306e9fb45b81 | [
"MIT"
] | 8 | 2017-06-26T13:15:06.000Z | 2021-11-12T18:39:54.000Z | #ifndef CENTERCLUSTERMAPPER_H
#define CENTERCLUSTERMAPPER_H
#include "typdefine.h"
#include "barcodecluster.hpp"
#include <cassert>
#include <list>
#include <memory>
#include <stdexcept>
#include <string>
#include <unordered_map>
#include <vector>
namespace barcodeSpace {
class CenterClusterMapper
{
public:
typedef BarcodeCluster Cluster;
CenterClusterMapper(int max_id);
const std::list<std::string>& myCenter(size_t c_id) {
return _cluster_2_center[c_id];
}
// Checks if it has the center in the dictionary.
bool hasCenter(const std::string& c) {
return _center_2_cluster.find(c) != _center_2_cluster.end();
}
// Checks if it has the cluster.
bool hasCluster(size_t c_id) {
if (c_id >= _cluster_2_instance.size()) {
throw std::out_of_range("The id exceeds the maximum possible id.");
}
return _cluster_2_instance[c_id].get() != NULL;
}
// RClusterResultProcessoremoves the cluster and its centers.
void removeCluster(size_t cid) {
if (_numOfClusters <= 0) {
return;
}
assert(cid < _cluster_2_instance.size());
if (_cluster_2_instance[cid].get()) {
_cluster_2_instance[cid].reset();
for (const auto& c : _cluster_2_center[cid]) {
_center_2_cluster.erase(c);
}
_cluster_2_center[cid].clear();
}
_numOfClusters -= 1;
}
std::shared_ptr<Cluster> getClusterByCenter(const std::string& c) {
if (hasCenter(c))
return _cluster_2_instance[_center_2_cluster[c]];
else {
return NULL;
}
}
// Gets the cluster pointer.
const std::shared_ptr<Cluster>& getClusterByID(size_t id) {
if (id >= _cluster_2_instance.size()) {
throw std::out_of_range("The id exceeds the maximum possible id.");
}
return _cluster_2_instance[id];
}
// Adds mapping pair between the cluster and its centers.
void addPair(const std::shared_ptr<Cluster>& cl, const std::vector<std::string>& centers) {
assert(cl.get());
size_t id = cl->ClusterID();
if (id >= _cluster_2_instance.size()) {
throw std::out_of_range("The id exceeds the maximum possible id.");
}
if (_cluster_2_instance[id].get()) {
throw std::runtime_error("Already have cluster " + std::to_string(id) + "when adding it to linkmapper!\n");
}
_numOfClusters += 1;
_cluster_2_instance[id] = cl;
for (const auto& c : centers) {
_cluster_2_center[id].push_back(c);
if (_center_2_cluster.find(c) != _center_2_cluster.end() &&
_center_2_cluster[c] != cl->ClusterID()) {
throw std::runtime_error("Two custers share the same center(cluster ids are: " + std::to_string(_center_2_cluster[c]) +
" and " + std::to_string(cl->ClusterID()) + ").\n");
}
_center_2_cluster[c] = id;
}
}
size_t numberOfClusters() const {return _numOfClusters;}
size_t size() const {
return _cluster_2_instance.size();
}
private:
std::vector<std::list<std::string>> _cluster_2_center;
std::unordered_map<std::string, int> _center_2_cluster;
std::vector<std::shared_ptr<Cluster>> _cluster_2_instance;
size_t _numOfClusters;
};
} // namespace barcodeSpace
#endif // CENTERCLUSTERMAPPER_H
| 32.324074 | 135 | 0.615583 | [
"vector"
] |
5f71b0b5efe655f220d7edbed190cdd93ba6933d | 6,844 | c | C | src/mca/plm/alps/plm_alps_component.c | angainor/prrte | fce7a49e6527143eebda13d34dabc9a55c6e1f25 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | src/mca/plm/alps/plm_alps_component.c | angainor/prrte | fce7a49e6527143eebda13d34dabc9a55c6e1f25 | [
"BSD-3-Clause-Open-MPI"
] | 1 | 2020-03-11T18:18:13.000Z | 2020-03-11T18:18:13.000Z | src/mca/plm/alps/plm_alps_component.c | AboorvaDevarajan/prrte | 6bab23ee556e7d30586c951808a340cd0f787989 | [
"BSD-3-Clause-Open-MPI"
] | null | null | null | /* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil -*- */
/*
* Copyright (c) 2004-2008 The Trustees of Indiana University and Indiana
* University Research and Technology
* Corporation. All rights reserved.
* Copyright (c) 2004-2005 The University of Tennessee and The University
* of Tennessee Research Foundation. All rights
* reserved.
* Copyright (c) 2004-2005 High Performance Computing Center Stuttgart,
* University of Stuttgart. All rights reserved.
* Copyright (c) 2004-2005 The Regents of the University of California.
* All rights reserved.
* Copyright (c) 2015 Los Alamos National Security, LLC. All rights
* reserved.
* Copyright (c) 2017-2019 Intel, Inc. All rights reserved.
* Copyright (c) 2019 Research Organization for Information Science
* and Technology (RIST). All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*
* These symbols are in a file by themselves to provide nice linker
* semantics. Since linkers generally pull in symbols by object
* files, keeping these symbols as the only symbols in this file
* prevents utility programs such as "ompi_info" from having to import
* entire components just to query their version and parameters.
*/
#include "prrte_config.h"
#include "constants.h"
#include "src/mca/base/prrte_mca_base_var.h"
#include "src/runtime/prrte_globals.h"
#include "src/mca/plm/plm.h"
#include "src/mca/plm/base/base.h"
#include "src/mca/plm/base/plm_private.h"
#include "plm_alps.h"
/*
* Public string showing the plm ompi_alps component version number
*/
const char *prrte_plm_alps_component_version_string =
"PRRTE alps plm MCA component version " PRRTE_VERSION;
/*
* Local functions
*/
static int plm_alps_register(void);
static int plm_alps_open(void);
static int plm_alps_close(void);
static int prrte_plm_alps_component_query(prrte_mca_base_module_t **module, int *priority);
/*
* Instantiate the public struct with all of our public information
* and pointers to our public functions in it
*/
prrte_plm_alps_component_t prrte_plm_alps_component = {
{
/* First, the mca_component_t struct containing meta
information about the component itself */
.base_version = {
PRRTE_PLM_BASE_VERSION_2_0_0,
/* Component name and version */
.mca_component_name = "alps",
PRRTE_MCA_BASE_MAKE_VERSION(component, PRRTE_MAJOR_VERSION, PRRTE_MINOR_VERSION,
PRRTE_RELEASE_VERSION),
/* Component open and close functions */
.mca_open_component = plm_alps_open,
.mca_close_component = plm_alps_close,
.mca_query_component = prrte_plm_alps_component_query,
.mca_register_component_params = plm_alps_register,
},
.base_data = {
/* The component is checkpoint ready */
PRRTE_MCA_BASE_METADATA_PARAM_CHECKPOINT
},
}
/* Other prrte_plm_alps_component_t items -- left uninitialized
here; will be initialized in plm_alps_open() */
};
static int plm_alps_register(void)
{
prrte_mca_base_component_t *comp = &prrte_plm_alps_component.super.base_version;
prrte_plm_alps_component.debug = false;
(void) prrte_mca_base_component_var_register (comp, "debug", "Enable debugging of alps plm",
PRRTE_MCA_BASE_VAR_TYPE_BOOL, NULL, 0, 0,
PRRTE_INFO_LVL_9,
PRRTE_MCA_BASE_VAR_SCOPE_READONLY,
&prrte_plm_alps_component.debug);
if (prrte_plm_alps_component.debug == 0) {
prrte_plm_alps_component.debug = prrte_debug_flag;
}
prrte_plm_alps_component.priority = 100;
(void) prrte_mca_base_component_var_register (comp, "priority", "Default selection priority",
PRRTE_MCA_BASE_VAR_TYPE_INT, NULL, 0, 0,
PRRTE_INFO_LVL_9,
PRRTE_MCA_BASE_VAR_SCOPE_READONLY,
&prrte_plm_alps_component.priority);
prrte_plm_alps_component.aprun_cmd = "aprun";
(void) prrte_mca_base_component_var_register (comp, "aprun", "Command to run instead of aprun",
PRRTE_MCA_BASE_VAR_TYPE_STRING, NULL, 0, 0,
PRRTE_INFO_LVL_9,
PRRTE_MCA_BASE_VAR_SCOPE_READONLY,
&prrte_plm_alps_component.aprun_cmd);
prrte_plm_alps_component.custom_args = NULL;
(void) prrte_mca_base_component_var_register (comp, "args", "Custom arguments to aprun",
PRRTE_MCA_BASE_VAR_TYPE_STRING, NULL, 0, 0,
PRRTE_INFO_LVL_9,
PRRTE_MCA_BASE_VAR_SCOPE_READONLY,
&prrte_plm_alps_component.custom_args);
return PRRTE_SUCCESS;
}
static int plm_alps_open(void)
{
return PRRTE_SUCCESS;
}
static int prrte_plm_alps_component_query(prrte_mca_base_module_t **module, int *priority)
{
#if CRAY_WLM_DETECT
char slurm[]="SLURM";
char *wlm_detected = NULL;
wlm_detected = wlm_detect_get_active();
/*
* The content of wlm_detected.h indicates wlm_detect_get_active
* may return NULL upon failure. Resort to the suggested plan
* B in that event.
*/
if (NULL == wlm_detected) {
wlm_detected = (char *)wlm_detect_get_default();
PRRTE_OUTPUT_VERBOSE((10, prrte_plm_base_framework.framework_output,
"%s plm:alps: wlm_detect_get_active returned NULL, using %s",
PRRTE_NAME_PRINT(PRRTE_PROC_MY_NAME), wlm_detected));
}
if((NULL != wlm_detected) && !strcmp(slurm, wlm_detected)) {
/* we are in a Cray SLURM environment, so we don't want
* this plm component */
*priority = 0;
*module = NULL;
return PRRTE_ERROR;
}
#endif
*priority = prrte_plm_alps_component.priority;
*module = (prrte_mca_base_module_t *) &prrte_plm_alps_module;
PRRTE_OUTPUT_VERBOSE((1, prrte_plm_base_framework.framework_output,
"%s plm:alps: available for selection",
PRRTE_NAME_PRINT(PRRTE_PROC_MY_NAME)));
return PRRTE_SUCCESS;
}
static int plm_alps_close(void)
{
return PRRTE_SUCCESS;
}
| 36.994595 | 99 | 0.620982 | [
"object"
] |
5f7be526eb81e74215a118a6fde3e2e752828226 | 11,418 | h | C | SWIG_CGAL/Point_set_3/Point_set_3.h | sloriot/cgal-swig-bindings | c9c5afdf64fa0c52f9c3785173159167ab2b3163 | [
"BSL-1.0"
] | null | null | null | SWIG_CGAL/Point_set_3/Point_set_3.h | sloriot/cgal-swig-bindings | c9c5afdf64fa0c52f9c3785173159167ab2b3163 | [
"BSL-1.0"
] | null | null | null | SWIG_CGAL/Point_set_3/Point_set_3.h | sloriot/cgal-swig-bindings | c9c5afdf64fa0c52f9c3785173159167ab2b3163 | [
"BSL-1.0"
] | null | null | null | // ------------------------------------------------------------------------------
// Copyright (c) 2020 GeometryFactory (FRANCE)
// Distributed under the Boost Software License, Version 1.0. (See accompany-
// ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// ------------------------------------------------------------------------------
#ifndef SWIG_CGAL_POINT_SET_3_POINT_SET_3_H
#define SWIG_CGAL_POINT_SET_3_POINT_SET_3_H
#include <boost/static_assert.hpp>
#include <SWIG_CGAL/Common/Reference_wrapper.h>
#include <SWIG_CGAL/Common/Macros.h>
#include <SWIG_CGAL/Kernel/Point_3.h>
#include <SWIG_CGAL/Kernel/Vector_3.h>
#include <SWIG_CGAL/Common/Iterator.h>
#include <SWIG_CGAL/Point_set_3/typedefs.h>
#include <SWIG_CGAL/Point_set_3/Point_set_3_Property_map.h>
#include <sstream>
#include <fstream>
template <typename Point_set_base, typename T>
struct Nested_iterator_helper
{
typedef typename Point_set_base::template Property_range<T>::const_iterator type;
};
template <typename Point_set_base>
class Point_set_3_wrapper
{
protected:
std::shared_ptr<Point_set_base> data_sptr;
public:
#ifndef SWIG
typedef Point_set_base cpp_base;
const cpp_base& get_data() const { return *data_sptr; }
cpp_base& get_data() { return *data_sptr; }
std::shared_ptr<cpp_base> shared_ptr() { return data_sptr; }
#endif
typedef Point_set_3_wrapper<Point_set_base> Self;
typedef SWIG_CGAL_Iterator<typename Point_set_base::const_iterator, int> iterator;
typedef SWIG_CGAL_Iterator<typename Point_set_base::Point_range::const_iterator, Point_3> Point_iterator;
typedef SWIG_CGAL_Iterator<typename Point_set_base::Vector_range::const_iterator, Vector_3> Vector_iterator;
typedef SWIG_CGAL_Iterator<typename Nested_iterator_helper<Point_set_base, int>::type, int> Int_iterator;
typedef SWIG_CGAL_Iterator<typename Nested_iterator_helper<Point_set_base, double>::type, double> Float_iterator;
typedef SWIG_Point_set_3::CGAL_Property_map<Point_set_base, Point_3> Point_map;
typedef SWIG_Point_set_3::CGAL_Property_map<Point_set_base, Vector_3> Vector_map;
typedef SWIG_Point_set_3::CGAL_Property_map<Point_set_base, int> Int_map;
typedef SWIG_Point_set_3::CGAL_Property_map<Point_set_base, double> Float_map;
Point_set_3_wrapper(bool with_normal_map = false) : data_sptr (new cpp_base(with_normal_map)) { }
Point_set_3_wrapper(const std::string& file) : data_sptr (new cpp_base()) { read(file); }
SWIG_CGAL_FORWARD_CALL_0(bool, is_empty)
SWIG_CGAL_FORWARD_CALL_0(bool, empty)
SWIG_CGAL_FORWARD_CALL_0(int, number_of_points)
SWIG_CGAL_FORWARD_CALL_0(int, size)
bool join (Self other)
{
return data_sptr->join (other.get_data());
}
SWIG_CGAL_FORWARD_CALL_0(void, clear)
SWIG_CGAL_FORWARD_CALL_0(void, clear_properties)
SWIG_CGAL_FORWARD_CALL_1(void, reserve, int)
SWIG_CGAL_FORWARD_CALL_1(void, resize, int)
int insert ()
{
return (int)(*(data_sptr->insert()));
}
int insert (const Point_3& point)
{
return (int)(*(data_sptr->insert(point.get_data())));
}
int insert (const Point_3& point, const Vector_3& normal)
{
return (int)(*(data_sptr->insert(point.get_data(), normal.get_data())));
}
int insert (const Self& other, int idx)
{
return (int)(*(data_sptr->insert(other.get_data(), idx)));
}
void insert_range (boost::shared_ptr<std::vector<EPIC_Kernel::Point_3> > range)
{
data_sptr->reserve (range->size());
for (const auto& p : *range)
data_sptr->insert(p);
}
iterator indices() { return iterator (get_data().begin(), get_data().end()); }
SWIG_CGAL_FORWARD_CALL_1(Point_3, point, int)
SWIG_CGAL_FORWARD_CALL_1(Vector_3, normal, int)
SWIG_CGAL_FORWARD_CALL_1(void, remove, int)
// void remove(iterator, iterator)
SWIG_CGAL_FORWARD_CALL_1(bool, is_removed, int)
iterator garbage() { return iterator (get_data().garbage_begin(), get_data().garbage_end()); }
SWIG_CGAL_FORWARD_CALL_0(int, number_of_removed_points)
SWIG_CGAL_FORWARD_CALL_0(int, garbage_size)
SWIG_CGAL_FORWARD_CALL_0(bool, has_garbage)
SWIG_CGAL_FORWARD_CALL_0(void, collect_garbage)
SWIG_CGAL_FORWARD_CALL_0(void, cancel_removals)
bool has_int_map (const std::string& name)
{
return data_sptr->template has_property_map<int>(name);
}
Int_map add_int_map (const std::string& name, int default_value = 0)
{
return Int_map(data_sptr->template add_property_map<int>(name, default_value));
}
Int_map int_map (const std::string& name)
{
return Int_map(data_sptr->template property_map<int>(name));
}
bool remove_int_map (Int_map map)
{
return data_sptr->remove_property_map (map.get_data());
}
bool has_float_map (const std::string& name)
{
return data_sptr->template has_property_map<double>(name);
}
Float_map add_float_map (const std::string& name, double default_value = 0.0)
{
return Float_map(data_sptr->template add_property_map<double>(name, default_value));
}
Float_map float_map (const std::string& name)
{
return Float_map(data_sptr->template property_map<double>(name));
}
bool remove_float_map (Float_map map)
{
return data_sptr->remove_property_map (map.get_data());
}
SWIG_CGAL_FORWARD_CALL_0(bool, has_normal_map)
Vector_map add_normal_map() { return Vector_map (data_sptr->add_normal_map()); }
Vector_map normal_map() { return Vector_map(data_sptr->normal_map(), data_sptr->has_normal_map()); }
SWIG_CGAL_FORWARD_CALL_0(bool, remove_normal_map)
Point_map point_map() { return Point_map(data_sptr->point_map(), true); }
void copy_properties (const Self& other)
{
data_sptr->copy_properties (other.get_data());
}
boost::shared_ptr<std::vector<std::string> > properties() const
{
return boost::shared_ptr<std::vector<std::string> >
(new std::vector<std::string>(data_sptr->properties()));
}
SWIG_CGAL_FORWARD_CALL_0(std::string, info)
Int_iterator range (Int_map map)
{
return Int_iterator (get_data().range(map.get_data()).begin(),
get_data().range(map.get_data()).end());
}
Float_iterator range (Float_map map)
{
return Float_iterator (get_data().range(map.get_data()).begin(),
get_data().range(map.get_data()).end());
}
Point_iterator points() const { return Point_iterator (get_data().points().begin(), get_data().points().end()); }
Vector_iterator normals() const { return Vector_iterator (get_data().normals().begin(), get_data().normals().end()); }
void read (const std::string& file)
{
std::ifstream ifile (file, std::ios_base::binary);
ifile >> *data_sptr;
convert_input_properties();
}
bool write (const std::string& file)
{
std::string extension (file.begin() + file.size() - 3, file.end());
std::transform(extension.begin(), extension.end(), extension.begin(),
[](unsigned char c){ return std::tolower(c); });
std::ofstream ofile (file, std::ios_base::binary);
if (extension == "xyz")
{
ofile.precision(18);
return CGAL::write_xyz_point_set (ofile, *data_sptr);
}
if (extension == "off")
{
ofile.precision(18);
return CGAL::write_off_point_set (ofile, *data_sptr);
}
if (extension == "ply")
{
convert_ply_output_properties();
CGAL::set_binary_mode(ofile);
bool out = CGAL::write_ply_point_set (ofile, *data_sptr);
convert_input_properties();
return out;
}
#ifdef CGAL_LINKED_WITH_LASLIB
if (extension == "las")
{
convert_las_output_properties();
bool out = CGAL::write_las_point_set (ofile, *data_sptr);
convert_input_properties();
return out;
}
std::cerr << "Error: unknown extension " << extension << ", possible values are xyz, off, ply or las" << std::endl;
#else
std::cerr << "Error: unknown extension " << extension << ", possible values are xyz, off or ply" << std::endl;
#endif
return false;
}
private:
void convert_input_properties()
{
std::vector<std::string> properties = data_sptr->properties();
for (const std::string& p : properties)
{
if (convert_map<char, int>(p))
continue;
if (convert_map<signed char, int>(p))
continue;
if (convert_map<unsigned char, int>(p))
continue;
if (convert_map<short, int>(p))
continue;
if (convert_map<unsigned short, int>(p))
continue;
if (convert_map<unsigned int, int>(p))
continue;
if (convert_map<float, double>(p))
continue;
}
}
void convert_ply_output_properties()
{
std::vector<std::string> properties = data_sptr->properties();
for (const std::string& p : properties)
if (p == "R" || p == "r" || p == "red" ||
p == "G" || p == "g" || p == "green" ||
p == "B" || p == "b" || p == "blue" ||
p == "A" || p == "a" || p == "alpha")
convert_map<int, unsigned char>(p);
}
void convert_las_output_properties()
{
std::vector<std::string> properties = data_sptr->properties();
for (const std::string& p : properties)
{
if (p == "intensity")
convert_map<int, unsigned short>(p);
else if (p == "return_number")
convert_map<int, unsigned char>(p);
else if (p == "number_of_returns")
convert_map<int, unsigned char>(p);
else if (p == "scan_direction_flag")
convert_map<int, unsigned char>(p);
else if (p == "edge_of_flight_line")
convert_map<int, unsigned char>(p);
else if (p == "classification")
convert_map<int, unsigned char>(p);
else if (p == "synthetic_flag")
convert_map<int, unsigned char>(p);
else if (p == "keypoint_flag")
convert_map<int, unsigned char>(p);
else if (p == "withheld_flag")
convert_map<int, unsigned char>(p);
else if (p == "scan_angle")
convert_map<double, float>(p);
else if (p == "user_data")
convert_map<int, unsigned char>(p);
else if (p == "point_source_ID")
convert_map<int, unsigned short>(p);
else if (p == "deleted_flag")
convert_map<int, unsigned int>(p);
else if (p == "R")
convert_map<int, unsigned short>(p);
else if (p == "G")
convert_map<int, unsigned short>(p);
else if (p == "B")
convert_map<int, unsigned short>(p);
else if (p == "I")
convert_map<int, unsigned short>(p);
}
}
template <typename Input, typename Output>
bool convert_map (const std::string& name)
{
typename Point_set_base::template Property_map<Input> imap;
bool okay;
std::tie (imap, okay) = data_sptr->template property_map<Input>(name);
if (!okay)
return false;
typename Point_set_base::template Property_map<Output> omap;
std::tie (omap, okay) = data_sptr->template add_property_map<Output>(name);
if (!okay)
return false;
for (typename Point_set_base::Index idx : *data_sptr)
omap[idx] = static_cast<Output>(imap[idx]);
data_sptr->remove_property_map(imap);
return true;
}
};
namespace CGAL { namespace Point_set_processing_3 {
template <typename T> class GetFt;
template <typename Point_set_base>
class GetFT<Point_set_3_wrapper<Point_set_base> >
{
public:
typedef double type;
};
} }
#endif // SWIG_CGAL_POINT_SET_3_POINT_SET_3_H
| 32.529915 | 120 | 0.670608 | [
"vector",
"transform"
] |
bec179daeb17f4067004a4c4f3f3373289e2a3c5 | 2,208 | h | C | include/shrike/http/httprequest.h | tr03p/shrike | 9ad29b4b0f1fa95f68f5029612ed8853e32a7909 | [
"MIT"
] | null | null | null | include/shrike/http/httprequest.h | tr03p/shrike | 9ad29b4b0f1fa95f68f5029612ed8853e32a7909 | [
"MIT"
] | null | null | null | include/shrike/http/httprequest.h | tr03p/shrike | 9ad29b4b0f1fa95f68f5029612ed8853e32a7909 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2018 Willem Kemp, willem@eneritix.co.za
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 SHRIKE_HTTPREQUEST_H
#define SHRIKE_HTTPREQUEST_H
#include <map>
#include <string>
#include <vector>
namespace shrike
{
class http_request
{
public:
http_request(const std::string& uri);
http_request(const std::string& uri, const std::string& data);
http_request(const std::string& uri, const std::vector<uint8_t>& data);
std::string uri() const { return _uri; }
std::vector<std::string> uriPath() const { return _uri_path; }
void set_header(const std::string& key, const std::string& value);
std::string header(const std::string& name) const;
const std::map<std::string, std::string>& headers() const;
void set_parameter(const std::string& key, const std::string& value);
std::string parameter(const std::string& name) const;
const std::string parameter_string() const;
const std::vector<uint8_t>& data() const { return _data; }
const std::string data_to_string() const;
private:
std::string _uri;
std::vector<std::string> _uri_path;
std::map<std::string, std::string> _headers;
std::map<std::string, std::string> _parameters;
std::vector<uint8_t> _data;
};
}
#endif
| 32.955224 | 79 | 0.755435 | [
"vector"
] |
bec3fcc0afcc913eee0c74142624fdcbec1450b2 | 383 | h | C | RayTracerChallengev3/src/Shapes/Plane.h | adamkunzler/RayTracerChallengeCpp | 81cda1c9b3a8f88fff314ec4798a10b6752f3396 | [
"MIT"
] | null | null | null | RayTracerChallengev3/src/Shapes/Plane.h | adamkunzler/RayTracerChallengeCpp | 81cda1c9b3a8f88fff314ec4798a10b6752f3396 | [
"MIT"
] | null | null | null | RayTracerChallengev3/src/Shapes/Plane.h | adamkunzler/RayTracerChallengeCpp | 81cda1c9b3a8f88fff314ec4798a10b6752f3396 | [
"MIT"
] | null | null | null | #pragma once
namespace RayTracer
{
/// <summary>
/// Represents an XZ plane
/// </summary>
struct Plane : public IShape
{
Plane() { }
Vector4 localNormalAt(const Point4& localPoint, const Intersection& i) const;
void localIntersectBy(const Ray& localRay, std::vector<std::shared_ptr<Intersection>>& intersections) const;
BoundingBox localBounds() const;
};
}
| 20.157895 | 110 | 0.699739 | [
"vector"
] |
bec962dd1180a29210c432c70e18133f8c17041f | 26,301 | h | C | src/MeatWagons/MeatWagons.h | motapinto/meat-wagons | 4d5e5a37135e488fe4dd1c093602aae6bce73f55 | [
"MIT"
] | null | null | null | src/MeatWagons/MeatWagons.h | motapinto/meat-wagons | 4d5e5a37135e488fe4dd1c093602aae6bce73f55 | [
"MIT"
] | null | null | null | src/MeatWagons/MeatWagons.h | motapinto/meat-wagons | 4d5e5a37135e488fe4dd1c093602aae6bce73f55 | [
"MIT"
] | null | null | null | #pragma once
#ifndef MEAT_WAGONS_MEATWAGONS_H
#define MEAT_WAGONS_MEATWAGONS_H
#include <unordered_set>
#include <set>
#include <time.h>
#include <algorithm>
#include "Request.h"
#include "../Graph/Reader.h"
#include "../GraphViewer/GraphVisualizer.h"
#include "Wagon.h"
bool compareRequests(Request* r1, Request* r2){
return r1->getArrival() < r2->getArrival();
}
class MeatWagons {
private:
int central;
Graph *graph = nullptr;
vector<Vertex*> pointsOfInterest;
string graphName;
multiset<Wagon> wagons;
multiset<Request*> requests;
multiset<Request*> constantRequests;
int zoneMaxDist;
bool processed = false;
const static int averageVelocity = 9;
public:
GraphVisualizer *viewer = new GraphVisualizer(600, 600);
MeatWagons(const int wagons) {
for(int i = 0; i < wagons; i++){
this->wagons.insert(Wagon(i, 5));
}
this->zoneMaxDist = 2000;
}
int getCentral() const;
bool setCentral(const int &id);
string getGraphName() const;
int getMaxDist() const;
void setMaxDist(const int max);
void setWagons(const int n, const int capacity);
Graph* getGraph() const;
multiset<Wagon> getWagons() const;
void addWagon(const int capacity);
void removeWagon(const int id);
multiset<Request*> getRequests() const;
multiset<Request*> getConstantRequests() const;
bool setGraph(const string path);
bool preProcess(const int node, const bool draw);
bool shortestPath(const int option, const int origin, const int dest);
multiset<Wagon>::iterator getWagon();
bool deliver(const int iteration);
int chooseDropOff(const vector<Vertex*> &pickupNodes);
vector<Request*> groupRequests(const int capacity);
Vertex* getNearestNeighbour(Vertex *node, const vector<Vertex*> &neighbours);
int tspPath(vector<Vertex*> &tspNodes, vector<Request *> reqs, vector<Edge> &tspPath, int dropOffNode, Time& startTime);
Delivery* drawDeliveriesFromThread(int wagonIndex, int deliveryIndex);
bool drawDeliveries(int wagonIndex, int deliveryIndex);
Request* findRequest(Vertex * vert, vector<Request *> requests);
bool firstIteration();
bool secondIteration();
bool thirdIteration();
int objectiveFunction();
//auxiliar functions
bool getViewerStatus(string &status);
void setViewerStatus(bool status);
};
int MeatWagons::getCentral() const {
return this->central;
}
bool MeatWagons::setCentral(const int &id) {
if(this->graph->findVertex(id) == nullptr) return false;
this->central = id;
return true;
}
string MeatWagons::getGraphName() const {
return this->graphName;
}
int MeatWagons::getMaxDist() const {
return this->zoneMaxDist;
}
void MeatWagons::setMaxDist(const int max) {
this->zoneMaxDist = max;
}
Graph* MeatWagons::getGraph() const {
return this->graph;
}
multiset<Wagon> MeatWagons::getWagons() const {
return this->wagons;
}
void MeatWagons::setWagons(const int n, const int capacity) {
this->wagons.clear();
for(int i=0; i < n; ++i) {
this->wagons.insert(Wagon(i, capacity));
}
}
void MeatWagons::addWagon(const int capacity) {
wagons.insert(Wagon(wagons.size(), capacity));
}
void MeatWagons::removeWagon(const int id) {
for (auto wit = wagons.begin(); wit != wagons.end(); wit++)
if (id == wit->getId()) {
wagons.erase(Wagon(id, wit->getCapacity()));
return;
}
}
multiset<Request*> MeatWagons::getRequests() const {
return this->requests;
}
multiset<Request*> MeatWagons::getConstantRequests() const {
return this->constantRequests;
}
/**
* @param graphPath path to graph
* @return true upon success
*/
bool MeatWagons::setGraph(const string graphPath) {
Reader graphReader = Reader(graphPath);
Graph* graphRead = new Graph();
if(!graphReader.readGraph(graphRead, central))
return false;
if(!graphReader.readRequests(requests))
return false;
this->constantRequests = requests;
this->processed = false;
this->graph = graphRead;
this->graphName = graphPath.substr(graphPath.find_last_of('/') + 1);
this->viewer->drawFromThread(this->graph);
this->processed = false;
return true;
}
/**
* Pre processes graph and eliminates all the requests in which the destination is a node that was removed
* after the pre processement of the graph
* @param node to be processed
* @return
*/
bool MeatWagons::preProcess(const int node, const bool draw) {
if(this->graph == nullptr) return false;
if(!this->graph->preProcess(node)) return false;
if(!this->graph->dijkstraOriginal(central)) return false;
for(int i = 0; i < this->requests.size(); i++) {
auto it = next(this->requests.begin(), i);
Request *r = *it;
Vertex *vert = this->graph->findVertex((r)->getDest());
if(vert == nullptr) {
this->requests.erase(it);
i--;
} else {
this->pointsOfInterest.push_back(vert);
}
}
this->processed = true;
if(draw) this->viewer->drawFromThread(this->graph);
return true;
}
/**
* @brief Calculates the shortest path from one point to another with different algorithms
* @param option - integer representing the algorithm to be used
* @param origin - start point to calculate the distance
* @param dest - destination of the path
*/
bool MeatWagons::shortestPath(const int option, const int origin, const int dest) {
if(this->graph == nullptr) return false;
unordered_set<int> processedEdges, processedEdgesInv;
switch (option) {
case 1: if (!this->graph->dijkstra(origin, dest, processedEdges)) return false; break;
case 2: if (!this->graph->dijkstraOrientedSearch(origin, dest, processedEdges)) return false; break;
case 3: if (!this->graph->dijkstraBidirectional(origin, dest, processedEdges, processedEdgesInv)) return false; break;
}
vector<Edge> edges;
this->graph->getPathTo(dest, edges);
this->viewer->drawShortestPathFromThread(processedEdges, processedEdgesInv, edges, this->graph);
return true;
}
/**
* Controls which iteration is to be used
* @param iteration - number of the iteration to use
*/
bool MeatWagons::deliver(int iteration) {
if(!this->processed) this->preProcess(central, false);
if(this->constantRequests.size() == 0) return false;
if(this->requests.size() == 0) {
this->requests = this->constantRequests;
for (int i = 0; i < this->requests.size(); i++) {
auto it = next(this->requests.begin(), i);
Request *r = *it;
Vertex *vert = this->graph->findVertex((r)->getDest());
if (vert == nullptr) {
this->requests.erase(it);
i--;
}
else this->pointsOfInterest.push_back(vert);
}
}
switch (iteration) {
case 1: return this->firstIteration();
case 2: return this->secondIteration();
case 3: return this->thirdIteration();
default: return false;
}
}
/**
* @brief Generates a random dropOff
* @param pickupNodes - nodes that cannot be used as drop off point
* @return an integer that represents the id of the drop off vertex
*/
int MeatWagons::chooseDropOff(const vector<Vertex*> &pickupNodes) {
srand((unsigned) time(0));
int id, randomId;
while(true){
randomId = (rand() % this->requests.size());
id = this->pointsOfInterest.at(randomId)->getId();
if(id == central) continue;
auto it = find_if(begin(pickupNodes), end(pickupNodes), [=](const Vertex* v) {
return v->getId() == id && (find(begin(pickupNodes), end(pickupNodes), v) != pickupNodes.end());
});
if(it != pickupNodes.end()) continue;
return id;
}
}
/**
* @brief Groups a number of requests together, based on their distance to one another
* @param capacity - number of requests to be grouped
* @return a vector containing pointers to the requests that were grouped
*/
vector<Request *> MeatWagons::groupRequests(const int capacity){
// Initialize the vector where we will put the grouped requests
vector <Request *> group;
int max_dist = 0, dist, pos = 0, max_dist_request_pos = 0;
auto it = requests.begin();
// We start with the first request since they are ordered by the arrival
Vertex* initial_vert = this->graph->findVertex((*it)->getDest());
group.push_back((*it));
it++;
// Iterate over the requests to find the nearest to the first one
while(it != requests.end()) {
// Get the vertex of the pick up node related to the request
Vertex *vert = this->graph->findVertex((*it)->getDest());
// Calculate its distance to the first request
dist = vert->getPosition().euclideanDistance(initial_vert->getPosition());
if(dist >= this->zoneMaxDist) { it++; continue; };
// If the vector as less requests then the capacity we can just add it to the vector
if(group.size() < capacity) {
group.push_back(*it);
pos++;
// Save the one that as the biggest distance to the first request
if(dist > max_dist) {
max_dist = dist;
max_dist_request_pos = pos;
}
}
else if(dist < max_dist) {
// Remove the request that has the biggest distance to the first request
// Save the requests from the first position to the position of the request that has the biggest distance
vector <Request *> groupInit;
groupInit.assign(group.begin(), group.begin() + max_dist_request_pos);
// Save the requests from (not including) the request that has the biggest distance to the last one
vector <Request *> groupFinal;
groupFinal.assign(group.begin() + max_dist_request_pos + 1, group.end());
// Clear the grouped requests and add the all the requests to it except the one that has the biggest distance
// It has to be done this way because we were working with pointer and using group.erase() would delete the request itself
group.clear();
group.insert(group.end(), groupInit.begin(), groupInit.end());
group.insert(group.end(), groupFinal.begin(), groupFinal.end());
// Assume the new request has the biggest distance to the first request
max_dist = dist;
max_dist_request_pos = pos;
// Check if there is a request with a bigger distance then the new request
for(auto itr = 0; itr < group.size(); itr++) {
auto *vertex = this->graph->findVertex(group[0]->getDest());
dist = vertex->getPosition().euclideanDistance(initial_vert->getPosition());
if(dist > max_dist) {
max_dist = dist;
max_dist_request_pos = itr;
}
}
// Put the new request into the vector
group.push_back(*it);
}
it++;
}
return group;
}
/**
* @brief finds the closest node to a specific node
* @param node - vertex use as a reference to calculate de distance
* @param neighbours - vector of vertex containing other nodes
* @return a pointer to the vertex closest to the given node
*/
Vertex* MeatWagons::getNearestNeighbour(Vertex *node, const vector<Vertex*> &neighbours) {
double nearestDistance = this->graph->findVertex(node->getId())->getPosition().euclideanDistance((*neighbours.begin())->getPosition());
auto nearestNeighbour = *neighbours.begin();
for(auto it = ++neighbours.begin(); it != neighbours.end(); it++) {
auto currDistance = this->graph->findVertex(node->getId())->getPosition().euclideanDistance((*it)->getPosition());
if(currDistance < nearestDistance) {
nearestDistance = currDistance;
nearestNeighbour = *it;
}
}
return nearestNeighbour;
}
/**
* @brief finds the request of a specific destination
* @param vert - Vertex * of de destination
* @param reqs - vector containing all the requests
* @return a pointer to the requests with vert as its destination, nullptr if it doens't exist any request
*/
Request *MeatWagons::findRequest(Vertex* vert, vector<Request*> reqs) {
for (auto it = reqs.begin(); it != reqs.end(); it++) {
if ((*it)->getDest() == vert->getId()) {
return *it;
}
}
return nullptr;
}
/**
* @brief Calculates the shortest path passing through various points using dijkstra bidirectional
* @param tspNodes - vector of all the vertex that the wagon must pass by
* @param reqs - vector of all the reqs that are used in this ride
* @param tspPath - vector of edges that are passed through
* @param dropOffNode - integer representing the id of the drop off vertex
* @param startTime - represents the time that the wagon leaves the central
* @return - integer representing the distance from the central to the drop off node passing through tspNodes
*/
int MeatWagons::tspPath(vector<Vertex*> &tspNodes, vector<Request *> reqs, vector<Edge> &tspPath, int dropOffNode, Time& startTime){
unordered_set <int> processedEdges, processedInvEdges;
int totalDist = 0;
// Because tspNodes is a vector ordered by dist -> the first element is the closest to the central
Vertex *closest = *tspNodes.begin();
// Calculate the distance from the central to the first point
totalDist += this->graph->getPathFromCentralTo(closest->getId(), tspPath);
tspNodes.erase(tspNodes.begin());
// Get the first request
Request* r = findRequest(closest, reqs);
// Set the real arrival time for the first request
if(r != nullptr){
// If the startTime is equal to the arrival it means the wagon is ready to leave before the arrival
if(startTime == r->getArrival())
startTime = startTime - Time(0, 0, totalDist / averageVelocity);
r->setRealArrival(startTime + Time(0, 0, totalDist / averageVelocity));
}
while(!tspNodes.empty()) {
// Get the nearest point
Vertex *next = getNearestNeighbour(closest, tspNodes);
//Calculate the distance from the previous point to the new one using Dijkstra Bidirectional
this->graph->dijkstraBidirectional(closest->getId(), next->getId(), processedEdges, processedInvEdges);
totalDist += this->graph->getPathTo(next->getId(), tspPath);
// Set the real arrival time of the request belonging to that vertex
r = findRequest(next, reqs);
if(r != nullptr)
r->setRealArrival(startTime + Time(0, 0, totalDist / averageVelocity));
tspNodes.erase(std::find(tspNodes.begin(), tspNodes.end(), next));
closest = next;
}
// Calculate the distance from the last point to the drop off point
this->graph->dijkstraBidirectional(closest->getId(), dropOffNode, processedEdges, processedInvEdges);
totalDist += this->graph->getPathTo(dropOffNode, tspPath);
// Set the real deliver time all the reqs (they are all delivered at the same point so it will be equal to everyone)
for(Request* req : reqs){
req->setRealDeliver(startTime + Time(0, 0, totalDist / averageVelocity));
this->requests.erase(req);
}
return totalDist;
}
Delivery* MeatWagons::drawDeliveriesFromThread(int wagonIndex, int deliveryIndex) {
thread threadProcess(&MeatWagons::drawDeliveries, this, wagonIndex, deliveryIndex);
threadProcess.detach();
return next(this->wagons.begin(), wagonIndex)->getDeliveries().at(deliveryIndex);
}
bool MeatWagons::drawDeliveries(int wagonIndex, int deliveryIndex) {
if(wagonIndex > this->wagons.size()) return false;
this->viewer->newGv();
Delivery * delivery = next(this->wagons.begin(), wagonIndex)->getDeliveries().at(deliveryIndex);
for(auto request : delivery->getRequests()) {
stringstream stream;
stream << request->getRealArrival();
this->graph->findVertex(request->getDest())->setTag(Vertex::PICKUP);
this->viewer->getViewer()->setVertexLabel(request->getDest(), request->getPrisoner() + " arrival at: " + stream.str());
this->graph->findVertex(delivery->getDropOff())->setTag(Vertex::DROPOFF);
}
vector<int> path = Edge::getIds(delivery->getForwardPath());
this->viewer->setPath(path, "blue", true);
this->viewer->draw(this->graph);
for(auto request : delivery->getRequests()) {
this->graph->findVertex(request->getDest())->setTag(Vertex::INTEREST_POINT);
this->graph->findVertex(delivery->getDropOff())->setTag(Vertex::INTEREST_POINT);
}
return true;
}
/**
* This iteration 1 wagon with capacity = 1, this is, it only delivers one prisioner at a time
* It uses dijkstra bidirectional to calculate the shortest path from the central to the drop off node passing through
* the pick up node and back to the central again.
*/
bool MeatWagons::firstIteration() {
if(wagons.size() != 1) return false;
if(wagons.begin()->getCapacity() != 1) return false;
unordered_set<int> processedEdges, processedInvEdges;
// Initialize the wagons that will be used
for(Wagon wagon : this->wagons) wagon.init();
// Iterate until all the requests are processed
while(!requests.empty()) {
// requests are ordered by pickup time
Request *request = *requests.begin();
// Get the wagon that has the maximum capacity (the wagons are ordered)
auto wagonIt = --this->wagons.end();
auto wagon = *wagonIt;
this->wagons.erase(wagonIt);
vector<Edge> edgesForwardTrip;
// Calculates the path from the central to the prisioner
int distToPrisoner = this->graph->getPathFromCentralTo(request->getDest(), edgesForwardTrip);
// Choose a drop off node
int dropOffNode = chooseDropOff({this->graph->findVertex(request->getDest())});
/* Calculate the distance from the prisioner node to the drop off node */
this->graph->dijkstraOrientedSearch(request->getDest(), dropOffNode, processedEdges);
int dropOffDist = graph->getPathTo(dropOffNode, edgesForwardTrip);
int totalDist = dropOffDist + distToPrisoner;
/* Calculate the distance from the drop off node back to the central */
this->graph->dijkstraOrientedSearch(dropOffNode, central, processedEdges);
totalDist += this->graph->getPathTo(central, edgesForwardTrip);
// The wagon leaves either when it returns from a trip or when it as time to travel to the first pick up node
Time startTime = wagon.getDeliveries().size() > 0 ? wagon.getNextAvailableTime() : request->getArrival() - Time(0, 0, distToPrisoner / averageVelocity);
// Set the real arrival and deliver based on the startTime
request->setRealArrival(startTime + Time(0, 0 , distToPrisoner / averageVelocity));
request->setRealDeliver(request->getRealArrival() + Time(0, 0, dropOffDist / averageVelocity));
wagon.setNextAvailableTime(startTime + Time(0, 0, totalDist / averageVelocity));
vector<Request *> vr;
vr.push_back(request);
// Create the delivery and add it to the wagon
Delivery *delivery = new Delivery(startTime, vr, edgesForwardTrip, totalDist / averageVelocity, dropOffNode, totalDist);
wagon.addDelivery(delivery);
// wagon now is back at the central
this->wagons.insert(wagon);
requests.erase(request);
}
return true;
}
/**
* This iteration 1 wagon with capacity > 1 to deliver the prisioners.
* It uses dijkstra bidirectional to calculate the shortest path through all the nodes that it needs to pass
* from the central to the drop Off node and back to the central.
*/
bool MeatWagons::secondIteration() {
if(wagons.size() != 1) return false;
if(wagons.begin()->getCapacity() <= 1) return false;
unordered_set<int> processedEdges, processedInvEdges;
// Initialize the wagons that will be used
for(Wagon wagon : this->wagons) wagon.init();
while(!requests.empty()) {
// Get the wagon that has the maximum capacity (the wagons are ordered)
auto wagonIt = --this->wagons.end();
auto wagon = *wagonIt;
this->wagons.erase(wagonIt);
// Groupes all the nearest requests into a vector and sorts it by arrival time
vector<Request *> groupedRequests = groupRequests(wagon.getCapacity());
sort(groupedRequests.begin(), groupedRequests.end(), compareRequests);
// Populates the tspNodes with the vertex where the prisioners are
vector<Vertex*> tspNodes;
for(auto r : groupedRequests) {
Vertex *tspNode = this->graph->findVertex(r->getDest());
tspNodes.push_back(tspNode);
}
// The wagon leaves either when it returns from a trip or when it as time to travel to the first pick up node
// The startTime will be changed in tspPath function if the wagon as time to travel to the first pick up node
Time startTime = wagon.getDeliveries().size() > 0 ?wagon.getNextAvailableTime() : groupedRequests[0]->getArrival();
// Choose a drop off node
int dropOffNode = chooseDropOff(tspNodes);
vector<Edge> tspPath;
// Calculate the distance using dijkstra Bidirectional
int totalDist = this->tspPath(tspNodes, groupedRequests, tspPath, dropOffNode, startTime);
// Calculate the distance from the drop off node back to the central
this->graph->dijkstraOrientedSearch(dropOffNode, central, processedEdges);
totalDist += this->graph->getPathTo(central, tspPath);
wagon.setNextAvailableTime(startTime + Time(0, 0, totalDist / averageVelocity));
// Add the delivery to the wagon
Delivery *delivery = new Delivery(startTime, groupedRequests, tspPath, totalDist / averageVelocity, dropOffNode, totalDist);
wagon.addDelivery(delivery);
// wagon now is back at the central
this->wagons.insert(wagon);
}
return true;
}
/**
* This iteration using more than 1 wagon with different capacity to deliver the prisioners.
* It uses dijkstra bidirectional to calculate the shortest path through all the nodes that it needs to pass
* from the central to the drop Off node and back to the central.
*/
bool MeatWagons::thirdIteration() {
if(wagons.size() <= 1) return false;
unordered_set<int> processedEdges, processedInvEdges;
for(Wagon wagon : this->wagons) wagon.init();
while(!requests.empty()) {
// get wagon with max capacity and the sooner available
auto wagonIt = getWagon();
auto wagon = *wagonIt;
this->wagons.erase(wagonIt);
// Groups all the nearest requests into a vector and sorts it by arrival time
vector<Request *> groupedRequests = groupRequests(wagon.getCapacity());
sort(groupedRequests.begin(), groupedRequests.end(), compareRequests);
// Populates the tspNodes with the vertex where the prisioners are
vector<Vertex*> tspNodes;
for(auto r : groupedRequests) {
Vertex *tspNode = this->graph->findVertex(r->getDest());
tspNodes.push_back(tspNode);
}
// The wagon leaves either when it returns from a trip or when it as time to travel to the first pick up node
// The startTime will be changed in tspPath function if the wagon as time to travel to the first pick up node
Time startTime = wagon.getDeliveries().size() > 0 ? wagon.getNextAvailableTime() : groupedRequests[0]->getArrival();
// Choose a drop off node
int dropOffNode = chooseDropOff(tspNodes);
vector<Edge> tspPath;
// Calculate the distance using dijkstra Bidirectional
int totalDist = this->tspPath(tspNodes, groupedRequests, tspPath, dropOffNode, startTime);
// Calculate the distance from the drop off node back to the central
this->graph->dijkstraOrientedSearch(dropOffNode, central, processedEdges);
totalDist += this->graph->getPathTo(central, tspPath);
wagon.setNextAvailableTime(startTime + Time(0, 0, totalDist / averageVelocity));
// Add the delivery to the wagon
Delivery *delivery = new Delivery(startTime, groupedRequests, tspPath, totalDist / averageVelocity, dropOffNode, totalDist);
wagon.addDelivery(delivery);
// wagon now is back at the central
this->wagons.insert(wagon);
}
return true;
}
/**
* @brief Searches for the wagon that has de biggest capacity and is available sooner
* @return An iterator pointing to a wagon
*/
multiset<Wagon>::iterator MeatWagons::getWagon(){
multiset<Wagon>::iterator itr = --this->wagons.end(), it = itr;
Time min_time = itr->getNextAvailableTime();
for(itr; itr != wagons.begin(); itr--){
if(itr->getNextAvailableTime() == Time()){
return itr;
}
if(itr->getNextAvailableTime() < min_time){
it = itr;
min_time = itr->getNextAvailableTime();
}
}
if(wagons.begin()->getNextAvailableTime() <= Time()){
return wagons.begin();
}
if(wagons.begin()->getNextAvailableTime() < min_time){
return wagons.begin();
}
return it;
}
/**
* @brief Calculates the score of the grouping function based on the distance the wagon travels and the empty spaces
* @return
*/
int MeatWagons::objectiveFunction() {
int sum = 0;
for(Wagon w : this->wagons)
for(Delivery *d: w.getDeliveries())
sum += d->getTotalDist() + w.getSpaceLeft();
return sum;
}
bool MeatWagons::getViewerStatus(string &status) {
if(viewer->getStatus()) status = "ON";
else status = "OFF";
return viewer->getStatus();
}
void MeatWagons::setViewerStatus(bool status) {
viewer->setStatus(status);
}
#endif //MEAT_WAGONS_MEATWAGONS_H | 37.519258 | 160 | 0.657085 | [
"vector"
] |
becd7fd3e99ad8605c96e854007f4df223561d73 | 570 | h | C | src/homework/tic_tac_toe/tic_tac_toe_manager.h | acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-a1945816 | d2582b3996a086febb211b60fba88940a207288a | [
"MIT"
] | null | null | null | src/homework/tic_tac_toe/tic_tac_toe_manager.h | acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-a1945816 | d2582b3996a086febb211b60fba88940a207288a | [
"MIT"
] | null | null | null | src/homework/tic_tac_toe/tic_tac_toe_manager.h | acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-a1945816 | d2582b3996a086febb211b60fba88940a207288a | [
"MIT"
] | null | null | null | //h
#ifndef TIC_TAC_TOE_MANAGER_H
#define TIC_TAC_TOE_MANAGER_H
#include<vector>
#include<memory>
#include "tic_tac_toe.h"
#include "tic_tac_toe_data.h"
class TicTacToeManager
{
public:
TicTacToeManager() = default;
TicTacToeManager(TicTacToeData&data);
void save_game(std::unique_ptr<TicTacToe> & game);
friend std::ostream& operator<<(std::ostream& out, const TicTacToeManager& m);
private:
void update_winner_count(std::string winner);
std::vector<std::unique_ptr<TicTacToe>> games;
int o_wins{ 0 }, x_wins{ 0 }, ties{ 0 };
};
#endif // !TIC_TAC_TOE_MANAGER_H | 27.142857 | 79 | 0.761404 | [
"vector"
] |
bee639b7b17c563d7d32a2dae09f6e4dc3fea484 | 12,703 | h | C | src/FloatAnimator.h | moebiussurfing/ofxSurfingAnimators | c7bc2b91a430c6b45c81c827a56fa2115f80f3c4 | [
"MIT"
] | 2 | 2020-12-19T10:08:11.000Z | 2021-12-28T10:14:10.000Z | src/FloatAnimator.h | moebiussurfing/ofxSurfingAnimators | c7bc2b91a430c6b45c81c827a56fa2115f80f3c4 | [
"MIT"
] | null | null | null | src/FloatAnimator.h | moebiussurfing/ofxSurfingAnimators | c7bc2b91a430c6b45c81c827a56fa2115f80f3c4 | [
"MIT"
] | null | null | null | #pragma once
#include "ofMain.h"
/*
TODO
+ fix curve type selector crash
*/
/*
This is a base class to other derivated like: position, color...etc.
*/
//----
// OPTIONS
//#define USE_SURFING_PRESETS // -> To allow multiple presets
//----
//#define SURFING_ANIMATOR_ENABLE_AUTO_DRAW // -> disabled to fix some problems...
//#define USE_RANDOMIZE_IMGUI_LAYOUT_MANAGER
#include "ofxAnimatableFloat.h"
#include "ofxSurfingHelpers.h"
#include "ofxSurfingImGui.h"
//#include "ofxGui.h"
#ifdef USE_SURFING_PRESETS
#include "ofxSurfingPresets.h"
#endif
class FloatAnimator
{
//----
public:
// fixing
//--------------------------------------------------------------
void setMinimized(bool b)
{
}
//-
public:
#ifdef USE_SURFING_PRESETS
ofxSurfingPresets presets;
#endif
//-
public:
FloatAnimator();
~FloatAnimator();
//-
ofParameter<float> paramLinked{ "-1", 0, 0, 0 };
//TODO://use &
//void setup(ofParameter<float>paramFloat, bool autoUpdate = false) { // only use to set min/max range but not auto update the param value!
//--------------------------------------------------------------
void setup(ofParameter<float> ¶mFloat) { // only use to set min/max range but not auto update the param value!
paramLinked.makeReferenceTo(paramFloat);
//bAutoUpdate = autoUpdate;
setNameLabel(paramFloat.getName());
setup(paramFloat.getMin(), paramFloat.getMax());
}
virtual void setup();
virtual void setupExtra();
void startup();
void setupGui();
//--------------------------------------------------------------
void setup(float start, float end) {
setStart(start);
setEnd(end);
setRanges();
setup();
}
virtual void update(ofEventArgs & args);
//private:
//void update();
//void update(float _dt)
//{
// dt = _dt;
// update();
//}
#ifndef SURFING_ANIMATOR_ENABLE_AUTO_DRAW
void draw();
#endif
#ifdef SURFING_ANIMATOR_ENABLE_AUTO_DRAW
void draw(ofEventArgs & args);
#endif
public:
void exit(); // not virtual. each class will have his own exit() function.
//--
private:
//TODO: use a pointer to allow autoUpdate..
//ofParameter<float> * paramRef = NULL;
//bool bAutoUpdate = false;
ofParameter<float>paramFloat{ "-1", -1, -1, -1 };
//-
//public:
private:
//#ifdef USE_RANDOMIZE_IMGUI_LAYOUT_MANAGER
ofxSurfing_ImGui_Manager guiManager;
//#endif
string panelName;
public:
string getNamePanel() { return panelName; }
public:
void drawImGuiWidgets();
virtual void drawImGuiWidgetsExtra();
void drawImGuiWidgetsBegin();
void drawImGuiWidgetsEnd();
//protected:
private:
bool bOpened = false;
//bool bParams = true;
private:
ofFbo fboPlot;
ImVec2 plotShape;
void drawPlot();
float widthGuiLayout;
float heightGuiLayout;
ofParameter<glm::vec2> positionGuiLayout{ "Gui PLot Position",
glm::vec2(ofGetWidth() / 2,ofGetHeight() / 2),//center
glm::vec2(0,0),
glm::vec2(ofGetWidth(), ofGetHeight())
};
//-
bool bCustomPositionPlot = false;
glm::vec2 positionPlot{ 50, 50 };
//-
private:
std::string path_GLOBAL_Folder;//top parent folder for all other subfolders
std::string path_Settings;
public:
//--------------------------------------------------------------
void setPath_GlobalFolder(string folder)//legacy api
{
ofLogNotice(__FUNCTION__) << folder;
path_GLOBAL_Folder = folder;
ofxSurfingHelpers::CheckFolder(folder);
}
//--------------------------------------------------------------
void setPathGlobalFolder(string folder) { setPath_GlobalFolder(folder); }
//--------------------------------------------------------------
// api
public:
void start();
void stop();
//-
void nextCurve(bool bAutoTrig = true);
void previousCurve(bool bAutoTrig = true);
private:
// plots
float size = 100;
void drawCurve(glm::vec2 &p);
//-
public:
//--------------------------------------------------------------
void setValueTarget(float &v)//legacy api
{
valueBack = &v;
}
//--------------------------------------------------------------
void setValuePtr(float &v)
{
valueBack = &v;
}
//--------------------------------------------------------------
void setFps(float _fps)
{
dt = 1.0f / _fps;
}
//--------------------------------------------------------------
void setVisible(bool b)
{
bGui = b;
}
//--------------------------------------------------------------
void setToggleVisible()
{
bGui = !bGui;
}
//--------------------------------------------------------------
void doReset()
{
reset = true;
}
//--------------------------------------------------------------
void setEnabled(bool b)
{
bEnableAnimator = b;
}
// settings
//--------------------------------------------------------------
void setAutoSaveLoad(bool b)
{
autoSettings = b;
}
//--------------------------------------------------------------
void saveSettings();
void loadSettings();
////--------------------------------------------------------------
//void setLooped(bool b)
//{
// anim_loop = b;
//}
//--
//--------------------------------------------------------------
bool isAnimating()
{
return floatAnimator.isAnimating();
}
//--------------------------------------------------------------
bool isEnabled()
{
return bEnableAnimator;
}
//--------------------------------------------------------------
void setStartRange(float v)
{
//valueStart = v;
value.setMin(v);
valueStart.setMin(v);
valueEnd.setMin(v);
}
//--------------------------------------------------------------
void setEndRange(float v)
{
//valueEnd = v;
value.setMax(v);
valueStart.setMax(v);
valueEnd.setMax(v);
}
//--------------------------------------------------------------
void setStart(float v)
{
valueStart = v;
}
//--------------------------------------------------------------
void setEnd(float v)
{
valueEnd = v;
}
//--------------------------------------------------------------
void setRanges() {//set params limits
float a, b;
a = valueStart;
b = valueEnd;
setStartRange(a);
setEndRange(b);
}
//--------------------------------------------------------------
void refresh_Labels()
{
repeatName = AnimRepeat_ToStr(repeatMode.get());
curveName = floatAnimator.getCurveName(AnimCurve(curveType.get()));
}
//-
//--------------------------------------------------------------
float getPercentDone()
{
return floatAnimator.getPercentDone();
}
//--------------------------------------------------------------
float getValue()
{
if (floatAnimator.isWaitingForAnimationToStart()) return valueStart;
else return value.get();
}
//--------------------------------------------------------------
float getDelay()
{
return animDelay;
//return (animDelay / globalTimeScale);
}
//--------------------------------------------------------------
float getDuration()
{
return duration;
//return (duration / globalTimeScale);
}
//-
public:
//bool bCustomPositionPlot = false;
//glm::vec2 positionPlot{ 50, 50 };
float pad = 15;
private:
string label = "FloatAnim";
std::vector<std::string> curveNamesList;
public:
//--------------------------------------------------------------
void setNameLabel(string s)//to label gui panel
{
label = s;
path_Settings = label + ".xml";
//TODO: allow more than one instance.
// must use different name and paths
//params.setName(label + "_ANIM");
//TODO:
bGui.setName(s);
}
public:
std::vector<std::string> getAllCurveNames() {
return floatAnimator.getAllCurveNames();
}
//control settings
//--------------------------------------------------------------
ofParameterGroup getControls()
{
return params_Control;
}
private:
// bpm engine
ofParameterGroup _params_Bpm{ "BPM ENGINE" };
public:
//--------------------------------------------------------------
ofParameterGroup getControlsBpm()
{
return _params_Bpm;
}
// helpers
//--------------------------------------------------------------
ofParameterGroup getHelpers()
{
return params_Helpers;
}
// params
//--------------------------------------------------------------
ofParameterGroup getParameters()
{
return params;
}
ofParameterGroup params;
ofParameter<bool> bEnableAnimator;
private:
ofParameterGroup params_Control;
ofParameterGroup params_Helpers;
bool autoSettings;
ofParameter<bool> SHOW_Plot{ "Show Plot", true };
public:
//--------------------------------------------------------------
void AutoSettings(bool b)
{
autoSettings = b;
}
//--------------------------------------------------------------
void setVisible_Plot(bool b)
{
SHOW_Plot = b;
}
////--------------------------------------------------------------
//void setGlobalTimeScale(float timeScale)
//{
// globalTimeScale = timeScale;
//}
// A tricky workaround to check if object class is instantiated...
//--------------------------------------------------------------
bool isInstantiated()
{
return doneInstantiated;
}
//---
//private:
public:
ofParameter<float> value;
ofParameter<float> valueStart;
ofParameter<float> valueEnd;
//-
private:
//tricky workaround to check if object class is instantiated
bool doneInstantiated = false;
//float globalTimeScale = 1.0f;
float *valueBack;
ofxAnimatableFloat floatAnimator;
void Changed_Params(ofAbstractParameter &e);
//public:
//ofxPanel gui;
//-
// bpm engine
public:
//--------------------------------------------------------------
void setDelayBeatMax(int maxBeats) {
bpmBeatDelay.setMax(maxBeats);
}
//--------------------------------------------------------------
void setDurationBeatMax(int maxBeats) {
bpmBeatDuration.setMax(maxBeats);
}
public:
//--------------------------------------------------------------
void setBpm(float _bpm) {
bpmSpeed = _bpm;
//if (!bpmMode) bpmMode = true;
}
ofParameter<float> bpmSpeed;
//--------------------------------------------------------------
void setModeBrowse(bool b) {//to autotrig animator when changing curve type
ModeBrowse = b;
}
ofParameter<int> bpmBeatDuration;
private:
ofParameterGroup params_Time;
ofParameterGroup params_Bpm;
ofParameter<bool> bpmMode;
ofParameter<bool> bpmSlow;
ofParameter<int> bpmBeatDelay;
//-
ofParameter<bool> ModeBrowse;
public:
ofParameter<float> duration;
private:
ofParameter<float> animDelay;
ofParameter<int> repeatMode;
ofParameter<string> repeatName;
ofParameter<int> repeatTimes;
ofParameter<int> curveType;
ofParameter<string> curveName;
ofParameter<int> animProgress;
ofParameter<bool> reset;
//ofParameter<bool> anim_loop;
//int repeatMode_anim_loop_PRE = 2;
void Changed_AnimatorDone(ofxAnimatable::AnimationEvent &);
//TODO:
bool bDone = false;
public:
//--------------------------------------------------------------
bool isDone() {
if (bDone) {
bDone = false;
return true;
}
else {
return false;
}
}
private:
//--------------------------------------------------------------
std::string AnimRepeat_ToStr(int n)
{
std::string s("unknown");
switch (n)
{
case 0:
{
s = "PLAY ONCE";
}
break;
case 1:
{
s = "LOOP";
}
break;
case 2:
{
s = "LOOP BACK & FORTH";
}
break;
case 3:
{
s = "BACK & FORTH ONCE";
}
break;
case 4:
{
s = "PLAY N TIMES";
}
break;
case 5:
{
s = "BACK & FORTH N TIMES";
}
break;
}
return s;
}
//glm::vec2 guiPos;
//string path;
float dt; // -> should remove?
//--
public:
ofParameter<bool> bGui{ "Show Animator", true };
private:
// widgets sizes
float _w100;
float _w99;
float _w50;
float _w33;
float _w25;
float _h;
//--
//TODO:
// deprecated
public:
//--------------------------------------------------------------
void setGuiPosition(glm::vec2 _p)
{
//guiPos = _p;
//gui.setPosition(guiPos.x, guiPos.y);
}
////--------------------------------------------------------------
//glm::vec2 getGuiPosition()
//{
// return guiPos;
//}
////--------------------------------------------------------------
//glm::vec2 getGuiShape()
//{
// ofRectangle r = gui.getShape();
// glm::vec2 _shape = glm::vec2(r.getWidth(), r.getHeight() + size + pad + 15);// lastone is text line height
// return _shape;
//}
////--------------------------------------------------------------
//void setMinimized(bool b)
//{
// if (b)
// {
// gui.minimizeAll();
// }
// else
// {
// gui.maximizeAll();
// }
//}
////--------------------------------------------------------------
//bool isMinimized()
//{
// return gui.isMinimized();
//}
////--------------------------------------------------------------
//void disableHeader()
//{
// gui.disableHeader();
//}
//--
};
| 18.463663 | 140 | 0.500039 | [
"object",
"vector"
] |
bee93efb27b15d8d841de424f5523d3f2d9202aa | 6,688 | h | C | BloksAIPlugin/Vendor/illustratorapi/illustrator/legacy/AI90Mask.h | WestonThayer/Bloks | d5c59807b17d4d52f7cb2e3ec952b6e6127b4e27 | [
"MIT"
] | 65 | 2016-06-27T15:34:44.000Z | 2022-02-06T03:48:15.000Z | illustratorapi/illustrator/legacy/AI90Mask.h | btempleton/sg-aics3mac-plugins | e5332b11ef8ce03a7e842c9df3fe1ce9145c0b67 | [
"Intel",
"Unlicense"
] | 17 | 2016-06-27T15:35:36.000Z | 2022-02-07T21:03:51.000Z | illustratorapi/illustrator/legacy/AI90Mask.h | btempleton/sg-aics3mac-plugins | e5332b11ef8ce03a7e842c9df3fe1ce9145c0b67 | [
"Intel",
"Unlicense"
] | 6 | 2016-08-05T05:08:24.000Z | 2017-09-04T04:38:45.000Z | #ifndef __AI90Mask__
#define __AI90Mask__
/*
* Name: AI90Mask.h
* $Revision: 2 $
* Author:
* Date:
* Purpose: Adobe Illustrator 9.0 Mask Suite.
*
* ADOBE SYSTEMS INCORPORATED
* Copyright 1986-2007 Adobe Systems Incorporated.
* All rights reserved.
*
* NOTICE: Adobe permits you to use, modify, and distribute this file
* in accordance with the terms of the Adobe license agreement
* accompanying it. If you have received this file from a source other
* than Adobe, then your use, modification, or distribution of it
* requires the prior written permission of Adobe.
*
*/
/*******************************************************************************
**
** Imports
**
**/
#include "AIMask.h"
#include "AIHeaderBegin.h"
/*******************************************************************************
**
** Suite name and version
**
**/
#define kAI90BlendStyleSuite "AI Blend Style Suite"
#define kAIBlendStyleSuiteVersion1 AIAPI_VERSION(1)
#define kAI90BlendStyleVersion kAIBlendStyleSuiteVersion1
#define kAI90MaskSuite "AI Mask Suite"
#define kAIMaskSuiteVersion1 AIAPI_VERSION(2)
#define kAI90MaskVersion kAIMaskSuiteVersion1
/*******************************************************************************
**
** Types
**
**/
/*******************************************************************************
**
** Suite
**
**/
/* The blend style suite allows manipulation of the compositing attributes
of object styles. */
typedef struct {
/* The following methods are a short hand for getting the object's style
and then modifying the opacity applied by the style to the object as
a whole. */
AIAPI AIBlendingMode (*GetBlendingMode) (AIArtHandle art);
AIAPI AIErr (*SetBlendingMode) (AIArtHandle art, AIBlendingMode mode);
AIAPI AIReal (*GetOpacity) (AIArtHandle art);
AIAPI AIErr (*SetOpacity) (AIArtHandle art, AIReal opacity);
AIAPI AIBoolean (*GetIsolated) (AIArtHandle art);
AIAPI AIErr (*SetIsolated) (AIArtHandle art, AIBoolean isolated);
AIAPI AIKnockout (*GetKnockout) (AIArtHandle art);
AIAPI AIKnockout (*GetInheritedKnockout) (AIArtHandle art); // always explicitly on or off.
AIAPI AIErr (*SetKnockout) (AIArtHandle art, AIKnockout knockout);
AIAPI AIBoolean (*GetAlphaIsShape) (AIArtHandle art);
AIAPI AIErr (*SetAlphaIsShape) (AIArtHandle art, AIBoolean alphaIsShape);
/* Copy the compositing attributes applied globally by the style applied
to the source object to the destination object.*/
AIAPI AIErr (*Copy) (const AIArtHandle source, AIArtHandle destination);
/* Manipulate the attributes applied to the object via a dictionary. See
the definitions above for the names of the appropriate keys. These
methods are a short hand for first getting the object's style and
then using the Get/SetStyleAttrs methods. */
AIAPI AIErr (*GetArtAttrs) (AIArtHandle art, AIDictionaryRef attrs);
AIAPI AIErr (*SetArtAttrs) (AIArtHandle art, AIDictionaryRef attrs);
/* Manipulate the attributes applied by the style via a dictionary. See
the definitions above for the names of the appropriate keys. */
AIAPI AIErr (*GetStyleAttrs) (AIArtStyleHandle style, AIDictionaryRef attrs);
AIAPI AIErr (*SetStyleAttrs) (AIArtStyleHandle style, AIDictionaryRef attrs,
AIArtStyleHandle* newStyle);
/* Manipulate the attributes applied by a specific filter element of an
active style via a dictionary. See the definitions above for the names
of the appropriate keys. * /
AIAPI AIErr (*GetFilterAttrs) (AIStyleFilterExecHandle filter, AIDictionaryRef style);
AIAPI AIErr (*SetFilterAttrs) (AIStyleFilterExecHandle filter, AIDictionaryRef attrs);*/
/* Get and set the transparency attributes for the current selection in the document */
AIAPI AIErr (*GetCurrentTransparency) (AIDictionaryRef styleAttrs,
AIDictionaryRef fillAttrs,
AIDictionaryRef strokeAttrs);
AIAPI AIErr (*SetCurrentTransparency) (AIDictionaryRef styleAttrs,
AIDictionaryRef fillAttrs,
AIDictionaryRef strokeAttrs);
AIAPI AIErr (*GetFocalFillAttrs) (AIArtStyleHandle artStyle, AIDictionaryRef attrs);
AIAPI AIErr (*GetFocalStrokeAttrs) (AIArtStyleHandle artStyle, AIDictionaryRef attrs);
AIAPI AIErr (*SetFocalFillAttrs) (AIArtStyleHandle artStyle, AIDictionaryRef attrs,
AIArtStyleHandle* newStyle);
AIAPI AIErr (*SetFocalStrokeAttrs) (AIArtStyleHandle artStyle, AIDictionaryRef attrs,
AIArtStyleHandle* newStyle );
} AI90BlendStyleSuite;
typedef struct {
/* Masks are reference counted. Call Release once you are done with
a mask to free its memory. */
AIAPI ASInt32 (*AddRef) (AIMaskRef mask);
AIAPI ASInt32 (*Release) (AIMaskRef mask);
/* GetMask obtains the mask associated with an object if any. */
AIAPI AIErr (*GetMask) (AIArtHandle object, AIMaskRef* mask);
/* Create a mask for an object if it doesn't already have one. The
art of the newly created mask is an empty group object. */
AIAPI AIErr (*CreateMask) (AIArtHandle object);
/* Delete the mask associated with an object. */
AIAPI AIErr (*DeleteMask) (AIArtHandle object);
/* The link state controls whether the mask is linked to the object.
When the mask is linked certain actions on the object automatically
apply to the mask. For example, rotating the object will also
rotate the mask. */
AIAPI AIBoolean (*GetLinked) (AIMaskRef mask);
AIAPI AIErr (*SetLinked) (AIMaskRef mask, AIBoolean linked);
/* The disabled state controls whether the mask is ignored for rendering
purposes. */
AIAPI AIBoolean (*GetDisabled) (AIMaskRef mask);
AIAPI AIErr (*SetDisabled) (AIMaskRef mask, AIBoolean disabled);
/* The inverted state controls whether the opacity of the mask is
inverted before being applied. */
AIAPI AIBoolean (*GetInverted) (AIMaskRef mask);
AIAPI AIErr (*SetInverted) (AIMaskRef mask, AIBoolean inverted);
/* Copy the mask and the link status. */
AIAPI AIErr (*Copy) (const AIArtHandle source, AIArtHandle destination);
/* GetArt returns the handle to the mask art which will be NULL if there
is none. */
AIAPI AIArtHandle (*GetArt) (AIMaskRef mask);
/* Methods to query and manipulate whether the mask art is being edited. */
AIAPI AIBoolean (*IsEditingArt) (AIMaskRef mask);
AIAPI AIErr (*SetEditingArt) (AIMaskRef mask, AIBoolean isedit);
/* If "mask" is a group object which is the mask art for some other object
then on return "masked" will be the masked object. If not then
"masked" will be nil on return. */
AIAPI AIErr (*GetMaskedArt) (AIArtHandle mask, AIArtHandle* masked);
} AI90MaskSuite;
#include "AIHeaderEnd.h"
#endif
| 35.956989 | 92 | 0.707237 | [
"object"
] |
bee9936a348499e6ca974425b4df67666d490cbb | 4,354 | h | C | torrent.h | my-official/QtBT | 0c78119b373bfc549a3262cb66794764a1416205 | [
"MIT"
] | 2 | 2018-04-06T16:00:13.000Z | 2018-04-06T16:01:15.000Z | torrent.h | my-official/QtBT | 0c78119b373bfc549a3262cb66794764a1416205 | [
"MIT"
] | null | null | null | torrent.h | my-official/QtBT | 0c78119b373bfc549a3262cb66794764a1416205 | [
"MIT"
] | null | null | null | #ifndef TORRENT_H
#define TORRENT_H
#include <QObject>
#include "metainfo.h"
#include <QList>
#include <QString>
#include <QUrl>
#include <QHostAddress>
#include <QBitArray>
#include "tracker.h"
#include "peer.h"
#include <unordered_map>
#include <map>
#include <vector>
#include <random>
#include <time.h>
namespace torrent
{
class Torrent : public QObject, public MetaInfo
{
Q_OBJECT
public:
enum class State
{
TS_STOPPED,
TS_PREPARING,
TS_DOWNLOADING,
TS_SEEDING,
TS_PAUSED
};
Torrent::State GetState() const;
QString GetStateString() const;
void SetDestDir(const QString& destDir);
void AddTrackerUrl(const QUrl& url);
bool AddPeerInfo(const QHostAddress& address, quint16 port);
QByteArray GetInfoHash() const;
quint64 GetUploadedBytesPerSession() const;
quint64 GetDownloadedBytesPerSession() const;
quint64 GetLeftBytes() const;
quint64 GetTotalBytes() const;
quint64 GetDownloadingSpeed() const;
quint64 GetUploadingSpeed() const;
quint32 GetActivePeerCount() const;
quint32 GetPeerCount() const;
QList< QSharedPointer<PeerInfo> > GetPeers() const;
QList< QSharedPointer<PeerInfo> > GetActivePeers() const;
void Start(bool skipPreparing = false);
void Stop();
void SetPause(bool pause);
bool Pause();
//virtual ~Torrent();
protected:
friend class Server;
friend class Peer;
friend class Verificator;
using MetaInfo::clear;
using MetaInfo::parse;
using MetaInfo::errorString;
bool AddPeerInfo(const QSharedPointer<PeerInfo>& peerInfo);
void AddIncomingPeer(const QSharedPointer<Peer>& peer);
std::multimap<quint32, PiecePart> m_DownloadedParts;
void WritePiecePart(quint32 index, quint32 begin, quint32 length, quint8* data);
void ReadPiecePart(quint32 index, quint32 begin, quint32 length, quint8* data);
void Prepare();
void StartDownloading();
void StartSeeding();
Torrent(Server* server, const MetaInfo& metainfo);
private:
State m_State;
bool m_Pause;
Server* m_Server;
QString m_DestDir;
QByteArray m_InfoHash;
const quint32 m_PieceCount;
QBitArray m_Pieces;
quint32 m_CheckingPiece;
quint32 m_CheckingPeerTimer;
QList< QSharedPointer<Tracker> > m_Trackers;
QList< QSharedPointer<PeerInfo> > m_PeerInfoList;
QList< QSharedPointer<Peer> > m_Peers;
QByteArray Read(quint64 pieceIndex, quint64 begin, quint64 length) const;
void Write(quint64 pieceIndex, quint64 begin, quint64 length, quint8* write) const;
bool CheckPieceSha(quint32 pieceIndex) const;
quint32 PieceCount() const;
int BitFieldByteSize() const;
quint32 PieceLengthAt(quint32 pieceIndex) const;
quint64 PieceOffset(quint32 pieceIndex) const;
bool HasPeerInfo(const PeerInfo& peerInfo) const;
//bool HasPeerInfo(const Peer& peer) const;
//bool HasPeerConnection(const Peer& peer) const;
bool HasPeerConnection(const PeerInfo& peerInfo) const;
void SeedingAlgorithm();
//void DownloadingAlgorithm();
void InitializePeer(Peer& peer);
QString FileAt(quint32 piece);
quint32 LastPieceAtFile(const QString& filename);
void UpdateSpeeds(quint32 deltaTime);
private slots:
//By Peer
void OnInfohashRecived(const QByteArray& infohash);
void OnPeerIdRecived();
void OnDataTransferReady();
void OnNeedRemove();
void OnChooseAlgorithm();
//By Tracker
void OnNewPeerInfo(const QSharedPointer<PeerInfo>& newPeerInfo);
//By FileVerificator
void OnVerifyFinished(Torrent* torrent, QBitArray pieces);
////////////////////////////?////////////////////////////////////////////////////////////
private:
std::vector< quint32 > m_Pieces2Availability;
//std::multimap<quint32, quint32 > m_Availability2Pieces;
QVector<quint32> m_PiecePartBeginForDownloading;
void BuildRequestListForPeer(Peer* peer, qint64 requestSize);
void OnReciveHave(Peer* peer, quint32 index);
void OnReciveBitField(Peer* peer, const QBitArray& pieces);
//void RebuildAvailabilityMap();
bool IsPartDownloaded(quint32 index, quint32 begin, quint32 length);
bool IsPartRequested(int index, quint32 begin, quint32 size);
//void AddToAvailabilityMap(quint32 availability, quint32 piece);
void RebuildPeerAvailabilityMap(PeerInfo* peerInfo);
bool GetNextRandomRarestPiecePart(Peer* peer, PiecePart& piecePart);
};
}
#endif // TORRENT_H
| 27.383648 | 91 | 0.73266 | [
"vector"
] |
bef19099a73d2d8a823ccf6ca6d809085790305a | 3,677 | h | C | COGengine/src/Core/Facade.h | dodoknight/CogEngine | fda1193c2d1258ba9780e1025933d33a8dce2284 | [
"MIT"
] | 3 | 2016-06-01T10:14:00.000Z | 2016-10-11T15:53:45.000Z | COGengine/src/Core/Facade.h | dormantor/ofxCogEngine | fda1193c2d1258ba9780e1025933d33a8dce2284 | [
"MIT"
] | null | null | null | COGengine/src/Core/Facade.h | dormantor/ofxCogEngine | fda1193c2d1258ba9780e1025933d33a8dce2284 | [
"MIT"
] | 1 | 2020-08-15T17:01:00.000Z | 2020-08-15T17:01:00.000Z | #pragma once
#include "Msg.h"
#include "InputAct.h"
#include "Soundfx.h"
#include "SheetAnim.h"
#include "Definitions.h"
#include "Settings.h"
#include "pugixml.h"
using namespace pugi;
namespace Cog {
class Behavior;
class Component;
class BaseComponent;
class ComponentStorage;
class Scene;
class Node;
class Msg;
class MsgPayload;
class InputAct;
class SheetAnim;
class GeneralAnim;
class AttribAnim;
class AsyncProcess;
class SpriteSheet;
ComponentStorage* CogGetComponentStorage();
/**********************************************************************************/
/* Facade methods that may be used for centralized access to important components */
/**********************************************************************************/
// =================== ofxCogEngine ====================
extern int CogGetFrameCounter();
extern uint64 CogGetAbsoluteTime();
extern float CogGetGameSpeed();
extern void CogSetGameSpeed(float gameSpeed);
// =================== Environment ====================
extern void CogAddSound(Soundfx* sound);
extern void CogPlaySound(Soundfx* sound);
extern vector<InputAct*>& CogGetPressedKeys();
extern vector<InputAct*>& CogGetPressedPoints();
extern vector<Soundfx*>& CogGetPlayedSounds();
extern void CogStopAllSounds();
extern bool CogIsKeyPressed(int key);
extern Vec2i CogGetMousePosition();
extern Vec2i CogGetMouseScroll();
extern int CogGetScreenWidth();
extern int CogGetVirtualWidth();
extern int CogGetScreenHeight();
extern int CogGetVirtualHeight();
extern float CogGetVirtualAspectRatio();
extern float CogGetScreenAspectRatio();
extern Vec2i CogGetScreenSize();
extern Vec2i CogGetVirtualScreenSize();
extern ofVec2f CogGetNativeSize();
extern void CogSetNativeSize(int width, int height);
extern float CogGetNativeScale();
extern void CogRunProcess(AsyncProcess* thread);
// =================== Scene ========================
extern void CogRegisterGlobalListener(StrId action, BaseComponent* listener);
extern void CogUnregisterGlobalListener(StrId action, BaseComponent* listener);
extern void CogSendMessage(Msg& msg);
// =================== Logger =========================
extern void CogLogError(const char* module, const char* format, ...);
extern void CogLogInfo(const char* module, const char* format, ...);
extern void CogLogTree(const char* module, int logLevel, const char* format, ...);
extern void CogLogDebug(const char* module, const char* format, ...);
extern void CogLoggerFlush();
extern void CogWriteLogStage();
extern void CogWriteLogActualScene();
extern void CogWriteTimeReport(bool restart);
// =================== Renderer =========================
extern void CogPushNodeForRendering(Node* node);
// =================== Resources =======================
extern spt<ofImage> CogGet2DImage(string path);
extern spt<ofImage> CogPreload2DImage(string path);
extern spt<ofVboMesh> CogGetVboMesh(string path);
extern spt<ofTrueTypeFont> CogGetFont(string path, int size);
extern Soundfx* CogGetSound(string path);
extern spt<xml_document> CogPreloadXMLFile(string path);
extern spt<xml_document> CogLoadXMLFile(string path);
extern spt<GeneralAnim> CogGetAnimation(string name);
extern spt<SheetAnim> CogGetSheetAnimation(string name);
extern spt<AttribAnim> CogGetAttribAnimation(string name);
extern spt<SpriteSheet> CogGetSpriteSheet(string name);
extern void CogStoreSpriteSheet(spt<SpriteSheet> sheet);
extern void CogStoreAnimation(spt<SheetAnim> anim);
extern Settings& CogGetGlobalSettings();
extern Settings& CogGetDefaultSettings();
extern Settings& CogGetProjectSettings();
}// namespace | 33.126126 | 85 | 0.689421 | [
"vector"
] |
bef63844553d73644e627d5a269258ee36cc9cc5 | 5,351 | h | C | fingerprintdb_cuda.h | Mariewelt/gpusimilarity | ff4fbf3ef0761d35510b148f07943d2958e6e7a5 | [
"BSD-3-Clause"
] | 61 | 2018-09-06T06:48:05.000Z | 2022-03-25T15:40:02.000Z | fingerprintdb_cuda.h | Mariewelt/gpusimilarity | ff4fbf3ef0761d35510b148f07943d2958e6e7a5 | [
"BSD-3-Clause"
] | 36 | 2018-05-22T12:55:31.000Z | 2020-10-04T14:05:27.000Z | fingerprintdb_cuda.h | Mariewelt/gpusimilarity | ff4fbf3ef0761d35510b148f07943d2958e6e7a5 | [
"BSD-3-Clause"
] | 18 | 2018-06-21T17:35:23.000Z | 2022-03-28T09:24:52.000Z | /* -------------------------------------------------------------------------
* Declares gpusim::FingerprintDB CUDA enabled similarity scoring
*
* Copyright Schrodinger LLC, All Rights Reserved.
--------------------------------------------------------------------------- */
#ifndef FINGERPRINTDB_CUDA
#define FINGERPRINTDB_CUDA
#include <memory>
#include <utility>
#include <vector>
#include <QObject>
#include <QString>
#include "types.h"
class QByteArray;
class QSize;
namespace gpusim
{
class FingerprintDB;
class FingerprintDBPriv;
struct StorageResultObject;
typedef std::pair<char*, char*> ResultData;
typedef std::pair<float, ResultData> SortableResult;
unsigned int get_gpu_count();
unsigned int get_next_gpu(size_t required_memory);
class FingerprintDBStorage
{
public:
friend class FingerprintDB;
FingerprintDBStorage(FingerprintDB* parent, std::vector<char>& fp_data,
int index_offset, int fp_bitcount);
unsigned int getOffsetIndex(unsigned int without_offset);
private:
FingerprintDB* m_parent;
std::vector<int> m_data;
std::shared_ptr<FingerprintDBPriv> m_priv; // Used to conceal cuda types
const unsigned int m_index_offset;
const int m_count;
int m_gpu_device;
};
class FingerprintDB : public QObject
{
friend class FingerprintDBStorage;
public:
FingerprintDB(int fp_bitcount, int fp_count, const QString& dbkey,
std::vector<std::vector<char>>& data,
std::vector<char*>& smiles_vector,
std::vector<char*>& ids_vector);
/**
* @brief
* Copy fingerprint memory up to the GPU, folding to a smaller size
* if necessary
*
* @param fold_factor: Minimum factor to fold fingerprints by, might need
* fold by a bigger factor to get even folding
*/
void copyToGPU(unsigned int fold_factor);
// Total number of fingerprints in DB
unsigned int count() const { return m_total_count; };
/*
* @brief
* This function takes an index in the range of all molecules, and finds
* which storage block that index is inside, and returns that storage block
* and the local index inside that block
*/
void getStorageAndLocalIndex(unsigned int offset_index,
FingerprintDBStorage** storage,
unsigned int* local_index) const;
/**
* @brief
* Get an indexed fingerprint that's currently stored in the database
*
* @param index: index of fingerprint to return
* @return: Fingerprint data
*/
Fingerprint getFingerprint(unsigned int index) const;
/**
* @brief
* Search the database for top ten most similar fingerprints to query
*
* @param query: Fingerprint to find closest matches to
* @param results_smiles: Vector to store smiles of results
* @param results_ids: Vector to store IDs of results
* @param results_scores: Vector to store scores of results
* @param return_count: Maximum number of results to return
* @param similarity_cutoff: Minimum similarity score to return
*/
void search(const Fingerprint& query, const QString& dbkey,
unsigned int max_return_count, float similarity_cutoff,
std::vector<char*>& results_smiles,
std::vector<char*>& results_ids,
std::vector<float>& results_scores,
unsigned long& approximate_result_count) const;
void search_cpu(const Fingerprint& query, const QString& dbkey,
unsigned int max_return_count, float similarity_cutoff,
std::vector<char*>& results_smiles,
std::vector<char*>& results_ids,
std::vector<float>& results_scores,
unsigned long& approximate_result_count) const;
char* getSmiles(int index) const { return m_smiles[index]; }
char* getID(int index) const { return m_ids[index]; }
size_t getFingerprintDataSize() const { return m_total_data_size; };
int getFingerprintBitcount() const
{
return m_fp_intsize * sizeof(int) * 8;
}
void search_storage(const Fingerprint& query,
const std::shared_ptr<FingerprintDBStorage>& storage,
StorageResultObject* results, unsigned int return_count,
float similarity_cutoff) const;
protected:
// INTERNAL: A CPU implementation of tanimoto similarity for validation
float tanimoto_similarity_cpu(const Fingerprint& fp1,
const Fingerprint& fp2) const;
std::vector<int> fold_data(const std::vector<int>& unfolded) const;
std::vector<std::shared_ptr<FingerprintDBStorage>> m_storage;
int m_total_count, m_fp_intsize, m_fold_factor;
size_t m_total_data_size;
std::vector<char*> m_smiles;
std::vector<char*> m_ids;
QString m_dbkey;
};
size_t get_available_gpu_memory();
/**
* @brief
* Used for CPU sorting to just get top results in O(number_required*N)
*/
void top_results_bubble_sort(std::vector<int>& indices,
std::vector<float>& scores, int number_required);
std::vector<int> fold_fingerprint(std::vector<int>&, const int);
} // namespace gpusim
#endif
| 32.828221 | 80 | 0.643805 | [
"vector"
] |
83002d71ecca036b84ce954ed1e3b28df94406fa | 1,350 | h | C | src/engine/window.h | ttrounce/tide | 981365710ec9876128b358aa7084691f0126c54c | [
"MIT"
] | 1 | 2021-07-04T07:14:55.000Z | 2021-07-04T07:14:55.000Z | src/engine/window.h | ttrounce/tide | 981365710ec9876128b358aa7084691f0126c54c | [
"MIT"
] | null | null | null | src/engine/window.h | ttrounce/tide | 981365710ec9876128b358aa7084691f0126c54c | [
"MIT"
] | null | null | null | #ifndef TIDE_WINDOW_H
#define TIDE_WINDOW_H
#include "types.h"
#include <glm/vec2.hpp>
#define GLFW_INCLUDE_NONE
#include <glfw/glfw3.h>
#include <vector>
#include <memory>
struct Keyboard
{
bool keys[GLFW_KEY_LAST];
};
struct Mouse
{
bool buttons[GLFW_MOUSE_BUTTON_LAST];
glm::vec2 delta;
glm::vec2 pos;
glm::vec2 lastPos;
};
struct Window
{
GLFWwindow* handle;
Unique<Keyboard> keyboard;
Unique<Mouse> mouse;
bool iconified;
uint fps;
double frameTime;
int frameRateTarget;
Window();
};
using key_listener = void (*)(int, int, int);
using char_listener = void (*)(uint);
using resize_listener = void (*)(int, int);
using update_func = void (*)(double, double);
using draw_func = void (*)();
class Engine
{
public:
Unique<Window> window;
std::vector<key_listener> keyListeners;
std::vector<char_listener> charListeners;
std::vector<resize_listener> resizeListeners;
std::vector<resize_listener> resizeFrameBufferListeners;
Engine(int initialWidth, int initialHeight, const std::string& title);
~Engine();
void Start(update_func update, draw_func draw);
bool GetStatus();
int GetWindowWidth();
int GetWindowHeight();
int GetFrameBufferWidth();
int GetFrameBufferHeight();
private:
bool success;
};
#endif // TIDE_WINDOW_H | 18.493151 | 74 | 0.69037 | [
"vector"
] |
8302176503154a874844bf724d8294df7e37d433 | 6,035 | h | C | linuxcan/include/i82527.h | Innovation-Cell/radar | de1bcd91e5a831e2858539241edfea3ce79f3afd | [
"MIT"
] | null | null | null | linuxcan/include/i82527.h | Innovation-Cell/radar | de1bcd91e5a831e2858539241edfea3ce79f3afd | [
"MIT"
] | null | null | null | linuxcan/include/i82527.h | Innovation-Cell/radar | de1bcd91e5a831e2858539241edfea3ce79f3afd | [
"MIT"
] | null | null | null | /*
** Copyright 2012-2016 by Kvaser AB, Molndal, Sweden
** http://www.kvaser.com
**
** This software is dual licensed under the following two licenses:
** BSD-new and GPLv2. You may use either one. See the included
** COPYING file for details.
**
** License: BSD-new
** ===============================================================================
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
** * Neither the name of the <organization> 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 <COPYRIGHT HOLDER> 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.
**
**
** License: GPLv2
** ===============================================================================
** This program is free software; you can redistribute it and/or
** modify it under the terms of the GNU General Public License
** as published by the Free Software Foundation; either version 2
** of the License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
**
** ---------------------------------------------------------------------------
**/
#define CAN_BASE 0
#define CAN_MSG1 0x10
#define CAN_MSG2 0x20
#define CAN_MSG3 0x30
#define CAN_MSG4 0x400
#define CAN_MSG5 0x410
#define CAN_MSG6 0x420
#define CAN_MSG7 0x430
#define CAN_MSG8 0x800
#define CAN_MSG9 0x810
#define CAN_MSG10 0x820
#define CAN_MSG11 0x830
#define CAN_MSG12 0xC00
#define CAN_MSG13 0xC10
#define CAN_MSG14 0xC20
#define CAN_MSG15 0xC30
#define CAN_CTRL CAN_BASE + 0x00
#define CAN_STAT CAN_BASE + 0x01
#define CAN_CPUIR CAN_BASE + 0x02
#define CAN_STDGBLMASK0 CAN_BASE + 0x06
#define CAN_STDGBLMASK1 CAN_BASE + 0x07
#define CAN_EXTGBLMASK0 CAN_BASE + 0x08
#define CAN_EXTGBLMASK1 CAN_BASE + 0x09
#define CAN_EXTGBLMASK2 CAN_BASE + 0x0a
#define CAN_EXTGBLMASK3 CAN_BASE + 0x0b
#define CAN_MSG15MASK0 CAN_BASE + 0x0c
#define CAN_MSG15MASK1 CAN_BASE + 0x0d
#define CAN_MSG15MASK2 CAN_BASE + 0x0e
#define CAN_MSG15MASK3 CAN_BASE + 0x0f
#define CAN_BUSCON CAN_MSG2 + 0x0f
#define CAN_BTR0 CAN_MSG3 + 0x0f
#define CAN_BTR1 CAN_MSG4 + 0x0f
#define CAN_IR CAN_MSG5 + 0x0f
#define CAN_P2CONF CAN_MSG10 + 0x0f
#define CAN_P2IN CAN_MSG12 + 0x0f
#define CAN_P2OUT CAN_MSG13 + 0x0f
#define CTRL_CCE 0x40
#define CTRL_EIE 0x08
#define CTRL_SIE 0x04
#define CTRL_IE 0x02
#define CTRL_INIT 0x1
#define STAT_BOFF 0x80
#define STAT_WARN 0x40
#define STAT_WAKE 0x20
#define STAT_RXOK 0x10
#define STAT_TXOK 0x08
#define CPUIR_RSTST 0X80
#define CPUIR_DSC 0X40
#define CPUIR_DMC 0X20
#define CPUIR_PWD 0X10
#define CPUIR_SLEEP 0X08
#define CPUIR_MUX 0X04
#define CPUIR_CEN 0X01
#define BUSCON_COBY 0X40
#define BUSCON_POL 0X20
#define BUSCON_DCT1 0X08
#define BUSCON_DCR1 0X02
#define BUSCON_DCR0 0X01
/* --- The message objects: */
#define CANmsg(addr, n) ((addr) + (((n)&0x03)<<4) + (((n)&0x0c)<<8))
#define CANmsg_CTRL0 0
#define CANmsg_CTRL1 1
#define CANmsg_ARB 2
#define CANmsg_CONF 6
#define CANmsg_DATA 7
/* Bits in the Message Object Controls: */
/* Control 0: */
#define MsgVal 3
#define TxIE 2
#define RxIE 1
#define IntPnd 0
#define CTRL0_MsgVal (1<<(MsgVal*2+1))
#define CTRL0_TxIE (1<<(TxIE*2+1))
#define CTRL0_RxIE (1<<(RxIE*2+1))
#define CTRL0_IntPnd (1<<(IntPnd*2+1))
/* Control 1: */
#define RmtPnd 3
#define TxRqst 2
#define MsgLst 1
#define CPUUpd 1
#define NewDat 0
#define CTRL1_RmtPnd (1<<(RmtPnd*2+1))
#define CTRL1_TxRqst (1<<(TxRqst*2+1))
#define CTRL1_MsgLst (1<<(MsgLst*2+1))
#define CTRL1_CPUUpd (1<<(CPUUpd*2+1))
#define CTRL1_NewDat (1<<(NewDat*2+1))
#define SET(x) (255 ^ (1 << ((x)<<1)))
#define CLR(x) (255 ^ (2 << ((x)<<1)))
#define TEST(x) (2 << ((x)<<1))
/* Use as in
* CANmessage(1)[CANmsg_Control0] = SET(MsgVal) & CLR(TxIE);
* or
* if (CANmessage(1)[CANmsg_Control0] & TEST(IntPnd)) ...
*/
/* Message Configuration Register: */
#define CANmsg_DLC(n) ((n)<<4)
#define CANmsg_Extended 4
#define CANmsg_Standard 0
#define CANmsg_Transmit 8
#define CANmsg_Receive 0
| 36.137725 | 82 | 0.665617 | [
"object"
] |
831cc474fe6493effafea0e533d31c0b6461276e | 6,675 | h | C | src/objects/compilation-cache-table-inl.h | KDr2/v8 | 6048f754931e0971cab58fb0de785482d175175b | [
"BSD-3-Clause"
] | null | null | null | src/objects/compilation-cache-table-inl.h | KDr2/v8 | 6048f754931e0971cab58fb0de785482d175175b | [
"BSD-3-Clause"
] | null | null | null | src/objects/compilation-cache-table-inl.h | KDr2/v8 | 6048f754931e0971cab58fb0de785482d175175b | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 the V8 project 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 V8_OBJECTS_COMPILATION_CACHE_TABLE_INL_H_
#define V8_OBJECTS_COMPILATION_CACHE_TABLE_INL_H_
#include "src/objects/compilation-cache-table.h"
#include "src/objects/name-inl.h"
#include "src/objects/script-inl.h"
#include "src/objects/shared-function-info.h"
#include "src/objects/smi.h"
#include "src/objects/string.h"
// Has to be the last include (doesn't have include guards):
#include "src/objects/object-macros.h"
namespace v8 {
namespace internal {
CompilationCacheTable::CompilationCacheTable(Address ptr)
: HashTable<CompilationCacheTable, CompilationCacheShape>(ptr) {
SLOW_DCHECK(IsCompilationCacheTable());
}
NEVER_READ_ONLY_SPACE_IMPL(CompilationCacheTable)
CAST_ACCESSOR(CompilationCacheTable)
Object CompilationCacheTable::PrimaryValueAt(InternalIndex entry) {
return get(EntryToIndex(entry) + 1);
}
void CompilationCacheTable::SetPrimaryValueAt(InternalIndex entry, Object value,
WriteBarrierMode mode) {
set(EntryToIndex(entry) + 1, value, mode);
}
Object CompilationCacheTable::EvalFeedbackValueAt(InternalIndex entry) {
static_assert(CompilationCacheShape::kEntrySize == 3);
return get(EntryToIndex(entry) + 2);
}
void CompilationCacheTable::SetEvalFeedbackValueAt(InternalIndex entry,
Object value,
WriteBarrierMode mode) {
set(EntryToIndex(entry) + 2, value, mode);
}
// The key in a script cache is a WeakFixedArray containing a weak pointer to
// the Script. The corresponding value can be either the root SharedFunctionInfo
// or undefined. The purpose of storing the root SharedFunctionInfo as the value
// is to keep it alive, not to save a lookup on the Script. A newly added entry
// always contains the root SharedFunctionInfo. After the root
// SharedFunctionInfo has aged sufficiently, it is replaced with undefined. In
// this way, all strong references to large objects are dropped, but there is
// still a way to get the Script if it happens to still be alive.
class ScriptCacheKey : public HashTableKey {
public:
enum Index {
kHash,
kWeakScript,
kEnd,
};
ScriptCacheKey(Handle<String> source, const ScriptDetails* script_details,
Isolate* isolate);
ScriptCacheKey(Handle<String> source, MaybeHandle<Object> name,
int line_offset, int column_offset,
v8::ScriptOriginOptions origin_options,
MaybeHandle<Object> host_defined_options, Isolate* isolate);
bool IsMatch(Object other) override;
bool MatchesOrigin(Script script);
Handle<Object> AsHandle(Isolate* isolate, Handle<SharedFunctionInfo> shared);
static base::Optional<String> SourceFromObject(Object obj) {
DisallowGarbageCollection no_gc;
DCHECK(obj.IsWeakFixedArray());
WeakFixedArray array = WeakFixedArray::cast(obj);
DCHECK_EQ(array.length(), kEnd);
MaybeObject maybe_script = array.Get(kWeakScript);
if (HeapObject script; maybe_script.GetHeapObjectIfWeak(&script)) {
PrimitiveHeapObject source_or_undefined = Script::cast(script).source();
// Scripts stored in the script cache should always have a source string.
return String::cast(source_or_undefined);
}
DCHECK(maybe_script.IsCleared());
return {};
}
private:
Handle<String> source_;
MaybeHandle<Object> name_;
int line_offset_;
int column_offset_;
v8::ScriptOriginOptions origin_options_;
MaybeHandle<Object> host_defined_options_;
Isolate* isolate_;
};
uint32_t CompilationCacheShape::RegExpHash(String string, Smi flags) {
return string.EnsureHash() + flags.value();
}
uint32_t CompilationCacheShape::EvalHash(String source,
SharedFunctionInfo shared,
LanguageMode language_mode,
int position) {
uint32_t hash = source.EnsureHash();
if (shared.HasSourceCode()) {
// Instead of using the SharedFunctionInfo pointer in the hash
// code computation, we use a combination of the hash of the
// script source code and the start position of the calling scope.
// We do this to ensure that the cache entries can survive garbage
// collection.
Script script(Script::cast(shared.script()));
hash ^= String::cast(script.source()).EnsureHash();
}
static_assert(LanguageModeSize == 2);
if (is_strict(language_mode)) hash ^= 0x8000;
hash += position;
return hash;
}
uint32_t CompilationCacheShape::HashForObject(ReadOnlyRoots roots,
Object object) {
// Eval: The key field contains the hash as a Number.
if (object.IsNumber()) return static_cast<uint32_t>(object.Number());
// Code: The key field contains the SFI key.
if (object.IsSharedFunctionInfo()) {
return SharedFunctionInfo::cast(object).Hash();
}
// Script.
if (object.IsWeakFixedArray()) {
uint32_t result = static_cast<uint32_t>(Smi::ToInt(
WeakFixedArray::cast(object).Get(ScriptCacheKey::kHash).ToSmi()));
return result;
}
// Eval: See EvalCacheKey::ToHandle for the encoding.
FixedArray val = FixedArray::cast(object);
if (val.map() == roots.fixed_cow_array_map()) {
DCHECK_EQ(4, val.length());
String source = String::cast(val.get(1));
int language_unchecked = Smi::ToInt(val.get(2));
DCHECK(is_valid_language_mode(language_unchecked));
LanguageMode language_mode = static_cast<LanguageMode>(language_unchecked);
int position = Smi::ToInt(val.get(3));
Object shared = val.get(0);
return EvalHash(source, SharedFunctionInfo::cast(shared), language_mode,
position);
}
// RegExp: The key field (and the value field) contains the
// JSRegExp::data fixed array.
DCHECK_GE(val.length(), JSRegExp::kMinDataArrayLength);
return RegExpHash(String::cast(val.get(JSRegExp::kSourceIndex)),
Smi::cast(val.get(JSRegExp::kFlagsIndex)));
}
InfoCellPair::InfoCellPair(Isolate* isolate, SharedFunctionInfo shared,
FeedbackCell feedback_cell)
: is_compiled_scope_(!shared.is_null() ? shared.is_compiled_scope(isolate)
: IsCompiledScope()),
shared_(shared),
feedback_cell_(feedback_cell) {}
} // namespace internal
} // namespace v8
#include "src/objects/object-macros-undef.h"
#endif // V8_OBJECTS_COMPILATION_CACHE_TABLE_INL_H_
| 37.290503 | 80 | 0.697228 | [
"object"
] |
7e8a2f50909e6f8c1c54496e560e91f44eec6293 | 33,957 | h | C | _thirdPartyLibs/include/GLV/glv_model.h | stratosger/glGA-edu | de8d8e72e732921f63ef15cd787899f454787ab0 | [
"BSD-4-Clause-UC"
] | 4 | 2018-08-22T03:43:30.000Z | 2021-03-11T18:20:27.000Z | _thirdPartyLibs/include/GLV/glv_model.h | stratosger/glGA-edu | de8d8e72e732921f63ef15cd787899f454787ab0 | [
"BSD-4-Clause-UC"
] | 7 | 2020-10-06T16:34:12.000Z | 2020-12-06T17:29:22.000Z | _thirdPartyLibs/include/GLV/glv_model.h | stratosger/glGA-edu | de8d8e72e732921f63ef15cd787899f454787ab0 | [
"BSD-4-Clause-UC"
] | 71 | 2015-03-26T10:28:04.000Z | 2021-11-07T10:09:12.000Z | #ifndef INC_GLV_MODEL_H
#define INC_GLV_MODEL_H
/* Graphics Library of Views (GLV) - GUI Building Toolkit
See COPYRIGHT file for authors and license information */
#include <map>
#include <vector>
#include <string>
#include <stdio.h>
namespace glv {
class Data;
/// Determines whether string is a valid C identifier for a variable
bool isIdentifier(const std::string& s);
/// Convert object to a string. Returns number of elements converted.
template<class T>
int toString(std::string& dst, const T& src);
int toString(std::string& dst, const char * src);
/// Convert value to a string with user-defined formatting
template<class T>
int toString(std::string& dst, const T& src, const char * format);
/// Convert objects to a string. Returns number of elements converted.
template<class T>
int toString(std::string& dst, const T * src, int size, int stride=1);
/// Returns a stringification of an object
template <class T>
inline std::string toString(const T& obj){ std::string r; toString(r,obj); return r; }
/// Convert string token to object. Returns number of elements converted.
template<class T>
int fromToken(T& dst, const std::string& src);
/// Convert string token to objects. Returns number of elements converted.
template<class T>
int fromToken(T * dst, int size, int stride, const std::string& src);
/// Convert object to a string token. Returns number of elements converted.
template<class T>
int toToken(std::string& dst, const T& src);
int toToken(std::string& dst, const char * src);
/// Convert objects to a string token. Returns number of elements converted.
template<class T>
int toToken(std::string& dst, const T * src, int size, int stride=1);
/// Returns string token of an object
template <class T>
inline std::string toToken(const T& obj){ std::string r; toToken(r,obj); return r; }
/// Convert Data object to string
int toString(std::string& dst, const Data& src);
/// Convert Data object to token string
int toToken(std::string& dst, const Data& src);
/// Assign Data object elements from string
int fromToken(Data& dst, const std::string& src);
class ReferenceCounter {
public:
/// Returns number of pointers to memory address being managed
static int references(void * const m){ return counting(m) ? refCount()[m] : 0; }
protected:
typedef std::map<void *, int> RefCount;
// Begin counting reference or increment count if already counting
static void acquire(void * m){
if(!m) return; // do not count null pointers for obvious reasons
counting(m) ? ++refCount()[m] : refCount()[m]=1;
}
// Increment count of reference if reference is being counted
static void incrementCount(void * m){
if(counting(m)) ++refCount()[m];
}
// Returns true if the reference was being counted and can now be freed
static bool release(void * m){
if(counting(m)){
int& c = refCount()[m];
if(1==c){
refCount().erase(m);
return true;
}
--c;
}
return false;
}
static RefCount& refCount(){
static RefCount * o = new RefCount;
return *o;
}
// is reference being counted already?
static bool counting(void * const m){ return refCount().count(m) != 0; }
// static bool owner(void * const m){ return references(m) != 1; }
};
/// Iterates through multidmensional arrays
class Indexer{
public:
/// @param[in] size1 size of dimension 1
/// @param[in] size2 size of dimension 2
/// @param[in] size3 size of dimension 3
Indexer(int size1=1, int size2=1, int size3=1){
reset();
int sizes[] = {size1,size2,size3};
setSizes(sizes);
}
/// @param[in] sizes array of dimension sizes
Indexer(const int * sizes){
reset(); setSizes(sizes);
}
/// Perform one iteration returning whether more elements exist
bool operator()() const {
if(++mIndex[0] == mSizes[0]){
if(++mIndex[1] == mSizes[1]){
if(++mIndex[2] == mSizes[2]){
return false;
}
mIndex[1] = 0;
}
mIndex[0] = 0;
}
return true;
}
/// Get current index within a dimension
int operator[](int dim) const { return mIndex[dim]; }
/// Get one-dimensional index into plane
int indexFlat(int dim1, int dim2) const { return mIndex[dim2]*size(dim1) + mIndex[dim1]; }
/// Get current position within a dimension in half-open unit interval [0, 1)
double frac(int dim) const { return double(mIndex[dim])/mSizes[dim]; }
/// Get current position within a dimension in closed unit interval [0, 1]
double fracClosed(int dim) const { return double(mIndex[dim])/(mSizes[dim]-1); }
/// Get size of a dimension
int size(int dim) const { return mSizes[dim]; }
/// Get product of sizes of two dimensions
int size(int dim1, int dim2) const { return mSizes[dim1]*mSizes[dim2]; }
/// Get product of sizes of all dimensions
int size() const { int r=1; for(int i=0; i<N; ++i) r*=size(i); return r; }
/// Reset position indices
Indexer& reset(){ mIndex[0]=-1; for(int i=1; i<N; ++i){mIndex[i]=0;} return *this; }
/// Set dimensions
Indexer& shape(const int * sizes, int n){ setSizes(sizes,n); return *this; }
/// Set dimensions
Indexer& shape(int size1, int size2=1, int size3=1){
int sizes[] = {size1, size2, size3};
return shape(sizes, 3);
}
protected:
enum{N=3}; // max number of dimensions
mutable int mIndex[N]; // indices of current position in array
int mSizes[N]; // dimensions of array
void setSizes(const int* v, int n=N){ for(int i=0;i<n;++i) mSizes[i]=v[i]; }
};
#ifndef DATA_MAXDIM
#define DATA_MAXDIM 4
#endif
/// Dynamically typed multidimensional array of primitive values
/// For operations between data with different types, standard type conversions
/// will be used when possible.
/// For binary operations between arrays, each array is treated as a
/// one-dimensional array. If the number of elements differ, then the maximum
/// possible number of elements are used in the comparison.
class Data : public ReferenceCounter {
public:
/// Data types
enum Type{
BOOL=0, /**< */
INT, /**< */
FLOAT, /**< */
DOUBLE, /**< */
STRING, /**< */
NONE /**< */
};
static std::string typeToString(Type t);
template<class T> static Type getType();
/// Value returned by various member functions when they fail
static const int npos = static_cast<int>(-1);
/// This sets the data type to void and does not allocate memory
Data();
/// @param[in] v data to reference
Data(Data& v);
/// @param[in] v data to make clone of
Data(const Data& v);
/// Constructor that sets internal attributes without allocating memory
/// @param[in] type type of data
/// @param[in] size1 size of dimension 1
/// @param[in] size2 size of dimension 2
/// @param[in] size3 size of dimension 3
/// @param[in] size4 size of dimension 4
Data(Data::Type type, int size1=1, int size2=1, int size3=1, int size4=1);
/// @param[in] value external value to reference
template <class T>
explicit Data(T& value){ init(); set(&value, 1); }
/// @param[in] value value to make clone of
template <class T>
explicit Data(const T& value){ init(); set(&value, 1); }
/// @param[in] data pointer to external data to reference
/// @param[in] size1 size of dimension 1 of external data
/// @param[in] size2 size of dimension 2 of external data
/// @param[in] size3 size of dimension 3 of external data
/// @param[in] size4 size of dimension 4 of external data
template <class T>
Data(T * data, int size1, int size2=1, int size3=1, int size4=1){
init();
int sizes[] = {size1,size2,size3,size4};
set(data, sizes, 4);
}
~Data();
/// Returns whether elements from each array are equal
bool operator== (const Data& v) const;
/// Returns whether elements from each array are not equal
bool operator!= (const Data& v) const { return !((*this)==v); }
Data& operator+= (const Data& v);
/// Get element at 1D index, performing type conversion if necessary
template <class T> T at(int idx) const;
/// Get element at 2D index, performing type conversion if necessary
template <class T> T at(int i1, int i2) const;
/// Get element at 3D index, performing type conversion if necessary
template <class T> T at(int i1, int i2, int i3) const;
/// Get element at 4D index, performing type conversion if necessary
template <class T> T at(int i1, int i2, int i3, int i4) const;
/// Copy all elements into another array
template <class T> void copyTo(T * dst) const { for(int i=0;i<size();++i) dst[i]=at<T>(i); }
/// Get reference to element at 1D index using raw pointer casting
template <class T>
const T& elem(int i) const { return elems<T>()[i*stride()]; }
/// Get reference to element at 2D index using raw pointer casting
template <class T>
const T& elem(int i1, int i2) const { return elems<T>()[indexFlat(i1,i2)*stride()]; }
/// Get reference to element at 3D index using raw pointer casting
template <class T>
const T& elem(int i1, int i2, int i3) const { return elems<T>()[indexFlat(i1,i2,i3)*stride()]; }
/// Get reference to element at 4D index using raw pointer casting
template <class T>
const T& elem(int i1, int i2, int i3, int i4) const { return elems<T>()[indexFlat(i1,i2,i3,i4)*stride()]; }
/// Returns whether there is valid data that can be accessed
bool hasData() const { return mData!=0; }
/// Returns whether 2D index is within bounds
bool inBounds(int i1, int i2) const { return (i1>=0) && (i1<size(0)) && (i2>=0) && (i2<size(1)); }
/// Returns whether 3D index is within bounds
bool inBounds(int i1, int i2, int i3) const { return inBounds(i1,i2) && (i3>=0) && (i3<size(2)); }
/// Returns whether 4D index is within bounds
bool inBounds(int i1, int i2, int i3, int i4) const { return inBounds(i1,i2,i3) && (i4>=0) && (i4<size(3)); }
/// Convert 2D index to 1D index
int indexFlat(int i1, int i2) const {
return i1 + size(0)*i2;
}
/// Convert 3D index to 1D index
int indexFlat(int i1, int i2, int i3) const {
return i1 + size(0)*(i2 + size(1)*i3);
}
/// Convert 4D index to 1D index
int indexFlat(int i1, int i2, int i3, int i4) const {
return i1 + size(0)*(i2 + size(1)*(i3 + size(2)*i4));
}
/// Convert 1D index to 2D index
void indexDim(int& i1, int& i2, const int& i) const {
i1=i%size(0); i2=i/size(0);
}
/// Convert 1D index to 3D index
void indexDim(int& i1, int& i2, int& i3, const int& i) const {
indexDim(i1,i2,i); i2%=size(1); i3=i/(size(0,1));
}
/// Convert 1D index to 4D index
void indexDim(int& i1, int& i2, int& i3, int& i4, const int& i) const {
indexDim(i1,i2,i3,i); i3%=size(2); i4=i/(size(0,1,2));
}
/// Get index of first element matching argument or Data::npos if not found
int indexOf(const Data& v) const;
/// Get index of first element matching argument or Data::npos if not found
template <class T>
int indexOf(const T& v) const { return indexOf(Data(v)); }
/// Returns whether type is numerical, i.e., int, float, or double
bool isNumerical() const { return type() < Data::STRING; }
/// Returns true if all values are zero
bool isZero() const;
/// Get maximum allowable dimensions
static int maxDim(){ return DATA_MAXDIM; }
/// Get element offset into source array
int offset() const { return (mElems-mData)/sizeType(); }
/// Get number of dimensions sized larger than 1
int order() const;
/// Returns reversed slice
Data reversed() const { return slice((size()-1)*stride(), size(), -stride()); }
/// Get total number of elements
int size() const { return product(mSizes, maxDim()); }
int size(int d) const { return mSizes[d]; }
int size(int d1, int d2) const { return size(d1)*size(d2); }
int size(int d1, int d2, int d3) const { return size(d1,d2)*size(d3); }
int size(int d1, int d2, int d3, int d4) const { return size(d1,d2,d3)*size(d4); }
/// Get size array
const int * shape() const { return mSizes; }
/// Get size, in bytes, of element type
int sizeType() const;
/// Returns maximally sized 1D slice at given offset
Data slice(int offset=0) const { return slice(offset, size()-offset); }
/// Returns 1D slice with given offset, and size
Data slice(int offset, int size) const { return slice(offset,size,stride()); }
/// Returns 1D slice with given offset, size, and stride
/// @param[in] offset element offset from source data
/// @param[in] size number of elements in slice
/// @param[in] stride element stride through source data
Data slice(int offset, int size, int stride) const;
/// Get index stride
int stride() const { return mStride; }
/// Get element type
const Type& type() const { return mType; }
/// Print information to stdout
void print() const;
int fromToken(const std::string& v){ return glv::fromToken(*this, v); }
std::string toString() const { return glv::toString(*this); }
std::string toToken() const { return glv::toToken(*this); }
int toToken(std::string& dst) const { return glv::toToken(dst, *this); }
/// Perform shallow copy from another Data
Data& operator= (const Data& v);
/// Assign value to first element
template <class T>
Data& assign(const T& v){ return assignFromArray(&v,1); }
/// Assign value to element at 1D index
template <class T>
Data& assign(const T& v, int idx){ slice(idx).assign(v); return *this; }
/// Assign value to element at 2D index
template <class T>
Data& assign(const T& v, int i1, int i2){ return assign(v,indexFlat(i1,i2)); }
/// Assign value to element at 3D index
template <class T>
Data& assign(const T& v, int i1, int i2, int i3){ return assign(v,indexFlat(i1,i2,i3)); }
/// Assign value to element at 4D index
template <class T>
Data& assign(const T& v, int i1, int i2, int i3, int i4){ return assign(v,indexFlat(i1,i2,i3,i4)); }
/// Assign elements to elements from argument Data
Data& assign(const Data& v, int i=0);
/// Assign elements to elements from argument Data
Data& assign(const Data& v, int i1, int i2){ return assign(v, indexFlat(i1,i2)); }
/// Assign elements to elements from argument Data
Data& assign(const Data& v, int i1, int i2, int i3){ return assign(v, indexFlat(i1,i2,i3)); }
/// Assign elements to elements from argument Data
Data& assign(const Data& v, int i1, int i2, int i3, int i4){ return assign(v, indexFlat(i1,i2,i3,i4)); }
/// Assign all elements to argument
template <class T>
Data& assignAll(const T& v){ for(int i=0;i<size();++i){assign(v,i);} return *this; }
/// Assign elements from an external array
/// @param[in] src source array
/// @param[in] size size of source array
/// @param[in] stride amount to stride through source array
/// @param[in] idx destination starting index
template <class T>
Data& assignFromArray(const T * src, int size, int stride=1, int idx=0){
return assign(Data(const_cast<T*>(src), size).stride(stride), idx);
}
/// Clear contents, leaving the size equal to 0
void clear();
/// Allocate internal memory and copy over previous data
void clone();
/// Get mutable reference to element at 1D index using raw pointer casting
template <class T>
T& elem(int i){ return elems<T>()[i*stride()]; }
/// Get mutable reference to element at 2D index using raw pointer casting
template <class T>
T& elem(int i1, int i2){ return elems<T>()[indexFlat(i1,i2)*stride()]; }
/// Get mutable reference to element at 3D index using raw pointer casting
template <class T>
T& elem(int i1, int i2, int i3){ return elems<T>()[indexFlat(i1,i2,i3)*stride()]; }
/// Get mutable reference to element at 4D index using raw pointer casting
template <class T>
T& elem(int i1, int i2, int i3, int i4){ return elems<T>()[indexFlat(i1,i2,i3,i4)*stride()]; }
/// Returns pointer to first element
// note: this is potentially dangerous call, therefore use with caution...
template <class T>
T * elems(){ return (T *)mElems; }
/// Get pointer to first element
template <class T>
const T * elems() const { return (const T *)mElems; }
// TODO: insert elements
// // src source array
// // count number of source elements
// // idx destination start index
// // stride destination stride
// template <class T>
// Data& insert(const T* src, int count, int idx, int stride){
// return *this;
// }
/// Assign contents from mixture
void mix(const Data& d1, const Data& d2, double c1, double c2);
void mix(const Data& d1, const Data& d2, const Data& d3, const Data& d4, double c1, double c2, double c3, double c4);
template <int N> void mix(const Data* D[], double c[]);
/// Resize array allocating new memory if necessary
int resize(const int * sizes, int numDims){
return resize(type(), sizes, numDims);
}
/// Resize array allocating new memory if necessary
int resize(int size1, int size2=1, int size3=1, int size4=1){
int s[]={size1,size2,size3,size4};
return resize(s,4);
}
/// Resize array allocating new memory if necessary
int resize(Data::Type type, const int * sizes, int numDims);
/// Resize array allocating new memory if necessary
int resize(Data::Type type, int size1=1, int size2=1, int size3=1, int size4=1){
int s[]={size1,size2,size3,size4}; return resize(type, s,4);
}
/// Set data to reference a scalar
template <class T>
Data& set(T& v){ return set(&v,1); }
/// Set new data from a scalar with specified value
template <class T>
Data& set(const T& v){ return set(&v,1); }
/// Set new data from a character string
Data& set(const char * v){ return set(std::string(v)); }
/// Set data to reference an external multidimensional array
template <class T>
Data& set(T * data, const int * sizes, int numDims);
/// Set data to reference an external 1D array
template <class T>
Data& set(T * data, int size){ return set(data, &size,1); }
/// Set data to reference an external 2D array
template <class T>
Data& set(T * data, int size1, int size2){
int s[]={size1,size2}; return set(data, s,2); }
/// Set data to reference an external 3D array
template <class T>
Data& set(T * data, int size1, int size2, int size3){
int s[]={size1,size2,size3}; return set(data, s,3); }
/// Set data to reference an external 4D array
template <class T>
Data& set(T * data, int size1, int size2, int size3, int size4){
int s[]={size1,size2,size3,size4}; return set(data, s,4); }
/// Set dimensions without reallocing new memory
Data& shape(const int * sizes, int n);
/// Set dimensions without reallocing new memory
Data& shape(int n1, int n2=1, int n3=1, int n4=1){
int n[]={n1,n2,n3,n4}; return shape(n,4);
}
/// Set index stride factor
Data& stride(int v){ mStride=v; return *this; }
/// Change type of data
/// New memory will be allocated if the type differs from the current
/// type and the number of elements in the array is non-zero.
Data& type(Data::Type type);
// static int interpretToken(Data::Type& type, int *& sizes, std::string& src);
protected:
typedef char* pointer; // pointer to memory address;
// char vs. void to simplify pointer arithmetic
pointer mData; // pointer to first element of source data
pointer mElems; // pointer to first element in this slice
int mStride; // stride factor
int mSizes[DATA_MAXDIM]; // sizes of each dimension
Type mType; // data type
Data& offset(int i){ mElems=mData+i*sizeType(); return *this; }
Data& shapeAll(int n);
template <class T>
const T * data() const { return (const T *)mData; }
void init(){ // zeros all attributes (used in c'tor)
mData=0; mElems=0; mStride=1; mType=NONE;
shapeAll(0);
}
// Reallocate memory; returns size change, in bytes
int realloc(Data::Type type, const int * sizes=0, int n=0);
void setRaw(void * data, int offset, int stride, Type type);
int sizeBytes() const { return size()*sizeType(); }
static int product(const int * v, int n){
if(n){ int r=v[0]; for(int i=1;i<n;++i) r*=v[i]; return r; }
return 0;
}
template <int N, class T>
static bool notEqual(const T* v){
for(int i=1; i<N; ++i){ if(v[0] != v[i]) return true; }
return false;
}
};
/// An interface for accessing the model state of an object
class Model{
public:
virtual ~Model(){}
/// Get data associated with the model, if any
/// @param[in] temp Default constructed Data object passed in by callee.
/// This can be used as a return value in situations
/// where either the base class does not have its own
/// Data object or when some kind of conversion of the
/// data in its Data object needs to occur.
virtual const Data& getData(Data& temp) const { return temp; }
/// Set data associated with the model, if any
virtual void setData(const Data& d){}
/// Set data from a string
int setDataFromString(const std::string& v){
Data d;
(d = getData(d)).clone();
int r = d.fromToken(v);
if(r) setData(d);
return r;
}
/// Get data as string
std::string getDataAsString(){ Data d; return toString(getData(d)); }
};
/// Supplies a Data object with accessors
class DataObject{
public:
DataObject(){}
DataObject(Data& d): mData(d){}
const Data& data() const { return mData; }
Data& data(){ return mData; }
protected:
Data mData;
};
/// A Model that explicitly contains Data
class DataModel : public Model, public DataObject{
public:
DataModel(){}
DataModel(Data& d): DataObject(d){}
virtual ~DataModel(){}
virtual const Data& getData(Data& temp) const { return data(); }
virtual void setData(const Data& d){ data().assign(d); }
};
/*
class DataModel : public Model{
public:
DataModel(){}
DataModel(Data& d): mData(d){}
virtual ~DataModel(){}
virtual const Data& getData(Data& temp) const { return data(); }
virtual void setData(const Data& d){ assignData(d); }
// virtual std::string modelToString(){
// return data().toToken();
// }
//
int modelFromString(const std::string& v){
Data d = data();
d.clone();
int r = d.fromToken(v);
if(r) assignData(d);
return r;
}
const Data& data() const { return mData; }
Data& data(){ return mData; }
void assignData(const Data& d, const int& idx=0){
int i1=0,i2=0; data().indexDim(i1,i2, idx);
assignData(d, i1,i2);
}
// Assigns argument to elements at specified index.
// assignData() is called with the input data if the indices are valid.
// assignData() can be used to constrain the input data before it is
// assigned.
void assignData(const Data& d, int ind1, int ind2){
if(data().inBounds(ind1, ind2)){
Data t=d; t.clone();
if(onAssignData(t, ind1, ind2)){
//model().assign(t, ind1, ind2);
}
}
}
protected:
Data mData;
virtual bool onAssignData(Data& d, int ind1, int ind2){
data().assign(d, ind1, ind2);
return true;
}
};
*/
/*
memento object that stores snapshot of another object
originator object from which snapshot is taken
caretaker keeps a list of mementos
undo mechanism will request memento object from originator
class ModelState{
public:
virtual void toToken(std::string& dst);
virtual void fromToken(const std::string& src);
};
{
["preset 1"] = {
author = "John Doe",
time = 10293339107,
keywords = "fuzzy, buzzy",
buttons = {0, 1, 0, 1},
label = "hello",
},
["preset 2"] = {
author = "Don Jo",
time = 10293339108,
keywords = "funny, bunny",
buttons = {0, 0, 0, 1},
label = "world",
},
}
*/
/// Manages the saving/restoring of model parameters to/from memory and disk.
/// A NamedModel is a string/Model pair associated with a "live" parameter of
/// the application. A Snapshot is a recording of all the application's
/// NamedModels as string/Data pairs.
/// When a snapshot is loaded, only data having an identifier having an
/// identical identifier of an attached model is loaded. If an attached model
/// variable exists, but does not have a corresponding variable in a snapshot,
/// then the model data will not be modified when the snapshot is loaded.
class ModelManager{
public:
template <class Key, class Val>
class Map : public std::map<Key, Val>{
public:
const Val& operator[](const Key& key) const {
static const Val null;
typename Map::const_iterator it = find(key);
return (it!=this->end()) ? it->second : null;
}
Val& operator[](const Key& key){ return this->std::map<Key,Val>::operator[](key); }
};
typedef Map<std::string, Model*> NamedModels;
typedef Map<std::string, const Model*> NamedConstModels;
typedef Map<std::string, Data> Snapshot;
typedef Map<std::string, Snapshot> Snapshots;
/// Prints currently stored snapshots
void printSnapshots() const;
/// Get default file path
std::string filePath() const { std::string s=""; defaultFilePath(s); return s; }
/// Get identifier name
const std::string& name() const { return mName; }
/// Get snapshots
const Snapshots& snapshots() const { return mSnapshots; }
Snapshots& snapshots(){ return mSnapshots; }
/// Save all snapshots to a file
/// @param[in] path path to file; if empty, then uses "<name>.txt"
/// \returns number of characters written
int snapshotsToFile(const std::string& path="") const;
/// Returns a string of all snapshots
std::string snapshotsToString() const {
std::string r; snapshotsToString(r); return r;
}
/// Convert all snapshots to a table string
/// \returns number of characters written
///
int snapshotsToString(std::string& dst) const;
/// Set snapshot from a table string. If the snapshot does not exist, a new one will be created.
int snapshotFromString(const std::string& src);
/// Load snapshots from a file
/// @param[in] path path to file;
/// if empty, then uses model name with ".txt" extension
/// @param[in] addtoExisting whether to add to or replace any existing snapshots
/// \returns number of characters read
int snapshotsFromFile(const std::string& path="", bool addtoExisting=true);
/// Set snapshots from a table string. If a snapshot does not exist, a new one will be created.
int snapshotsFromString(const std::string& src);
/// Add reference to readable-writable model
/// The added Model should have the same lifecycle as 'this' since it is
/// referenced through a pointer.
void add(const std::string& name, Model& v);
/// Add reference to read-only model
/// The added Model should have the same lifecycle as 'this' since it is
/// referenced through a pointer.
void add(const std::string& name, const Model& v);
/// Remove all models
void clearModels();
/// Copy over models from another manager; replaces existing models
ModelManager& copyModels(const ModelManager& m);
/// Clear all currently stored snapshots
void clearSnapshots();
/// Set the default file directory and name
/// @param[in] name file name without directory;
/// if empty, then uses model name with ".txt" extension
/// @param[in] dir file directory
ModelManager& filePath(const std::string& name, const std::string& dir="");
/// Set the default file directory
/// @param[in] dir file directory
///
ModelManager& fileDir(const std::string& dir);
/// Set identifier name
ModelManager& name(const std::string& v);
/// Remove model data with given name
void remove(const std::string& name);
/// Save current model state as a snapshot with given name
/// If a snapshot with the given name exists, then it will be overwritten.
///
void saveSnapshot(const std::string& name);
/// Load snapshot with given name into current model state
/// \returns whether snapshot was loaded successfully
///
bool loadSnapshot(const std::string& name);
/// Load linear mixture of two snapshots
/// \returns whether snapshot mixture was loaded successfully
///
bool loadSnapshot(const std::string& name1, const std::string& name2, double c1, double c2);
bool loadSnapshot(const Snapshot& ss1, const Snapshot& ss2, double c1, double c2);
bool loadSnapshot(
const std::string& name1, const std::string& name2, const std::string& name3, const std::string& name4,
double c1, double c2, double c3, double c4);
bool loadSnapshot(
const Snapshot& ss1, const Snapshot& ss2, const Snapshot& ss3, const Snapshot& ss4,
double c1, double c2, double c3, double c4);
void makeClosed();
protected:
std::string mName; // name identifier
std::string mFileDir, mFileName;// directory and name of file
NamedModels mState; // pointers to active readable/writable models
NamedConstModels mConstState; // pointers to active read-only models
Snapshots mSnapshots; // repository of saved model data
// // Convert current model state to string
// bool stateToToken(std::string& dst, const std::string& modelName) const;
// // Convert string to model state
// int stateFromToken(const std::string& src);
bool defaultFilePath(std::string& s) const;
// template <int N> bool loadSnapshot(const std::string ** names, const double * c);
// template <int N> bool loadSnapshot(const Snapshot ** snapshots, const double * c);
static std::string namedDataToString(const std::string& s, const Data& d){
std::string r;
if(d.toToken(r)) r = s + " = " + r + ",\r\n";
return r;
}
};
// Implementation ______________________________________________________________
template<class T>
int toString(std::string& dst, const T& src, const char * format){
#ifdef WIN32
#define TO_STRING_FUNC _snprintf
#else
#define TO_STRING_FUNC snprintf
#endif
char buf[32];
TO_STRING_FUNC(buf, sizeof(buf), format, src);
dst = buf;
#undef TO_STRING_FUNC
return 1;
}
template<class T>
inline int stringifyArray(
std::string& dst, const T * src, int size, int stride,
int (*stringifyElem)(std::string&, const T&)
){
if(1==size){ return stringifyElem(dst, *src); }
else{
dst = "";
std::string temp;
int count=0;
for(int i=0; i<size; ++i){
count += stringifyElem(temp, src[i*stride]);
dst += temp;
if(i != (size-1)) dst += ", ";
}
return count;
}
}
template<class T>
int toString(std::string& dst, const T * src, int size, int stride){
return stringifyArray<T>(dst,src,size,stride, toString);
}
template<class T>
inline int toToken(std::string& dst, const T& src){ return toString(dst,src); }
template<>
inline int toToken<std::string>(std::string& dst, const std::string& src){
dst = "\"" + src + "\""; return 1;
}
template<class T>
int toToken(std::string& dst, const T * src, int size, int stride){
int res = stringifyArray<T>(dst,src,size,stride, toToken);
if(1!=size) dst = "{" + dst + "}";
return res;
}
// Data ________________________________________________________________________
template<> inline Data::Type Data::getType<bool>(){ return Data::BOOL; }
template<> inline Data::Type Data::getType<int>(){ return Data::INT; }
template<> inline Data::Type Data::getType<float>(){ return Data::FLOAT; }
template<> inline Data::Type Data::getType<double>(){ return Data::DOUBLE; }
template<> inline Data::Type Data::getType<std::string>(){ return Data::STRING; }
template <class T>
T Data::at(int i) const {
#define CS(TY,t) case Data::TY: return static_cast<const T>(elem<t>(i));
switch(type()){
CS(BOOL,bool) CS(INT,int) CS(FLOAT,float) CS(DOUBLE,double)
case Data::STRING: {
T v; if(glv::fromToken(v, elem<std::string>(i))){ return v; }
}
default: return T();
}
#undef CS
}
template<>
inline std::string Data::at<std::string>(int i) const {
#define CS(T,t) case Data::T: return glv::toString(elem<t>(i));
switch(type()){
CS(BOOL,bool) CS(INT,int) CS(FLOAT,float) CS(DOUBLE,double)
CS(STRING,std::string)
default: return "";
}
#undef CS
}
template <class T>
inline T Data::at(int i1, int i2) const { return at<T>(indexFlat(i1,i2)); }
template <class T>
inline T Data::at(int i1, int i2, int i3) const { return at<T>(indexFlat(i1,i2,i3)); }
template <class T>
inline T Data::at(int i1, int i2, int i3, int i4) const { return at<T>(indexFlat(i1,i2,i3,i4)); }
#define DATA_SET(t, T)\
template<> inline Data& Data::set<t>(t * src, const int * sizes, int n){\
setRaw(src,0,1,Data::T); shape(sizes,n); return *this;\
}\
template<> inline Data& Data::set<const t>(const t * src, const int * sizes, int n){\
if(product(sizes,n)!=size() || Data::T!=type()) realloc(Data::T, sizes,n);\
for(int i=0; i<size(); ++i){ elems<t>()[i] = src[i]; }\
return *this;\
}
DATA_SET(bool, BOOL)
DATA_SET(int, INT)
DATA_SET(float, FLOAT)
DATA_SET(double, DOUBLE)
DATA_SET(std::string, STRING)
//template<> inline Data& Data::set<char *>(char* * src, const int * sizes, int n){
// setRaw(src,0,1,Data::STRING); shape(sizes,n); return *this;
//}
#undef DATA_SET
inline void Data::mix(const Data& d1, const Data& d2, double c1, double c2){
const Data* d[]={&d1,&d2};
double c[]={c1,c2};
mix<2>(d,c);
}
inline void Data::mix(
const Data& d1, const Data& d2, const Data& d3, const Data& d4,
double c1, double c2, double c3, double c4
){
const Data* d[]={&d1,&d2,&d3,&d4};
double c[]={c1,c2,c3,c4};
mix<4>(d,c);
}
template <int M>
void Data::mix(const Data* D[], double c[]){
int N = size();
//bool isNum = isNumerical();
bool isNum = true;
for(int i=0; i<M; ++i){
const Data& d = *D[i];
int sz = d.size();
if(sz < N) N = sz;
isNum &= d.isNumerical()
&& (d.type() != Data::BOOL);
}
// TODO: make this more efficient...
if(isNum){
double v[M];
for(int i=0; i<N; ++i){
for(int m=0; m<M; ++m) v[m] = D[m]->at<double>(i);
if(notEqual<M>(v)){ // avoid numerical error
double res = v[0]*c[0];
for(int m=1; m<M; ++m) res += v[m]*c[m];
// for booleans, we truncate first
//if(type() == Data::BOOL) assign(int(res), i);
//else assign(res, i);
assign(res, i);
}
else{
assign(v[0], i);
}
}
}
else{ // for strings and bools copy the lower index middle element
assign(*D[M/2-1]);
}
}
/// This assumes that all snapshots are members of a closed set
//template <int N>
//bool ModelManager::loadSnapshot(const Snapshot ** S, double * c){
//
// Snapshot::const_iterator it[N];
// for(int i=0; i<N; ++i) it[i] = S[i]->begin();
//
// while(S[0]->end() != it[0]){
//
// const Data * D[N];
// for(int i=0; i<N; ++i) D[i] = &(it[i]->second);
//
// Data temp = data1;
// temp.clone();
// temp.mix<N>(D, c);
// itState->second->setData(temp);
//
// for(int i=0; i<N; ++i) ++(it[i]);
// }
// return true;
//}
} // glv::
#endif
| 29.656769 | 118 | 0.672939 | [
"object",
"shape",
"vector",
"model",
"3d"
] |
7e8f7271b15c01128ae6c013b001e7568a4e29f2 | 3,017 | h | C | src/libcore/inc/ccm/misc/FloatConsts.h | sparkoss/ccm | 9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d | [
"Apache-2.0"
] | 6 | 2018-05-08T10:08:21.000Z | 2021-11-13T13:22:58.000Z | src/libcore/inc/ccm/misc/FloatConsts.h | sparkoss/ccm | 9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d | [
"Apache-2.0"
] | 1 | 2018-05-08T10:20:17.000Z | 2018-07-23T05:19:19.000Z | src/libcore/inc/ccm/misc/FloatConsts.h | sparkoss/ccm | 9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d | [
"Apache-2.0"
] | 4 | 2018-03-13T06:21:11.000Z | 2021-06-19T02:48:07.000Z | //=========================================================================
// Copyright (C) 2018 The C++ Component Model(CCM) Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#ifndef __CCM_MISC_FLOATCONSTS_H__
#define __CCM_MISC_FLOATCONSTS_H__
#include <ccmtypes.h>
namespace ccm {
namespace misc {
class FloatConsts
{
public:
static const Float POSITIVE_INFINITY;
static const Float NEGATIVE_INFINITY;
static const Float NaN;
static const Float MAX_VALUE;
static const Float MIN_VALUE;
/**
* A constant holding the smallest positive normal value of type
* <code>float</code>, 2<sup>-126</sup>. It is equal to the value
* returned by <code>Float.intBitsToFloat(0x00800000)</code>.
*/
static constexpr Float MIN_NORMAL = 1.17549435E-38f;
/**
* The number of logical bits in the significand of a
* <code>float</code> number, including the implicit bit.
*/
static constexpr Integer SIGNIFICAND_WIDTH = 24;
/**
* Maximum exponent a finite <code>float</code> number may have.
* It is equal to the value returned by
* <code>Math.ilogb(Float.MAX_VALUE)</code>.
*/
static constexpr Integer MAX_EXPONENT = 127;
/**
* Minimum exponent a normalized <code>float</code> number may
* have. It is equal to the value returned by
* <code>Math.ilogb(Float.MIN_NORMAL)</code>.
*/
static constexpr Integer MIN_EXPONENT = -126;
/**
* The exponent the smallest positive <code>float</code> subnormal
* value would have if it could be normalized. It is equal to the
* value returned by <code>FpUtils.ilogb(Float.MIN_VALUE)</code>.
*/
static constexpr Integer MIN_SUB_EXPONENT = MIN_EXPONENT - (SIGNIFICAND_WIDTH - 1);
/**
* Bias used in representing a <code>float</code> exponent.
*/
static constexpr Integer EXP_BIAS = 127;
/**
* Bit mask to isolate the sign bit of a <code>float</code>.
*/
static constexpr Integer SIGN_BIT_MASK = 0x80000000;
/**
* Bit mask to isolate the exponent field of a
* <code>float</code>.
*/
static constexpr Integer EXP_BIT_MASK = 0x7F800000;
/**
* Bit mask to isolate the significand field of a
* <code>float</code>.
*/
static constexpr Integer SIGNIF_BIT_MASK = 0x007FFFFF;
private:
FloatConsts();
};
}
}
#endif // __CCM_MISC_FLOATCONSTS_H__
| 30.785714 | 87 | 0.647663 | [
"model"
] |
7e992d0bc475d739cb29100685319c71f42457f6 | 11,657 | c | C | kernel/drivers/video/fbdev/hisi/dss/hisi_dss_sync.c | wonderful666/marx-10.1.0 | a8be8880fe31bff4f94d6e3fad17c455666ff60f | [
"MIT"
] | null | null | null | kernel/drivers/video/fbdev/hisi/dss/hisi_dss_sync.c | wonderful666/marx-10.1.0 | a8be8880fe31bff4f94d6e3fad17c455666ff60f | [
"MIT"
] | null | null | null | kernel/drivers/video/fbdev/hisi/dss/hisi_dss_sync.c | wonderful666/marx-10.1.0 | a8be8880fe31bff4f94d6e3fad17c455666ff60f | [
"MIT"
] | null | null | null | /* Copyright (c) 2015-2018, Hisilicon Tech. Co., Ltd. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only 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.
*
*/
#include <linux/fs.h>
#include <linux/file.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/sync_file.h>
#include "hisi_dss_sync.h"
#include "hisi_fb.h"
#define HISI_DSS_SYNC_NAME_SIZE 64
#define HISI_DSS_SYNC_DRIVER_NAME "hisi_dss"
#if defined(CONFIG_SYNC_FILE)
/*
* to_hisi_dss_fence - get hisi dss fence from fence base object
* @fence: Pointer to fence base object
*/
static struct hisi_dss_fence *to_hisi_dss_fence(dss_dma_fence_t *fence)
{
return container_of(fence, struct hisi_dss_fence, base);
}
/*
* to_hisi_dss_timeline - get hisi dss timeline from fence base object
* @fence: Pointer to fence base object
*/
static struct hisi_dss_timeline *to_hisi_dss_timeline(dss_dma_fence_t *fence)
{
return container_of(fence->lock, struct hisi_dss_timeline, lock);
}
/*
* hisi_dss_free_timeline - Free the given timeline object
* @kref: Pointer to timeline kref object.
*/
static void hisi_dss_free_timeline(struct kref *kref)
{
struct hisi_dss_timeline *tl =
container_of(kref, struct hisi_dss_timeline, kref);
kfree(tl);
}
/*
* hisi_dss_put_timeline - Put the given timeline object
* @tl: Pointer to timeline object.
*/
static void hisi_dss_put_timeline(struct hisi_dss_timeline *tl)
{
if (!tl) {
HISI_FB_ERR("invalid parameters\n");
return;
}
kref_put(&tl->kref, hisi_dss_free_timeline);
}
/*
* hisi_dss_get_timeline - Get the given timeline object
* @tl: Pointer to timeline object.
*/
static void hisi_dss_get_timeline(struct hisi_dss_timeline *tl)
{
if (!tl) {
HISI_FB_ERR("invalid parameters\n");
return;
}
kref_get(&tl->kref);
}
static const char *hisi_dss_fence_get_driver_name(dss_dma_fence_t *fence)
{
return HISI_DSS_SYNC_DRIVER_NAME;
}
static const char *hisi_dss_fence_get_timeline_name(dss_dma_fence_t *fence)
{
struct hisi_dss_timeline *tl = to_hisi_dss_timeline(fence);
return tl->name;
}
static bool hisi_dss_fence_enable_signaling(dss_dma_fence_t *fence)
{
return true;
}
static bool hisi_dss_fence_signaled(dss_dma_fence_t *fence)
{
struct hisi_dss_timeline *tl = to_hisi_dss_timeline(fence);
bool status;
status = ((s32) (tl->value - fence->seqno)) >= 0;
return status;
}
static void hisi_dss_fence_release(dss_dma_fence_t *fence)
{
struct hisi_dss_fence *f = to_hisi_dss_fence(fence);
struct hisi_dss_timeline *tl = to_hisi_dss_timeline(fence);
unsigned long flags;
if (g_debug_fence_timeline) {
HISI_FB_INFO("release for fence %s\n", f->name);
}
spin_lock_irqsave(&tl->list_lock, flags);
if (!list_empty(&f->fence_list))
list_del(&f->fence_list);
spin_unlock_irqrestore(&tl->list_lock, flags);
hisi_dss_put_timeline(to_hisi_dss_timeline(fence));
kfree_rcu(f, base.rcu); //lint !e571 !e666
}
static void hisi_dss_fence_value_str(dss_dma_fence_t *fence, char *str, int size)
{
snprintf(str, size, "%u", fence->seqno);
}
static void hisi_dss_fence_timeline_value_str(dss_dma_fence_t *fence, char *str,
int size)
{
struct hisi_dss_timeline *tl = to_hisi_dss_timeline(fence);
snprintf(str, size, "%u", tl->value);
}
static struct dma_fence_ops hisi_dss_fence_ops = {
.get_driver_name = hisi_dss_fence_get_driver_name,
.get_timeline_name = hisi_dss_fence_get_timeline_name,
.enable_signaling = hisi_dss_fence_enable_signaling,
.signaled = hisi_dss_fence_signaled,
.wait = dma_fence_default_wait,
.release = hisi_dss_fence_release,
.fence_value_str = hisi_dss_fence_value_str,
.timeline_value_str = hisi_dss_fence_timeline_value_str,
};
/*
* hisi_dss_create_timeline - Create timeline object with the given name
* @name: Pointer to name character string.
*/
struct hisi_dss_timeline *hisi_dss_create_timeline(const char *name)
{
struct hisi_dss_timeline *tl;
if (!name) {
HISI_FB_ERR("invalid parameters\n");
return NULL;
}
tl = kzalloc(sizeof(struct hisi_dss_timeline), GFP_KERNEL);
if (!tl)
return NULL;
kref_init(&tl->kref);
snprintf(tl->name, sizeof(tl->name), "%s", name);
spin_lock_init(&tl->lock);
spin_lock_init(&tl->list_lock);
tl->context = dma_fence_context_alloc(1);
INIT_LIST_HEAD(&tl->fence_list_head);
return tl;
}
/*
* hisi_dss_destroy_timeline - Destroy the given timeline object
* @tl: Pointer to timeline object.
*/
void hisi_dss_destroy_timeline(struct hisi_dss_timeline *tl)
{
hisi_dss_put_timeline(tl);
}
/*
* hisi_dss_inc_timeline_locked - Increment timeline by given amount
* @tl: Pointer to timeline object.
* @increment: the amount to increase the timeline by.
*/
static int hisi_dss_inc_timeline_locked(struct hisi_dss_timeline *tl,
int increment)
{
struct hisi_dss_fence *f, *next;
s32 val;
bool is_signaled = false;
struct list_head local_list_head;
unsigned long flags;
INIT_LIST_HEAD(&local_list_head);
spin_lock(&tl->list_lock);
if (list_empty(&tl->fence_list_head)) {
HISI_FB_DEBUG("fence list is empty\n");
tl->value += 1;
spin_unlock(&tl->list_lock);
return 0;
}
list_for_each_entry_safe(f, next, &tl->fence_list_head, fence_list)
list_move(&f->fence_list, &local_list_head);
spin_unlock(&tl->list_lock);
spin_lock_irqsave(&tl->lock, flags);
val = tl->next_value - tl->value;
if (val < increment) {
HISI_FB_INFO("timeline->value didnot update, val:%d, inc:%d, tl->value:%d!\n", val, increment, tl->value);
}
tl->value += increment;
spin_unlock_irqrestore(&tl->lock, flags);
list_for_each_entry_safe(f, next, &local_list_head, fence_list) {
spin_lock_irqsave(&tl->lock, flags);
is_signaled = dma_fence_is_signaled_locked(&f->base);
spin_unlock_irqrestore(&tl->lock, flags);
if (is_signaled) {
if (g_debug_fence_timeline) {
HISI_FB_INFO("%s signaled\n", f->name);
}
list_del_init(&f->fence_list);
dma_fence_put(&f->base);
} else {
spin_lock(&tl->list_lock);
list_move(&f->fence_list, &tl->fence_list_head);
spin_unlock(&tl->list_lock);
}
}
return 0;
}
/*
* hisi_dss_resync_timeline - Resync timeline to last committed value
* @tl: Pointer to timeline object.
*/
void hisi_dss_resync_timeline(struct hisi_dss_timeline *tl)
{
s32 val;
if (!tl) {
pr_err("invalid parameters\n");
return;
}
val = tl->next_value - tl->value;
if (val > 0) {
if (g_debug_fence_timeline) {
HISI_FB_INFO("flush %s:%d TL(Nxt %d , Crnt %d)\n", tl->name, val,
tl->next_value, tl->value);
}
hisi_dss_inc_timeline_locked(tl, val);
}
}
/*lint -e429 */
/*
* hisi_dss_get_sync_fence - Create fence object from the given timeline
* @tl: Pointer to timeline object
* @timestamp: Pointer to timestamp of the returned fence. Null if not required.
* Return: pointer fence created on give time line.
*/
struct hisi_dss_fence *hisi_dss_get_sync_fence(
struct hisi_dss_timeline *tl, const char *fence_name,
u32 *timestamp, int value)
{
struct hisi_dss_fence *f; //lint !e429
unsigned long flags;
if (!tl) {
HISI_FB_ERR("invalid parameters\n");
return NULL;
}
f = kzalloc(sizeof(struct hisi_dss_fence), GFP_KERNEL);
if (!f)
return NULL;
INIT_LIST_HEAD(&f->fence_list);
spin_lock_irqsave(&tl->lock, flags);
tl->next_value = value;
dma_fence_init(&f->base, &hisi_dss_fence_ops, &tl->lock, tl->context, value);
hisi_dss_get_timeline(tl);
spin_unlock_irqrestore(&tl->lock, flags);
spin_lock_irqsave(&tl->list_lock, flags);
list_add_tail(&f->fence_list, &tl->fence_list_head);
spin_unlock_irqrestore(&tl->list_lock, flags);
snprintf(f->name, sizeof(f->name), "%s_%u", fence_name, value);
if (timestamp)
*timestamp = value;
if (g_debug_fence_timeline) {
HISI_FB_INFO("fence created at val=%u tl->name=%s tl->value=%d tl->next_value=%d\n",
value, tl->name, tl->value, tl->next_value);
}
return f; //lint !e429
}
/*lint +e429 */
/*
* hisi_dss_inc_timeline - Increment timeline by given amount
* @tl: Pointer to timeline object.
* @increment: the amount to increase the timeline by.
*/
int hisi_dss_inc_timeline(struct hisi_dss_timeline *tl, int increment)
{
int rc;
if (!tl) {
HISI_FB_ERR("invalid parameters\n");
return -EINVAL;
}
rc = hisi_dss_inc_timeline_locked(tl, increment);
return rc;
}
/*
* hisi_dss_get_timeline_commit_ts - Return commit tick of given timeline
* @tl: Pointer to timeline object.
*/
u32 hisi_dss_get_timeline_commit_ts(struct hisi_dss_timeline *tl)
{
if (!tl) {
HISI_FB_ERR("invalid parameters\n");
return 0;
}
return tl->next_value;
}
/*
* hisi_dss_get_timeline_retire_ts - Return retire tick of given timeline
* @tl: Pointer to timeline object.
*/
u32 hisi_dss_get_timeline_retire_ts(struct hisi_dss_timeline *tl)
{
if (!tl) {
HISI_FB_ERR("invalid parameters\n");
return 0;
}
return tl->value;
}
/*
* hisi_dss_put_sync_fence - Destroy given fence object
* @fence: Pointer to fence object.
*/
void hisi_dss_put_sync_fence(struct hisi_dss_fence *fence)
{
if (!fence) {
HISI_FB_ERR("invalid parameters\n");
return;
}
dma_fence_put((dss_dma_fence_t *) fence);
}
/*
* hisi_dss_wait_sync_fence - Wait until fence signal or timeout
* @fence: Pointer to fence object.
* @timeout: maximum wait time, in msec, for fence to signal.
*/
int hisi_dss_wait_sync_fence(struct hisi_dss_fence *fence,
long timeout)
{
int rc;
if (!fence) {
HISI_FB_ERR("invalid parameters\n");
return -EINVAL;
}
rc = dma_fence_wait_timeout((dss_dma_fence_t *) fence, false,
msecs_to_jiffies(timeout));
if (rc > 0) {
if (g_debug_fence_timeline) {
dss_dma_fence_t *input_fence = (dss_dma_fence_t *) fence;
HISI_FB_INFO(
"drv:%s timeline:%s seqno:%d\n",
input_fence->ops->get_driver_name(input_fence),
input_fence->ops->get_timeline_name(input_fence),
input_fence->seqno);
}
rc = 0;
} else if (rc == 0) {
dss_dma_fence_t *input_fence = (dss_dma_fence_t *) fence;
HISI_FB_ERR(
"drv:%s timeline:%s seqno:%d.\n",
input_fence->ops->get_driver_name(input_fence),
input_fence->ops->get_timeline_name(input_fence),
input_fence->seqno);
rc = -ETIMEDOUT;
}
return rc;
}
/*
* hisi_dss_get_fd_sync_fence - Get fence object of given file descriptor
* @fd: File description of fence object.
*/
struct hisi_dss_fence *hisi_dss_get_fd_sync_fence(int fd)
{
return (struct hisi_dss_fence *) sync_file_get_fence(fd);
}
/*
* hisi_dss_get_sync_fence_fd - Get file descriptor of given fence object
* @fence: Pointer to fence object.
* Return: File descriptor on success, or error code on error
*/
int hisi_dss_get_sync_fence_fd(struct hisi_dss_fence *fence)
{
int fd;
struct sync_file *sync_file;
if (!fence) {
HISI_FB_ERR("invalid parameters\n");
return -EINVAL;
}
fd = get_unused_fd_flags(O_CLOEXEC);
if (fd < 0) {
HISI_FB_ERR("fail to get unused fd\n");
return fd;
}
sync_file = sync_file_create((dss_dma_fence_t *) fence);
if (!sync_file) {
put_unused_fd(fd);
HISI_FB_ERR("failed to create sync file\n");
return -ENOMEM;
}
fd_install(fd, sync_file->file);
return fd;
}
/*
* hisi_dss_get_sync_fence_name - get given fence object name
* @fence: Pointer to fence object.
* Return: fence name
*/
const char *hisi_dss_get_sync_fence_name(struct hisi_dss_fence *fence)
{
if (!fence) {
HISI_FB_ERR("invalid parameters\n");
return NULL;
}
return fence->name;
}
#endif
| 24.697034 | 108 | 0.731234 | [
"object"
] |
7e9b4851e278713e3558ed74f173a440a170f34b | 4,690 | h | C | wss/include/tencentcloud/wss/v20180426/WssClient.h | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | wss/include/tencentcloud/wss/v20180426/WssClient.h | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | wss/include/tencentcloud/wss/v20180426/WssClient.h | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_WSS_V20180426_WSSCLIENT_H_
#define TENCENTCLOUD_WSS_V20180426_WSSCLIENT_H_
#include <functional>
#include <future>
#include <tencentcloud/core/AbstractClient.h>
#include <tencentcloud/core/Credential.h>
#include <tencentcloud/core/profile/ClientProfile.h>
#include <tencentcloud/core/AsyncCallerContext.h>
#include <tencentcloud/wss/v20180426/model/DeleteCertRequest.h>
#include <tencentcloud/wss/v20180426/model/DeleteCertResponse.h>
#include <tencentcloud/wss/v20180426/model/DescribeCertListRequest.h>
#include <tencentcloud/wss/v20180426/model/DescribeCertListResponse.h>
#include <tencentcloud/wss/v20180426/model/UploadCertRequest.h>
#include <tencentcloud/wss/v20180426/model/UploadCertResponse.h>
namespace TencentCloud
{
namespace Wss
{
namespace V20180426
{
class WssClient : public AbstractClient
{
public:
WssClient(const Credential &credential, const std::string ®ion);
WssClient(const Credential &credential, const std::string ®ion, const ClientProfile &profile);
typedef Outcome<Core::Error, Model::DeleteCertResponse> DeleteCertOutcome;
typedef std::future<DeleteCertOutcome> DeleteCertOutcomeCallable;
typedef std::function<void(const WssClient*, const Model::DeleteCertRequest&, DeleteCertOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DeleteCertAsyncHandler;
typedef Outcome<Core::Error, Model::DescribeCertListResponse> DescribeCertListOutcome;
typedef std::future<DescribeCertListOutcome> DescribeCertListOutcomeCallable;
typedef std::function<void(const WssClient*, const Model::DescribeCertListRequest&, DescribeCertListOutcome, const std::shared_ptr<const AsyncCallerContext>&)> DescribeCertListAsyncHandler;
typedef Outcome<Core::Error, Model::UploadCertResponse> UploadCertOutcome;
typedef std::future<UploadCertOutcome> UploadCertOutcomeCallable;
typedef std::function<void(const WssClient*, const Model::UploadCertRequest&, UploadCertOutcome, const std::shared_ptr<const AsyncCallerContext>&)> UploadCertAsyncHandler;
/**
*本接口(DeleteCert)用于删除证书。
* @param req DeleteCertRequest
* @return DeleteCertOutcome
*/
DeleteCertOutcome DeleteCert(const Model::DeleteCertRequest &request);
void DeleteCertAsync(const Model::DeleteCertRequest& request, const DeleteCertAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr);
DeleteCertOutcomeCallable DeleteCertCallable(const Model::DeleteCertRequest& request);
/**
*本接口(DescribeCertList)用于获取证书列表。
* @param req DescribeCertListRequest
* @return DescribeCertListOutcome
*/
DescribeCertListOutcome DescribeCertList(const Model::DescribeCertListRequest &request);
void DescribeCertListAsync(const Model::DescribeCertListRequest& request, const DescribeCertListAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr);
DescribeCertListOutcomeCallable DescribeCertListCallable(const Model::DescribeCertListRequest& request);
/**
*本接口(UploadCert)用于上传证书。
* @param req UploadCertRequest
* @return UploadCertOutcome
*/
UploadCertOutcome UploadCert(const Model::UploadCertRequest &request);
void UploadCertAsync(const Model::UploadCertRequest& request, const UploadCertAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr);
UploadCertOutcomeCallable UploadCertCallable(const Model::UploadCertRequest& request);
};
}
}
}
#endif // !TENCENTCLOUD_WSS_V20180426_WSSCLIENT_H_
| 51.538462 | 205 | 0.706397 | [
"model"
] |
7ea7fe52ed1bb783152fc65926917a317be4c011 | 735 | h | C | LibLemon/include/Lemon/Graphics/Surface.h | edithlzh/LemonOS | fd519fc12ceb6b33e3e23b449867d59d9f32a52e | [
"BSD-2-Clause"
] | 685 | 2021-02-21T22:14:22.000Z | 2022-03-31T18:05:34.000Z | LibLemon/include/Lemon/Graphics/Surface.h | edithlzh/LemonOS | fd519fc12ceb6b33e3e23b449867d59d9f32a52e | [
"BSD-2-Clause"
] | 22 | 2021-02-27T12:40:06.000Z | 2022-03-28T15:17:24.000Z | LibLemon/include/Lemon/Graphics/Surface.h | edithlzh/LemonOS | fd519fc12ceb6b33e3e23b449867d59d9f32a52e | [
"BSD-2-Clause"
] | 36 | 2021-03-05T08:13:24.000Z | 2022-03-15T19:51:33.000Z | #pragma once
#include <stdint.h>
#include <Lemon/Graphics/Rect.h>
#include <Lemon/Graphics/Vector.h>
typedef struct Surface {
int width = 0;
int height = 0; // Self-explanatory
uint8_t depth = 32; // Pixel depth, unsupported
uint8_t* buffer = nullptr; // Start of the buffer
// Returns buffer size in bytes
inline unsigned BufferSize() const { return width * height * (depth >> 3); }
void Blit(const Surface* src);
void Blit(const Surface* src, const Vector2i& offset);
void Blit(const Surface* src, const Vector2i& offset, const struct Rect& region);
void AlphaBlit(const Surface* src, const Vector2i& offset, const Rect& region = {0, 0, INT_MAX, INT_MAX});
} surface_t;
| 33.409091 | 110 | 0.669388 | [
"vector"
] |
7eb33596c43430365b229550c14360494187ec0a | 20,934 | h | C | include/radosstriper/libradosstriper.h | liucxer/ceph-msg | 2e5c18c0c72253b283bfd3d0576033c0b515ce55 | [
"Apache-2.0"
] | null | null | null | include/radosstriper/libradosstriper.h | liucxer/ceph-msg | 2e5c18c0c72253b283bfd3d0576033c0b515ce55 | [
"Apache-2.0"
] | null | null | null | include/radosstriper/libradosstriper.h | liucxer/ceph-msg | 2e5c18c0c72253b283bfd3d0576033c0b515ce55 | [
"Apache-2.0"
] | null | null | null | #ifndef CEPH_LIBRADOSSTRIPER_H
#define CEPH_LIBRADOSSTRIPER_H
#ifdef __cplusplus
extern "C" {
#endif
#include <string.h>
#include "../rados/librados.h"
#define LIBRADOSSTRIPER_VER_MAJOR 0
#define LIBRADOSSTRIPER_VER_MINOR 0
#define LIBRADOSSTRIPER_VER_EXTRA 0
#define LIBRADOSSTRIPER_VERSION(maj, min, extra) ((maj << 16) + (min << 8) + extra)
#define LIBRADOSSTRIPER_VERSION_CODE LIBRADOSSTRIPER_VERSION(LIBRADOSSTRIPER_VER_MAJOR, LIBRADOSSTRIPER_VER_MINOR, LIBRADOSSTRIPER_VER_EXTRA)
/**
* @typedef rados_striper_t
*
* A handle for interacting with striped objects in a RADOS cluster.
*/
typedef void *rados_striper_t;
/**
* @defgroup libradosstriper_h_init Setup and Teardown
* These are the first and last functions to that should be called
* when using libradosstriper.
*
* @{
*/
/**
* Creates a rados striper using the given io context
* Striper has initially default object layout.
* See rados_striper_set_object_layout_*() to change this
*
* @param ioctx the rados context to use
* @param striper where to store the rados striper
* @returns 0 on success, negative error code on failure
*/
int rados_striper_create(rados_ioctx_t ioctx,
rados_striper_t *striper);
/**
* Destroys a rados striper
*
* @param striper the striper to destroy
*/
void rados_striper_destroy(rados_striper_t striper);
/**
* Sets the object layout's stripe unit of a rados striper for future objects.
* This layout will be used when new objects are created (by writing to them)
* Already existing objects will be opened with their own layout.
*
* @param striper the targeted striper
* @param stripe_unit the stripe_unit value of the new object layout
* @returns 0 on success, negative error code on failure
*/
int rados_striper_set_object_layout_stripe_unit(rados_striper_t striper,
unsigned int stripe_unit);
/**
* Sets the object layout's stripe count of a rados striper for future objects.
* This layout will be used when new objects are created (by writing to them)
* Already existing objects will be opened with their own layout.
*
* @param striper the targeted striper
* @param stripe_count the stripe_count value of the new object layout
* @returns 0 on success, negative error code on failure
*/
int rados_striper_set_object_layout_stripe_count(rados_striper_t striper,
unsigned int stripe_count);
/**
* Sets the object layout's object_size of a rados striper for future objects.
* This layout will be used when new objects are created (by writing to them)
* Already existing objects will be opened with their own layout.
*
* @param striper the targeted striper
* @param object_size the object_size value of the new object layout
* @returns 0 on success, negative error code on failure
*/
int rados_striper_set_object_layout_object_size(rados_striper_t striper,
unsigned int object_size);
/** @} init */
/**
* @defgroup libradosstriper_h_synch_io Synchronous I/O
* Writes are striped to several rados objects which are then
* replicated to a number of OSDs based on the configuration
* of the pool they are in. These write functions block
* until data is in memory on all replicas of the object they're
* writing to - they are equivalent to doing the corresponding
* asynchronous write, and the calling
* rados_striper_ioctx_wait_for_complete().
*
* @{
*/
/**
* Synchronously write data to a striped object at the specified offset
*
* @param striper the striper in which the write will occur
* @param soid the name of the striped object
* @param buf data to write
* @param len length of the data, in bytes
* @param off byte offset in the object to begin writing at
* @returns 0 on success, negative error code on failure
* failure
*/
int rados_striper_write(rados_striper_t striper,
const char *soid,
const char *buf,
size_t len,
uint64_t off);
/**
* Synchronously write an entire striped object
*
* The striped object is filled with the provided data. If the striped object exists,
* it is truncated and then written.
*
* @param striper the striper in which the write will occur
* @param soid the name of the striped object
* @param buf data to write
* @param len length of the data, in bytes
* @returns 0 on success, negative error code on failure
*/
int rados_striper_write_full(rados_striper_t striper,
const char *soid,
const char *buf,
size_t len);
/**
* Append data to an object
*
* @param striper the striper in which the write will occur
* @param soid the name of the striped object
* @param buf the data to append
* @param len length of buf (in bytes)
* @returns 0 on success, negative error code on failure
* failure
*/
int rados_striper_append(rados_striper_t striper,
const char *soid,
const char *buf,
size_t len);
/**
* Synchronously read data from a striped object at the specified offset
*
* @param striper the striper in which the read will occur
* @param soid the name of the striped object
* @param buf where to store the results
* @param len the number of bytes to read
* @param off the offset to start reading from in the object
* @returns number of bytes read on success, negative error code on
* failure
*/
int rados_striper_read(rados_striper_t striper,
const char *soid,
char *buf,
size_t len,
uint64_t off);
/**
* Synchronously removes a striped object
*
* @note There is no atomicity of the deletion and the striped
* object may be left incomplete if an error is returned (metadata
* all present, but some stripes missing)
* However, there is a atomicity of the metadata deletion and
* the deletion can not happen if any I/O is ongoing (it
* will return EBUSY). Identically, no I/O will be able to start
* during deletion (same EBUSY return code)
* @param striper the striper in which the remove will occur
* @param soid the name of the striped object
* @returns 0 on success, negative error code on failure
*/
int rados_striper_remove(rados_striper_t striper,
const char* soid);
/**
* Resize an object
*
* If this enlarges the object, the new area is logically filled with
* zeroes. If this shrinks the object, the excess data is removed.
*
* @note the truncation is not fully atomic. The metadata part is,
* so the behavior will be atomic from user point of view when
* the object size is reduced. However, in case of failure, old data
* may stay around, hidden. They may reappear if the object size is
* later grown, instead of the expected 0s. When growing the
* object and in case of failure, the new 0 data may not be
* fully created. This can lead to ENOENT errors when
* writing/reading the missing parts.
* @note the truncation can not happen if any I/O is ongoing (it
* will return EBUSY). Identically, no I/O will be able to start
* during truncation (same EBUSY return code)
* @param io the rados context to use
* @param soid the name of the striped object
* @param size the new size of the object in bytes
* @returns 0 on success, negative error code on failure
*/
int rados_striper_trunc(rados_striper_t striper, const char *soid, uint64_t size);
/** @} Synchronous I/O */
/**
* @defgroup libradosstriper_h_xattrs Xattrs
* Extended attributes are stored as extended attributes on the
* first rados regular object of the striped object.
* Thus, they have the same limitations as the underlying
* rados extended attributes.
*
* @{
*/
/**
* Get the value of an extended attribute on a striped object.
*
* @param striper the striper in which the getxattr will occur
* @param oid name of the striped object
* @param name which extended attribute to read
* @param buf where to store the result
* @param len size of buf in bytes
* @returns length of xattr value on success, negative error code on failure
*/
int rados_striper_getxattr(rados_striper_t striper,
const char *oid,
const char *name,
char *buf,
size_t len);
/**
* Set an extended attribute on a striped object.
*
* @param striper the striper in which the setxattr will occur
* @param oid name of the object
* @param name which extended attribute to set
* @param buf what to store in the xattr
* @param len the number of bytes in buf
* @returns 0 on success, negative error code on failure
*/
int rados_striper_setxattr(rados_striper_t striper,
const char *oid,
const char *name,
const char *buf,
size_t len);
/**
* Delete an extended attribute from a striped object.
*
* @param striper the striper in which the rmxattr will occur
* @param oid name of the object
* @param name which xattr to delete
* @returns 0 on success, negative error code on failure
*/
int rados_striper_rmxattr(rados_striper_t striper,
const char *oid,
const char *name);
/**
* Start iterating over xattrs on a striped object.
*
* @post iter is a valid iterator
*
* @param striper the striper in which the getxattrs will occur
* @param oid name of the object
* @param iter where to store the iterator
* @returns 0 on success, negative error code on failure
*/
int rados_striper_getxattrs(rados_striper_t striper,
const char *oid,
rados_xattrs_iter_t *iter);
/**
* Get the next xattr on the striped object
*
* @pre iter is a valid iterator
*
* @post name is the NULL-terminated name of the next xattr, and val
* contains the value of the xattr, which is of length len. If the end
* of the list has been reached, name and val are NULL, and len is 0.
*
* @param iter iterator to advance
* @param name where to store the name of the next xattr
* @param val where to store the value of the next xattr
* @param len the number of bytes in val
* @returns 0 on success, negative error code on failure
*/
int rados_striper_getxattrs_next(rados_xattrs_iter_t iter,
const char **name,
const char **val,
size_t *len);
/**
* Close the xattr iterator.
*
* iter should not be used after this is called.
*
* @param iter the iterator to close
*/
void rados_striper_getxattrs_end(rados_xattrs_iter_t iter);
/** @} Xattrs */
/**
* Synchronously get object stats (size/mtime)
*
* @param striper the striper in which the stat will occur
* @param soid the id of the striped object
* @param psize where to store object size
* @param pmtime where to store modification time
* @returns 0 on success, negative error code on failure
*/
int rados_striper_stat(rados_striper_t striper,
const char* soid,
uint64_t *psize,
time_t *pmtime);
/**
* @defgroup libradosstriper_h_asynch_io Asynchronous I/O
* Read and write to objects without blocking.
*
* @{
*/
/**
* @typedef rados_striper_multi_completion_t
* Represents the state of a set of asynchronous operations
* it contains the aggregated return value once the operations complete
* and can be used to block until all operations are complete and/or safe.
*/
typedef void *rados_striper_multi_completion_t;
/**
* Constructs a multi completion to use with asynchronous operations
*
* The complete and safe callbacks correspond to operations being
* acked and committed, respectively. The callbacks are called in
* order of receipt, so the safe callback may be triggered before the
* complete callback, and vice versa. This is affected by journalling
* on the OSDs.
*
* @note Read operations only get a complete callback.
* @note BUG: this should check for ENOMEM instead of throwing an exception
*
* @param cb_arg application-defined data passed to the callback functions
* @param cb_complete the function to be called when the operation is
* in memory on all relpicas
* @param cb_safe the function to be called when the operation is on
* stable storage on all replicas
* @param pc where to store the completion
* @returns 0
*/
int rados_striper_multi_aio_create_completion(void *cb_arg,
rados_callback_t cb_complete,
rados_callback_t cb_safe,
rados_striper_multi_completion_t *pc);
/**
* Block until all operation complete
*
* This means data is in memory on all replicas.
*
* @param c operations to wait for
* @returns 0
*/
void rados_striper_multi_aio_wait_for_complete(rados_striper_multi_completion_t c);
/**
* Block until all operation are safe
*
* This means data is on stable storage on all replicas.
*
* @param c operations to wait for
* @returns 0
*/
void rados_striper_multi_aio_wait_for_safe(rados_striper_multi_completion_t c);
/**
* Has a multi asynchronous operation completed?
*
* @warning This does not imply that the complete callback has
* finished
*
* @param c async operations to inspect
* @returns whether c is complete
*/
int rados_striper_multi_aio_is_complete(rados_striper_multi_completion_t c);
/**
* Is a multi asynchronous operation safe?
*
* @warning This does not imply that the safe callback has
* finished
*
* @param c async operations to inspect
* @returns whether c is safe
*/
int rados_striper_multi_aio_is_safe(rados_striper_multi_completion_t c);
/**
* Block until all operations complete and callback completes
*
* This means data is in memory on all replicas and can be read.
*
* @param c operations to wait for
* @returns 0
*/
void rados_striper_multi_aio_wait_for_complete_and_cb(rados_striper_multi_completion_t c);
/**
* Block until all operations are safe and callback has completed
*
* This means data is on stable storage on all replicas.
*
* @param c operations to wait for
* @returns 0
*/
void rados_striper_multi_aio_wait_for_safe_and_cb(rados_striper_multi_completion_t c);
/**
* Has a multi asynchronous operation and callback completed
*
* @param c async operations to inspect
* @returns whether c is complete
*/
int rados_striper_multi_aio_is_complete_and_cb(rados_striper_multi_completion_t c);
/**
* Is a multi asynchronous operation safe and has the callback completed
*
* @param c async operations to inspect
* @returns whether c is safe
*/
int rados_striper_multi_aio_is_safe_and_cb(rados_striper_multi_completion_t c);
/**
* Get the return value of a multi asychronous operation
*
* The return value is set when all operations are complete or safe,
* whichever comes first.
*
* @pre The operation is safe or complete
*
* @note BUG: complete callback may never be called when the safe
* message is received before the complete message
*
* @param c async operations to inspect
* @returns aggregated return value of the operations
*/
int rados_striper_multi_aio_get_return_value(rados_striper_multi_completion_t c);
/**
* Release a multi asynchrnous IO completion
*
* Call this when you no longer need the completion. It may not be
* freed immediately if the operation is not acked and committed.
*
* @param c multi completion to release
*/
void rados_striper_multi_aio_release(rados_striper_multi_completion_t c);
/**
* Asynchronously write data to a striped object at the specified offset
*
* The return value of the completion will be 0 on success, negative
* error code on failure.
*
* @param striper the striper in which the write will occur
* @param soid the name of the striped object
* @param completion what to do when the write is safe and complete
* @param buf data to write
* @param len length of the data, in bytes
* @param off byte offset in the object to begin writing at
* @returns 0 on success, negative error code on
* failure
*/
int rados_striper_aio_write(rados_striper_t striper,
const char *soid,
rados_completion_t completion,
const char *buf,
size_t len,
uint64_t off);
/**
* Asynchronously appends data to a striped object
*
* The return value of the completion will be 0 on success, negative
* error code on failure.
*
* @param striper the striper in which the write will occur
* @param soid the name of the striped object
* @param completion what to do when the write is safe and complete
* @param buf data to write
* @param len length of the data, in bytes
* @returns 0 on success, negative error code on
* failure
*/
int rados_striper_aio_append(rados_striper_t striper,
const char *soid,
rados_completion_t completion,
const char *buf,
size_t len);
/**
* Asynchronously fills and object with the provided data.
* If the object exists, it is truncated and then written.
*
* The return value of the completion will be 0 on success, negative
* error code on failure.
*
* @param striper the striper in which the write will occur
* @param soid the name of the striped object
* @param completion what to do when the write is safe and complete
* @param buf data to write
* @param len length of the data, in bytes
* @returns 0 on success, negative error code on
* failure
*/
int rados_striper_aio_write_full(rados_striper_t striper,
const char *soid,
rados_completion_t completion,
const char *buf,
size_t len);
/**
* Asynchronously read data from a striped object at the specified offset
*
* The return value of the completion will be number of bytes read on
* success, negative error code on failure.
*
* @param striper the striper in which the read will occur
* @param soid the name of the striped object
* @param completion what to do when the read is safe and complete
* @param buf where to store the results
* @param len the number of bytes to read
* @param off the offset to start reading from in the object
* @returns 0 on success, negative error code on
* failure
*/
int rados_striper_aio_read(rados_striper_t striper,
const char *soid,
rados_completion_t completion,
char *buf,
const size_t len,
uint64_t off);
/**
* Asynchronously removes a striped object
*
* @note There is no atomicity of the deletion and the striped
* object may be left incomplete if an error is returned (metadata
* all present, but some stripes missing)
* However, there is a atomicity of the metadata deletion and
* the deletion can not happen if any I/O is ongoing (it
* will return EBUSY). Identically, no I/O will be able to start
* during deletion (same EBUSY return code)
* @param striper the striper in which the remove will occur
* @param soid the name of the striped object
* @param completion what to do when the remove is safe and complete
* @returns 0 on success, negative error code on failure
*/
int rados_striper_aio_remove(rados_striper_t striper,
const char* soid,
rados_completion_t completion);
/**
* Block until all pending writes in a striper are safe
*
* This is not equivalent to calling rados_striper_multi_aio_wait_for_safe() on all
* write completions, since this waits for the associated callbacks to
* complete as well.
*
* @param striper the striper in which the flush will occur
* @returns 0 on success, negative error code on failure
*/
void rados_striper_aio_flush(rados_striper_t striper);
/**
* Asynchronously get object stats (size/mtime)
*
* @param striper the striper in which the stat will occur
* @param soid the id of the striped object
* @param psize where to store object size
* @param pmtime where to store modification time
* @param completion what to do when the stats is complete
* @returns 0 on success, negative error code on failure
*/
int rados_striper_aio_stat(rados_striper_t striper,
const char* soid,
rados_completion_t completion,
uint64_t *psize,
time_t *pmtime);
/** @} Asynchronous I/O */
#ifdef __cplusplus
}
#endif
#endif
| 34.261866 | 141 | 0.686921 | [
"object"
] |
7eb52d98e9214dc81763dd8b0c45e194053c3a6c | 5,086 | h | C | nsrc/environment.h | mrkmarron/logpp | 40f459182d3eab2c6480754e4b0e44004c334265 | [
"MIT"
] | 60 | 2018-05-30T19:54:03.000Z | 2022-02-25T06:41:46.000Z | nsrc/environment.h | mrkmarron/logpp | 40f459182d3eab2c6480754e4b0e44004c334265 | [
"MIT"
] | 7 | 2018-05-30T18:29:42.000Z | 2019-09-07T16:54:14.000Z | nsrc/environment.h | mrkmarron/logpp | 40f459182d3eab2c6480754e4b0e44004c334265 | [
"MIT"
] | null | null | null | #pragma once
//forward decls
class MsgFormat;
class LogProcessingBlock;
class FormatWorker;
class LoggingEnvironment
{
private:
//Keep track of which logging level is enabled
LoggingLevel m_enabledLoggingLevel;
std::map<LoggingLevel, std::string> m_loggingLevelToNames;
//Keep track of which category names
std::map<int64_t, std::string> m_categoryNames;
std::string m_hostName;
std::string m_appName;
int64_t m_msgTimeLimit;
size_t m_msgCountLimit;
std::vector<std::shared_ptr<MsgFormat>> m_formats;
std::vector<std::shared_ptr<LogProcessingBlock>> m_processing;
char m_processingMode = 'n';
FormatWorker* m_formatWorker;
public:
LoggingEnvironment(const LoggingLevel level, const std::string& hostName, const std::string& appName) :
m_enabledLoggingLevel(level), m_loggingLevelToNames(), m_categoryNames(),
m_hostName(hostName), m_appName(appName),
m_msgTimeLimit(DEFAULT_LOG_TIMELIMIT), m_msgCountLimit(DEFAULT_LOG_SLOTSUSED),
m_formats(),
m_processing(), m_processingMode('n'),
m_formatWorker(nullptr)
{
this->m_categoryNames[1] = "$default"; //$default is defined by default
this->m_categoryNames[2] = "$explicit"; //$explicit is defined by default
this->m_loggingLevelToNames[LoggingLevel::LLOFF] = std::string("OFF");
this->m_loggingLevelToNames[LoggingLevel::LLFATAL] = std::string("FATAL");
this->m_loggingLevelToNames[LoggingLevel::LLERROR] = std::string("ERROR");
this->m_loggingLevelToNames[LoggingLevel::LLWARN] = std::string("WARN");
this->m_loggingLevelToNames[LoggingLevel::LLINFO] = std::string("INFO");
this->m_loggingLevelToNames[LoggingLevel::LLDETAIL] = std::string("DETAIL");
this->m_loggingLevelToNames[LoggingLevel::LLDEBUG] = std::string("DEBUG");
this->m_loggingLevelToNames[LoggingLevel::LLTRACE] = std::string("TRACE");
this->m_loggingLevelToNames[LoggingLevel::LLOFF] = std::string("OFF");
}
void InitializeEnvironmentData(const LoggingLevel level, const std::string& hostName, const std::string& appName)
{
this->m_enabledLoggingLevel = level;
this->m_hostName = hostName;
this->m_appName = appName;
}
void AddFormat(int64_t fmtId, std::shared_ptr<MsgFormat> fmt)
{
if (fmtId == static_cast<int64_t>(this->m_formats.size()))
{
this->m_formats.push_back(fmt);
}
else
{
//a previous format add failed so replace the index with the new one
this->m_formats[fmtId] = fmt;
}
}
std::shared_ptr<MsgFormat> GetFormat(int64_t idx) const
{
return this->m_formats[idx];
}
const std::string& GetHostName() const { return this->m_hostName; }
const std::string& GetAppName() const { return this->m_appName; }
void SetMsgTimeLimit(int64_t limit) { this->m_msgTimeLimit = limit; }
int64_t GetMsgTimeLimit() const { return this->m_msgTimeLimit; }
void SetMsgSlotsLimit(size_t limit) { this->m_msgCountLimit = limit; }
size_t GetMsgSlotsLimit() const { return this->m_msgCountLimit; }
void AddCategory(int64_t categoryId, const std::string& name) { this->m_categoryNames[categoryId] = name; }
const std::string& GetCategoryName(int64_t categoryId) const { return this->m_categoryNames.at(categoryId); }
void SetEnabledLoggingLevel(LoggingLevel level) { this->m_enabledLoggingLevel = level; }
LoggingLevel GetEnabledLoggingLevel() const { return this->m_enabledLoggingLevel; }
const std::string& GetLogLevelName(LoggingLevel level) const { return this->m_loggingLevelToNames.at(level); }
void AddProcessingBlock(std::shared_ptr<LogProcessingBlock> block) { this->m_processing.push_back(block); }
std::shared_ptr<LogProcessingBlock> GetActiveProcessingBlock() { return this->m_processing.back(); }
void SetProcessingMode(char c) { this->m_processingMode = c; }
char GetProcessingMode() const { return this->m_processingMode; }
void DiscardProcesingBlock(std::shared_ptr<LogProcessingBlock> pb)
{
//should always be the last block
this->m_processing.pop_back();
}
void AddBlockFromFormatterAbort(std::shared_ptr<LogProcessingBlock> pb)
{
this->m_processing.insert(this->m_processing.begin(), pb);
}
std::shared_ptr<LogProcessingBlock> GetNextFormatBlock()
{
if (this->m_processing.empty())
{
return nullptr;
}
else
{
std::shared_ptr<LogProcessingBlock> pb = this->m_processing.front();
this->m_processing.erase(this->m_processing.begin());
return pb;
}
}
void SetAsyncFormatWorker(FormatWorker* formatWorker) { this->m_formatWorker = formatWorker; }
FormatWorker* GetAsyncFormatWorker() { return this->m_formatWorker; }
void ClearAsyncFormatWorker() { this->m_formatWorker = nullptr; }
bool HasWorkPending() const
{
return !this->m_processing.empty();
}
};
| 37.397059 | 117 | 0.687377 | [
"vector"
] |
7ebe6886aecdc13c8945b27020d055839d812fd7 | 3,706 | h | C | src/include/CosmoInterface/measurements/measurementsIO/std/measurementssaverstd.h | cosmolattice/cosmolattice | bd9a31a026c0b47d53ff486db23448797dbe2fe0 | [
"MIT"
] | 12 | 2021-02-01T16:04:54.000Z | 2022-03-18T08:27:46.000Z | src/include/CosmoInterface/measurements/measurementsIO/std/measurementssaverstd.h | cosmolattice/cosmolattice | bd9a31a026c0b47d53ff486db23448797dbe2fe0 | [
"MIT"
] | 1 | 2021-04-24T10:09:35.000Z | 2021-04-24T10:09:35.000Z | src/include/CosmoInterface/measurements/measurementsIO/std/measurementssaverstd.h | cosmolattice/cosmolattice | bd9a31a026c0b47d53ff486db23448797dbe2fe0 | [
"MIT"
] | 2 | 2021-08-11T07:35:25.000Z | 2022-03-07T21:33:30.000Z | #ifndef COSMOINTERFACE_MEASUREMENTS_STD_MEASUREMENTSSAVERSTD_H
#define COSMOINTERFACE_MEASUREMENTS_STD_MEASUREMENTSSAVERSTD_H
/* This file is part of CosmoLattice, available at www.cosmolattice.net .
Copyright Daniel G. Figueroa, Adrien Florio, Francisco Torrenti and Wessel Valkenburg.
Released under the MIT license, see LICENSE.md. */
// File info: Main contributor(s): Daniel G. Figueroa, Adrien Florio, Francisco Torrenti, Year: 2019
#include "TempLat/util/tdd/tdd.h"
#include "TempLat/util/conditionaloutput/outputstream.h"
#include <sstream>
#include <iomanip>
#include "TempLat/lattice/field/field.h"
#include "CosmoInterface/measurements/measurementsIO/filesmanager.h"
namespace TempLat {
/** \brief A class which is used to save measurements using the standard library.
*
*
* Unit test: make test-measurementssaverstd
**/
template<typename T>
class MeasurementsSaverStd {
public:
/* Put public methods here. These should change very little over time. */
MeasurementsSaverStd(FilesManager& fm, std::string fn, bool amIRoot, bool appendMode, const std::vector<std::string>& headers = {}) :
mMode(!appendMode ? std::ios_base::out : std::ios_base::app ),
outputAv(std::make_shared<OutputStream<T>>(fm.getWorkingDir() + fm.getTag() +"average_" + fn + ".txt", amIRoot, mMode)),
stream(std::make_shared<std::stringstream>()),
headerStream(std::make_shared<std::stringstream>()),
headerSaved(false)
{
if(!appendMode && fm.getPrintHeaders()) for(auto& str : headers) addHeader(str);
else headerSaved = true;
}
MeasurementsSaverStd(FilesManager& fm, const Field<T>& fld,bool amIRoot, bool appendMode, const std::vector<std::string>& headers = {}) :
mMode(!appendMode ? std::ios_base::out : std::ios_base::app ),
stream(std::make_shared<std::stringstream>()),
headerStream(std::make_shared<std::stringstream>()),
headerSaved(false)
{
std::string name = fld.toString();
name = name.erase(name.find("(",3));
name = fm.getWorkingDir() +"average_" + name;
outputAv = std::make_shared<OutputStream<T>>(name + ".txt", amIRoot, mMode);
if(!appendMode && fm.getPrintHeaders()) for(auto& str : headers) addHeader(str);
else headerSaved = true;
}
virtual ~MeasurementsSaverStd(){}
void addAverage(const T& r)
{
(*stream) << std::setprecision(15) << " " << r;
}
void addHeader(const std::string& str)
{
(*headerStream) << " " << str;
}
void save()
{
if(!headerSaved){
(*outputAv) << "#" << StringTrimmer::ltrimmed(headerStream->str()) << "\n";
headerSaved = true;
}
(*outputAv) << StringTrimmer::ltrimmed(stream->str()) << "\n";
stream->str("");
outputAv->flush();
}
private:
/* Put all member variables and private methods here. These may change arbitrarily. */
std::ios_base::openmode mMode;
std::shared_ptr<OutputStream<T>> outputAv;
std::shared_ptr<std::stringstream> stream;
std::shared_ptr<std::stringstream> headerStream;
bool headerSaved;
};
struct MeasurementsSaverStdTester{
#ifdef TEMPLATTEST
static inline void Test(TDDAssertion& tdd);
#endif
};
} /* TempLat */
#ifdef TEMPLATTEST
#include "CosmoInterface/measurements/measurementsIO/std/measurementssaverstd_test.h"
#endif
#endif
| 33.690909 | 145 | 0.618457 | [
"vector"
] |
7edbdeb1e6e70c973bd216748aaa683438aab435 | 52,569 | c | C | src/libhades.c | michael-hartmann/libhades | 81a2ab18dbf59975f8fbae0693a757b054b4501c | [
"Unlicense"
] | 4 | 2015-11-03T15:07:53.000Z | 2019-08-28T20:09:32.000Z | src/libhades.c | michael-hartmann/libhades | 81a2ab18dbf59975f8fbae0693a757b054b4501c | [
"Unlicense"
] | null | null | null | src/libhades.c | michael-hartmann/libhades | 81a2ab18dbf59975f8fbae0693a757b054b4501c | [
"Unlicense"
] | null | null | null | /**
* @file libhades.c
* @author Michael Hartmann <michael.hartmann@physik.uni-augsburg.de>
* @date February, 2016
* @brief library to access low-level LAPACK functions
*/
#include <cblas.h>
#include <errno.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <strings.h>
#include <libhades.h>
#include <libhades/parse_npy_dict.h>
/** \defgroup misc miscellaneous functions
* @{
*/
/** @brief malloc wrapper
*
* This function uses malloc to allocate size bytes of memory and returns a
* pointer to the memory. If an error occures, an error message is printed to
* stderr and the program is aborted.
*
* @param [in] size amount of memory to allocate
* @retval ptr pointer to the allocated memory
*/
void *libhades_malloc(size_t size)
{
void *ptr = malloc(size);
if(ptr == NULL)
{
const int err = errno;
fprintf(stderr, "malloc can't allocate %zu bytes of memory: %s (%d)\n", size, strerror(err), err);
abort();
}
return ptr;
}
/** @brief free wrapper
*
* This function frees the memory allocated by \ref libhades_malloc or \ref
* libhades_realloc (or malloc and realloc). If the pointer given is NULL, an error is
* printed to stderr and the program is aborted.
*
* @param [in] ptr pointer to the memory that should be freed
*/
void libhades_free(void *ptr)
{
if(ptr == NULL)
{
fprintf(stderr, "Trying to free NULL pointer\n");
abort();
}
free(ptr);
}
/** @brief realloc wrapper
*
* This function changes the size of the memory block pointed to by ptr to size
* bytes. If ptr is NULL, this function behaves like \ref libhades_malloc. If
* an error occures, an error is printed to stderr and the program is aboprted.
*
* @param [in] ptr pointer to the memory block
* @param [in] size size of the memory block
* @retval ptr_new pointer to the new memory block
*/
void *libhades_realloc(void *ptr, size_t size)
{
void *ptr_new = realloc(ptr, size);
if(ptr_new == NULL)
{
int err = errno;
fprintf(stderr, "realloc can't allocate %zu bytes of memory: %s (%d)\n", size, strerror(err), err);
abort();
}
return ptr_new;
}
static void *(*malloc_cb)(size_t) = &libhades_malloc;
static void *(*realloc_cb)(void *, size_t) = &libhades_realloc;
static void (*free_cb)(void *) = &libhades_free;
/** macro to create functions argmin, argmax, argabsmin, argabsmax */
#define ARGXXX(FUNCTION_NAME, FUNCTION, RELATION) \
size_t FUNCTION_NAME(double list[], size_t size) \
{ \
size_t index = 0; \
for(size_t i = 0; i < size; i++) \
if(FUNCTION(list[i]) RELATION FUNCTION(list[index])) \
index = i; \
return index; \
}
/** @brief Return index of smallest element in list
*
* @param [in] list
* @param [in] size elements in list
*
* @retval index
*/
ARGXXX(argmin, +, <)
/** @brief Return index of largest element in list
*
* @param [in] list
* @param [in] size elements in list
*
* @retval index
*/
ARGXXX(argmax, +, >)
/** @brief Return index of element with smallest absolute value in list
*
* @param [in] list
* @param [in] size elements in list
*
* @retval index
*/
ARGXXX(argabsmin, fabs, <)
/** @brief Return index of element with largest absolute value in list
*
* @param [in] list
* @param [in] size elements in list
*
* @retval index
*/
ARGXXX(argabsmax, fabs, >)
/** @}*/
/** \defgroup create Creating, printing and freeing matrices
* @{
*/
static inline void _swap_int(int *a, int *b);
static inline void _swap_size_t(size_t *a, size_t *b);
static inline void _swap_int(int *a, int *b)
{
int c = *a;
*a = *b;
*b = c;
}
static inline void _swap_size_t(size_t *a, size_t *b)
{
size_t c = *a;
*a = *b;
*b = c;
}
#define MATRIX_SWAP(FUNCTION_NAME, MATRIX_TYPE, TYPE) \
void FUNCTION_NAME(MATRIX_TYPE *A, MATRIX_TYPE *B) \
{ \
/* swap pointers */ \
TYPE *ptr = A->M; \
A->M = B->M; \
B->M = ptr; \
\
/* swap rows */ \
_swap_int(&A->rows, &B->rows); \
\
/* swap columns */ \
_swap_int(&A->columns, &B->columns); \
\
/* swap min */ \
_swap_int(&A->min, &B->min); \
\
/* swap size */ \
_swap_size_t(&A->size, &B->size); \
\
/* swap type */ \
_swap_int(&A->type, &B->type); \
\
/* swap min */ \
_swap_int(&A->min, &B->min); \
}
/** @brief Swap matrices A and B
*
* This function swaps the matrices A and B. The former content of A will be
* the content of B and vice versa. No data is copied or moved, but the
* pointers are swapped.
*
* @param [in,out] A matrix A
* @param [in,out] B matrix B
*/
MATRIX_SWAP(matrix_swap, matrix_t, double);
/** @brief Swap matrices A and B
*
* See \ref matrix_swap.
*
* @param [in,out] A matrix A
* @param [in,out] B matrix B
*/
MATRIX_SWAP(matrix_complex_swap, matrix_complex_t, complex_t);
/** macro to create a diagnal matrix out of a vector */
#define MATRIX_DIAG(FUNCTION_NAME, MATRIX_TYPE, ZEROS) \
MATRIX_TYPE *FUNCTION_NAME(MATRIX_TYPE *v) \
{ \
int dim = v->size; \
MATRIX_TYPE *A = ZEROS(dim, dim, NULL); \
if(A == NULL) \
return NULL; \
\
for(int i = 0; i < dim; i++) \
matrix_set(A, i,i, v->M[i]); \
\
return A; \
}
/** @brief Construct a real diagonal matrix from a row or columns vector
*
* @param [in] v row or column vector
*
* @retval A A = diag(v) if successfull, NULL otherwise
*/
MATRIX_DIAG(matrix_diag, matrix_t, matrix_zeros)
/** @brief Construct a complex diagonal matrix from a row or columns vector
*
* @param [in] v row or column vector
*
* @retval A A = diag(v) if successfull, NULL otherwise
*/
MATRIX_DIAG(matrix_complex_diag, matrix_complex_t, matrix_complex_zeros)
/** @brief Set functions to allocate and free memory
*
* By default wrappers to malloc and free from <stdlib.h> are used to allocate
* and free memory. If allocation of memory fails or a NULL pointer is freed,
* the program will terminate.
*
* @param [in] _malloc_cb callback to a malloc-alike function
* @param [in] _free_cb callback to a free-alike function
*/
void matrix_set_alloc(void *(*_malloc_cb)(size_t), void (*_free_cb)(void *))
{
malloc_cb = _malloc_cb;
free_cb = _free_cb;
}
/** macro for copying matrices. */
#define MATRIX_COPY(FUNCTION_NAME, MTYPE, TYPE, ALLOC) \
MTYPE *FUNCTION_NAME(MTYPE *A, MTYPE *C) \
{ \
if(C == NULL) { \
C = ALLOC(A->rows, A->columns); \
if(C == NULL) \
return NULL; \
} \
\
C->rows = A->rows; \
C->columns = A->columns; \
C->min = A->min; \
C->size = A->size; \
C->type = A->type; \
C->view = 0; \
memcpy(C->M, A->M, C->size*sizeof(TYPE)); \
return C; \
}
/** @brief Copy real matrix A
*
* Copy matrix A into C. If C is NULL, space for the matrix C will be
* allocated.
*
* @param [in] A real matrix
* @param [in,out] C real matrix
*
* @retval C copy of A
*/
MATRIX_COPY(matrix_copy, matrix_t, double, matrix_alloc)
/** @brief Copy complex matrix A
*
* Copy matrix A into C. If C is NULL, space for the matrix C will be
* allocated.
*
* @param [in] A complex matrix
* @param [in,out] C complex matrix
*
* @retval C copy of A
*/
MATRIX_COPY(matrix_complex_copy, matrix_complex_t, complex_t, matrix_complex_alloc)
/** @brief Copy a real matrix A to a complex matrix C
*
* Copy the matrix A to a complex matrix C. The matrix elements of A and C will
* be identical. If C is NULL, memory for the matrix will be allocated.
*
* @param [in] A real matrix
*
* @retval C copy of A if successfull, NULL otherwise
*/
matrix_complex_t *matrix_tocomplex(matrix_t *A, matrix_complex_t *C)
{
if(C == NULL)
{
C = matrix_complex_alloc(A->rows, A->columns);
if(C == NULL)
return NULL;
}
for(size_t i = 0; i < C->size; i++)
C->M[i] = A->M[i];
return C;
}
/** @brief Print real matrix M to stream
*
* Print the matrix A to the stream given by stream, e.g. stdout or stderr.
* The format is given by the format string format, the separator of two
* columns is sep, the separator between lines is given by sep_line. Both sep
* and sep_line may be NULL.
*
* @param [in] stream output stream
* @param [in] A real matrix
* @param [in] format output format, e.g. "%lf" or "%g"
* @param [in] sep separator between columns, e.g. "\t"
* @param [in] sep_line separator between lines, e.g. "\n"
*/
void matrix_fprintf(FILE *stream, matrix_t *A, const char *format, const char *sep, const char *sep_line)
{
const int rows = A->rows, columns = A->columns;
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
{
fprintf(stream, format, matrix_get(A, i,j));
if(sep != NULL)
fputs(sep, stream);
}
if(sep_line != NULL)
fputs(sep_line, stream);
}
}
/** @brief Print complex matrix A to stream
*
* See matrix_fprintf.
*
* @param [in] stream output stream
* @param [in] A complex matrix
* @param [in] format output format, e.g. "%+lf%+lfi"
* @param [in] sep separator between columns, e.g. "\t"
* @param [in] sep_line separator between lines, e.g. "\n"
*/
void matrix_complex_fprintf(FILE *stream, matrix_complex_t *A, const char *format, const char *sep, const char *sep_line)
{
const int rows = A->rows, columns = A->columns;
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
{
const complex_t c = matrix_get(A, i,j);
fprintf(stream, format, CREAL(c), CIMAG(c));
if(sep != NULL)
fputs(sep, stream);
}
if(sep_line != NULL)
fputs(sep_line, stream);
}
}
/** macro for matrix allocations. */
#define MATRIX_ALLOC(FUNCTION_NAME, MTYPE, TYPE) \
MTYPE *FUNCTION_NAME(int rows, int columns) \
{ \
if(rows <= 0 || columns <= 0) \
return NULL; \
\
MTYPE *A = malloc_cb(sizeof(MTYPE)); \
if(A == NULL) \
return NULL; \
\
const size_t size = (size_t)rows*(size_t)columns; \
\
A->rows = rows; \
A->columns = columns; \
A->min = MIN(rows, columns); \
A->size = size; \
A->type = 0; \
A->view = 0; \
A->M = malloc_cb(size*sizeof(TYPE)); \
if(A->M == NULL) \
{ \
free_cb(A); \
return NULL; \
} \
\
return A; \
}
/** @brief Allocate memory for real matrix of m rows and n columns
*
* This function will allocate and return a matrix of m lines and n columns.
* The function given by matrix_set_alloc will be used to allocate memory; by
* default this is malloc from <stdlib.h>.
*
* The matrix elements will be undefined. To allocate a matrix initialized with
* zeros, see matrix_zeros. To create a unity matrix, see matrix_eye.
*
* @param [in] rows rows of matrix M (rows > 0)
* @param [in] columns columns of matrix M (columns > 0)
*
* @retval A real matrix if successful, NULL otherwise
*/
MATRIX_ALLOC(matrix_alloc, matrix_t, double)
/** @brief Allocate memory for complex matrix of m rows and n columns
*
* See matrix_alloc.
*
* @param [in] rows rows of matrix M (rows > 0)
* @param [in] columns columns of matrix M (columns > 0)
*
* @retval A complex matrix if successful, otherwise NULL
*/
MATRIX_ALLOC(matrix_complex_alloc, matrix_complex_t, complex_t)
/** macro to create zero matrix */
#define MATRIX_ZEROS(FUNCTION_NAME, MTYPE, TYPE, ALLOC, SETALL) \
MTYPE *FUNCTION_NAME(int rows, int columns, MTYPE *A) \
{ \
if(A == NULL) \
{ \
A = ALLOC(rows,columns); \
if(A == NULL) \
return NULL; \
} \
\
SETALL(A, 0); \
\
return A; \
}
/** @brief Generate a real zero matrix of m lines and n columns
*
* Set every element of matrix A to 0. If A is NULL, the matrix will be
* created. In this case, you have to free the matrix yourself.
*
* @param [in] rows rows of matrix M
* @param [in] columns columns of matrix M
* @param [in,out] A: matrix
*
* @retval A real matrix 0 if successful, otherwise NULL
*/
MATRIX_ZEROS(matrix_zeros, matrix_t, double, matrix_alloc, matrix_setall)
/** @brief Generate a complex zero matrix of m lines and n columns
*
* See matrix_zeros.
*
* @param [in] rows rows of matrix M
* @param [in] columns columns of matrix M
* @param [in,out] A: matrix
*
* @retval A complex matrix 0 if successful, otherwise NULL
*/
MATRIX_ZEROS(matrix_complex_zeros, matrix_complex_t, complex_t, matrix_complex_alloc, matrix_complex_setall)
/** macro to create matrix x*Id */
#define MATRIX_SETALL(FUNCTION_NAME, MATRIX_TYPE, TYPE) \
void FUNCTION_NAME(MATRIX_TYPE *A, TYPE x) \
{ \
const size_t size = A->size; \
TYPE *M = A->M; \
for(size_t i = 0; i < size; i++) \
*M++ = x; \
}
/** @brief Set matrix elements of A to x
*
* @param [in,out] A real matrix
* @param [in] x real number
*/
MATRIX_SETALL(matrix_setall, matrix_t, double)
/** @brief Set matrix elements of A to x
*
* @param [in,out] A complex matrix
* @param [in] x complex number
*/
MATRIX_SETALL(matrix_complex_setall, matrix_complex_t, complex_t)
/** macro to create unity matrix */
#define MATRIX_EYE(FUNCTION_NAME, MTYPE, TYPE, ALLOC, SETALL) \
MTYPE *FUNCTION_NAME(int dim, MTYPE *A) \
{ \
if(A == NULL) \
{ \
A = ALLOC(dim,dim); \
if(A == NULL) \
return NULL; \
} \
\
const int min = A->min; \
TYPE *M = A->M; \
SETALL(A,0); \
for(int i = 0; i < min; i++) \
*(M+i*(min+1)) = 1; \
\
return A; \
}
/** @brief Create real identity matrix
*
* If A == NULL, a identity matrix of dimension dim times dim is created and
* returned.
* If A != NULL, the matrix A is set to the identity matrix and the parameter
* dim is ignored. More specific, for a general (e.g. not square) matrix A, the
* matrix elements are set to A_ij = Delta_ij.
*
* @param [in] dim dimension of identity matrix (ignored for A == NULL)
* @param [in,out] A real matrix
*
* @retval A identity matrix if successful, NULL otherwise
*/
MATRIX_EYE(matrix_eye, matrix_t, double, matrix_alloc, matrix_setall)
/** @brief Create complex identity matrix
*
* See matrix_eye.
*
* @param [in] dim dimension of identity matrix (ignored for A == NULL)
* @param [in,out] A complex matrix
*
* @retval A identity matrix if successful, NULL otherwise
*/
MATRIX_EYE(matrix_complex_eye, matrix_complex_t, complex_t, matrix_complex_alloc, matrix_complex_setall)
/** macro to free matrices */
#define MATRIX_FREE(FUNCTION_NAME, MTYPE) \
void FUNCTION_NAME(MTYPE *A) \
{ \
if(A != NULL) \
{ \
if(!A->view && A->M != NULL) \
{ \
free_cb(A->M); \
A->M = NULL; \
} \
free_cb(A); \
} \
}
/** @brief Free real matrix
*
* This function will free the memory allocated for matrix M. If M is NULL this
* function will do nothing.
*
* @param [in,out] A matrix to free
*/
MATRIX_FREE(matrix_free, matrix_t)
/** @brief Free complex matrix
*
* See matrix_free.
*
* @param [in,out] A matrix to free
*/
MATRIX_FREE(matrix_complex_free, matrix_complex_t)
/** @}*/
/** \defgroup trdet trace and determinant
* @{
*/
/** macro to calculate trace of matrix */
#define MATRIX_TRACE(FUNCTION_NAME, MATRIX_TYPE, TYPE) \
TYPE FUNCTION_NAME(MATRIX_TYPE *A) \
{ \
const int min = A->min; \
const TYPE *M = A->M; \
TYPE trace = 0; \
for(int i = 0; i < min; i++) \
trace += *(M+i*(1+min)); \
\
return trace; \
}
/** @brief Calculate Tr(A) of real matrix A
*
* @param [in] A complex matrix
*
* @retval x with x=Tr(A)
*/
MATRIX_TRACE(matrix_trace, matrix_t, double)
/** @brief Calculate Tr(A) of complex matrix A
*
* @param [in] A complex matrix
*
* @retval z with z=Tr(A)
*/
MATRIX_TRACE(matrix_complex_trace, matrix_complex_t, complex_t)
/** @brief Calculate Tr(A*B)
*
* This will calculate the trace of A*B: Tr(A*B). Matrix A and B must be square
* matrices of dimension dim, dim.
*
* A and B must not point to the same matrix or the behaviour will be
* undefined!
*
* @param [in] A real matrix
* @param [in] B real matrix
*
* @retval x with x=Tr(A*B)
*/
double matrix_trace_AB(matrix_t *A, matrix_t *B)
{
const int dim = A->min;
double sum = 0;
double *M1 = A->M;
double *M2 = B->M;
for(int i = 0; i < dim; i++)
sum += cblas_ddot(dim, M1+i, dim, M2+i*dim, 1);
return sum;
}
/** @brief Calculate Tr(A*B) for A,B complex
*
* See matrix_trace_AB.
*
* @param [in] A complex matrix
* @param [in] B complex matrix
*
* @retval z with z=Tr(A*B)
*/
complex_t matrix_trace_complex_AB(matrix_complex_t *A, matrix_complex_t *B)
{
const int dim = A->min;
complex_t sum = 0;
for(int i = 0; i < dim; i++)
for(int k = 0; k < dim; k++)
sum += matrix_get(A, i,k)*matrix_get(B, k,i);
return sum;
}
/** @brief Calculate Re(Tr(A*B)) for A,B complex
*
* See matrix_trace_AB.
*
* @param [in] A complex matrix
* @param [in] B complex matrix
*
* @retval x with x=Re(Tr(A*B))
*/
double matrix_trace_complex_AB_real(matrix_complex_t *A, matrix_complex_t *B)
{
const int dim = A->rows;
double sum = 0;
const complex_t *M1 = A->M;
const complex_t *M2 = B->M;
for(int i = 0; i < dim; i++)
for(int k = 0; k < dim; k++)
sum += CREAL(M1[i*dim+k]*M2[k*dim+i]);
return sum;
}
/** @}*/
/** \defgroup kron Kronecker product
* @{
*/
/** macro to create Kronecker product */
#define MATRIX_KRON(FUNCTION_NAME, MTYPE, TYPE, ALLOC, SETALL) \
MTYPE *FUNCTION_NAME(MTYPE *A, MTYPE *B, MTYPE *C) \
{ \
const int Am = A->rows, An = A->columns; \
const int Bm = B->rows, Bn = B->columns; \
if(C == NULL) \
{ \
C = ALLOC(Am*Bm, An*Bn); \
if(C == NULL) \
return NULL; \
} \
SETALL(C, 0); \
\
for(int m = 0; m < Am; m++) \
for(int n = 0; n < An; n++) \
{ \
const TYPE c = matrix_get(A,m,n); \
if(c != 0) \
{ \
for(int im = 0; im < Bm; im++) \
for(int in = 0; in < Bn; in++) \
matrix_set(C, m*Bm+im, n*Bn+in, c*matrix_get(B,im,in)); \
} \
} \
\
return C; \
}
/** @brief Calculate Kronecker product of real matrices A and B
*
* Matrix A has dimension Am,An, matrix B has dimension Bm,Bn.
*
* If C is not NULL, the Kronecker product will be stored in C. C must have
* dimension Am+Bm,An+Bn. If C is NULL, memory for the matrix will be allocated
* and the matrix will be returned. You have to free the memory for the
* returned matrix yourself.
*
* @param [in] A real matrix
* @param [in] B real matrix
* @param [in,out] C Kronecker product
*
* @retval C Kronecker product of A and B, NULL if no memory could be allocated
*/
MATRIX_KRON(matrix_kron, matrix_t, double, matrix_alloc, matrix_setall)
/** @brief Calculate Kronecker product of complex matrices A and B
*
* See matrix_kron.
*
* @param [in] A complex matrix
* @param [in] B complex matrix
* @param [in,out] C Kronecker product
*
* @retval C Kronecker product of A and B
*/
MATRIX_KRON(matrix_complex_kron, matrix_complex_t, complex_t, matrix_complex_alloc, matrix_complex_setall)
/** @}*/
/** \defgroup addsubmult Add, subtract and multiply matrices
* @{
*/
/** macro to multiply matrix with scalar factor */
#define MATRIX_MULT_SCALAR(FUNCTION_NAME, MTYPE, TYPE) \
void FUNCTION_NAME(MTYPE *A, TYPE alpha) \
{ \
const size_t size = A->size; \
TYPE *M = A->M; \
for(size_t i = 0; i < size; i++) \
M[i] *= alpha; \
}
/** @brief Multiply real matrix with a real scalar
*
* alpha*A -> A
*
* @param [in,out] A real matrix
* @param [in] alpha real scalar
* @retval A, A=alpha*A
*/
MATRIX_MULT_SCALAR(matrix_mult_scalar, matrix_t, double)
/** @brief Multiply complex matrix with a complex scalar
*
* alpha*A -> A
*
* @param [in,out] A complex matrix
* @param [in] alpha complex scalar
* @retval A, A=alpha*A
*/
MATRIX_MULT_SCALAR(matrix_complex_mult_scalar, matrix_complex_t, complex_t)
/** @brief Multiply real matrix with a complex scalar
*
* alpha*A -> C
*
* If C is NULL, memory for the matrix C will be allocated. If C is not NULL, C
* must have the correct dimension.
*
* @param [in] A real matrix
* @param [in] alpha complex scalar
* @param [in,out] C complex matrix
*
* @retval C, C = alpha*A
*/
matrix_complex_t *matrix_mult_complex_scalar(matrix_t *A, complex_t alpha, matrix_complex_t *C)
{
const int rows = A->rows;
const int columns = A->columns;
const double *AM = A->M;
complex_t *CM;
if(C == NULL)
{
C = matrix_complex_alloc(rows, columns);
if(C == NULL)
return NULL;
}
CM = C->M;
for(size_t i = 0; i < C->size; i++)
CM[i] = alpha*AM[i];
return C;
}
/* compute alpha*A*B */
#define MATRIX_MULT(FUNCTION_NAME, MATRIX_TYPE, TYPE, ALLOC, BLAS_xGEMM, PTR) \
MATRIX_TYPE *FUNCTION_NAME(MATRIX_TYPE *A, MATRIX_TYPE *B, TYPE alpha, MATRIX_TYPE *C) \
{ \
TYPE beta = 0; \
\
if(A->columns != B->rows) \
return NULL; \
\
if(C == NULL) \
{ \
C = ALLOC(A->rows, B->columns); \
if(C == NULL) \
return NULL; \
} \
\
/* xGEMM ( TRANSA, TRANSB, M, N, K, ALPHA, A, LDA, B, LDB, BETA, C, LDC) */ \
BLAS_xGEMM(CblasColMajor, /* column order */ \
CblasNoTrans, /* don't transpose/conjugate A */ \
CblasNoTrans, /* don't transpose/conjugate B */ \
A->rows, /* M: rows of A and C */ \
B->columns, /* N: columns of B and C */ \
A->columns, /* K: columns of A and rows of B */ \
PTR alpha, /* alpha: scalar */ \
A->M, /* A: matrix A */ \
A->rows, /* LDA: leading dimension of A (columns) */ \
B->M, /* B: matrix B */ \
A->columns, /* LDB: leading dimension of B (columns) */ \
PTR beta, /* beta: scalar */ \
C->M, /* C: matrix C */ \
C->rows /* LDC: leading dimension of C (columns) */ \
); \
\
return C; \
}
/** @brief Multiply real matrices
*
* alpha*A*B -> C
*
* If C is NULL, memory for the matrix C will be allocated.
*
* @param [in] A real matrix
* @param [in] B real matrix
* @param [in] alpha real scalar
* @param [in,out] C real matrix
*
* @retval C, C = alpha*A*B
*/
MATRIX_MULT(matrix_mult, matrix_t, double, matrix_alloc, cblas_dgemm, +)
/** @brief Multiply complex matrices
*
* alpha*A*B -> C
*
* If C is NULL, memory for the matrix C will be allocated.
*
* @param [in] A complex matrix
* @param [in] B complex matrix
* @param [in] alpha complex scalar
* @param [in,out] C complex matrix
*
* @retval C, C = alpha*A*B
*/
MATRIX_MULT(matrix_complex_mult, matrix_complex_t, complex_t, matrix_complex_alloc, cblas_zgemm, &)
/** macro to add two matrices */
#define MATRIX_ADD(FUNCTION_NAME, TYPE1, MTYPE1, TYPE2, MTYPE2) \
int FUNCTION_NAME(MTYPE1 *A, MTYPE2 *B, TYPE1 alpha, MTYPE1 *C) \
{ \
const size_t size = A->size; \
TYPE1 *M3; \
TYPE1 *M1 = A->M; \
TYPE2 *M2 = B->M; \
\
if(C == NULL) \
M3 = A->M; \
else \
M3 = C->M; \
\
if(A->rows != B->rows || A->columns != B->columns) \
return LIBHADES_ERROR_SHAPE; \
\
for(size_t i = 0; i < size; i++) \
M3[i] = M1[i] + (alpha*M2[i]); \
\
return 0; \
}
/** @brief Add real matrices A and B
*
* Calculate A+alpha*B -> C.
*
* The result will be stored in C. If C is NULL, the result is stored in A.
*
* @param [in,out] A real matrix
* @param [in] B real matrix
* @param [in] alpha real scalar
* @param [in,out] C real matrix or NULL
*
* @retval 0 if successfull
* @retval LIBHADES_ERROR_SHAPE if matrices have wrong shape
*/
MATRIX_ADD(matrix_add, double, matrix_t, double, matrix_t)
/** @brief Add complex matrices A and B
*
* Calculate A+alpha*B -> C.
*
* The result will be stored in C. If C is NULL, the result is stored in A.
*
* @param [in,out] A complex matrix
* @param [in] B complex matrix
* @param [in] alpha complex number
* @param [in,out] C complex matrix or NULL
*
* @retval 0 if successfull
* @retval LIBHADES_ERROR_SHAPE if matrices have wrong shape
*/
MATRIX_ADD(matrix_complex_add, complex_t, matrix_complex_t, complex_t, matrix_complex_t)
/** @brief Add complex matrix A and real matrix B
*
* Calculate A+alpha*B -> C.
*
* The result will be stored in C. If C is NULL, the result is stored in A.
*
* @param [in,out] A complex matrix
* @param [in] B real matrix
* @param [in] alpha complex scalar
* @param [in,out] C complex matrix or NULL
*
* @retval 0 if successfull
* @retval LIBHADES_ERROR_SHAPE if matrices have wrong shape
*/
MATRIX_ADD(matrix_complex_add_real, complex_t, matrix_complex_t, double, matrix_t)
/** @}*/
/** \defgroup transconj Transpose, conjugate
* @{
*/
#define MATRIX_TRANSPOSE(FUNCTION_NAME, MTYPE, TYPE) \
void FUNCTION_NAME(MTYPE *A) \
{ \
const int rows = A->rows; \
const int columns = A->columns; \
for(int im = 0; im < rows; im++) \
for(int in = im+1; in < columns; in++) \
{ \
TYPE temp = matrix_get(A, im, in); \
matrix_set(A, im, in, matrix_get(A, in, im)); \
matrix_set(A, in, im, temp); \
} \
\
A->rows = columns; \
A->columns = rows; \
}
/** @brief Transpose real matrix A
*
* The matrix will be transposed.
*
* @param [in,out] A real matrix
*
* @retval C with C=A^T
*/
MATRIX_TRANSPOSE(matrix_transpose, matrix_t, double)
/** @brief Transpose complex matrix A
*
* The matrix will be transposed.
*
* @param [in,out] A complex matrix
*
* @retval C with C=A^T
*/
MATRIX_TRANSPOSE(matrix_complex_transpose, matrix_complex_t, complex_t)
/** @}*/
/** \defgroup ev Eigenvalue problems
* @{
*/
/** @brief Compute eigenvalues and optionally eigenvectors of symmetric matrix A
*
* This function computes all eigenvalues and, optionally, eigenvectors of a
* real symmetric matrix A.
*
* See dsyev.
*
* @param [in] A real matrix
* @param [in] JOBZ 'N': only eigenvalues, 'V' eigenvalues and eigenvectors
* @param [in] UPLO 'U': upper triangle part of A is stored; 'L': lower triangle part of A is stored
* @param [in] w real matrix of dimension (dim,1) (i.e. a vector); the eigenvalues will be stored in w
*
* @retval 0 on success
*/
int eig_sym(matrix_t *A, char *JOBZ, char *UPLO, matrix_t *w)
{
int info, lwork = -1, N = A->min;
double workopt;
double *work;
dsyev_(JOBZ, UPLO, &N, A->M, &N, w->M, &workopt, &lwork, &info);
if(info != 0)
return info;
lwork = workopt;
work = malloc_cb(lwork*sizeof(double));
if(work == NULL)
return LIBHADES_ERROR_OOM;
dsyev_(JOBZ, UPLO, &N, A->M, &N, w->M, work, &lwork, &info);
free_cb(work);
return info;
}
/** @brief Compute eigenvalues and optionally eigenvectors of Hermitian matrix A
*
* This function computes all eigenvalues and, optionally, eigenvectors of a
* Hermitian symmetric matrix A.
*
* See zheev.
*
* @param [in] A complex matrix
* @param [in] JOBZ 'N': only eigenvalues, 'V' eigenvalues and eigenvectors
* @param [in] UPLO 'U': upper triangle part of A is stored; 'L': lower triangle part of A is stored
* @param [in] w real matrix of dimension (dim,1) (i.e. a vector); the eigenvalues will be stored in w
*
* @retval 0 on success
*/
int eig_herm(matrix_complex_t *A, char *JOBZ, char *UPLO, matrix_t *w)
{
int info, lwork = -1, N = A->min;
complex_t workopt;
complex_t *work = NULL;
double *rwork;
rwork = malloc_cb(MAX(1, 3*N-2)*sizeof(double));
if(rwork == NULL)
return LIBHADES_ERROR_OOM;
zheev_(JOBZ, UPLO, &N, A->M, &N, w->M, &workopt, &lwork, rwork, &info);
if(info != 0)
{
free_cb(rwork);
return info;
}
lwork = CREAL(workopt);
work = malloc_cb(lwork*sizeof(complex_t));
if(work == NULL)
{
free_cb(rwork);
return LIBHADES_ERROR_OOM;
}
zheev_(JOBZ, UPLO, &N, A->M, &N, w->M, work, &lwork, rwork, &info);
free_cb(rwork);
free_cb(work);
return info;
}
/** @brief Compute eigenvalues and optionally eigenvectors of matrix A
*
* Compute for an N-by-N complex nonsymmetric matrix A, the eigen- values and,
* optionally, right eigenvectors
*
* See zgeev.
*
* @param [in] A real matrix
* @param [in] w list containing the eigenvalues of A
* @param [in] vr if vr != NULL, right eigenvectors are computed and will be stored in vr; vr must be a complex matrix of dimension (dim,dim)
* @param [in] vl if vl != NULL, lefft eigenvectors are computed and will be stored in vl; vl must be a complex matrix of dimension (dim,dim)
*
* @retval 0 on success
*/
/* Parameters */
int eig_complex_generic(matrix_complex_t *A, matrix_complex_t *w, matrix_complex_t *vl, matrix_complex_t *vr)
{
int N = A->min;
int lwork = -1;
char jobvr = 'N';
char jobvl = 'N';
int info;
complex_t *evr = NULL;
complex_t *evl = NULL;
complex_t *work = NULL;
double *rwork = NULL;
complex_t wopt;
/* if vr is not NULL, calculate right eigenvectors */
if(vr != NULL)
{
jobvr = 'V';
evr = vr->M;
}
/* if vl is not NULL, calculate left eigenvectors */
if(vl != NULL)
{
jobvl = 'V';
evl = vl->M;
}
/* get the optimal size for workspace work */
zgeev_(&jobvl, &jobvr, &N, A->M, &N, w->M, evl, &N, evr, &N, &wopt, &lwork, rwork, &info);
if(info != 0)
return info;
lwork = CREAL(wopt);
rwork = malloc_cb(2*N*sizeof(double));
work = malloc_cb(lwork*sizeof(complex_t));
if(rwork == NULL || work == NULL)
{
if(rwork != NULL)
free(rwork);
if(work != NULL)
free(work);
return LIBHADES_ERROR_OOM;
}
/* SUBROUTINE ZGEEV( JOBVL, JOBVR, N, A, LDA, W, VL, LDVL, VR, LDVR, WORK, LWORK, RWORK, INFO ) */
zgeev_(
&jobvl, /* left eigenvectors of A are not computed */
&jobvr, /* calculate/don't calculate right eigenvectors */
&N, /* order of matrix A */
A->M, /* matrix A */
&N, /* LDA - leading dimension of A */
w->M, /* eigenvalues */
evl, /* left eigenvectors */
&N, /* leading dimension of array vl */
evr, /* eigenvectors */
&N, /* leading dimension of the array VR */
work, /* COMPLEX*16 array, dimension (LWORK) */
&lwork, /* dimension of the array WORK; LWORK >= max(1,2*N) */
rwork, /* (workspace) DOUBLE PRECISION array, dimension (2*N) */
&info /* 0 == success */
);
free_cb(work);
free_cb(rwork);
return info;
}
int eig_complex_vr(matrix_complex_t *M, complex_t lambda, matrix_complex_t *vr)
{
matrix_complex_t *A = NULL, *b = NULL;
const int rows = M->rows;
const int columns = M->columns;
/* lapack */
char trans = 'N';
int info, lwork;
complex_t work_size, *work = NULL;
int m = rows+1, n = columns, nrhs = 1;
int lda = m, ldb = MAX(m,n);
if((A = matrix_complex_alloc(rows+1, columns)) == NULL)
return LIBHADES_ERROR_OOM;
if((b = matrix_complex_zeros(rows+1,1,NULL)) == NULL)
{
matrix_complex_free(A);
return LIBHADES_ERROR_OOM;
}
matrix_set(b, rows,0, 1);
for(int j = 0; j < columns; j++)
{
for(int i = 0; i < rows; i++)
matrix_set(A, i, j, matrix_get(M, i,j));
/* - lambda Id */
matrix_set(A, j,j, matrix_get(A,j,j)-lambda);
/* set nomalization condition */
matrix_set(A, rows,j, 1);
}
/* determine work size */
lwork = -1;
zgels_(&trans, &m, &n, &nrhs, A->M, &lda, b->M, &ldb, &work_size, &lwork, &info);
lwork = (int)CREAL(work_size);
if((work = malloc_cb(lwork*sizeof(complex_t))) == NULL)
{
matrix_complex_free(A);
matrix_complex_free(vr);
return LIBHADES_ERROR_OOM;
}
/* calculate eigenvector */
zgels_(
&trans, /* find least squares solution of overdetermined system */
&m, /* number of rows of matrix A */
&n, /* number of columns of matrix A */
&nrhs, /* number of columns of matrix B */
A->M, /* matrix A (will be overwritten) */
&lda, /* leading dimension of A, LDA >= max(1,M) */
b->M, /* on entry: right hand side vectors, on exit: solution */
&ldb, /* leading dimension of B, LDB >= MAX(1,M,N) */
work, /* workspace */
&lwork, /* dimension of work */
&info /* status */
);
free_cb(work);
matrix_complex_free(A);
for(int i = 0; i < rows; i++)
matrix_set(vr, i,0, matrix_get(b, i,0));
matrix_complex_free(b);
return info;
}
/** @}*/
/** \defgroup exp Calculate matrix exponential
* @{
*/
/** macro to calculate matrix norm */
#define MATRIX_NORM(FUNCTION_NAME, MTYPE, LAPACK_FUNC) \
int FUNCTION_NAME(MTYPE *A, char norm_type, double *norm) \
{ \
double *work = NULL; \
\
if(norm_type == 'I') \
{ \
work = malloc_cb(A->rows*sizeof(double)); \
if(work == NULL) \
return LIBHADES_ERROR_OOM; \
} \
\
*norm = LAPACK_FUNC(&norm_type, &A->rows, &A->columns, A->M, &A->rows, work); \
\
if(work != NULL) \
free_cb(work); \
\
return 0; \
}
/** @brief Compute matrix norm for real matrix
*
* See dlange.
*
* Returns
* max(abs(A(i,j))), norm_type = 'M' or 'm'
* norm1(A), norm_type = '1', 'O' or 'o'
* normI(A), norm_type = 'I' or 'i'
* normF(A), norm_type = 'F', 'f', 'E' or 'e'
*
* @param [in] A real matrix
* @param [in] norm_type type of norm, e.g. 'F' for Frobenius norm
* @param [out] norm value of norm
*
* @retval ret 0 if successfull, <0 otherwise
*/
MATRIX_NORM(matrix_norm, matrix_t, dlange_);
/** @brief Compute matrix norm for complex matrix
*
* See matrix_norm.
*
* @param [in] A complex matrix
* @param [in] norm_type type of norm, e.g. 'F' for Frobenius norm
* @param [out] norm value of norm
*
* @retval ret 0 if successfull, <0 otherwise
*/
MATRIX_NORM(matrix_complex_norm, matrix_complex_t, zlange_);
matrix_complex_t *matrix_complex_exp_taylor(matrix_complex_t *A, int order)
{
const int rows = A->min;
matrix_complex_t *C = matrix_complex_alloc(rows,rows);
/* B = E+A/order */
matrix_complex_t *B = matrix_complex_copy(A,NULL);
matrix_complex_mult_scalar(B, 1./order);
for(int i = 0; i < rows; i++)
matrix_set(B, i,i, 1+matrix_get(B,i,i));
for(int k = order-1; k > 0; k--)
{
matrix_complex_mult(A, B, 1./order, C);
/* swap */
{
matrix_complex_t *temp;
temp = C;
C = B;
B = temp;
}
for(int i = 0; i < rows; i++)
matrix_set(B, i,i, 1+matrix_get(B,i,i));
}
matrix_complex_free(C);
return B;
}
/** @}*/
/** \defgroup LA LU decomposition, inverting
* @{
*/
#define LU_DECOMPOSITION(FUNCTION_NAME, MATRIX_TYPE, XGETRF) \
int FUNCTION_NAME(MATRIX_TYPE *A, int ipiv[]) \
{ \
int info; \
\
XGETRF( \
&A->rows, /* M number of rows of A */ \
&A->columns, /* N number of columns of A */ \
A->M, /* matrix A to be factored */ \
&A->columns, /* LDA: leading dimension of A */ \
ipiv, /* pivot indices of dimension (min(M,N)) */ \
&info \
); \
\
return info; \
}
/** @brief Compute LU decomposition of real matrix A
*
* See dgetrf.
*
* The factorization has the form
* A = P * L * U
* where P is a permutation matrix, L is lower triangular with unit
* diagonal elements (lower trapezoidal if rows > columns), and U is upper
* triangular (upper trapezoidal if m < n).
*
* @param [in,out] A real matrix
* @param [out] ipiv pivot indices; array of dimension MIN(rows,columns)
*
* @retval INFO
*/
LU_DECOMPOSITION(matrix_lu_decomposition, matrix_t, dgetrf_)
/** @brief Compute LU decomposition of complex matrix A
*
* See matrix_lu_decomposition.
*
* @param [in,out] A complex matrix
* @param [out] ipiv pivot indices; array of dimension MIN(rows,columns)
*
* @retval INFO
*/
LU_DECOMPOSITION(matrix_complex_lu_decomposition, matrix_complex_t, zgetrf_)
#define MATRIX_INVERT(FUNCTION_NAME, TYPE, MATRIX_TYPE, LU_DECOMPOSITION, XGETRI) \
int FUNCTION_NAME(MATRIX_TYPE *A) \
{ \
int info, lwork, dim = A->min; \
int *ipiv = NULL; \
TYPE *work = NULL; \
TYPE workopt; \
\
ipiv = malloc_cb(dim*sizeof(int)); \
if(ipiv == NULL) \
return LIBHADES_ERROR_OOM; \
\
info = LU_DECOMPOSITION(A, ipiv); \
if(info != 0) \
goto out; \
\
lwork = -1; \
XGETRI(&dim, A->M, &dim, ipiv, &workopt, &lwork, &info); \
if(info != 0) \
goto out; \
\
lwork = (int)workopt; \
work = malloc_cb(lwork*sizeof(TYPE)); \
if(work == NULL) \
{ \
info = LIBHADES_ERROR_OOM; \
goto out; \
} \
\
XGETRI( \
&dim, /* order of matrix A */ \
A->M, /* factors L and U from LU decomposition */ \
&dim, /* LDA: leading dimension of A */ \
ipiv, /* pivot indices */ \
work, /* workspace of dimension LWORK */ \
&lwork, /* length of work */ \
&info \
); \
\
out: \
free_cb(ipiv); \
if(work != NULL) \
free_cb(work); \
\
return info; \
}
/** @brief Invert real matrix A
*
* The inverse of A is computed using the LU factorzation of A
*
* @param [in] A real matrix
*
* @retval INFO
*/
MATRIX_INVERT(matrix_invert, double, matrix_t, matrix_lu_decomposition, dgetri_)
/** @brief Invert complex matrix A
*
* See matrix_invert.
*
* @param [in] A complex matrix
*
* @retval INFO
*/
MATRIX_INVERT(matrix_complex_invert, complex_t, matrix_complex_t, matrix_complex_lu_decomposition, zgetri_)
#define MATRIX_SOLVE(FUNCTION_NAME, MATRIX_TYPE, LU_DECOMPOSITION, XGETRS) \
int FUNCTION_NAME(MATRIX_TYPE *A, MATRIX_TYPE *b) \
{ \
int N = A->min; \
char trans = 'N'; \
int nrhs = b->columns; \
int info = -1; \
int *ipiv = malloc_cb(N*sizeof(int)); \
\
if(ipiv == NULL) \
return LIBHADES_ERROR_OOM; \
\
LU_DECOMPOSITION(A, ipiv); \
XGETRS(&trans, &N, &nrhs, A->M, &N, ipiv, b->M, &N, &info); \
\
free_cb(ipiv); \
\
return info; \
}
/** @brief Solve system of linear equations
*
* Solve the system of linear equations:
* A*x = b
*
* @param [in,out] A matrix
* @param [in,out] b vector/matrix
*
* @retval INFO
*/
/** @}*/
MATRIX_SOLVE(matrix_solve, matrix_t, matrix_lu_decomposition, dgetrs_);
/** @brief Solve system of linear equations
*
* Solve the system of complex linear equations:
* A*x = b
*
* @param [in,out] A complex matrix
* @param [in,out] b complex vector/matrix
*
* @retval INFO
*/
/** @}*/
MATRIX_SOLVE(matrix_complex_solve, matrix_complex_t, matrix_complex_lu_decomposition, zgetrs_);
/*
static void _cblas_zaxpy(const int N, const double alpha, const void *X, const int incX, void *Y, const int incY)
{
complex_t beta = alpha;
cblas_zaxpy(N, &beta, X, incX, Y, incY);
}
*/
/** @brief Calculate dot product of vectors x and y
*
* Calculate dot product of first column of x,y. If x and y have different
* rows, the minimum is used.
*
* @param [in] x vector
* @param [in] y vector
* @retval x*y
*/
double vector_dot(matrix_t *x, matrix_t *y)
{
int incx = 1;
int incy = 1;
int N = MIN(x->rows, y->rows);
return ddot_(&N, x->M, &incx, y->M, &incy);
}
/** @brief Calculate dot product of vectors x and y
*
* Calculate dot product of first column of x,y. If x and y have different
* rows, the minimum is used.
*
* @param [in] x vector
* @param [in] y vector
* @retval x*y
*/
complex_t vector_complex_dot(matrix_complex_t *x, matrix_complex_t *y)
{
/*
int incx = 1;
int incy = 1;
int N = MIN(x->rows, y->rows);
complex_t z = 0;
zdotc_(&z, &N, x->M, &incx, y->M, &incy);
return z;
*/
int N = MIN(x->rows, y->rows);
complex_t z = 0;
for(int i = 0; i < N; i++)
z += matrix_get(x,i,0)*matrix_get(y,i,0);
return z;
}
#define MATRIX_GET_COLUMN(FUNCTION_NAME, TYPE, MATRIX_TYPE) \
MATRIX_TYPE *FUNCTION_NAME(MATRIX_TYPE *A, int i) \
{ \
const int rows = A->rows; \
MATRIX_TYPE *v = malloc_cb(sizeof(MATRIX_TYPE)); \
if(v == NULL) \
return NULL; \
\
v->rows = rows; \
v->columns = 1; \
v->min = 1; \
v->size = rows; \
v->type = 0; \
v->view = 1; \
v->M = &A->M[i*rows]; \
\
return v; \
}
/** @brief Get i-th column of matrix A
*
* @param [in] A matrix
* @param [in] i column number
* @retval x*y
*/
MATRIX_GET_COLUMN(matrix_get_column, double, matrix_t);
/** @brief Get i-th column of matrix A
*
* @param [in] A matrix
* @param [in] i column number
* @retval x*y
*/
MATRIX_GET_COLUMN(matrix_complex_get_column, complex_t, matrix_complex_t);
/** \defgroup sparse Functions for sparse matrices
* @{
*/
#ifdef SUPPORT_SPARSE
/** @brief Calculate eigenvalues of a sparse complex matrix
*
* @param [in] N number of columns/rows of matrix
* @param [in] nev number of eigenvalues to compute
* @param [in] which LM (largest magnitude), SM (smallest magnitude), LR (largest real part), SR (smallest real part), LI (largest imaginary part), SI (smallest imaginary part)
* @param [in] Av callback function that implements the matrix-vector operation Av; the input vector is given as in, the vector Av must be written in out
* @param [in,out] d on exit d contains the Rith approximations (must be of length nev+1)
* @param [in] mxiter maximum number of Arnoldi update iterations allowed
* @param [in] tol relative accuracy of the Ritz value
* @param [in] data pointer that is given to callback function Av
*
* @retval 0 if successful
*/
int sparse_complex_eig(int N, int nev, char *which, void (*Av)(int N, complex_t *in, complex_t *out, void *data), complex_t *d, int mxiter, double tol, void *data)
{
int ret = LIBHADES_ERROR_OOM;
int info = 0;
int ido = 0;
char *bmat = "I"; /* standard eigenproblem */
int ncv = MIN(2*nev+2, N);
int ishift = 1;
int mode = 1;
int iparam[11] = { ishift, 0, mxiter, 1, 0, 0, mode, 0, 0, 0, 0 };
int ipntr[14];
int lworkl = ncv*(3*ncv + 5);
int rvec = 0;
char *howmny = "P";
complex_t *workd = NULL, *workl = NULL, *resid = NULL, *v = NULL, *workev = NULL;
int *select = NULL;
double *rwork = NULL;
/* allocate memory */
ret = LIBHADES_ERROR_OOM;
workd = malloc_cb(3*N*sizeof(complex_t));
if(workd == NULL)
goto out;
workl = malloc_cb(lworkl*sizeof(complex_t));
if(workl == NULL)
goto out;
rwork = malloc_cb(ncv*sizeof(double));
if(rwork == NULL)
goto out;
resid = malloc_cb(N*sizeof(complex_t));
if(resid == NULL)
goto out;
v = malloc_cb(N*ncv*sizeof(complex_t));
if(v == NULL)
goto out;
select = malloc_cb(ncv*sizeof(int));
if(select == NULL)
goto out;
workev = malloc_cb((2*ncv)*sizeof(complex_t));
if(workev == NULL)
goto out;
/* loop */
while(1)
{
/* http://www.caam.rice.edu/software/ARPACK/UG/node138.html */
znaupd_(
&ido, bmat, &N, which, &nev, &tol, resid, &ncv, v, &N, iparam,
ipntr, workd, workl, &lworkl, rwork, &info, strlen(bmat),
strlen(which)
);
if(ido == 1 || ido == -1)
Av(N, &workd[ipntr[0]-1], &workd[ipntr[1]-1], data);
else if(ido == 99)
break;
else
{
ret = ido;
goto out;
}
}
if(info != 0)
{
ret = info;
goto out;
}
/* http://www.mathkeisan.com/usersguide/man/zneupd.html */
zneupd_(
&rvec, howmny, select, d, NULL, &N, NULL, workev, bmat, &N, which,
&nev, &tol, resid, &ncv, v, &N, iparam, ipntr, workd, workl, &lworkl,
rwork, &info, strlen(howmny), strlen(bmat), strlen(which)
);
ret = info;
out:
if(resid != NULL)
free_cb(resid);
if(v != NULL)
free_cb(v);
if(workd != NULL)
free_cb(workd);
if(workl != NULL)
free_cb(workl);
if(rwork != NULL)
free_cb(rwork);
if(select != NULL)
free_cb(select);
if(workev != NULL)
free_cb(workev);
return ret;
}
#endif
/** @}*/
/** \defgroup io Save/load matrices
* @{
*/
#define MATRIX_LOAD_FROM_STREAM(FUNCTION_NAME, MATRIX_TYPE, TYPE, ALLOC, TRANSPOSE, IS_COMPLEX) \
MATRIX_TYPE *FUNCTION_NAME(FILE *stream, int *ret) \
{ \
MATRIX_TYPE *M; \
uint16_t len; \
int rows, columns, fortran_order, is_complex; \
char header[10] = { 0 }; \
char dict[2048] = { 0 }; \
\
if(ret != NULL) \
*ret = 0; \
\
/* read magic string, major and minor number */ \
fread(header, 8, 1, stream); \
if(memcmp(header, "\x93NUMPY\x01\x00", 8) != 0) \
{ \
if(ret != NULL) \
*ret = LIBHADES_ERROR_HEADER; \
return NULL; \
} \
\
/* read length of dict */ \
fread(&len, sizeof(uint16_t), 1, stream); \
\
if(len >= sizeof(dict)/sizeof(dict[0])) \
{ \
if(ret != NULL) \
*ret = LIBHADES_ERROR_INV_LENGTH; \
return NULL; \
} \
\
fread(dict, sizeof(char), len, stream); \
\
if(npy_dict_get_fortran_order(dict, &fortran_order) != 0) \
{ \
if(ret != NULL) \
*ret = LIBHADES_ERROR_ORDER; \
return NULL; \
} \
\
if(npy_dict_get_shape(dict, &rows, &columns) != 0) \
{ \
if(ret != NULL) \
*ret = LIBHADES_ERROR_SHAPE; \
return NULL; \
} \
\
if(npy_dict_get_descr(dict, &is_complex) != 0) \
{ \
if(ret != NULL) \
*ret = LIBHADES_ERROR_DESCR; \
return NULL; \
} \
\
if(is_complex != IS_COMPLEX) \
{ \
if(ret != NULL) \
*ret = LIBHADES_ERROR_FORMAT; \
return NULL; \
} \
\
M = ALLOC(rows,columns); \
fread(M->M, sizeof(TYPE), rows*columns, stream); \
\
if(!fortran_order) \
TRANSPOSE(M); \
\
M->min = MIN(rows,columns); \
M->size = (size_t)rows*(size_t)columns; \
M->view = 0; \
M->type = 0; \
\
return M; \
}
/** @brief Load real matrix from stream
*
* Load real matrix A from a stream. This function will also allocate memory
* for the matrix.
*
* If error != NULL, error will be set to:
* 0 if successful
* LIBHADES_ERROR_HEADER if magic or major/minor number is invalid
* LIBHADES_ERROR_INV_LENGTH if length of dictionary is invalid (too long)
* LIBHADES_ERROR_ORDER if order is invalid (Fortran/C order)
* LIBHADES_ERROR_SHAPE if shape is invalid (rows/columns)
* LIBHADES_ERROR_DESCR if dtype is wrong/not supported
* LIBHADES_ERROR_FORMAT if wrong format (real instead of complex)
* 0 rows/columns wrong
*
* @param [in] stream file handle of a opened file
* @param [out] error error code
* @retval A matrix
* @retval NULL if an error occured
*/
MATRIX_LOAD_FROM_STREAM(matrix_load_from_stream, matrix_t, double, matrix_alloc, matrix_transpose, 0);
/** @brief Load complex matrix from stream
*
* Load complex matrix A from a stream. This function will also allocate memory
* for the matrix.
*
* If error != NULL, error will be set to:
* 0 if successful
* LIBHADES_ERROR_HEADER if magic or major/minor number is invalid
* LIBHADES_ERROR_INV_LENGTH if length of dictionary is invalid (too long)
* LIBHADES_ERROR_ORDER if order is invalid (Fortran/C order)
* LIBHADES_ERROR_SHAPE if shape is invalid (rows/columns)
* LIBHADES_ERROR_DESCR if dtype is wrong/not supported
* LIBHADES_ERROR_FORMAT if wrong format (complex instead of real)
* 0 rows/columns wrong
*
* @param [in] stream file handle of a opened file
* @param [out] error error code
* @retval A matrix
* @retval NULL if an error occured
*/
MATRIX_LOAD_FROM_STREAM(matrix_complex_load_from_stream, matrix_complex_t, complex_t, matrix_complex_alloc, matrix_complex_transpose, 1);
#define MATRIX_LOAD(FUNCTION_NAME, MATRIX_TYPE, LOAD_FUNCTION) \
MATRIX_TYPE *FUNCTION_NAME(const char *filename, int *ret) \
{ \
FILE *stream; \
MATRIX_TYPE *M; \
\
if((stream = fopen(filename, "r")) == NULL) \
{ \
if(ret != NULL) \
*ret = LIBHADES_ERROR_IO; \
return NULL; \
} \
\
M = LOAD_FUNCTION(stream, ret); \
\
fclose(stream); \
\
return M; \
}
/** @brief Load real matrix from file
*
* Load real matrix A from file given by filename. This function will also
* allocate memory for the matrix. See \ref matrix_load_from_stream for errors.
*
* @param [in] filename path to the file
* @param [out] error error code
* @retval A matrix
* @retval NULL if an error occured
*/
MATRIX_LOAD(matrix_load, matrix_t, matrix_load_from_stream);
/** @brief Load complex matrix from file
*
* Load complex matrix A from file given by filename. This function will also
* allocate memory for the matrix. See \ref matrix_complex_load_from_stream for
* errors.
*
* @param [in] filename path to the file
* @param [out] error error code
* @retval A matrix
* @retval NULL if an error occured
*/
MATRIX_LOAD(matrix_complex_load, matrix_complex_t, matrix_complex_load_from_stream);
#define MATRIX_SAVE_TO_STREAM(FUNCTION_NAME, TYPE, MATRIX_TYPE, DTYPE) \
void FUNCTION_NAME(MATRIX_TYPE *M, FILE *stream) \
{ \
char d_str[512] = { 0 }; \
uint16_t len = 0; \
const int rows = M->rows, columns = M->columns; \
\
/* write magic string, major number and minor number */ \
fwrite("\x93NUMPY\x01\x00", sizeof(char), 8, stream); \
\
/* write length of header and header */ \
snprintf(d_str, sizeof(d_str)/sizeof(d_str[0]), "{'descr': '%s', 'fortran_order': True, 'shape': (%d, %d), }", DTYPE, rows, columns); \
\
len = strlen(d_str); \
\
fwrite(&len, sizeof(len), 1, stream); \
fwrite(d_str, sizeof(char), len, stream); \
\
/* write matrix */ \
fwrite(M->M, sizeof(TYPE), M->size, stream); \
}
/** @brief Save real matrix A to stream
*
* Save real matrix A to a file handle given by stream. The datatype
* corresponds to Numpy's npy file format.
*
* @param [in] A matrix to be dumped to file
* @param [in] stream file handle of opened file
*/
MATRIX_SAVE_TO_STREAM(matrix_save_to_stream, double, matrix_t, "<f8");
/** @brief Save complex matrix A to stream
*
* Save complex matrix A to a file handle given by stream. The datatype
* corresponds to Numpy's npy file format.
*
* @param [in] A matrix to be dumped to file
* @param [in] stream file handle of opened file
*/
MATRIX_SAVE_TO_STREAM(matrix_complex_save_to_stream, complex_t, matrix_complex_t, "<c16");
#define MATRIX_SAVE(FUNCTION_NAME, MATRIX_TYPE, SAVE_FUNCTION) \
int FUNCTION_NAME(MATRIX_TYPE *M, const char *filename) \
{ \
FILE *stream = fopen(filename, "w"); \
if(stream == NULL) \
return LIBHADES_ERROR_IO; \
\
SAVE_FUNCTION(M, stream); \
\
fclose(stream); \
\
return 0; \
};
/** @brief Save real matrix A to file
*
* Save real matrix A to file given by filename. The datatype corresponds to
* Numpy's .npy file format.
*
* @param [in] A matrix to be dumped to file
* @param [in] filename path to the file
* @retval 0 if successful
* @retval LIBHADES_ERROR_IO if file could not be opened
*/
MATRIX_SAVE(matrix_save, matrix_t, matrix_save_to_stream);
/** @brief Save complex matrix A to file
*
* Save complex matrix A to file given by filename. The datatype corresponds to
* Numpy's .npy file format.
*
* @param [in] A matrix to be dumped to file
* @param [in] filename path to the file
* @retval 0 if successful
* @retval LIBHADES_ERROR_IO if file could not be opened
*/
MATRIX_SAVE(matrix_complex_save, matrix_complex_t, matrix_complex_save_to_stream);
/** @}*/
| 26.350376 | 176 | 0.605908 | [
"shape",
"vector"
] |
7edfe620a6f40548f5507f402cec7e994e6301b5 | 1,242 | h | C | Source/meshes/arena.h | lowlevel86/OpenGL-3D-Adventure-Game-Engine | 7f93b8d5ba17fedc638fcb7127e09a23ceb59a19 | [
"MIT"
] | 11 | 2018-08-22T02:31:33.000Z | 2021-11-18T21:40:26.000Z | Source/meshes/arena.h | lowlevel86/OpenGL-3D-Adventure-Game-Engine | 7f93b8d5ba17fedc638fcb7127e09a23ceb59a19 | [
"MIT"
] | null | null | null | Source/meshes/arena.h | lowlevel86/OpenGL-3D-Adventure-Game-Engine | 7f93b8d5ba17fedc638fcb7127e09a23ceb59a19 | [
"MIT"
] | 3 | 2018-08-28T08:30:49.000Z | 2022-01-07T14:48:13.000Z | extern float arena_TRANS[320];
extern float arena_POINT[13050];
extern short arena_QUAD[1536];
extern short arena_TRI[2814];
extern char arena_VCOLOR[17400];
extern float arena_TEXCOORD[8700];
extern int arena_TEXLINKDAT[20];
extern int arena_TEXCNT;
int arena_TEX[1];
extern int arena_POINTDATSZ[21];
extern int arena_QUADDATSZ[21];
extern int arena_TRIDATSZ[21];
extern int arena_VCOLORDATSZ[21];
extern int arena_TEXCOORDDATSZ[21];
extern int arena_HIDE[20];
//unchanging transformation data
float arena_STATICTRANS[320];
//unchanging point data
float arena_STATICPOINT[13050];
extern int arena_MESHCNT;
//mesh names
#define arena_cage 0
#define arena_camera 1
#define arena_cannonBall 2
#define arena_explode 3
#define arena_explodeRed 4
#define arena_explodeYellow 5
#define arena_ground 6
#define arena_sphere 7
#define arena_t1Barrel 8
#define arena_t1Body 9
#define arena_t1LeftTrack 10
#define arena_t1RightTrack 11
#define arena_t1Turret 12
#define arena_t2Barrel 13
#define arena_t2Body 14
#define arena_t2LeftTrack 15
#define arena_t2RightTrack 16
#define arena_t2Turret 17
#define arena_tank_CameraA 18
#define arena_tank_CameraB 19
//textures
#define arena_grass_bmp 0
| 23.884615 | 36 | 0.789855 | [
"mesh"
] |
7ee5d92ee191db846099dca749110f09175e0bea | 4,898 | h | C | EvilHangmanGame/string.h | hoangviet1993/C-codes | 0b59479860dc9450b56d42351f9229b4d426102f | [
"MIT"
] | null | null | null | EvilHangmanGame/string.h | hoangviet1993/C-codes | 0b59479860dc9450b56d42351f9229b4d426102f | [
"MIT"
] | null | null | null | EvilHangmanGame/string.h | hoangviet1993/C-codes | 0b59479860dc9450b56d42351f9229b4d426102f | [
"MIT"
] | null | null | null |
#ifndef string_h
#define string_h
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "status.h"
typedef struct string* String_Ptr;
//Precondition: None
//Postcndition: returns a handle to a valid string object
String_Ptr string_init_default();
//Precondition: c_str is a c string to use to initialize the string object
//Postcondition: a handle to the string object
String_Ptr string_init_c_string(char* c_str);
//Precondition: phString is a pointer to a handle to the string object
//Postcondition: Returns SUCCESS if we successfully freed
//the memory, FAILURE otherwise
void string_destroy(String_Ptr* phString);
//Precondition: hString1 and hString2 are handles to two different
//string objects to compare between them.
//Postcondition: 0 both strings are equal
// < 0: the first character that does not match has a lower value in str1 than in str2
// >0: the first character that does not match has a higher value in str1 than in str2
int string_compare(String_Ptr hString1, String_Ptr hString2);
//Precondition: hString is a handle to a string object
//Postcondition: the number of characters currently held by the string object
int string_get_size(String_Ptr hString);
//Precondition: hString is a handle to a string object
//Postcondition: the maximum number of characters the string object can hold
int string_get_capacity(String_Ptr hString);
//Precondition: hString is a handle to a string object, fp is a pointer
// to a file to read a string from
//Postcondition: SUCCESS if we successfully read a single string from the file,
// FAILURE if reached the EOF and string is still size zero
Status string_extraction(String_Ptr hString, FILE * fp);
//Precondition: hString is a handle to a string object, fp is a pointer to
// a file to write a tring to
//Postcondition: SUCCES if it successfully wrote into the FILE* and
// FAILURE if it failed to do so
Status string_insertion(String_Ptr hString, FILE * fp);
//Precondition: hString is a handle to a valid string object,
//item is a character to add to the end of the string
//Postcondition:
// return SUCCESS if the item is successfully
// added to the end of the string.
// The end of the string refers to the current size of the string.
// If the string reached its maximum capacity, i.e., size == capacity,
// then the string needed to be resized to be able to add the new item
// Resize the string by doubling its capacity
// Return FAILURE if the string could not be resized
Status string_push_back(String_Ptr hString, char item);
//Precondition: hString is a handle to a valid string object
//Postcondition: Removes the last character in the string.
// Returns SUCCESS if the last character was successfully removed
// and FAILURE if the string was empty
Status string_pop_back(String_Ptr hString);
void* string_make_temp(String_Ptr hString,unsigned int old_size);
Status string_resize(String_Ptr hString);
//Precondition: hString is the handle to a valid String_Ptr object.
//Postcondition: Returns the address of the first element of the string object
// for use as a c-string. The resulting c-string is guaranteed to be NULL
// terminated and the memory is still maintained by the string object though
// the NULL is not actually counted as part of the string (in size).
char* string_c_str(String_Ptr hString);
//Precondition: hResult and hAppend are handles to valid String objects.
//Postcondition: hResult is the handle of a string that contains the original
// hResult object followed by the hAppend object concatenated together. This
// function should guarantee no change to the hAppend object and return
// SUCCESS if they operation is successful and FAILURE if the hResult object
// is unable to accomodate the characters in the hAppend string perhaps
// because of a failed resize operation. On FAILURE, no change to either
// string should be made.
Status string_concat(String_Ptr hResult, String_Ptr hAppend);
//Precondition: hString is the handle to a valid String object.
//Postcondition: Returns an enumerated type with value TRUE if the string
// is empty and FALSE otherwise.
Boolean string_empty(String_Ptr hString);
//print all char inside hstring
Status string_print(String_Ptr hString);
//prompt user if char input matched any of the char inside htring
Status string_print_matched_char(String_Ptr hString,char c);
//Precondition:current_word_family, new_key and word are all handles to valid
// MY_STRING opaque objects. guess is an alphabetical character that can be either
// upper or lower case.
//Postcondition: Returns SUCCESS after replacing the string in new_key with the key
// value formed by considering the current word family, the word and the guess.
// Returns failure in the case of a resizing problem with the new_key string.
Status get_word_key_value(String_Ptr current_word_family, String_Ptr new_key, String_Ptr word, char guess);
#endif /* string_h */
| 44.93578 | 107 | 0.788281 | [
"object"
] |
7eea3d5addfafe6d3c581322bf3d833050720b7e | 1,620 | h | C | apiwznm/WznmQFilList.h | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | 3 | 2020-09-20T16:24:48.000Z | 2021-12-01T19:44:51.000Z | apiwznm/WznmQFilList.h | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | null | null | null | apiwznm/WznmQFilList.h | mpsitech/wznm-WhizniumSBE | 4911d561b28392d485c46e98fb915168d82b3824 | [
"MIT"
] | null | null | null | /**
* \file WznmQFilList.h
* API code for table TblWznmQFilList (declarations)
* \copyright (C) 2016-2020 MPSI Technologies GmbH
* \author Alexander Wirthmueller (auto-generation)
* \date created: 5 Dec 2020
*/
// IP header --- ABOVE
#ifndef WZNMQFILLIST_H
#define WZNMQFILLIST_H
#include <sbecore/Xmlio.h>
/**
* WznmQFilList
*/
class WznmQFilList {
public:
WznmQFilList(const Sbecore::uint jnum = 0, const std::string stubGrp = "", const std::string stubOwn = "", const std::string Filename = "", const std::string srefRefIxVTbl = "", const std::string titRefIxVTbl = "", const std::string stubRefUref = "", const std::string osrefKContent = "", const std::string titOsrefKContent = "", const std::string srefKMimetype = "", const std::string titSrefKMimetype = "", const Sbecore::uint Size = 0);
public:
Sbecore::uint jnum;
std::string stubGrp;
std::string stubOwn;
std::string Filename;
std::string srefRefIxVTbl;
std::string titRefIxVTbl;
std::string stubRefUref;
std::string osrefKContent;
std::string titOsrefKContent;
std::string srefKMimetype;
std::string titSrefKMimetype;
Sbecore::uint Size;
public:
bool readXML(xmlXPathContext* docctx, std::string basexpath = "", bool addbasetag = false);
};
/**
* ListWznmQFilList
*/
class ListWznmQFilList {
public:
ListWznmQFilList();
ListWznmQFilList(const ListWznmQFilList& src);
ListWznmQFilList& operator=(const ListWznmQFilList& src);
~ListWznmQFilList();
void clear();
public:
std::vector<WznmQFilList*> nodes;
public:
bool readXML(xmlXPathContext* docctx, std::string basexpath = "", bool addbasetag = false);
};
#endif
| 26.129032 | 440 | 0.725926 | [
"vector"
] |
7eee6c4cc381b08a92e01f917be5c200170d8c7f | 10,935 | h | C | Include/xy-platforms/xy-linux.h | BEASTSM96/fork-xy | 363cbe3f6608ead359cfea1f7b5f2dcdb435a2ea | [
"Zlib"
] | null | null | null | Include/xy-platforms/xy-linux.h | BEASTSM96/fork-xy | 363cbe3f6608ead359cfea1f7b5f2dcdb435a2ea | [
"Zlib"
] | null | null | null | Include/xy-platforms/xy-linux.h | BEASTSM96/fork-xy | 363cbe3f6608ead359cfea1f7b5f2dcdb435a2ea | [
"Zlib"
] | null | null | null | /*
* Copyright (c) 2021 Sebastian Kylander https://gaztin.com/
*
* This software is provided 'as-is', without any express or implied warranty. In no event will
* the authors be held liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose, including commercial
* applications, and to alter it and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not claim that you wrote the
* original software. If you use this software in a product, an acknowledgment in the product
* documentation would be appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be misrepresented as
* being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#pragma once
#include "../xy.h"
#if defined( XY_OS_LINUX )
//////////////////////////////////////////////////////////////////////////
/// Linux-specific includes
#include <vector>
#include <unordered_map>
#include <chrono>
#include <xcb/xcb.h>
#include <X11/Xlib-xcb.h>
#include <xcb/xcb_icccm.h> // install libxcb-icccm4-dev
#include <string>
#include <cstring>
#include <signal.h>
//////////////////////////////////////////////////////////////////////////
/// Linux-specific data structures
class xyMessageBoxData
{
public:
xyMessageBoxData( const char* pTitle, const char* pMessageContent, xyMessageButtons MessageButtons ) : m_pTitle( pTitle ), m_pMessageContent( pMessageContent ) { m_MessageButtons = MessageButtons; }
// #TODO:
~xyMessageBoxData();
// Main Event loop
bool WaitClose();
void CreateFontGC();
public:
const char* m_pTitle = "";
const char* m_pMessageContent = "";
float m_Width = 463;
float m_Height = 310;
xyMessageButtons m_MessageButtons = xyMessageButtons::Ok;
// XCB Data
xcb_window_t m_Window = NULL;
xcb_screen_t* m_pScreen = nullptr;
xcb_connection_t* m_pConnection = nullptr;
xcb_drawable_t m_PixelMap;
xcb_gcontext_t m_ForegroundGC;
xcb_gcontext_t m_FillGC;
xcb_gcontext_t m_FontGC;
xcb_intern_atom_reply_t* m_pDeleteWindReply = nullptr;
int m_VisualID = 0;
// X11 Data
Display* m_pDisplay = nullptr;
private:
void DrawMessageBox();
void TestCookie( xcb_void_cookie_t Cookie );
};
struct xyPlatformImpl
{
void xyCreateXCBMsgBox( std::string_view Title, std::string_view Message, xyMessageButtons = xyMessageButtons::Ok );
std::vector< xyMessageBoxData > m_MessageBoxes;
}; // xyPlatformImpl
//////////////////////////////////////////////////////////////////////////
/*
██╗███╗ ███╗██████╗ ██╗ ███████╗███╗ ███╗███████╗███╗ ██╗████████╗ █████╗ ████████╗██╗ ██████╗ ███╗ ██╗
██║████╗ ████║██╔══██╗██║ ██╔════╝████╗ ████║██╔════╝████╗ ██║╚══██╔══╝██╔══██╗╚══██╔══╝██║██╔═══██╗████╗ ██║
██║██╔████╔██║██████╔╝██║ █████╗ ██╔████╔██║█████╗ ██╔██╗ ██║ ██║ ███████║ ██║ ██║██║ ██║██╔██╗ ██║
██║██║╚██╔╝██║██╔═══╝ ██║ ██╔══╝ ██║╚██╔╝██║██╔══╝ ██║╚██╗██║ ██║ ██╔══██║ ██║ ██║██║ ██║██║╚██╗██║
██║██║ ╚═╝ ██║██║ ███████╗███████╗██║ ╚═╝ ██║███████╗██║ ╚████║ ██║ ██║ ██║ ██║ ██║╚██████╔╝██║ ╚████║
╚═╝╚═╝ ╚═╝╚═╝ ╚══════╝╚══════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝
*/
#if defined( XY_IMPLEMENT )
xyMessageBoxData::~xyMessageBoxData()
{
xcb_free_gc( m_pConnection, m_FontGC );
xcb_free_gc( m_pConnection, m_ForegroundGC );
xcb_free_gc( m_pConnection, m_FillGC );
xcb_free_pixmap( m_pConnection, m_PixelMap );
xcb_destroy_window( m_pConnection, m_Window );
xcb_disconnect( m_pConnection );
m_pDisplay = nullptr;
m_pScreen = nullptr;
}
void xyMessageBoxData::TestCookie( xcb_void_cookie_t Cookie )
{
xcb_generic_error_t* pError = xcb_request_check( m_pConnection, Cookie );
// #TODO: Print and maybe not raise.
if( pError )
raise( SIGTRAP );
}
void xyMessageBoxData::CreateFontGC()
{
const char* pFontName = "fixed";
xcb_void_cookie_t Cookie;
xcb_font_t Font = xcb_generate_id( m_pConnection );
Cookie = xcb_open_font_checked( m_pConnection, Font, strlen( pFontName ), pFontName );
TestCookie( Cookie );
uint32_t Mask = XCB_GC_FOREGROUND | XCB_GC_BACKGROUND | XCB_GC_FONT;
// Here we want the text to be rendered on the same color as the fill gc, with white as the text color.
uint32_t Values[] ={ m_pScreen->white_pixel, 0x343434, Font };
Cookie = xcb_create_gc_checked( m_pConnection, m_FontGC, m_PixelMap, Mask, Values );
TestCookie( Cookie );
Cookie = xcb_close_font_checked( m_pConnection, Font );
TestCookie( Cookie );
}
void xyMessageBoxData::DrawMessageBox()
{
xcb_void_cookie_t Cookie;
switch( m_MessageButtons )
{
case xyMessageButtons::Ok:
{
xcb_rectangle_t Rectangles[] ={ { m_Width / 2, m_Height / 2 - 50, 73, 30 } };
Cookie = xcb_poly_fill_rectangle_checked( m_pConnection, m_PixelMap, m_ForegroundGC, 1, Rectangles );
TestCookie( Cookie );
Cookie = xcb_image_text_8_checked( m_pConnection, strlen( "Ok" ), m_PixelMap, m_FontGC, m_Width / 2, m_Height / 2 - 50, "Ok" );
TestCookie( Cookie );
} break;
case xyMessageButtons::OkCancel:
{
// Ive got no idea what the hell this is.
xcb_rectangle_t Rectangles[] ={ { m_Width / 2 - 50, m_Height / 2, 73, 30 }, { m_Width / 2 - 40, m_Height / 2 - 50, 73, 30 } };
Cookie = xcb_poly_fill_rectangle_checked( m_pConnection, m_PixelMap, m_ForegroundGC, 2, Rectangles );
TestCookie( Cookie );
} break;
default:
break;
}
// Draw message content.
Cookie = xcb_image_text_8_checked( m_pConnection, strlen( m_pMessageContent ), m_PixelMap, m_FontGC, m_Width / 2, m_Height / 2, m_pMessageContent );
TestCookie( Cookie );
}
bool xyMessageBoxData::WaitClose()
{
xcb_generic_event_t* pEvent;
while( pEvent = xcb_wait_for_event( m_pConnection ) )
{
switch( pEvent->response_type & ~0x80 )
{
case XCB_CLIENT_MESSAGE:
{
if( ( *( xcb_client_message_event_t* )pEvent ).data.data32[ 0 ] == ( *m_pDeleteWindReply ).atom )
{
return true;
}
}
case XCB_EXPOSE:
{
xcb_clear_area( m_pConnection, 1, m_Window, 0, 0, m_Width, m_Height );
DrawMessageBox();
xcb_flush( m_pConnection );
return false;
}
}
return false;
}
}
void xyPlatformImpl::xyCreateXCBMsgBox( std::string_view Title, std::string_view Message, xyMessageButtons MessageButtons )
{
xyMessageBoxData MessageBox ={ Title.data(), Message.data(), MessageButtons };
// Open Xlib display.
MessageBox.m_pDisplay = XOpenDisplay( 0 );
// Get connection from xlib.
MessageBox.m_pConnection = XGetXCBConnection( MessageBox.m_pDisplay );
// Find first screen.
MessageBox.m_pScreen = xcb_setup_roots_iterator( xcb_get_setup( MessageBox.m_pConnection ) ).data;
uint32_t GCMask = 0;
uint32_t GCValues[ 2 ];
// Create black graphic context.
MessageBox.m_ForegroundGC = xcb_generate_id( MessageBox.m_pConnection );
MessageBox.m_FillGC = xcb_generate_id( MessageBox.m_pConnection ); // #TODO: We might not need this.
MessageBox.m_FontGC = xcb_generate_id( MessageBox.m_pConnection ); // Will be used when rendering
// Create foreground gc.
GCMask = XCB_GC_FOREGROUND | XCB_GC_GRAPHICS_EXPOSURES;
GCValues[ 0 ] = 0x2c2c2c;
GCValues[ 1 ] = 0;
xcb_create_gc( MessageBox.m_pConnection, MessageBox.m_ForegroundGC, MessageBox.m_pScreen->root, GCMask, GCValues );
// Create pixel/pixmap map.
MessageBox.m_PixelMap = xcb_generate_id( MessageBox.m_pConnection );
xcb_create_pixmap( MessageBox.m_pConnection, MessageBox.m_pScreen->root_depth, MessageBox.m_PixelMap, MessageBox.m_pScreen->root, 500, 500 );
MessageBox.CreateFontGC();
// Create fill gc.
GCMask = XCB_GC_FOREGROUND | XCB_GC_BACKGROUND;
GCValues[ 0 ] = 0x343434;
GCValues[ 1 ] = 0x343434;
xcb_create_gc( MessageBox.m_pConnection, MessageBox.m_FillGC, MessageBox.m_pScreen->root, GCMask, GCValues );
// Generate window ID
MessageBox.m_Window = xcb_generate_id( MessageBox.m_pConnection );
// xcb events -> https://xcb.freedesktop.org/tutorial/events/
uint32_t Mask = XCB_CW_BACK_PIXMAP | XCB_CW_EVENT_MASK;
uint32_t EventMask = XCB_EVENT_MASK_EXPOSURE | XCB_EVENT_MASK_KEY_PRESS;
uint32_t ValueList[] ={ MessageBox.m_PixelMap, EventMask };
xcb_create_window( MessageBox.m_pConnection, XCB_COPY_FROM_PARENT, MessageBox.m_Window, MessageBox.m_pScreen->root, 0, 0, MessageBox.m_Width, MessageBox.m_Height, 8, XCB_WINDOW_CLASS_INPUT_OUTPUT, MessageBox.m_VisualID, Mask, ValueList );
// Move window to center
int WindowPos[] ={ MessageBox.m_pScreen->width_in_pixels - MessageBox.m_Width, MessageBox.m_pScreen->height_in_pixels - MessageBox.m_Height };
xcb_configure_window( MessageBox.m_pConnection, MessageBox.m_Window, XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y, WindowPos );
// Set title.
xcb_change_property( MessageBox.m_pConnection, XCB_PROP_MODE_REPLACE, MessageBox.m_Window, XCB_ATOM_WM_NAME, XCB_ATOM_STRING, 8, strlen( MessageBox.m_pTitle ), MessageBox.m_pTitle );
// Icon title.
xcb_change_property( MessageBox.m_pConnection, XCB_PROP_MODE_REPLACE, MessageBox.m_Window, XCB_ATOM_WM_ICON_NAME, XCB_ATOM_STRING, 8, strlen( MessageBox.m_pTitle ), MessageBox.m_pTitle );
xcb_intern_atom_cookie_t ProtocolsCookie = xcb_intern_atom( MessageBox.m_pConnection, 1, 12, "WM_PROTOCOLS" );
xcb_intern_atom_reply_t* pProtcolsReply = xcb_intern_atom_reply( MessageBox.m_pConnection, ProtocolsCookie, 0 );
xcb_intern_atom_cookie_t CloseWindowCookie = xcb_intern_atom( MessageBox.m_pConnection, 0, 16, "WM_DELETE_WINDOW" );
MessageBox.m_pDeleteWindReply = xcb_intern_atom_reply( MessageBox.m_pConnection, CloseWindowCookie, 0 );
// Gain access to WM_PROTOCOLS.
xcb_change_property( MessageBox.m_pConnection, XCB_PROP_MODE_REPLACE, MessageBox.m_Window, ( *pProtcolsReply ).atom, 4, 32, 1, &( *MessageBox.m_pDeleteWindReply ).atom );
xcb_map_window( MessageBox.m_pConnection, MessageBox.m_Window );
// Great hack...
xcb_size_hints_t SizeHints;
SizeHints.flags = XCB_ICCCM_SIZE_HINT_P_MIN_SIZE | XCB_ICCCM_SIZE_HINT_P_MAX_SIZE;
SizeHints.min_width = SizeHints.max_width = MessageBox.m_Width;
SizeHints.min_height = SizeHints.max_height = MessageBox.m_Height;
xcb_icccm_set_wm_normal_hints( MessageBox.m_pConnection, MessageBox.m_Window, &SizeHints );
xcb_flush( MessageBox.m_pConnection );
// Fill rect with black. #TODO: Fill color corresponding to theme. Or even see if the theme color is a warm/cool color and set fill accordingly.
xcb_rectangle_t Rectangles[] ={ { 0, 0, MessageBox.m_Width, MessageBox.m_Height } };
xcb_poly_fill_rectangle( MessageBox.m_pConnection, MessageBox.m_PixelMap, MessageBox.m_FillGC, 1, Rectangles );
while( !MessageBox.WaitClose() )
std::this_thread::sleep_for( std::chrono::milliseconds( 1 ) );
//MessageBox = { };
}
#endif
#endif // XY_OS_LINUX
| 34.171875 | 239 | 0.687609 | [
"vector"
] |
7eeeb5e52cc221c2e731a1e64268cd6ab2583f08 | 4,494 | h | C | source/tensors/edges/class_edges_finite.h | DavidAce/DMRG | e465fd903eade1bf6aa74daacd8e2cf02e9e9332 | [
"MIT"
] | 9 | 2017-10-31T22:50:28.000Z | 2022-03-10T15:45:27.000Z | source/tensors/edges/class_edges_finite.h | DavidAce/DMRG | e465fd903eade1bf6aa74daacd8e2cf02e9e9332 | [
"MIT"
] | null | null | null | source/tensors/edges/class_edges_finite.h | DavidAce/DMRG | e465fd903eade1bf6aa74daacd8e2cf02e9e9332 | [
"MIT"
] | 1 | 2019-07-16T00:27:56.000Z | 2019-07-16T00:27:56.000Z | #pragma once
#include "class_env_pair.h"
#include <complex>
#include <config/enums.h>
#include <general/eigen_tensor_fwd_decl.h>
#include <memory>
#include <optional>
#include <vector>
class class_env_ene;
class class_env_var;
class class_edges_finite {
public:
using Scalar = std::complex<double>;
std::vector<size_t> active_sites;
private:
// size_t iter = 0;
// size_t step = 0;
// int direction = 1;
std::vector<std::unique_ptr<class_env_ene>> eneL;
std::vector<std::unique_ptr<class_env_ene>> eneR;
std::vector<std::unique_ptr<class_env_var>> varL;
std::vector<std::unique_ptr<class_env_var>> varR;
public:
class_edges_finite();
~class_edges_finite(); // Read comment on implementation
class_edges_finite(class_edges_finite &&other) noexcept; // default move ctor
class_edges_finite &operator=(class_edges_finite &&other) noexcept; // default move assign
class_edges_finite(const class_edges_finite &other); // copy ctor
class_edges_finite &operator=(const class_edges_finite &other); // copy assign
void initialize(size_t model_size);
[[nodiscard]] const class_env_ene &get_eneL(size_t pos) const;
[[nodiscard]] const class_env_ene &get_eneR(size_t pos) const;
[[nodiscard]] const class_env_var &get_varL(size_t pos) const;
[[nodiscard]] const class_env_var &get_varR(size_t pos) const;
[[nodiscard]] class_env_ene & get_eneL(size_t pos);
[[nodiscard]] class_env_var & get_varR(size_t pos);
[[nodiscard]] class_env_var & get_varL(size_t pos);
[[nodiscard]] class_env_ene & get_eneR(size_t pos);
[[nodiscard]] size_t get_length() const;
[[nodiscard]] bool is_real() const;
[[nodiscard]] bool has_nan() const;
void assert_validity() const;
void eject_edges_inactive_ene(std::optional<std::vector<size_t>> sites = std::nullopt);
void eject_edges_inactive_var(std::optional<std::vector<size_t>> sites = std::nullopt);
void eject_edges_inactive(std::optional<std::vector<size_t>> sites = std::nullopt);
void eject_edges_all_ene();
void eject_edges_all_var();
void eject_edges_all();
[[nodiscard]] env_pair<const class_env_ene> get_ene(size_t posL, size_t posR) const;
[[nodiscard]] env_pair<const class_env_var> get_var(size_t posL, size_t posR) const;
[[nodiscard]] env_pair<class_env_ene> get_ene(size_t posL, size_t posR);
[[nodiscard]] env_pair<class_env_var> get_var(size_t posL, size_t posR);
[[nodiscard]] env_pair<const class_env_ene> get_ene(size_t pos) const;
[[nodiscard]] env_pair<const class_env_var> get_var(size_t pos) const;
[[nodiscard]] env_pair<class_env_ene> get_ene(size_t pos);
[[nodiscard]] env_pair<class_env_var> get_var(size_t pos);
[[nodiscard]] env_pair<const Eigen::Tensor<Scalar, 3>> get_ene_blk(size_t posL, size_t posR) const;
[[nodiscard]] env_pair<const Eigen::Tensor<Scalar, 3>> get_var_blk(size_t posL, size_t posR) const;
[[nodiscard]] env_pair<Eigen::Tensor<Scalar, 3>> get_ene_blk(size_t posL, size_t posR);
[[nodiscard]] env_pair<Eigen::Tensor<Scalar, 3>> get_var_blk(size_t posL, size_t posR);
[[nodiscard]] env_pair<const class_env_ene> get_multisite_ene(std::optional<std::vector<size_t>> sites = std::nullopt) const;
[[nodiscard]] env_pair<const class_env_var> get_multisite_var(std::optional<std::vector<size_t>> sites = std::nullopt) const;
[[nodiscard]] env_pair<class_env_ene> get_multisite_ene(std::optional<std::vector<size_t>> sites = std::nullopt);
[[nodiscard]] env_pair<class_env_var> get_multisite_var(std::optional<std::vector<size_t>> sites = std::nullopt);
[[nodiscard]] env_pair<const Eigen::Tensor<Scalar, 3>> get_multisite_ene_blk(std::optional<std::vector<size_t>> sites = std::nullopt) const;
[[nodiscard]] env_pair<const Eigen::Tensor<Scalar, 3>> get_multisite_var_blk(std::optional<std::vector<size_t>> sites = std::nullopt) const;
[[nodiscard]] env_pair<Eigen::Tensor<Scalar, 3>> get_multisite_ene_blk(std::optional<std::vector<size_t>> sites = std::nullopt);
[[nodiscard]] env_pair<Eigen::Tensor<Scalar, 3>> get_multisite_var_blk(std::optional<std::vector<size_t>> sites = std::nullopt);
[[nodiscard]] std::pair<std::vector<size_t>, std::vector<size_t>> get_active_ids() const;
};
| 51.655172 | 144 | 0.694036 | [
"vector"
] |
7ef361f12bd5455b915387945f68e3c9f45343c7 | 931 | h | C | src/backends/dx/RenderComponent/DescHeapPool.h | shiinamiyuki/LuisaCompute | f8358f8ec138950a84f570c0ede24cc76fc159de | [
"BSD-3-Clause"
] | null | null | null | src/backends/dx/RenderComponent/DescHeapPool.h | shiinamiyuki/LuisaCompute | f8358f8ec138950a84f570c0ede24cc76fc159de | [
"BSD-3-Clause"
] | null | null | null | src/backends/dx/RenderComponent/DescHeapPool.h | shiinamiyuki/LuisaCompute | f8358f8ec138950a84f570c0ede24cc76fc159de | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <Common/GFXUtil.h>
#include <util/VObject.h>
#include <util/MetaLib.h>
#include <RenderComponent/DescriptorHeap.h>
struct DescHeapElement
{
DescriptorHeap* heap;
uint offset;
DescHeapElement() : heap(nullptr), offset(0) {}
DescHeapElement(DescriptorHeap* const heap,
uint const offset) : heap(heap), offset(offset) {}
void operator=(const DescHeapElement& other)
{
heap = other.heap;
offset = other.offset;
}
};
class VENGINE_DLL_RENDERER DescHeapPool
{
private:
vstd::vector<std::unique_ptr<DescriptorHeap>> arr;
ArrayList<DescHeapElement> poolValue;
uint capacity;
uint size;
D3D12_DESCRIPTOR_HEAP_TYPE type;
void Add(GFXDevice* device);
public:
DescHeapPool(uint size, uint initCapacity, D3D12_DESCRIPTOR_HEAP_TYPE type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
DescHeapElement Get(GFXDevice* device);
void Return(const DescHeapElement& target);
KILL_COPY_CONSTRUCT(DescHeapPool)
};
| 27.382353 | 118 | 0.780881 | [
"vector"
] |
7d09e4860da339a4c6807f43d3f6b5f8ba44d806 | 1,073 | h | C | src/glossary/include/DictionaryStatistics.h | michalovsky/Glossary | a5623d474d7b8a839ef27571adfe5f2151a5fb79 | [
"MIT"
] | 6 | 2020-01-14T05:11:38.000Z | 2021-06-14T09:35:42.000Z | src/glossary/include/DictionaryStatistics.h | michalovsky/Glossary | a5623d474d7b8a839ef27571adfe5f2151a5fb79 | [
"MIT"
] | null | null | null | src/glossary/include/DictionaryStatistics.h | michalovsky/Glossary | a5623d474d7b8a839ef27571adfe5f2151a5fb79 | [
"MIT"
] | null | null | null | #pragma once
#include <ostream>
#include <vector>
#include "dictionaryService/DictionaryName.h"
namespace glossary
{
struct DictionaryStatistics
{
dictionaryService::DictionaryName dictionaryName;
unsigned correctAnswers;
unsigned incorrectAnswers;
};
using DictionariesStatistics = std::vector<DictionaryStatistics>;
inline bool operator==(const DictionaryStatistics& lhs, const DictionaryStatistics& rhs)
{
return lhs.dictionaryName == rhs.dictionaryName && lhs.correctAnswers == rhs.correctAnswers &&
lhs.incorrectAnswers == rhs.incorrectAnswers;
}
inline std::string toString(const DictionaryStatistics& dictionaryStatistics)
{
return "{dictionaryName:" + dictionaryStatistics.dictionaryName +
",correctAnswers:" + std::to_string(dictionaryStatistics.correctAnswers) +
",incorrectAnswers:" + std::to_string(dictionaryStatistics.incorrectAnswers) + "}";
}
inline std::ostream& operator<<(std::ostream& os, const DictionaryStatistics& dictionaryStatistics)
{
return os << toString(dictionaryStatistics);
}
} | 29.805556 | 99 | 0.759553 | [
"vector"
] |
7d0a1e21084ec4dda71e3a15808f10de4be68015 | 872 | h | C | include/il2cpp/System/Action_BeforeRenderHelper.OrderBlock_.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | 1 | 2022-01-15T20:20:27.000Z | 2022-01-15T20:20:27.000Z | include/il2cpp/System/Action_BeforeRenderHelper.OrderBlock_.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | null | null | null | include/il2cpp/System/Action_BeforeRenderHelper.OrderBlock_.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | null | null | null | #pragma once
#include "il2cpp.h"
void System_Action_BeforeRenderHelper_OrderBlock____ctor (System_Action_BeforeRenderHelper_OrderBlock__o* __this, Il2CppObject* object, intptr_t method, const MethodInfo* method_info);
void System_Action_BeforeRenderHelper_OrderBlock___Invoke (System_Action_BeforeRenderHelper_OrderBlock__o* __this, UnityEngine_BeforeRenderHelper_OrderBlock_o obj, const MethodInfo* method_info);
System_IAsyncResult_o* System_Action_BeforeRenderHelper_OrderBlock___BeginInvoke (System_Action_BeforeRenderHelper_OrderBlock__o* __this, UnityEngine_BeforeRenderHelper_OrderBlock_o obj, System_AsyncCallback_o* callback, Il2CppObject* object, const MethodInfo* method_info);
void System_Action_BeforeRenderHelper_OrderBlock___EndInvoke (System_Action_BeforeRenderHelper_OrderBlock__o* __this, System_IAsyncResult_o* result, const MethodInfo* method_info);
| 96.888889 | 274 | 0.897936 | [
"object"
] |
7d0f2377e6fb445d609d87694a05f0bd2bf5c1b5 | 480 | h | C | SceneImporter.h | teddemunnik/cpu-pathtracer | a135c1984473f0fb925688607bdecb3517f23757 | [
"MIT"
] | 1 | 2015-05-27T22:27:03.000Z | 2015-05-27T22:27:03.000Z | SceneImporter.h | teddemunnik/cpu-pathtracer | a135c1984473f0fb925688607bdecb3517f23757 | [
"MIT"
] | null | null | null | SceneImporter.h | teddemunnik/cpu-pathtracer | a135c1984473f0fb925688607bdecb3517f23757 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <vector>
#include <map>
#include "template.h"
namespace Tmpl8{
class Material;
};
using namespace Tmpl8;
struct Group{
Group() : intensity(1.0f), refl(0.0f), refr(0.0f), refrIndex(1.0f){}
float intensity;
float refl;
float refr;
float refrIndex;
float light;
float absorption;
};
struct Model{
std::string name;
std::map<std::string, Group*> groups;
};
void ImportScene( const char* path, std::vector<Model*>* out_models); | 16 | 69 | 0.697917 | [
"vector",
"model"
] |
7d2156208273a2a12ac24917f118d1c2e0368f72 | 1,280 | h | C | Physics3D_4_-_handout/PhysBody3D.h | marcpt98/Physics_car_game | e1685f9c4e43000c5ab13796e7c0bd46824abdf4 | [
"Unlicense"
] | null | null | null | Physics3D_4_-_handout/PhysBody3D.h | marcpt98/Physics_car_game | e1685f9c4e43000c5ab13796e7c0bd46824abdf4 | [
"Unlicense"
] | null | null | null | Physics3D_4_-_handout/PhysBody3D.h | marcpt98/Physics_car_game | e1685f9c4e43000c5ab13796e7c0bd46824abdf4 | [
"Unlicense"
] | null | null | null | #ifndef __PhysBody3D_H__
#define __PhysBody3D_H__
#include "p2DynArray.h"
#include "glmath.h"
class btRigidBody;
class btCollisionShape;
struct btDefaultMotionState;
class Module;
class btRaycastVehicle;
class vec3;
class Sphere;
class Cube;
class Cylinder;
class Plane;
class btQuaternion;
class Primitive;
class PhysBody3D
{
public:
PhysBody3D();
~PhysBody3D();
void SetBody(Sphere* primitive, float mass);
void SetBody(Cube* primitive, float mass);
void SetBody(Cylinder* primitive, float mass);
bool HasBody() const;
btRigidBody* GetBody() const;
void GetTransform(float* matrix) const;
void SetTransform(const float* matrix) const;
void SetPos(float x, float y, float z);
void SetRotation(btQuaternion quat);
const vec3 GetPos() const;
vec3 GetForwardVector() const;
vec3 GetaAboveVector() const;
void SetAsSensor(bool is_sensor);
bool IsSensor() const;
void SetSpeed(vec3 speed);
void Push(vec3 force);
void Stop();
private:
void SetBody(btCollisionShape* shape, Primitive* parent, float mass);
btRigidBody* body;
btCollisionShape* colShape;
btDefaultMotionState* motionState;
public:
Primitive* parentPrimitive;
p2DynArray<Module*> collision_listeners;
btRaycastVehicle* vehicle;
bool is_sensor = false;
};
#endif // __PhysBody3D_H__ | 20.31746 | 70 | 0.771094 | [
"shape"
] |
b425187dda9c6b5b5dfededab5d872b8c35a0b8c | 1,880 | h | C | MapRenderer/include/renderer/DynamicObjects.h | zerodowned/Iris1_DeveloperTools | 0b5510bb46824d8939846f73c7e63ed7eecf827d | [
"DOC"
] | 1 | 2019-02-08T18:03:28.000Z | 2019-02-08T18:03:28.000Z | MapRenderer/include/renderer/DynamicObjects.h | SiENcE/Iris1_DeveloperTools | 0b5510bb46824d8939846f73c7e63ed7eecf827d | [
"DOC"
] | null | null | null | MapRenderer/include/renderer/DynamicObjects.h | SiENcE/Iris1_DeveloperTools | 0b5510bb46824d8939846f73c7e63ed7eecf827d | [
"DOC"
] | 7 | 2015-03-11T22:06:23.000Z | 2019-12-21T09:49:57.000Z | //
// File: DynamicObjects.h
// Created by: Alexander Oster - tensor@ultima-iris.de
//
/*****
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*****/
#ifndef _DYNAMICOBJECTS_H_
#define _DYNAMICOBJECTS_H_
#ifdef WIN32
#include <windows.h>
#endif
#include "SDL/SDL.h"
#include <map>
#define DYNAMICTYPE_WORLD 0
#define DYNAMICTYPE_CONTAINER 1
#define DYNAMICTYPE_EQUIPMENT 2
class cDynamicObject {
private:
public:
Uint32 id;
int x, y, z;
int model;
int itemcount;
int incrcounter;
Uint8 direction;
Uint16 dye;
Uint8 flag;
bool clip;
int type;
Uint32 parent;
float sphere[5];
cDynamicObject ();
~ cDynamicObject ();
};
typedef std::map<Uint32, cDynamicObject *> dynamiclist_t;
class cDynamicObjectList
{
private:
dynamiclist_t dynamiclist;
public:
cDynamicObjectList ();
~cDynamicObjectList ();
void Clear (void);
cDynamicObject * Add (Uint32 id);
cDynamicObject * Get (unsigned int id);
void Delete (unsigned int id);
dynamiclist_t * GetList(void) { return &dynamiclist; }
int GetCount(void) { return dynamiclist.size(); }
protected:
};
extern cDynamicObjectList * pDynamicObjectList;
#endif //_DYNAMICOBJECTS_H_
| 21.860465 | 77 | 0.714362 | [
"model"
] |
b426416c37570f49e4074a0388abffecfcef1492 | 4,672 | h | C | include/MeshVerticesBuffer.h | ciliz-co-ltd/w4-sdk-updater | ecf21ea5d884d6f0a29532764ccfb225dcd1c9a0 | [
"MIT"
] | null | null | null | include/MeshVerticesBuffer.h | ciliz-co-ltd/w4-sdk-updater | ecf21ea5d884d6f0a29532764ccfb225dcd1c9a0 | [
"MIT"
] | null | null | null | include/MeshVerticesBuffer.h | ciliz-co-ltd/w4-sdk-updater | ecf21ea5d884d6f0a29532764ccfb225dcd1c9a0 | [
"MIT"
] | 1 | 2021-10-13T14:25:11.000Z | 2021-10-13T14:25:11.000Z | #pragma once
#include "VerticesBuffer.h"
#include "Nodes/Mesh.h"
#include "Nodes/SkinnedMesh.h"
#include "UserVerticesBuffer.h"
namespace w4::resources
{
class MeshVerticesBuffer
: public VerticesBuffer<render::Mesh::VertexFormat>
, public core::Cache<MeshVerticesBuffer, sptr<MeshVerticesBuffer>, ResourceLoadDescr>
{
W4_OBJECT(MeshVerticesBuffer, VerticesBuffer<render::Mesh::VertexFormat>);
public:
using VerticesBuffer<render::Mesh::VertexFormat>::VerticesBuffer;
static sptr<MeshVerticesBuffer> load(const ResourceLoadDescr& source)
{
if (source.getLoadType() != ResourceLoadType::File)
{
FATAL_ERROR("generators are not supported for MeshVerticesBuffer");
}
return Asset::getResource<MeshVerticesBuffer>(*source.getFileDescription());
}
};
class SkinnedMeshVerticesBuffer
: public VerticesBuffer<render::SkinnedMesh::VertexFormat>
, public core::Cache<SkinnedMeshVerticesBuffer, sptr<SkinnedMeshVerticesBuffer>, ResourceLoadDescr>
{
W4_OBJECT(SkinnedMeshVerticesBuffer, VerticesBuffer<render::Mesh::VertexFormat>);
public:
using VerticesBuffer<render::SkinnedMesh::VertexFormat>::VerticesBuffer;
static sptr<SkinnedMeshVerticesBuffer> load(const ResourceLoadDescr& source)
{
if (source.getLoadType() != ResourceLoadType::File)
{
FATAL_ERROR("generators are not supported for SkinnedMeshVerticesBuffer");
}
return Asset::getResource<SkinnedMeshVerticesBuffer>(*source.getFileDescription());
}
};
#define SPECIALIZE_USER_VERTEX_BUFFER(PREFIX, VERTEX_FORMAT) \
class PREFIX##UserVerticesBuffer: public UserVerticesBuffer<VERTEX_FORMAT>, public core::Cache<PREFIX##UserVerticesBuffer> \
{ \
W4_OBJECT(PREFIX##UserVerticesBuffer, UserVerticesBuffer<VERTEX_FORMAT>); \
public: \
explicit PREFIX##UserVerticesBuffer(const ResourceLoadDescr& source): Super(source) {} \
PREFIX##UserVerticesBuffer(const ResourceLoadDescr& source, cref<filesystem::Stream> stream, uint64_t offset, uint64_t size) \
: Super(source, stream, offset, size) {} \
static w4::sptr<PREFIX##UserVerticesBuffer> load(const ResourceLoadDescr& source) \
{ \
if (source.getLoadType() != ResourceLoadType::File) \
{ \
FATAL_ERROR("generators are not supported for " #PREFIX "UserVerticesBuffer"); \
} \
if (source.getFileDescription()->getAssetFilePath().empty()) \
{ \
return make::sptr<PREFIX##UserVerticesBuffer>(source); \
} \
return Asset::getResource<PREFIX##UserVerticesBuffer>(*source.getFileDescription()); \
} \
} \
SPECIALIZE_USER_VERTEX_BUFFER(Mesh, MeshVertexFormat);
SPECIALIZE_USER_VERTEX_BUFFER(SkinnedMesh, SkinnedMeshVertexFormat);
#undef SPECIALIZE_USER_VERTEX_BUFFER
} | 65.802817 | 133 | 0.439212 | [
"mesh",
"render"
] |
b435322ea4058dc6b274fa9a65512dab7bebb96d | 219 | c | C | tests/openacc-users-group/NAS_SHOC_OpenACC_2.5/reference/ref_add_bt.c | passlab/accparser | e8c18d16432eb5122ab0de04d3519d8559d23a34 | [
"BSD-2-Clause"
] | null | null | null | tests/openacc-users-group/NAS_SHOC_OpenACC_2.5/reference/ref_add_bt.c | passlab/accparser | e8c18d16432eb5122ab0de04d3519d8559d23a34 | [
"BSD-2-Clause"
] | null | null | null | tests/openacc-users-group/NAS_SHOC_OpenACC_2.5/reference/ref_add_bt.c | passlab/accparser | e8c18d16432eb5122ab0de04d3519d8559d23a34 | [
"BSD-2-Clause"
] | null | null | null | #pragma acc parallel loop gang present (u, rhs) num_gangs (gp22) num_workers (4) vector_length (32)
#pragma acc kernels loop gang present (u, rhs)
#pragma acc loop worker independent
#pragma acc loop vector independent
| 43.8 | 99 | 0.780822 | [
"vector"
] |
b43ef4fcbb4df7d14025541b002ae72ab8f662e4 | 8,080 | h | C | src/lib/elfldltl/include/lib/elfldltl/memory.h | Prajwal-Koirala/fuchsia | ca7ae6c143cd4c10bad9aa1869ffcc24c3e4b795 | [
"BSD-2-Clause"
] | 2 | 2021-12-29T10:11:08.000Z | 2022-01-04T15:37:09.000Z | src/lib/elfldltl/include/lib/elfldltl/memory.h | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | 2 | 2021-09-19T21:55:09.000Z | 2021-12-19T03:34:53.000Z | src/lib/elfldltl/include/lib/elfldltl/memory.h | PlugFox/fuchsia | 39afe5230d41628b3c736a6e384393df954968c8 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef SRC_LIB_ELFLDLTL_INCLUDE_LIB_ELFLDLTL_MEMORY_H_
#define SRC_LIB_ELFLDLTL_INCLUDE_LIB_ELFLDLTL_MEMORY_H_
#include <lib/stdcompat/span.h>
#include <cstdint>
#include <optional>
namespace elfldltl {
// Various interfaces require a File or Memory type to access data structures.
//
// This header specifies the API contracts those template interfaces require,
// and provides an implementation for the simplest case.
//
// Both File and Memory types are not copied or moved, only used by reference.
// Each interface uses either the File API or the Memory API, but both APIs
// can be implemented by a single object when appropriate.
//
// The File type provides these methods, which take an offset into the file,
// guaranteed to be correctly aligned with respect to T:
//
// * template <typename T>
// std::optional<Result> ReadFromFile(size_t offset);
//
// This reads a single datum from the file. If Result is not T then const
// Result& is convertible to const T&. Thus Result can yield the T by value
// or by reference, depending on the implementation. In the simple memory
// implementation it is by reference. Other implementations read directly
// into a local T object and return that.
//
// * template <typename T, size_t MaxCount>
// std::optional<Result> ReadArrayFromFile(size_t offset, size_t count);
//
// This is like ReadFromFile, but for an array of T[count]. The const
// Result& referring to the return value's value() can be treated as a
// view-like container of T whose size() == count, but that might own the
// data. MaxCount may be ignored if Result is a non-owning type. If the
// array will be returned by value, MaxCount is a reasonable static upper
// bound for count. A count beyond the static limit results in std::nullopt,
// not truncation.
//
// The Memory type provides these methods, which take a memory address as used
// in the ELF metadata in this file, guaranteed to be correctly aligned with
// respect to T.
//
// * template <typename T>
// std::optional<cpp20::span<const T>> ReadArray(uintptr_t address, size_t count);
//
// This returns a view of T[count] if that's accessible at the address. The
// data must be permanently accessible for the lifetime of the Memory object.
//
// * template <typename T>
// std::optional<cpp20::span<const T>> ReadArray(uintptr_t address);
//
// This is the same but for when the caller doesn't know the size of the
// array. So this returns a view of T[n] for some n > 0 that is accessible,
// as much as is possibly accessible for valid RODATA in the ELF file's
// memory image. The caller will be doing random-access that will only
// access the "actually valid" indices of the returned span if the rest of
// the input data (e.g. relocation records) is also valid. Access past the
// true size of the array may return garbage, but reading from pointers into
// anywhere in the span returned will at least be safe to perform (for the
// lifetime of the Memory object).
//
// * template <typename T>
// bool Store(Addr address, U value);
//
// This stores a T at the given address, which is in some writable segment
// of the file previously arranged with this Memory object. It returns
// false if processing should fail early. Note the explicit template
// argument is always used to indicate the type whose operator= will be
// called on the actual memory, so it is of the explicitly intended width
// and can be a byte-swapping type. The value argument might be of the same
// type or of any type convertible to it.
//
// * template <typename T>
// bool StoreAdd(Addr address, U value);
//
// This is like Store but it adds the argument to the word already in place,
// i.e. the in-place addend. Note T::operator= is always called, not +=.
// This does direct memory access to an ELF load image already mapped in.
// Addresses in the ELF metadata are relative to a given base address that
// corresponds to the beginning of the image this object points to.
class DirectMemory {
public:
// This type could easily be copyable. But the template APIs should always
// use Memory types only be reference. So make this type uncopyable and
// unmovable just so using it enforces API constraints other implementations
// might actually need to rely on.
DirectMemory() = delete;
DirectMemory(const DirectMemory&) = delete;
DirectMemory(DirectMemory&&) = delete;
// This takes a memory image and the file-relative address it corresponds to.
DirectMemory(cpp20::span<std::byte> image, uintptr_t base) : image_(image), base_(base) {}
// File API assumes this file's first segment has page-aligned p_offset of 0.
template <typename T>
std::optional<std::reference_wrapper<const T>> ReadFromFile(size_t offset) {
if (offset >= image_.size()) [[unlikely]] {
return std::nullopt;
}
auto memory = image_.subspan(offset);
if (memory.size() < sizeof(T)) [[unlikely]] {
return std::nullopt;
}
return std::cref(*reinterpret_cast<const T*>(memory.data()));
}
template <typename T, size_t MaxCount>
std::optional<cpp20::span<const T>> ReadArrayFromFile(size_t offset, size_t count) {
auto data = ReadAll<T>(offset);
if (data.empty() || count > data.size()) [[unlikely]] {
return std::nullopt;
}
return data.subspan(0, count);
}
// Memory API assumes the image represents the PT_LOAD segment layout of the
// file by p_vaddr relative to the base address (not the raw file image by
// p_offset).
template <typename T>
std::optional<cpp20::span<const T>> ReadArray(uintptr_t ptr, size_t count) {
if (ptr < base_) [[unlikely]] {
return std::nullopt;
}
return ReadArrayFromFile<T, 0>(ptr - base_, count);
}
template <typename T>
std::optional<cpp20::span<const T>> ReadArray(uintptr_t ptr) {
if (ptr < base_) [[unlikely]] {
return std::nullopt;
}
auto data = ReadAll<T>(ptr - base_);
if (data.empty()) [[unlikely]] {
return std::nullopt;
}
return data;
}
// Note the argument is not of type T so that T can never be deduced from the
// argument: the caller must use Store<T> explicitly to avoid accidentally
// using the wrong type since lots of integer types are silently coercible to
// other ones. (The caller doesn't need to supply the U template parameter.)
template <typename T, typename U>
bool Store(uintptr_t ptr, U value) {
if (auto word = StoreLocation<T>(ptr)) [[likely]] {
*word = value;
return true;
}
return false;
}
// Note the argument is not of type T so that T can never be deduced from the
// argument: the caller must use Store<T> explicitly to avoid accidentally
// using the wrong type since lots of integer types are silently coercible to
// other ones. (The caller doesn't need to supply the U template parameter.)
template <typename T, typename U>
bool StoreAdd(uintptr_t ptr, U value) {
if (auto word = StoreLocation<T>(ptr)) [[likely]] {
*word = *word + value; // Don't assume T::operator+= works.
return true;
}
return false;
}
private:
template <typename T>
cpp20::span<const T> ReadAll(size_t offset) {
if (offset >= image_.size()) [[unlikely]] {
return {};
}
auto memory = image_.subspan(offset);
return {
reinterpret_cast<const T*>(memory.data()),
memory.size() / sizeof(T),
};
}
template <typename T>
T* StoreLocation(uintptr_t ptr) {
if (ptr < base_ || ptr - base_ >= image_.size() || image_.size() - (ptr - base_) < sizeof(T))
[[unlikely]] {
return nullptr;
}
return reinterpret_cast<T*>(&image_[ptr - base_]);
}
cpp20::span<std::byte> image_;
uintptr_t base_;
};
} // namespace elfldltl
#endif // SRC_LIB_ELFLDLTL_INCLUDE_LIB_ELFLDLTL_MEMORY_H_
| 39.414634 | 97 | 0.694802 | [
"object"
] |
b43f68ea542342ffa0b87bce6e87bfaabeb97479 | 3,005 | h | C | generation/WinSDK/RecompiledIdlHeaders/um/devquerydef.h | forksnd/win32metadata | 3e92612032578896ca3eebd543701c97a95d5214 | [
"MIT"
] | 984 | 2021-01-21T17:39:07.000Z | 2022-03-30T16:29:34.000Z | generation/WinSDK/RecompiledIdlHeaders/um/devquerydef.h | forksnd/win32metadata | 3e92612032578896ca3eebd543701c97a95d5214 | [
"MIT"
] | 684 | 2021-01-21T20:24:26.000Z | 2022-03-31T23:06:50.000Z | generation/WinSDK/RecompiledIdlHeaders/um/devquerydef.h | forksnd/win32metadata | 3e92612032578896ca3eebd543701c97a95d5214 | [
"MIT"
] | 65 | 2021-01-21T18:21:34.000Z | 2022-03-24T05:08:12.000Z | /*++
Copyright (c) Microsoft Corporation
Abstract:
This module contains the Device Object API shared definitions.
*/
#pragma once
#include <winapifamily.h>
#pragma region Desktop Family or OneCore Family
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_SYSTEM)
#include <devfiltertypes.h>
#if (NTDDI_VERSION >= NTDDI_WIN8)
#if defined(__cplusplus)
extern "C" {
#endif // defined(__cplusplus)
typedef
#ifdef MIDL_PASS
[v1_enum]
#endif
enum
_DEV_OBJECT_TYPE
{
DevObjectTypeUnknown,
DevObjectTypeDeviceInterface,
DevObjectTypeDeviceContainer,
DevObjectTypeDevice,
DevObjectTypeDeviceInterfaceClass,
DevObjectTypeAEP,
DevObjectTypeAEPContainer,
DevObjectTypeDeviceInstallerClass,
DevObjectTypeDeviceInterfaceDisplay,
DevObjectTypeDeviceContainerDisplay,
DevObjectTypeAEPService,
DevObjectTypeDevicePanel,
} DEV_OBJECT_TYPE, *PDEV_OBJECT_TYPE;
typedef
#ifdef MIDL_PASS
[v1_enum]
#endif
enum _DEV_QUERY_FLAGS
{
DevQueryFlagNone = 0x0,
DevQueryFlagUpdateResults = 0x1,
DevQueryFlagAllProperties = 0x2,
DevQueryFlagLocalize = 0x4,
DevQueryFlagAsyncClose = 0x8
} DEV_QUERY_FLAGS, *PDEV_QUERY_FLAGS;
typedef
#ifdef MIDL_PASS
[v1_enum]
#endif
enum _DEV_QUERY_STATE
{
DevQueryStateInitialized,
DevQueryStateEnumCompleted,
DevQueryStateAborted,
DevQueryStateClosed
} DEV_QUERY_STATE, *PDEV_QUERY_STATE;
typedef
#ifdef MIDL_PASS
[v1_enum]
#endif
enum _DEV_QUERY_RESULT_ACTION
{
DevQueryResultStateChange,
DevQueryResultAdd,
DevQueryResultUpdate,
DevQueryResultRemove
} DEV_QUERY_RESULT_ACTION, *PDEV_QUERY_RESULT_ACTION;
typedef struct _DEV_OBJECT
{
DEV_OBJECT_TYPE ObjectType;
__in PCWSTR pszObjectId;
#ifdef MIDL_PASS
[range(0, 10000)]
#endif
__in ULONG cPropertyCount;
#ifdef MIDL_PASS
[size_is(cPropertyCount)]
#endif
__field_ecount_opt(cPropertyCount) const DEVPROPERTY *pProperties;
} DEV_OBJECT, *PDEV_OBJECT;
typedef struct _DEV_QUERY_RESULT_ACTION_DATA
{
DEV_QUERY_RESULT_ACTION Action;
#ifdef MIDL_PASS
[switch_is(Action)]
[switch_type(DEV_QUERY_RESULT_ACTION)]
#endif
union _DEV_QUERY_RESULT_UPDATE_PAYLOAD
{
#ifdef MIDL_PASS
[case (DevQueryResultStateChange)]
#endif
DEV_QUERY_STATE State;
#ifdef MIDL_PASS
[case (DevQueryResultAdd, DevQueryResultUpdate, DevQueryResultRemove)]
#endif
DEV_OBJECT DeviceObject;
} Data;
} DEV_QUERY_RESULT_ACTION_DATA, *PDEV_QUERY_RESULT_ACTION_DATA;
#if (NTDDI_VERSION >= NTDDI_WINBLUE)
typedef struct _DEV_QUERY_PARAMETER {
DEVPROPKEY Key;
DEVPROPTYPE Type;
ULONG BufferSize;
#ifdef MIDL_PASS
[size_is(BufferSize)] PBYTE Buffer;
#else
__field_bcount_opt(BufferSize) PVOID Buffer;
#endif
} DEV_QUERY_PARAMETER, *PDEV_QUERY_PARAMETER;
#endif
#if defined(__cplusplus)
}
#endif // defined(__cplusplus)
#endif // NTDDI_VERSION
#endif // WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_SYSTEM)
| 21.312057 | 85 | 0.774376 | [
"object"
] |
b44a37b2bdfd735b3fff3ac8cf9fb168a588fe44 | 881 | h | C | Grid.h | firepro20/labyrinthoftime | 82365f674dcf8d37ea502a5f86e5edb60bb64f65 | [
"MIT"
] | null | null | null | Grid.h | firepro20/labyrinthoftime | 82365f674dcf8d37ea502a5f86e5edb60bb64f65 | [
"MIT"
] | null | null | null | Grid.h | firepro20/labyrinthoftime | 82365f674dcf8d37ea502a5f86e5edb60bb64f65 | [
"MIT"
] | 1 | 2020-12-09T12:28:24.000Z | 2020-12-09T12:28:24.000Z | #pragma once
#include "pch.h"
#include "Cell.h"
#include "CellPoint.h"
#include "AStar.h"
class Grid {
public:
Cell cellMatrix[27][27];
int getNeighbours(int x, int z);
void initializeGrid();
void nextGeneration();
bool GetInitialised();
void SetInitialised(bool state);
void Clear();
int Size();
Cell GetTreasureCell();
Cell GetPlayerCell();
//AStar
int* GetDistance();
void ResetPlayerInStateMatrix(int,int);
std::vector<CellPoint> haveChanged;
private:
const int gridSize = 27;
const int probabilityToBeAlive = 30;
bool gridInitialised = false;
bool m_isPlayerSet, m_isTreasureSet;
Cell m_cellTreasure;
Cell m_cellPlayer;
AStar m_aStar;
std::pair<int,int> m_treasureIndex;
std::pair<int, int> m_playerIndex;
int stateMatrix[27][27];
bool m_LevelSolvable;
bool m_distance;
int m_searchResult;
}; | 19.152174 | 41 | 0.696935 | [
"vector"
] |
b44eb55cc807541d7fd4d311d609e9be363a7924 | 786 | h | C | evadialog.h | qwertylevel3/Ele | 1a828f5d27d754bdf197410b7fa7eb366ea65439 | [
"MIT"
] | null | null | null | evadialog.h | qwertylevel3/Ele | 1a828f5d27d754bdf197410b7fa7eb366ea65439 | [
"MIT"
] | null | null | null | evadialog.h | qwertylevel3/Ele | 1a828f5d27d754bdf197410b7fa7eb366ea65439 | [
"MIT"
] | null | null | null | #ifndef EVADIALOG_H
#define EVADIALOG_H
#include <QDialog>
#include<QSqlTableModel>
#include<QStandardItemModel>
#include"simpledate.h"
namespace Ui {
class EvaDialog;
}
class EvaDialog : public QDialog
{
Q_OBJECT
public:
explicit EvaDialog(QWidget *parent = 0);
~EvaDialog();
void initModel(QSqlTableModel* model);
public slots:
void evaluate();
private:
double evaluate(const QString& eleName,SimpleDate d1,SimpleDate d2);
void initListWidget();
//获取某一天的评价指数
double evaluate(double r15,double t15,
double r30,double t30,
double r45,double t45,
double r60,double t60);
Ui::EvaDialog *ui;
QSqlTableModel* dataModel{nullptr};
QString eleName;
};
#endif // EVADIALOG_H
| 18.27907 | 72 | 0.666667 | [
"model"
] |
b46077b49ef3b8f79ae307b36f1555c4f55354c0 | 645 | h | C | src/editors/xrEProps/stdafx.h | acidicMercury8/xray-1.0 | 65e85c0e31e82d612c793d980dc4b73fa186c76c | [
"Linux-OpenIB"
] | 2 | 2020-01-30T12:51:49.000Z | 2020-08-31T08:36:49.000Z | src/editors/xrEProps/stdafx.h | acidicMercury8/xray-1.0 | 65e85c0e31e82d612c793d980dc4b73fa186c76c | [
"Linux-OpenIB"
] | null | null | null | src/editors/xrEProps/stdafx.h | acidicMercury8/xray-1.0 | 65e85c0e31e82d612c793d980dc4b73fa186c76c | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:21.000Z | 2022-03-26T17:00:21.000Z | //----------------------------------------------------
// file: stdafx.h
//----------------------------------------------------
#ifndef stdafxH
#define stdafxH
#pragma once
#include <xrCore.h>
#define smart_cast dynamic_cast
//refs
namespace CDB{
class MODEL;
};
#include "xrEProps.h"
#include "FolderLib.h"
#define ENGINE_API
#define DLL_API __declspec(dllimport)
#define ECORE_API __declspec(dllexport)
#include "Defines.h"
// libs
#pragma comment (lib,"xrSoundB.lib")
#pragma comment (lib,"xrCoreB.lib")
#pragma comment (lib,"EToolsB.lib")
#endif //stdafxH
| 18.970588 | 55 | 0.527132 | [
"model"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.